Using mutexes around accesses to refcounts seems to make the Windows build much less...
[synfig.git] / synfig-core / trunk / src / synfig / valuenode.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file valuenode.cpp
3 **      \brief Implementation of the "Placeholder" valuenode conversion.
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007, 2008 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 #define SYNFIG_NO_ANGLE
27
28 //#define HAS_HASH_MAP 1
29
30 #ifdef USING_PCH
31 #       include "pch.h"
32 #else
33 #ifdef HAVE_CONFIG_H
34 #       include <config.h>
35 #endif
36
37 #include "valuenode.h"
38 #include "general.h"
39 #include "canvas.h"
40 #include "paramdesc.h"
41 #include "releases.h"
42
43 #include "valuenode_const.h"
44 #include "valuenode_linear.h"
45 #include "valuenode_composite.h"
46 #include "valuenode_reference.h"
47 #include "valuenode_scale.h"
48 #include "valuenode_blinecalctangent.h"
49 #include "valuenode_blinecalcvertex.h"
50 #include "valuenode_blinecalcwidth.h"
51 #include "valuenode_blinereversetangent.h"
52 #include "valuenode_segcalctangent.h"
53 #include "valuenode_segcalcvertex.h"
54 #include "valuenode_repeat_gradient.h"
55 #include "valuenode_stripes.h"
56 #include "valuenode_range.h"
57 #include "valuenode_add.h"
58 #include "valuenode_subtract.h"
59 #include "valuenode_timedswap.h"
60 #include "valuenode_twotone.h"
61 #include "valuenode_bline.h"
62 #include "valuenode_dynamiclist.h"
63 #include "valuenode_radialcomposite.h"
64 #include "valuenode_gradientrotate.h"
65 #include "valuenode_sine.h"
66 #include "valuenode_cos.h"
67 #include "valuenode_atan2.h"
68 #include "valuenode_exp.h"
69 #include "valuenode_switch.h"
70 #include "valuenode_timeloop.h"
71 #include "valuenode_reciprocal.h"
72 #include "valuenode_duplicate.h"
73 #include "valuenode_integer.h"
74 #include "valuenode_step.h"
75
76 #include "layer.h"
77
78 #endif
79
80 /* === U S I N G =========================================================== */
81
82 using namespace std;
83 using namespace etl;
84 using namespace synfig;
85
86 /* === M A C R O S ========================================================= */
87
88 /* === G L O B A L S ======================================================= */
89
90 static int value_node_count(0);
91
92 static LinkableValueNode::Book *book_;
93
94
95 ValueNode::LooseHandle
96 synfig::find_value_node(const GUID& guid)
97 {
98         return guid_cast<ValueNode>(guid);
99 }
100
101 /* === P R O C E D U R E S ================================================= */
102
103 /* === M E T H O D S ======================================================= */
104
105 bool
106 ValueNode::subsys_init()
107 {
108         book_=new LinkableValueNode::Book();
109
110 #define ADD_VALUENODE(class,name,local,version)                                                                                                 \
111         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create);            \
112         (*book_)[name].check_type=&class::check_type;                                                                                           \
113         (*book_)[name].local_name=local;                                                                                                                        \
114         (*book_)[name].release_version=version
115
116 #define ADD_VALUENODE2(class,name,local,version)                                                                                                \
117         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create_from);       \
118         (*book_)[name].check_type=&class::check_type;                                                                                           \
119         (*book_)[name].local_name=local;                                                                                                                        \
120         (*book_)[name].release_version=version
121
122         ADD_VALUENODE(ValueNode_Linear,                   "linear",                       _("Linear"),                   RELEASE_VERSION_0_61_06);
123         ADD_VALUENODE(ValueNode_Composite,                "composite",            _("Composite"),                RELEASE_VERSION_0_61_06);
124         ADD_VALUENODE(ValueNode_RadialComposite,  "radial_composite", _("Radial Composite"), RELEASE_VERSION_0_61_06);
125         ADD_VALUENODE(ValueNode_Reference,                "reference",            _("Reference"),                RELEASE_VERSION_0_61_06);
126         ADD_VALUENODE(ValueNode_Scale,                    "scale",                        _("Scale"),                    RELEASE_VERSION_0_61_06);
127         ADD_VALUENODE(ValueNode_SegCalcTangent,   "segcalctangent",       _("Segment Tangent"),  RELEASE_VERSION_0_61_06);
128         ADD_VALUENODE(ValueNode_SegCalcVertex,    "segcalcvertex",        _("Segment Vertex"),   RELEASE_VERSION_0_61_06);
129         ADD_VALUENODE(ValueNode_Stripes,                  "stripes",              _("Stripes"),                  RELEASE_VERSION_0_61_06);
130         ADD_VALUENODE(ValueNode_Subtract,                 "subtract",             _("Subtract"),                 RELEASE_VERSION_0_61_06);
131         ADD_VALUENODE(ValueNode_TwoTone,                  "twotone",              _("Two-Tone"),                 RELEASE_VERSION_0_61_06);
132         ADD_VALUENODE(ValueNode_BLine,                    "bline",                        _("BLine"),                    RELEASE_VERSION_0_61_06);
133         ADD_VALUENODE2(ValueNode_DynamicList,     "dynamic_list",         _("Dynamic List"),     RELEASE_VERSION_0_61_06);
134         ADD_VALUENODE(ValueNode_GradientRotate,   "gradient_rotate",  _("Gradient Rotate"),      RELEASE_VERSION_0_61_06);
135         ADD_VALUENODE(ValueNode_Sine,                     "sine",                         _("Sine"),                     RELEASE_VERSION_0_61_06);
136
137         ADD_VALUENODE(ValueNode_TimedSwap,                "timed_swap",           _("Timed Swap"),               RELEASE_VERSION_0_61_07); // SVN r610
138         ADD_VALUENODE(ValueNode_Repeat_Gradient,  "repeat_gradient",  _("Repeat Gradient"),      RELEASE_VERSION_0_61_07); // SVN r666
139         ADD_VALUENODE(ValueNode_Exp,                      "exp",                          _("Exponential"),              RELEASE_VERSION_0_61_07); // SVN r739
140         ADD_VALUENODE(ValueNode_Add,                      "add",                          _("Add"),                              RELEASE_VERSION_0_61_07); // SVN r742
141         ADD_VALUENODE(ValueNode_BLineCalcTangent, "blinecalctangent", _("BLine Tangent"),        RELEASE_VERSION_0_61_07); // SVN r744
142         ADD_VALUENODE(ValueNode_BLineCalcVertex,  "blinecalcvertex",  _("BLine Vertex"),         RELEASE_VERSION_0_61_07); // SVN r744
143         ADD_VALUENODE(ValueNode_Range,                    "range",                        _("Range"),                    RELEASE_VERSION_0_61_07); // SVN r776
144
145         ADD_VALUENODE(ValueNode_Switch,                   "switch",                       _("Switch"),                   RELEASE_VERSION_0_61_08); // SVN r923
146         ADD_VALUENODE(ValueNode_Cos,                      "cos",                          _("Cos"),                              RELEASE_VERSION_0_61_08); // SVN r1111
147         ADD_VALUENODE(ValueNode_Atan2,                    "atan2",                        _("aTan2"),                    RELEASE_VERSION_0_61_08); // SVN r1132
148         ADD_VALUENODE(ValueNode_BLineRevTangent,  "blinerevtangent",  _("Reverse Tangent"),      RELEASE_VERSION_0_61_08); // SVN r1162
149         ADD_VALUENODE(ValueNode_TimeLoop,                 "timeloop",             _("Time Loop"),                RELEASE_VERSION_0_61_08); // SVN r1226
150         ADD_VALUENODE(ValueNode_Reciprocal,               "reciprocal",           _("Reciprocal"),               RELEASE_VERSION_0_61_08); // SVN r1238
151         ADD_VALUENODE(ValueNode_Duplicate,                "duplicate",            _("Duplicate"),                RELEASE_VERSION_0_61_08); // SVN r1267
152         ADD_VALUENODE(ValueNode_Integer,                  "fromint",              _("From Integer"),     RELEASE_VERSION_0_61_08); // SVN r1267
153         ADD_VALUENODE(ValueNode_Step,                     "step",                         _("Step"),                     RELEASE_VERSION_0_61_08); // SVN r1691
154         ADD_VALUENODE(ValueNode_BLineCalcWidth,   "blinecalcwidth",       _("BLine Width"),              RELEASE_VERSION_0_61_08); // SVN r1694
155
156 #undef ADD_VALUENODE
157 #undef ADD_VALUENODE2
158
159         return true;
160 }
161
162 bool
163 ValueNode::subsys_stop()
164 {
165         delete book_;
166 /*      if(global_value_node_map.size() || value_node_count)
167         {
168                 if(value_node_count)
169                         synfig::error("%d ValueNodes haven't been destroyed yet!",value_node_count);
170
171                 if(global_value_node_map.size()!=value_node_count)
172                         synfig::error("value node count mismatch! map.size()!=value_node_count (%d!=%d)",global_value_node_map.size(),value_node_count);
173
174                 GlobalValueNodeMap::iterator iter;
175                 for(iter=global_value_node_map.begin();iter!=global_value_node_map.end();++iter)
176                 {
177                         if(!iter->second->is_exported())
178                                 synfig::info(_("%s: count:%d name:%s type:%s"),
179                                         iter->first.get_string().c_str(),
180                                         iter->second->count(),
181                                         iter->second->get_name().c_str(),
182                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
183                                 );
184                         else
185                                 synfig::info(_("%s: id:%s count:%d name:%s type:%s"),
186                                         iter->first.get_string().c_str(),
187                                         iter->second->get_id().c_str(),
188                                         iter->second->count(),
189                                         iter->second->get_name().c_str(),
190                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
191                                 );
192                 }
193         }
194 */
195         return true;
196 }
197
198 ValueNode::ValueNode(ValueBase::Type type):type(type)
199 {
200         value_node_count++;
201 }
202
203 LinkableValueNode::Book&
204 LinkableValueNode::book()
205 {
206         return *book_;
207 }
208
209 LinkableValueNode::Handle
210 LinkableValueNode::create(const String &name, const ValueBase& x)
211 {
212         if(!book().count(name))
213                 return 0;
214
215         if (!check_type(name, x.get_type()) &&
216                 // the Duplicate ValueNode is an exception - we don't want the
217                 // user creating it for themselves, so check_type() fails for
218                 // it even when it is valid
219                 !(name == "duplicate" && x.get_type() == ValueBase::TYPE_REAL))
220         {
221                 error(_("Bad type: ValueNode '%s' doesn't accept type '%s'"), book()[name].local_name.c_str(), ValueBase::type_local_name(x.get_type()).c_str());
222                 return 0;
223         }
224
225         return book()[name].factory(x);
226 }
227
228 bool
229 LinkableValueNode::check_type(const String &name, ValueBase::Type x)
230 {
231         if(!book().count(name) || !book()[name].check_type)
232                 return false;
233         return book()[name].check_type(x);
234 }
235
236 bool
237 LinkableValueNode::set_link(int i,ValueNode::Handle x)
238 {
239         ValueNode::Handle previous(get_link(i));
240
241         if(set_link_vfunc(i,x))
242         {
243                 if(previous)
244                         remove_child(previous.get());
245                 add_child(x.get());
246
247                 if(!x->is_exported() && get_parent_canvas())
248                 {
249                         x->set_parent_canvas(get_parent_canvas());
250                 }
251                 changed();
252                 return true;
253         }
254         return false;
255 }
256
257 ValueNode::LooseHandle
258 LinkableValueNode::get_link(int i)const
259 {
260         return get_link_vfunc(i);
261 }
262
263 void
264 LinkableValueNode::unlink_all()
265 {
266         for(int i=0;i<link_count();i++)
267         {
268                 ValueNode::LooseHandle value_node(get_link(i));
269                 if(value_node)
270                         value_node->parent_set.erase(this);
271         }
272 }
273
274 ValueNode::~ValueNode()
275 {
276         value_node_count--;
277
278         begin_delete();
279 }
280
281 void
282 ValueNode::on_changed()
283 {
284         etl::loose_handle<Canvas> parent_canvas = get_parent_canvas();
285         if(parent_canvas)
286                 do                                              // signal to all the ancestor canvases
287                         parent_canvas->signal_value_node_changed()(this);
288                 while (parent_canvas = parent_canvas->parent());
289         else if(get_root_canvas())
290                 get_root_canvas()->signal_value_node_changed()(this);
291
292         Node::on_changed();
293 }
294
295 int
296 ValueNode::replace(etl::handle<ValueNode> x)
297 {
298         if(x.get()==this)
299                 return 0;
300
301         while(parent_set.size())
302         {
303                 (*parent_set.begin())->add_child(x.get());
304                 (*parent_set.begin())->remove_child(this);
305                 //x->parent_set.insert(*parent_set.begin());
306                 //parent_set.erase(parent_set.begin());
307         }
308         int r(RHandle(this).replace(x));
309         x->changed();
310         return r;
311 }
312
313 void
314 ValueNode::set_id(const String &x)
315 {
316         if(name!=x)
317         {
318                 name=x;
319                 signal_id_changed_();
320         }
321 }
322
323 String
324 ValueNode::get_description(bool show_exported_name)const
325 {
326         String ret(_("ValueNode"));
327
328         if (dynamic_cast<const LinkableValueNode*>(this))
329                 return (dynamic_cast<const LinkableValueNode*>(this))->get_description(-1, show_exported_name);
330
331         if (show_exported_name && !is_exported())
332                 show_exported_name = false;
333
334         if (show_exported_name)
335                 ret += strprintf(" (%s)", get_id().c_str());
336
337         return ret;
338 }
339
340 ValueNodeList::ValueNodeList():
341         placeholder_count_(0)
342 {
343 }
344
345 bool
346 ValueNodeList::count(const String &id)const
347 {
348         const_iterator iter;
349
350         if(id.empty())
351                 return false;
352
353         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
354                 ;
355
356         if(iter==end())
357                 return false;
358
359         return true;
360 }
361
362 ValueNode::Handle
363 ValueNodeList::find(const String &id)
364 {
365         iterator iter;
366
367         if(id.empty())
368                 throw Exception::IDNotFound("Empty ID");
369
370         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
371                 ;
372
373         if(iter==end())
374                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
375
376         return *iter;
377 }
378
379 ValueNode::ConstHandle
380 ValueNodeList::find(const String &id)const
381 {
382         const_iterator iter;
383
384         if(id.empty())
385                 throw Exception::IDNotFound("Empty ID");
386
387         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
388                 ;
389
390         if(iter==end())
391                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
392
393         return *iter;
394 }
395
396 ValueNode::Handle
397 ValueNodeList::surefind(const String &id)
398 {
399         if(id.empty())
400                 throw Exception::IDNotFound("Empty ID");
401
402         ValueNode::Handle value_node;
403
404         try
405         {
406                 value_node=find(id);
407         }
408         catch(Exception::IDNotFound)
409         {
410                 value_node=PlaceholderValueNode::create();
411                 value_node->set_id(id);
412                 push_back(value_node);
413                 placeholder_count_++;
414         }
415
416         return value_node;
417 }
418
419 bool
420 ValueNodeList::erase(ValueNode::Handle value_node)
421 {
422         assert(value_node);
423
424         iterator iter;
425
426         for(iter=begin();iter!=end();++iter)
427                 if(value_node.get()==iter->get())
428                 {
429                         std::list<ValueNode::RHandle>::erase(iter);
430                         if(PlaceholderValueNode::Handle::cast_dynamic(value_node))
431                                 placeholder_count_--;
432                         return true;
433                 }
434         return false;
435 }
436
437 bool
438 ValueNodeList::add(ValueNode::Handle value_node)
439 {
440         if(!value_node)
441                 return false;
442         if(value_node->get_id().empty())
443                 return false;
444
445         try
446         {
447                 ValueNode::RHandle other_value_node=find(value_node->get_id());
448                 if(PlaceholderValueNode::Handle::cast_dynamic(other_value_node))
449                 {
450                         other_value_node->replace(value_node);
451                         placeholder_count_--;
452                         return true;
453                 }
454
455                 return false;
456         }
457         catch(Exception::IDNotFound)
458         {
459                 push_back(value_node);
460                 return true;
461         }
462
463         return false;
464 }
465
466 void
467 ValueNodeList::audit()
468 {
469         iterator iter,next;
470
471         for(next=begin(),iter=next++;iter!=end();iter=next++)
472                 if(iter->count()==1)
473                         std::list<ValueNode::RHandle>::erase(iter);
474 }
475
476
477 String
478 PlaceholderValueNode::get_name()const
479 {
480         return "placeholder";
481 }
482
483 String
484 PlaceholderValueNode::get_local_name()const
485 {
486         return _("Placeholder");
487 }
488
489 ValueNode*
490 PlaceholderValueNode::clone(const GUID& deriv_guid)const
491 {
492         ValueNode* ret(new PlaceholderValueNode());
493         ret->set_guid(get_guid()^deriv_guid);
494         return ret;
495 }
496
497 PlaceholderValueNode::Handle
498 PlaceholderValueNode::create(ValueBase::Type type)
499 {
500         return new PlaceholderValueNode(type);
501 }
502
503 ValueBase
504 PlaceholderValueNode::operator()(Time /*t*/)const
505 {
506         assert(0);
507         return ValueBase();
508 }
509
510 PlaceholderValueNode::PlaceholderValueNode(ValueBase::Type type):
511         ValueNode(type)
512 {
513 }
514
515 ValueNode*
516 LinkableValueNode::clone(const GUID& deriv_guid)const
517 {
518         {
519                 ValueNode* x(find_value_node(get_guid()^deriv_guid).get());
520                 if(x)
521                         return x;
522         }
523
524         int i;
525         LinkableValueNode *ret=create_new();
526         ret->set_guid(get_guid()^deriv_guid);
527
528         for(i=0;i<link_count();i++)
529         {
530                 ValueNode::Handle link=get_link_vfunc(i);
531                 if(!link->is_exported())
532                 {
533                         ValueNode::LooseHandle value_node(find_value_node(link->get_guid()^deriv_guid));
534                         if(!value_node)
535                                 value_node=link->clone(deriv_guid);
536                         ret->set_link(i,value_node);
537                 }
538                 else
539                         ret->set_link(i,link);
540         }
541
542         return ret;
543 }
544
545 String
546 ValueNode::get_relative_id(etl::loose_handle<const Canvas> x)const
547 {
548         assert(is_exported());
549         assert(canvas_);
550
551         if(x.get()==canvas_.get())
552                 return get_id();
553
554         return canvas_->_get_relative_id(x)+':'+get_id();
555 }
556
557 void
558 ValueNode::set_parent_canvas(etl::loose_handle<Canvas> x)
559 {
560         canvas_=x; if(x) root_canvas_=x->get_root();
561 }
562
563 void
564 ValueNode::set_root_canvas(etl::loose_handle<Canvas> x)
565 {
566         root_canvas_=x->get_root();
567 }
568
569 void LinkableValueNode::get_times_vfunc(Node::time_set &set) const
570 {
571         ValueNode::LooseHandle  h;
572
573         int size = link_count();
574
575         //just add it to the set...
576         for(int i=0; i < size; ++i)
577         {
578                 h = get_link(i);
579
580                 if(h)
581                 {
582                         const Node::time_set &tset = h->get_times();
583                         set.insert(tset.begin(),tset.end());
584                 }
585         }
586 }
587
588 String
589 LinkableValueNode::get_description(int index, bool show_exported_name)const
590 {
591         String description;
592
593         if (index == -1)
594         {
595                 if (show_exported_name && is_exported())
596                         description += strprintf(" (%s)", get_id().c_str());
597         }
598         else
599         {
600                 description = String(":") + link_local_name(index);
601
602                 if (show_exported_name)
603                 {
604                         ValueNode::LooseHandle link(get_link(index));
605                         if (link->is_exported())
606                                 description += strprintf(" (%s)", link->get_id().c_str());
607                 }
608         }
609
610         const synfig::Node* node = this;
611         LinkableValueNode::ConstHandle parent_linkable_vn = 0;
612
613         // walk up through the valuenodes trying to find the layer at the top
614         while (!node->parent_set.empty() && !dynamic_cast<const Layer*>(node))
615         {
616                 LinkableValueNode::ConstHandle linkable_value_node(dynamic_cast<const LinkableValueNode*>(node));
617                 if (linkable_value_node)
618                 {
619                         String link;
620                         int cnt = linkable_value_node->link_count();
621                         for (int i = 0; i < cnt; i++)
622                                 if (linkable_value_node->get_link(i) == parent_linkable_vn)
623                                 {
624                                         link = String(":") + linkable_value_node->link_local_name(i);
625                                         break;
626                                 }
627
628                         description = linkable_value_node->get_local_name() + link + (parent_linkable_vn?">":"") + description;
629                 }
630                 node = *node->parent_set.begin();
631                 parent_linkable_vn = linkable_value_node;
632         }
633
634         Layer::ConstHandle parent_layer(dynamic_cast<const Layer*>(node));
635         if(parent_layer)
636         {
637                 String param;
638                 const Layer::DynamicParamList &dynamic_param_list(parent_layer->dynamic_param_list());
639                 // loop to find the parameter in the dynamic parameter list - this gives us its name
640                 for (Layer::DynamicParamList::const_iterator iter = dynamic_param_list.begin(); iter != dynamic_param_list.end(); iter++)
641                         if (iter->second == parent_linkable_vn)
642                                 param = String(":") + parent_layer->get_param_local_name(iter->first);
643                 description = strprintf("(%s)%s>%s",
644                                                                 parent_layer->get_non_empty_description().c_str(),
645                                                                 param.c_str(),
646                                                                 description.c_str());
647         }
648
649         return description;
650 }