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