Fix 1675309: CanvasView::close() was previously just hiding the canvas, not closing it.
[synfig.git] / synfig-studio / trunk / src / gtkmm / state_bline.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file rotoscope_bline.cpp
3 **      \brief Template File
4 **
5 **      $Id: state_bline.cpp,v 1.1.1.1 2005/01/07 03:34:36 darco Exp $
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_bline.h"
38 #include "canvasview.h"
39 #include "workarea.h"
40 #include "app.h"
41 #include <synfig/valuenode_bline.h>
42 #include <ETL/hermite>
43 #include <ETL/calculus>
44 #include <utility>
45 #include "event_mouse.h"
46 #include "event_layerclick.h"
47 #include "toolbox.h"
48 #include "dialog_tooloptions.h"
49 #include <gtkmm/spinbutton.h>
50 #include <synfig/transform.h>
51 #include <synfigapp/main.h>
52
53 #endif
54
55 /* === U S I N G =========================================================== */
56
57 using namespace std;
58 using namespace etl;
59 using namespace synfig;
60 using namespace studio;
61
62 /* === M A C R O S ========================================================= */
63
64 /* === G L O B A L S ======================================================= */
65
66 StateBLine studio::state_bline;
67
68 /* === C L A S S E S & S T R U C T S ======================================= */
69
70 class studio::StateBLine_Context : public sigc::trackable
71 {
72         etl::handle<CanvasView> canvas_view_;
73         CanvasView::IsWorking is_working;
74         
75         bool prev_table_status;
76         bool loop_;
77         bool prev_workarea_layer_status_;
78
79         int depth;
80         Canvas::Handle canvas;
81
82         Gtk::Menu menu;
83
84         Duckmatic::Push duckmatic_push;
85         
86         etl::handle<Duck> curr_duck;
87
88         etl::handle<Duck> next_duck;
89         
90         std::list<synfig::ValueNode_Const::Handle> bline_point_list;
91         synfigapp::Settings& settings;
92         
93         bool on_vertex_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node);
94         bool on_tangent1_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node);
95         bool on_tangent2_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node);
96
97
98         void popup_handle_menu(synfig::ValueNode_Const::Handle value_node);
99         void popup_vertex_menu(synfig::ValueNode_Const::Handle value_node);
100         void popup_bezier_menu(float location, synfig::ValueNode_Const::Handle value_node);
101
102         void bline_detach_handle(synfig::ValueNode_Const::Handle value_node);
103         void bline_attach_handle(synfig::ValueNode_Const::Handle value_node);
104         void bline_delete_vertex(synfig::ValueNode_Const::Handle value_node);
105         void bline_insert_vertex(synfig::ValueNode_Const::Handle value_node,float origin=0.5);
106         void loop_bline();
107         void unloop_bline();
108
109         void refresh_ducks(bool x=true);
110         
111         Gtk::Table options_table;
112         Gtk::Entry entry_id;
113         Gtk::CheckButton checkbutton_layer_region;
114         Gtk::CheckButton checkbutton_layer_bline;
115         Gtk::CheckButton checkbutton_layer_curve_gradient;
116         Gtk::CheckButton checkbutton_auto_export;
117         Gtk::Button button_make;
118         Gtk::Button button_clear;
119         Gtk::Adjustment  adj_feather;
120         Gtk::SpinButton  spin_feather;
121         
122         
123         
124 public:
125
126         int layers_to_create()const
127         {
128                 return
129                         get_layer_region_flag()+
130                         get_layer_bline_flag()+
131                         get_layer_curve_gradient_flag();
132         }
133         
134         void sanity_check()
135         {
136                 if(layers_to_create()==0)
137                         set_layer_region_flag(true);
138         }
139
140         bool get_auto_export_flag()const { return checkbutton_auto_export.get_active(); }
141         void set_auto_export_flag(bool x) { return checkbutton_auto_export.set_active(x); }
142         
143         bool get_layer_region_flag()const { return checkbutton_layer_region.get_active(); }
144         void set_layer_region_flag(bool x) { return checkbutton_layer_region.set_active(x); }
145         
146         bool get_layer_bline_flag()const { return checkbutton_layer_bline.get_active(); }
147         void set_layer_bline_flag(bool x) { return checkbutton_layer_bline.set_active(x); }
148         
149         bool get_layer_curve_gradient_flag()const { return checkbutton_layer_curve_gradient.get_active(); }
150         void set_layer_curve_gradient_flag(bool x) { return checkbutton_layer_curve_gradient.set_active(x); }
151
152         Real get_feather() const { return adj_feather.get_value(); }
153         void set_feather(Real x) { return adj_feather.set_value(x); }
154         synfig::String get_id()const { return entry_id.get_text(); }
155         void set_id(const synfig::String& x) { return entry_id.set_text(x); }
156
157         Smach::event_result event_stop_handler(const Smach::event& x);
158
159         Smach::event_result event_refresh_handler(const Smach::event& x);
160
161         Smach::event_result event_mouse_click_handler(const Smach::event& x);
162         Smach::event_result event_mouse_release_handler(const Smach::event& x);
163         Smach::event_result event_mouse_motion_handler(const Smach::event& x);
164         Smach::event_result event_refresh_tool_options(const Smach::event& x);
165
166         Smach::event_result event_hijack(const Smach::event& x) { return Smach::RESULT_ACCEPT; }
167         
168         void refresh_tool_options();
169
170         StateBLine_Context(CanvasView* canvas_view);
171
172         ~StateBLine_Context();
173
174         const etl::handle<CanvasView>& get_canvas_view()const{return canvas_view_;}
175         etl::handle<synfigapp::CanvasInterface> get_canvas_interface()const{return canvas_view_->canvas_interface();}
176         synfig::Canvas::Handle get_canvas()const{return canvas_view_->get_canvas();}
177         WorkArea * get_work_area()const{return canvas_view_->get_work_area();}
178         const synfig::TransformStack& get_transform_stack()const { return canvas_view_->get_curr_transform_stack(); }
179         
180         void load_settings();
181         void save_settings();
182         void reset();
183         void increment_id();
184         //void on_user_click(synfig::Point point);
185
186         bool run_();
187         bool run();
188         
189         bool no_egress_on_selection_change;
190         Smach::event_result event_layer_selection_changed_handler(const Smach::event& x)
191         {
192                 if(!no_egress_on_selection_change)
193                         throw Smach::egress_exception();
194                 return Smach::RESULT_OK;
195         }
196         
197 };      // END of class StateBLine_Context
198
199
200 /* === M E T H O D S ======================================================= */
201
202 StateBLine::StateBLine():
203         Smach::state<StateBLine_Context>("bline")
204 {
205         insert(event_def(EVENT_LAYER_SELECTION_CHANGED,&StateBLine_Context::event_layer_selection_changed_handler));
206         insert(event_def(EVENT_STOP,&StateBLine_Context::event_stop_handler));
207         insert(event_def(EVENT_REFRESH,&StateBLine_Context::event_refresh_handler));
208         insert(event_def(EVENT_REFRESH_DUCKS,&StateBLine_Context::event_hijack));
209         insert(event_def(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,&StateBLine_Context::event_mouse_click_handler));
210         insert(event_def(EVENT_WORKAREA_MOUSE_BUTTON_UP,&StateBLine_Context::event_mouse_release_handler));
211         insert(event_def(EVENT_WORKAREA_MOUSE_MOTION,&StateBLine_Context::event_mouse_motion_handler));
212         insert(event_def(EVENT_WORKAREA_MOUSE_BUTTON_DRAG,&StateBLine_Context::event_mouse_motion_handler));
213         insert(event_def(EVENT_REFRESH_TOOL_OPTIONS,&StateBLine_Context::event_refresh_tool_options));
214 }       
215
216 StateBLine::~StateBLine()
217 {
218 }
219
220 void
221 StateBLine_Context::load_settings()
222 {       
223         String value;
224
225         if(settings.get_value("bline.layer_region",value) && value=="0")
226                 set_layer_region_flag(false);
227         else
228                 set_layer_region_flag(true);
229
230         if(settings.get_value("bline.layer_bline",value) && value=="0")
231                 set_layer_bline_flag(false);
232         else
233                 set_layer_bline_flag(true);
234
235         if(settings.get_value("bline.layer_curve_gradient",value) && value=="1")
236                 set_layer_curve_gradient_flag(true);
237         else
238                 set_layer_curve_gradient_flag(false);
239
240         if(settings.get_value("bline.auto_export",value) && value=="1")
241                 set_auto_export_flag(true);
242         else
243                 set_auto_export_flag(false);
244
245         if(settings.get_value("bline.id",value))
246                 set_id(value);
247         else
248                 set_id("NewBLine");
249
250         if(settings.get_value("bline.feather",value))
251         {
252                 Real n = atof(value.c_str());
253                 set_feather(n);
254         }
255
256         sanity_check();
257 }
258
259 void
260 StateBLine_Context::save_settings()
261 {       
262         sanity_check();
263         settings.set_value("bline.layer_bline",get_layer_bline_flag()?"1":"0");
264         settings.set_value("bline.layer_region",get_layer_region_flag()?"1":"0");
265         settings.set_value("bline.layer_curve_gradient",get_layer_curve_gradient_flag()?"1":"0");
266         settings.set_value("bline.auto_export",get_auto_export_flag()?"1":"0");
267         settings.set_value("bline.id",get_id().c_str());
268         settings.set_value("bline.feather",strprintf("%f",get_feather()));
269 }
270
271 void
272 StateBLine_Context::reset()
273 {
274         loop_=false;
275         bline_point_list.clear();
276         refresh_ducks();
277 }
278
279 void
280 StateBLine_Context::increment_id()
281 {
282         String id(get_id());
283         int number=1;
284         int digits=0;
285         
286         if(id.empty())
287                 id="NewBLine";
288         
289         // If there is a number
290         // already at the end of the
291         // id, then remove it.
292         if(id[id.size()-1]<='9' && id[id.size()-1]>='0')
293         {
294                 // figure out how many digits it is
295                 for(digits=0;(int)id.size()-1>=digits && id[id.size()-1-digits]<='9' && id[id.size()-1-digits]>='0';digits++)while(false);
296                 
297                 String str_number;
298                 str_number=String(id,id.size()-digits,id.size());
299                 id=String(id,0,id.size()-digits);
300                 synfig::info("---------------- \"%s\"",str_number.c_str());
301                 
302                 number=atoi(str_number.c_str());
303         }
304         else
305         {
306                 number=1;
307                 digits=3;
308         }
309         
310         number++;
311         
312         // Add the number back onto the id
313         {
314                 const String format(strprintf("%%0%dd",digits));
315                 id+=strprintf(format.c_str(),number);
316         }
317         
318         // Set the ID
319         set_id(id);
320 }
321
322
323 StateBLine_Context::StateBLine_Context(CanvasView* canvas_view):
324         canvas_view_(canvas_view),
325         is_working(*canvas_view),
326         loop_(false),
327         prev_workarea_layer_status_(get_work_area()->allow_layer_clicks),
328         duckmatic_push(get_work_area()),
329         settings(synfigapp::Main::get_selected_input_device()->settings()),
330         entry_id(),
331         checkbutton_layer_region(_("Fill")),
332         checkbutton_layer_bline(_("Outline")),
333         checkbutton_layer_curve_gradient(_("Gradient")),
334         checkbutton_auto_export(_("Auto Export")),
335         button_make(_("Make")),
336         button_clear(_("Clear")),
337         adj_feather(0,0,10000,0.01,0.1),
338         spin_feather(adj_feather,0.01,4)
339 {
340         depth=-1;
341         no_egress_on_selection_change=false;
342         load_settings();
343                 
344         // Set up the tool options dialog
345         //options_table.attach(*manage(new Gtk::Label(_("BLine Tool"))), 0, 2, 0, 1, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);       
346         options_table.attach(entry_id, 0, 2, 1, 2, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
347         options_table.attach(checkbutton_layer_region, 0, 2, 2, 3, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0); 
348         options_table.attach(checkbutton_layer_bline, 0, 2, 3, 4, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);  
349         options_table.attach(checkbutton_layer_curve_gradient, 0, 2, 4, 5, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0); 
350         options_table.attach(*manage(new Gtk::Label(_("Feather"))), 0, 1, 10, 11, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);  
351         options_table.attach(spin_feather, 1, 2, 10, 11, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
352         options_table.attach(checkbutton_auto_export, 0, 2, 11, 12, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);        
353         //options_table.attach(button_make, 0, 2, 5, 6, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);    
354         //button_make.signal_pressed().connect(sigc::mem_fun(*this,&StateBLine_Context::run));
355         options_table.show_all();
356         refresh_tool_options();
357         App::dialog_tool_options->present();
358         
359         // Turn off layer clicking
360         get_work_area()->allow_layer_clicks=false;
361         
362         // clear out the ducks
363         get_work_area()->clear_ducks();
364         
365         // Refresh the work area
366         get_work_area()->queue_draw();
367         
368         // Hide the tables if they are showing
369         prev_table_status=get_canvas_view()->tables_are_visible();
370         if(prev_table_status)get_canvas_view()->hide_tables();
371                 
372         // Hide the time bar
373         get_canvas_view()->hide_timebar();
374         
375         // Connect a signal
376         //get_work_area()->signal_user_click().connect(sigc::mem_fun(*this,&studio::StateBLine_Context::on_user_click));
377         get_canvas_view()->work_area->set_cursor(Gdk::CROSSHAIR);
378
379         App::toolbox->refresh();
380 }
381
382 void
383 StateBLine_Context::refresh_tool_options()
384 {
385         App::dialog_tool_options->clear();
386         App::dialog_tool_options->set_widget(options_table);
387         App::dialog_tool_options->set_local_name(_("BLine Tool"));
388         App::dialog_tool_options->set_name("bline");
389
390         App::dialog_tool_options->add_button(
391                 Gtk::StockID("gtk-execute"),
392                 _("Make BLine and/or Region")
393         )->signal_clicked().connect(
394                 sigc::hide_return(sigc::mem_fun(
395                         *this,
396                         &StateBLine_Context::run
397                 ))
398         );
399
400         App::dialog_tool_options->add_button(
401                 Gtk::StockID("gtk-clear"),
402                 _("Clear current BLine")
403         )->signal_clicked().connect(
404                 sigc::mem_fun(
405                         *this,
406                         &StateBLine_Context::reset
407                 )
408         );
409 }
410
411 Smach::event_result
412 StateBLine_Context::event_refresh_tool_options(const Smach::event& x)
413 {
414         refresh_tool_options();
415         return Smach::RESULT_ACCEPT;
416 }
417
418 StateBLine_Context::~StateBLine_Context()
419 {
420         run();
421
422         save_settings();
423         App::dialog_tool_options->clear();
424
425         get_canvas_view()->work_area->reset_cursor();
426
427         // Restore layer clicking
428         get_work_area()->allow_layer_clicks=prev_workarea_layer_status_;
429
430         // Show the time bar
431         if(get_canvas_view()->get_canvas()->rend_desc().get_time_start()!=get_canvas_view()->get_canvas()->rend_desc().get_time_end())
432                 get_canvas_view()->show_timebar();
433
434         // Bring back the tables if they were out before
435         if(prev_table_status)get_canvas_view()->show_tables();
436
437 //      get_canvas_view()->get_smach().process_event(EVENT_REFRESH_DUCKS);
438         
439         // Refresh the work area
440         get_work_area()->queue_draw();
441
442         App::toolbox->refresh();
443 }
444
445 Smach::event_result
446 StateBLine_Context::event_stop_handler(const Smach::event& x)
447 {
448         synfig::info("STATE RotoBLine: Received Stop Event");
449 //      run();
450         reset();
451 //      throw Smach::egress_exception();
452 //      get_canvas_view()->get_smach().pop_state();
453         return Smach::RESULT_ACCEPT;
454 }
455
456 Smach::event_result
457 StateBLine_Context::event_refresh_handler(const Smach::event& x)
458 {
459         synfig::info("STATE RotoBLine: Received Refresh Event");
460         refresh_ducks();
461         return Smach::RESULT_ACCEPT;
462 }
463
464 bool
465 StateBLine_Context::run()
466 {
467         sanity_check();
468
469         String err;
470         bool success(false);
471         for(int i=5;i>0 && !success;i--)try
472         {
473                 success=run_();
474         }
475         catch(String s)
476         {
477                 err=s;
478         }
479         if(!success && !err.empty())
480         {
481                 get_canvas_view()->get_ui_interface()->error(err);
482         }
483         return success;
484 }
485
486 bool
487 StateBLine_Context::run_()
488 {
489         curr_duck=0;
490         next_duck=0;
491
492         // Now we need to generate it
493         
494         if(bline_point_list.empty())
495         {
496                 return false;
497         }
498         if(bline_point_list.size()<2)
499         {
500                 //get_canvas_view()->get_ui_interface()->error(_("You need at least two (2) points to create a BLine"));
501                 return false;
502         }
503         
504         do
505         {                       
506                 
507                 // Create the action group
508                 synfigapp::Action::PassiveGrouper group(get_canvas_interface()->get_instance().get(),_("New BLine"));
509
510                 std::vector<BLinePoint> new_list;
511                 std::list<synfig::ValueNode_Const::Handle>::iterator iter;
512                 const synfig::TransformStack& transform(get_transform_stack());
513                 
514                 for(iter=bline_point_list.begin();iter!=bline_point_list.end();++iter)
515                 {
516                         BLinePoint bline_point((*iter)->get_value().get(BLinePoint()));
517                         Point new_vertex(transform.unperform(bline_point.get_vertex()));
518                         
519                         bline_point.set_tangent1(
520                                 transform.unperform(
521                                         bline_point.get_tangent1()+bline_point.get_vertex()
522                                 ) -new_vertex
523                         );
524
525                         bline_point.set_tangent2(
526                                 transform.unperform(
527                                         bline_point.get_tangent2()+bline_point.get_vertex()
528                                 ) -new_vertex
529                         );
530                         
531                         bline_point.set_vertex(new_vertex);
532                         
533                         new_list.push_back(bline_point);
534                 }
535                         
536                 ValueNode_BLine::Handle value_node_bline(ValueNode_BLine::create(new_list));
537                 
538                 assert(value_node_bline);
539                 
540                 // Set the looping flag
541                 value_node_bline->set_loop(loop_);
542                 
543                 // Add the BLine to the canvas
544                 if(get_auto_export_flag() && !get_canvas_interface()->add_value_node(value_node_bline,get_id()))
545                 {
546                         //get_canvas_view()->get_ui_interface()->error(_("Unable to add value node"));
547                         group.cancel();
548                         increment_id();
549                         throw String(_("Unable to add value node"));
550                         return false;
551                 }
552                 
553                 Layer::Handle layer;
554                                 
555                 // we are temporarily using the layer to hold something
556                 layer=get_canvas_view()->get_selection_manager()->get_selected_layer();
557
558                 if(layer)
559                 {
560                         if(depth<0)
561                                 depth=layer->get_depth();
562                         if(!canvas)
563                                 canvas=layer->get_canvas();
564                 }
565                 else
566                         depth=0;
567                 
568                 if(!canvas)
569                         canvas=get_canvas_view()->get_canvas();
570
571                 synfigapp::SelectionManager::LayerList layer_selection;
572                 
573                 // If we were asked to create a region layer, go ahead and do so
574                 if(get_layer_region_flag())
575                 {
576                         synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
577
578                         Layer::Handle layer(get_canvas_interface()->add_layer_to("region",canvas,depth));
579                         layer_selection.push_back(layer);
580                         assert(layer);
581                         layer->set_description(get_id()+_(" Region"));
582                         get_canvas_interface()->signal_layer_new_description()(layer,layer->get_description());
583
584                         if(get_feather())
585                         {
586                                 layer->set_param("feather",get_feather());
587                                 get_canvas_interface()->signal_layer_param_changed()(layer,"feather");
588                         }
589                         
590                         if(get_layer_bline_flag())
591                                 layer->set_param("color",synfigapp::Main::get_background_color());
592                         
593                         synfigapp::Action::Handle action(synfigapp::Action::create("layer_param_connect"));
594                         
595                         assert(action);
596                         
597                         action->set_param("canvas",get_canvas());                       
598                         action->set_param("canvas_interface",get_canvas_interface());                   
599                         action->set_param("layer",layer);
600                         if(!action->set_param("param",String("bline")))
601                                 synfig::error("LayerParamConnect didn't like \"param\"");
602                         if(!action->set_param("value_node",ValueNode::Handle(value_node_bline)))
603                                 synfig::error("LayerParamConnect didn't like \"value_node\"");
604
605                         if(!get_canvas_interface()->get_instance()->perform_action(action))
606                         {
607                                 //get_canvas_view()->get_ui_interface()->error(_("Unable to create Region layer"));
608                                 group.cancel();
609                                 throw String(_("Unable to create Region layer"));
610                                 return false;
611                         }
612                 }
613
614                 // If we were asked to create a BLine layer, go ahead and do so
615                 if(get_layer_bline_flag())
616                 {
617                         synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
618
619                         Layer::Handle layer(get_canvas_interface()->add_layer_to("outline",canvas,depth));
620                         layer_selection.push_back(layer);
621                         layer->set_description(get_id()+_(" Outline"));
622                         get_canvas_interface()->signal_layer_new_description()(layer,layer->get_description());
623                         if(get_feather())
624                         {
625                                 layer->set_param("feather",get_feather());
626                                 get_canvas_interface()->signal_layer_param_changed()(layer,"feather");
627                         }
628                         
629                         assert(layer);
630
631
632                         synfigapp::Action::Handle action(synfigapp::Action::create("layer_param_connect"));
633
634                         assert(action);
635                         
636                         action->set_param("canvas",get_canvas());                       
637                         action->set_param("canvas_interface",get_canvas_interface());                   
638                         action->set_param("layer",layer);                       
639                         if(!action->set_param("param",String("bline")))
640                                 synfig::error("LayerParamConnect didn't like \"param\"");
641                         if(!action->set_param("value_node",ValueNode::Handle(value_node_bline)))
642                                 synfig::error("LayerParamConnect didn't like \"value_node\"");
643
644                         if(!get_canvas_interface()->get_instance()->perform_action(action))
645                         {
646                                 //get_canvas_view()->get_ui_interface()->error(_("Unable to create BLine layer"));
647                                 group.cancel();
648                                 throw String(_("Unable to create Outline layer"));
649                                 return false;
650                         }                       
651
652                         /*if(get_layer_region_flag() && !get_auto_export_flag())
653                         {
654                                 get_canvas_interface()->auto_export(synfigapp::ValueDesc(layer,"bline"));
655                         }*/
656                 }
657
658
659                 
660                 // If we were asked to create a CurveGradient layer, go ahead and do so
661                 if(get_layer_curve_gradient_flag())
662                 {
663                         synfigapp::PushMode push_mode(get_canvas_interface(),synfigapp::MODE_NORMAL);
664
665                         Layer::Handle layer(get_canvas_interface()->add_layer_to("curve_gradient",canvas,depth));
666                         layer_selection.push_back(layer);
667                         layer->set_description(get_id()+_(" Gradient"));
668                         get_canvas_interface()->signal_layer_new_description()(layer,layer->get_description());
669                         
670                         assert(layer);
671
672
673                         synfigapp::Action::Handle action(synfigapp::Action::create("layer_param_connect"));
674
675                         assert(action);
676                         
677                         action->set_param("canvas",get_canvas());                       
678                         action->set_param("canvas_interface",get_canvas_interface());                   
679                         action->set_param("layer",layer);                       
680                         if(!action->set_param("param",String("bline")))
681                                 synfig::error("LayerParamConnect didn't like \"param\"");
682                         if(!action->set_param("value_node",ValueNode::Handle(value_node_bline)))
683                                 synfig::error("LayerParamConnect didn't like \"value_node\"");
684
685                         if(!get_canvas_interface()->get_instance()->perform_action(action))
686                         {
687                                 //get_canvas_view()->get_ui_interface()->error(_("Unable to create BLine layer"));
688                                 group.cancel();
689                                 throw String(_("Unable to create Gradient layer"));
690                                 return false;
691                         }                       
692
693                         /*if(get_layer_region_flag() && !get_auto_export_flag())
694                         {
695                                 get_canvas_interface()->auto_export(synfigapp::ValueDesc(layer,"bline"));
696                         }*/
697                 }
698
699                 no_egress_on_selection_change=true;
700                 get_canvas_interface()->get_selection_manager()->clear_selected_layers();
701                 get_canvas_interface()->get_selection_manager()->set_selected_layers(layer_selection);
702                 no_egress_on_selection_change=false;
703                 
704                 //if(finish_bline_dialog.get_region_flag() || finish_bline_dialog.get_bline_flag())
705                 //      get_canvas_interface()->signal_dirty_preview()();
706                         
707         } while(0);
708
709         reset();
710         increment_id();
711         return true;
712 }
713
714 Smach::event_result
715 StateBLine_Context::event_mouse_motion_handler(const Smach::event& x)
716 {
717         const EventMouse& event(*reinterpret_cast<const EventMouse*>(&x));
718         
719         if(curr_duck)
720         {
721                 //synfig::info("Moved Duck");
722                 Point p(get_work_area()->snap_point_to_grid(event.pos));
723                 curr_duck->set_trans_point(p);
724                 if(next_duck)
725                         next_duck->set_trans_point(p);
726                 get_work_area()->queue_draw();
727                 return Smach::RESULT_ACCEPT;
728         }
729         
730         return Smach::RESULT_OK;
731 }
732
733 Smach::event_result
734 StateBLine_Context::event_mouse_release_handler(const Smach::event& x)
735 {
736         if(curr_duck)
737         {
738                 //synfig::info("Released current duck");
739                 curr_duck->signal_edited()(curr_duck->get_point());
740                 if(next_duck)
741                 {
742                         //synfig::info("grabbing next duck");
743                         curr_duck=next_duck;
744                         next_duck=0;
745                 }
746                 return Smach::RESULT_ACCEPT;
747         }
748         return Smach::RESULT_OK;
749 }
750
751 Smach::event_result
752 StateBLine_Context::event_mouse_click_handler(const Smach::event& x)
753 {
754         synfig::info("STATE BLINE: Received mouse button down Event");
755         const EventMouse& event(*reinterpret_cast<const EventMouse*>(&x));
756         switch(event.button)
757         {
758         case BUTTON_LEFT:
759                 {
760                         // If we are already looped up, then don't try to add anything else
761                         if(loop_)
762                                 return Smach::RESULT_OK;
763         
764                         BLinePoint bline_point;
765                         
766                         bline_point.set_vertex(get_work_area()->snap_point_to_grid(event.pos));
767                         //bline_point.set_width(synfigapp::Main::get_bline_width());
768                         bline_point.set_width(1.0f);
769                         bline_point.set_origin(0.5f);
770                         bline_point.set_split_tangent_flag(false);
771                         bline_point.set_tangent1(Vector(0,0));
772                         
773                         // set the tangent
774                         /*
775                         if(bline_point_list.empty())
776                         {
777                                 bline_point.set_tangent1(Vector(1,1));
778                         }
779                         else
780                         {
781                                 const Vector t(event.pos-bline_point_list.back()->get_value().get(BLinePoint()).get_vertex());
782                                 bline_point.set_tangent1(t);
783                         }
784                         
785                         if(bline_point_list.size()>1)
786                         {
787                                 std::list<synfig::ValueNode_Const::Handle>::iterator iter;
788                                 iter=bline_point_list.end();
789                                 iter--;iter--;
790                                 BLinePoint prev(bline_point_list.back()->get_value().get(BLinePoint()));
791                                 prev.set_tangent1(event.pos-(*iter)->get_value().get(BLinePoint()).get_vertex());
792                                 bline_point_list.back()->set_value(prev);
793                         };
794                         */
795                         
796                         bline_point_list.push_back(ValueNode_Const::create(bline_point));
797                 
798                         refresh_ducks();
799                         return Smach::RESULT_ACCEPT;
800                 }
801         
802         case BUTTON_RIGHT: // Intercept the right-button click to short-circut the pop-up menu
803                 return Smach::RESULT_ACCEPT;
804         
805         default:        
806                 return Smach::RESULT_OK;
807         }
808 }
809
810 void
811 StateBLine_Context::refresh_ducks(bool button_down)
812 {
813         get_work_area()->clear_ducks();
814         get_work_area()->queue_draw();
815         
816         if(bline_point_list.empty())
817                 return;
818
819         list<ValueNode_Const::Handle>::iterator iter;
820
821         handle<WorkArea::Bezier> bezier;
822         handle<WorkArea::Duck> duck,tduck;
823         BLinePoint bline_point;
824         
825         for(iter=bline_point_list.begin();iter!=bline_point_list.end();++iter)
826         {
827                 ValueNode_Const::Handle value_node(*iter);
828                 bline_point=(value_node->get_value().get(BLinePoint()));
829                 assert(value_node);
830
831
832                 // First add the duck associated with this vertex               
833                 duck=new WorkArea::Duck(bline_point.get_vertex());
834                 duck->set_editable(true);
835                 duck->set_type(Duck::TYPE_VERTEX);
836                 duck->set_name(strprintf("%x-vertex",value_node.get()));
837                 duck->signal_edited().connect(
838                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_vertex_change),value_node)
839                 );
840                 duck->signal_user_click(2).connect(
841                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::popup_vertex_menu),value_node)
842                 );
843                 duck->set_guid(value_node->get_guid()^GUID::hasher(0));
844
845                 get_work_area()->add_duck(duck);                        
846
847                 // Add the tangent1 duck
848                 tduck=new WorkArea::Duck(bline_point.get_tangent1());
849                 tduck->set_editable(true);
850                 tduck->set_name(strprintf("%x-tangent1",value_node.get()));
851                 tduck->set_origin(duck);
852                 tduck->set_scalar(-0.33333333333333333);
853                 tduck->set_tangent(true);
854                 tduck->set_guid(value_node->get_guid()^GUID::hasher(3));
855                 tduck->signal_edited().connect(
856                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_tangent1_change),value_node)
857                 );
858                 tduck->signal_user_click(2).connect(
859                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::popup_handle_menu),value_node)
860                 );
861                 
862                 // See if we need to add that duck to the previous bezier
863                 if(bezier)
864                 {
865                         get_work_area()->add_duck(tduck);                       
866                         bezier->p2=duck;
867                         bezier->c2=tduck;
868
869                         bezier->signal_user_click(2).connect(
870                                 sigc::bind(
871                                         sigc::mem_fun(
872                                                 *this,
873                                                 &studio::StateBLine_Context::popup_bezier_menu
874                                         ),
875                                         value_node
876                                 )
877                         );
878
879                         //get_work_area()->add_duck(bezier->c1);                        
880                         //get_work_area()->add_duck(bezier->c2);                        
881                         get_work_area()->add_bezier(bezier);
882
883                         bezier=0;
884                 }
885                 
886                 // Now we see if we need to create a bezier
887                 list<ValueNode_Const::Handle>::iterator next(iter);
888                 next++;
889                 
890                 // If our next iterator is the end, then we don't need
891                 // to add a bezier.
892                 //if(next==bline_point_list.end() && !loop_)
893                 //      continue;
894                 
895                 bezier=new WorkArea::Bezier();
896
897                 // Add the tangent2 duck
898                 tduck=new WorkArea::Duck(bline_point.get_tangent2());
899                 tduck->set_editable(true);
900                 tduck->set_origin(duck);
901                 tduck->set_scalar(0.33333333333333333);
902                 tduck->set_tangent(true);
903                 if(bline_point.get_split_tangent_flag())
904                 {
905                         tduck->set_name(strprintf("%x-tangent2",value_node.get()));
906                         tduck->signal_edited().connect(
907                                 sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_tangent2_change),value_node)
908                         );
909                 }
910                 else
911                 {
912                         tduck->set_name(strprintf("%x-tangent1",value_node.get()));
913                         tduck->signal_edited().connect(
914                                 sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_tangent1_change),value_node)
915                         );
916                 }
917                 tduck->set_guid(value_node->get_guid()^GUID::hasher(4));
918                 tduck->signal_user_click(2).connect(
919                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::popup_handle_menu),value_node)
920                 );
921                 
922                 // Setup the next bezier
923                 bezier->p1=duck;
924                 bezier->c1=tduck;
925
926                 get_work_area()->add_duck(tduck);                       
927                 curr_duck=tduck;
928         }
929         
930         // Add the loop, if requested
931         if(bezier && loop_)
932         {
933                 curr_duck=0;
934                 BLinePoint bline_point(bline_point_list.front()->get_value().get(BLinePoint()));
935
936                 duck=new WorkArea::Duck(bline_point.get_vertex());
937                 duck->set_editable(true);
938                 duck->set_name(strprintf("%x-vertex",bline_point_list.front().get()));
939                 duck->signal_edited().connect(
940                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_vertex_change),bline_point_list.front())
941                 );
942                 duck->signal_user_click(2).connect(
943                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::popup_vertex_menu),bline_point_list.front())
944                 );
945                 get_work_area()->add_duck(duck);                        
946
947                 // Add the tangent1 duck
948                 tduck=new WorkArea::Duck(bline_point.get_tangent1());
949                 tduck->set_editable(true);
950                 tduck->set_name(strprintf("%x-tangent1",bline_point_list.front().get()));
951                 tduck->set_origin(duck);
952                 tduck->set_scalar(-0.33333333333333333);
953                 tduck->set_tangent(true);
954                 tduck->signal_edited().connect(
955                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::on_tangent1_change),bline_point_list.front())
956                 );
957                 tduck->signal_user_click(2).connect(
958                         sigc::bind(sigc::mem_fun(*this,&studio::StateBLine_Context::popup_handle_menu),bline_point_list.front())
959                 );
960                 get_work_area()->add_duck(tduck);                       
961                 
962                 bezier->p2=duck;
963                 bezier->c2=tduck;
964
965                 bezier->signal_user_click(2).connect(
966                         sigc::bind(
967                                 sigc::mem_fun(
968                                         *this,
969                                         &studio::StateBLine_Context::popup_bezier_menu
970                                 ),
971                                 bline_point_list.front()
972                         )
973                 );
974
975                 //get_work_area()->add_duck(bezier->c1);                        
976                 get_work_area()->add_bezier(bezier);
977         }
978         if(bezier && !loop_)
979         {
980                 duck=new WorkArea::Duck(bline_point.get_vertex());
981                 duck->set_editable(false);
982                 duck->set_name("temp");
983
984                 // Add the tangent1 duck
985                 tduck=new WorkArea::Duck(Vector(0,0));
986                 tduck->set_editable(false);
987                 tduck->set_name("ttemp");
988                 tduck->set_origin(duck);
989                 tduck->set_scalar(-0.33333333333333333);
990
991                 tduck->set_tangent(true);
992                 bezier->p2=duck;
993                 bezier->c2=tduck;
994
995                 get_work_area()->add_duck(bezier->p2);                  
996                 //get_work_area()->add_duck(bezier->c2);                        
997                 get_work_area()->add_bezier(bezier);
998
999                 duck->set_guid(GUID());
1000                 tduck->set_guid(GUID());
1001                 
1002                 next_duck=duck;
1003         }
1004         
1005         if(!button_down)
1006         {
1007                 if(curr_duck)
1008                 {
1009                         if(next_duck)
1010                         {
1011                                 curr_duck=next_duck;
1012                                 next_duck=0;
1013                         }
1014                 }
1015         }
1016         get_work_area()->queue_draw();                  
1017 }
1018
1019
1020 bool
1021 StateBLine_Context::on_vertex_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node)
1022 {
1023         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1024         bline_point.set_vertex(point);
1025         value_node->set_value(bline_point);
1026         //refresh_ducks();
1027         return true;
1028 }
1029
1030 bool
1031 StateBLine_Context::on_tangent1_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node)
1032 {
1033         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1034         bline_point.set_tangent1(point);
1035         value_node->set_value(bline_point);
1036         //refresh_ducks();
1037         return true;
1038 }
1039
1040 bool
1041 StateBLine_Context::on_tangent2_change(const synfig::Point &point, synfig::ValueNode_Const::Handle value_node)
1042 {
1043         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1044         bline_point.set_tangent2(point);
1045         value_node->set_value(bline_point);
1046         //refresh_ducks();
1047         return true;
1048 }
1049
1050 void
1051 StateBLine_Context::loop_bline()
1052 {
1053         loop_=true;
1054
1055         refresh_ducks(false);
1056 }
1057
1058 void
1059 StateBLine_Context::unloop_bline()
1060 {
1061         loop_=false;
1062
1063         refresh_ducks(false);
1064 }
1065
1066 void
1067 StateBLine_Context::popup_vertex_menu(synfig::ValueNode_Const::Handle value_node)
1068 {
1069         menu.items().clear();
1070
1071         if(loop_)
1072         {
1073                 menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Unloop BLine",
1074                                 sigc::mem_fun(*this,&studio::StateBLine_Context::unloop_bline)
1075                 ));
1076         } else {
1077                 menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Loop BLine",
1078                                 sigc::mem_fun(*this,&studio::StateBLine_Context::loop_bline)
1079                 ));
1080         }
1081         
1082         menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Delete Vertex",
1083                 sigc::bind(
1084                         sigc::mem_fun(*this,&studio::StateBLine_Context::bline_delete_vertex),
1085                         value_node
1086                 )
1087         ));
1088
1089         menu.popup(0,0);
1090 }
1091
1092 void
1093 StateBLine_Context::popup_bezier_menu(float location, synfig::ValueNode_Const::Handle value_node)
1094 {
1095         menu.items().clear();
1096
1097         menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Insert Vertex",
1098                 sigc::bind(
1099                         sigc::bind(
1100                                 sigc::mem_fun(*this,&studio::StateBLine_Context::bline_insert_vertex),
1101                                 location
1102                         ),
1103                         value_node
1104                 )
1105         ));
1106
1107         menu.popup(0,0);
1108 }
1109
1110 void
1111 StateBLine_Context::bline_insert_vertex(synfig::ValueNode_Const::Handle value_node, float origin)
1112 {
1113         list<ValueNode_Const::Handle>::iterator iter;
1114         
1115         for(iter=bline_point_list.begin();iter!=bline_point_list.end();++iter)
1116                 if(*iter==value_node)
1117                 {
1118                         list<ValueNode_Const::Handle>::iterator prev(iter);
1119                         --prev;
1120
1121                         BLinePoint bline_point;
1122                         
1123                         BLinePoint next_bline_point((*iter)->get_value().get(BLinePoint()));
1124                         BLinePoint prev_bline_point;
1125                         
1126                         if(iter!=bline_point_list.begin())
1127                         {
1128                                 prev_bline_point=(*prev)->get_value().get(BLinePoint());
1129                         }
1130                         else
1131                         {
1132                                 prev_bline_point.set_vertex(Point(0,0));
1133                                 prev_bline_point.set_width(next_bline_point.get_width());
1134                                 prev_bline_point.set_origin(0.5);
1135                                 prev_bline_point.set_split_tangent_flag(false);
1136                         }
1137
1138                         etl::hermite<Vector> curve(prev_bline_point.get_vertex(),next_bline_point.get_vertex(),prev_bline_point.get_tangent2(),next_bline_point.get_tangent1());
1139                         etl::derivative< etl::hermite<Vector> > deriv(curve);
1140
1141                         bline_point.set_vertex(curve(origin));
1142                         bline_point.set_width((next_bline_point.get_width()-prev_bline_point.get_width())*origin+prev_bline_point.get_width());
1143 #ifdef ETL_FIXED_DERIVATIVE
1144                         bline_point.set_tangent1(deriv(origin)*std::min(1.0f-origin,origin));
1145 #else
1146                         bline_point.set_tangent1(-deriv(origin)*std::min(1.0f-origin,origin));
1147 #endif
1148                         bline_point.set_tangent2(bline_point.get_tangent1());
1149                         bline_point.set_split_tangent_flag(false);
1150                         bline_point.set_origin(origin);
1151                         
1152 /*
1153                         bline_point.set_vertex((next_bline_point.get_vertex()+prev_bline_point.get_vertex())*0.5);
1154                         bline_point.set_width((next_bline_point.get_width()+prev_bline_point.get_width())*0.5);
1155                         bline_point.set_origin(origin);
1156                         bline_point.set_split_tangent_flag(false);
1157                         bline_point.set_tangent1((next_bline_point.get_vertex()-prev_bline_point.get_vertex())*0.5);
1158 */
1159
1160                         bline_point_list.insert(iter,ValueNode_Const::create(bline_point));
1161                         break;
1162                 }
1163
1164         if(iter==bline_point_list.end())
1165         {
1166                 get_canvas_view()->get_ui_interface()->error("Unable to find where to insert vertex, internal error, please report this bug");
1167         }
1168
1169         refresh_ducks(false);   
1170 }
1171
1172 void
1173 StateBLine_Context::bline_delete_vertex(synfig::ValueNode_Const::Handle value_node)
1174 {
1175         list<ValueNode_Const::Handle>::iterator iter;
1176         
1177         for(iter=bline_point_list.begin();iter!=bline_point_list.end();++iter)
1178                 if(*iter==value_node)
1179                 {
1180                         bline_point_list.erase(iter);
1181                         break;
1182                 }
1183         if(iter==bline_point_list.end())
1184         {
1185                 get_canvas_view()->get_ui_interface()->error("Unable to remove vertex, internal error, please report this bug");
1186         }
1187
1188         refresh_ducks(false);   
1189 }
1190
1191 void
1192 StateBLine_Context::popup_handle_menu(synfig::ValueNode_Const::Handle value_node)
1193 {
1194         menu.items().clear();
1195
1196         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1197
1198         if(bline_point.get_split_tangent_flag())
1199                 menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Merge Tangents",
1200                         sigc::bind(
1201                                 sigc::mem_fun(*this,&studio::StateBLine_Context::bline_attach_handle),
1202                                 value_node
1203                         )
1204                 ));
1205         else
1206                 menu.items().push_back(Gtk::Menu_Helpers::MenuElem("Split Tangents",
1207                         sigc::bind(
1208                                 sigc::mem_fun(*this,&studio::StateBLine_Context::bline_detach_handle),
1209                                 value_node
1210                         )
1211                 ));
1212
1213         menu.popup(0,0);
1214 }
1215
1216 void
1217 StateBLine_Context::bline_detach_handle(synfig::ValueNode_Const::Handle value_node)
1218 {
1219         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1220         bline_point.set_split_tangent_flag(true);
1221         bline_point.set_tangent2(bline_point.get_tangent1());
1222         value_node->set_value(bline_point);
1223         refresh_ducks(false);
1224 }
1225
1226 void
1227 StateBLine_Context::bline_attach_handle(synfig::ValueNode_Const::Handle value_node)
1228 {
1229         BLinePoint bline_point(value_node->get_value().get(BLinePoint()));
1230         bline_point.set_tangent1((bline_point.get_tangent1()+bline_point.get_tangent2())*0.5);
1231         bline_point.set_split_tangent_flag(false);
1232         value_node->set_value(bline_point);
1233         refresh_ducks(false);
1234 }