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