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