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