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