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