Fix bugs in previous commit that caused FTBFS in synfig and ETL FTBFS with older...
[synfig.git] / synfig-core / tags / synfig_0_61_06 / src / tool / main.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file tool/main.cpp
3 **      \brief SYNFIG Tool
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 */
21 /* ========================================================================= */
22
23 /* === H E A D E R S ======================================================= */
24
25 #ifdef USING_PCH
26 #       include "pch.h"
27 #else
28 #ifdef HAVE_CONFIG_H
29 #       include <config.h>
30 #endif
31
32 #include <iostream>
33 #include <ETL/stringf>
34 #include <list>
35 #include <ETL/clock>
36 #include <algorithm>
37
38 #include <synfig/loadcanvas.h>
39 #include <synfig/savecanvas.h>
40 #include <synfig/target_scanline.h>
41 #include <synfig/module.h>
42 #include <synfig/importer.h>
43 #include <synfig/layer.h>
44 #include <synfig/canvas.h>
45 #include <synfig/target.h>
46 #include <synfig/time.h>
47 #include <synfig/string.h>
48 #include <synfig/paramdesc.h>
49 #include <synfig/main.h>
50 #include <synfig/guid.h>
51 #endif
52
53 using namespace std;
54 using namespace etl;
55 using namespace synfig;
56
57 /* === M A C R O S ========================================================= */
58
59 enum exit_code
60 {
61         SYNFIGTOOL_OK                           =0,
62         SYNFIGTOOL_FILENOTFOUND         =1,
63         SYNFIGTOOL_BORRED                       =2,
64         SYNFIGTOOL_HELP                         =3,
65         SYNFIGTOOL_UNKNOWNARGUMENT      =4,
66         SYNFIGTOOL_UNKNOWNERROR         =5,
67         SYNFIGTOOL_INVALIDTARGET                =6,
68         SYNFIGTOOL_RENDERFAILURE                =7,
69         SYNFIGTOOL_BLANK                                =8,
70         SYNFIGTOOL_BADVERSION           =9,
71         SYNFIGTOOL_MISSINGARGUMENT      =10
72 };
73
74 #ifndef VERSION
75 #define VERSION "unknown"
76 #define PACKAGE "synfig-tool"
77 #endif
78
79 #ifdef DEFAULT_QUALITY
80 #undef DEFAULT_QUALITY
81 #endif
82
83 #define DEFAULT_QUALITY         2
84 #define VERBOSE_OUT(x) if(verbosity>=(x))std::cerr
85
86 /* === G L O B A L S ======================================================= */
87
88 const char *progname;
89 int verbosity=0;
90 bool be_quiet=false;
91 bool print_benchmarks=false;
92
93 /* === M E T H O D S ======================================================= */
94
95 class Progress : public synfig::ProgressCallback
96 {
97         const char *program;
98
99 public:
100
101         Progress(const char *name):program(name) { }
102
103         virtual bool
104         task(const String &task)
105         {
106                 VERBOSE_OUT(1)<<program<<": "<<task<<std::endl;
107                 return true;
108         }
109
110         virtual bool
111         error(const String &task)
112         {
113                 std::cerr<<program<<": "<<_("error")<<": "<<task<<std::endl;
114                 return true;
115         }
116
117         virtual bool
118         warning(const String &task)
119         {
120                 std::cerr<<program<<": "<<_("warning")<<": "<<task<<std::endl;
121                 return true;
122         }
123
124         virtual bool
125         amount_complete(int current, int total)
126         {
127                 return true;
128         }
129 };
130
131 class RenderProgress : public synfig::ProgressCallback
132 {
133         string taskname;
134
135         etl::clock clk;
136         int clk_scanline; // The scanline at which the clock was reset
137         etl::clock clk2;
138
139         float last_time;
140 public:
141
142         RenderProgress():clk_scanline(0), last_time(0) { }
143
144         virtual bool
145         task(const String &thetask)
146         {
147                 taskname=thetask;
148                 return true;
149         }
150
151         virtual bool
152         error(const String &task)
153         {
154                 std::cout<<_("error")<<": "<<task<<std::endl;
155                 return true;
156         }
157
158         virtual bool
159         warning(const String &task)
160         {
161                 std::cout<<_("warning")<<": "<<task<<std::endl;
162                 return true;
163         }
164
165         virtual bool
166         amount_complete(int scanline, int h)
167         {
168                 if(be_quiet)return true;
169                 if(scanline!=h)
170                 {
171                         const float time(clk()*(float)(h-scanline)/(float)(scanline-clk_scanline));
172                         const float delta(time-last_time);
173
174                         int weeks=0,days=0,hours=0,minutes=0,seconds=0;
175
176                         last_time=time;
177
178                         if(clk2()<0.2)
179                                 return true;
180                         clk2.reset();
181
182                         if(scanline)
183                                 seconds=(int)time+1;
184                         else
185                         {
186                                 //cerr<<"reset"<<endl;
187                                 clk.reset();
188                                 clk_scanline=scanline;
189                         }
190
191                         if(seconds<0)
192                         {
193                                 clk.reset();
194                                 clk_scanline=scanline;
195                                 seconds=0;
196                         }
197                         while(seconds>=60)
198                                 minutes++,seconds-=60;
199                         while(minutes>=60)
200                                 hours++,minutes-=60;
201                         while(hours>=24)
202                                 days++,hours-=24;
203                         while(days>=7)
204                                 weeks++,days-=7;
205
206                         cerr<<taskname<<": "<<_("Line")<<" "<<scanline<<_(" of ")<<h<<" -- ";
207                         //cerr<<time/(h-clk_scanline)<<" ";
208                         /*
209                         if(delta>=-time/(h-clk_scanline)  )
210                                 cerr<<">";
211                         */
212                         if(delta>=0 && clk()>4.0 && scanline>clk_scanline+200)
213                         {
214                                 //cerr<<"reset"<<endl;
215                                 clk.reset();
216                                 clk_scanline=scanline;
217                         }
218
219                         if(weeks)
220                                 cerr<<weeks<<"w ";
221                         if(days)
222                                 cerr<<days<<"d ";
223                         if(hours)
224                                 cerr<<hours<<"h ";
225                         if(minutes)
226                                 cerr<<minutes<<"m ";
227                         if(seconds)
228                                 cerr<<seconds<<"s ";
229
230                         cerr<<"           \r";
231                 }
232                 else
233                         cerr<<taskname<<": "<<_("DONE")<<"                        "<<endl;;
234                 return true;
235         }
236 };
237
238 struct Job
239 {
240         String filename;
241         String outfilename;
242
243         RendDesc desc;
244
245         Canvas::Handle root;
246         Canvas::Handle canvas;
247         Target::Handle target;
248
249         int quality;
250         bool sifout;
251 };
252
253 typedef list<String> arg_list_t;
254 typedef list<Job> job_list_t;
255
256 void guid_test()
257 {
258         cout<<"GUID Test"<<endl;
259         for(int i=20;i;i--)
260         {
261                 cout<<synfig::GUID().get_string()<<' '<<synfig::GUID().get_string()<<endl;
262         }
263 }
264
265 void signal_test_func()
266 {
267         cout<<"**SIGNAL CALLED**"<<endl;
268 }
269
270 void signal_test()
271 {
272         sigc::signal<void> sig;
273         sigc::connection conn;
274         cout<<"Signal Test"<<endl;
275         conn=sig.connect(sigc::ptr_fun(signal_test_func));
276         cout<<"Next line should exclaim signal called."<<endl;
277         sig();
278         conn.disconnect();
279         cout<<"Next line should NOT exclaim signal called."<<endl;
280         sig();
281         cout<<"done."<<endl;
282 }
283
284 /* === P R O C E D U R E S ================================================= */
285
286 void display_help(int amount)
287 {
288         class Argument
289         {
290         public:
291                 Argument(const char *flag,const char *arg, string description)
292                 {
293                         const char spaces[]="                      ";
294                         if(arg)
295                                 cerr<<strprintf(" %s %s %s",flag, arg, spaces+strlen(arg)+strlen(flag)+1)+description<<endl;
296                         else
297                                 cerr<<strprintf(" %s %s",flag,spaces+strlen(flag))+description<<endl;
298
299                 }
300         };
301         cerr<<_("syntax: ")<<progname<<" [DEFAULT OPTIONS] ([SIF FILE] [SPECIFIC OPTIONS])..."<<endl;
302         cerr<<endl;
303         if(amount>=1)
304         {
305                 Argument("-t","<output type>",_("Specify output target (Default:unknown)"));
306                 Argument("-w","<pixel width>",_("Set the image width (Use zero for file default)"));
307                 Argument("-h","<pixel height>",_("Set the image height (Use zero for file default)"));
308                 Argument("-s","<image dist>",_("Set the diagonal size of image window (Span)"));
309                 Argument("-a","<1...30>",_("Set antialias amount for parametric renderer."));
310                 Argument("-Q","<0...10>",strprintf(_("Specify image quality for accelerated renderer (default=%d)"),DEFAULT_QUALITY).c_str());
311                 Argument("-g","<amount>",_("Gamma (default=2.2)"));
312                 Argument("-v",NULL,_("Verbose Output (add more for more verbosity)"));
313                 Argument("-q",NULL,_("Quiet mode (No progress/time-remaining display)"));
314                 Argument("-c","<canvas id>",_("Render the canvas with the given id instead of the root."));
315                 Argument("-o","<output file>",_("Specify output filename"));
316                 Argument("-T","<# of threads>",_("Enable multithreaded renderer using specified # of threads"));
317
318                 Argument("-b",NULL,_("Print Benchmarks"));
319
320                 Argument("--fps","<framerate>",_("Set the frame rate"));
321                 Argument("--time","<time>",_("Render a single frame at <seconds>"));
322                 Argument("--begin-time","<time>",_("Set the starting time"));
323                 Argument("--end-time","<time>",_("Set the ending time"));
324                 Argument("--dpi","<res>",_("Set the dots-per-inch"));
325                 Argument("--append","<filename>",_("Append layers in <filename> to composition"));
326
327                 Argument("--layer-info","<layer>",_("Print out layer's description, parameter info, etc."));
328                 Argument("--layers",NULL,_("Print out the list of available layers"));
329                 Argument("--targets",NULL,_("Print out the list of available targets"));
330                 Argument("--importers",NULL,_("Print out the list of available importers"));
331                 Argument("--valuenodes",NULL,_("Print out the list of available ValueNodes"));
332                 Argument("--modules",NULL,_("Print out the list of loaded modules"));
333                 Argument("--version",NULL,_("Print out version information"));
334                 Argument("--info",NULL,_("Print out misc build information"));
335                 Argument("--license",NULL,_("Print out license information"));
336
337 #ifdef _DEBUG
338                 Argument("--guid-test",NULL,_("Test GUID generation"));
339                 Argument("--signal-test",NULL,_("Test signal implementation"));
340 #endif
341         }
342         else
343
344         Argument("--help",NULL,_("Print out usage and syntax info"));
345         cerr<<endl;
346 }
347
348 int process_global_flags(arg_list_t &arg_list)
349 {
350         arg_list_t::iterator iter, next;
351
352         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
353         {
354                 if(*iter == "--")
355                         return SYNFIGTOOL_OK;
356
357                 if(*iter == "--signal-test")
358                 {
359                         signal_test();
360                         return SYNFIGTOOL_HELP;
361                 }
362
363                 if(*iter == "--guid-test")
364                 {
365                         guid_test();
366                         return SYNFIGTOOL_HELP;
367                 }
368
369
370                 if(*iter == "--help")
371                 {
372                         display_help(1);
373
374                         return SYNFIGTOOL_HELP;
375                 }
376
377                 if(*iter == "--info")
378                 {
379                         cout<<PACKAGE"-"VERSION<<endl;
380                         cout<<"Compiled on "__DATE__ " at "__TIME__;
381 #ifdef __GNUC__
382                         cout<<" with GCC "<<__VERSION__;
383 #endif
384 #ifdef _MSC_VER
385                         cout<<" with Microsoft Visual C++ "<<(_MSC_VER>>8)<<'.'<<(_MSC_VER&255);
386 #endif
387 #ifdef __TCPLUSPLUS__
388                         cout<<" with Borland Turbo C++ "<<(__TCPLUSPLUS__>>8)<<'.'<<((__TCPLUSPLUS__&255)>>4)<<'.'<<(__TCPLUSPLUS__&15);
389 #endif
390
391                         cout<<endl<<SYNFIG_COPYRIGHT<<endl;
392                         cout<<endl;
393                         return SYNFIGTOOL_HELP;
394                 }
395
396                 if(*iter == "--layers")
397                 {
398                         Progress p(PACKAGE);
399                         synfig::Main synfig_main(dirname(progname),&p);
400                         synfig::Layer::Book::iterator iter=synfig::Layer::book().begin();
401                         for(;iter!=synfig::Layer::book().end();iter++)
402                                 cout<<iter->first<<endl;
403
404                         return SYNFIGTOOL_HELP;
405                 }
406
407                 if(*iter == "--layer-info")
408                 {
409                         Progress p(PACKAGE);
410                         synfig::Main synfig_main(dirname(progname),&p);
411                         iter=next++;
412                         Layer::Handle layer=synfig::Layer::create(*iter);
413                         cout<<"Layer Name: "<<layer->get_name()<<endl;
414                         cout<<"Localized Layer Name: "<<layer->get_local_name()<<endl;
415                         cout<<"Version: "<<layer->get_version()<<endl;
416                         Layer::Vocab vocab=layer->get_param_vocab();
417                         for(;!vocab.empty();vocab.pop_front())
418                         {
419                                 cout<<"param - "<<vocab.front().get_name();
420                                 if(!vocab.front().get_critical())
421                                         cout<<" (not critical)";
422                                 cout<<endl<<"\tLocalized Name: "<<vocab.front().get_local_name()<<endl;
423                                 if(!vocab.front().get_description().empty())
424                                         cout<<"\tDescription: "<<vocab.front().get_description()<<endl;
425                                 if(!vocab.front().get_hint().empty())
426                                         cout<<"\tHint: "<<vocab.front().get_hint()<<endl;
427                         }
428
429                         return SYNFIGTOOL_HELP;
430                 }
431
432                 if(*iter == "--modules")
433                 {
434                         Progress p(PACKAGE);
435                         synfig::Main synfig_main(dirname(progname),&p);
436                         synfig::Module::Book::iterator iter=synfig::Module::book().begin();
437                         for(;iter!=synfig::Module::book().end();iter++)
438                                 cout<<iter->first<<endl;
439                         return SYNFIGTOOL_HELP;
440                 }
441
442                 if(*iter == "--targets")
443                 {
444                         Progress p(PACKAGE);
445                         synfig::Main synfig_main(dirname(progname),&p);
446                         synfig::Target::Book::iterator iter=synfig::Target::book().begin();
447                         for(;iter!=synfig::Target::book().end();iter++)
448                                 cout<<iter->first<<endl;
449
450                         return SYNFIGTOOL_HELP;
451                 }
452
453                 if(*iter == "--valuenodes")
454                 {
455                         Progress p(PACKAGE);
456                         synfig::Main synfig_main(dirname(progname),&p);
457                         synfig::LinkableValueNode::Book::iterator iter=synfig::LinkableValueNode::book().begin();
458                         for(;iter!=synfig::LinkableValueNode::book().end();iter++)
459                                 cout<<iter->first<<endl;
460
461                         return SYNFIGTOOL_HELP;
462                 }
463
464                 if(*iter == "--importers")
465                 {
466                         Progress p(PACKAGE);
467                         synfig::Main synfig_main(dirname(progname),&p);
468                         synfig::Importer::Book::iterator iter=synfig::Importer::book().begin();
469                         for(;iter!=synfig::Importer::book().end();iter++)
470                                 cout<<iter->first<<endl;
471
472                         return SYNFIGTOOL_HELP;
473                 }
474
475                 if(*iter == "--version")
476                 {
477                         cerr<<PACKAGE<<" "<<VERSION<<endl;
478
479                         arg_list.erase(iter);
480
481                         return SYNFIGTOOL_HELP;
482                 }
483
484                 if(*iter == "--license")
485                 {
486                         cerr<<PACKAGE<<" "<<VERSION<<endl;
487                         cout<<SYNFIG_COPYRIGHT<<endl<<endl;
488                         cerr<<"\
489 **      This package is free software; you can redistribute it and/or\n\
490 **      modify it under the terms of the GNU General Public License as\n\
491 **      published by the Free Software Foundation; either version 2 of\n\
492 **      the License, or (at your option) any later version.\n\
493 **\n\
494 **      " << endl << endl;
495                         arg_list.erase(iter);
496
497                         return SYNFIGTOOL_HELP;
498                 }
499
500                 if(*iter == "-v")
501                 {
502                         verbosity++;
503
504                         arg_list.erase(iter);
505
506                         continue;
507                 }
508
509                 if(*iter == "-q")
510                 {
511                         be_quiet=true;
512
513                         arg_list.erase(iter);
514
515                         continue;
516                 }
517                 if(*iter == "-b")
518                 {
519                         print_benchmarks=true;
520
521                         arg_list.erase(iter);
522
523                         continue;
524                 }
525         }
526
527         return SYNFIGTOOL_OK;
528 }
529
530 int extract_arg_cluster(arg_list_t &arg_list,arg_list_t &cluster)
531 {
532         arg_list_t::iterator iter, next;
533
534         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
535         {
536                 if(*iter->begin() != '-')
537                 {
538                         //cerr<<*iter->begin()<<"-----------"<<endl;
539                         return SYNFIGTOOL_OK;
540                 }
541
542                 if(
543                         *iter=="-t" ||
544                         *iter=="-w" ||
545                         *iter=="-h" ||
546                         *iter=="-a" ||
547                         *iter=="-g" ||
548                         *iter=="-o" ||
549                         *iter=="-s" ||
550                         *iter=="-Q" ||
551                         *iter=="-c" ||
552                         *iter=="--fps" ||
553                         *iter=="--start-time" ||
554                         *iter=="--begin-time" ||
555                         *iter=="--end-time" ||
556                         *iter=="--start-frame" ||
557                         *iter=="--end-frame" ||
558                         *iter=="--time" ||
559                         *iter=="--frame" ||
560                         *iter=="--dpi" ||
561                         *iter=="--dpi-x" ||
562                         *iter=="--dpi-y" ||
563                         *iter=="--append" ||
564                         *iter=="-T" )
565                 {
566                         cluster.push_back(*iter);
567                         arg_list.erase(iter);
568                         iter=next++;
569                         if (iter==arg_list.end()) {
570                                 error("The `%s' flag requires a value.  Use --help for a list of options.", cluster.back().c_str());
571                                 return SYNFIGTOOL_MISSINGARGUMENT;
572                         }
573                 }
574
575                 cluster.push_back(*iter);
576                 arg_list.erase(iter);
577         }
578
579         return SYNFIGTOOL_OK;
580 }
581
582 int extract_RendDesc(arg_list_t &arg_list,RendDesc &desc)
583 {
584         arg_list_t::iterator iter, next;
585         int w=0,h=0;
586         float span=0;
587         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
588         {
589                 if(*iter=="-w")
590                 {
591                         arg_list.erase(iter);
592                         iter=next++;
593                         w=atoi(iter->c_str());
594                         arg_list.erase(iter);
595                 }
596                 else if(*iter=="-h")
597                 {
598                         arg_list.erase(iter);
599                         iter=next++;
600                         h=atoi(iter->c_str());
601                         arg_list.erase(iter);
602                 }
603                 else if(*iter=="-a")
604                 {
605             int a;
606                         arg_list.erase(iter);
607                         iter=next++;
608                         a=atoi(iter->c_str());
609                         desc.set_antialias(a);
610                         VERBOSE_OUT(1)<<strprintf(_("Antialiasing set to %d, (%d samples per pixel)"),a,a*a)<<endl;
611                         arg_list.erase(iter);
612                 }
613                 else if(*iter=="-s")
614                 {
615                         arg_list.erase(iter);
616                         iter=next++;
617                         span=atof(iter->c_str());
618                         VERBOSE_OUT(1)<<strprintf(_("Span set to %d units"),span)<<endl;
619                         arg_list.erase(iter);
620                 }
621                 else if(*iter=="--fps")
622                 {
623                         arg_list.erase(iter);
624                         iter=next++;
625                         float fps=atof(iter->c_str());
626                         desc.set_frame_rate(fps);
627                         arg_list.erase(iter);
628                         VERBOSE_OUT(1)<<strprintf(_("Frame rate set to %d frames per second"),fps)<<endl;
629                 }
630                 else if(*iter=="--dpi")
631                 {
632                         arg_list.erase(iter);
633                         iter=next++;
634                         float dpi=atof(iter->c_str());
635                         float dots_per_meter=dpi*39.3700787402;
636                         desc.set_x_res(dots_per_meter).set_y_res(dots_per_meter);
637                         arg_list.erase(iter);
638                         VERBOSE_OUT(1)<<strprintf(_("Physical resolution set to %f dpi"),dpi)<<endl;
639                 }
640                 else if(*iter=="--dpi-x")
641                 {
642                         arg_list.erase(iter);
643                         iter=next++;
644                         float dpi=atof(iter->c_str());
645                         float dots_per_meter=dpi*39.3700787402;
646                         desc.set_x_res(dots_per_meter);
647                         arg_list.erase(iter);
648                         VERBOSE_OUT(1)<<strprintf(_("Physical X resolution set to %f dpi"),dpi)<<endl;
649                 }
650                 else if(*iter=="--dpi-y")
651                 {
652                         arg_list.erase(iter);
653                         iter=next++;
654                         float dpi=atof(iter->c_str());
655                         float dots_per_meter=dpi*39.3700787402;
656                         desc.set_y_res(dots_per_meter);
657                         arg_list.erase(iter);
658                         VERBOSE_OUT(1)<<strprintf(_("Physical Y resolution set to %f dpi"),dpi)<<endl;
659                 }
660                 else if(*iter=="--start-time" || *iter=="--begin-time")
661                 {
662                         arg_list.erase(iter);
663                         iter=next++;
664                         desc.set_time_start(Time(*iter,desc.get_frame_rate()));
665                         arg_list.erase(iter);
666                 }
667                 else if(*iter=="--end-time")
668                 {
669                         arg_list.erase(iter);
670                         iter=next++;
671                         desc.set_time_end(Time(*iter,desc.get_frame_rate()));
672                         arg_list.erase(iter);
673                 }
674                 else if(*iter=="--time")
675                 {
676                         arg_list.erase(iter);
677                         iter=next++;
678                         desc.set_time(Time(*iter,desc.get_frame_rate()));
679                         VERBOSE_OUT(1)<<_("Rendering frame at ")<<desc.get_time_start().get_string(desc.get_frame_rate())<<endl;
680                         arg_list.erase(iter);
681                 }
682                 else if(*iter=="-g")
683                 {
684                         synfig::warning("Gamma argument is currently ignored");
685                         arg_list.erase(iter);
686                         iter=next++;
687                         //desc.set_gamma(Gamma(atof(iter->c_str())));
688                         arg_list.erase(iter);
689                 }
690         }
691         if(w&&h)
692         {
693                 desc.set_wh(w,h);
694                 VERBOSE_OUT(1)<<strprintf(_("Resolution set to %dx%d"),w,h)<<endl;
695         }
696         else
697         {
698                 if(w)
699                 {
700                         VERBOSE_OUT(1)<<strprintf(_("Width set to %d pixels"),w)<<endl;
701                         desc.set_w(w);
702                 }
703                 if(h)
704                 {
705                         VERBOSE_OUT(1)<<strprintf(_("Height set to %d pixels"),h)<<endl;
706                         desc.set_h(h);
707                 }
708         }
709         if(span)
710                 desc.set_span(span);
711         return SYNFIGTOOL_OK;
712 }
713
714 int extract_quality(arg_list_t &arg_list,int &quality)
715 {
716         arg_list_t::iterator iter, next;
717         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
718         {
719                 if(*iter=="-Q")
720                 {
721                         arg_list.erase(iter);
722                         iter=next++;
723                         quality=atoi(iter->c_str());
724                         VERBOSE_OUT(1)<<strprintf(_("Quality set to %d"),quality)<<endl;
725                         arg_list.erase(iter);
726                 }
727         }
728
729         return SYNFIGTOOL_OK;
730 }
731
732 int extract_threads(arg_list_t &arg_list,int &threads)
733 {
734         arg_list_t::iterator iter, next;
735         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
736         {
737                 if(*iter=="-T")
738                 {
739                         arg_list.erase(iter);
740                         iter=next++;
741                         threads=atoi(iter->c_str());
742                         VERBOSE_OUT(1)<<strprintf(_("Threads set to %d"),threads)<<endl;
743                         arg_list.erase(iter);
744                 }
745         }
746
747         return SYNFIGTOOL_OK;
748 }
749
750 int extract_target(arg_list_t &arg_list,string &type)
751 {
752         arg_list_t::iterator iter, next;
753         type.clear();
754
755         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
756         {
757                 if(*iter=="-t")
758                 {
759                         arg_list.erase(iter);
760                         iter=next++;
761                         type=*iter;
762                         arg_list.erase(iter);
763                 }
764         }
765
766         return SYNFIGTOOL_OK;
767 }
768
769 int extract_append(arg_list_t &arg_list,string &filename)
770 {
771         arg_list_t::iterator iter, next;
772         filename.clear();
773
774         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
775         {
776                 if(*iter=="--append")
777                 {
778                         arg_list.erase(iter);
779                         iter=next++;
780                         filename=*iter;
781                         arg_list.erase(iter);
782                 }
783         }
784
785         return SYNFIGTOOL_OK;
786 }
787
788 int extract_outfile(arg_list_t &arg_list,string &outfile)
789 {
790         arg_list_t::iterator iter, next;
791         int ret=SYNFIGTOOL_FILENOTFOUND;
792         outfile.clear();
793
794         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
795         {
796                 if(*iter=="-o")
797                 {
798                         arg_list.erase(iter);
799                         iter=next++;
800                         outfile=*iter;
801                         arg_list.erase(iter);
802                         ret=SYNFIGTOOL_OK;
803                 }
804         }
805
806         return ret;
807 }
808
809 int extract_canvasid(arg_list_t &arg_list,string &canvasid)
810 {
811         arg_list_t::iterator iter, next;
812         //canvasid.clear();
813
814         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
815         {
816                 if(*iter=="-c")
817                 {
818                         arg_list.erase(iter);
819                         iter=next++;
820                         canvasid=*iter;
821                         arg_list.erase(iter);
822                 }
823         }
824
825         return SYNFIGTOOL_OK;
826 }
827
828 /* === M E T H O D S ======================================================= */
829
830 /* === E N T R Y P O I N T ================================================= */
831
832 int main(int argc, char *argv[])
833 {
834         int i;
835         arg_list_t arg_list;
836         job_list_t job_list;
837
838         progname=argv[0];
839         Progress p(argv[0]);
840
841         if(!SYNFIG_CHECK_VERSION())
842         {
843                 cerr<<_("FATAL: Synfig Version Mismatch")<<endl;
844                 return SYNFIGTOOL_BADVERSION;
845         }
846         if(argc==1)
847         {
848                 display_help(0);
849                 return SYNFIGTOOL_BLANK;
850         }
851
852         for(i=1;i<argc;i++)
853                 arg_list.push_back(argv[i]);
854
855         if((i=process_global_flags(arg_list)))
856                 return i;
857
858         VERBOSE_OUT(1)<<_("verbosity set to ")<<verbosity<<endl;
859         synfig::Main synfig_main(dirname(progname),&p);
860
861         {
862                 arg_list_t defaults, imageargs;
863                 int ret;
864
865                 // Grab the defaults before the first file
866                 if ((ret = extract_arg_cluster(arg_list,defaults)) != SYNFIGTOOL_OK)
867                   return ret;
868
869                 while(arg_list.size())
870                 {
871                         string target_name;
872                         job_list.push_front(Job());
873                         int threads=0;
874
875                         imageargs=defaults;
876                         job_list.front().filename=arg_list.front();
877                         arg_list.pop_front();
878
879                         if ((ret = extract_arg_cluster(arg_list,imageargs)) != SYNFIGTOOL_OK)
880                           return ret;
881
882                         // Open the composition
883                         {
884                                 job_list.front().root=open_canvas(job_list.front().filename);
885                         }
886                         if(!job_list.front().root)
887                         {
888                                 cerr<<_("Unable to open ")<<job_list.front().filename<<"."<<endl;
889                                 cerr<<_("Throwing out job...")<<endl;
890                                 job_list.pop_front();
891                                 continue;
892                         }
893
894                         job_list.front().root->set_time(0);
895
896                         string canvasid;
897                         extract_canvasid(imageargs,canvasid);
898                         if(!canvasid.empty())
899                         {
900                                 try
901                                 {
902                                         job_list.front().canvas=job_list.front().root->find_canvas(canvasid);
903                                 }
904                                 catch(Exception::IDNotFound)
905                                 {
906                                         cerr<<_("Unable to find canvas with ID \"")<<canvasid<<_("\" in ")<<job_list.front().filename<<"."<<endl;
907                                         cerr<<_("Throwing out job...")<<endl;
908                                         job_list.pop_front();
909                                         continue;
910
911                                 }
912                                 catch(Exception::BadLinkName)
913                                 {
914                                         cerr<<_("Invalid canvas name \"")<<canvasid<<_("\" in ")<<job_list.front().filename<<"."<<endl;
915                                         cerr<<_("Throwing out job...")<<endl;
916                                         job_list.pop_front();
917                                         continue;
918
919                                 }
920                         }
921                         else
922                                 job_list.front().canvas=job_list.front().root;
923
924                         extract_RendDesc(imageargs,job_list.front().canvas->rend_desc());
925                         extract_target(imageargs,target_name);
926                         extract_threads(imageargs,threads);
927                         job_list.front().quality=DEFAULT_QUALITY;
928                         extract_quality(imageargs,job_list.front().quality);
929                         VERBOSE_OUT(2)<<_("Quality set to ")<<job_list.front().quality<<endl;
930                         job_list.front().desc=job_list.front().canvas->rend_desc();
931                         extract_outfile(imageargs,job_list.front().outfilename);
932
933                         // Extract composite
934                         do{
935                                 string composite_file;
936                                 extract_append(imageargs,composite_file);
937                                 if(!composite_file.empty())
938                                 {
939                                         Canvas::Handle composite(open_canvas(composite_file));
940                                         if(!composite)
941                                                 break;
942                                         Canvas::reverse_iterator iter;
943                                         for(iter=composite->rbegin();iter!=composite->rend();++iter)
944                                         {
945                                                 Layer::Handle layer(*iter);
946                                                 if(layer->active())
947                                                         job_list.front().canvas->push_front(layer->clone());
948                                         }
949                                         VERBOSE_OUT(2)<<_("Appended contents of ")<<composite_file<<endl;
950                                 }
951                         }while(false);
952
953                         VERBOSE_OUT(4)<<_("Attempting to determine target/outfile...")<<endl;
954
955                         // If the target type is not yet defined,
956                         // try to figure it out from the outfile.
957                         if(target_name.empty() && !job_list.front().outfilename.empty())
958                         {
959                                 VERBOSE_OUT(3)<<_("Target name undefined, attempting to figure it out")<<endl;
960                                 string ext=job_list.front().outfilename.substr(job_list.front().outfilename.rfind('.')+1);
961                                 if(Target::ext_book().count(ext))
962                                         target_name=Target::ext_book()[ext];
963                                 else
964                                         target_name=ext;
965                         }
966
967                         // If the target type is STILL not yet defined, then
968                         // set it to a some sort of default
969                         if(target_name.empty())
970                         {
971                                 VERBOSE_OUT(2)<<_("Defaulting to PNG target...")<<endl;
972                                 target_name="png";
973                         }
974
975                         // If no output filename was provided, then
976                         // create a output filename based on the
977                         // given input filename. (ie: change the extension)
978                         if(job_list.front().outfilename.empty())
979                         {
980                                 job_list.front().outfilename=job_list.front().filename;
981                                 job_list.front().outfilename.erase(find(job_list.front().outfilename.begin(),job_list.front().outfilename.end(),'.'),job_list.front().outfilename.end());
982                                 job_list.front().outfilename+='.';
983                                 if(Target::book().count(target_name))
984                                         job_list.front().outfilename+=Target::book()[target_name].second;
985                                 else
986                                         job_list.front().outfilename+=target_name;
987                         }
988
989                         VERBOSE_OUT(4)<<"target_name="<<target_name<<endl;
990                         VERBOSE_OUT(4)<<"outfile_name="<<job_list.front().outfilename<<endl;
991
992                         VERBOSE_OUT(4)<<_("Creating the target...")<<endl;
993                         job_list.front().target=synfig::Target::create(target_name,job_list.front().outfilename);
994
995                         if(target_name=="sif")
996                         {
997                                 job_list.front().sifout=true;
998                         }
999                         else
1000                         {
1001                                 if(!job_list.front().target)
1002                                 {
1003                                         cerr<<_("Unknown target for ")<<job_list.front().filename<<": "<<target_name<<endl;
1004                                         cerr<<_("Throwing out job...")<<endl;
1005                                         job_list.pop_front();
1006                                         continue;
1007                                 }
1008                                 job_list.front().sifout=false;
1009                         }
1010
1011                         // Set the Canvas on the Target
1012                         if(job_list.front().target)
1013                         {
1014                                 VERBOSE_OUT(4)<<_("Setting the canvas on the target...")<<endl;
1015                                 job_list.front().target->set_canvas(job_list.front().canvas);
1016                                 VERBOSE_OUT(4)<<_("Setting the quality of the target...")<<endl;
1017                                 job_list.front().target->set_quality(job_list.front().quality);
1018                         }
1019
1020                         // Set the threads for the target
1021                         if(job_list.front().target && Target_Scanline::Handle::cast_dynamic(job_list.front().target))
1022                         {
1023                                 Target_Scanline::Handle::cast_dynamic(job_list.front().target)->set_threads(threads);
1024                         }
1025
1026                         if(imageargs.size())
1027                         {
1028                                 cerr<<_("Unidentified arguments for ")<<job_list.front().filename<<": ";
1029                                 for(;imageargs.size();imageargs.pop_front())
1030                                         cerr<<' '<<imageargs.front();
1031                                 cerr<<endl;
1032                                 cerr<<_("Throwing out job...")<<endl;
1033                                 job_list.pop_front();
1034                                 continue;
1035                         }
1036                         //string bleh;
1037                         //getline(cin,bleh);
1038                 }
1039         }
1040
1041         if(arg_list.size())
1042         {
1043                 cerr<<_("Unidentified arguments:");
1044                 for(;arg_list.size();arg_list.pop_front())
1045                         cerr<<' '<<arg_list.front();
1046                 cerr<<endl;
1047                 return SYNFIGTOOL_UNKNOWNARGUMENT;
1048         }
1049
1050         if(!job_list.size())
1051         {
1052                 cerr<<_("Nothing to do!")<<endl;
1053                 return SYNFIGTOOL_BORRED;
1054         }
1055
1056         for(;job_list.size();job_list.pop_front())
1057         {
1058                 VERBOSE_OUT(3)<<job_list.front().filename<<" -- "<<endl<<'\t'<<
1059                 strprintf("w:%d, h:%d, a:%d, pxaspect:%f, imaspect:%f, span:%f",
1060                         job_list.front().desc.get_w(),
1061                         job_list.front().desc.get_h(),
1062                         job_list.front().desc.get_antialias(),
1063                         job_list.front().desc.get_pixel_aspect(),
1064                         job_list.front().desc.get_image_aspect(),
1065                         job_list.front().desc.get_span()
1066                         )<<endl<<'\t'<<
1067                 strprintf("tl:[%f,%f], br:[%f,%f], focus:[%f,%f]",
1068                         job_list.front().desc.get_tl()[0],job_list.front().desc.get_tl()[1],
1069                         job_list.front().desc.get_br()[0],job_list.front().desc.get_br()[1],
1070                         job_list.front().desc.get_focus()[0],job_list.front().desc.get_focus()[1]
1071                         )<<endl;
1072
1073                 RenderProgress p;
1074                 p.task(job_list.front().filename+" ==> "+job_list.front().outfilename);
1075                 if(!job_list.front().sifout)
1076                 {
1077                         VERBOSE_OUT(1)<<_("Rendering...")<<endl;
1078                         etl::clock timer;
1079                         timer.reset();
1080                         // Call the render member of the target
1081                         if(!job_list.front().target->render(&p))
1082                         {
1083                                 cerr<<"Render Failure."<<endl;
1084                                 return SYNFIGTOOL_RENDERFAILURE;
1085                         }
1086                         if(print_benchmarks)
1087                         {
1088                                 cout<<job_list.front().filename+": Rendered in "<<timer()<<" seconds."<<endl;
1089                         }
1090                 }
1091                 else
1092                 {
1093                         if(!save_canvas(job_list.front().outfilename,job_list.front().canvas))
1094                         {
1095                                 cerr<<"Render Failure."<<endl;
1096                                 return SYNFIGTOOL_RENDERFAILURE;
1097                         }
1098                 }
1099         }
1100
1101         job_list.clear();
1102
1103         VERBOSE_OUT(1)<<_("Done.")<<endl;
1104
1105         return SYNFIGTOOL_OK;
1106 }