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