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