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