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