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