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