Using mutexes around accesses to refcounts seems to make the Windows build much less...
[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, 2008 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         bool list_canvases;
262 };
263
264 typedef list<String> arg_list_t;
265 typedef list<Job> job_list_t;
266
267 void guid_test()
268 {
269         cout<<"GUID Test"<<endl;
270         for(int i=20;i;i--)
271                 cout<<synfig::GUID().get_string()<<' '<<synfig::GUID().get_string()<<endl;
272 }
273
274 void signal_test_func()
275 {
276         cout<<"**SIGNAL CALLED**"<<endl;
277 }
278
279 void signal_test()
280 {
281         sigc::signal<void> sig;
282         sigc::connection conn;
283         cout<<"Signal Test"<<endl;
284         conn=sig.connect(sigc::ptr_fun(signal_test_func));
285         cout<<"Next line should exclaim signal called."<<endl;
286         sig();
287         conn.disconnect();
288         cout<<"Next line should NOT exclaim signal called."<<endl;
289         sig();
290         cout<<"done."<<endl;
291 }
292
293 /* === P R O C E D U R E S ================================================= */
294
295 void display_help(int amount)
296 {
297         class Argument
298         {
299         public:
300                 Argument(const char *flag,const char *arg, string description)
301                 {
302                         const char spaces[]="                      ";
303                         if(arg)
304                                 cerr<<strprintf(" %s %s %s",flag, arg, spaces+strlen(arg)+strlen(flag)+1)+description<<endl;
305                         else
306                                 cerr<<strprintf(" %s %s",flag,spaces+strlen(flag))+description<<endl;
307                 }
308         };
309
310         cerr << endl << _("syntax: ") << progname << " [DEFAULT OPTIONS] ([SIF FILE] [SPECIFIC OPTIONS])..." << endl << endl;
311
312         if(amount == 0)
313                 Argument("--help",NULL,_("Print out usage and syntax info"));
314         else
315         {
316                 Argument("-t","<output type>",_("Specify output target (Default:unknown)"));
317                 Argument("-w","<pixel width>",_("Set the image width (Use zero for file default)"));
318                 Argument("-h","<pixel height>",_("Set the image height (Use zero for file default)"));
319                 Argument("-s","<image dist>",_("Set the diagonal size of image window (Span)"));
320                 Argument("-a","<1...30>",_("Set antialias amount for parametric renderer."));
321                 Argument("-Q","<0...10>",strprintf(_("Specify image quality for accelerated renderer (default=%d)"),DEFAULT_QUALITY).c_str());
322                 Argument("-g","<amount>",_("Gamma (default=2.2)"));
323                 Argument("-v",NULL,_("Verbose Output (add more for more verbosity)"));
324                 Argument("-q",NULL,_("Quiet mode (No progress/time-remaining display)"));
325                 Argument("-c","<canvas id>",_("Render the canvas with the given id instead of the root."));
326                 Argument("-o","<output file>",_("Specify output filename"));
327                 Argument("-T","<# of threads>",_("Enable multithreaded renderer using specified # of threads"));
328                 Argument("-b",NULL,_("Print Benchmarks"));
329                 Argument("--fps","<framerate>",_("Set the frame rate"));
330                 Argument("--time","<time>",_("Render a single frame at <seconds>"));
331                 Argument("--begin-time","<time>",_("Set the starting time"));
332                 Argument("--start-time","<time>",_("Set the starting time"));
333                 Argument("--end-time","<time>",_("Set the ending time"));
334                 Argument("--dpi","<res>",_("Set the physical resolution (dots-per-inch)"));
335                 Argument("--dpi-x","<res>",_("Set the physical X resolution (dots-per-inch)"));
336                 Argument("--dpi-y","<res>",_("Set the physical Y resolution (dots-per-inch)"));
337
338                 Argument("--list-canvases",NULL,_("List the exported canvases in the composition"));
339                 Argument("--append","<filename>",_("Append layers in <filename> to composition"));
340
341                 Argument("--layer-info","<layer>",_("Print out layer's description, parameter info, etc."));
342                 Argument("--layers",NULL,_("Print out the list of available layers"));
343                 Argument("--targets",NULL,_("Print out the list of available targets"));
344                 Argument("--importers",NULL,_("Print out the list of available importers"));
345                 Argument("--valuenodes",NULL,_("Print out the list of available ValueNodes"));
346                 Argument("--modules",NULL,_("Print out the list of loaded modules"));
347                 Argument("--version",NULL,_("Print out version information"));
348                 Argument("--info",NULL,_("Print out misc build information"));
349                 Argument("--license",NULL,_("Print out license information"));
350
351 #ifdef _DEBUG
352                 Argument("--guid-test",NULL,_("Test GUID generation"));
353                 Argument("--signal-test",NULL,_("Test signal implementation"));
354 #endif
355         }
356
357         cerr<<endl;
358 }
359
360 int process_global_flags(arg_list_t &arg_list)
361 {
362         arg_list_t::iterator iter, next;
363
364         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
365         {
366                 if(*iter == "--")
367                         return SYNFIGTOOL_OK;
368
369                 if(*iter == "--signal-test")
370                 {
371                         signal_test();
372                         return SYNFIGTOOL_HELP;
373                 }
374
375                 if(*iter == "--guid-test")
376                 {
377                         guid_test();
378                         return SYNFIGTOOL_HELP;
379                 }
380
381                 if(*iter == "--help")
382                 {
383                         display_help(1);
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                                 if (iter->second.category != CATEGORY_DO_NOT_USE)
413                                         cout<<iter->first<<endl;
414
415                         return SYNFIGTOOL_HELP;
416                 }
417
418                 if(*iter == "--layer-info")
419                 {
420                         Progress p(PACKAGE);
421                         synfig::Main synfig_main(dirname(progname),&p);
422                         iter=next++;
423                         if (iter==arg_list.end())
424                         {
425                                 error("The `%s' flag requires a value.  Use --help for a list of options.", "--layer-info");
426                                 return SYNFIGTOOL_MISSINGARGUMENT;
427                         }
428                         Layer::Handle layer=synfig::Layer::create(*iter);
429                         cout<<"Layer Name: "<<layer->get_name()<<endl;
430                         cout<<"Localized Layer Name: "<<layer->get_local_name()<<endl;
431                         cout<<"Version: "<<layer->get_version()<<endl;
432                         Layer::Vocab vocab=layer->get_param_vocab();
433                         for(;!vocab.empty();vocab.pop_front())
434                         {
435                                 cout<<"param - "<<vocab.front().get_name();
436                                 if(!vocab.front().get_critical())
437                                         cout<<" (not critical)";
438                                 cout<<endl<<"\tLocalized Name: "<<vocab.front().get_local_name()<<endl;
439                                 if(!vocab.front().get_description().empty())
440                                         cout<<"\tDescription: "<<vocab.front().get_description()<<endl;
441                                 if(!vocab.front().get_hint().empty())
442                                         cout<<"\tHint: "<<vocab.front().get_hint()<<endl;
443                         }
444
445                         return SYNFIGTOOL_HELP;
446                 }
447
448                 if(*iter == "--modules")
449                 {
450                         Progress p(PACKAGE);
451                         synfig::Main synfig_main(dirname(progname),&p);
452                         synfig::Module::Book::iterator iter=synfig::Module::book().begin();
453                         for(;iter!=synfig::Module::book().end();iter++)
454                                 cout<<iter->first<<endl;
455                         return SYNFIGTOOL_HELP;
456                 }
457
458                 if(*iter == "--targets")
459                 {
460                         Progress p(PACKAGE);
461                         synfig::Main synfig_main(dirname(progname),&p);
462                         synfig::Target::Book::iterator iter=synfig::Target::book().begin();
463                         for(;iter!=synfig::Target::book().end();iter++)
464                                 cout<<iter->first<<endl;
465                         return SYNFIGTOOL_HELP;
466                 }
467
468                 if(*iter == "--valuenodes")
469                 {
470                         Progress p(PACKAGE);
471                         synfig::Main synfig_main(dirname(progname),&p);
472                         synfig::LinkableValueNode::Book::iterator iter=synfig::LinkableValueNode::book().begin();
473                         for(;iter!=synfig::LinkableValueNode::book().end();iter++)
474                                 cout<<iter->first<<endl;
475                         return SYNFIGTOOL_HELP;
476                 }
477
478                 if(*iter == "--importers")
479                 {
480                         Progress p(PACKAGE);
481                         synfig::Main synfig_main(dirname(progname),&p);
482                         synfig::Importer::Book::iterator iter=synfig::Importer::book().begin();
483                         for(;iter!=synfig::Importer::book().end();iter++)
484                                 cout<<iter->first<<endl;
485                         return SYNFIGTOOL_HELP;
486                 }
487
488                 if(*iter == "--version")
489                 {
490                         cerr<<PACKAGE<<" "<<VERSION<<endl;
491                         arg_list.erase(iter);
492                         return SYNFIGTOOL_HELP;
493                 }
494
495                 if(*iter == "--license")
496                 {
497                         cerr<<PACKAGE<<" "<<VERSION<<endl;
498                         cout<<SYNFIG_COPYRIGHT<<endl<<endl;
499                         cerr<<"\
500 **      This package is free software; you can redistribute it and/or\n\
501 **      modify it under the terms of the GNU General Public License as\n\
502 **      published by the Free Software Foundation; either version 2 of\n\
503 **      the License, or (at your option) any later version.\n\
504 **\n\
505 **      " << endl << endl;
506                         arg_list.erase(iter);
507                         return SYNFIGTOOL_HELP;
508                 }
509
510                 if(*iter == "-v")
511                 {
512                         verbosity++;
513                         arg_list.erase(iter);
514                         continue;
515                 }
516
517                 if(*iter == "-q")
518                 {
519                         be_quiet=true;
520                         arg_list.erase(iter);
521                         continue;
522                 }
523                 if(*iter == "-b")
524                 {
525                         print_benchmarks=true;
526                         arg_list.erase(iter);
527                         continue;
528                 }
529         }
530
531         return SYNFIGTOOL_OK;
532 }
533
534 /* true if the given flag takes an extra parameter */
535 bool flag_requires_value(String flag)
536 {
537         return (flag=="-a"                      || flag=="-c"                   || flag=="-g"                   || flag=="-h"                   || flag=="-o"           ||
538                         flag=="-Q"                      || flag=="-s"                   || flag=="-t"                   || flag=="-T"                   || flag=="-w"           ||
539                         flag=="--append"        || flag=="--begin-time" || flag=="--dpi"                || flag=="--dpi-x"              || flag=="--dpi-y"      ||
540                         flag=="--end-time"      || flag=="--fps"                || flag=="--layer-info" || flag=="--start-time" || flag=="--time"       );
541 }
542
543 int extract_arg_cluster(arg_list_t &arg_list,arg_list_t &cluster)
544 {
545         arg_list_t::iterator iter, next;
546
547         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
548         {
549                 if(*iter->begin() != '-')
550                 {
551                         //cerr<<*iter->begin()<<"-----------"<<endl;
552                         return SYNFIGTOOL_OK;
553                 }
554
555                 if (flag_requires_value(*iter))
556                 {
557                         cluster.push_back(*iter);
558                         arg_list.erase(iter);
559                         iter=next++;
560                         if (iter==arg_list.end())
561                         {
562                                 error("The `%s' flag requires a value.  Use --help for a list of options.", cluster.back().c_str());
563                                 return SYNFIGTOOL_MISSINGARGUMENT;
564                         }
565                 }
566
567                 cluster.push_back(*iter);
568                 arg_list.erase(iter);
569         }
570
571         return SYNFIGTOOL_OK;
572 }
573
574 int extract_RendDesc(arg_list_t &arg_list,RendDesc &desc)
575 {
576         arg_list_t::iterator iter, next;
577         int w=0,h=0;
578         float span=0;
579         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
580         {
581                 if(*iter=="-w")
582                 {
583                         arg_list.erase(iter);
584                         iter=next++;
585                         w=atoi(iter->c_str());
586                         arg_list.erase(iter);
587                 }
588                 else if(*iter=="-h")
589                 {
590                         arg_list.erase(iter);
591                         iter=next++;
592                         h=atoi(iter->c_str());
593                         arg_list.erase(iter);
594                 }
595                 else if(*iter=="-a")
596                 {
597             int a;
598                         arg_list.erase(iter);
599                         iter=next++;
600                         a=atoi(iter->c_str());
601                         desc.set_antialias(a);
602                         VERBOSE_OUT(1)<<strprintf(_("Antialiasing set to %d, (%d samples per pixel)"),a,a*a)<<endl;
603                         arg_list.erase(iter);
604                 }
605                 else if(*iter=="-s")
606                 {
607                         arg_list.erase(iter);
608                         iter=next++;
609                         span=atof(iter->c_str());
610                         VERBOSE_OUT(1)<<strprintf(_("Span set to %d units"),span)<<endl;
611                         arg_list.erase(iter);
612                 }
613                 else if(*iter=="--fps")
614                 {
615                         arg_list.erase(iter);
616                         iter=next++;
617                         float fps=atof(iter->c_str());
618                         desc.set_frame_rate(fps);
619                         arg_list.erase(iter);
620                         VERBOSE_OUT(1)<<strprintf(_("Frame rate set to %d frames per second"),fps)<<endl;
621                 }
622                 else if(*iter=="--dpi")
623                 {
624                         arg_list.erase(iter);
625                         iter=next++;
626                         float dpi=atof(iter->c_str());
627                         float dots_per_meter=dpi*39.3700787402;
628                         desc.set_x_res(dots_per_meter).set_y_res(dots_per_meter);
629                         arg_list.erase(iter);
630                         VERBOSE_OUT(1)<<strprintf(_("Physical resolution set to %f dpi"),dpi)<<endl;
631                 }
632                 else if(*iter=="--dpi-x")
633                 {
634                         arg_list.erase(iter);
635                         iter=next++;
636                         float dpi=atof(iter->c_str());
637                         float dots_per_meter=dpi*39.3700787402;
638                         desc.set_x_res(dots_per_meter);
639                         arg_list.erase(iter);
640                         VERBOSE_OUT(1)<<strprintf(_("Physical X resolution set to %f dpi"),dpi)<<endl;
641                 }
642                 else if(*iter=="--dpi-y")
643                 {
644                         arg_list.erase(iter);
645                         iter=next++;
646                         float dpi=atof(iter->c_str());
647                         float dots_per_meter=dpi*39.3700787402;
648                         desc.set_y_res(dots_per_meter);
649                         arg_list.erase(iter);
650                         VERBOSE_OUT(1)<<strprintf(_("Physical Y resolution set to %f dpi"),dpi)<<endl;
651                 }
652                 else if(*iter=="--start-time" || *iter=="--begin-time")
653                 {
654                         arg_list.erase(iter);
655                         iter=next++;
656                         desc.set_time_start(Time(*iter,desc.get_frame_rate()));
657                         arg_list.erase(iter);
658                 }
659                 else if(*iter=="--end-time")
660                 {
661                         arg_list.erase(iter);
662                         iter=next++;
663                         desc.set_time_end(Time(*iter,desc.get_frame_rate()));
664                         arg_list.erase(iter);
665                 }
666                 else if(*iter=="--time")
667                 {
668                         arg_list.erase(iter);
669                         iter=next++;
670                         desc.set_time(Time(*iter,desc.get_frame_rate()));
671                         VERBOSE_OUT(1)<<_("Rendering frame at ")<<desc.get_time_start().get_string(desc.get_frame_rate())<<endl;
672                         arg_list.erase(iter);
673                 }
674                 else if(*iter=="-g")
675                 {
676                         synfig::warning("Gamma argument is currently ignored");
677                         arg_list.erase(iter);
678                         iter=next++;
679                         //desc.set_gamma(Gamma(atof(iter->c_str())));
680                         arg_list.erase(iter);
681                 }
682                 else if (flag_requires_value(*iter))
683                         iter=next++;
684         }
685         if(w&&h)
686         {
687                 desc.set_wh(w,h);
688                 VERBOSE_OUT(1)<<strprintf(_("Resolution set to %dx%d"),w,h)<<endl;
689         }
690         else
691         {
692                 if(w)
693                 {
694                         VERBOSE_OUT(1)<<strprintf(_("Width set to %d pixels"),w)<<endl;
695                         desc.set_w(w);
696                 }
697                 if(h)
698                 {
699                         VERBOSE_OUT(1)<<strprintf(_("Height set to %d pixels"),h)<<endl;
700                         desc.set_h(h);
701                 }
702         }
703         if(span)
704                 desc.set_span(span);
705         return SYNFIGTOOL_OK;
706 }
707
708 int extract_quality(arg_list_t &arg_list,int &quality)
709 {
710         arg_list_t::iterator iter, next;
711         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
712         {
713                 if(*iter=="-Q")
714                 {
715                         arg_list.erase(iter);
716                         iter=next++;
717                         quality=atoi(iter->c_str());
718                         VERBOSE_OUT(1)<<strprintf(_("Quality set to %d"),quality)<<endl;
719                         arg_list.erase(iter);
720                 }
721                 else if (flag_requires_value(*iter))
722                         iter=next++;
723         }
724
725         return SYNFIGTOOL_OK;
726 }
727
728 int extract_threads(arg_list_t &arg_list,int &threads)
729 {
730         arg_list_t::iterator iter, next;
731         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
732         {
733                 if(*iter=="-T")
734                 {
735                         arg_list.erase(iter);
736                         iter=next++;
737                         threads=atoi(iter->c_str());
738                         VERBOSE_OUT(1)<<strprintf(_("Threads set to %d"),threads)<<endl;
739                         arg_list.erase(iter);
740                 }
741                 else if (flag_requires_value(*iter))
742                         iter=next++;
743         }
744
745         return SYNFIGTOOL_OK;
746 }
747
748 int extract_target(arg_list_t &arg_list,string &type)
749 {
750         arg_list_t::iterator iter, next;
751         type.clear();
752
753         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
754         {
755                 if(*iter=="-t")
756                 {
757                         arg_list.erase(iter);
758                         iter=next++;
759                         type=*iter;
760                         arg_list.erase(iter);
761                 }
762                 else if (flag_requires_value(*iter))
763                         iter=next++;
764         }
765
766         return SYNFIGTOOL_OK;
767 }
768
769 int extract_append(arg_list_t &arg_list,string &filename)
770 {
771         arg_list_t::iterator iter, next;
772         filename.clear();
773
774         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
775         {
776                 if(*iter=="--append")
777                 {
778                         arg_list.erase(iter);
779                         iter=next++;
780                         filename=*iter;
781                         arg_list.erase(iter);
782                 }
783                 else if (flag_requires_value(*iter))
784                         iter=next++;
785         }
786
787         return SYNFIGTOOL_OK;
788 }
789
790 int extract_outfile(arg_list_t &arg_list,string &outfile)
791 {
792         arg_list_t::iterator iter, next;
793         int ret=SYNFIGTOOL_FILENOTFOUND;
794         outfile.clear();
795
796         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
797         {
798                 if(*iter=="-o")
799                 {
800                         arg_list.erase(iter);
801                         iter=next++;
802                         outfile=*iter;
803                         arg_list.erase(iter);
804                         ret=SYNFIGTOOL_OK;
805                 }
806                 else if (flag_requires_value(*iter))
807                         iter=next++;
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                 else if (flag_requires_value(*iter))
828                         iter=next++;
829         }
830
831         return SYNFIGTOOL_OK;
832 }
833
834 int extract_list_canvases(arg_list_t &arg_list,bool &list_canvases)
835 {
836         arg_list_t::iterator iter, next;
837
838         for(next=arg_list.begin(),iter=next++;iter!=arg_list.end();iter=next++)
839                 if(*iter=="--list-canvases")
840                 {
841                         list_canvases = true;
842                         arg_list.erase(iter);
843                 }
844
845         return SYNFIGTOOL_OK;
846 }
847
848 void list_child_canvases(string prefix, Canvas::Handle canvas)
849 {
850         Canvas::Children children(canvas->children());
851         for (Canvas::Children::iterator iter = children.begin(); iter != children.end(); iter++)
852         {
853                 cout << prefix << ":" << (*iter)->get_id() << endl;
854                 list_child_canvases(prefix + ":" + (*iter)->get_id(), *iter);
855         }
856 }
857
858 /* === M E T H O D S ======================================================= */
859
860 /* === E N T R Y P O I N T ================================================= */
861
862 int main(int argc, char *argv[])
863 {
864         int i;
865         arg_list_t arg_list;
866         job_list_t job_list;
867
868         setlocale(LC_ALL, "");
869
870 #ifdef ENABLE_NLS
871         bindtextdomain("synfig", LOCALEDIR);
872         textdomain("synfig");
873 #endif
874
875         progname=argv[0];
876         Progress p(argv[0]);
877
878         if(!SYNFIG_CHECK_VERSION())
879         {
880                 cerr<<_("FATAL: Synfig Version Mismatch")<<endl;
881                 return SYNFIGTOOL_BADVERSION;
882         }
883
884         if(argc==1)
885         {
886                 display_help(0);
887                 return SYNFIGTOOL_BLANK;
888         }
889
890         for(i=1;i<argc;i++)
891                 arg_list.push_back(argv[i]);
892
893         if((i=process_global_flags(arg_list)))
894                 return i;
895
896         VERBOSE_OUT(1)<<_("verbosity set to ")<<verbosity<<endl;
897         synfig::Main synfig_main(dirname(progname),&p);
898
899         {
900                 arg_list_t defaults, imageargs;
901                 int ret;
902
903                 // Grab the defaults before the first file
904                 if ((ret = extract_arg_cluster(arg_list,defaults)) != SYNFIGTOOL_OK)
905                   return ret;
906
907                 while(arg_list.size())
908                 {
909                         string target_name;
910                         job_list.push_front(Job());
911                         int threads=0;
912
913                         imageargs=defaults;
914                         job_list.front().filename=arg_list.front();
915                         arg_list.pop_front();
916
917                         if ((ret = extract_arg_cluster(arg_list,imageargs)) != SYNFIGTOOL_OK)
918                           return ret;
919
920                         // Open the composition
921                         job_list.front().root=open_canvas(job_list.front().filename);
922
923                         if(!job_list.front().root)
924                         {
925                                 cerr<<_("Unable to open ")<<job_list.front().filename<<"."<<endl;
926                                 cerr<<_("Throwing out job...")<<endl;
927                                 job_list.pop_front();
928                                 continue;
929                         }
930
931                         bool list_canvases = false;
932                         extract_list_canvases(imageargs, list_canvases);
933                         job_list.front().list_canvases = list_canvases;
934
935                         job_list.front().root->set_time(0);
936
937                         string canvasid;
938                         extract_canvasid(imageargs,canvasid);
939                         if(!canvasid.empty())
940                         {
941                                 try
942                                 {
943                                         job_list.front().canvas=job_list.front().root->find_canvas(canvasid);
944                                 }
945                                 catch(Exception::IDNotFound)
946                                 {
947                                         cerr<<_("Unable to find canvas with ID \"")<<canvasid<<_("\" in ")<<job_list.front().filename<<"."<<endl;
948                                         cerr<<_("Throwing out job...")<<endl;
949                                         job_list.pop_front();
950                                         continue;
951
952                                 }
953                                 catch(Exception::BadLinkName)
954                                 {
955                                         cerr<<_("Invalid canvas name \"")<<canvasid<<_("\" in ")<<job_list.front().filename<<"."<<endl;
956                                         cerr<<_("Throwing out job...")<<endl;
957                                         job_list.pop_front();
958                                         continue;
959                                 }
960                         }
961                         else
962                                 job_list.front().canvas=job_list.front().root;
963
964                         extract_RendDesc(imageargs,job_list.front().canvas->rend_desc());
965                         extract_target(imageargs,target_name);
966                         extract_threads(imageargs,threads);
967                         job_list.front().quality=DEFAULT_QUALITY;
968                         extract_quality(imageargs,job_list.front().quality);
969                         VERBOSE_OUT(2)<<_("Quality set to ")<<job_list.front().quality<<endl;
970                         job_list.front().desc=job_list.front().canvas->rend_desc();
971                         extract_outfile(imageargs,job_list.front().outfilename);
972
973                         // Extract composite
974                         do{
975                                 string composite_file;
976                                 extract_append(imageargs,composite_file);
977                                 if(!composite_file.empty())
978                                 {
979                                         Canvas::Handle composite(open_canvas(composite_file));
980                                         if(!composite)
981                                                 break;
982                                         Canvas::reverse_iterator iter;
983                                         for(iter=composite->rbegin();iter!=composite->rend();++iter)
984                                         {
985                                                 Layer::Handle layer(*iter);
986                                                 if(layer->active())
987                                                         job_list.front().canvas->push_front(layer->clone());
988                                         }
989                                         VERBOSE_OUT(2)<<_("Appended contents of ")<<composite_file<<endl;
990                                 }
991                         } while(false);
992
993                         VERBOSE_OUT(4)<<_("Attempting to determine target/outfile...")<<endl;
994
995                         // If the target type is not yet defined,
996                         // try to figure it out from the outfile.
997                         if(target_name.empty() && !job_list.front().outfilename.empty())
998                         {
999                                 VERBOSE_OUT(3)<<_("Target name undefined, attempting to figure it out")<<endl;
1000                                 string ext = filename_extension(job_list.front().outfilename);
1001                                 if (ext.length()) ext = ext.substr(1);
1002                                 if(Target::ext_book().count(ext))
1003                                 {
1004                                         target_name=Target::ext_book()[ext];
1005                                         info("target name not specified - using %s", target_name.c_str());
1006                                 }
1007                                 else
1008                                 {
1009                                         string lower_ext(ext);
1010
1011                                         for(unsigned int i=0;i<ext.length();i++)
1012                                                 lower_ext[i] = tolower(ext[i]);
1013
1014                                         if(Target::ext_book().count(lower_ext))
1015                                         {
1016                                                 target_name=Target::ext_book()[lower_ext];
1017                                                 info("target name not specified - using %s", target_name.c_str());
1018                                         }
1019                                         else
1020                                                 target_name=ext;
1021                                 }
1022                         }
1023
1024                         // If the target type is STILL not yet defined, then
1025                         // set it to a some sort of default
1026                         if(target_name.empty())
1027                         {
1028                                 VERBOSE_OUT(2)<<_("Defaulting to PNG target...")<<endl;
1029                                 target_name="png";
1030                         }
1031
1032                         // If no output filename was provided, then
1033                         // create a output filename based on the
1034                         // given input filename. (ie: change the extension)
1035                         if(job_list.front().outfilename.empty())
1036                         {
1037                                 job_list.front().outfilename = filename_sans_extension(job_list.front().filename) + '.';
1038                                 if(Target::book().count(target_name))
1039                                         job_list.front().outfilename+=Target::book()[target_name].second;
1040                                 else
1041                                         job_list.front().outfilename+=target_name;
1042                         }
1043
1044                         VERBOSE_OUT(4)<<"target_name="<<target_name<<endl;
1045                         VERBOSE_OUT(4)<<"outfile_name="<<job_list.front().outfilename<<endl;
1046
1047                         VERBOSE_OUT(4)<<_("Creating the target...")<<endl;
1048                         job_list.front().target=synfig::Target::create(target_name,job_list.front().outfilename);
1049
1050                         if(target_name=="sif")
1051                                 job_list.front().sifout=true;
1052                         else
1053                         {
1054                                 if(!job_list.front().target)
1055                                 {
1056                                         cerr<<_("Unknown target for ")<<job_list.front().filename<<": "<<target_name<<endl;
1057                                         cerr<<_("Throwing out job...")<<endl;
1058                                         job_list.pop_front();
1059                                         continue;
1060                                 }
1061                                 job_list.front().sifout=false;
1062                         }
1063
1064                         // Set the Canvas on the Target
1065                         if(job_list.front().target)
1066                         {
1067                                 VERBOSE_OUT(4)<<_("Setting the canvas on the target...")<<endl;
1068                                 job_list.front().target->set_canvas(job_list.front().canvas);
1069                                 VERBOSE_OUT(4)<<_("Setting the quality of the target...")<<endl;
1070                                 job_list.front().target->set_quality(job_list.front().quality);
1071                         }
1072
1073                         // Set the threads for the target
1074                         if(job_list.front().target && Target_Scanline::Handle::cast_dynamic(job_list.front().target))
1075                                 Target_Scanline::Handle::cast_dynamic(job_list.front().target)->set_threads(threads);
1076
1077                         if(imageargs.size())
1078                         {
1079                                 cerr<<_("Unidentified arguments for ")<<job_list.front().filename<<": ";
1080                                 for(;imageargs.size();imageargs.pop_front())
1081                                         cerr<<' '<<imageargs.front();
1082                                 cerr<<endl;
1083                                 cerr<<_("Throwing out job...")<<endl;
1084                                 job_list.pop_front();
1085                                 continue;
1086                         }
1087                 }
1088         }
1089
1090         if(arg_list.size())
1091         {
1092                 cerr<<_("Unidentified arguments:");
1093                 for(;arg_list.size();arg_list.pop_front())
1094                         cerr<<' '<<arg_list.front();
1095                 cerr<<endl;
1096                 return SYNFIGTOOL_UNKNOWNARGUMENT;
1097         }
1098
1099         if(!job_list.size())
1100         {
1101                 cerr<<_("Nothing to do!")<<endl;
1102                 return SYNFIGTOOL_BORED;
1103         }
1104
1105         for(;job_list.size();job_list.pop_front())
1106         {
1107                 VERBOSE_OUT(3)<<job_list.front().filename<<" -- "<<endl<<'\t'<<
1108                 strprintf("w:%d, h:%d, a:%d, pxaspect:%f, imaspect:%f, span:%f",
1109                         job_list.front().desc.get_w(),
1110                         job_list.front().desc.get_h(),
1111                         job_list.front().desc.get_antialias(),
1112                         job_list.front().desc.get_pixel_aspect(),
1113                         job_list.front().desc.get_image_aspect(),
1114                         job_list.front().desc.get_span()
1115                         )<<endl<<'\t'<<
1116                 strprintf("tl:[%f,%f], br:[%f,%f], focus:[%f,%f]",
1117                         job_list.front().desc.get_tl()[0],job_list.front().desc.get_tl()[1],
1118                         job_list.front().desc.get_br()[0],job_list.front().desc.get_br()[1],
1119                         job_list.front().desc.get_focus()[0],job_list.front().desc.get_focus()[1]
1120                         )<<endl;
1121
1122                 RenderProgress p;
1123                 p.task(job_list.front().filename+" ==> "+job_list.front().outfilename);
1124                 if(job_list.front().sifout)
1125                 {
1126                         if(!save_canvas(job_list.front().outfilename,job_list.front().canvas))
1127                         {
1128                                 cerr<<"Render Failure."<<endl;
1129                                 return SYNFIGTOOL_RENDERFAILURE;
1130                         }
1131                 }
1132                 else if (job_list.front().list_canvases)
1133                 {
1134                         list_child_canvases(job_list.front().filename + "#", job_list.front().canvas);
1135                         cerr << endl;
1136                 }
1137                 else
1138                 {
1139                         VERBOSE_OUT(1)<<_("Rendering...")<<endl;
1140                         etl::clock timer;
1141                         timer.reset();
1142                         // Call the render member of the target
1143                         if(!job_list.front().target->render(&p))
1144                         {
1145                                 cerr<<"Render Failure."<<endl;
1146                                 return SYNFIGTOOL_RENDERFAILURE;
1147                         }
1148                         if(print_benchmarks)
1149                                 cout<<job_list.front().filename+": Rendered in "<<timer()<<" seconds."<<endl;
1150                 }
1151         }
1152
1153         job_list.clear();
1154
1155         VERBOSE_OUT(1)<<_("Done.")<<endl;
1156
1157         return SYNFIGTOOL_OK;
1158 }