8988a50d88c9ddecd388e23c41a4f69970bafe9b
[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 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 */
21 /* ========================================================================= */
22
23 /* === H E A D E R S ======================================================= */
24
25 #ifdef USING_PCH
26 #       include "pch.h"
27 #else
28 #ifdef HAVE_CONFIG_H
29 #       include <config.h>
30 #endif
31
32 #ifdef HAVE_SYS_ERRNO_H
33 #       include <sys/errno.h>
34 #endif
35
36 #include "savecanvas.h"
37 #include "general.h"
38 #include "valuenode.h"
39 #include "valuenode_subtract.h"
40 #include "valuenode_animated.h"
41 #include "valuenode_composite.h"
42 #include "valuenode_const.h"
43 #include "valuenode_linear.h"
44 #include "valuenode_dynamiclist.h"
45 #include "valuenode_reference.h"
46 #include "valuenode_segcalctangent.h"
47 #include "valuenode_segcalcvertex.h"
48 #include "valuenode_bline.h"
49 #include "time.h"
50 #include "keyframe.h"
51 #include "layer.h"
52 #include "string.h"
53 #include "paramdesc.h"
54
55 #include <libxml++/libxml++.h>
56 #include <ETL/stringf>
57 #include "gradient.h"
58 #include <errno.h>
59
60 extern "C" {
61 #include <libxml/tree.h>
62 }
63
64 #endif
65
66 /* === U S I N G =========================================================== */
67
68 using namespace std;
69 using namespace etl;
70 using namespace synfig;
71
72 /* === M A C R O S ========================================================= */
73
74 #define COLOR_VALUE_TYPE_FORMAT         "%f"
75 #define VECTOR_VALUE_TYPE_FORMAT        "%0.10f"
76 #define TIME_TYPE_FORMAT                        "%0.3f"
77 #define VIEW_BOX_FORMAT                         "%f %f %f %f"
78
79 /* === G L O B A L S ======================================================= */
80
81 /* === P R O C E D U R E S ================================================= */
82
83 xmlpp::Element* encode_canvas(xmlpp::Element* root,Canvas::ConstHandle canvas);
84 xmlpp::Element* encode_value_node(xmlpp::Element* root,ValueNode::ConstHandle value_node,Canvas::ConstHandle canvas);
85
86 xmlpp::Element* encode_keyframe(xmlpp::Element* root,const Keyframe &kf, float fps)
87 {
88         root->set_name("keyframe");
89         root->set_attribute("time",kf.get_time().get_string(fps));
90         if(!kf.get_description().empty())
91                 root->set_child_text(kf.get_description());
92         return root;
93 }
94
95
96 xmlpp::Element* encode_real(xmlpp::Element* root,Real v)
97 {
98         root->set_name("real");
99         root->set_attribute("value",strprintf(VECTOR_VALUE_TYPE_FORMAT,v));
100         return root;
101 }
102
103 xmlpp::Element* encode_time(xmlpp::Element* root,Time t, float /*fps*/=0)
104 {
105         root->set_name("time");
106         //root->set_attribute("value",t.get_string(fps));
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()));
218         case ValueBase::TYPE_TIME:
219                 if(canvas)
220                         return encode_time(root,data.get(Time()),canvas->rend_desc().get_frame_rate());
221                 else
222                         return encode_time(root,data.get(Time()));
223         case ValueBase::TYPE_INTEGER:
224                 return encode_integer(root,data.get(int()));
225         case ValueBase::TYPE_COLOR:
226                 return encode_color(root,data.get(Color()));
227         case ValueBase::TYPE_VECTOR:
228                 return encode_vector(root,data.get(Vector()));
229         case ValueBase::TYPE_ANGLE:
230                 return encode_angle(root,data.get(Angle()));
231         case ValueBase::TYPE_BOOL:
232                 return encode_bool(root,data.get(bool()));
233         case ValueBase::TYPE_STRING:
234                 return encode_string(root,data.get(String()));
235         case ValueBase::TYPE_SEGMENT:
236                 return encode_segment(root,data.get(Segment()));
237         case ValueBase::TYPE_BLINEPOINT:
238                 return encode_bline_point(root,data.get(BLinePoint()));
239         case ValueBase::TYPE_GRADIENT:
240                 return encode_gradient(root,data.get(Gradient()));
241         case ValueBase::TYPE_LIST:
242                 return encode_list(root,data,canvas);
243         case ValueBase::TYPE_CANVAS:
244                 return encode_canvas(root,data.get(Canvas::Handle()).get());
245         case ValueBase::TYPE_NIL:
246                 synfig::error("Encountered NIL ValueBase");
247                 root->set_name("nil");
248                 return root;
249         default:
250                 synfig::error(strprintf("Unknown value(%s), cannot create XML representation!",ValueBase::type_name(data.get_type()).c_str()));
251                 root->set_name("nil");
252                 return root;
253         }
254 }
255
256 xmlpp::Element* encode_animated(xmlpp::Element* root,ValueNode_Animated::ConstHandle value_node,Canvas::ConstHandle canvas=0)
257 {
258         assert(value_node);
259         root->set_name("animated");
260
261         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
262
263         const ValueNode_Animated::WaypointList &waypoint_list=value_node->waypoint_list();
264         ValueNode_Animated::WaypointList::const_iterator iter;
265
266         for(iter=waypoint_list.begin();iter!=waypoint_list.end();++iter)
267         {
268                 xmlpp::Element *waypoint_node=root->add_child("waypoint");
269                 //waypoint_node->set_attribute("time",iter->get_time().get_string(canvas->rend_desc().get_frame_rate()));
270                 waypoint_node->set_attribute("time",iter->get_time().get_string());
271
272                 //waypoint_node->add_child(encode_value(iter->get_value(),canvas));
273                 if(iter->get_value_node()->is_exported())
274                         waypoint_node->set_attribute("use",iter->get_value_node()->get_relative_id(canvas));
275                 else {
276                         ValueNode::ConstHandle value_node = iter->get_value_node();
277                         if(ValueNode_Const::ConstHandle::cast_dynamic(value_node)) {
278                                 const ValueBase data = ValueNode_Const::ConstHandle::cast_dynamic(value_node)->get_value();
279                                 if (data.get_type() == ValueBase::TYPE_CANVAS)
280                                         waypoint_node->set_attribute("use",data.get(Canvas::Handle()).get()->get_relative_id(canvas));
281                                 else
282                                         encode_value_node(waypoint_node->add_child("value_node"),iter->get_value_node(),canvas);
283                         }
284                         else
285                                 encode_value_node(waypoint_node->add_child("value_node"),iter->get_value_node(),canvas);
286                 }
287
288                 switch(iter->get_before())
289                 {
290                 case INTERPOLATION_HALT:
291                         waypoint_node->set_attribute("before","halt");
292                         break;
293                 case INTERPOLATION_LINEAR:
294                         // This is the default value for angles, so don't add a new attribute for them
295                         if (value_node->get_type() != ValueBase::TYPE_ANGLE)
296                                 waypoint_node->set_attribute("before","linear");
297                         break;
298                 case INTERPOLATION_MANUAL:
299                         waypoint_node->set_attribute("before","manual");
300                         break;
301                 case INTERPOLATION_CONSTANT:
302                         waypoint_node->set_attribute("before","constant");
303                         break;
304                 case INTERPOLATION_TCB:
305                         // This is the default value, so don't add a new attribute (unless it's an angle - they default to linear)
306                         if (value_node->get_type() == ValueBase::TYPE_ANGLE)
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                         // This is the default value for angles, so don't add a new attribute for them
320                         if (value_node->get_type() != ValueBase::TYPE_ANGLE)
321                                 waypoint_node->set_attribute("after","linear");
322                         break;
323                 case INTERPOLATION_MANUAL:
324                         waypoint_node->set_attribute("after","manual");
325                         break;
326                 case INTERPOLATION_CONSTANT:
327                         waypoint_node->set_attribute("after","constant");
328                         break;
329                 case INTERPOLATION_TCB:
330                         // This is the default value, so don't add a new attribute (unless it's an angle - they default to linear)
331                         if (value_node->get_type() == ValueBase::TYPE_ANGLE)
332                                 waypoint_node->set_attribute("after","auto");
333                         break;
334                 default:
335                         error("Unknown waypoint type for \"after\" attribute");
336                 }
337
338                 if(iter->get_tension()!=0.0)
339                         waypoint_node->set_attribute("tension",strprintf("%f",iter->get_tension()));
340                 if(iter->get_time_tension()!=0.0)
341                         waypoint_node->set_attribute("temporal-tension",strprintf("%f",iter->get_time_tension()));
342                 if(iter->get_continuity()!=0.0)
343                         waypoint_node->set_attribute("continuity",strprintf("%f",iter->get_continuity()));
344                 if(iter->get_bias()!=0.0)
345                         waypoint_node->set_attribute("bias",strprintf("%f",iter->get_bias()));
346
347         }
348
349         return root;
350 }
351
352 xmlpp::Element* encode_composite(xmlpp::Element* root,ValueNode_Composite::ConstHandle value_node,Canvas::ConstHandle canvas=0)
353 {
354         assert(value_node);
355         root->set_name("composite");
356
357         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
358
359         int i;
360         for(i=0;i<value_node->link_count();i++)
361         {
362                 string name(strprintf("c%d",i+1));
363                 assert(value_node->get_link(i));
364                 if(value_node->get_link(i)->is_exported())
365                         root->set_attribute(name,value_node->get_link(i)->get_relative_id(canvas));
366                 else
367                         encode_value_node(root->add_child(name)->add_child("value_node"),value_node->get_link(i).constant(),canvas);
368         }
369
370         return root;
371 }
372
373 xmlpp::Element* encode_subtract(xmlpp::Element* root,ValueNode_Subtract::ConstHandle value_node,Canvas::ConstHandle canvas=0)
374 {
375         assert(value_node);
376         root->set_name("subtract");
377
378         ValueNode::ConstHandle lhs=value_node->get_lhs();
379         ValueNode::ConstHandle rhs=value_node->get_rhs();
380         ValueNode::ConstHandle scalar=value_node->get_scalar();
381
382         assert(lhs);
383         assert(rhs);
384
385         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
386
387         if(lhs==rhs)
388                 warning("LHS is equal to RHS, this <subtract> will always be zero!");
389
390         //if(value_node->get_scalar()!=1)
391         //      root->set_attribute("scalar",strprintf(VECTOR_VALUE_TYPE_FORMAT,value_node->get_scalar()));
392
393         if(!scalar->get_id().empty())
394                 root->set_attribute("scalar",scalar->get_relative_id(canvas));
395         else
396                 encode_value_node(root->add_child("scalar")->add_child("value_node"),scalar,canvas);
397
398         if(!lhs->get_id().empty())
399                 root->set_attribute("lhs",lhs->get_relative_id(canvas));
400         else
401                 encode_value_node(root->add_child("lhs")->add_child("value_node"),lhs,canvas);
402
403         if(!rhs->get_id().empty())
404                 root->set_attribute("rhs",rhs->get_relative_id(canvas));
405         else
406                 encode_value_node(root->add_child("rhs")->add_child("value_node"),rhs,canvas);
407
408         return root;
409 }
410
411 xmlpp::Element* encode_dynamic_list(xmlpp::Element* root,ValueNode_DynamicList::ConstHandle value_node,Canvas::ConstHandle canvas=0)
412 {
413         assert(value_node);
414         const float fps(canvas?canvas->rend_desc().get_frame_rate():0);
415
416         root->set_name(value_node->get_name());
417
418         root->set_attribute("type",ValueBase::type_name(value_node->get_contained_type()));
419
420         vector<ValueNode_DynamicList::ListEntry>::const_iterator iter;
421
422         ValueNode_BLine::ConstHandle bline_value_node(ValueNode_BLine::ConstHandle::cast_dynamic(value_node));
423
424         if(bline_value_node)
425         {
426                 if(bline_value_node->get_loop())
427                         root->set_attribute("loop","true");
428                 else
429                         root->set_attribute("loop","false");
430         }
431
432         for(iter=value_node->list.begin();iter!=value_node->list.end();++iter)
433         {
434                 xmlpp::Element  *entry_node=root->add_child("entry");
435                 assert(iter->value_node);
436                 if(!iter->value_node->get_id().empty())
437                         entry_node->set_attribute("use",iter->value_node->get_relative_id(canvas));
438                 else
439                         encode_value_node(entry_node->add_child("value_node"),iter->value_node,canvas);
440
441                 // process waypoints
442                 {
443                         typedef synfig::ValueNode_DynamicList::ListEntry::Activepoint Activepoint;
444                         typedef synfig::ValueNode_DynamicList::ListEntry::ActivepointList ActivepointList;
445                         String begin_sequence;
446                         String end_sequence;
447
448                         const ActivepointList& timing_info(iter->timing_info);
449                         ActivepointList::const_iterator entry_iter;
450
451                         for(entry_iter=timing_info.begin();entry_iter!=timing_info.end();++entry_iter)
452                                 if(entry_iter->state==true)
453                                 {
454                                         if(entry_iter->priority)
455                                         {
456                                                 printf("begin priority is %d\n", entry_iter->priority);
457                                                 begin_sequence+=strprintf("p%d ",entry_iter->priority);
458                                         }
459                                         begin_sequence+=entry_iter->time.get_string(fps)+", ";
460                                 }
461                                 else
462                                 {
463                                         if(entry_iter->priority)
464                                         {
465                                                 printf("end priority is %d\n", entry_iter->priority);
466                                                 end_sequence+=strprintf("p%d ",entry_iter->priority);
467                                         }
468                                         end_sequence+=entry_iter->time.get_string(fps)+", ";
469                                 }
470
471                         // If this is just a plane-jane vanilla entry,
472                         // then don't bother with begins and ends
473                         if(end_sequence.empty() && begin_sequence=="SOT, ")
474                                 begin_sequence.clear();
475
476                         if(!begin_sequence.empty())
477                         {
478                                 // Remove the last ", " stuff
479                                 begin_sequence=String(begin_sequence.begin(),begin_sequence.end()-2);
480                                 // Add the attribute
481                                 entry_node->set_attribute("on",begin_sequence);
482                         }
483
484                         if(!end_sequence.empty())
485                         {
486                                 // Remove the last ", " stuff
487                                 end_sequence=String(end_sequence.begin(),end_sequence.end()-2);
488                                 // Add the attribute
489                                 entry_node->set_attribute("off",end_sequence);
490                         }
491                 }
492         }
493
494         return root;
495 }
496
497 // Generic linkable data node entry
498 xmlpp::Element* encode_linkable_value_node(xmlpp::Element* root,LinkableValueNode::ConstHandle value_node,Canvas::ConstHandle canvas=0)
499 {
500         assert(value_node);
501         root->set_name(value_node->get_name());
502
503         root->set_attribute("type",ValueBase::type_name(value_node->get_type()));
504
505         int i;
506         for(i=0;i<value_node->link_count();i++)
507         {
508                 ValueNode::ConstHandle link=value_node->get_link(i).constant();
509                 if(!link)
510                         throw runtime_error("Bad link");
511                 if(link->is_exported())
512                         root->set_attribute(value_node->link_name(i),link->get_relative_id(canvas));
513                 else
514                         encode_value_node(root->add_child(value_node->link_name(i))->add_child("value_node"),link,canvas);
515         }
516
517         return root;
518 }
519
520 xmlpp::Element* encode_value_node(xmlpp::Element* root,ValueNode::ConstHandle value_node,Canvas::ConstHandle canvas)
521 {
522         assert(value_node);
523
524         if(ValueNode_Animated::ConstHandle::cast_dynamic(value_node))
525                 encode_animated(root,ValueNode_Animated::ConstHandle::cast_dynamic(value_node),canvas);
526         else
527         if(ValueNode_Composite::ConstHandle::cast_dynamic(value_node))
528                 encode_composite(root,ValueNode_Composite::ConstHandle::cast_dynamic(value_node),canvas);
529         else
530         if(ValueNode_Subtract::ConstHandle::cast_dynamic(value_node))
531                 encode_subtract(root,ValueNode_Subtract::ConstHandle::cast_dynamic(value_node),canvas);
532         else
533         if(ValueNode_DynamicList::ConstHandle::cast_dynamic(value_node))
534                 encode_dynamic_list(root,ValueNode_DynamicList::ConstHandle::cast_dynamic(value_node),canvas);
535         else if(ValueNode_Const::ConstHandle::cast_dynamic(value_node))
536         {
537                 encode_value(root,ValueNode_Const::ConstHandle::cast_dynamic(value_node)->get_value(),canvas);
538         }
539         else
540         if(LinkableValueNode::ConstHandle::cast_dynamic(value_node))
541                 encode_linkable_value_node(root,LinkableValueNode::ConstHandle::cast_dynamic(value_node),canvas);
542         else
543         {
544                 error(_("Unknown ValueNode Type (%s), cannot create an XML representation"),value_node->get_local_name().c_str());
545                 root->set_name("nil");
546         }
547
548         assert(root);
549
550         if(!value_node->get_id().empty())
551                 root->set_attribute("id",value_node->get_id());
552
553         if(value_node->rcount()>1)
554                 root->set_attribute("guid",(value_node->get_guid()^canvas->get_root()->get_guid()).get_string());
555
556         return root;
557 }
558
559 xmlpp::Element* encode_layer(xmlpp::Element* root,Layer::ConstHandle layer)
560 {
561         root->set_name("layer");
562
563         root->set_attribute("type",layer->get_name());
564         root->set_attribute("active",layer->active()?"true":"false");
565
566         if(!layer->get_version().empty())
567                 root->set_attribute("version",layer->get_version());
568         if(!layer->get_description().empty())
569                 root->set_attribute("desc",layer->get_description());
570         if(!layer->get_group().empty())
571                 root->set_attribute("group",layer->get_group());
572
573         Layer::Vocab vocab(layer->get_param_vocab());
574         Layer::Vocab::const_iterator iter;
575
576         const Layer::DynamicParamList &dynamic_param_list=layer->dynamic_param_list();
577
578         for(iter=vocab.begin();iter!=vocab.end();++iter)
579         {
580                 // Handle dynamic parameters
581                 if(dynamic_param_list.count(iter->get_name()))
582                 {
583                         xmlpp::Element *node=root->add_child("param");
584                         node->set_attribute("name",iter->get_name());
585
586                         handle<const ValueNode> value_node=dynamic_param_list.find(iter->get_name())->second;
587
588                         // If the valuenode has no ID, then it must be defined in-place
589                         if(value_node->get_id().empty())
590                         {
591                                 encode_value_node(node->add_child("value_node"),value_node,layer->get_canvas().constant());
592                         }
593                         else
594                         {
595                                 node->set_attribute("use",value_node->get_relative_id(layer->get_canvas()));
596                         }
597                 }
598                 else  // Handle normal parameters
599                 if(iter->get_critical())
600                 {
601                         ValueBase value=layer->get_param(iter->get_name());
602                         if(!value.is_valid())
603                         {
604                                 error("Layer doesn't know its own vocabulary -- "+iter->get_name());
605                                 continue;
606                         }
607
608                         if(value.get_type()==ValueBase::TYPE_CANVAS)
609                         {
610                                 // the ->is_inline() below was crashing if the canvas
611                                 // contained a PasteCanvas with the default <No Image
612                                 // Selected> Canvas setting;  this avoids the crash
613                                 if (!value.get(Canvas::LooseHandle()))
614                                         continue;
615
616                                 if (!value.get(Canvas::LooseHandle())->is_inline())
617                                 {
618                                         Canvas::Handle child(value.get(Canvas::LooseHandle()));
619
620                                         if(!value.get(Canvas::Handle()))
621                                                 continue;
622                                         xmlpp::Element *node=root->add_child("param");
623                                         node->set_attribute("name",iter->get_name());
624                                         node->set_attribute("use",child->get_relative_id(layer->get_canvas()));
625                                         continue;
626                                 }
627                         }
628                         xmlpp::Element *node=root->add_child("param");
629                         node->set_attribute("name",iter->get_name());
630
631                         encode_value(node->add_child("value"),value,layer->get_canvas().constant());
632                 }
633         }
634
635
636         return root;
637 }
638
639 xmlpp::Element* encode_canvas(xmlpp::Element* root,Canvas::ConstHandle canvas)
640 {
641         assert(canvas);
642         const RendDesc &rend_desc=canvas->rend_desc();
643         root->set_name("canvas");
644
645         if(canvas->is_root())
646                 root->set_attribute("version","0.1");
647
648         if(!canvas->get_id().empty() && !canvas->is_root() && !canvas->is_inline())
649                 root->set_attribute("id",canvas->get_id());
650
651         if(!canvas->parent() || canvas->parent()->rend_desc().get_w()!=canvas->rend_desc().get_w())
652                 root->set_attribute("width",strprintf("%d",rend_desc.get_w()));
653
654         if(!canvas->parent() || canvas->parent()->rend_desc().get_h()!=canvas->rend_desc().get_h())
655                 root->set_attribute("height",strprintf("%d",rend_desc.get_h()));
656
657         if(!canvas->parent() || canvas->parent()->rend_desc().get_x_res()!=canvas->rend_desc().get_x_res())
658                 root->set_attribute("xres",strprintf("%f",rend_desc.get_x_res()));
659
660         if(!canvas->parent() || canvas->parent()->rend_desc().get_y_res()!=canvas->rend_desc().get_y_res())
661                 root->set_attribute("yres",strprintf("%f",rend_desc.get_y_res()));
662
663
664         if(!canvas->parent() ||
665                 canvas->parent()->rend_desc().get_tl()!=canvas->rend_desc().get_tl() ||
666                 canvas->parent()->rend_desc().get_br()!=canvas->rend_desc().get_br())
667         root->set_attribute("view-box",strprintf(VIEW_BOX_FORMAT,
668                 rend_desc.get_tl()[0],
669                 rend_desc.get_tl()[1],
670                 rend_desc.get_br()[0],
671                 rend_desc.get_br()[1])
672         );
673
674         if(!canvas->parent() || canvas->parent()->rend_desc().get_antialias()!=canvas->rend_desc().get_antialias())
675                 root->set_attribute("antialias",strprintf("%d",rend_desc.get_antialias()));
676
677         if(!canvas->parent())
678                 root->set_attribute("fps",strprintf(TIME_TYPE_FORMAT,rend_desc.get_frame_rate()));
679
680         if(!canvas->parent() || canvas->parent()->rend_desc().get_time_start()!=canvas->rend_desc().get_time_start())
681                 root->set_attribute("begin-time",rend_desc.get_time_start().get_string(rend_desc.get_frame_rate()));
682
683         if(!canvas->parent() || canvas->parent()->rend_desc().get_time_end()!=canvas->rend_desc().get_time_end())
684                 root->set_attribute("end-time",rend_desc.get_time_end().get_string(rend_desc.get_frame_rate()));
685
686         if(!canvas->is_inline())
687         {
688                 root->set_attribute("bgcolor",strprintf(VIEW_BOX_FORMAT,
689                         rend_desc.get_bg_color().get_r(),
690                         rend_desc.get_bg_color().get_g(),
691                         rend_desc.get_bg_color().get_b(),
692                         rend_desc.get_bg_color().get_a())
693                 );
694
695                 if(!canvas->get_name().empty())
696                         root->add_child("name")->set_child_text(canvas->get_name());
697                 if(!canvas->get_description().empty())
698                         root->add_child("desc")->set_child_text(canvas->get_description());
699                 if(!canvas->get_author().empty())
700                         root->add_child("author")->set_child_text(canvas->get_description());
701
702                 std::list<String> meta_keys(canvas->get_meta_data_keys());
703                 while(!meta_keys.empty())
704                 {
705                         xmlpp::Element* meta_element(root->add_child("meta"));
706                         meta_element->set_attribute("name",meta_keys.front());
707                         meta_element->set_attribute("content",canvas->get_meta_data(meta_keys.front()));
708                         meta_keys.pop_front();
709                 }
710                 for(KeyframeList::const_iterator iter=canvas->keyframe_list().begin();iter!=canvas->keyframe_list().end();++iter)
711                         encode_keyframe(root->add_child("keyframe"),*iter,canvas->rend_desc().get_frame_rate());
712         }
713
714         // Output the <defs> section
715         if(!canvas->is_inline() && !canvas->value_node_list().empty() || !canvas->children().empty())
716         {
717                 xmlpp::Element *node=root->add_child("defs");
718                 const ValueNodeList &value_node_list(canvas->value_node_list());
719
720                 for(ValueNodeList::const_iterator iter=value_node_list.begin();iter!=value_node_list.end();++iter)
721                 {
722                         // If the value_node is a constant, then use the shorthand
723                         if(handle<ValueNode_Const>::cast_dynamic(*iter))
724                         {
725                                 ValueNode_Const::Handle value_node(ValueNode_Const::Handle::cast_dynamic(*iter));
726                                 reinterpret_cast<xmlpp::Element*>(encode_value(node->add_child("value"),value_node->get_value()))->set_attribute("id",value_node->get_id());
727                                 continue;
728                         }
729                         encode_value_node(node->add_child("value_node"),*iter,canvas);
730                         // writeme
731                 }
732
733                 for(Canvas::Children::const_iterator iter=canvas->children().begin();iter!=canvas->children().end();++iter)
734                 {
735                         encode_canvas(node->add_child("canvas"),*iter);
736                 }
737         }
738
739         Canvas::const_reverse_iterator iter;
740
741         for(iter=canvas->rbegin();iter!=canvas->rend();++iter)
742                 encode_layer(root->add_child("layer"),*iter);
743
744         return root;
745 }
746
747 bool
748 synfig::save_canvas(const String &filename, Canvas::ConstHandle canvas)
749 {
750     ChangeLocale change_locale(LC_NUMERIC, "C");
751
752         synfig::String tmp_filename(filename+".TMP");
753
754         if (String(filename.begin() + filename.find_last_of('.')+1, filename.end()) == "sifz")
755                 xmlSetCompressMode(9);
756         else
757                 xmlSetCompressMode(0);
758
759         try
760         {
761                 assert(canvas);
762                 xmlpp::Document document;
763
764                 encode_canvas(document.create_root_node("canvas"),canvas);
765
766                 document.write_to_file_formatted(tmp_filename);
767         }
768         catch(...) { synfig::error("synfig::save_canvas(): Caught unknown exception"); return false; }
769
770
771 #ifdef _WIN32
772         // On Win32 platforms, rename() has bad behavior. work around it.
773         char old_file[80]="sif.XXXXXXXX";
774         mktemp(old_file);
775         rename(filename.c_str(),old_file);
776         if(rename(tmp_filename.c_str(),filename.c_str())!=0)
777         {
778                 rename(old_file,tmp_filename.c_str());
779                 synfig::error("synfig::save_canvas(): Unable to rename file to correct filename, errno=%d",errno);
780                 return false;
781         }
782         remove(old_file);
783 #else
784         if(rename(tmp_filename.c_str(),filename.c_str())!=0)
785         {
786                 synfig::error("synfig::save_canvas(): Unable to rename file to correct filename, errno=%d",errno);
787                 return false;
788         }
789 #endif
790
791         return true;
792 }
793
794 String
795 synfig::canvas_to_string(Canvas::ConstHandle canvas)
796 {
797     ChangeLocale change_locale(LC_NUMERIC, "C");
798         assert(canvas);
799
800         xmlpp::Document document;
801
802         encode_canvas(document.create_root_node("canvas"),canvas);
803
804         return document.write_to_string_formatted();
805 }