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