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