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