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