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