Add actions (add to group, ,remove from group, export, un-export, set layer descripti...
[synfig.git] / synfig-studio / src / gtkmm / state_draw.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file state_draw.cpp
3 **      \brief Template File
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007 Chris Moore
10 **      Copyright (c) 2009 Nikita Kitaev
11 **
12 **      This package is free software; you can redistribute it and/or
13 **      modify it under the terms of the GNU General Public License as
14 **      published by the Free Software Foundation; either version 2 of
15 **      the License, or (at your option) any later version.
16 **
17 **      This package is distributed in the hope that it will be useful,
18 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 **      General Public License for more details.
21 **      \endlegal
22 */
23 /* ========================================================================= */
24
25 /* === H E A D E R S ======================================================= */
26
27 #ifdef USING_PCH
28 #       include "pch.h"
29 #else
30 #ifdef HAVE_CONFIG_H
31 #       include <config.h>
32 #endif
33
34 #include <gtkmm/dialog.h>
35 #include <gtkmm/entry.h>
36
37 #include <synfig/valuenode_dynamiclist.h>
38
39 #include "state_draw.h"
40 #include "state_stroke.h"
41 #include "state_normal.h"
42 #include "canvasview.h"
43 #include "workarea.h"
44 #include "app.h"
45 #include <synfig/valuenode_bline.h>
46 #include <synfig/valuenode_composite.h>
47 #include <ETL/hermite>
48 #include <ETL/calculus>
49 #include <utility>
50 #include "event_mouse.h"
51 #include "event_layerclick.h"
52 #include "toolbox.h"
53
54 #include <synfigapp/blineconvert.h>
55 #include <synfigapp/main.h>
56
57 #include <ETL/gaussian>
58 #include "dialog_tooloptions.h"
59
60 #include <gtkmm/table.h>
61 #include <gtkmm/label.h>
62 #include <gtkmm/button.h>
63 #include <gtkmm/checkbutton.h>
64 #include <gtkmm/scale.h>
65 #include <sigc++/connection.h>
66
67 #include "general.h"
68
69 #endif
70
71 /* === U S I N G =========================================================== */
72
73 using namespace std;
74 using namespace etl;
75 using namespace synfig;
76 using namespace studio;
77
78 /* === M A C R O S ========================================================= */
79
80 /* === G L O B A L S ======================================================= */
81
82 StateDraw studio::state_draw;
83
84 /* === C L A S S E S & S T R U C T S ======================================= */
85
86 class studio::StateDraw_Context : public sigc::trackable
87 {
88         typedef etl::smart_ptr<std::list<synfig::Point> > StrokeData;
89         typedef etl::smart_ptr<std::list<synfig::Real> > WidthData;
90
91         typedef list< pair<StrokeData,WidthData> > StrokeQueue;
92
93         StrokeQueue stroke_queue;
94
95
96         etl::handle<CanvasView> canvas_view_;
97         CanvasView::IsWorking is_working;
98
99         bool prev_table_status;
100         bool loop_;
101         bool prev_workarea_layer_status_;
102
103         int nested;
104         sigc::connection process_queue_connection;
105
106         ValueNode_BLine::Handle last_stroke;
107         synfig::String last_stroke_id;
108
109         Gtk::Menu menu;
110
111         //Duckmatic::Push duckmatic_push;
112
113         std::list< etl::smart_ptr<std::list<synfig::Point> > > stroke_list;
114
115         void refresh_ducks();
116
117         Duckmatic::Type old_duckmask;
118
119         void fill_last_stroke();
120         Smach::event_result fill_last_stroke_and_unselect_other_layers();
121
122         Smach::event_result new_bline(std::list<synfig::BLinePoint> bline,bool loop_bline_flag,float radius);
123
124         Smach::event_result new_region(std::list<synfig::BLinePoint> bline,synfig::Real radius);
125
126         Smach::event_result extend_bline_from_begin(ValueNode_BLine::Handle value_node,std::list<synfig::BLinePoint> bline,bool complete_loop);
127         Smach::event_result extend_bline_from_end(ValueNode_BLine::Handle value_node,std::list<synfig::BLinePoint> bline,bool complete_loop);
128         void reverse_bline(std::list<synfig::BLinePoint> &bline);
129
130         synfigapp::Settings& settings;
131
132         Gtk::Table options_table;
133         Gtk::Entry entry_id;
134         Gtk::CheckButton checkbutton_pressure_width;
135         Gtk::CheckButton checkbutton_round_ends;
136         Gtk::CheckButton checkbutton_auto_loop;   // whether to loop new strokes which start and end in the same place
137         Gtk::CheckButton checkbutton_auto_extend; // whether to extend existing lines
138         Gtk::CheckButton checkbutton_auto_link;   // whether to link new ducks to existing ducks
139         Gtk::CheckButton checkbutton_region;      // whether to create regions
140         Gtk::CheckButton checkbutton_outline;     // whether to create outlines
141         Gtk::CheckButton checkbutton_auto_export;
142         Gtk::Button button_fill_last_stroke;
143
144         //pressure spinner and such
145         Gtk::Adjustment  adj_min_pressure;
146         Gtk::SpinButton  spin_min_pressure;
147         Gtk::CheckButton check_min_pressure;
148
149         Gtk::Adjustment  adj_feather;
150         Gtk::SpinButton  spin_feather;
151
152         Gtk::Adjustment  adj_globalthres;
153         Gtk::SpinButton  spin_globalthres;
154
155         Gtk::Adjustment  adj_localthres;
156         Gtk::CheckButton check_localerror;
157         void UpdateErrorBox();  //switches the stuff if need be :)
158
159         //Added by Adrian - data drive HOOOOO
160         synfigapp::BLineConverter blineconv;
161
162 public:
163         synfig::String get_id()const { return entry_id.get_text(); }
164         void set_id(const synfig::String& x) { return entry_id.set_text(x); }
165
166         bool get_pressure_width_flag()const { return checkbutton_pressure_width.get_active(); }
167         void set_pressure_width_flag(bool x) { return checkbutton_pressure_width.set_active(x); }
168
169         bool get_auto_loop_flag()const { return checkbutton_auto_loop.get_active(); }
170         void set_auto_loop_flag(bool x) { return checkbutton_auto_loop.set_active(x); }
171
172         bool get_auto_extend_flag()const { return checkbutton_auto_extend.get_active(); }
173         void set_auto_extend_flag(bool x) { return checkbutton_auto_extend.set_active(x); }
174
175         bool get_auto_link_flag()const { return checkbutton_auto_link.get_active(); }
176         void set_auto_link_flag(bool x) { return checkbutton_auto_link.set_active(x); }
177
178         bool get_region_flag()const { return checkbutton_region.get_active(); }
179         void set_region_flag(bool x) { return checkbutton_region.set_active(x); }
180
181         bool get_outline_flag()const { return checkbutton_outline.get_active(); }
182         void set_outline_flag(bool x) { return checkbutton_outline.set_active(x); }
183
184         bool get_auto_export_flag()const { return checkbutton_auto_export.get_active(); }
185         void set_auto_export_flag(bool x) { return checkbutton_auto_export.set_active(x); }
186
187         Real get_min_pressure() const { return adj_min_pressure.get_value(); }
188         void set_min_pressure(Real x) { return adj_min_pressure.set_value(x); }
189
190         Real get_feather() const { return adj_feather.get_value(); }
191         void set_feather(Real x) { return adj_feather.set_value(x); }
192
193         Real get_gthres() const { return adj_globalthres.get_value(); }
194         void set_gthres(Real x) { return adj_globalthres.set_value(x); }
195
196         Real get_lthres() const { return adj_localthres.get_value(); }
197         void set_lthres(Real x) { return adj_localthres.set_value(x); }
198
199         bool get_local_error_flag() const { return check_localerror.get_active(); }
200         void set_local_error_flag(bool x) { check_localerror.set_active(x); }
201
202         bool get_min_pressure_flag()const { return check_min_pressure.get_active(); }
203         void set_min_pressure_flag(bool x) { check_min_pressure.set_active(x); }
204
205         void load_settings();
206         void save_settings();
207         void increment_id();
208
209         Smach::event_result event_stop_handler(const Smach::event& x);
210
211         Smach::event_result event_refresh_handler(const Smach::event& x);
212
213         Smach::event_result event_mouse_down_handler(const Smach::event& x);
214
215         Smach::event_result event_stroke(const Smach::event& x);
216         Smach::event_result event_refresh_tool_options(const Smach::event& x);
217         void refresh_tool_options();
218
219         Smach::event_result process_stroke(StrokeData stroke_data, WidthData width_data, bool region_flag=false);
220
221         bool process_queue();
222
223
224         StateDraw_Context(CanvasView* canvas_view);
225
226         ~StateDraw_Context();
227
228         const etl::handle<CanvasView>& get_canvas_view()const{return canvas_view_;}
229         etl::handle<synfigapp::CanvasInterface> get_canvas_interface()const{return canvas_view_->canvas_interface();}
230         synfig::Time get_time()const { return get_canvas_interface()->get_time(); }
231         synfig::Canvas::Handle get_canvas()const{return canvas_view_->get_canvas();}
232         WorkArea * get_work_area()const{return canvas_view_->get_work_area();}
233
234         //void on_user_click(synfig::Point point);
235
236 //      bool run();
237 };      // END of class StateDraw_Context
238
239
240 /* === M E T H O D S ======================================================= */
241
242 StateDraw::StateDraw():
243         Smach::state<StateDraw_Context>("draw")
244 {
245         insert(event_def(EVENT_STOP,&StateDraw_Context::event_stop_handler));
246         insert(event_def(EVENT_REFRESH,&StateDraw_Context::event_refresh_handler));
247         insert(event_def(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,&StateDraw_Context::event_mouse_down_handler));
248         insert(event_def(EVENT_WORKAREA_STROKE,&StateDraw_Context::event_stroke));
249         insert(event_def(EVENT_REFRESH_TOOL_OPTIONS,&StateDraw_Context::event_refresh_tool_options));
250 }
251
252 StateDraw::~StateDraw()
253 {
254 }
255
256
257 void
258 StateDraw_Context::load_settings()
259 {
260         String value;
261
262         if(settings.get_value("draw.id",value))
263                 set_id(value);
264         else
265                 set_id("NewDrawing");
266
267         if(settings.get_value("draw.pressure_width",value) && value=="0")
268                 set_pressure_width_flag(false);
269         else
270                 set_pressure_width_flag(true);
271
272         if(settings.get_value("draw.auto_loop",value) && value=="0")
273                 set_auto_loop_flag(false);
274         else
275                 set_auto_loop_flag(true);
276
277         if(settings.get_value("draw.auto_extend",value) && value=="0")
278                 set_auto_extend_flag(false);
279         else
280                 set_auto_extend_flag(true);
281
282         if(settings.get_value("draw.auto_link",value) && value=="0")
283                 set_auto_link_flag(false);
284         else
285                 set_auto_link_flag(true);
286
287         if(settings.get_value("draw.region",value) && value=="0")
288                 set_region_flag(false);
289         else
290                 set_region_flag(true);
291
292         if(settings.get_value("draw.outline",value) && value=="0")
293                 set_outline_flag(false);
294         else
295                 set_outline_flag(true);
296
297         if(settings.get_value("draw.auto_export",value) && value=="1")
298                 set_auto_export_flag(true);
299         else
300                 set_auto_export_flag(false);
301
302         if(settings.get_value("draw.min_pressure_on",value) && value=="0")
303                 set_min_pressure_flag(false);
304         else
305                 set_min_pressure_flag(true);
306
307         if(settings.get_value("draw.min_pressure",value))
308         {
309                 Real n = atof(value.c_str());
310                 set_min_pressure(n);
311         }else
312                 set_min_pressure(0);
313
314         if(settings.get_value("draw.feather",value))
315         {
316                 Real n = atof(value.c_str());
317                 set_feather(n);
318         }else
319                 set_feather(0);
320
321         if(settings.get_value("draw.gthreshold",value))
322         {
323                 Real n = atof(value.c_str());
324                 set_gthres(n);
325         }
326
327         if(settings.get_value("draw.lthreshold",value))
328         {
329                 Real n = atof(value.c_str());
330                 set_lthres(n);
331         }
332
333         if(settings.get_value("draw.localize",value) && value == "1")
334                 set_local_error_flag(true);
335         else
336                 set_local_error_flag(false);
337 }
338
339 void
340 StateDraw_Context::save_settings()
341 {
342         settings.set_value("draw.id",get_id().c_str());
343         settings.set_value("draw.pressure_width",get_pressure_width_flag()?"1":"0");
344         settings.set_value("draw.auto_loop",get_auto_loop_flag()?"1":"0");
345         settings.set_value("draw.auto_extend",get_auto_extend_flag()?"1":"0");
346         settings.set_value("draw.auto_link",get_auto_link_flag()?"1":"0");
347         settings.set_value("draw.region",get_region_flag()?"1":"0");
348         settings.set_value("draw.outline",get_outline_flag()?"1":"0");
349         settings.set_value("draw.auto_export",get_auto_export_flag()?"1":"0");
350         settings.set_value("draw.min_pressure",strprintf("%f",get_min_pressure()));
351         settings.set_value("draw.feather",strprintf("%f",get_feather()));
352         settings.set_value("draw.min_pressure_on",get_min_pressure_flag()?"1":"0");
353         settings.set_value("draw.gthreshold",strprintf("%f",get_gthres()));
354         settings.set_value("draw.lthreshold",strprintf("%f",get_lthres()));
355         settings.set_value("draw.localize",get_local_error_flag()?"1":"0");
356 }
357
358 void
359 StateDraw_Context::increment_id()
360 {
361         String id(get_id());
362         int number=1;
363         int digits=0;
364
365         if(id.empty())
366                 id="Drawing";
367
368         // If there is a number
369         // already at the end of the
370         // id, then remove it.
371         if(id[id.size()-1]<='9' && id[id.size()-1]>='0')
372         {
373                 // figure out how many digits it is
374                 for (digits = 0;
375                          (int)id.size()-1 >= digits && id[id.size()-1-digits] <= '9' && id[id.size()-1-digits] >= '0';
376                          digits++)
377                         ;
378
379                 String str_number;
380                 str_number=String(id,id.size()-digits,id.size());
381                 id=String(id,0,id.size()-digits);
382                 // synfig::info("---------------- \"%s\"",str_number.c_str());
383
384                 number=atoi(str_number.c_str());
385         }
386         else
387         {
388                 number=1;
389                 digits=3;
390         }
391
392         number++;
393
394         // Add the number back onto the id
395         {
396                 const String format(strprintf("%%0%dd",digits));
397                 id+=strprintf(format.c_str(),number);
398         }
399
400         // Set the ID
401         set_id(id);
402 }
403
404 StateDraw_Context::StateDraw_Context(CanvasView* canvas_view):
405         canvas_view_(canvas_view),
406         is_working(*canvas_view),
407         loop_(false),
408         prev_workarea_layer_status_(get_work_area()->get_allow_layer_clicks()),
409         settings(synfigapp::Main::get_selected_input_device()->settings()),
410         entry_id(),
411         checkbutton_pressure_width(_("Pressure Width")),
412         checkbutton_auto_loop(_("Auto Loop")),
413         checkbutton_auto_extend(_("Auto Extend")),
414         checkbutton_auto_link(_("Auto Link")),
415         checkbutton_region(_("Create Region BLine")),
416         checkbutton_outline(_("Create Outline BLine")),
417         checkbutton_auto_export(_("Auto Export")),
418         button_fill_last_stroke(_("Fill Last Stroke")),
419         adj_min_pressure(0,0,1,0.01,0.1),
420         spin_min_pressure(adj_min_pressure,0.1,3),
421         check_min_pressure(_("Min Pressure")),
422         adj_feather(0,0,10000,0.01,0.1),
423         spin_feather(adj_feather,0.01,4),
424         adj_globalthres(.70f,0.01,10000,0.01,0.1),
425         spin_globalthres(adj_globalthres,0.01,3),
426         adj_localthres(20,1,100000,0.1,1),
427         check_localerror(_("LocalError"))
428
429 {
430         nested=0;
431         load_settings();
432
433         UpdateErrorBox();
434
435         options_table.attach(*manage(new Gtk::Label(_("Draw Tool"))),   0, 2, 0, 1, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
436         options_table.attach(entry_id,                                                                  0, 2,  1,  2, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
437         options_table.attach(checkbutton_outline,                                               0, 2,  2,  3, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
438         options_table.attach(checkbutton_region,                                                0, 2,  3,  4, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
439         options_table.attach(checkbutton_auto_loop,                                             0, 2,  4,  5, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
440         options_table.attach(checkbutton_auto_extend,                                   0, 2,  5,  6, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
441         options_table.attach(checkbutton_auto_link,                                             0, 2,  6,  7, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
442         options_table.attach(checkbutton_auto_export,                                   0, 2,  7,  8, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
443         options_table.attach(checkbutton_pressure_width,                                0, 2,  8,  9, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
444         options_table.attach(check_localerror,                                                  0, 2,  9, 10, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
445
446         options_table.attach(check_min_pressure,                                                0, 1, 10, 11, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
447         options_table.attach(spin_min_pressure,                                                 1, 2, 10, 11, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
448
449         options_table.attach(*manage(new Gtk::Label(_("Smooth"))),              0, 1, 11, 12, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
450         options_table.attach(spin_globalthres,                                                  1, 2, 11, 12, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
451
452         options_table.attach(*manage(new Gtk::Label(_("Feather"))),     0, 1, 12, 13, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
453         options_table.attach(spin_feather,                                                              1, 2, 12, 13, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
454
455         //options_table.attach(button_fill_last_stroke, 0, 2, 13, 14, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
456
457         button_fill_last_stroke.signal_pressed().connect(sigc::mem_fun(*this,&StateDraw_Context::fill_last_stroke));
458         check_localerror.signal_toggled().connect(sigc::mem_fun(*this,&StateDraw_Context::UpdateErrorBox));
459
460         options_table.show_all();
461         refresh_tool_options();
462         //App::dialog_tool_options->set_widget(options_table);
463         App::dialog_tool_options->present();
464
465
466         old_duckmask=get_work_area()->get_type_mask();
467         get_work_area()->set_type_mask(Duck::TYPE_ALL-Duck::TYPE_TANGENT-Duck::TYPE_WIDTH);
468
469         // Turn off layer clicking
470         get_work_area()->set_allow_layer_clicks(false);
471
472         // Turn off duck clicking
473         get_work_area()->set_allow_duck_clicks(false);
474
475         // clear out the ducks
476         //get_work_area()->clear_ducks();
477
478         // Refresh the work area
479         //get_work_area()->queue_draw();
480
481         // Hide the tables if they are showing
482         prev_table_status=get_canvas_view()->tables_are_visible();
483         //if(prev_table_status)get_canvas_view()->hide_tables();
484
485         // Disable the time bar
486         get_canvas_view()->set_sensitive_timebar(false);
487
488         // Connect a signal
489         //get_work_area()->signal_user_click().connect(sigc::mem_fun(*this,&studio::StateDraw_Context::on_user_click));
490
491         get_work_area()->set_cursor(Gdk::PENCIL);
492
493         App::toolbox->refresh();
494
495         refresh_ducks();
496 }
497
498
499 void StateDraw_Context::UpdateErrorBox()
500 {
501         if(get_local_error_flag())
502         {
503                 spin_globalthres.set_adjustment(adj_localthres);
504                 spin_globalthres.set_value(adj_localthres.get_value());
505                 spin_globalthres.set_increments(0.1,1);
506         }else
507         {
508                 spin_globalthres.set_adjustment(adj_globalthres);
509                 spin_globalthres.set_value(adj_globalthres.get_value());
510                 spin_globalthres.set_increments(0.01,.1);
511         }
512
513         spin_globalthres.update();
514 }
515
516 void
517 StateDraw_Context::refresh_tool_options()
518 {
519         App::dialog_tool_options->clear();
520         App::dialog_tool_options->set_widget(options_table);
521         App::dialog_tool_options->set_local_name(_("Draw Tool"));
522         App::dialog_tool_options->set_name("draw");
523
524         App::dialog_tool_options->add_button(
525                 Gtk::StockID("synfig-fill"),
526                 _("Fill Last Stroke")
527         )->signal_clicked().connect(
528                 sigc::mem_fun(
529                         *this,
530                         &StateDraw_Context::fill_last_stroke));
531 }
532
533 Smach::event_result
534 StateDraw_Context::event_refresh_tool_options(const Smach::event& /*x*/)
535 {
536         refresh_tool_options();
537         return Smach::RESULT_ACCEPT;
538 }
539
540 StateDraw_Context::~StateDraw_Context()
541 {
542         save_settings();
543
544         App::dialog_tool_options->clear();
545
546         get_work_area()->set_type_mask(old_duckmask);
547
548         get_work_area()->reset_cursor();
549
550         // Restore layer clicking
551         get_work_area()->set_allow_layer_clicks(prev_workarea_layer_status_);
552
553         // Restore duck clicking
554         get_work_area()->set_allow_duck_clicks(true);
555
556         // Enable the time bar
557         get_canvas_view()->set_sensitive_timebar(true);
558
559         // Bring back the tables if they were out before
560         if(prev_table_status)get_canvas_view()->show_tables();
561
562         // Refresh the work area
563         get_work_area()->queue_draw();
564
565         App::toolbox->refresh();
566 }
567
568 Smach::event_result
569 StateDraw_Context::event_stop_handler(const Smach::event& /*x*/)
570 {
571         //throw Smach::egress_exception();
572         throw &state_normal;
573         return Smach::RESULT_OK;
574 }
575
576 Smach::event_result
577 StateDraw_Context::event_refresh_handler(const Smach::event& /*x*/)
578 {
579         refresh_ducks();
580         return Smach::RESULT_ACCEPT;
581 }
582
583 Smach::event_result
584 StateDraw_Context::event_mouse_down_handler(const Smach::event& x)
585 {
586         const EventMouse& event(*reinterpret_cast<const EventMouse*>(&x));
587         switch(event.button)
588         {
589         case BUTTON_LEFT:
590                 {
591                         // Enter the stroke state to get the stroke
592                         get_canvas_view()->get_smach().push_state(&state_stroke);
593                         return Smach::RESULT_ACCEPT;
594                 }
595
596         default:
597                 return Smach::RESULT_OK;
598         }
599 }
600
601 #define SIMILAR_TANGENT_THRESHOLD       (0.2)
602
603 struct debugclass
604 {
605         synfig::String x;
606         debugclass(const synfig::String &x):x(x)
607         {
608 //              synfig::warning(">>>>>>>>>>>>>>>>>>> "+x);
609         }
610         ~debugclass()
611         {
612 //              synfig::warning("<<<<<<<<<<<<<<<<<<< "+x);
613         }
614 };
615
616 struct DepthCounter
617 {
618         int &i;
619         DepthCounter(int &i):i(i) { i++; }
620         ~DepthCounter() { i--; }
621 };
622
623 Smach::event_result
624 StateDraw_Context::event_stroke(const Smach::event& x)
625 {
626 //      debugclass debugger("StateDraw_Context::event_stroke(const Smach::event& x)");
627
628         const EventStroke& event(*reinterpret_cast<const EventStroke*>(&x));
629
630         assert(event.stroke_data);
631
632         get_work_area()->add_stroke(event.stroke_data,synfigapp::Main::get_outline_color());
633
634         if(nested==0)
635         {
636                 DirtyTrap dirty_trap(get_work_area());
637                 Smach::event_result result;
638                 result=process_stroke(event.stroke_data,event.width_data,event.modifier&Gdk::CONTROL_MASK || event.modifier&Gdk::BUTTON2_MASK);
639                 process_queue();
640                 return result;
641         }
642
643         stroke_queue.push_back(pair<StrokeData,WidthData>(event.stroke_data,event.width_data));
644
645         return Smach::RESULT_ACCEPT;
646 }
647
648 bool
649 StateDraw_Context::process_queue()
650 {
651 //      debugclass debugger("StateDraw_Context::process_queue()");
652         if(nested)
653                 return true;
654         DepthCounter depth_counter(nested);
655         while(!stroke_queue.empty())
656         {
657                 pair<StrokeData,WidthData> front(stroke_queue.front());
658                 process_stroke(front.first,front.second);
659                 stroke_queue.pop_front();
660         }
661         return false;
662 }
663
664 Smach::event_result
665 StateDraw_Context::process_stroke(StrokeData stroke_data, WidthData width_data, bool region_flag)
666 {
667 //      debugclass debugger("StateDraw_Context::process_stroke");
668         DepthCounter depth_counter(nested);
669
670         const float radius(synfigapp::Main::get_bline_width().units(get_canvas()->rend_desc())+(abs(get_work_area()->get_pw())+abs(get_work_area()->get_ph()))*5);
671
672
673         // If we aren't using pressure width,
674         // then set all the width to 1
675         if(!get_pressure_width_flag())
676         {
677                 std::list<synfig::Real>::iterator iter;
678                 for(iter=width_data->begin();iter!=width_data->end();++iter)
679                 {
680                         *iter=1.0;
681                 }
682         }
683
684         //get_work_area()->add_stroke(event.stroke_data,synfigapp::Main::get_outline_color());
685         //stroke_list.push_back(event.stroke_data);
686         //refresh_ducks();
687
688         std::list<synfig::BLinePoint> bline;
689         bool loop_bline_flag(false);
690
691         //Changed by Adrian - use resident class :)
692         //synfigapp::convert_stroke_to_bline(bline, *event.stroke_data,*event.width_data, synfigapp::Main::get_bline_width());
693         blineconv.width = synfigapp::Main::get_bline_width().units(get_canvas()->rend_desc());
694
695         if(get_local_error_flag())
696         {
697                 float pw = get_work_area()->get_pw();
698                 float ph = get_work_area()->get_ph();
699
700                 blineconv.pixelwidth = sqrt(pw*pw+ph*ph);
701                 blineconv.smoothness = get_lthres();
702         }else
703         {
704                 blineconv.pixelwidth = 1;
705                 blineconv.smoothness = get_gthres();
706         }
707
708         blineconv(bline,*stroke_data,*width_data);
709
710         //Postprocess to require minimum pressure
711         if(get_min_pressure_flag())
712         {
713                 synfigapp::BLineConverter::EnforceMinWidth(bline,get_min_pressure());
714         }
715
716         // If the start and end points are similar, then make them the same point
717         if (get_auto_loop_flag() &&
718                 bline.size() > 2 &&
719                 (bline.front().get_vertex() - bline.back().get_vertex()).mag() <= radius)
720         {
721                 loop_bline_flag=true;
722                 Vector tangent;
723                 Real width(0);
724
725                 while (bline.size() > 2 &&
726                            (bline.front().get_vertex() - bline.back().get_vertex()).mag() <= radius)
727                 {
728                         tangent=bline.back().get_tangent1();
729                         width=bline.back().get_width();
730                         bline.pop_back();
731                 }
732
733                 if(abs(bline.front().get_tangent1().norm()*tangent.norm().perp())>SIMILAR_TANGENT_THRESHOLD)
734                 {
735                         // If the tangents are not similar, then
736                         // split the tangents
737                         bline.front().set_split_tangent_flag(true);
738                         bline.front().set_tangent1(tangent);
739                 }
740                 else
741                 {
742                         // If the tangents are similar, then set the tangent
743                         // to the average of the two
744                         bline.front().set_tangent((tangent+bline.front().get_tangent1())*0.5f);
745                 }
746
747                 // Add the widths of the two points
748                 {
749                         Real tmp_width(bline.front().get_width()+width);
750                         tmp_width=tmp_width<=1?tmp_width:1;
751                         bline.front().set_width(tmp_width);
752                 }
753         }
754
755         // If the bline only has one blinepoint, then there is nothing to do.
756         if(bline.size() < 2)
757         {
758                 // hide the 'stroke' line we were drawing, unless the user
759                 // explicitly requests that they are kept
760                 if (!getenv("SYNFIG_KEEP_ABORTED_DRAW_LINES"))
761                         refresh_ducks();
762
763                 return Smach::RESULT_OK;
764         }
765
766         if(region_flag)
767                 return new_region(bline,radius);
768
769         return new_bline(bline,loop_bline_flag,radius);
770 }
771
772 Smach::event_result
773 StateDraw_Context::new_bline(std::list<synfig::BLinePoint> bline,bool loop_bline_flag,float radius)
774 {
775         synfigapp::SelectionManager::LayerList layer_list = get_canvas_view()->get_selection_manager()->get_selected_layers();
776
777         // Create the action group
778         synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("Sketch BLine"));
779
780         bool shift_origin = false;
781         Vector shift_origin_vector;
782         bool join_start_no_extend=false,join_finish_no_extend=false;
783         synfigapp::ValueDesc start_duck_value_desc,finish_duck_value_desc;
784         bool extend_start=false,extend_finish=false,complete_loop=false;
785         bool extend_start_join_same=false,extend_start_join_different=false;
786         bool extend_finish_join_same=false,extend_finish_join_different=false;
787         int start_duck_index = 0,finish_duck_index = 0; // initialized to keep the compiler happy; shouldn't be needed though
788         ValueNode_BLine::Handle start_duck_value_node_bline=NULL,finish_duck_value_node_bline=NULL;
789
790         // Find any ducks at the start or end that we might attach to
791         // (this used to only run if we didn't just draw a loop - ie. !loop_bline_flag
792         // but having loops auto-connect can be useful as well)
793         if(get_auto_extend_flag() || get_auto_link_flag())
794         {
795                 etl::handle<Duck> start_duck(get_work_area()->find_duck(bline.front().get_vertex(),radius,Duck::TYPE_VERTEX));
796                 etl::handle<Duck> finish_duck(get_work_area()->find_duck(bline.back().get_vertex(),radius,Duck::TYPE_VERTEX));
797
798                 // check whether the start of the new line extends an
799                 // existing line.  this is only the case if the new
800                 // line isn't a self-contained loop, and if the new
801                 // line starts at one of the ends of an existing line
802                 if(start_duck)do
803                 {
804                         if(!(start_duck_value_desc=start_duck->get_value_desc()))break;
805                         if(loop_bline_flag)break; // loops don't extend anything
806                         if(!start_duck_value_desc.parent_is_value_node())break;
807                         start_duck_index=start_duck_value_desc.get_index(); // which point on the line did we start drawing at
808                         start_duck_value_node_bline=ValueNode_BLine::Handle::cast_dynamic(start_duck_value_desc.get_parent_value_node());
809                         if(!get_auto_extend_flag())break;
810
811                         // don't extend looped blines
812                         if(start_duck_value_node_bline&&!start_duck_value_node_bline->get_loop()&&
813                            // did we start drawing at either end of the line?
814                            (start_duck_index==0||start_duck_index==start_duck_value_node_bline->link_count()-1))
815                         {
816                                 extend_start=true;
817                                 shift_origin=true;
818                                 shift_origin_vector=start_duck->get_origin();
819                         }
820                 }while(0);
821
822                 // check whether the end of the new line extends an
823                 // existing line.  this is only the case if the new
824                 // line isn't a self-contained loop, and if the new
825                 // line ends at one of the ends of an existing line
826                 if(finish_duck)do
827                 {
828                         if(!(finish_duck_value_desc=finish_duck->get_value_desc()))break;
829                         if(loop_bline_flag)break;
830                         if(!finish_duck_value_desc.parent_is_value_node())break;
831                         finish_duck_index=finish_duck_value_desc.get_index();
832                         finish_duck_value_node_bline=ValueNode_BLine::Handle::cast_dynamic(finish_duck_value_desc.get_parent_value_node());
833                         if(!get_auto_extend_flag())break;
834
835                         // don't extend looped blines
836                         if(finish_duck_value_node_bline&&!finish_duck_value_node_bline->get_loop()&&
837                            (finish_duck_index==0||finish_duck_index==finish_duck_value_node_bline->link_count()-1))
838                         {
839                                 if(extend_start)
840                                 {
841                                         // we've started and finished drawing at the end of a bline.  we can't
842                                         // extend both blines, so unless we started and finished at the 2 ends
843                                         // of the same bline, only extend the one we started on
844                                         if(start_duck_value_node_bline==finish_duck_value_node_bline)
845                                                 complete_loop=extend_finish=true;
846                                 }else{
847                                         extend_finish=true;
848                                         shift_origin=true;
849                                         shift_origin_vector=finish_duck->get_origin();
850                                 }
851                         }
852                 }while(0);
853
854                 // if the new line's start didn't extend an existing line,
855                 // check whether it needs to be linked to an existing duck
856                 if(!extend_start&&get_auto_link_flag()&&start_duck&&start_duck_value_desc)
857                         switch(start_duck_value_desc.get_value_type())
858                         {
859                         case synfig::ValueBase::TYPE_BLINEPOINT:
860                                 start_duck_value_desc=synfigapp::ValueDesc(LinkableValueNode::Handle::cast_dynamic(start_duck_value_desc.get_value_node()),0);
861                                 // fall through
862                         case synfig::ValueBase::TYPE_VECTOR:
863                                 if (shift_origin && shift_origin_vector != start_duck->get_origin())
864                                         break;
865                                 shift_origin = true;
866                                 shift_origin_vector = start_duck->get_origin();
867                                 get_canvas_interface()->auto_export(start_duck_value_desc);
868                                 if (extend_finish)
869                                         if(start_duck_value_node_bline&&start_duck_value_node_bline==finish_duck_value_node_bline)
870                                                 extend_finish_join_same=true;
871                                         else
872                                                 extend_finish_join_different=true;
873                                 else
874                                         join_start_no_extend=true;
875                                 // fall through
876                         default:break;
877                         }
878
879                 // if the new line's end didn't extend an existing line,
880                 // check whether it needs to be linked to an existing duck
881                 if(!extend_finish&&get_auto_link_flag()&&finish_duck&&finish_duck_value_desc)
882                         switch(finish_duck_value_desc.get_value_type())
883                         {
884                         case synfig::ValueBase::TYPE_BLINEPOINT:
885                                 finish_duck_value_desc=synfigapp::ValueDesc(LinkableValueNode::Handle::cast_dynamic(finish_duck_value_desc.get_value_node()),0);
886                                 // fall through
887                         case synfig::ValueBase::TYPE_VECTOR:
888                                 if (shift_origin && shift_origin_vector != finish_duck->get_origin())
889                                         break;
890                                 shift_origin = true;
891                                 shift_origin_vector = finish_duck->get_origin();
892                                 get_canvas_interface()->auto_export(finish_duck_value_desc);
893                                 if(extend_start)
894                                         if(finish_duck_value_node_bline&&start_duck_value_node_bline==finish_duck_value_node_bline)
895                                                 extend_start_join_same=true;
896                                         else
897                                                 extend_start_join_different=true;
898                                 else
899                                         join_finish_no_extend=true;
900                                 // fall through
901                         default:break;
902                         }
903         }
904
905         ValueNode_BLine::Handle value_node;
906         std::list<synfig::BLinePoint> trans_bline;
907
908         {
909                 std::list<synfig::BLinePoint>::iterator iter;
910                 const synfig::TransformStack& transform(get_canvas_view()->get_curr_transform_stack());
911
912                 for(iter=bline.begin();iter!=bline.end();++iter)
913                 {
914                         BLinePoint bline_point(*iter);
915                         Point new_vertex(transform.unperform(bline_point.get_vertex()));
916
917                         bline_point.set_tangent1(
918                                 transform.unperform(
919                                         bline_point.get_tangent1()+bline_point.get_vertex()
920                                 ) -new_vertex
921                         );
922
923                         bline_point.set_tangent2(
924                                 transform.unperform(
925                                         bline_point.get_tangent2()+bline_point.get_vertex()
926                                 ) -new_vertex
927                         );
928
929                         if (shift_origin)
930                                 new_vertex=new_vertex-shift_origin_vector;
931
932                         bline_point.set_vertex(new_vertex);
933
934                         trans_bline.push_back(bline_point);
935                 }
936                 value_node=ValueNode_BLine::create(synfig::ValueBase(trans_bline,loop_bline_flag));
937
938                 Canvas::Handle canvas(get_canvas_view()->get_canvas());
939                 Layer::Handle layer(get_canvas_view()->get_selection_manager()->get_selected_layer());
940                 if (layer) canvas=layer->get_canvas();
941                 value_node->set_member_canvas(canvas);
942         }
943
944         Smach::event_result result;
945         synfig::ValueNode_DynamicList::ListEntry source;
946
947         // the new line's start extends an existing line
948         if(extend_start)
949         {
950                 int target_offset = 0;
951                 if(complete_loop)trans_bline.pop_back();
952                 trans_bline.pop_front();
953                 if(start_duck_index==0)
954                 {       // We need to reverse the BLine first.
955                         reverse_bline(trans_bline);
956                         result=extend_bline_from_begin(start_duck_value_node_bline,trans_bline,complete_loop);
957                         source=start_duck_value_node_bline->list.front();
958                         target_offset=trans_bline.size();
959                 }
960                 else
961                 {
962                         result=extend_bline_from_end(start_duck_value_node_bline,trans_bline,complete_loop);
963                         source=start_duck_value_node_bline->list.back();
964                 }
965
966                 if(extend_start_join_different)
967                         LinkableValueNode::Handle::cast_dynamic(source.value_node)->
968                                 set_link("point",finish_duck_value_desc.get_value_node());
969                 else if(extend_start_join_same)
970                         LinkableValueNode::Handle::cast_dynamic(source.value_node)->
971                                 set_link("point",synfigapp::ValueDesc(LinkableValueNode::Handle::cast_dynamic(start_duck_value_node_bline->
972                                                                                                         list[target_offset+finish_duck_index].value_node),0).get_value_node());
973                 return result;
974         }
975
976         // the new line's end extends an existing line
977         if(extend_finish)
978         {
979                 int target_offset = 0;
980                 trans_bline.pop_back();
981                 if(finish_duck_index==0)
982                 {
983                         result=extend_bline_from_begin(finish_duck_value_node_bline,trans_bline,false);
984                         source=finish_duck_value_node_bline->list.front();
985                         target_offset=trans_bline.size();
986                 }
987                 else
988                 {       // We need to reverse the BLine first.
989                         reverse_bline(trans_bline);
990                         result=extend_bline_from_end(finish_duck_value_node_bline,trans_bline,false);
991                         source=finish_duck_value_node_bline->list.back();
992                 }
993
994                 if(extend_finish_join_different)
995                         LinkableValueNode::Handle::cast_dynamic(source.value_node)->
996                                 set_link("point",start_duck_value_desc.get_value_node());
997                 else if(extend_finish_join_same)
998                         LinkableValueNode::Handle::cast_dynamic(source.value_node)->
999                                 set_link("point",synfigapp::ValueDesc(LinkableValueNode::Handle::cast_dynamic(finish_duck_value_node_bline->
1000                                                                                                         list[target_offset+start_duck_index].value_node),0).get_value_node());
1001                 return result;
1002         }
1003
1004         if (join_start_no_extend)
1005                 LinkableValueNode::Handle::cast_dynamic(value_node->list.front().value_node)->
1006                   set_link("point",start_duck_value_desc.get_value_node());
1007
1008         if (join_finish_no_extend)
1009                 LinkableValueNode::Handle::cast_dynamic(value_node->list.back().value_node)->
1010                   set_link("point",finish_duck_value_desc.get_value_node());
1011
1012         if(get_auto_export_flag())
1013                 if (!get_canvas_interface()->add_value_node(value_node,get_id()))
1014                 {
1015                         /* it's no big deal, is it?  let's keep the shape anyway */
1016                         // get_canvas_view()->get_ui_interface()->error(_("Unable to add value node"));
1017                         // group.cancel();
1018                         // increment_id();
1019                         // return Smach::RESULT_ERROR;
1020                 }
1021
1022         last_stroke=value_node;
1023         last_stroke_id=get_id();
1024
1025         {
1026                 // Create the layer(s)
1027                 Layer::Handle layer;
1028                 Canvas::Handle canvas(get_canvas_view()->get_canvas());
1029                 int depth(0);
1030
1031                 // we are temporarily using the layer to hold something
1032                 layer=get_canvas_view()->get_selection_manager()->get_selected_layer();
1033                 if(layer)
1034                 {
1035                         depth=layer->get_depth();
1036                         canvas=layer->get_canvas();
1037                 }
1038
1039                 // fill_last_stroke() will take care of clearing the selection if we're calling it
1040                 if(get_outline_flag() && get_region_flag())
1041                 {
1042                         if (fill_last_stroke_and_unselect_other_layers() == Smach::RESULT_ERROR)
1043                         {
1044                                 get_canvas_view()->get_selection_manager()->set_selected_layers(layer_list);
1045                                 get_canvas_view()->get_ui_interface()->error(_("Unable to create layer"));
1046                                 group.cancel();
1047                                 return Smach::RESULT_ERROR;
1048                         }
1049                 }
1050                 else
1051                         get_canvas_interface()->get_selection_manager()->clear_selected_layers();
1052
1053                 //int number(synfig::UniqueID().get_uid());
1054
1055                 synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
1056
1057                 // if they're both defined, we'll add the region later
1058                 if(get_outline_flag())
1059                 {
1060                         layer=get_canvas_interface()->add_layer_to("outline",canvas,depth);
1061                         if (!layer)
1062                         {
1063                                 get_canvas_view()->get_selection_manager()->set_selected_layers(layer_list);
1064                                 get_canvas_view()->get_ui_interface()->error(_("Unable to create layer"));
1065                                 group.cancel();
1066                                 return Smach::RESULT_ERROR;
1067                         }
1068                         layer->set_description(get_id()+_(" Outline"));
1069                 }
1070                 else
1071                 {
1072                         layer=get_canvas_interface()->add_layer_to("region",canvas,depth);
1073                         if (!layer)
1074                         {
1075                                 get_canvas_view()->get_selection_manager()->set_selected_layers(layer_list);
1076                                 get_canvas_view()->get_ui_interface()->error(_("Unable to create layer"));
1077                                 group.cancel();
1078                                 return Smach::RESULT_ERROR;
1079                         }
1080                         layer->set_description(get_id()+_(" Region"));
1081                 }
1082
1083                 if(get_feather())
1084                 {
1085                         layer->set_param("feather",get_feather());
1086                         get_canvas_interface()->signal_layer_param_changed()(layer,"feather");
1087                 }
1088                 assert(layer);
1089                 //layer->set_description(strprintf("Stroke %d",number));
1090                 //get_canvas_interface()->signal_layer_new_description()(layer,layer->get_description());
1091
1092                 if (shift_origin)
1093                         get_canvas_interface()->
1094                           change_value(synfigapp::ValueDesc(layer,"origin"),shift_origin_vector);
1095
1096                 synfigapp::Action::Handle action(synfigapp::Action::create("LayerParamConnect"));
1097
1098                 assert(action);
1099
1100                 action->set_param("canvas",get_canvas());
1101                 action->set_param("canvas_interface",get_canvas_interface());
1102                 action->set_param("layer",layer);
1103                 if(!action->set_param("param",String("bline")))
1104                         synfig::error("LayerParamConnect didn't like \"param\"");
1105                 if(!action->set_param("value_node",ValueNode::Handle(value_node)))
1106                         synfig::error("LayerParamConnect didn't like \"value_node\"");
1107
1108                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1109                 {
1110                         get_canvas_view()->get_ui_interface()->error(_("Unable to create layer"));
1111                         group.cancel();
1112                         increment_id();
1113                         //refresh_ducks();
1114                         return Smach::RESULT_ERROR;
1115                 }
1116                 layer_list.push_back(layer);
1117                 get_canvas_view()->get_selection_manager()->set_selected_layers(layer_list);
1118                 //refresh_ducks();
1119         }
1120
1121         increment_id();
1122         return Smach::RESULT_ACCEPT;
1123 }
1124
1125 #ifdef _DEBUG
1126 static void
1127 debug_show_vertex_list(int iteration, std::list<synfigapp::ValueDesc>& vertex_list,
1128                                            std::string title, int current)
1129 {
1130         std::list<synfigapp::ValueDesc>::iterator i = vertex_list.begin();
1131         printf("\n%s\n  ----- iter %d : ", title.c_str(), iteration);
1132         int c = 0;
1133         synfig::LinkableValueNode::Handle last = 0;
1134         int start = -1;
1135         int index;
1136         int prev;
1137         int dir = 0;
1138         bool started = false;
1139         for(;i!=vertex_list.end();i++,c++)
1140         {
1141                 synfigapp::ValueDesc value_desc(*i);
1142
1143                 if (value_desc.parent_is_value_node()) {
1144                         if(value_desc.parent_is_linkable_value_node())
1145                         {
1146                                 index = value_desc.get_index();
1147                                 // printf("<%d>", index);
1148                                 if (last == synfig::LinkableValueNode::Handle::cast_reinterpret(value_desc.get_parent_value_node()))
1149                                 {
1150                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1151                                         if (start != -1)
1152                                         {
1153                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1154                                                 if (c == current)
1155                                                 {
1156                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1157                                                         if (dir)
1158                                                         {
1159                                                                 if (started) printf(", "); else started = true;
1160                                                                 printf("%d--%d", start, prev);
1161                                                         }
1162                                                         else
1163                                                         {
1164                                                                 if (started) printf(", "); else started = true;
1165                                                                 printf("%d", start);
1166                                                         }
1167                                                         printf(", *%d*", index);
1168                                                         start = -1;
1169                                                 }
1170                                                 else if (dir == 0)
1171                                                 {
1172                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1173                                                         if (index == start + 1)
1174                                                         {
1175                                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1176                                                                 dir = 1;
1177                                                                 prev = index;
1178                                                         }
1179                                                         else if (index == start - 1)
1180                                                         {
1181                                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1182                                                                 dir = -1;
1183                                                                 prev = index;
1184                                                         }
1185                                                         else
1186                                                         {
1187                                                                 if (started) printf(", "); else started = true;
1188                                                                 printf("%d", start);
1189                                                                 start = index;
1190                                                         }
1191                                                 }
1192                                                 else if (index == prev + dir)
1193                                                 {
1194                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1195                                                         prev = index;
1196                                                 }
1197                                                 else
1198                                                 {
1199                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1200                                                         if (started) printf(", "); else started = true;
1201                                                         if (prev != start)
1202                                                                 printf("%d--%d", start, prev);
1203                                                         else
1204                                                                 printf("%d", start);
1205                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1206                                                         start = index;
1207                                                         dir = 0;
1208                                                 }
1209                                         }
1210                                         else
1211                                         {
1212                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1213                                                 if (c == current)
1214                                                 {
1215                                                         if (started) printf(", "); else started = true;
1216                                                         printf("*%d*", index);
1217                                                 }
1218                                                 else
1219                                                 {
1220                                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1221                                                         start = index;
1222                                                         dir = 0;
1223                                                 }
1224                                         }
1225                                 }
1226                                 else
1227                                 {
1228                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1229                                         if (last)
1230                                         {
1231                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1232                                                 if (start != -1)
1233                                                 {
1234                                                         if (started) printf(", "); else started = true;
1235                                                         if (dir != 0)
1236                                                                 printf("%d--%d", start, prev);
1237                                                         else
1238                                                                 printf("%d", start);
1239                                                 }
1240                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1241                                                 printf(") ");
1242                                         }
1243                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1244                                         last = synfig::LinkableValueNode::Handle::cast_reinterpret(value_desc.get_parent_value_node());
1245                                         printf("%d:(", synfig::LinkableValueNode::Handle::cast_reinterpret(value_desc.get_parent_value_node())->link_count());
1246                                         started = false;
1247                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1248                                         if (c == current)
1249                                         {
1250                                                 start = -1;
1251                                                 printf("*%d*", index);
1252                                         }
1253                                         else
1254                                         {
1255                                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1256                                                 start = index;
1257                                                 dir = 0;
1258                                         }
1259                                         // printf("\n%s:%d\n", __FILE__, __LINE__);
1260                                 }
1261                                 // printf("\n%s:%d\n", __FILE__, __LINE__);
1262                         }
1263                         else if (last)
1264                                 if (last) printf("?!) ");
1265                 }
1266                 else
1267                 {
1268                         last = 0;
1269                         printf("? ");
1270                 }
1271         }
1272         if (last)
1273         {
1274                 if (started) printf(", "); else started = true;
1275                 if (start != -1)
1276                 {
1277                         if (dir != 0)
1278                                 printf("%d--%d", start, prev);
1279                         else
1280                                 printf("%d", start);
1281                 }
1282                 printf(")");
1283         }
1284         printf("\n");
1285 }
1286 #else  // _DEBUG
1287 #define debug_show_vertex_list(a,b,c,d)
1288 #endif  // _DEBUG
1289
1290 Smach::event_result
1291 StateDraw_Context::new_region(std::list<synfig::BLinePoint> bline, synfig::Real radius)
1292 {
1293         // Create the action group
1294         synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("Define Region"));
1295
1296         std::list<synfigapp::ValueDesc> vertex_list;
1297
1298         printf("new_region with %zd bline points\n", bline.size());
1299
1300         // First we need to come up with a rough list of
1301         // BLinePoints that we are going to be using to
1302         // define our region.
1303         {
1304                 std::list<synfig::BLinePoint>::iterator iter;
1305                 for(iter=bline.begin();iter!=bline.end();++iter)
1306                 {
1307                         etl::handle<Duck> duck(get_work_area()->find_duck(iter->get_vertex(),0,Duck::TYPE_VERTEX));
1308
1309                         if(!duck)
1310                         {
1311                                 synfig::info(__FILE__":%d: Nothing to enclose!",__LINE__);
1312                                 return Smach::RESULT_OK;
1313                         }
1314
1315                         assert(duck->get_type()==Duck::TYPE_VERTEX);
1316
1317                         synfigapp::ValueDesc value_desc(duck->get_value_desc());
1318
1319                         if(!value_desc)
1320                         {
1321                                 synfig::info(__FILE__":%d: Got a hit, but no ValueDesc on this duck",__LINE__);
1322                                 continue;
1323                         }
1324
1325                         switch(value_desc.get_value_type())
1326                         {
1327                         case synfig::ValueBase::TYPE_BLINEPOINT:
1328                                 //if(vertex_list.empty() || value_desc!=vertex_list.back())
1329                                 vertex_list.push_back(value_desc);
1330                                 assert(vertex_list.back().is_valid());
1331
1332                                 break;
1333                         default:
1334                                 break;
1335                         }
1336                 }
1337         }
1338
1339         assert(vertex_list.back().is_valid());
1340
1341         printf("vertex list with %zd bline points\n", vertex_list.size());
1342
1343         // Remove any duplicates
1344         {
1345         }
1346
1347         ValueNode_BLine::Handle value_node_bline;
1348
1349         // Now we need to test for the trivial case,
1350         // which is where all of the vertices
1351         // come from one BLine.
1352         if(vertex_list.front().parent_is_linkable_value_node())
1353         {
1354                 bool trivial_case(true);
1355                 ValueNode::Handle trivial_case_value_node;
1356
1357                 trivial_case_value_node=vertex_list.front().get_parent_value_node();
1358
1359                 std::list<synfigapp::ValueDesc>::iterator iter;
1360                 for(iter=vertex_list.begin();iter!=vertex_list.end();++iter)
1361                 {
1362                         if(trivial_case_value_node!=iter->get_parent_value_node())
1363                         {
1364                                 trivial_case=false;
1365                                 break;
1366                         }
1367                 }
1368
1369                 // \todo - re-enable this code
1370                 if(trivial_case && false)
1371                 {
1372                         synfig::info("all points are on the same bline, so just fill that line");
1373                         value_node_bline=ValueNode_BLine::Handle::cast_dynamic(trivial_case_value_node);
1374
1375                         synfig::info("the line has %d vertices", value_node_bline->link_count());
1376
1377                         if(value_node_bline->link_count() <= 2)
1378                         {
1379                                 synfig::info(__FILE__":%d: Vertex list too small to make region.",__LINE__);
1380                                 return Smach::RESULT_OK;
1381                         }
1382                 }
1383         }
1384
1385         if(!value_node_bline)
1386                 if(vertex_list.size()<=2)
1387                 {
1388                         synfig::info(__FILE__":%d: Vertex list too small to make region.",__LINE__);
1389                         return Smach::RESULT_OK;
1390                 }
1391
1392         // Now we need to clean the list of vertices up
1393         // a bit. This includes inserting missing vertices
1394         // and removing extraneous ones.
1395         // We can do this in multiple passes.
1396         if(!value_node_bline)
1397         {
1398                 debug_show_vertex_list(0, vertex_list, "before shifting stuff", -1);
1399                 // rearrange the list so that the first and last node are on different blines
1400                 std::list<synfigapp::ValueDesc>::iterator iter, start;
1401                 ValueNode::Handle last_value_node = vertex_list.back().get_parent_value_node();
1402                 for(iter = vertex_list.begin(); iter!=vertex_list.end(); iter++)
1403                         if (iter->get_parent_value_node() != last_value_node)
1404                         {
1405                                 vertex_list.insert(vertex_list.end(), vertex_list.begin(), iter);
1406                                 vertex_list.erase(vertex_list.begin(), iter);
1407                                 break;
1408                         }
1409
1410                 debug_show_vertex_list(0, vertex_list, "before detecting direction and limits", -1);
1411                 // rearrange the list so that the first and last node are on different blines
1412                 iter = vertex_list.begin();
1413                 while (iter!=vertex_list.end())
1414                 {
1415                         // make a note of which bline we're looking at
1416                         ValueNode::Handle parent_value_node = iter->get_parent_value_node();
1417                         start = iter;
1418                         int points_in_line = synfig::LinkableValueNode::Handle::cast_reinterpret(parent_value_node)->link_count();
1419                         bool looped = (*parent_value_node)(get_time()).get_loop();
1420                         int this_index, last_index = iter->get_index();
1421                         int min_index = last_index, max_index = last_index;
1422                         bool whole;
1423                         int direction = 0;
1424
1425                         // printf("there are %d points in this line - first is index %d\n", points_in_line, last_index);
1426
1427                         // while we're looking at the same bline, keep going
1428                         iter++;
1429                         while (iter != vertex_list.end() && iter->get_parent_value_node() == parent_value_node)
1430                         {
1431                                 this_index = iter->get_index();
1432                                 // printf("index went from %d to %d\n", last_index, this_index);
1433                                 if (looped)
1434                                 {
1435                                         if (this_index - last_index > points_in_line/2)
1436                                                 while (this_index - last_index > points_in_line/2)
1437                                                         this_index -= points_in_line;
1438                                         else if (last_index - this_index > points_in_line/2)
1439                                                 while (last_index - this_index > points_in_line/2)
1440                                                         this_index += points_in_line;
1441                                 }
1442
1443                                 if (this_index < min_index) min_index = this_index;
1444                                 if (this_index > max_index) max_index = this_index;
1445
1446                                 // printf("so let's imagine index went from %d to %d\n", last_index, this_index);
1447                                 if (this_index > last_index)
1448                                         direction++;
1449                                 else if (this_index < last_index)
1450                                         direction--;
1451
1452                                 last_index = this_index;
1453                                 iter++;
1454                         }
1455
1456                         // printf("min %d and max %d\n", min_index, max_index);
1457                         whole = max_index - min_index >= points_in_line;
1458                         min_index = (min_index % points_in_line + points_in_line) % points_in_line;
1459                         max_index = (max_index % points_in_line + points_in_line) % points_in_line;
1460                         // they drew around a shape more than once - what's the start/end point?  does it matter?
1461                         if (whole) min_index = max_index = (min_index + max_index) / 2;
1462                         // printf("processed min %d max %d whole %d\n", min_index, max_index, whole);
1463
1464                         if (direction < 0)
1465                         {
1466                                 if (whole)
1467                                 {
1468                                         // printf("whole (down) (%d) ", min_index);
1469                                         for (int i = min_index; i >= 0; i--)
1470                                         {
1471                                                 // printf("%d ", i);
1472                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1473                                         }
1474                                         for (int i = points_in_line - 1; i >= min_index; i--)
1475                                         {
1476                                                 // printf("%d ", i);
1477                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1478                                         }
1479                                 }
1480                                 else
1481                                 {
1482                                         // printf("part (down) (%d -> %d) ", max_index, min_index);
1483                                         for (int i = max_index; i != min_index; i--)
1484                                         {
1485                                                 if (i == -1) i = points_in_line - 1;
1486                                                 // printf("%d ", i);
1487                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1488                                         }
1489                                         vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, min_index));
1490                                 }
1491                         }
1492                         else
1493                         {
1494                                 if (whole)
1495                                 {
1496                                         // printf("whole (%d) ", min_index);
1497                                         for (int i = min_index; i < points_in_line; i++)
1498                                         {
1499                                                 // printf("%d ", i);
1500                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1501                                         }
1502                                         for (int i = 0; i <= min_index; i++)
1503                                         {
1504                                                 // printf("%d ", i);
1505                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1506                                         }
1507                                 }
1508                                 else
1509                                 {
1510                                         // printf("part (%d -> %d) ", min_index, max_index);
1511                                         for (int i = min_index; i != max_index; i++)
1512                                         {
1513                                                 if (i == points_in_line) i = 0;
1514                                                 // printf("%d ", i);
1515                                                 vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, i));
1516                                         }
1517                                         vertex_list.insert(start, synfigapp::ValueDesc(parent_value_node, max_index));
1518                                 }
1519                         }
1520                         // printf("\n");
1521                         // debug_show_vertex_list(0, vertex_list, "after insert", -1);
1522                         vertex_list.erase(start, iter);
1523                         // debug_show_vertex_list(0, vertex_list, "after delete", -1);
1524                 }
1525
1526                 debug_show_vertex_list(0, vertex_list, "continuous vertices", -1);
1527
1528                 // \todo reenable or delete this section
1529                 int i=100;
1530                 for(bool done=false;!done && i<30;i++)
1531                 {
1532                         debug_show_vertex_list(i, vertex_list, "in big loop", -1);
1533
1534                         // Set done to "true" for now. If
1535                         // any updates are performed, we will
1536                         // change it back to false.
1537                         done=true;
1538
1539                         std::list<synfigapp::ValueDesc>::iterator prev,next;
1540                         prev=vertex_list.end();prev--;  // Set prev to the last ValueDesc
1541                         next=vertex_list.begin();
1542                         iter=next++; // Set iter to the first value desc, and next to the second
1543
1544                         int current = 0;
1545                         for(;iter!=vertex_list.end();prev=iter,iter++,next++,current++)
1546                         {
1547                                 // we need to be able to erase(next) and can't do that if next is end()
1548                                 if (next == vertex_list.end()) next = vertex_list.begin();
1549                                 debug_show_vertex_list(i, vertex_list, "in loop around vertices", current);
1550                                 synfigapp::ValueDesc value_prev(*prev);
1551                                 synfigapp::ValueDesc value_desc(*iter);
1552                                 synfigapp::ValueDesc value_next(*next);
1553
1554                                 assert(value_desc.is_valid());
1555                                 assert(value_next.is_valid());
1556                                 assert(value_prev.is_valid());
1557
1558                                 // synfig::info("-------");
1559                                 // synfig::info(__FILE__":%d: value_prev 0x%08X:%d",__LINE__,value_prev.get_parent_value_node().get(),value_prev.get_index());
1560                                 // synfig::info(__FILE__":%d: value_desc 0x%08X:%d",__LINE__,value_desc.get_parent_value_node().get(),value_desc.get_index());
1561                                 // synfig::info(__FILE__":%d: value_next 0x%08X:%d",__LINE__,value_next.get_parent_value_node().get(),value_next.get_index());
1562
1563                                 /*
1564                                   if(value_prev.parent_is_value_node() && value_desc.parent_is_value_node() && value_next.parent_is_value_node())
1565                                   {
1566                                   // Remove random extraneous vertices
1567                                   if(value_prev.get_parent_value_node()==value_next.get_parent_value_node() &&
1568                                   value_prev.get_parent_value_node()!=value_desc.get_parent_value_node())
1569                                   {
1570                                   vertex_list.erase(iter);
1571                                   done=false;
1572                                   break;
1573                                   }
1574                                   }
1575                                 */
1576
1577                                 // // Remove duplicate vertices
1578
1579                                 // // if previous is the same as current or
1580                                 // //    current is the same as next, remove current
1581                                 // if(value_prev.get_value_node()==value_desc.get_value_node() ||
1582                                 //    value_desc.get_value_node()==value_next.get_value_node())
1583                                 // {
1584                                 //      vertex_list.erase(iter);
1585                                 //      done=false;
1586                                 //      printf("erased node - i = %d\n", i);
1587                                 //      break;
1588                                 // }
1589
1590                                 // // if previous is the same as next, remove previous?  or next?
1591                                 // if(value_prev.get_value_node()==value_next.get_value_node())
1592                                 // {
1593                                 //      vertex_list.erase(next);
1594                                 //      // vertex_list.erase(prev);
1595                                 //      done=false;
1596                                 //      printf("erased node - i = %d\n", i);
1597                                 //      break;
1598                                 // }
1599
1600                                 // if 'this' and 'next' both have parents
1601                                 if (value_desc.parent_is_value_node() && value_next.parent_is_value_node())
1602                                 {
1603                                         // if they are both on the same bline - this has been handled by new code above
1604                                         if (value_desc.get_parent_value_node() == value_next.get_parent_value_node())
1605                                         {
1606                                                 // // if (next != vertex_list.end())
1607                                                 // {
1608                                                 //      printf("parent loop is %d and node loop is ??\n",
1609                                                 //                 (*(value_desc.get_parent_value_node()))(get_time()).get_loop()
1610                                                 //                 // value_desc.get_value_node().get_loop(),
1611                                                 //              );
1612                                                 //
1613                                                 //      // Fill in missing vertices
1614                                                 //      // \todo take loops into account: seeing (15, 2, 3, 4) probably means that (0, 1) is missing, not 14 through 3
1615                                                 //      if(value_desc.get_index()<value_next.get_index()-1)
1616                                                 //      {
1617                                                 //              debug_show_vertex_list(i, vertex_list,
1618                                                 //                                                         strprintf("same parent, different points this %d < next-1 %d",
1619                                                 //                                                                               value_desc.get_index(), ((value_next.get_index()-1))),
1620                                                 //                                                         current);
1621                                                 //              for (int index = value_desc.get_index()+1; index < value_next.get_index(); index++)
1622                                                 //              {
1623                                                 //                      printf("inserting up %d\n", index);
1624                                                 //                      vertex_list.insert(next, synfigapp::ValueDesc(value_desc.get_parent_value_node(), index));
1625                                                 //              }
1626                                                 //              debug_show_vertex_list(i, vertex_list, "new list", current);
1627                                                 //              done=false;
1628                                                 //              break;
1629                                                 //      }
1630                                                 //      if(value_next.get_index()<value_desc.get_index()-1)
1631                                                 //      {
1632                                                 //              debug_show_vertex_list(i, vertex_list,
1633                                                 //                                                         strprintf("same parent, different points next %d < this-1 %d",
1634                                                 //                                                                               value_next.get_index(), ((value_desc.get_index()-1))),
1635                                                 //                                                         current);
1636                                                 //              for (int index = value_desc.get_index()-1; index > value_next.get_index(); index--)
1637                                                 //              {
1638                                                 //                      printf("inserting down %d\n", index);
1639                                                 //                      vertex_list.insert(next, synfigapp::ValueDesc(value_desc.get_parent_value_node(), index));
1640                                                 //              }
1641                                                 //              debug_show_vertex_list(i, vertex_list, "new list", current);
1642                                                 //              done=false;
1643                                                 //              break;
1644                                                 //      }
1645                                                 // }
1646                                         }
1647                                         // 'this' and 'next' have different parents
1648                                         else
1649                                         {
1650                                                 ValueNode::Handle v1 = value_desc.get_value_node();
1651                                                 ValueNode::Handle v2 = value_desc.get_parent_value_node();
1652                                                 if (v1 == v2)
1653                                                         printf("same\n");
1654                                                 else
1655                                                         printf("different\n");
1656
1657                                                 if (value_desc.get_value_node() != value_next.get_value_node())
1658                                                 {
1659                                                         // Ensure that connections between blines are properly connected
1660                                                         BLinePoint vertex(value_desc.get_value(get_time()).get(BLinePoint()));
1661                                                         BLinePoint vertex_next(value_next.get_value(get_time()).get(BLinePoint()));
1662
1663                                                         //synfig::info("--------");
1664                                                         //synfig::info(__FILE__":%d: vertex: [%f, %f]",__LINE__,vertex.get_vertex()[0],vertex.get_vertex()[1]);
1665                                                         //synfig::info(__FILE__":%d: vertex_next: [%f, %f]",__LINE__,vertex_next.get_vertex()[0],vertex_next.get_vertex()[1]);
1666
1667                                                         // if this vertex is close to the next one, replace this vertex with a new one
1668                                                         // and erase the next one
1669                                                         printf("this point is %5.2f from the next point - compare with %5.2f\n",
1670                                                                    (vertex.get_vertex()-vertex_next.get_vertex()).mag_squared(),
1671                                                                    radius*radius);
1672                                                         if((vertex.get_vertex()-vertex_next.get_vertex()).mag_squared()<radius*radius)
1673                                                         {
1674                                                                 printf("in one - it's close\n");
1675                                                                 ValueNode_Composite::Handle value_node;
1676                                                                 ValueNode_Composite::Handle value_node_next;
1677                                                                 value_node=ValueNode_Composite::Handle::cast_dynamic(value_desc.get_value_node().clone());
1678                                                                 value_node_next=ValueNode_Composite::Handle::cast_dynamic(value_next.get_value_node().clone());
1679                                                                 if(!value_node || !value_node_next)
1680                                                                 {
1681                                                                         synfig::info(__FILE__":%d: Unable to properly connect blines.",__LINE__);
1682                                                                         continue;
1683                                                                 }
1684                                                                 // \todo if next isn't split, don't we want to copy its 'Tangent 1' instead?
1685                                                                 value_node->set_link("t2",value_node_next->get_link("t2"));
1686                                                                 value_node->set_link("split",ValueNode_Const::create(true));
1687
1688                                                                 // get_canvas_interface()->auto_export(value_node);
1689                                                                 printf("exporting\n");
1690                                                                 get_canvas_interface()->add_value_node(value_node,value_node->get_id() + strprintf("foo %d", rand()));
1691
1692                                                                 assert(value_node->is_exported());
1693                                                                 // replace 'this' with the new valuenode
1694                                                                 *iter=synfigapp::ValueDesc(get_canvas(),value_node->get_id());
1695                                                                 printf("erasing next\n");
1696                                                                 printf("erasing next point\n");
1697                                                                 vertex_list.erase(next);
1698                                                                 done=false;
1699                                                                 break;
1700                                                         } // this vertex isn't close to the next one
1701                                                         else if (value_prev.parent_is_value_node())
1702                                                         {
1703                                                                 printf("in two - it's far\n");
1704                                                                 // \todo this only makes sense if prev is on the same bline
1705                                                                 printf("this is index %d\n", value_desc.get_index());
1706                                                                 printf("prev is index %d\n", value_prev.get_index());
1707                                                                 bool positive_trend(value_desc.get_index()>value_prev.get_index());
1708
1709                                                                 if(positive_trend)
1710                                                                 {
1711                                                                         printf("positive trend\n");
1712                                                                         printf("comparing index %d < link_count()-1 = %d-1 = %d\n",
1713                                                                                    value_desc.get_index(),
1714                                                                                    LinkableValueNode::Handle::cast_static(value_desc.get_parent_value_node())->link_count(),
1715                                                                                    LinkableValueNode::Handle::cast_static(value_desc.get_parent_value_node())->link_count()-1);
1716                                                                         if (value_desc.get_index()<LinkableValueNode::Handle::cast_static(value_desc.get_parent_value_node())->link_count()-1)
1717                                                                         {
1718                                                                                 printf("in two - b\n");
1719                                                                                 printf("inserting node with index %d\n", value_desc.get_index()+1);
1720                                                                                 vertex_list.insert(next,
1721                                                                                                                    synfigapp::ValueDesc(value_desc.get_parent_value_node(),
1722                                                                                                                                                                 value_desc.get_index()+1));
1723                                                                                 done=false;
1724                                                                                 break;
1725                                                                         }
1726                                                                 }
1727                                                                 else // !positive_trend
1728                                                                 {
1729                                                                         printf("negative trend\n");
1730                                                                         if(value_desc.get_index()>0)
1731                                                                         {
1732                                                                                 printf("in two - a\n");
1733                                                                                 printf("inserting node on this line with index %d\n",
1734                                                                                            value_desc.get_index()-1);
1735                                                                                 vertex_list.insert(next,
1736                                                                                                                    synfigapp::ValueDesc(value_desc.get_parent_value_node(),
1737                                                                                                                                                                 value_desc.get_index()-1));
1738                                                                                 done=false;
1739                                                                                 break;
1740                                                                         }
1741                                                                 }
1742                                                         }
1743                                                 }
1744                                         }
1745                                 }
1746                         }
1747                 }
1748
1749                 if(vertex_list.size()<=2)
1750                 {
1751                         synfig::info(__FILE__":%d: Vertex list too small to make region.",__LINE__);
1752                         return Smach::RESULT_OK;
1753                 }
1754
1755                 debug_show_vertex_list(i, vertex_list, "finished tidying list", -1);
1756         }
1757
1758         // If we aren't the trivial case,
1759         // then go ahead and create the new
1760         // BLine value node
1761         if(!value_node_bline)
1762         {
1763                 synfig::info("not all points are on the same bline");
1764                 value_node_bline=ValueNode_BLine::create();
1765
1766                 std::list<synfigapp::ValueDesc>::iterator iter;
1767                 for(iter=vertex_list.begin();iter!=vertex_list.end();++iter)
1768                 {
1769                         // Ensure that the vertex is exported.
1770                         get_canvas_interface()->auto_export(*iter);
1771
1772                         value_node_bline->add(iter->get_value_node());
1773                         //value_node_bline->add(ValueNode_BLine::ListEntry(iter->get_value_node()));
1774                 }
1775
1776                 value_node_bline->set_loop(true);
1777         }
1778
1779         get_canvas_interface()->auto_export(value_node_bline);
1780
1781         // Now we create the region layer
1782         // Create the layer
1783         {
1784                 Layer::Handle layer;
1785                 Canvas::Handle canvas(get_canvas_view()->get_canvas());
1786                 int depth(0);
1787
1788                 // we are temporarily using the layer to hold something
1789                 layer=get_canvas_view()->get_selection_manager()->get_selected_layer();
1790                 if(layer)
1791                 {
1792                         depth=layer->get_depth();
1793                         canvas=layer->get_canvas();
1794                 }
1795
1796                 synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
1797
1798                 layer=get_canvas_interface()->add_layer_to("region",canvas,depth);
1799                 if (!layer)
1800                 {
1801                         get_canvas_view()->get_ui_interface()->error(_("Unable to create layer"));
1802                         group.cancel();
1803                         return Smach::RESULT_ERROR;
1804                 }
1805
1806                 if(get_feather())
1807                 {
1808                         layer->set_param("feather",get_feather());
1809                         get_canvas_interface()->signal_layer_param_changed()(layer,"feather");
1810                 }
1811                 get_canvas_interface()->signal_layer_param_changed()(layer,"color");
1812
1813                 synfigapp::Action::Handle action(synfigapp::Action::create("LayerParamConnect"));
1814
1815                 assert(action);
1816
1817                 action->set_param("canvas",get_canvas());
1818                 action->set_param("canvas_interface",get_canvas_interface());
1819                 action->set_param("layer",layer);
1820                 if(!action->set_param("param",String("bline")))
1821                         synfig::error("LayerParamConnect didn't like \"param\"");
1822                 if(!action->set_param("value_node",ValueNode::Handle(value_node_bline)))
1823                         synfig::error("LayerParamConnect didn't like \"value_node\"");
1824
1825                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1826                 {
1827                         get_canvas_view()->get_ui_interface()->error(_("Unable to create Region layer"));
1828                         group.cancel();
1829                         return Smach::RESULT_ERROR;
1830                 }
1831                 get_canvas_view()->get_selection_manager()->set_selected_layer(layer);
1832         }
1833
1834         return Smach::RESULT_ACCEPT;
1835 }
1836
1837 void
1838 StateDraw_Context::refresh_ducks()
1839 {
1840         get_canvas_view()->queue_rebuild_ducks();
1841 /*
1842         get_work_area()->clear_ducks();
1843
1844
1845         std::list< etl::smart_ptr<std::list<synfig::Point> > >::iterator iter;
1846
1847         for(iter=stroke_list.begin();iter!=stroke_list.end();++iter)
1848         {
1849                 get_work_area()->add_stroke(*iter);
1850         }
1851
1852         get_work_area()->queue_draw();
1853 */
1854 }
1855
1856
1857 Smach::event_result
1858 StateDraw_Context::extend_bline_from_begin(ValueNode_BLine::Handle value_node,std::list<synfig::BLinePoint> bline,bool complete_loop)
1859 {
1860         // Create the action group
1861         synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("Extend BLine"));
1862
1863         if (complete_loop)
1864         {
1865                 synfigapp::Action::Handle action(synfigapp::Action::create("ValueNodeDynamicListLoop"));
1866                 assert(action);
1867
1868                 action->set_param("canvas",get_canvas());
1869                 action->set_param("canvas_interface",get_canvas_interface());
1870                 action->set_param("value_node",ValueNode::Handle(value_node));
1871
1872                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1873                 {
1874                         get_canvas_view()->get_ui_interface()->error(_("Unable to set loop for bline"));
1875                         group.cancel();
1876                         return Smach::RESULT_ERROR;
1877                 }
1878         }
1879
1880         std::list<synfig::BLinePoint>::reverse_iterator iter;
1881         for(iter=bline.rbegin();!(iter==bline.rend());++iter)
1882         {
1883                 ValueNode_Composite::Handle composite(ValueNode_Composite::create(*iter));
1884
1885                 synfigapp::Action::Handle action(synfigapp::Action::create("ValueNodeDynamicListInsert"));
1886
1887                 assert(action);
1888                 synfigapp::ValueDesc value_desc(value_node,0);
1889
1890                 action->set_param("canvas",get_canvas());
1891                 action->set_param("canvas_interface",get_canvas_interface());
1892                 action->set_param("value_desc",value_desc);
1893                 if(!action->set_param("item",ValueNode::Handle(composite)))
1894                         synfig::error("ACTION didn't like \"item\"");
1895
1896                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1897                 {
1898                         get_canvas_view()->get_ui_interface()->error(_("Unable to insert item"));
1899                         group.cancel();
1900                         //refresh_ducks();
1901                         return Smach::RESULT_ERROR;
1902                 }
1903         }
1904         last_stroke=value_node;
1905         return Smach::RESULT_ACCEPT;
1906 }
1907
1908 Smach::event_result
1909 StateDraw_Context::extend_bline_from_end(ValueNode_BLine::Handle value_node,std::list<synfig::BLinePoint> bline,bool complete_loop)
1910 {
1911         // Create the action group
1912         synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("Extend BLine"));
1913
1914         if (complete_loop)
1915         {
1916                 synfigapp::Action::Handle action(synfigapp::Action::create("ValueNodeDynamicListLoop"));
1917                 assert(action);
1918
1919                 action->set_param("canvas",get_canvas());
1920                 action->set_param("canvas_interface",get_canvas_interface());
1921                 action->set_param("value_node",ValueNode::Handle(value_node));
1922
1923                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1924                 {
1925                         get_canvas_view()->get_ui_interface()->error(_("Unable to set loop for bline"));
1926                         group.cancel();
1927                         return Smach::RESULT_ERROR;
1928                 }
1929         }
1930
1931         std::list<synfig::BLinePoint>::iterator iter;
1932         for(iter=bline.begin();iter!=bline.end();++iter)
1933         {
1934                 ValueNode_Composite::Handle composite(ValueNode_Composite::create(*iter));
1935
1936                 synfigapp::Action::Handle action(synfigapp::Action::create("ValueNodeDynamicListInsert"));
1937
1938                 assert(action);
1939                 synfigapp::ValueDesc value_desc(value_node,value_node->link_count());
1940
1941                 action->set_param("canvas",get_canvas());
1942                 action->set_param("canvas_interface",get_canvas_interface());
1943                 action->set_param("value_desc",value_desc);
1944                 if(!action->set_param("item",ValueNode::Handle(composite)))
1945                         synfig::error("ACTION didn't like \"item\"");
1946
1947                 if(!get_canvas_interface()->get_instance()->perform_action(action))
1948                 {
1949                         get_canvas_view()->get_ui_interface()->error(_("Unable to insert item"));
1950                         group.cancel();
1951                         //refresh_ducks();
1952                         return Smach::RESULT_ERROR;
1953                 }
1954         }
1955         last_stroke=value_node;
1956         return Smach::RESULT_ACCEPT;
1957 }
1958
1959 void
1960 StateDraw_Context::reverse_bline(std::list<synfig::BLinePoint> &bline)
1961 {
1962         int i;
1963
1964         std::list<synfig::BLinePoint>::iterator iter,eiter;
1965         iter=bline.begin();
1966         eiter=bline.end();
1967         eiter--;
1968         for(i=0;i<(int)bline.size()/2;++iter,--eiter,i++)
1969         {
1970                 iter_swap(iter,eiter);
1971                 iter->reverse();
1972                 eiter->reverse();
1973         }
1974 }
1975
1976 Smach::event_result
1977 StateDraw_Context::fill_last_stroke_and_unselect_other_layers()
1978 {
1979         if(!last_stroke)
1980                 return Smach::RESULT_OK;
1981
1982         synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("Fill Stroke"));
1983
1984         Layer::Handle layer;
1985
1986         get_canvas_interface()->auto_export(last_stroke);
1987
1988         synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
1989
1990         Canvas::Handle canvas(get_canvas_view()->get_canvas());
1991         int depth(0);
1992
1993         layer=get_canvas_view()->get_selection_manager()->get_selected_layer();
1994         if(layer)
1995         {
1996                 depth=layer->get_depth();
1997                 canvas=layer->get_canvas();
1998         }
1999
2000         get_canvas_interface()->get_selection_manager()->clear_selected_layers();
2001         layer=get_canvas_interface()->add_layer_to("region", canvas, depth);
2002         if (!layer) return Smach::RESULT_ERROR;
2003         layer->set_description(last_stroke_id + _(" Region"));
2004
2005         synfigapp::Action::Handle action(synfigapp::Action::create("LayerParamConnect"));
2006
2007         assert(action);
2008
2009         action->set_param("canvas",get_canvas());
2010         action->set_param("canvas_interface",get_canvas_interface());
2011         action->set_param("layer",layer);
2012         if(!action->set_param("param",String("bline")))
2013                 synfig::error("LayerParamConnect didn't like \"param\"");
2014         if(!action->set_param("value_node",ValueNode::Handle(last_stroke)))
2015                 synfig::error("LayerParamConnect didn't like \"value_node\"");
2016
2017         if(!get_canvas_interface()->get_instance()->perform_action(action))
2018         {
2019                 get_canvas_view()->get_ui_interface()->error(_("Unable to create Region layer"));
2020                 group.cancel();
2021                 return Smach::RESULT_OK;
2022         }
2023         get_canvas_view()->get_selection_manager()->set_selected_layer(layer);
2024         return Smach::RESULT_OK;
2025 }
2026
2027 void
2028 StateDraw_Context::fill_last_stroke()
2029 {
2030         if(!last_stroke)
2031                 return;
2032
2033         synfigapp::SelectionManager::LayerList layer_list = get_canvas_view()->get_selection_manager()->get_selected_layers();
2034         fill_last_stroke_and_unselect_other_layers();
2035         get_canvas_view()->get_selection_manager()->set_selected_layers(layer_list);
2036 }