Merge branch 'genete_static_values'
[synfig.git] / synfig-core / src / synfig / savecanvas.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file savecanvas.cpp
3 **      \brief Writeme
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 #ifdef HAVE_SYS_ERRNO_H
34 #       include <sys/errno.h>
35 #endif
36
37 #include "savecanvas.h"
38 #include "general.h"
39 #include "valuenode.h"
40 #include "valuenode_animated.h"
41 #include "valuenode_const.h"
42 #include "valuenode_dynamiclist.h"
43 #include "valuenode_reference.h"
44 #include "valuenode_bline.h"
45 #include "time.h"
46 #include "keyframe.h"
47 #include "layer.h"
48 #include "string.h"
49 #include "paramdesc.h"
50
51 #include <libxml++/libxml++.h>
52 #include <ETL/stringf>
53 #include "gradient.h"
54 #include <errno.h>
55
56 extern "C" {
57 #include <libxml/tree.h>
58 }
59
60 #endif
61
62 /* === U S I N G =========================================================== */
63
64 using namespace std;
65 using namespace etl;
66 using namespace synfig;
67
68 /* === M A C R O S ========================================================= */
69
70 #define COLOR_VALUE_TYPE_FORMAT         "%f"
71 #define VECTOR_VALUE_TYPE_FORMAT        "%0.10f"
72 #define TIME_TYPE_FORMAT                        "%0.3f"
73 #define VIEW_BOX_FORMAT                         "%f %f %f %f"
74
75 /* === G L O B A L S ======================================================= */
76
77 ReleaseVersion save_canvas_version = ReleaseVersion(RELEASE_VERSION_END-1);
78 int valuenode_too_new_count;
79
80 /* === P R O C E D U R E S ================================================= */
81
82 xmlpp::Element* encode_canvas(xmlpp::Element* root,Canvas::ConstHandle canvas);
83 xmlpp::Element* encode_value_node(xmlpp::Element* root,ValueNode::ConstHandle value_node,Canvas::ConstHandle canvas);
84
85 xmlpp::Element* encode_keyframe(xmlpp::Element* root,const Keyframe &kf, float fps)
86 {
87         root->set_name("keyframe");
88         root->set_attribute("time",kf.get_time().get_string(fps));
89         if(!kf.get_description().empty())
90                 root->set_child_text(kf.get_description());
91         return root;
92 }
93
94 xmlpp::Element* encode_static(xmlpp::Element* root,bool s)
95 {
96         if(s)
97                 root->set_attribute("static", s?"true":"false");
98         return root;
99 }
100
101
102 xmlpp::Element* encode_real(xmlpp::Element* root,Real v,bool s=false)
103 {
104         root->set_name("real");
105         root->set_attribute("value",strprintf(VECTOR_VALUE_TYPE_FORMAT,v));
106         encode_static(root, s);
107         return root;
108 }
109
110 xmlpp::Element* encode_time(xmlpp::Element* root,Time t,bool s=false)
111 {
112         root->set_name("time");
113         root->set_attribute("value",t.get_string());
114         encode_static(root, s);
115         return root;
116 }
117
118 xmlpp::Element* encode_integer(xmlpp::Element* root,int i,bool s=false)
119 {
120         root->set_name("integer");
121         root->set_attribute("value",strprintf("%i",i));
122         encode_static(root, s);
123         return root;
124 }
125
126 xmlpp::Element* encode_bool(xmlpp::Element* root, bool b,bool s=false)
127 {
128         root->set_name("bool");
129         root->set_attribute("value",b?"true":"false");
130         encode_static(root, s);
131         return root;
132 }
133
134 xmlpp::Element* encode_string(xmlpp::Element* root,const String &str,bool s=false)
135 {
136         root->set_name("string");
137         root->set_child_text(str);
138         encode_static(root, s);
139         return root;
140 }
141
142 xmlpp::Element* encode_vector(xmlpp::Element* root,Vector vect,bool s=false)
143 {
144         root->set_name("vector");
145         root->add_child("x")->set_child_text(strprintf(VECTOR_VALUE_TYPE_FORMAT,(float)vect[0]));
146         root->add_child("y")->set_child_text(strprintf(VECTOR_VALUE_TYPE_FORMAT,(float)vect[1]));
147         encode_static(root, s);
148         return root;
149 }
150
151 xmlpp::Element* encode_color(xmlpp::Element* root,Color color,bool s=false)
152 {
153         root->set_name("color");
154         root->add_child("r")->set_child_text(strprintf(COLOR_VALUE_TYPE_FORMAT,(float)color.get_r()));
155         root->add_child("g")->set_child_text(strprintf(COLOR_VALUE_TYPE_FORMAT,(float)color.get_g()));
156         root->add_child("b")->set_child_text(strprintf(COLOR_VALUE_TYPE_FORMAT,(float)color.get_b()));
157         root->add_child("a")->set_child_text(strprintf(COLOR_VALUE_TYPE_FORMAT,(float)color.get_a()));
158         encode_static(root, s);
159         return root;
160 }
161
162 xmlpp::Element* encode_angle(xmlpp::Element* root,Angle theta,bool s=false)
163 {
164         root->set_name("angle");
165         root->set_attribute("value",strprintf("%f",(float)Angle::deg(theta).get()));
166         encode_static(root, s);
167         return root;
168 }
169
170 xmlpp::Element* encode_segment(xmlpp::Element* root,Segment seg,bool s=false)
171 {
172         root->set_name("segment");
173         encode_vector(root->add_child("p1")->add_child("vector"),seg.p1);
174         encode_vector(root->add_child("t1")->add_child("vector"),seg.t1);
175         encode_vector(root->add_child("p2")->add_child("vector"),seg.p2);
176         encode_vector(root->add_child("t2")->add_child("vector"),seg.t2);
177         encode_static(root, s);
178         return root;
179 }
180
181 xmlpp::Element* encode_bline_point(xmlpp::Element* root,BLinePoint bline_point)
182 {
183         root->set_name(ValueBase::type_name(ValueBase::TYPE_BLINEPOINT));
184
185         encode_vector(root->add_child("vertex")->add_child("vector"),bline_point.get_vertex());
186         encode_vector(root->add_child("t1")->add_child("vector"),bline_point.get_tangent1());
187
188         if(bline_point.get_split_tangent_flag())
189                 encode_vector(root->add_child("t2")->add_child("vector"),bline_point.get_tangent2());
190
191         encode_real(root->add_child("width")->add_child("real"),bline_point.get_width());
192         encode_real(root->add_child("origin")->add_child("real"),bline_point.get_origin());
193         return root;
194 }
195
196 xmlpp::Element* encode_gradient(xmlpp::Element* root,Gradient x,bool s=false)
197 {
198         root->set_name("gradient");
199         encode_static(root, s);
200         Gradient::const_iterator iter;
201         x.sort();
202         for(iter=x.begin();iter!=x.end();iter++)
203         {
204                 xmlpp::Element *cpoint(encode_color(root->add_child("color"),iter->color));
205                 cpoint->set_attribute("pos",strprintf("%f",iter->pos));
206         }
207         return root;
208 }
209
210
211 xmlpp::Element* encode_value(xmlpp::Element* root,const ValueBase &data,Canvas::ConstHandle canvas=0);
212
213 xmlpp::Element* encode_list(xmlpp::Element* root,std::list<ValueBase> list, Canvas::ConstHandle canvas=0)
214 {
215         root->set_name("list");
216
217         while(!list.empty())
218         {
219                 encode_value(root->add_child("value"),list.front(),canvas);
220                 list.pop_front();
221         }
222
223         return root;
224 }
225
226 xmlpp::Element* encode_value(xmlpp::Element* root,const ValueBase &data,Canvas::ConstHandle canvas)
227 {
228         switch(data.get_type())
229         {
230         case ValueBase::TYPE_REAL:
231                 return encode_real(root,data.get(Real()), data.get_static());
232         case ValueBase::TYPE_TIME:
233                 return encode_time(root,data.get(Time()), data.get_static());
234         case ValueBase::TYPE_INTEGER:
235                 return encode_integer(root,data.get(int()), data.get_static());
236         case ValueBase::TYPE_COLOR:
237                 return encode_color(root,data.get(Color()), data.get_static());
238         case ValueBase::TYPE_VECTOR:
239                 return encode_vector(root,data.get(Vector()), data.get_static());
240         case ValueBase::TYPE_ANGLE:
241                 return encode_angle(root,data.get(Angle()), data.get_static());
242         case ValueBase::TYPE_BOOL:
243                 return encode_bool(root,data.get(bool()), data.get_static());
244         case ValueBase::TYPE_STRING:
245                 return encode_string(root,data.get(String()), data.get_static());
246         case ValueBase::TYPE_SEGMENT:
247                 return encode_segment(root,data.get(Segment()), data.get_static());
248         case ValueBase::TYPE_BLINEPOINT:
249                 return encode_bline_point(root,data.get(BLinePoint()));
250         case ValueBase::TYPE_GRADIENT:
251                 return encode_gradient(root,data.get(Gradient()), data.get_static());
252         case ValueBase::TYPE_LIST:
253                 return encode_list(root,data,canvas);
254         case ValueBase::TYPE_CANVAS:
255                 return encode_canvas(root,data.get(Canvas::Handle()).get());
256         case ValueBase::TYPE_NIL:
257                 synfig::error("Encountered NIL ValueBase");
258                 root->set_name("nil");
259                 return root;
260         default:
261                 synfig::error(strprintf(_("Unknown value(%s), cannot create XML representation!"),ValueBase::type_local_name(data.get_type()).c_str()));
262                 root->set_name("nil");
263                 return root;
264         }
265 }
266
267 xmlpp::Element* encode_animated(xmlpp::Element* root,ValueNode_Animated::ConstHandle value_node,Canvas::ConstHandle canvas=0)
268 {
269         assert(value_node);
270         root->set_name("animated");
271
272         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
273
274         const ValueNode_Animated::WaypointList &waypoint_list=value_node->waypoint_list();
275         ValueNode_Animated::WaypointList::const_iterator iter;
276
277         for(iter=waypoint_list.begin();iter!=waypoint_list.end();++iter)
278         {
279                 xmlpp::Element *waypoint_node=root->add_child("waypoint");
280                 waypoint_node->set_attribute("time",iter->get_time().get_string());
281
282                 if(iter->get_value_node()->is_exported())
283                         waypoint_node->set_attribute("use",iter->get_value_node()->get_relative_id(canvas));
284                 else {
285                         ValueNode::ConstHandle value_node = iter->get_value_node();
286                         if(ValueNode_Const::ConstHandle::cast_dynamic(value_node)) {
287                                 const ValueBase data = ValueNode_Const::ConstHandle::cast_dynamic(value_node)->get_value();
288                                 if (data.get_type() == ValueBase::TYPE_CANVAS)
289                                         waypoint_node->set_attribute("use",data.get(Canvas::Handle()).get()->get_relative_id(canvas));
290                                 else
291                                         encode_value_node(waypoint_node->add_child("value_node"),iter->get_value_node(),canvas);
292                         }
293                         else
294                                 encode_value_node(waypoint_node->add_child("value_node"),iter->get_value_node(),canvas);
295                 }
296
297                 switch(iter->get_before())
298                 {
299                 case INTERPOLATION_HALT:
300                         waypoint_node->set_attribute("before","halt");
301                         break;
302                 case INTERPOLATION_LINEAR:
303                         waypoint_node->set_attribute("before","linear");
304                         break;
305                 case INTERPOLATION_MANUAL:
306                         waypoint_node->set_attribute("before","manual");
307                         break;
308                 case INTERPOLATION_CONSTANT:
309                         waypoint_node->set_attribute("before","constant");
310                         break;
311                 case INTERPOLATION_TCB:
312                         waypoint_node->set_attribute("before","auto");
313                         break;
314                 default:
315                         error("Unknown waypoint type for \"before\" attribute");
316                 }
317
318                 switch(iter->get_after())
319                 {
320                 case INTERPOLATION_HALT:
321                         waypoint_node->set_attribute("after","halt");
322                         break;
323                 case INTERPOLATION_LINEAR:
324                         waypoint_node->set_attribute("after","linear");
325                         break;
326                 case INTERPOLATION_MANUAL:
327                         waypoint_node->set_attribute("after","manual");
328                         break;
329                 case INTERPOLATION_CONSTANT:
330                         waypoint_node->set_attribute("after","constant");
331                         break;
332                 case INTERPOLATION_TCB:
333                         waypoint_node->set_attribute("after","auto");
334                         break;
335                 default:
336                         error("Unknown waypoint type for \"after\" attribute");
337                 }
338
339                 if(iter->get_tension()!=0.0)
340                         waypoint_node->set_attribute("tension",strprintf("%f",iter->get_tension()));
341                 if(iter->get_temporal_tension()!=0.0)
342                         waypoint_node->set_attribute("temporal-tension",strprintf("%f",iter->get_temporal_tension()));
343                 if(iter->get_continuity()!=0.0)
344                         waypoint_node->set_attribute("continuity",strprintf("%f",iter->get_continuity()));
345                 if(iter->get_bias()!=0.0)
346                         waypoint_node->set_attribute("bias",strprintf("%f",iter->get_bias()));
347
348         }
349
350         return root;
351 }
352
353 xmlpp::Element* encode_dynamic_list(xmlpp::Element* root,ValueNode_DynamicList::ConstHandle value_node,Canvas::ConstHandle canvas=0)
354 {
355         assert(value_node);
356         const float fps(canvas?canvas->rend_desc().get_frame_rate():0);
357
358         root->set_name(value_node->get_name());
359
360         root->set_attribute("type",ValueBase::type_name(value_node->get_contained_type()));
361
362         vector<ValueNode_DynamicList::ListEntry>::const_iterator iter;
363
364         ValueNode_BLine::ConstHandle bline_value_node(ValueNode_BLine::ConstHandle::cast_dynamic(value_node));
365
366         if(bline_value_node)
367         {
368                 if(bline_value_node->get_loop())
369                         root->set_attribute("loop","true");
370                 else
371                         root->set_attribute("loop","false");
372         }
373
374         for(iter=value_node->list.begin();iter!=value_node->list.end();++iter)
375         {
376                 xmlpp::Element  *entry_node=root->add_child("entry");
377                 assert(iter->value_node);
378                 if(!iter->value_node->get_id().empty())
379                         entry_node->set_attribute("use",iter->value_node->get_relative_id(canvas));
380                 else
381                         encode_value_node(entry_node->add_child("value_node"),iter->value_node,canvas);
382
383                 // process waypoints
384                 {
385                         typedef synfig::ValueNode_DynamicList::ListEntry::Activepoint Activepoint;
386                         typedef synfig::ValueNode_DynamicList::ListEntry::ActivepointList ActivepointList;
387                         String begin_sequence;
388                         String end_sequence;
389
390                         const ActivepointList& timing_info(iter->timing_info);
391                         ActivepointList::const_iterator entry_iter;
392
393                         for(entry_iter=timing_info.begin();entry_iter!=timing_info.end();++entry_iter)
394                                 if(entry_iter->state==true)
395                                 {
396                                         if(entry_iter->priority)
397                                                 begin_sequence+=strprintf("p%d ",entry_iter->priority);
398                                         begin_sequence+=entry_iter->time.get_string(fps)+", ";
399                                 }
400                                 else
401                                 {
402                                         if(entry_iter->priority)
403                                                 end_sequence+=strprintf("p%d ",entry_iter->priority);
404                                         end_sequence+=entry_iter->time.get_string(fps)+", ";
405                                 }
406
407                         // If this is just a plane-jane vanilla entry,
408                         // then don't bother with begins and ends
409                         if(end_sequence.empty() && begin_sequence=="SOT, ")
410                                 begin_sequence.clear();
411
412                         if(!begin_sequence.empty())
413                         {
414                                 // Remove the last ", " stuff
415                                 begin_sequence=String(begin_sequence.begin(),begin_sequence.end()-2);
416                                 // Add the attribute
417                                 entry_node->set_attribute("on",begin_sequence);
418                         }
419
420                         if(!end_sequence.empty())
421                         {
422                                 // Remove the last ", " stuff
423                                 end_sequence=String(end_sequence.begin(),end_sequence.end()-2);
424                                 // Add the attribute
425                                 entry_node->set_attribute("off",end_sequence);
426                         }
427                 }
428         }
429
430         return root;
431 }
432
433 // Generic linkable data node entry
434 xmlpp::Element* encode_linkable_value_node(xmlpp::Element* root,LinkableValueNode::ConstHandle value_node,Canvas::ConstHandle canvas=0)
435 {
436         assert(value_node);
437
438         String name(value_node->get_name());
439         ReleaseVersion saving_version(get_file_version());
440         ReleaseVersion feature_version(LinkableValueNode::book()[name].release_version);
441
442         if (saving_version < feature_version)
443         {
444                 valuenode_too_new_count++;
445                 warning("can't save <%s> valuenodes in this old file format version", name.c_str());
446
447                 ValueBase value((*value_node)(0));
448                 encode_value(root,value,canvas);
449
450                 return root;
451         }
452
453         root->set_name(name);
454
455         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
456
457         int i;
458         for(i=0;i<value_node->link_count();i++)
459         {
460                 ValueNode::ConstHandle link=value_node->get_link(i).constant();
461                 if(!link)
462                         throw runtime_error("Bad link");
463                 if(link->is_exported())
464                         root->set_attribute(value_node->link_name(i),link->get_relative_id(canvas));
465                 else
466                         encode_value_node(root->add_child(value_node->link_name(i))->add_child("value_node"),link,canvas);
467         }
468
469         return root;
470 }
471
472 xmlpp::Element* encode_value_node(xmlpp::Element* root,ValueNode::ConstHandle value_node,Canvas::ConstHandle canvas)
473 {
474         assert(value_node);
475
476         if(ValueNode_Animated::ConstHandle::cast_dynamic(value_node))
477                 encode_animated(root,ValueNode_Animated::ConstHandle::cast_dynamic(value_node),canvas);
478         else
479         if(ValueNode_DynamicList::ConstHandle::cast_dynamic(value_node))
480                 encode_dynamic_list(root,ValueNode_DynamicList::ConstHandle::cast_dynamic(value_node),canvas);
481         else if(ValueNode_Const::ConstHandle::cast_dynamic(value_node))
482         {
483                 encode_value(root,ValueNode_Const::ConstHandle::cast_dynamic(value_node)->get_value(),canvas);
484         }
485         else
486         if(LinkableValueNode::ConstHandle::cast_dynamic(value_node))
487                 encode_linkable_value_node(root,LinkableValueNode::ConstHandle::cast_dynamic(value_node),canvas);
488         else
489         {
490                 error(_("Unknown ValueNode Type (%s), cannot create an XML representation"),value_node->get_local_name().c_str());
491                 root->set_name("nil");
492         }
493
494         assert(root);
495
496         if(!value_node->get_id().empty())
497                 root->set_attribute("id",value_node->get_id());
498
499         if(value_node->rcount()>1)
500                 root->set_attribute("guid",(value_node->get_guid()^canvas->get_root()->get_guid()).get_string());
501
502         return root;
503 }
504
505 xmlpp::Element* encode_layer(xmlpp::Element* root,Layer::ConstHandle layer)
506 {
507         root->set_name("layer");
508
509         root->set_attribute("type",layer->get_name());
510         root->set_attribute("active",layer->active()?"true":"false");
511
512         if(!layer->get_version().empty())
513                 root->set_attribute("version",layer->get_version());
514         if(!layer->get_description().empty())
515                 root->set_attribute("desc",layer->get_description());
516         if(!layer->get_group().empty())
517                 root->set_attribute("group",layer->get_group());
518
519         Layer::Vocab vocab(layer->get_param_vocab());
520         Layer::Vocab::const_iterator iter;
521
522         const Layer::DynamicParamList &dynamic_param_list=layer->dynamic_param_list();
523
524         for(iter=vocab.begin();iter!=vocab.end();++iter)
525         {
526                 // Handle dynamic parameters
527                 if(dynamic_param_list.count(iter->get_name()))
528                 {
529                         xmlpp::Element *node=root->add_child("param");
530                         node->set_attribute("name",iter->get_name());
531
532                         handle<const ValueNode> value_node=dynamic_param_list.find(iter->get_name())->second;
533
534                         // If the valuenode has no ID, then it must be defined in-place
535                         if(value_node->get_id().empty())
536                         {
537                                 encode_value_node(node->add_child("value_node"),value_node,layer->get_canvas().constant());
538                         }
539                         else
540                         {
541                                 node->set_attribute("use",value_node->get_relative_id(layer->get_canvas()));
542                         }
543                 }
544                 else  // Handle normal parameters
545                 if(iter->get_critical())
546                 {
547                         ValueBase value=layer->get_param(iter->get_name());
548                         if(!value.is_valid())
549                         {
550                                 error("Layer doesn't know its own vocabulary -- "+iter->get_name());
551                                 continue;
552                         }
553
554                         if(value.get_type()==ValueBase::TYPE_CANVAS)
555                         {
556                                 // the ->is_inline() below was crashing if the canvas
557                                 // contained a PasteCanvas with the default <No Image
558                                 // Selected> Canvas setting;  this avoids the crash
559                                 if (!value.get(Canvas::LooseHandle()))
560                                         continue;
561
562                                 if (!value.get(Canvas::LooseHandle())->is_inline())
563                                 {
564                                         Canvas::Handle child(value.get(Canvas::LooseHandle()));
565
566                                         if(!value.get(Canvas::Handle()))
567                                                 continue;
568                                         xmlpp::Element *node=root->add_child("param");
569                                         node->set_attribute("name",iter->get_name());
570                                         node->set_attribute("use",child->get_relative_id(layer->get_canvas()));
571                                         if(value.get_static())
572                                                 node->set_attribute("static", value.get_static()?"true":"false");
573                                         continue;
574                                 }
575                         }
576                         xmlpp::Element *node=root->add_child("param");
577                         node->set_attribute("name",iter->get_name());
578
579                         encode_value(node->add_child("value"),value,layer->get_canvas().constant());
580                 }
581         }
582
583
584         return root;
585 }
586
587 xmlpp::Element* encode_canvas(xmlpp::Element* root,Canvas::ConstHandle canvas)
588 {
589         assert(canvas);
590         const RendDesc &rend_desc=canvas->rend_desc();
591         root->set_name("canvas");
592
593         if(canvas->is_root())
594                 root->set_attribute("version",canvas->get_version());
595
596         if(!canvas->get_id().empty() && !canvas->is_root() && !canvas->is_inline())
597                 root->set_attribute("id",canvas->get_id());
598
599         if(!canvas->parent() || canvas->parent()->rend_desc().get_w()!=canvas->rend_desc().get_w())
600                 root->set_attribute("width",strprintf("%d",rend_desc.get_w()));
601
602         if(!canvas->parent() || canvas->parent()->rend_desc().get_h()!=canvas->rend_desc().get_h())
603                 root->set_attribute("height",strprintf("%d",rend_desc.get_h()));
604
605         if(!canvas->parent() || canvas->parent()->rend_desc().get_x_res()!=canvas->rend_desc().get_x_res())
606                 root->set_attribute("xres",strprintf("%f",rend_desc.get_x_res()));
607
608         if(!canvas->parent() || canvas->parent()->rend_desc().get_y_res()!=canvas->rend_desc().get_y_res())
609                 root->set_attribute("yres",strprintf("%f",rend_desc.get_y_res()));
610
611
612         if(!canvas->parent() ||
613                 canvas->parent()->rend_desc().get_tl()!=canvas->rend_desc().get_tl() ||
614                 canvas->parent()->rend_desc().get_br()!=canvas->rend_desc().get_br())
615         root->set_attribute("view-box",strprintf(VIEW_BOX_FORMAT,
616                 rend_desc.get_tl()[0],
617                 rend_desc.get_tl()[1],
618                 rend_desc.get_br()[0],
619                 rend_desc.get_br()[1])
620         );
621
622         if(!canvas->parent() || canvas->parent()->rend_desc().get_antialias()!=canvas->rend_desc().get_antialias())
623                 root->set_attribute("antialias",strprintf("%d",rend_desc.get_antialias()));
624
625         if(!canvas->parent())
626                 root->set_attribute("fps",strprintf(TIME_TYPE_FORMAT,rend_desc.get_frame_rate()));
627
628         if(!canvas->parent() || canvas->parent()->rend_desc().get_time_start()!=canvas->rend_desc().get_time_start())
629                 root->set_attribute("begin-time",rend_desc.get_time_start().get_string(rend_desc.get_frame_rate()));
630
631         if(!canvas->parent() || canvas->parent()->rend_desc().get_time_end()!=canvas->rend_desc().get_time_end())
632                 root->set_attribute("end-time",rend_desc.get_time_end().get_string(rend_desc.get_frame_rate()));
633
634         if(!canvas->is_inline())
635         {
636                 root->set_attribute("bgcolor",strprintf(VIEW_BOX_FORMAT,
637                         rend_desc.get_bg_color().get_r(),
638                         rend_desc.get_bg_color().get_g(),
639                         rend_desc.get_bg_color().get_b(),
640                         rend_desc.get_bg_color().get_a())
641                 );
642
643                 if(!canvas->get_name().empty())
644                         root->add_child("name")->set_child_text(canvas->get_name());
645                 if(!canvas->get_description().empty())
646                         root->add_child("desc")->set_child_text(canvas->get_description());
647                 if(!canvas->get_author().empty())
648                         root->add_child("author")->set_child_text(canvas->get_description());
649
650                 std::list<String> meta_keys(canvas->get_meta_data_keys());
651                 while(!meta_keys.empty())
652                 {
653                         xmlpp::Element* meta_element(root->add_child("meta"));
654                         meta_element->set_attribute("name",meta_keys.front());
655                         meta_element->set_attribute("content",canvas->get_meta_data(meta_keys.front()));
656                         meta_keys.pop_front();
657                 }
658                 for(KeyframeList::const_iterator iter=canvas->keyframe_list().begin();iter!=canvas->keyframe_list().end();++iter)
659                         encode_keyframe(root->add_child("keyframe"),*iter,canvas->rend_desc().get_frame_rate());
660         }
661
662         // Output the <defs> section
663         //! Check where the parentheses should really go - around the && or the ||?
664         //! If children is not empty (there are exported canvases in the current canvas)
665         //! they must be listed in the defs section regardless the result of check the
666         //! Value Node list (exported value nodes in the canvas) and if the canvas is
667         //! in line or not. Inline canvases cannot have exported canvases inside.
668         if((!canvas->is_inline() && !canvas->value_node_list().empty()) || !canvas->children().empty())
669         {
670                 xmlpp::Element *node=root->add_child("defs");
671                 const ValueNodeList &value_node_list(canvas->value_node_list());
672
673                 for(ValueNodeList::const_iterator iter=value_node_list.begin();iter!=value_node_list.end();++iter)
674                 {
675                         // If the value_node is a constant, then use the shorthand
676                         if(handle<ValueNode_Const>::cast_dynamic(*iter))
677                         {
678                                 ValueNode_Const::Handle value_node(ValueNode_Const::Handle::cast_dynamic(*iter));
679                                 reinterpret_cast<xmlpp::Element*>(encode_value(node->add_child("value"),value_node->get_value()))->set_attribute("id",value_node->get_id());
680                                 continue;
681                         }
682                         encode_value_node(node->add_child("value_node"),*iter,canvas);
683                         // writeme
684                 }
685
686                 for(Canvas::Children::const_iterator iter=canvas->children().begin();iter!=canvas->children().end();++iter)
687                 {
688                         encode_canvas(node->add_child("canvas"),*iter);
689                 }
690         }
691
692         Canvas::const_reverse_iterator iter;
693
694         for(iter=canvas->rbegin();iter!=canvas->rend();++iter)
695                 encode_layer(root->add_child("layer"),*iter);
696
697         return root;
698 }
699
700 xmlpp::Element* encode_canvas_toplevel(xmlpp::Element* root,Canvas::ConstHandle canvas)
701 {
702         valuenode_too_new_count = 0;
703
704         xmlpp::Element* ret = encode_canvas(root, canvas);
705
706         if (valuenode_too_new_count)
707                 warning("saved %d valuenodes as constant values in old file format\n", valuenode_too_new_count);
708
709         return ret;
710 }
711
712 bool
713 synfig::save_canvas(const String &filename, Canvas::ConstHandle canvas)
714 {
715     ChangeLocale change_locale(LC_NUMERIC, "C");
716
717         synfig::String tmp_filename(filename+".TMP");
718
719         if (filename_extension(filename) == ".sifz")
720                 xmlSetCompressMode(9);
721         else
722                 xmlSetCompressMode(0);
723
724         try
725         {
726                 assert(canvas);
727                 xmlpp::Document document;
728
729                 encode_canvas_toplevel(document.create_root_node("canvas"),canvas);
730
731                 document.write_to_file_formatted(tmp_filename);
732
733 #ifdef _WIN32
734                 // On Win32 platforms, rename() has bad behavior. work around it.
735                 char old_file[80]="sif.XXXXXXXX";
736                 mktemp(old_file);
737                 rename(filename.c_str(),old_file);
738                 if(rename(tmp_filename.c_str(),filename.c_str())!=0)
739                 {
740                         rename(old_file,tmp_filename.c_str());
741                         synfig::error("synfig::save_canvas(): Unable to rename file to correct filename, errno=%d",errno);
742                         return false;
743                 }
744                 remove(old_file);
745 #else
746                 if(rename(tmp_filename.c_str(),filename.c_str())!=0)
747                 {
748                         synfig::error("synfig::save_canvas(): Unable to rename file to correct filename, errno=%d",errno);
749                         return false;
750                 }
751 #endif
752         }
753         catch(...) { synfig::error("synfig::save_canvas(): Caught unknown exception"); return false; }
754
755         return true;
756 }
757
758 String
759 synfig::canvas_to_string(Canvas::ConstHandle canvas)
760 {
761     ChangeLocale change_locale(LC_NUMERIC, "C");
762         assert(canvas);
763
764         xmlpp::Document document;
765
766         encode_canvas_toplevel(document.create_root_node("canvas"),canvas);
767
768         return document.write_to_string_formatted();
769 }
770
771 void
772 synfig::set_file_version(ReleaseVersion version)
773 {
774         save_canvas_version = version;
775 }
776
777 ReleaseVersion
778 synfig::get_file_version()
779 {
780         return save_canvas_version;
781 }