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