more updates
[synfig.git] / synfig-core / trunk / src / synfig / canvas.cpp
1 /* === S I N F G =========================================================== */
2 /*!     \file canvas.cpp
3 **      \brief Canvas Class Member Definitions
4 **
5 **      $Id: canvas.cpp,v 1.1.1.1 2005/01/04 01:23:14 darco Exp $
6 **
7 **      \legal
8 **      Copyright (c) 2002 Robert B. Quattlebaum Jr.
9 **
10 **      This software and associated documentation
11 **      are CONFIDENTIAL and PROPRIETARY property of
12 **      the above-mentioned copyright holder.
13 **
14 **      You may not copy, print, publish, or in any
15 **      other way distribute this software without
16 **      a prior written agreement with
17 **      the copyright holder.
18 **      \endlegal
19 */
20 /* ========================================================================= */
21
22 /* === H E A D E R S ======================================================= */
23
24 #define SINFG_NO_ANGLE
25
26 #ifdef USING_PCH
27 #       include "pch.h"
28 #else
29 #ifdef HAVE_CONFIG_H
30 #       include <config.h>
31 #endif
32
33 #include "layer.h"
34 #include "canvas.h"
35 #include <cassert>
36 #include "exception.h"
37 #include "time.h"
38 #include "context.h"
39 #include "layer_pastecanvas.h"
40 #include <sigc++/bind.h>
41
42 #endif
43
44 using namespace sinfg;
45 using namespace etl;
46 using namespace std;
47
48 namespace sinfg { extern Canvas::Handle open_canvas(const String &filename); };
49
50 /* === M A C R O S ========================================================= */
51
52 struct _CanvasCounter
53 {
54         static int counter;
55         ~_CanvasCounter()
56         {
57                 if(counter)
58                         sinfg::error("%d canvases not yet deleted!",counter);
59         }
60 } _canvas_counter;
61
62 int _CanvasCounter::counter(0);
63
64 /* === G L O B A L S ======================================================= */
65
66 /* === P R O C E D U R E S ================================================= */
67
68 /* === M E T H O D S ======================================================= */
69
70 Canvas::Canvas(const string &id):
71         id_                     (id),
72         cur_time_       (0),
73         is_inline_      (false),
74         is_dirty_       (true),
75         op_flag_        (false)
76 {
77         _CanvasCounter::counter++;
78         clear();
79 }
80
81 void
82 Canvas::on_changed()
83 {
84         is_dirty_=true;
85         Node::on_changed();
86 }
87
88 Canvas::~Canvas()
89 {
90         //if(is_inline() && parent_) assert(0);
91         _CanvasCounter::counter--;
92         //DEBUGPOINT();
93         clear();
94         begin_delete();
95 }
96
97 Canvas::iterator
98 Canvas::end()
99 {
100         return CanvasBase::end()-1;
101 }
102
103 Canvas::const_iterator
104 Canvas::end()const
105 {
106         return CanvasBase::end()-1;
107 }
108
109 Canvas::reverse_iterator
110 Canvas::rbegin()
111 {
112         return CanvasBase::rbegin()+1;
113 }
114
115 Canvas::const_reverse_iterator
116 Canvas::rbegin()const
117 {
118         return CanvasBase::rbegin()+1;
119 }
120
121 int
122 Canvas::size()const
123 {
124         return CanvasBase::size()-1;
125 }
126
127 void
128 Canvas::clear()
129 {
130         while(!empty())
131         {
132                 Layer::Handle layer(front());
133                 //if(layer->count()>2)sinfg::info("before layer->count()=%d",layer->count());
134                                 
135                 erase(begin());
136                 //if(layer->count()>1)sinfg::info("after layer->count()=%d",layer->count());
137         }
138         //CanvasBase::clear();
139
140         // We need to keep a blank handle at the
141         // end of the image list, and acts at
142         // the bottom. Without it, the layers
143         // would just continue going when polled
144         // for a color.
145         CanvasBase::push_back(Layer::Handle());
146         
147         changed();
148 }
149
150 bool
151 Canvas::empty()const
152 {
153         return CanvasBase::size()<=1;
154 }
155
156 Layer::Handle &
157 Canvas::back()
158 {
159         return *(CanvasBase::end()-1);
160 }
161
162 const Layer::Handle &
163 Canvas::back()const
164 {
165         return *(CanvasBase::end()-1);
166 }
167
168 Context
169 Canvas::get_context()const
170 {
171         return begin();
172 }
173
174 const ValueNodeList &
175 Canvas::value_node_list()const
176 {
177         if(is_inline() && parent_)
178                 return parent_->value_node_list();
179         return value_node_list_;
180 }
181
182 KeyframeList &
183 Canvas::keyframe_list()
184 {
185         if(is_inline() && parent_)
186                 return parent_->keyframe_list();
187         return keyframe_list_;
188 }
189
190 const KeyframeList &
191 Canvas::keyframe_list()const
192 {
193         if(is_inline() && parent_)
194                 return parent_->keyframe_list();
195         return keyframe_list_;
196 }
197
198 etl::handle<Layer>
199 Canvas::find_layer(const Point &pos)
200 {
201         return get_context().hit_check(pos);
202 }
203
204 static bool
205 valid_id(const String &x)
206 {
207         static const char bad_chars[]=" :#@$^&()*";
208         unsigned int i;
209         
210         if(!x.empty() && x[0]>='0' && x[0]<='9')
211                 return false;
212         
213         for(i=0;i<sizeof(bad_chars);i++)
214                 if(x.find_first_of(bad_chars[i])!=string::npos)
215                         return false;
216
217         return true;
218 }
219
220 void
221 Canvas::set_id(const String &x)
222 {
223         if(is_inline() && parent_)
224                 throw runtime_error("Inline Canvas cannot have an ID");
225         
226         if(!valid_id(x))
227                 throw runtime_error("Invalid ID");
228         id_=x;
229         signal_id_changed_();
230 }
231
232 void
233 Canvas::set_name(const String &x)
234 {
235         name_=x;
236         signal_meta_data_changed()("name");
237         signal_meta_data_changed("name")();
238 }
239
240 void
241 Canvas::set_author(const String &x)
242 {
243         author_=x;
244         signal_meta_data_changed()("author");
245         signal_meta_data_changed("author")();
246 }
247
248 void
249 Canvas::set_description(const String &x)
250 {
251         description_=x;
252         signal_meta_data_changed()("description");
253         signal_meta_data_changed("description")();
254 }
255
256 void
257 Canvas::set_time(Time t)const
258 {       
259         if(is_dirty_ || !get_time().is_equal(t))
260         {       
261 #if 0
262                 if(is_root())
263                 {
264                         sinfg::info("is_dirty_=%d",is_dirty_);
265                         sinfg::info("get_time()=%f",(float)get_time());
266                         sinfg::info("t=%f",(float)t);
267                 }
268 #endif
269
270                 // ...questionable
271                 const_cast<Canvas&>(*this).cur_time_=t;
272                 
273                 is_dirty_=false;
274                 get_context().set_time(t);
275         }
276         is_dirty_=false;
277 }
278
279 Canvas::LooseHandle
280 Canvas::get_root()const
281 {
282         return parent_?parent_->get_root().get():const_cast<sinfg::Canvas *>(this);
283 }
284
285 int
286 Canvas::get_depth(etl::handle<Layer> layer)const
287 {
288         const_iterator iter;
289         int i(0);
290         for(iter=begin();iter!=end();++iter,i++)
291         {
292                 if(layer==*iter)
293                         return i;
294         }
295         return -1;
296 }
297
298 String
299 Canvas::get_relative_id(etl::loose_handle<const Canvas> x)const
300 {
301         if(x->get_root()==this)
302                 return ":";
303         if(is_inline() && parent_)
304                 return parent_->_get_relative_id(x);
305         return _get_relative_id(x);
306 }
307
308 String
309 Canvas::_get_relative_id(etl::loose_handle<const Canvas> x)const
310 {
311         if(is_inline() && parent_)
312                 return parent_->_get_relative_id(x);
313
314         if(x.get()==this)
315                 return String();
316         
317         if(parent()==x.get())
318                 return get_id();
319         
320         String id;
321         
322         const Canvas* canvas=this;
323         
324         for(;!canvas->is_root();canvas=canvas->parent().get())
325                 id=':'+canvas->get_id()+id;
326         
327         if(x && get_root()!=x->get_root())
328         {
329                 //String file_name=get_file_name();
330                 //String file_path=x->get_file_path();
331                 
332                 String file_name;
333                 if(is_absolute_path(get_file_name()))
334                         file_name=etl::relative_path(x->get_file_path(),get_file_name());
335                 else
336                         file_name=get_file_name();
337                 
338                 // If the path of X is inside of file_name,
339                 // then remove it.
340                 //if(file_name.size()>file_path.size())
341                 //      if(file_path==String(file_name,0,file_path.size()))
342                 //              file_name.erase(0,file_path.size()+1);
343                         
344                 id=file_name+'#'+id;
345         }
346
347         return id;
348 }
349
350
351 ValueNode::Handle
352 Canvas::find_value_node(const String &id)
353 {
354         return
355                 ValueNode::Handle::cast_const(
356                         const_cast<const Canvas*>(this)->find_value_node(id)
357                 );
358 }
359
360 ValueNode::ConstHandle
361 Canvas::find_value_node(const String &id)const
362 {
363         if(is_inline() && parent_)
364                 return parent_->find_value_node(id);
365                 
366         if(id.empty())
367                 throw Exception::IDNotFound("Empty ID");
368
369         // If we do not have any resolution, then we assume that the
370         // request is for this immediate canvas
371         if(id.find_first_of(':')==string::npos && id.find_first_of('#')==string::npos)
372                 return value_node_list_.find(id);
373
374         String canvas_id(id,0,id.rfind(':'));
375         String value_node_id(id,id.rfind(':')+1);
376         if(canvas_id.empty())
377                 canvas_id=':';
378         //sinfg::warning("constfind:value_node_id: "+value_node_id);
379         //sinfg::warning("constfind:canvas_id: "+canvas_id);
380
381         return find_canvas(canvas_id)->value_node_list_.find(value_node_id);
382 }
383
384 ValueNode::Handle
385 Canvas::surefind_value_node(const String &id)
386 {
387         if(is_inline() && parent_)
388                 return parent_->surefind_value_node(id);
389
390         if(id.empty())
391                 throw Exception::IDNotFound("Empty ID");
392
393         // If we do not have any resolution, then we assume that the
394         // request is for this immediate canvas
395         if(id.find_first_of(':')==string::npos && id.find_first_of('#')==string::npos)
396                 return value_node_list_.surefind(id);
397
398         String canvas_id(id,0,id.rfind(':'));
399         String value_node_id(id,id.rfind(':')+1);
400         if(canvas_id.empty())
401                 canvas_id=':';
402                 
403         return surefind_canvas(canvas_id)->value_node_list_.surefind(value_node_id);
404 }
405
406 void
407 Canvas::add_value_node(ValueNode::Handle x, const String &id)
408 {
409         if(is_inline() && parent_)
410                 return parent_->add_value_node(x,id);
411 //              throw runtime_error("You cannot add a ValueNode to an inline Canvas");
412
413         //DEBUGPOINT();
414         if(x->is_exported())
415                 throw runtime_error("ValueNode is already exported");
416
417         if(id.empty())
418                 throw Exception::BadLinkName("Empty ID");
419
420         if(id.find_first_of(':',0)!=string::npos)
421                 throw Exception::BadLinkName("Bad character");
422         
423         try
424         {
425                 //DEBUGPOINT();
426                 if(PlaceholderValueNode::Handle::cast_dynamic(value_node_list_.find(id)))
427                         throw Exception::IDNotFound("add_value_node()");
428                 
429                 //DEBUGPOINT();
430                 throw Exception::IDAlreadyExists(id);
431         }
432         catch(Exception::IDNotFound)
433         {
434                 //DEBUGPOINT();
435                 x->set_id(id);
436         
437                 x->set_parent_canvas(this);
438         
439                 if(!value_node_list_.add(x))
440                 {
441                         sinfg::error("Unable to add ValueNode");
442                         throw std::runtime_error("Unable to add ValueNode");
443                 }
444                 //DEBUGPOINT();
445                 
446                 return;
447         }
448 }
449
450 /*
451 void
452 Canvas::rename_value_node(ValueNode::Handle x, const String &id)
453 {
454         if(id.empty())
455                 throw Exception::BadLinkName("Empty ID");
456
457         if(id.find_first_of(": ",0)!=string::npos)
458                 throw Exception::BadLinkName("Bad character");
459
460         try
461         {
462                 if(PlaceholderValueNode::Handle::cast_dynamic(value_node_list_.find(id)))
463                         throw Exception::IDNotFound("rename_value_node");
464                 throw Exception::IDAlreadyExists(id);
465         }
466         catch(Exception::IDNotFound)
467         {
468                 x->set_id(id);  
469
470                 return;
471         }
472 }
473 */
474
475 void
476 Canvas::remove_value_node(ValueNode::Handle x)
477 {
478         if(is_inline() && parent_)
479                 return parent_->remove_value_node(x);
480 //              throw Exception::IDNotFound("Canvas::remove_value_node() was called from an inline canvas");
481                 
482         if(!x)
483                 throw Exception::IDNotFound("Canvas::remove_value_node() was passed empty handle");
484         
485         if(!value_node_list_.erase(x))
486                 throw Exception::IDNotFound("Canvas::remove_value_node(): ValueNode was not found inside of this canvas");
487
488         //x->set_parent_canvas(0);
489         
490         x->set_id("");
491 }
492
493
494 etl::handle<Canvas>
495 Canvas::surefind_canvas(const String &id)
496 {
497         if(is_inline() && parent_)
498                 return parent_->surefind_canvas(id);
499         
500         if(id.empty())
501                 return this;
502         
503         // If the ID contains a "#" character, then a filename is
504         // expected on the left side. 
505         if(id.find_first_of('#')!=string::npos)
506         {
507                 // If '#' is the first character, remove it
508                 // and attempt to parse the ID again.
509                 if(id[0]=='#')
510                         return surefind_canvas(String(id,1));
511                 
512                 //! \todo This needs alot more optimization
513                 String file_name(id,0,id.find_first_of('#'));
514                 String external_id(id,id.find_first_of('#')+1);
515                 
516                 Canvas::Handle external_canvas;
517                 
518                 // If the composition is already open, then use it.
519                 if(externals_.count(file_name))
520                         external_canvas=externals_[file_name];
521                 else
522                 {
523                         if(is_absolute_path(file_name))
524                                 external_canvas=open_canvas(file_name);
525                         else
526                                 external_canvas=open_canvas(get_file_path()+'/'+file_name);
527
528                         if(!external_canvas)
529                                 throw Exception::FileNotFound(file_name);
530                         externals_[file_name]=external_canvas;
531                 }
532                 
533                 return Handle::cast_const(external_canvas.constant()->find_canvas(external_id));
534         }
535         
536         // If we do not have any resolution, then we assume that the
537         // request is for this immediate canvas
538         if(id.find_first_of(':')==string::npos)
539         {
540                 Children::iterator iter;
541         
542                 // Search for the image in the image list,
543                 // and return it if it is found
544                 for(iter=children().begin();iter!=children().end();iter++)
545                         if(id==(*iter)->get_id())
546                                 return *iter;
547                         
548                 // Create a new canvas and return it
549                 //sinfg::warning("Implicitly creating canvas named "+id);
550                 return new_child_canvas(id);
551         }
552         
553         // If the first character is the seperator, then 
554         // this references the root canvas.
555         if(id[0]==':')
556                 return get_root()->surefind_canvas(string(id,1));
557
558         // Now we know that the requested Canvas is in a child
559         // of this canvas. We have to find that canvas and 
560         // call "find_canvas" on it, and return the result.
561         
562         String canvas_name=string(id,0,id.find_first_of(':'));
563         
564         Canvas::Handle child_canvas=surefind_canvas(canvas_name);
565
566         return child_canvas->surefind_canvas(string(id,id.find_first_of(':')+1));
567 }
568
569 Canvas::Handle
570 Canvas::find_canvas(const String &id)
571 {
572         return
573                 Canvas::Handle::cast_const(
574                         const_cast<const Canvas*>(this)->find_canvas(id)
575                 );
576 }
577
578 Canvas::ConstHandle
579 Canvas::find_canvas(const String &id)const
580 {
581         if(is_inline() && parent_)return parent_->find_canvas(id);
582
583         if(id.empty())
584                 return this;
585
586         // If the ID contains a "#" character, then a filename is
587         // expected on the left side. 
588         if(id.find_first_of('#')!=string::npos)
589         {
590                 // If '#' is the first character, remove it
591                 // and attempt to parse the ID again.
592                 if(id[0]=='#')
593                         return find_canvas(String(id,1));
594                 
595                 //! \todo This needs alot more optimization
596                 String file_name(id,0,id.find_first_of('#'));
597                 String external_id(id,id.find_first_of('#')+1);
598                 
599                 Canvas::Handle external_canvas;
600                 
601                 // If the composition is already open, then use it.
602                 if(externals_.count(file_name))
603                         external_canvas=externals_[file_name];
604                 else
605                 {
606                         if(is_absolute_path(file_name))
607                                 external_canvas=open_canvas(file_name);
608                         else
609                                 external_canvas=open_canvas(get_file_path()+'/'+file_name);
610
611                         if(!external_canvas)
612                                 throw Exception::FileNotFound(file_name);
613                         externals_[file_name]=external_canvas;
614                 }
615                 
616                 return Handle::cast_const(external_canvas.constant()->find_canvas(external_id));
617         }
618         
619         // If we do not have any resolution, then we assume that the
620         // request is for this immediate canvas
621         if(id.find_first_of(':')==string::npos)
622         {
623                 Children::const_iterator iter;
624         
625                 // Search for the image in the image list,
626                 // and return it if it is found
627                 for(iter=children().begin();iter!=children().end();iter++)
628                         if(id==(*iter)->get_id())
629                                 return *iter;
630                         
631                 throw Exception::IDNotFound("Child Canvas in Parent Canvas: (child)"+id);
632         }
633         
634         // If the first character is the seperator, then 
635         // this references the root canvas.
636         if(id.find_first_of(':')==0)
637                 return get_root()->find_canvas(string(id,1));
638
639         // Now we know that the requested Canvas is in a child
640         // of this canvas. We have to find that canvas and 
641         // call "find_canvas" on it, and return the result.
642         
643         String canvas_name=string(id,0,id.find_first_of(':'));
644         
645         Canvas::ConstHandle child_canvas=find_canvas(canvas_name);
646
647         return child_canvas->find_canvas(string(id,id.find_first_of(':')+1));
648 }
649
650
651 Canvas::Handle
652 Canvas::create()
653 {
654         return new Canvas("Untitled");
655 }
656
657 void
658 Canvas::push_back(etl::handle<Layer> x)
659 {
660 //      DEBUGPOINT();
661 //      int i(x->count());
662         insert(end(),x);
663         //if(x->count()!=i+1)sinfg::info("push_back before %d, after %d",i,x->count());
664 }
665
666 void
667 Canvas::push_front(etl::handle<Layer> x)
668 {
669 //      DEBUGPOINT();
670 //      int i(x->count());
671         insert(begin(),x);
672         //if(x->count()!=i+1)sinfg::error("push_front before %d, after %d",i,x->count());
673 }
674
675 void
676 Canvas::insert(iterator iter,etl::handle<Layer> x)
677 {
678 //      int i(x->count());
679         CanvasBase::insert(iter,x);
680
681         /*if(x->count()!=i+1)
682         {
683                 sinfg::error(__FILE__":%d: Canvas::insert(): ***FAILURE*** before %d, after %d",__LINE__,i,x->count());
684                 return;
685                 //throw runtime_error("Canvas Insertion Failed");
686         }*/
687
688         x->set_canvas(this);
689
690
691         add_child(x.get());
692
693         
694         LooseHandle correct_canvas(this);
695         //while(correct_canvas->is_inline())correct_canvas=correct_canvas->parent();
696         Layer::LooseHandle loose_layer(x);
697         
698         x->signal_added_to_group().connect(
699                 sigc::bind(
700                         sigc::mem_fun(
701                                 *correct_canvas,
702                                 &Canvas::add_group_pair
703                         ),
704                         loose_layer
705                 )
706         );
707         x->signal_removed_from_group().connect(
708                 sigc::bind(
709                         sigc::mem_fun(
710                                 *correct_canvas,
711                                 &Canvas::remove_group_pair
712                         ),
713                         loose_layer
714                 )
715         );
716
717
718         if(!x->get_group().empty())
719                 add_group_pair(x->get_group(),x);
720
721
722         changed();
723 }
724
725 void
726 Canvas::push_back_simple(etl::handle<Layer> x)
727 {
728         CanvasBase::insert(end(),x);
729         changed();
730 }
731
732 void
733 Canvas::erase(Canvas::iterator iter)
734 {
735         if(!(*iter)->get_group().empty())
736                 remove_group_pair((*iter)->get_group(),(*iter));
737         
738         // HACK: We really shouldn't be wiping
739         // out these signals entirely. We should
740         // only be removing the specific connections
741         // that we made. At the moment, I'm too
742         // lazy to add the code to keep track
743         // of those connections, and no one else
744         // is using these signals, so I'll just
745         // leave these next two lines like they
746         // are for now - darco 07-30-2004
747         (*iter)->signal_added_to_group().clear();
748         (*iter)->signal_removed_from_group().clear();
749
750         if(!op_flag_)remove_child(iter->get());
751                 
752         CanvasBase::erase(iter);
753         if(!op_flag_)changed();
754 }
755
756 Canvas::Handle
757 Canvas::clone(const GUID& deriv_guid)const
758 {
759         sinfg::String name;
760         if(is_inline())
761                 name="inline";
762         else
763         {
764                 name=get_id()+"_CLONE";
765                 
766                 throw runtime_error("Cloning of non-inline canvases is not yet suported");
767         }
768         
769         Handle canvas(new Canvas(name));
770         
771         if(is_inline())
772         {
773                 canvas->is_inline_=true;
774                 canvas->parent_=0;
775                 //canvas->set_inline(parent());
776         }
777
778         canvas->set_guid(get_guid()^deriv_guid);
779
780         const_iterator iter;
781         for(iter=begin();iter!=end();++iter)
782         {
783                 Layer::Handle layer((*iter)->clone(deriv_guid));
784                 if(layer)
785                 {
786                         assert(layer.count()==1);
787                         int presize(size());
788                         canvas->push_back(layer);
789                         if(!(layer.count()>1))
790                         {
791                                 sinfg::error("Canvas::clone(): Cloned layer insertion failure!");
792                                 sinfg::error("Canvas::clone(): \tlayer.count()=%d",layer.count());
793                                 sinfg::error("Canvas::clone(): \tlayer->get_name()=%s",layer->get_name().c_str());
794                                 sinfg::error("Canvas::clone(): \tbefore size()=%d",presize);
795                                 sinfg::error("Canvas::clone(): \tafter size()=%d",size());
796                         }
797                         assert(layer.count()>1);
798                 }
799                 else
800                 {
801                         sinfg::error("Unable to clone layer");
802                 }
803         }
804
805         canvas->signal_group_pair_removed().clear();
806         canvas->signal_group_pair_added().clear();
807
808         return canvas;
809 }
810
811 void
812 Canvas::set_inline(LooseHandle parent)
813 {
814         if(is_inline_ && parent_)
815         {
816                 
817         }
818         
819         id_="inline";
820         is_inline_=true;
821         parent_=parent;
822
823         // Have the parent inherit all of the group stuff
824
825         std::map<String,std::set<etl::handle<Layer> > >::const_iterator iter;
826
827         for(iter=group_db_.begin();iter!=group_db_.end();++iter)
828         {
829                 parent->group_db_[iter->first].insert(iter->second.begin(),iter->second.end());
830         }
831         
832         rend_desc()=parent->rend_desc();
833 }
834
835 Canvas::Handle
836 Canvas::create_inline(Handle parent)
837 {
838         assert(parent);
839         //if(parent->is_inline())
840         //      return create_inline(parent->parent());
841         
842         Handle canvas(new Canvas("inline"));
843         canvas->set_inline(parent);
844         return canvas;
845 }
846
847 Canvas::Handle
848 Canvas::new_child_canvas()
849 {
850         if(is_inline() && parent_)
851                 return parent_->new_child_canvas();
852 //              runtime_error("You cannot create a child Canvas in an inline Canvas");
853
854         // Create a new canvas
855         children().push_back(create());
856         Canvas::Handle canvas(children().back());
857
858         canvas->parent_=this;
859
860         canvas->rend_desc()=rend_desc();
861
862         return canvas;
863 }
864
865 Canvas::Handle
866 Canvas::new_child_canvas(const String &id)
867 {
868         if(is_inline() && parent_)
869                 return parent_->new_child_canvas(id);
870 //              runtime_error("You cannot create a child Canvas in an inline Canvas");
871
872         // Create a new canvas
873         children().push_back(create());
874         Canvas::Handle canvas(children().back());
875         
876         canvas->set_id(id);
877         canvas->parent_=this;
878         canvas->rend_desc()=rend_desc();
879
880         return canvas;
881 }
882
883 Canvas::Handle
884 Canvas::add_child_canvas(Canvas::Handle child_canvas, const sinfg::String& id)
885 {
886         if(is_inline() && parent_)
887                 return parent_->add_child_canvas(child_canvas,id);
888
889         if(child_canvas->parent() && !child_canvas->is_inline())
890                 throw std::runtime_error("Cannot add child canvas because it belongs to someone else!");
891         
892         if(!valid_id(id))
893                 throw runtime_error("Invalid ID");
894         
895         try
896         {
897                 find_canvas(id);
898                 throw Exception::IDAlreadyExists(id);
899         }
900         catch(Exception::IDNotFound)
901         {
902                 if(child_canvas->is_inline())
903                         child_canvas->is_inline_=false;
904                 child_canvas->id_=id;
905                 children().push_back(child_canvas);
906                 child_canvas->parent_=this;
907         }
908         
909         return child_canvas;
910 }
911
912 void
913 Canvas::remove_child_canvas(Canvas::Handle child_canvas)
914 {
915         if(is_inline() && parent_)
916                 return parent_->remove_child_canvas(child_canvas);
917         
918         if(child_canvas->parent_!=this)
919                 throw runtime_error("Given child does not belong to me");
920         
921         if(find(children().begin(),children().end(),child_canvas)==children().end())
922                 throw Exception::IDNotFound(child_canvas->get_id());
923         
924         children().remove(child_canvas);
925
926         child_canvas->parent_=0;
927 }
928
929 void
930 Canvas::set_file_name(const String &file_name)
931 {
932         if(parent())
933                 parent()->set_file_name(file_name);
934         else
935         {
936                 file_name_=file_name;
937                 signal_file_name_changed_();
938         }
939 }
940
941 sigc::signal<void>&
942 Canvas::signal_file_name_changed()
943 {
944         if(parent())
945                 return signal_file_name_changed();
946         else
947                 return signal_file_name_changed_;
948 }
949
950 String
951 Canvas::get_file_name()const
952 {
953         if(parent())
954                 return parent()->get_file_name();
955         return file_name_;
956 }
957
958 String
959 Canvas::get_file_path()const
960 {
961         if(parent())
962                 return parent()->get_file_path();
963         return dirname(file_name_);
964 }
965
966         
967 String
968 Canvas::get_meta_data(const String& key)const
969 {
970         if(!meta_data_.count(key))
971                 return String();
972         return meta_data_.find(key)->second;
973 }
974
975 void
976 Canvas::set_meta_data(const String& key, const String& data)
977 {
978         if(meta_data_[key]!=data)
979         {
980                 meta_data_[key]=data;
981                 signal_meta_data_changed()(key);
982                 signal_meta_data_changed(key)();
983         }
984 }
985
986 void
987 Canvas::erase_meta_data(const String& key)
988 {
989         if(meta_data_.count(key))
990         {
991                 meta_data_.erase(key);
992                 signal_meta_data_changed()(key);
993                 signal_meta_data_changed(key)();
994         }
995 }
996
997 std::list<String>
998 Canvas::get_meta_data_keys()const
999 {
1000         std::list<String> ret;
1001
1002         std::map<String,String>::const_iterator iter;
1003
1004         for(iter=meta_data_.begin();!(iter==meta_data_.end());++iter)
1005                 ret.push_back(iter->first);
1006         
1007         return ret;
1008 }
1009
1010 void
1011 sinfg::optimize_layers(Context context, Canvas::Handle op_canvas)
1012 {
1013         Context iter;
1014
1015         std::vector< std::pair<float,Layer::Handle> > sort_list;
1016         int i;
1017         
1018         // Go ahead and start romping through the canvas to paste
1019         for(iter=context,i=0;*iter;iter++,i++)
1020         {
1021                 Layer::Handle layer=*iter;
1022                 float z_depth(layer->get_z_depth()*1.0001+i);
1023                 
1024                 // If the layer isn't active, don't worry about it
1025                 if(!layer->active())
1026                         continue;
1027
1028                 // Any layer with an amount of zero is implicitly disabled.
1029                 ValueBase value(layer->get_param("amount"));
1030                 if(value.get_type()==ValueBase::TYPE_REAL && value.get(Real())==0)
1031                         continue;
1032
1033                 Layer_PasteCanvas* paste_canvas(static_cast<Layer_PasteCanvas*>(layer.get()));
1034                 if(layer->get_name()=="PasteCanvas" && paste_canvas->get_time_offset()==0)
1035                 {
1036                         Canvas::Handle sub_canvas(Canvas::create_inline(op_canvas));
1037                         optimize_layers(paste_canvas->get_sub_canvas()->get_context(),sub_canvas);
1038 //#define SINFG_OPTIMIZE_PASTE_CANVAS 1
1039
1040 #ifdef SINFG_OPTIMIZE_PASTE_CANVAS                      
1041                         Canvas::iterator sub_iter;
1042                         // Determine if we can just remove the paste canvas
1043                         // altogether                   
1044                         if(paste_canvas->get_blend_method()==Color::BLEND_COMPOSITE && paste_canvas->get_amount()==1.0f && paste_canvas->get_zoom()==0 && paste_canvas->get_time_offset()==0 && paste_canvas->get_origin()==Point(0,0))
1045                         try{
1046                                 for(sub_iter=sub_canvas->begin();sub_iter!=sub_canvas->end();++sub_iter)
1047                                 {
1048                                         Layer* layer=sub_iter->get();
1049                                         
1050                                         // any layers that deform end up breaking things
1051                                         // so do things the old way if we run into anything like this
1052                                         if(!dynamic_cast<Layer_NoDeform*>(layer))
1053                                                 throw int();
1054
1055                                         ValueBase value(layer->get_param("blend_method"));
1056                                         if(value.get_type()!=ValueBase::TYPE_INTEGER || value.get(int())!=(int)Color::BLEND_COMPOSITE)
1057                                                 throw int();
1058                                 }
1059                                 
1060                                 // It has turned out that we don't need a paste canvas
1061                                 // layer, so just go ahead and add all the layers onto
1062                                 // the current stack and be done with it
1063                                 while(sub_canvas->size())
1064                                 {
1065                                         sort_list.push_back(std::pair<float,Layer::Handle>(z_depth,sub_canvas->front()));
1066                                         //op_canvas->push_back_simple(sub_canvas->front());
1067                                         sub_canvas->pop_front();
1068                                 }
1069                                 continue;
1070                         }catch(int) { }
1071 #endif
1072                         Layer::Handle new_layer(Layer::create("PasteCanvas"));
1073                         dynamic_cast<Layer_PasteCanvas*>(new_layer.get())->set_do_not_muck_with_time(true);
1074                         Layer::ParamList param_list(paste_canvas->get_param_list());
1075                         //param_list.erase("canvas");
1076                         new_layer->set_param_list(param_list);
1077                         dynamic_cast<Layer_PasteCanvas*>(new_layer.get())->set_sub_canvas(sub_canvas);
1078                         dynamic_cast<Layer_PasteCanvas*>(new_layer.get())->set_do_not_muck_with_time(false);
1079                         layer=new_layer;
1080                 }
1081                                                                 
1082                 sort_list.push_back(std::pair<float,Layer::Handle>(z_depth,layer));
1083                 //op_canvas->push_back_simple(layer);   
1084         }
1085         
1086         //sort_list.sort();
1087         stable_sort(sort_list.begin(),sort_list.end());
1088         std::vector< std::pair<float,Layer::Handle> >::iterator iter2;
1089         for(iter2=sort_list.begin();iter2!=sort_list.end();++iter2)
1090                 op_canvas->push_back_simple(iter2->second);
1091         op_canvas->op_flag_=true;
1092 }
1093
1094 void
1095 Canvas::get_times_vfunc(Node::time_set &set) const
1096 {
1097         const_iterator  i = begin(),
1098                                 iend = end();
1099         
1100         for(; i != iend; ++i)
1101         {
1102                 const Node::time_set &tset = (*i)->get_times();
1103                 set.insert(tset.begin(),tset.end());
1104         }
1105 }
1106
1107 std::set<etl::handle<Layer> >
1108 Canvas::get_layers_in_group(const String&group)
1109 {
1110         if(is_inline() && parent_)
1111                 return parent_->get_layers_in_group(group);
1112
1113         if(group_db_.count(group)==0)
1114                 return std::set<etl::handle<Layer> >();
1115         return group_db_.find(group)->second;
1116 }
1117
1118 std::set<String>
1119 Canvas::get_groups()const
1120 {
1121         if(is_inline() && parent_)
1122                 return parent_->get_groups();
1123
1124         std::set<String> ret;
1125         std::map<String,std::set<etl::handle<Layer> > >::const_iterator iter;
1126         for(iter=group_db_.begin();iter!=group_db_.end();++iter)
1127                 ret.insert(iter->first);
1128         return ret;
1129 }
1130
1131 int
1132 Canvas::get_group_count()const
1133 {
1134         if(is_inline() && parent_)
1135                 return parent_->get_group_count();
1136
1137         return group_db_.size();
1138 }
1139         
1140 void
1141 Canvas::add_group_pair(String group, etl::handle<Layer> layer)
1142 {
1143         group_db_[group].insert(layer);
1144         if(group_db_[group].size()==1)
1145                 signal_group_added()(group);
1146         else
1147                 signal_group_changed()(group);
1148         
1149         signal_group_pair_added()(group,layer);
1150
1151         if(is_inline()  && parent_)
1152                 return parent_->add_group_pair(group,layer);
1153 }
1154
1155 void
1156 Canvas::remove_group_pair(String group, etl::handle<Layer> layer)
1157 {
1158         group_db_[group].erase(layer);
1159
1160         signal_group_pair_removed()(group,layer);
1161
1162         if(group_db_[group].empty())
1163         {
1164                 group_db_.erase(group);
1165                 signal_group_removed()(group);
1166         }
1167         else
1168                 signal_group_changed()(group);
1169
1170         if(is_inline() && parent_)
1171                 return parent_->remove_group_pair(group,layer);
1172 }
1173
1174 void
1175 Canvas::rename_group(const String&old_name,const String&new_name)
1176 {
1177         if(is_inline() && parent_)
1178                 return parent_->rename_group(old_name,new_name);
1179         
1180         {
1181                 std::map<String,std::set<etl::handle<Layer> > >::iterator iter;
1182                 iter=group_db_.find(old_name);
1183                 if(iter!=group_db_.end())
1184                 for(++iter;iter!=group_db_.end() && iter->first.find(old_name)==0;iter=group_db_.find(old_name),++iter)
1185                 {
1186                         String name(iter->first,old_name.size(),String::npos);
1187                         name=new_name+name;
1188                         rename_group(iter->first,name);
1189                 }
1190         }
1191         
1192         std::set<etl::handle<Layer> > layers(get_layers_in_group(old_name));
1193         std::set<etl::handle<Layer> >::iterator iter;
1194         
1195         for(iter=layers.begin();iter!=layers.end();++iter)
1196         {
1197                 (*iter)->remove_from_group(old_name);
1198                 (*iter)->add_to_group(new_name);
1199         }
1200 }