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