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