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