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