Fix a crash when running single-threaded and dragging the time slider.
[synfig.git] / synfig-studio / trunk / src / gtkmm / workarea.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file workarea.cpp
3 **      \brief Template Header
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright 2006 Yue Shi Lai
10 **      Copyright (c) 2007 Chris Moore
11 **
12 **      This package is free software; you can redistribute it and/or
13 **      modify it under the terms of the GNU General Public License as
14 **      published by the Free Software Foundation; either version 2 of
15 **      the License, or (at your option) any later version.
16 **
17 **      This package is distributed in the hope that it will be useful,
18 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 **      General Public License for more details.
21 **      \endlegal
22 */
23 /* ========================================================================= */
24
25 /* === H E A D E R S ======================================================= */
26
27 #ifdef USING_PCH
28 #       include "pch.h"
29 #else
30 #ifdef HAVE_CONFIG_H
31 #       include <config.h>
32 #endif
33
34 #include <sigc++/adaptors/hide.h>
35
36 #include "workarea.h"
37 #include "canvasview.h"
38 #include "app.h"
39 #include <gtkmm/window.h>
40 #include <gtkmm/image.h>
41 #include <gtkmm/drawingarea.h>
42 #include <gtkmm/ruler.h>
43 #include <gtkmm/arrow.h>
44 #include <gtkmm/image.h>
45 #include <gtkmm/scrollbar.h>
46 #include <cmath>
47 #include <sigc++/retype_return.h>
48 #include <sigc++/retype.h>
49 #include <sigc++/hide.h>
50 #include <ETL/misc>
51
52 #include <synfig/target_scanline.h>
53 #include <synfig/target_tile.h>
54 #include <synfig/surface.h>
55 #include <synfig/valuenode_composite.h>
56 #include <synfigapp/canvasinterface.h>
57 #include "event_mouse.h"
58 #include "event_layerclick.h"
59 #include "widget_color.h"
60 #include <synfig/distance.h>
61 #include "workarearenderer.h"
62
63 #include "renderer_canvas.h"
64 #include "renderer_grid.h"
65 #include "renderer_guides.h"
66 #include "renderer_timecode.h"
67 #include "renderer_ducks.h"
68 #include "renderer_dragbox.h"
69 #include "renderer_bbox.h"
70 #include "asyncrenderer.h"
71 #include <gtkmm/frame.h>
72
73 #include <synfig/mutex.h>
74
75 #endif
76
77 /* === U S I N G =========================================================== */
78
79 using namespace std;
80 using namespace etl;
81 using namespace synfig;
82 using namespace studio;
83
84 /* === M A C R O S ========================================================= */
85
86 #define RULER_FIX               15
87
88 #ifndef stratof
89 #define stratof(X) (atof((X).c_str()))
90 #define stratoi(X) (atoi((X).c_str()))
91 #endif
92
93
94 /* === G L O B A L S ======================================================= */
95
96 /* === C L A S S E S ======================================================= */
97
98 class studio::WorkAreaTarget : public synfig::Target_Tile
99 {
100 public:
101         WorkArea *workarea;
102         bool low_res;
103         int w,h;
104         int real_tile_w,real_tile_h;
105         //std::vector<Glib::RefPtr<Gdk::Pixbuf> >::iterator tile_iter;
106
107         int twindow_start, twindow_width, twindow_height, twindow_pad;
108         int refresh_id;
109
110         bool onionskin;
111         bool onion_first_tile;
112         int onion_layers;
113
114         std::list<synfig::Time> onion_skin_queue;
115
116         synfig::Mutex mutex;
117
118         void set_onion_skin(bool x)
119         {
120                 onionskin=x;
121
122                 Time time(rend_desc().get_time_start());
123
124                 onion_skin_queue.push_back(time);
125                 //onion_skin_queue.push_back(time-1);
126                 //onion_skin_queue.push_back(time+1);
127
128                 try
129                 {
130                         onion_skin_queue.push_back(
131                                 get_canvas()->keyframe_list().find_prev(
132                                         time
133                                 )->get_time()
134                         );
135                 }
136                 catch(...)
137                 {  }
138
139                 try
140                 {
141                         onion_skin_queue.push_back(
142                                 get_canvas()->keyframe_list().find_next(
143                                         time
144                                 )->get_time()
145                         );
146                 }
147                 catch(...)
148                 {  }
149
150                 onion_layers=onion_skin_queue.size();
151
152                 onion_first_tile=false;
153         }
154 public:
155
156         WorkAreaTarget(WorkArea *workarea,int w, int h):
157                 workarea(workarea),
158                 low_res(workarea->get_low_resolution_flag()),
159                 w(w),
160                 h(h),
161                 real_tile_w(workarea->tile_w),
162                 real_tile_h(workarea->tile_h),
163                 refresh_id(workarea->refreshes),
164                 onionskin(false),
165                 onion_layers(0)
166         {
167                 //set_remove_alpha();
168                 //set_avoid_time_sync();
169                 set_clipping(true);
170                 if(low_res)
171                 {
172                         set_tile_w(workarea->tile_w/2);
173                         set_tile_h(workarea->tile_h/2);
174                 }
175                 else
176                 {
177                         set_tile_w(workarea->tile_w);
178                         set_tile_h(workarea->tile_h);
179                 }
180                 set_canvas(workarea->get_canvas());
181                 set_quality(workarea->get_quality());
182         }
183
184         ~WorkAreaTarget()
185         {
186                 workarea->queue_draw();
187         }
188
189         virtual bool set_rend_desc(synfig::RendDesc *newdesc)
190         {
191                 assert(workarea);
192                 newdesc->set_flags(RendDesc::PX_ASPECT|RendDesc::IM_SPAN);
193                 if(low_res)
194                         newdesc->set_wh(w/2,h/2);
195                 else
196                         newdesc->set_wh(w,h);
197
198                 if(
199                                 workarea->get_w()!=w
200                         ||      workarea->get_h()!=h
201                 ) workarea->set_wh(w,h,4);
202
203                 workarea->full_frame=false;
204
205                 desc=*newdesc;
206                 return true;
207         }
208
209         virtual int total_tiles()const
210         {
211                 int tw(rend_desc().get_w()/get_tile_w());
212                 int th(rend_desc().get_h()/get_tile_h());
213                 if(rend_desc().get_w()%get_tile_w()!=0)tw++;
214                 if(rend_desc().get_h()%get_tile_h()!=0)th++;
215                 return tw*th;
216         }
217
218         virtual int next_frame(Time& time)
219         {
220                 synfig::Mutex::Lock lock(mutex);
221
222                 if(!onionskin)
223                         return synfig::Target_Tile::next_frame(time);
224
225                 onion_first_tile=(onion_layers==(signed)onion_skin_queue.size());
226
227                 if(!onion_skin_queue.empty())
228                 {
229                         time=onion_skin_queue.front();
230                         onion_skin_queue.pop_front();
231                 }
232                 else
233                         return 0;
234
235                 return onion_skin_queue.size()+1;
236         }
237
238         virtual int next_tile(int& x, int& y)
239         {
240                 synfig::Mutex::Lock lock(mutex);
241                 //if(workarea->tile_queue.empty()) return 0;
242
243                 //int curr_tile(workarea->tile_queue.front());
244                 //workarea->tile_queue.pop_front();
245                 int curr_tile(workarea->next_unrendered_tile(refresh_id-onion_skin_queue.size()));
246                 if(curr_tile<0)
247                         return 0;
248
249                 // Width of the image(in tiles)
250                 int tw(rend_desc().get_w()/get_tile_w());
251                 if(rend_desc().get_w()%get_tile_w()!=0)tw++;
252
253                 y=(curr_tile/tw)*get_tile_w();
254                 x=(curr_tile%tw)*get_tile_h();
255
256                 // Mark this tile as "up-to-date"
257                 if(onionskin)
258                         workarea->tile_book[curr_tile].second=refresh_id-onion_skin_queue.size();
259                 else
260                         workarea->tile_book[curr_tile].second=refresh_id;
261
262                 return total_tiles()-curr_tile+1;
263         }
264
265
266         virtual bool start_frame(synfig::ProgressCallback */*cb*/)
267         {
268                 synfig::Mutex::Lock lock(mutex);
269
270                 int tw(rend_desc().get_w()/get_tile_w());
271                 if(rend_desc().get_w()%get_tile_w()!=0)tw++;
272                 int th(rend_desc().get_h()/get_tile_h());
273                 if(rend_desc().get_h()%get_tile_h()!=0)th++;
274
275                 twindow_start=0;
276                 twindow_width=tw;
277                 twindow_height=th;
278                 twindow_pad=0;
279
280                 workarea->tile_book.resize(total_tiles());
281                 //tile_iter=workarea->tile_book.begin()+twindow_start;
282                 return true;
283         }
284
285         static void free_buff(const guint8 *x) { free(const_cast<guint8*>(x)); }
286
287         virtual bool add_tile(const synfig::Surface &surface, int x, int y)
288         {
289                 synfig::Mutex::Lock lock(mutex);
290                 assert(surface);
291
292                 PixelFormat pf(PF_RGB);
293
294                 const int total_bytes(get_tile_w()*get_tile_h()*synfig::channels(pf));
295
296                 unsigned char *buffer((unsigned char*)malloc(total_bytes));
297
298                 if(!surface || !buffer)
299                         return false;
300                 {
301                         unsigned char *dest(buffer);
302                         const Color *src(surface[0]);
303                         int w(get_tile_w());
304                         int h(get_tile_h());
305                         int x(surface.get_w()*surface.get_h());
306                         //if(low_res) { w/=2,h/=2; }
307                         Color dark(0.6,0.6,0.6);
308                         Color lite(0.8,0.8,0.8);
309                         for(int i=0;i<x;i++)
310                                 dest=Color2PixelFormat(
311                                         Color::blend(
312                                                 (*(src++)),
313                                                 ((i/surface.get_w())*8/h+(i%surface.get_w())*8/w)&1?dark:lite,
314                                                 1.0f
315                                         ).clamped(),
316                                         pf,dest,App::gamma
317                                 );
318                 }
319
320                 x/=get_tile_w();
321                 y/=get_tile_h();
322                 int tw(rend_desc().get_w()/get_tile_w());
323                 if(rend_desc().get_w()%get_tile_w()!=0)tw++;
324                 unsigned int index=y*tw+x;
325
326                 // Sanity check
327                 if(index>workarea->tile_book.size())
328                         return false;
329
330                 Glib::RefPtr<Gdk::Pixbuf> pixbuf;
331
332                 pixbuf=Gdk::Pixbuf::create_from_data(
333                         buffer, // pointer to the data
334                         Gdk::COLORSPACE_RGB, // the colorspace
335                         ((pf&PF_A)==PF_A), // has alpha?
336                         8, // bits per sample
337                         surface.get_w(),        // width
338                         surface.get_h(),        // height
339                         surface.get_w()*synfig::channels(pf), // stride (pitch)
340                         sigc::ptr_fun(&WorkAreaTarget::free_buff)
341                 );
342
343                 if(low_res)
344                 {
345                         // We need to scale up
346                         pixbuf=pixbuf->scale_simple(
347                                 surface.get_w()*2,
348                                 surface.get_h()*2,
349                                 Gdk::INTERP_NEAREST
350                         );
351                 }
352
353                 if(!onionskin || onion_first_tile || !workarea->tile_book[index].first)
354                 {
355                         workarea->tile_book[index].first=pixbuf;
356                 }
357                 else
358                 {
359                         pixbuf->composite(
360                                 workarea->tile_book[index].first, // Dest
361                                 0,//int dest_x
362                                 0,//int dest_y
363                                 pixbuf->get_width(), // dest width
364                                 pixbuf->get_height(), // dest_height,
365                                 0, // double offset_x
366                                 0, // double offset_y
367                                 1, // double scale_x
368                                 1, // double scale_y
369                                 Gdk::INTERP_NEAREST, // interp
370                                 255/(onion_layers-onion_skin_queue.size()+1) //int overall_alpha
371                         );
372                 }
373
374                 //if(index%2)
375                         workarea->queue_draw();
376                 assert(workarea->tile_book[index].first);
377                 return true;
378         }
379
380         virtual void end_frame()
381         {
382                 //workarea->queue_draw();
383         }
384 };
385
386
387 class studio::WorkAreaTarget_Full : public synfig::Target_Scanline
388 {
389 public:
390         WorkArea *workarea;
391         bool low_res;
392         int w,h;
393         int real_tile_w,real_tile_h;
394         //std::vector<Glib::RefPtr<Gdk::Pixbuf> >::iterator tile_iter;
395
396         int twindow_start, twindow_width, twindow_height, twindow_pad;
397         int refresh_id;
398
399         bool onionskin;
400         bool onion_first_tile;
401         int onion_layers;
402
403         Surface surface;
404
405         std::list<synfig::Time> onion_skin_queue;
406
407         void set_onion_skin(bool x)
408         {
409                 onionskin=x;
410
411                 Time time(rend_desc().get_time_start());
412
413                 onion_skin_queue.push_back(time);
414                 //onion_skin_queue.push_back(time-1);
415                 //onion_skin_queue.push_back(time+1);
416                 if(!onionskin)
417                         return;
418
419                 try
420                 {
421                         onion_skin_queue.push_back(
422                                 get_canvas()->keyframe_list().find_prev(
423                                         time
424                                 )->get_time()
425                         );
426                 }
427                 catch(...)
428                 {  }
429
430                 try
431                 {
432                         onion_skin_queue.push_back(
433                                 get_canvas()->keyframe_list().find_next(
434                                         time
435                                 )->get_time()
436                         );
437                 }
438                 catch(...)
439                 {  }
440
441                 onion_layers=onion_skin_queue.size();
442
443                 onion_first_tile=false;
444         }
445 public:
446
447         WorkAreaTarget_Full(WorkArea *workarea,int w, int h):
448                 workarea(workarea),
449                 low_res(workarea->get_low_resolution_flag()),
450                 w(w),
451                 h(h),
452                 refresh_id(workarea->refreshes),
453                 onionskin(false),
454                 onion_layers(0)
455         {
456                 set_canvas(workarea->get_canvas());
457                 set_quality(workarea->get_quality());
458         }
459
460         ~WorkAreaTarget_Full()
461         {
462         }
463
464         virtual bool set_rend_desc(synfig::RendDesc *newdesc)
465         {
466                 assert(workarea);
467                 newdesc->set_flags(RendDesc::PX_ASPECT|RendDesc::IM_SPAN);
468                 if(low_res)
469                         newdesc->set_wh(w/2,h/2);
470                 else
471                         newdesc->set_wh(w,h);
472
473                 if(
474                                 workarea->get_w()!=w
475                         ||      workarea->get_h()!=h
476                 ) workarea->set_wh(w,h,4);
477
478                 surface.set_wh(newdesc->get_w(),newdesc->get_h());
479
480                 desc=*newdesc;
481                 workarea->full_frame=true;
482                 workarea->tile_book.resize(1);
483                 return true;
484         }
485
486         virtual int next_frame(Time& time)
487         {
488                 // Mark this tile as "up-to-date"
489                 if(onionskin)
490                         workarea->tile_book[0].second=refresh_id-onion_skin_queue.size();
491                 else
492                         workarea->tile_book[0].second=refresh_id;
493
494                 if(!onionskin)
495                         return synfig::Target_Scanline::next_frame(time);
496
497                 onion_first_tile=(onion_layers==(signed)onion_skin_queue.size());
498
499                 if(!onion_skin_queue.empty())
500                 {
501                         time=onion_skin_queue.front();
502                         onion_skin_queue.pop_front();
503                 }
504                 else
505                         return 0;
506                 return onion_skin_queue.size()+1;
507         }
508
509
510         virtual bool start_frame(synfig::ProgressCallback */*cb*/)
511         {
512                 return true;
513         }
514
515         virtual Color * start_scanline(int scanline)
516         {
517                 return surface[scanline];
518         }
519
520         virtual bool end_scanline()
521         {
522                 return true;
523         }
524
525         static void free_buff(const guint8 *x) { free(const_cast<guint8*>(x)); }
526
527         virtual void end_frame()
528         {
529                 assert(surface);
530
531                 PixelFormat pf(PF_RGB);
532
533                 const int total_bytes(surface.get_w()*surface.get_h()*synfig::channels(pf));
534
535                 unsigned char *buffer((unsigned char*)malloc(total_bytes));
536
537                 if(!surface || !buffer)
538                         return;
539                 {
540                         unsigned char *dest(buffer);
541                         const Color *src(surface[0]);
542                         int w(surface.get_w());
543                         //int h(surface.get_h());
544                         int x(surface.get_w()*surface.get_h());
545                         //if(low_res) { w/=2,h/=2; }
546                         Color dark(0.6,0.6,0.6);
547                         Color lite(0.8,0.8,0.8);
548                         int tw=workarea->tile_w;
549                         int th=workarea->tile_h;
550                         if(low_res)
551                         {
552                                 tw/=2;
553                                 th/=2;
554                         }
555                         for(int i=0;i<x;i++)
556                                 dest=Color2PixelFormat(
557                                         Color::blend(
558                                                 (*(src++)),
559                                                 ((i/w)*8/th+(i%w)*8/tw)&1?dark:lite,
560                                                 1.0f
561                                         ).clamped(),
562                                         pf,
563                                         dest,
564                                         App::gamma
565                                 );
566                 }
567
568                 Glib::RefPtr<Gdk::Pixbuf> pixbuf;
569
570                 pixbuf=Gdk::Pixbuf::create_from_data(
571                         buffer, // pointer to the data
572                         Gdk::COLORSPACE_RGB, // the colorspace
573                         ((pf&PF_A)==PF_A), // has alpha?
574                         8, // bits per sample
575                         surface.get_w(),        // width
576                         surface.get_h(),        // height
577                         surface.get_w()*synfig::channels(pf), // stride (pitch)
578                         sigc::ptr_fun(&WorkAreaTarget::free_buff)
579                 );
580
581                 if(low_res)
582                 {
583                         // We need to scale up
584                         pixbuf=pixbuf->scale_simple(
585                                 surface.get_w()*2,
586                                 surface.get_h()*2,
587                                 Gdk::INTERP_NEAREST
588                         );
589                 }
590
591                 int index=0;
592
593                 if(!onionskin || onion_first_tile || !workarea->tile_book[index].first)
594                 {
595                         workarea->tile_book[index].first=pixbuf;
596                 }
597                 else
598                 {
599                         pixbuf->composite(
600                                 workarea->tile_book[index].first, // Dest
601                                 0,//int dest_x
602                                 0,//int dest_y
603                                 pixbuf->get_width(), // dest width
604                                 pixbuf->get_height(), // dest_height,
605                                 0, // double offset_x
606                                 0, // double offset_y
607                                 1, // double scale_x
608                                 1, // double scale_y
609                                 Gdk::INTERP_NEAREST, // interp
610                                 255/(onion_layers-onion_skin_queue.size()+1) //int overall_alpha
611                         );
612                 }
613
614                 workarea->queue_draw();
615                 assert(workarea->tile_book[index].first);
616         }
617 };
618
619
620
621
622 /* === M E T H O D S ======================================================= */
623
624
625 WorkArea::WorkArea(etl::loose_handle<synfigapp::CanvasInterface> canvas_interface):
626         Gtk::Table(4+RULER_FIX, 3, false),
627         canvas_interface(canvas_interface),
628         canvas(canvas_interface->get_canvas()),
629         scrollx_adjustment(0,-4,4,0.01,0.1),
630         scrolly_adjustment(0,-4,4,0.01,0.1),
631         w(128),
632         h(128),
633         last_event_time(0),
634         progresscallback(0),
635         dragging(DRAG_NONE),
636         show_grid(false),
637         tile_w(128),
638         tile_h(128),
639         timecode_width(0),
640         timecode_height(0)
641 {
642         show_guides=true;
643         curr_input_device=0;
644         full_frame=false;
645         allow_duck_clicks=true;
646         allow_layer_clicks=true;
647         render_idle_func_id=0;
648         zoom=prev_zoom=1.0;
649         quality=10;
650         rendering=false;
651         canceled_=false;
652         low_resolution=true;
653         pw=0.001;
654         ph=0.001;
655         last_focus_point=Point(0,0);
656         onion_skin=false;
657         queued=false;
658         dirty_trap_enabled=false;
659         solid_lines=true;
660
661         dirty_trap_queued=0;
662
663         meta_data_lock=false;
664
665         insert_renderer(new Renderer_Canvas,    000);
666         insert_renderer(new Renderer_Grid,              100);
667         insert_renderer(new Renderer_Guides,    200);
668         insert_renderer(new Renderer_Ducks,             300);
669         insert_renderer(new Renderer_BBox,              399);
670         insert_renderer(new Renderer_Dragbox,   400);
671         insert_renderer(new Renderer_Timecode,  500);
672
673         signal_duck_selection_changed().connect(sigc::mem_fun(*this,&studio::WorkArea::queue_draw));
674         signal_strokes_changed().connect(sigc::mem_fun(*this,&studio::WorkArea::queue_draw));
675         signal_grid_changed().connect(sigc::mem_fun(*this,&studio::WorkArea::queue_draw));
676         signal_grid_changed().connect(sigc::mem_fun(*this,&studio::WorkArea::save_meta_data));
677         signal_sketch_saved().connect(sigc::mem_fun(*this,&studio::WorkArea::save_meta_data));
678
679         // Not that it really makes a difference... (setting this to zero, that is)
680         refreshes=0;
681
682         drawing_area=manage(new class Gtk::DrawingArea());
683         drawing_area->show();
684         drawing_area->set_extension_events(Gdk::EXTENSION_EVENTS_ALL);
685
686         drawing_frame=manage(new Gtk::Frame);
687         drawing_frame->add(*drawing_area);
688         //drawing_frame->set_shadow_type(Gtk::SHADOW_NONE);
689         //drawing_frame->property_border_width()=5;
690         //drawing_frame->modify_fg(Gtk::STATE_NORMAL,Gdk::Color("#00ffff"));
691         //drawing_frame->modify_base(Gtk::STATE_NORMAL,Gdk::Color("#ff00ff"));
692         /*drawing_frame->modify_fg(Gtk::STATE_ACTIVE,Gdk::Color("#00ffff"));
693         drawing_frame->modify_base(Gtk::STATE_ACTIVE,Gdk::Color("#ff00ff"));
694         drawing_frame->modify_bg(Gtk::STATE_ACTIVE,Gdk::Color("#00ff00"));
695         drawing_frame->modify_fg(Gtk::STATE_INSENSITIVE,Gdk::Color("#00ffff"));
696         drawing_frame->modify_base(Gtk::STATE_INSENSITIVE,Gdk::Color("#ff00ff"));
697         drawing_frame->modify_bg(Gtk::STATE_INSENSITIVE,Gdk::Color("#00ff00"));
698         drawing_frame->modify_fg(Gtk::STATE_SELECTED,Gdk::Color("#00ffff"));
699         drawing_frame->modify_base(Gtk::STATE_SELECTED,Gdk::Color("#ff00ff"));
700         drawing_frame->modify_bg(Gtk::STATE_SELECTED,Gdk::Color("#00ff00"));
701         */
702         //drawing_frame->set_state(Gtk::STATE_NORMAL);
703
704         drawing_frame->show();
705
706         attach(*drawing_frame, 1, 3+RULER_FIX, 1, 2, Gtk::EXPAND|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
707
708         Gtk::IconSize iconsize=Gtk::IconSize::from_name("synfig-small_icon");
709
710
711         // Create the vertical and horizontal rulers
712         vruler = manage(new class Gtk::VRuler());
713         hruler = manage(new class Gtk::HRuler());
714         vruler->set_metric(Gtk::PIXELS);
715         hruler->set_metric(Gtk::PIXELS);
716         vruler->show();
717         hruler->show();
718         attach(*vruler, 0, 1, 1, 2, Gtk::SHRINK|Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
719         attach(*hruler, 1, 3+RULER_FIX, 0, 1, Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL, 0, 0);
720         hruler->signal_event().connect(sigc::mem_fun(*this, &WorkArea::on_hruler_event));
721         vruler->signal_event().connect(sigc::mem_fun(*this, &WorkArea::on_vruler_event));
722         hruler->add_events(Gdk::BUTTON1_MOTION_MASK | Gdk::BUTTON2_MOTION_MASK |Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
723         vruler->add_events(Gdk::BUTTON1_MOTION_MASK | Gdk::BUTTON2_MOTION_MASK |Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
724
725         // Create the menu button
726         menubutton=manage(new class Gtk::Button());
727         Gtk::Arrow *arrow1 = manage(new class Gtk::Arrow(Gtk::ARROW_RIGHT, Gtk::SHADOW_OUT));
728         menubutton->add(*arrow1);
729         menubutton->show_all();
730         menubutton->signal_pressed().connect(sigc::mem_fun(*this, &WorkArea::popup_menu));
731         attach(*menubutton, 0, 1, 0, 1, Gtk::SHRINK, Gtk::SHRINK, 0, 0);
732
733
734
735         Gtk::VScrollbar *vscrollbar1 = manage(new class Gtk::VScrollbar(*get_scrolly_adjustment()));
736         Gtk::HScrollbar *hscrollbar1 = manage(new class Gtk::HScrollbar(*get_scrollx_adjustment()));
737         vscrollbar1->show();
738         hscrollbar1->show();
739         attach(*vscrollbar1, 3+RULER_FIX, 4+RULER_FIX, 1, 2, Gtk::FILL, Gtk::EXPAND|Gtk::FILL, 0, 0);
740         attach(*hscrollbar1, 2+RULER_FIX, 3+RULER_FIX, 2, 3, Gtk::EXPAND|Gtk::FILL, Gtk::FILL, 0, 0);
741
742         ZoomDial *zoomdial=manage(new class ZoomDial(iconsize));
743         zoomdial->signal_zoom_in().connect(sigc::mem_fun(*this, &studio::WorkArea::zoom_in));
744         zoomdial->signal_zoom_out().connect(sigc::mem_fun(*this, &studio::WorkArea::zoom_out));
745         zoomdial->signal_zoom_fit().connect(sigc::mem_fun(*this, &studio::WorkArea::zoom_fit));
746         zoomdial->signal_zoom_norm().connect(sigc::mem_fun(*this, &studio::WorkArea::zoom_norm));
747         zoomdial->show();
748         attach(*zoomdial, 0, 2+RULER_FIX, 2, 3, Gtk::SHRINK, Gtk::SHRINK, 0, 0);
749
750         drawing_area->add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);
751         add_events(Gdk::KEY_PRESS_MASK);
752         drawing_area->add_events(Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK);
753         drawing_area->add_events(Gdk::BUTTON1_MOTION_MASK | Gdk::BUTTON2_MOTION_MASK |Gdk::POINTER_MOTION_MASK);
754
755         // ----------------- Attach signals
756
757         drawing_area->signal_expose_event().connect(sigc::mem_fun(*this, &WorkArea::refresh));
758         drawing_area->signal_event().connect(sigc::mem_fun(*this, &WorkArea::on_drawing_area_event));
759         drawing_area->signal_size_allocate().connect(sigc::hide(sigc::mem_fun(*this, &WorkArea::refresh_dimension_info)));
760
761
762
763         canvas_interface->signal_rend_desc_changed().connect(sigc::mem_fun(*this, &WorkArea::refresh_dimension_info));
764         // When either of the scrolling adjustments change, then redraw.
765         get_scrollx_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &WorkArea::queue_scroll));
766         get_scrolly_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &WorkArea::queue_scroll));
767         get_scrollx_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &WorkArea::refresh_dimension_info));
768         get_scrolly_adjustment()->signal_value_changed().connect(sigc::mem_fun(*this, &WorkArea::refresh_dimension_info));
769
770         get_canvas()->signal_meta_data_changed("grid_size").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
771         get_canvas()->signal_meta_data_changed("grid_snap").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
772         get_canvas()->signal_meta_data_changed("grid_show").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
773         get_canvas()->signal_meta_data_changed("guide_show").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
774         get_canvas()->signal_meta_data_changed("guide_x").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
775         get_canvas()->signal_meta_data_changed("guide_y").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
776         get_canvas()->signal_meta_data_changed("onion_skin").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
777         get_canvas()->signal_meta_data_changed("guide_snap").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
778         get_canvas()->signal_meta_data_changed("sketch").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
779         get_canvas()->signal_meta_data_changed("solid_lines").connect(sigc::mem_fun(*this,&WorkArea::load_meta_data));
780
781         queued=false;
782         meta_data_lock=false;
783         set_focus_point(Point(0,0));
784
785
786         load_meta_data();
787         // Load sketch
788         {
789                 String data(canvas->get_meta_data("sketch"));
790                 if(!data.empty())
791                 {
792                         if(!load_sketch(data))
793                                 load_sketch(dirname(canvas->get_file_name())+ETL_DIRECTORY_SEPARATOR+basename(data));
794                 }
795         }
796
797         hruler->property_max_size()=double(10.0);
798         vruler->property_max_size()=double(10.0);
799
800         drawing_area->set_flags(drawing_area->get_flags()|Gtk::CAN_FOCUS);
801 }
802
803 WorkArea::~WorkArea()
804 {
805 //      delete [] buffer;
806
807         // don't leave the render function queued if we are about to vanish;
808         // that causes crashes
809         if(render_idle_func_id)
810                 render_idle_func_id=0;
811 }
812
813 bool
814 WorkArea::get_updating()const
815 {
816         return App::single_threaded && async_renderer && async_renderer->updating;
817 }
818
819 void
820 WorkArea::stop_updating(bool cancel)
821 {
822         async_renderer->stop();
823         if (cancel) canceled_=true;
824 }
825
826 void
827 WorkArea::save_meta_data()
828 {
829         if(meta_data_lock)
830                 return;
831         meta_data_lock=true;
832
833         Vector s(get_grid_size());
834         canvas_interface->set_meta_data("grid_size",strprintf("%f %f",s[0],s[1]));
835         canvas_interface->set_meta_data("grid_snap",get_grid_snap()?"1":"0");
836         canvas_interface->set_meta_data("guide_snap",get_guide_snap()?"1":"0");
837         canvas_interface->set_meta_data("guide_show",get_show_guides()?"1":"0");
838         canvas_interface->set_meta_data("grid_show",show_grid?"1":"0");
839         canvas_interface->set_meta_data("onion_skin",onion_skin?"1":"0");
840         {
841                 String data;
842                 GuideList::const_iterator iter;
843                 for(iter=get_guide_list_x().begin();iter!=get_guide_list_x().end();++iter)
844                 {
845                         if(!data.empty())
846                                 data+=' ';
847                         data+=strprintf("%f",*iter);
848                 }
849                 if(!data.empty())
850                         canvas_interface->set_meta_data("guide_x",data);
851
852                 data.clear();
853                 for(iter=get_guide_list_y().begin();iter!=get_guide_list_y().end();++iter)
854                 {
855                         if(!data.empty())
856                                 data+=' ';
857                         data+=strprintf("%f",*iter);
858                 }
859                 if(!data.empty())
860                         canvas_interface->set_meta_data("guide_y",data);
861         }
862
863         if(get_sketch_filename().size())
864         {
865                 if(dirname(canvas->get_file_name())==dirname(get_sketch_filename()))
866                         canvas_interface->set_meta_data("sketch",basename(get_sketch_filename()));
867                 else
868                         canvas_interface->set_meta_data("sketch",get_sketch_filename());
869         }
870
871         meta_data_lock=false;
872 }
873
874 void
875 WorkArea::load_meta_data()
876 {
877         if(meta_data_lock)
878                 return;
879         meta_data_lock=true;
880
881         String data;
882
883         data=canvas->get_meta_data("grid_size");
884         if(!data.empty())
885         {
886                 float gx(get_grid_size()[0]),gy(get_grid_size()[1]);
887
888                 String::iterator iter(find(data.begin(),data.end(),' '));
889                 String tmp(data.begin(),iter);
890
891                 if(!tmp.empty())
892                         gx=stratof(tmp);
893
894                 if(iter==data.end())
895                         tmp.clear();
896                 else
897                         tmp=String(iter+1,data.end());
898
899                 if(!tmp.empty())
900                         gy=stratof(tmp);
901
902                 set_grid_size(Vector(gx,gy));
903         }
904         else
905                 synfig::error("WorkArea::load_meta_data(): Unable to parse data for \"grid_size\", which was \"%s\"",data.c_str());
906
907         data=canvas->get_meta_data("grid_show");
908         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
909                 show_grid=true;
910         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
911                 show_grid=false;
912
913         data=canvas->get_meta_data("solid_lines");
914         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
915                 solid_lines=true;
916         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
917                 solid_lines=false;
918
919         data=canvas->get_meta_data("guide_show");
920         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
921                 show_guides=true;
922         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
923                 show_guides=false;
924
925         data=canvas->get_meta_data("grid_snap");
926         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
927                 set_grid_snap(true);
928         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
929                 set_grid_snap(false);
930
931         data=canvas->get_meta_data("guide_snap");
932         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
933                 set_guide_snap(true);
934         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
935                 set_guide_snap(false);
936
937         data=canvas->get_meta_data("onion_skin");
938         if(data.size() && (data=="1" || data[0]=='t' || data[0]=='T'))
939                 set_onion_skin(true);
940         if(data.size() && (data=="0" || data[0]=='f' || data[0]=='F'))
941                 set_onion_skin(false);
942
943         data=canvas->get_meta_data("guide_x");
944         get_guide_list_x().clear();
945         while(!data.empty())
946         {
947                 String::iterator iter(find(data.begin(),data.end(),' '));
948                 String guide(data.begin(),iter);
949
950                 if(!guide.empty())
951                         get_guide_list_x().push_back(stratof(guide));
952
953                 if(iter==data.end())
954                         data.clear();
955                 else
956                         data=String(iter+1,data.end());
957         }
958         //sort(get_guide_list_x());
959
960         data=canvas->get_meta_data("guide_y");
961         get_guide_list_y().clear();
962         while(!data.empty())
963         {
964                 String::iterator iter(find(data.begin(),data.end(),' '));
965                 String guide(data.begin(),iter);
966
967                 if(!guide.empty())
968                         get_guide_list_y().push_back(stratof(guide));
969
970                 if(iter==data.end())
971                         data.clear();
972                 else
973                         data=String(iter+1,data.end());
974         }
975         //sort(get_guide_list_y());
976
977         meta_data_lock=false;
978         queue_draw();
979 }
980
981 void
982 WorkArea::set_onion_skin(bool x)
983 {
984         if(onion_skin==x)
985                 return;
986         onion_skin=x;
987         save_meta_data();
988         queue_render_preview();
989         signal_onion_skin_changed()();
990 }
991
992 bool
993 WorkArea::get_onion_skin()const
994 {
995         return onion_skin;
996 }
997
998 void
999 WorkArea::enable_grid()
1000 {
1001         show_grid=true;
1002         save_meta_data();
1003         queue_draw();
1004 }
1005
1006 void
1007 WorkArea::disable_grid()
1008 {
1009         show_grid=false;
1010         save_meta_data();
1011         queue_draw();
1012 }
1013
1014 void
1015 WorkArea::set_show_guides(bool x)
1016 {
1017         show_guides=x;
1018         save_meta_data();
1019         queue_draw();
1020 }
1021
1022 void
1023 WorkArea::toggle_grid()
1024 {
1025         show_grid=!show_grid;
1026         save_meta_data();
1027         queue_draw();
1028 }
1029
1030 void
1031 WorkArea::set_low_resolution_flag(bool x)
1032 {
1033         if(x!=low_resolution)
1034         {
1035                 low_resolution=x;
1036                 queue_render_preview();
1037         }
1038 }
1039
1040 void
1041 WorkArea::toggle_low_resolution_flag()
1042 {
1043         set_low_resolution_flag(!get_low_resolution_flag());
1044 }
1045
1046 void
1047 WorkArea::popup_menu()
1048 {
1049         signal_popup_menu()();
1050 }
1051
1052 void
1053 WorkArea::set_grid_size(const synfig::Vector &s)
1054 {
1055         Duckmatic::set_grid_size(s);
1056         save_meta_data();
1057         queue_draw();
1058 }
1059
1060 void
1061 WorkArea::set_focus_point(const synfig::Point &point)
1062 {
1063         // These next three lines try to ensure that we place the
1064         // focus on a pixel boundry
1065         /*Point adjusted(point[0]/abs(get_pw()),point[1]/abs(get_ph()));
1066         adjusted[0]=(abs(adjusted[0]-floor(adjusted[0]))<0.5)?floor(adjusted[0])*abs(get_pw()):ceil(adjusted[0])*abs(get_ph());
1067         adjusted[1]=(abs(adjusted[1]-floor(adjusted[1]))<0.5)?floor(adjusted[1])*abs(get_ph()):ceil(adjusted[1])*abs(get_ph());
1068         */
1069         const synfig::Point& adjusted(point);
1070
1071         synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
1072         Real x_factor=(rend_desc.get_br()[0]-rend_desc.get_tl()[0]>0)?-1:1;
1073         Real y_factor=(rend_desc.get_br()[1]-rend_desc.get_tl()[1]>0)?-1:1;
1074
1075         get_scrollx_adjustment()->set_value(adjusted[0]*x_factor);
1076         get_scrolly_adjustment()->set_value(adjusted[1]*y_factor);
1077 }
1078
1079 synfig::Point
1080 WorkArea::get_focus_point()const
1081 {
1082         synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
1083         Real x_factor=(rend_desc.get_br()[0]-rend_desc.get_tl()[0]>0)?-1:1;
1084         Real y_factor=(rend_desc.get_br()[1]-rend_desc.get_tl()[1]>0)?-1:1;
1085
1086         return synfig::Point(get_scrollx_adjustment()->get_value()*x_factor, get_scrolly_adjustment()->get_value()*y_factor);
1087 }
1088
1089 bool
1090 WorkArea::set_wh(int W, int H,int CHAN)
1091 {
1092         // If our size is already set, don't set it again
1093         if(W==w && H==h && CHAN==bpp)
1094         {
1095                 return true;
1096         }
1097         if(W<=0 || H<=0 || CHAN<=0)
1098                 return false;
1099
1100         assert(W>0);
1101         assert(H>0);
1102         assert(CHAN>0);
1103
1104         // Set all of the parameters
1105         w=W;
1106         h=H;
1107         bpp=CHAN;
1108
1109         refresh_dimension_info();
1110
1111         tile_book.clear();
1112
1113         return true;
1114 }
1115
1116 bool
1117 WorkArea::on_key_press_event(GdkEventKey* event)
1118 {
1119         if(get_selected_ducks().empty())
1120                 return false;
1121
1122         Real multiplier(1.0);
1123
1124         if(Gdk::ModifierType(event->state)&GDK_SHIFT_MASK)
1125                 multiplier=10.0;
1126
1127         Vector nudge;
1128         switch(event->keyval)
1129         {
1130                 case GDK_Left:
1131                         nudge=Vector(-pw,0);
1132                         break;
1133                 case GDK_Right:
1134                         nudge=Vector(pw,0);
1135                         break;
1136                 case GDK_Up:
1137                         nudge=Vector(0,-ph);
1138                         break;
1139                 case GDK_Down:
1140                         nudge=Vector(0,ph);
1141                         break;
1142                 default:
1143                         return false;
1144                         break;
1145         }
1146
1147         synfigapp::Action::PassiveGrouper grouper(instance.get(),"Nudge");
1148
1149         // Grid snap does not apply to nudging
1150         bool grid_snap_holder(get_grid_snap());
1151         bool guide_snap_holder(get_guide_snap());
1152         set_grid_snap(false);
1153
1154         try {
1155                 start_duck_drag(get_selected_duck()->get_trans_point());
1156                 translate_selected_ducks(get_selected_duck()->get_trans_point()+nudge*multiplier);
1157                 end_duck_drag();
1158         }
1159         catch(String)
1160         {
1161                 canvas_view->duck_refresh_flag=true;
1162                 canvas_view->queue_rebuild_ducks();
1163         }
1164
1165         set_grid_snap(grid_snap_holder);
1166         set_guide_snap(guide_snap_holder);
1167
1168         return true;
1169 }
1170
1171 bool
1172 WorkArea::on_drawing_area_event(GdkEvent *event)
1173 {
1174         synfig::Point mouse_pos;
1175     float bezier_click_pos;
1176         const float radius((abs(pw)+abs(ph))*4);
1177         int button_pressed(0);
1178         float pressure(0);
1179         bool is_mouse(false);
1180         Gdk::ModifierType modifier(Gdk::ModifierType(0));
1181
1182         drawing_area->grab_focus();
1183
1184         // Handle input stuff
1185         if(
1186                 event->any.type==GDK_MOTION_NOTIFY ||
1187                 event->any.type==GDK_BUTTON_PRESS ||
1188                 event->any.type==GDK_2BUTTON_PRESS ||
1189                 event->any.type==GDK_3BUTTON_PRESS ||
1190                 event->any.type==GDK_BUTTON_RELEASE
1191         )
1192         {
1193                 GdkDevice *device;
1194                 if(event->any.type==GDK_MOTION_NOTIFY)
1195                 {
1196                         device=event->motion.device;
1197                         modifier=Gdk::ModifierType(event->motion.state);
1198                 }
1199                 else
1200                 {
1201                         device=event->button.device;
1202                         modifier=Gdk::ModifierType(event->button.state);
1203                 }
1204
1205                 // Make sure we recognise the device
1206                 if(curr_input_device)
1207                 {
1208                         if(curr_input_device!=device)
1209                         {
1210                                 assert(device);
1211                                 curr_input_device=device;
1212                                 signal_input_device_changed()(curr_input_device);
1213                         }
1214                 }
1215                 else if(device)
1216                 {
1217                         curr_input_device=device;
1218                         signal_input_device_changed()(curr_input_device);
1219                 }
1220
1221                 assert(curr_input_device);
1222
1223                 // Calculate the position of the
1224                 // input device in canvas coordinates
1225                 // and the buttons
1226                 if(!event->button.axes)
1227                 {
1228                         mouse_pos=synfig::Point(screen_to_comp_coords(synfig::Point(event->button.x,event->button.y)));
1229                         button_pressed=event->button.button;
1230                         pressure=1.0f;
1231                         is_mouse=true;
1232                         if(isnan(event->button.x) || isnan(event->button.y))
1233                                 return false;
1234                 }
1235                 else
1236                 {
1237                         double x(event->button.axes[0]);
1238                         double y(event->button.axes[1]);
1239                         if(isnan(x) || isnan(y))
1240                                 return false;
1241
1242                         pressure=event->button.axes[2];
1243                         //synfig::info("pressure=%f",pressure);
1244                         pressure-=0.04f;
1245                         pressure/=1.0f-0.04f;
1246
1247
1248                         assert(!isnan(pressure));
1249
1250                         mouse_pos=synfig::Point(screen_to_comp_coords(synfig::Point(x,y)));
1251
1252                         button_pressed=event->button.button;
1253
1254                         if(button_pressed==1 && pressure<0 && (event->any.type!=GDK_BUTTON_RELEASE && event->any.type!=GDK_BUTTON_PRESS))
1255                                 button_pressed=0;
1256                         if(pressure<0)
1257                                 pressure=0;
1258
1259                         //if(event->any.type==GDK_BUTTON_PRESS && button_pressed)
1260                         //      synfig::info("Button pressed on input device = %d",event->button.button);
1261
1262                         //if(event->button.axes[2]>0.1)
1263                         //      button_pressed=1;
1264                         //else
1265                         //      button_pressed=0;
1266                 }
1267         }
1268         // GDK mouse scrolling events
1269         else if(event->any.type==GDK_SCROLL)
1270         {
1271                 // GDK information needed to properly interprete mouse
1272                 // scrolling events are: scroll.state, scroll.x/scroll.y, and
1273                 // scroll.direction. The value of scroll.direction will be
1274                 // obtained later.
1275
1276                 modifier=Gdk::ModifierType(event->scroll.state);
1277                 mouse_pos=synfig::Point(screen_to_comp_coords(synfig::Point(event->scroll.x,event->scroll.y)));
1278         }
1279
1280         // Handle the renderables
1281         {
1282                 std::set<etl::handle<WorkAreaRenderer> >::iterator iter;
1283                 for(iter=renderer_set_.begin();iter!=renderer_set_.end();++iter)
1284                 {
1285                         if((*iter)->get_enabled())
1286                                 if((*iter)->event_vfunc(event))
1287                                 {
1288                                         // Event handled. Return true.
1289                                         return true;
1290                                 }
1291                 }
1292         }
1293
1294         // Event hasn't been handled, pass it down
1295         switch(event->type)
1296     {
1297         case GDK_BUTTON_PRESS:
1298                 {
1299                 switch(button_pressed)
1300                 {
1301                 case 1: // Attempt to click on a duck
1302                 {
1303                         etl::handle<Duck> duck;
1304                         dragging=DRAG_NONE;
1305
1306                         if(allow_duck_clicks)
1307                         {
1308                                 duck=find_duck(mouse_pos,radius);
1309
1310                                 if(duck)
1311                                 {
1312                                         // make a note of whether the duck we click on was selected or not
1313                                         if(duck_is_selected(duck))
1314                                                 clicked_duck=duck;
1315                                         else
1316                                         {
1317                                                 clicked_duck=0;
1318                                                 // if CTRL isn't pressed, clicking an unselected duck will unselect all other ducks
1319                                                 if(!(modifier&GDK_CONTROL_MASK))
1320                                                         clear_selected_ducks();
1321                                                 select_duck(duck);
1322                                         }
1323                                 }
1324                         }
1325                         //else
1326                         //      clear_selected_ducks();
1327
1328
1329
1330                         selected_bezier=find_bezier(mouse_pos,radius,&bezier_click_pos);
1331                         if(duck && duck->get_editable())
1332                         {
1333                                 //get_selected_duck()->signal_user_click(0)();
1334                                 //if(clicked_duck)clicked_duck->signal_user_click(0)();
1335
1336                                 // if the user is holding shift while clicking on a tangent duck, consider splitting the tangent
1337                                 if (event->motion.state&GDK_SHIFT_MASK && duck->get_type() == Duck::TYPE_TANGENT)
1338                                 {
1339                                         synfigapp::ValueDesc value_desc = duck->get_value_desc();
1340
1341                                         // we have the tangent, but need the vertex - that's the parent
1342                                         if (value_desc.parent_is_value_node()) {
1343                                                 ValueNode_Composite::Handle parent_value_node = value_desc.get_parent_value_node();
1344
1345                                                 // if the tangent isn't split, then split it
1346                                                 if (!((*(parent_value_node->get_link("split")))(get_time()).get(bool())))
1347                                                 {
1348                                                         get_canvas_view()->canvas_interface()->
1349                                                                 change_value(synfigapp::ValueDesc(parent_value_node,
1350                                                                                                                                   parent_value_node->get_link_index_from_name("split")),
1351                                                                                          true);
1352                                                         // rebuild the ducks from scratch, so the tangents ducks aren't connected
1353                                                         get_canvas_view()->rebuild_ducks();
1354
1355                                                         // reprocess the mouse click
1356                                                         return on_drawing_area_event(event);
1357                                                 }
1358                                         } else {
1359                                                 // I don't know how to access the vertex from the tangent duck when originally drawing the bline in the bline tool
1360
1361                                                 // synfig::ValueNode::Handle vn = value_desc.get_value_node();
1362                                                 synfig::info("parent isn't value node?  shift-drag-tangent doesn't work in bline tool yet...");
1363                                         }
1364                                 }
1365
1366                                 dragging=DRAG_DUCK;
1367                                 drag_point=mouse_pos;
1368                                 //drawing_area->queue_draw();
1369                                 start_duck_drag(mouse_pos);
1370                                 get_canvas_view()->reset_cancel_status();
1371                                 return true;
1372                         }
1373 // I commented out this section because
1374 // it was causing issues when rotoscoping.
1375 // At the moment, we don't need it, so
1376 // this was the easiest way to fix the problem.
1377 /*
1378                         else
1379                         if(selected_bezier)
1380                         {
1381                                 selected_duck=0;
1382                                 selected_bezier->signal_user_click(0)(bezier_click_pos);
1383                         }
1384 */
1385                         else
1386                         {
1387                                 //clear_selected_ducks();
1388                                 selected_bezier=0;
1389                                 if(canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,BUTTON_LEFT,mouse_pos,pressure,modifier))==Smach::RESULT_OK)
1390                                 {
1391                                         // Check for a guide click
1392                                         GuideList::iterator iter;
1393
1394                                         iter=find_guide_x(mouse_pos,radius);
1395                                         if(iter==get_guide_list_x().end())
1396                                         {
1397                                                 curr_guide_is_x=false;
1398                                                 iter=find_guide_y(mouse_pos,radius);
1399                                         }
1400                                         else
1401                                                 curr_guide_is_x=true;
1402                                         if(iter!=get_guide_list_x().end() && iter!=get_guide_list_y().end())
1403                                         {
1404                                                 dragging=DRAG_GUIDE;
1405                                                 curr_guide=iter;
1406                                                 return true;
1407                                         }
1408
1409
1410                                         // All else fails, try making a selection box
1411                                         dragging=DRAG_BOX;
1412                                         curr_point=drag_point=mouse_pos;
1413                                         return true;
1414                                 }
1415                         }
1416                         break;
1417                 }
1418                 case 2: // Attempt to drag and move the window
1419                 {
1420                         etl::handle<Duck> duck=find_duck(mouse_pos,radius);
1421                         etl::handle<Bezier> bezier=find_bezier(mouse_pos,radius,&bezier_click_pos);
1422                         if(duck)
1423                                 duck->signal_user_click(1)();
1424                         else
1425                         if(bezier)
1426                                 bezier->signal_user_click(1)(bezier_click_pos);
1427
1428                         if(canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,BUTTON_MIDDLE,mouse_pos,pressure,modifier))==Smach::RESULT_OK)
1429                         if(is_mouse)
1430                         {
1431                                 dragging=DRAG_WINDOW;
1432                                 drag_point=mouse_pos;
1433                                 signal_user_click(1)(mouse_pos);
1434                         }
1435                         break;
1436                 }
1437                 case 3: // Attempt to either get info on a duck, or open the menu
1438                 {
1439                         etl::handle<Duck> duck=find_duck(mouse_pos,radius);
1440                         etl::handle<Bezier> bezier=find_bezier(mouse_pos,radius,&bezier_click_pos);
1441
1442                         Layer::Handle layer(get_canvas()->find_layer(mouse_pos));
1443                         if(duck)
1444                         {
1445                                 if(get_selected_ducks().size()<=1)
1446                                         duck->signal_user_click(2)();
1447                                 else
1448                                 {
1449                                         canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MULTIPLE_DUCKS_CLICKED,BUTTON_RIGHT,mouse_pos,pressure,modifier));
1450                                 }
1451                                 return true;
1452                         }
1453                         else
1454                         if(bezier)
1455                         {
1456                                 bezier->signal_user_click(2)(bezier_click_pos);
1457                                 return true;
1458                         }
1459                         else
1460                         if(layer)
1461                         {
1462                                 if(canvas_view->get_smach().process_event(EventLayerClick(layer,BUTTON_RIGHT,mouse_pos))==Smach::RESULT_OK)
1463                                         return false;
1464                                 return true;
1465                         }
1466                         else
1467                                 canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,BUTTON_RIGHT,mouse_pos,pressure,modifier));
1468                         /*
1469                         if(canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DOWN,BUTTON_RIGHT,mouse_pos,pressure,modifier))==Smach::RESULT_OK)
1470                         {
1471                                 //popup_menu();
1472                                 return true;
1473                         }
1474                         */
1475                         break;
1476                 }
1477                 case 4:
1478                         signal_user_click(3)(mouse_pos);
1479                         break;
1480                 case 5:
1481                         signal_user_click(4)(mouse_pos);
1482                         break;
1483                 default:
1484                         break;
1485                 }
1486                 }
1487                 break;
1488         case GDK_MOTION_NOTIFY:
1489                 curr_point=mouse_pos;
1490
1491                 if(event->motion.time-last_event_time<25)
1492                         return true;
1493                 else
1494                         last_event_time=event->motion.time;
1495
1496                 signal_cursor_moved_();
1497
1498                 // Guide/Duck hilights on hover
1499                 if(dragging==DRAG_NONE)
1500                 {
1501                         GuideList::iterator iter;
1502
1503                         iter=find_guide_x(mouse_pos,radius);
1504                         if(iter==get_guide_list_x().end())
1505                                 iter=find_guide_y(mouse_pos,radius);
1506
1507                         if(iter!=curr_guide)
1508                         {
1509                                 curr_guide=iter;
1510                                 drawing_area->queue_draw();
1511                         }
1512
1513                         etl::handle<Duck> duck;
1514                         duck=find_duck(mouse_pos,radius);
1515                         if(duck!=hover_duck)
1516                         {
1517                                 hover_duck=duck;
1518                                 drawing_area->queue_draw();
1519                         }
1520                 }
1521
1522
1523                 if(dragging==DRAG_DUCK)
1524                 {
1525                         if(canvas_view->get_cancel_status())
1526                         {
1527                                 dragging=DRAG_NONE;
1528                                 canvas_view->queue_rebuild_ducks();
1529                                 return true;
1530                         }
1531                         /*
1532                         Point point((mouse_pos-selected_duck->get_origin())/selected_duck->get_scalar());
1533                         if(get_grid_snap())
1534                         {
1535                                 point[0]=floor(point[0]/grid_size[0]+0.5)*grid_size[0];
1536                                 point[1]=floor(point[1]/grid_size[1]+0.5)*grid_size[1];
1537                         }
1538                         selected_duck->set_point(point);
1539                         */
1540
1541                         //Point p(mouse_pos);
1542
1543                         set_axis_lock(event->motion.state&GDK_SHIFT_MASK);
1544
1545                         translate_selected_ducks(mouse_pos);
1546
1547                         drawing_area->queue_draw();
1548                 }
1549                 if(dragging==DRAG_BOX)
1550                 {
1551                         curr_point=mouse_pos;
1552                         drawing_area->queue_draw();
1553                 }
1554                 if(dragging==DRAG_GUIDE)
1555                 {
1556                         if(curr_guide_is_x)
1557                                 *curr_guide=mouse_pos[0];
1558                         else
1559                                 *curr_guide=mouse_pos[1];
1560                         drawing_area->queue_draw();
1561                 }
1562                 if(dragging!=DRAG_WINDOW)
1563                 {       // Update those triangle things on the rulers
1564                         const synfig::Point point(mouse_pos);
1565                         hruler->property_position()=Distance(point[0],Distance::SYSTEM_UNITS).get(App::distance_system,get_canvas()->rend_desc());
1566                         vruler->property_position()=Distance(point[1],Distance::SYSTEM_UNITS).get(App::distance_system,get_canvas()->rend_desc());
1567                 }
1568                 if(dragging==DRAG_WINDOW)
1569                 {
1570                         set_focus_point(get_focus_point()+mouse_pos-drag_point);
1571                 }
1572                 else
1573                 if(event->motion.state&GDK_BUTTON1_MASK && canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DRAG,BUTTON_LEFT,mouse_pos,pressure,modifier))==Smach::RESULT_ACCEPT)
1574                         return true;
1575                 else
1576                 if(event->motion.state&GDK_BUTTON2_MASK && canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DRAG,BUTTON_MIDDLE,mouse_pos,pressure,modifier))==Smach::RESULT_ACCEPT)
1577                         return true;
1578                 else
1579                 if(event->motion.state&GDK_BUTTON3_MASK && canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_DRAG,BUTTON_RIGHT,mouse_pos,pressure,modifier))==Smach::RESULT_ACCEPT)
1580                         return true;
1581                 else
1582                 if(canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_MOTION,BUTTON_NONE,mouse_pos,pressure,modifier))==Smach::RESULT_ACCEPT)
1583                         return true;
1584
1585                 break;
1586         case GDK_BUTTON_RELEASE:
1587         {
1588                 bool ret(false);
1589
1590                 if(dragging==DRAG_GUIDE)
1591                 {
1592                         dragging=DRAG_NONE;
1593                         save_meta_data();
1594                         return true;
1595                 }
1596                 else
1597                 if(dragging==DRAG_DUCK)
1598                 {
1599                         synfigapp::Action::PassiveGrouper grouper(instance.get(),"Move");
1600                         dragging=DRAG_NONE;
1601                         //translate_selected_ducks(mouse_pos);
1602                         set_axis_lock(false);
1603
1604                         try{
1605                         get_canvas_view()->duck_refresh_flag=false;
1606                         get_canvas_view()->duck_refresh_needed=false;
1607                         const bool drag_did_anything(end_duck_drag());
1608                         get_canvas_view()->duck_refresh_flag=true;
1609                         if(!drag_did_anything)
1610                         {
1611                                 // if we originally clicked on a selected duck ...
1612                                 if(clicked_duck)
1613                                 {
1614                                         // ... and CTRL is pressed, then just toggle the clicked duck
1615                                         //     otherwise make the clicked duck the only selected duck
1616                                         if(modifier&GDK_CONTROL_MASK)
1617                                                 unselect_duck(clicked_duck);
1618                                         else
1619                                         {
1620                                                 clear_selected_ducks();
1621                                                 select_duck(clicked_duck);
1622                                         }
1623                                         clicked_duck->signal_user_click(0)();
1624                                 }
1625                         }
1626                         else
1627                         {
1628                                 if(canvas_view->duck_refresh_needed)
1629                                         canvas_view->queue_rebuild_ducks();
1630                                 return true;
1631                         }
1632                         }catch(String)
1633                         {
1634                                 canvas_view->duck_refresh_flag=true;
1635                                 canvas_view->queue_rebuild_ducks();
1636                                 return true;
1637                         }
1638                         //queue_draw();
1639                         clicked_duck=0;
1640
1641                         ret=true;
1642                 }
1643
1644                 if(dragging==DRAG_BOX)
1645                 {
1646                         dragging=DRAG_NONE;
1647                         if((drag_point-mouse_pos).mag()>radius/2.0f)
1648                         {
1649                                 if(canvas_view->get_smach().process_event(EventBox(drag_point,mouse_pos,MouseButton(event->button.button),modifier))==Smach::RESULT_ACCEPT)
1650                                         return true;
1651
1652                                 // when dragging a box around some ducks:
1653                                 // SHIFT selects; CTRL toggles; SHIFT+CTRL unselects; <none> clears all then selects
1654                                 if(modifier&GDK_SHIFT_MASK)
1655                                         select_ducks_in_box(drag_point,mouse_pos);
1656
1657                                 if(modifier&GDK_CONTROL_MASK)
1658                                         toggle_select_ducks_in_box(drag_point,mouse_pos);
1659                                 else if(!(modifier&GDK_SHIFT_MASK))
1660                                 {
1661                                         clear_selected_ducks();
1662                                         select_ducks_in_box(drag_point,mouse_pos);
1663                                 }
1664                                 ret=true;
1665                         }
1666                         else
1667                         {
1668                                 if(allow_layer_clicks)
1669                                 {
1670                                         Layer::Handle layer(get_canvas()->find_layer(drag_point));
1671                                         //if(layer)
1672                                         {
1673                                                 if(canvas_view->get_smach().process_event(EventLayerClick(layer,BUTTON_LEFT,mouse_pos,modifier))==Smach::RESULT_OK)
1674                                                         signal_layer_selected_(layer);
1675                                                 ret=true;
1676                                         }
1677                                 }
1678                                 else
1679                                 {
1680                                         signal_user_click(0)(mouse_pos);
1681                                 }
1682                         }
1683                 }
1684
1685                 dragging=DRAG_NONE;
1686
1687                 if(canvas_view->get_smach().process_event(EventMouse(EVENT_WORKAREA_MOUSE_BUTTON_UP,MouseButton(event->button.button),mouse_pos,pressure,modifier))==Smach::RESULT_ACCEPT)
1688                         ret=true;
1689
1690                 return ret;
1691         }
1692                 break;
1693         case GDK_SCROLL:
1694         {
1695                 // Handle a mouse scrolling event like Xara Xtreme and
1696                 // Inkscape:
1697
1698                 // Scroll up/down: scroll up/down
1699                 // Shift + scroll up/down: scroll left/right
1700                 // Control + scroll up/down: zoom in/out
1701
1702                 if(modifier&GDK_CONTROL_MASK)
1703                 {
1704
1705                         // The zoom is performed while preserving the pointer
1706                         // position as a fixed point (similarly to Xara Xtreme and
1707                         // Inkscape).
1708
1709                         // The strategy used below is to scroll to the updated
1710                         // position, then zoom. This is easy to implement within
1711                         // the present architecture, but has the disadvantage of
1712                         // triggering multiple visible refreshes. Note: 1.25 is
1713                         // the hard wired ratio in zoom_in()/zoom_out(). The
1714                         // variable "drift" compensates additional inaccuracies in
1715                         // the zoom. There is also an additional minus sign for
1716                         // the inverted y coordinates.
1717
1718                         // FIXME: One might want to figure out where in the code
1719                         // this empirical drift is been introduced.
1720
1721                         const synfig::Point scroll_point(get_scrollx_adjustment()->get_value(),get_scrolly_adjustment()->get_value());
1722                         const double drift = 0.052;
1723
1724                         switch(event->scroll.direction)
1725                         {
1726                                 case GDK_SCROLL_UP:
1727                                 case GDK_SCROLL_RIGHT:
1728                                         get_scrollx_adjustment()->set_value(scroll_point[0]+(mouse_pos[0]-scroll_point[0])*(1.25-(1+drift)));
1729                                         get_scrolly_adjustment()->set_value(scroll_point[1]-(mouse_pos[1]+scroll_point[1])*(1.25-(1+drift)));
1730                                         zoom_in();
1731                                         break;
1732                                 case GDK_SCROLL_DOWN:
1733                                 case GDK_SCROLL_LEFT:
1734                                         get_scrollx_adjustment()->set_value(scroll_point[0]+(mouse_pos[0]-scroll_point[0])*(1/1.25-(1+drift)));
1735                                         get_scrolly_adjustment()->set_value(scroll_point[1]-(mouse_pos[1]+scroll_point[1])*(1/1.25-(1+drift)));
1736                                         zoom_out();
1737                                         break;
1738                                 default:
1739                                         break;
1740                         }
1741                 }
1742                 else if(modifier&GDK_SHIFT_MASK)
1743                 {
1744                         // Scroll in either direction by 20 pixels. Ideally, the
1745                         // amount of pixels per scrolling event should be
1746                         // configurable. Xara Xtreme currently uses an (hard
1747                         // wired) amount 20 pixel, Inkscape defaults to 40 pixels.
1748
1749                         const int scroll_pixel = 20;
1750
1751                         switch(event->scroll.direction)
1752                         {
1753                                 case GDK_SCROLL_UP:
1754                                         get_scrollx_adjustment()->set_value(get_scrollx_adjustment()->get_value()-scroll_pixel*pw);
1755                                         break;
1756                                 case GDK_SCROLL_DOWN:
1757                                         get_scrollx_adjustment()->set_value(get_scrollx_adjustment()->get_value()+scroll_pixel*pw);
1758                                         break;
1759                                 case GDK_SCROLL_LEFT:
1760                                         get_scrolly_adjustment()->set_value(get_scrolly_adjustment()->get_value()+scroll_pixel*ph);
1761                                         break;
1762                                 case GDK_SCROLL_RIGHT:
1763                                         get_scrolly_adjustment()->set_value(get_scrolly_adjustment()->get_value()-scroll_pixel*ph);
1764                                         break;
1765                                 default:
1766                                         break;
1767                         }
1768                 }
1769                 else
1770                 {
1771                         // Scroll in either direction by 20 pixels. Ideally, the
1772                         // amount of pixels per scrolling event should be
1773                         // configurable. Xara Xtreme currently uses an (hard
1774                         // wired) amount 20 pixel, Inkscape defaults to 40 pixels.
1775
1776                         const int scroll_pixel = 20;
1777
1778                         switch(event->scroll.direction)
1779                         {
1780                                 case GDK_SCROLL_UP:
1781                                         get_scrolly_adjustment()->set_value(get_scrolly_adjustment()->get_value()+scroll_pixel*ph);
1782                                         break;
1783                                 case GDK_SCROLL_DOWN:
1784                                         get_scrolly_adjustment()->set_value(get_scrolly_adjustment()->get_value()-scroll_pixel*ph);
1785                                         break;
1786                                 case GDK_SCROLL_LEFT:
1787                                         get_scrollx_adjustment()->set_value(get_scrollx_adjustment()->get_value()-scroll_pixel*pw);
1788                                         break;
1789                                 case GDK_SCROLL_RIGHT:
1790                                         get_scrollx_adjustment()->set_value(get_scrollx_adjustment()->get_value()+scroll_pixel*pw);
1791                                         break;
1792                                 default:
1793                                         break;
1794                         }
1795                 }
1796         }
1797                 break;
1798         default:
1799                 break;
1800         }
1801                 return false;
1802 }
1803
1804 bool
1805 WorkArea::on_hruler_event(GdkEvent */*event*/)
1806 {
1807 /*
1808         switch(event->type)
1809     {
1810         case GDK_BUTTON_PRESS:
1811                 if(dragging==DRAG_NONE)
1812                 {
1813                         dragging=DRAG_GUIDE;
1814                         curr_guide=get_guide_list_y().insert(get_guide_list_y().begin());
1815                         curr_guide_is_x=false;
1816                 }
1817                 return true;
1818                 break;
1819
1820         case GDK_MOTION_NOTIFY:
1821                 // Guide movement
1822                 if(dragging==DRAG_GUIDE && curr_guide_is_x==false)
1823                 {
1824                         double y,x;
1825                         if(event->button.axes)
1826                         {
1827                                 x=(event->button.axes[0]);
1828                                 y=(event->button.axes[1]);
1829                         }
1830                         else
1831                         {
1832                                 x=event->button.x;
1833                                 y=event->button.y;
1834                         }
1835
1836                         if(isnan(y) || isnan(x))
1837                                 return false;
1838
1839                         *curr_guide=synfig::Point(screen_to_comp_coords(synfig::Point(x,y)))[1];
1840
1841                         queue_draw();
1842                 }
1843                 return true;
1844                 break;
1845
1846         case GDK_BUTTON_RELEASE:
1847                 if(dragging==DRAG_GUIDE && curr_guide_is_x==false)
1848                 {
1849                         dragging=DRAG_NONE;
1850                         get_guide_list_y().erase(curr_guide);
1851                 }
1852                 break;
1853                 return true;
1854         default:
1855                 break;
1856         }
1857 */
1858         return false;
1859 }
1860
1861 bool
1862 WorkArea::on_vruler_event(GdkEvent */*event*/)
1863 {
1864 /*
1865         switch(event->type)
1866     {
1867         case GDK_BUTTON_PRESS:
1868                 DEBUGPOINT();
1869                 if(dragging==DRAG_NONE)
1870                 {
1871                         DEBUGPOINT();
1872                         dragging=DRAG_GUIDE;
1873                         curr_guide=get_guide_list_x().insert(get_guide_list_x().begin());
1874                         curr_guide_is_x=true;
1875                 }
1876                 return true;
1877                 break;
1878         case GDK_BUTTON_RELEASE:
1879                 DEBUGPOINT();
1880                 if(dragging==DRAG_GUIDE && curr_guide_is_x==true)
1881                 {
1882                         DEBUGPOINT();
1883                         dragging=DRAG_NONE;
1884                         get_guide_list_x().erase(curr_guide);
1885                 }
1886                 break;
1887                 return true;
1888         default:
1889                 break;
1890         }
1891 */
1892         return false;
1893 }
1894
1895
1896 void
1897 WorkArea::refresh_dimension_info()
1898 {
1899         synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
1900
1901         canvaswidth=rend_desc.get_br()[0]-rend_desc.get_tl()[0];
1902         canvasheight=rend_desc.get_br()[1]-rend_desc.get_tl()[1];
1903
1904         pw=canvaswidth/w;
1905         ph=canvasheight/h;
1906
1907         scrollx_adjustment.set_page_increment(abs(get_grid_size()[0]));
1908         scrollx_adjustment.set_step_increment(abs(pw));
1909         scrollx_adjustment.set_lower(-abs(canvaswidth));
1910         scrollx_adjustment.set_upper(abs(canvaswidth));
1911         scrolly_adjustment.set_lower(-abs(canvasheight));
1912         scrolly_adjustment.set_upper(abs(canvasheight));
1913         scrolly_adjustment.set_step_increment(abs(ph));
1914         scrolly_adjustment.set_page_increment(abs(get_grid_size()[1]));
1915
1916
1917
1918         if(drawing_area->get_width()<=0 || drawing_area->get_height()<=0 || w==0 || h==0)
1919                 return;
1920
1921         const synfig::Point focus_point(get_focus_point());
1922         const synfig::Real x(focus_point[0]/pw+drawing_area->get_width()/2-w/2);
1923         const synfig::Real y(focus_point[1]/ph+drawing_area->get_height()/2-h/2);
1924
1925         window_tl[0]=rend_desc.get_tl()[0]-pw*x;
1926         window_br[0]=rend_desc.get_br()[0]+pw*(drawing_area->get_width()-x-w);
1927
1928         window_tl[1]=rend_desc.get_tl()[1]-ph*y;
1929         window_br[1]=rend_desc.get_br()[1]+ph*(drawing_area->get_height()-y-h);
1930
1931         hruler->property_lower()=Distance(window_tl[0],Distance::SYSTEM_UNITS).get(App::distance_system,rend_desc);
1932         hruler->property_upper()=Distance(window_br[0],Distance::SYSTEM_UNITS).get(App::distance_system,rend_desc);
1933         vruler->property_lower()=Distance(window_tl[1],Distance::SYSTEM_UNITS).get(App::distance_system,rend_desc);
1934         vruler->property_upper()=Distance(window_br[1],Distance::SYSTEM_UNITS).get(App::distance_system,rend_desc);
1935
1936         view_window_changed();
1937 }
1938
1939
1940 synfig::Point
1941 WorkArea::screen_to_comp_coords(synfig::Point pos)const
1942 {
1943         synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
1944         //synfig::Vector::value_type canvaswidth=rend_desc.get_br()[0]-rend_desc.get_tl()[0];
1945         //synfig::Vector::value_type canvasheight=rend_desc.get_br()[1]-rend_desc.get_tl()[1];
1946         //synfig::Vector::value_type pw=canvaswidth/w;
1947         //synfig::Vector::value_type ph=canvasheight/h;
1948         Vector focus_point=get_focus_point();
1949         synfig::Vector::value_type x=focus_point[0]/pw+drawing_area->get_width()/2-w/2;
1950         synfig::Vector::value_type y=focus_point[1]/ph+drawing_area->get_height()/2-h/2;
1951
1952         return rend_desc.get_tl()-synfig::Point(pw*x,ph*y)+synfig::Point(pw*pos[0],ph*pos[1]);
1953 }
1954
1955 synfig::Point
1956 WorkArea::comp_to_screen_coords(synfig::Point /*pos*/)const
1957 {
1958         synfig::warning("WorkArea::comp_to_screen_coords: Not yet implemented");
1959         return synfig::Point();
1960 }
1961
1962 int
1963 WorkArea::next_unrendered_tile(int refreshes)const
1964 {
1965         //assert(!tile_book.empty());
1966         if(tile_book.empty())
1967                 return -1;
1968
1969         //const synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
1970
1971         const synfig::Vector focus_point(get_focus_point());
1972
1973         // Calculate the window coordinates of the top-left
1974         // corner of the canvas.
1975         const synfig::Vector::value_type
1976                 x(focus_point[0]/pw+drawing_area->get_width()/2-w/2),
1977                 y(focus_point[1]/ph+drawing_area->get_height()/2-h/2);
1978
1979         const int width_in_tiles(w/tile_w+(w%tile_w?1:0));
1980         const int height_in_tiles(h/tile_h+(h%tile_h?1:0));
1981
1982         int
1983                 u(0),v(0),
1984                 u1(int(-x/tile_w)),
1985                 v1(int(-y/tile_h)),
1986                 u2(int((-x+drawing_area->get_width())/tile_w+1)),
1987                 v2(int((-y+drawing_area->get_height())/tile_h+1));
1988
1989         if(u2>width_in_tiles)u2=width_in_tiles;
1990         if(v2>height_in_tiles)v2=height_in_tiles;
1991         if(u1<0)u1=0;
1992         if(v1<0)v1=0;
1993
1994         int last_good_tile(-1);
1995
1996         for(v=v1;v<v2;v++)
1997                 for(u=u1;u<u2;u++)
1998                 {
1999                         int index(v*width_in_tiles+u);
2000                         if(tile_book[index].second<refreshes)
2001                         {
2002                                 last_good_tile=index;
2003                                 if(rand()%8==0)
2004                                         return index;
2005                         }
2006                 }
2007         return last_good_tile;
2008 }
2009
2010 /*
2011 template <typename F, typename T=WorkAreaRenderer, typename R=typename F::result_type>
2012 class handle2ptr_t : public std::unary_function<typename etl::handle<T>,R>
2013 {
2014 private:
2015         F func;
2016 public:
2017         handle2ptr_t(const F &func):func(func) { };
2018
2019         R operator()(typename etl::handle<T> x) { return func(*x); }
2020 };
2021
2022 template <typename F>
2023 handle2ptr_t<F>
2024 handle2ptr(F func)
2025 {
2026         return handle2ptr_t<F>(func);
2027 }
2028         for_each(
2029                 renderer_set_.begin(),
2030                 renderer_set_.end(),
2031                 handle2ptr(
2032                         sigc::bind(
2033                                 sigc::bind(
2034                                         sigc::mem_fun(
2035                                                 &WorkAreaRenderer::render_vfunc
2036                                         ),
2037                                         Gdk::Rectangle(event->area)
2038                                 ),
2039                                 drawing_area->get_window()
2040                         )
2041                 )
2042         );
2043 */
2044
2045 bool
2046 WorkArea::refresh(GdkEventExpose*event)
2047 {
2048         assert(get_canvas());
2049
2050         drawing_area->get_window()->clear();
2051
2052         //const synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
2053
2054         const synfig::Vector focus_point(get_focus_point());
2055
2056         // Update the old focus point
2057         last_focus_point=focus_point;
2058
2059         // Draw out the renderables
2060         {
2061                 std::set<etl::handle<WorkAreaRenderer> >::iterator iter;
2062                 for(iter=renderer_set_.begin();iter!=renderer_set_.end();++iter)
2063                 {
2064                         if((*iter)->get_enabled())
2065                                 (*iter)->render_vfunc(
2066                                         drawing_area->get_window(),
2067                                         Gdk::Rectangle(&event->area)
2068                                 );
2069                 }
2070         }
2071
2072         // Calculate the window coordinates of the top-left
2073         // corner of the canvas.
2074         //const synfig::Vector::value_type
2075         //      x(focus_point[0]/pw+drawing_area->get_width()/2-w/2),
2076         //      y(focus_point[1]/ph+drawing_area->get_height()/2-h/2);
2077
2078         //const synfig::Vector::value_type window_startx(window_tl[0]);
2079         //const synfig::Vector::value_type window_endx(window_br[0]);
2080         //const synfig::Vector::value_type window_starty(window_tl[1]);
2081         //const synfig::Vector::value_type window_endy(window_br[1]);
2082
2083         Glib::RefPtr<Gdk::GC> gc=Gdk::GC::create(drawing_area->get_window());
2084
2085         // If we are in animate mode, draw a red border around the screen
2086         if(canvas_interface->get_mode()&synfigapp::MODE_ANIMATE)
2087         {
2088 // #define USE_FRAME_BACKGROUND_TO_SHOW_EDIT_MODE
2089 #ifdef USE_FRAME_BACKGROUND_TO_SHOW_EDIT_MODE
2090                 // This method of drawing the red border doesn't work on any
2091                 // Gtk theme which uses the crux-engine, hcengine, industrial,
2092                 // mist, or ubuntulooks engine, such as the default ubuntu
2093                 // 'Human' theme.
2094                 drawing_frame->modify_bg(Gtk::STATE_NORMAL,Gdk::Color("#FF0000"));
2095 #else
2096                 // So let's do it in a more primitive fashion.
2097                 gc->set_rgb_fg_color(Gdk::Color("#FF0000"));
2098                 gc->set_line_attributes(1,Gdk::LINE_SOLID,Gdk::CAP_BUTT,Gdk::JOIN_MITER);
2099                 drawing_area->get_window()->draw_rectangle(
2100                         gc,
2101                         false,  // Fill?
2102                         0,0,    // x,y
2103                         drawing_area->get_width()-1,drawing_area->get_height()-1); // w,h
2104 #endif
2105         }
2106 #ifdef USE_FRAME_BACKGROUND_TO_SHOW_EDIT_MODE
2107         else
2108                 drawing_frame->unset_bg(Gtk::STATE_NORMAL);
2109 #endif
2110
2111         previous_focus=get_focus_point();
2112
2113         return true;
2114 }
2115
2116 void
2117 WorkArea::done_rendering()
2118 {
2119 /*
2120         assert(buffer);
2121         assert(w>0);
2122         assert(h>0);
2123         pix_buf=Gdk::Pixbuf::create_from_data(
2124                 buffer, // pointer to the data
2125                 Gdk::COLORSPACE_RGB, // the colorspace
2126                 true, // has alpha?
2127                 8, // bits per sample
2128                 w,      // width
2129                 h,      // height
2130                 w*bpp); // stride (pitch)
2131         assert(pix_buf);
2132 */
2133 }
2134
2135
2136 void
2137 WorkArea::set_quality(int x)
2138 {
2139         if(x==quality)
2140                 return;
2141         quality=x;
2142         queue_render_preview();
2143 }
2144
2145
2146 namespace studio
2147 {
2148 class WorkAreaProgress : public synfig::ProgressCallback
2149 {
2150         WorkArea *work_area;
2151         ProgressCallback *cb;
2152
2153 public:
2154
2155         WorkAreaProgress(WorkArea *work_area,ProgressCallback *cb):
2156                 work_area(work_area),cb(cb)
2157         {
2158                 assert(cb);
2159         }
2160
2161         virtual bool
2162         task(const std::string &str)
2163         {
2164                 if(work_area->dirty)
2165                         return false;
2166                 return cb->task(str);
2167         }
2168
2169         virtual bool
2170         error(const std::string &err)
2171         {
2172                 if(work_area->dirty)
2173                         return false;
2174                 return cb->error(err);
2175         }
2176
2177         virtual bool
2178         amount_complete(int current, int total)
2179         {
2180                 if(work_area->dirty)
2181                         return false;
2182                 return cb->amount_complete(current,total);
2183         }
2184 };
2185 }
2186
2187 bool
2188 studio::WorkArea::async_update_preview()
2189 {
2190         if (get_updating())
2191         {
2192                 stop_updating();
2193                 return false;
2194         }
2195
2196         async_renderer=0;
2197
2198         queued=false;
2199         canceled_=false;
2200         get_canvas_view()->reset_cancel_status();
2201
2202         // This object will mark us as busy until
2203         // we are done.
2204         //studio::App::Busy busy;
2205
2206         //WorkAreaProgress callback(this,get_canvas_view()->get_ui_interface().get());
2207         //synfig::ProgressCallback *cb=&callback;
2208
2209         if(!is_visible())return false;
2210
2211         /*
2212         // If we are queued to render the scene at the next idle
2213         // go ahead and de-queue it.
2214         if(render_idle_func_id)
2215         {
2216                 g_source_remove(render_idle_func_id);
2217                 //queued=false;
2218                 render_idle_func_id=0;
2219         }
2220         */
2221
2222         dirty=false;
2223         get_canvas_view()->reset_cancel_status();
2224
2225         //bool ret=false;
2226         RendDesc desc=get_canvas()->rend_desc();
2227
2228         int w=(int)(desc.get_w()*zoom);
2229         int h=(int)(desc.get_h()*zoom);
2230
2231         // Setup the description parameters
2232         desc.set_antialias(1);
2233         desc.set_time(cur_time);
2234
2235         set_rend_desc(desc);
2236
2237         // Create the render target
2238         handle<Target> target;
2239
2240         if(w*h>(low_resolution?480*270:480*270/2))
2241         {
2242                 handle<WorkAreaTarget> trgt(new class WorkAreaTarget(this,w,h));
2243
2244                 trgt->set_rend_desc(&desc);
2245                 trgt->set_onion_skin(get_onion_skin());
2246                 target=trgt;
2247         }
2248         else
2249         {
2250                 handle<WorkAreaTarget_Full> trgt(new class WorkAreaTarget_Full(this,w,h));
2251
2252                 trgt->set_rend_desc(&desc);
2253                 trgt->set_onion_skin(get_onion_skin());
2254                 target=trgt;
2255         }
2256
2257         // We can rest assured that our time has already
2258         // been set, so there is no need to have to
2259         // recalculate that over again.
2260         // UPDATE: This is kind of needless with
2261         // the way that time is handled now in SYNFIG.
2262         //target->set_avoid_time_sync(true);
2263         async_renderer=new AsyncRenderer(target);
2264         async_renderer->signal_finished().connect(
2265                 sigc::mem_fun(this,&WorkArea::async_update_finished)
2266         );
2267
2268         rendering=true;
2269         async_renderer->start();
2270
2271         synfig::ProgressCallback *cb=get_canvas_view()->get_ui_interface().get();
2272
2273         rendering=true;
2274         cb->task("Rendering...");
2275         rendering=true;
2276
2277         return true;
2278 }
2279
2280 void
2281 studio::WorkArea::async_update_finished()
2282 {
2283         synfig::ProgressCallback *cb=get_canvas_view()->get_ui_interface().get();
2284
2285         rendering=false;
2286
2287         if(!async_renderer)
2288                 return;
2289
2290         // If we completed successfully, then
2291         // we aren't dirty anymore
2292         if(async_renderer->has_success())
2293         {
2294                 dirty=false;
2295                 //queued=false;
2296                 cb->task("Idle");
2297         }
2298         else
2299         {
2300                 dirty=true;
2301                 cb->task("Render Failed");
2302         }
2303         //get_canvas_view()->reset_cancel_status();
2304         done_rendering();
2305 }
2306
2307 bool
2308 studio::WorkArea::sync_update_preview()
2309 {
2310         //      const Time &time(cur_time);
2311
2312         canceled_=false;
2313         get_canvas_view()->reset_cancel_status();
2314
2315         async_renderer=0;
2316
2317 again:
2318         // This object will mark us as busy until
2319         // we are done.
2320         studio::App::Busy busy;
2321
2322         WorkAreaProgress callback(this,get_canvas_view()->get_ui_interface().get());
2323         synfig::ProgressCallback *cb=&callback;
2324
2325         // We don't want to render if we are already rendering
2326         if(rendering)
2327         {
2328                 dirty=true;
2329                 return false;
2330         }
2331
2332         if(!is_visible())return false;
2333         get_canvas()->set_time(get_time());
2334         get_canvas_view()->get_smach().process_event(EVENT_REFRESH_DUCKS);
2335         signal_rendering()();
2336
2337         // If we are queued to render the scene at the next idle
2338         // go ahead and de-queue it.
2339         if(render_idle_func_id)
2340         {
2341                 g_source_remove(render_idle_func_id);
2342                 //queued=false;
2343                 render_idle_func_id=0;
2344         }
2345         // Start rendering
2346         rendering=true;
2347
2348         dirty=false;
2349         get_canvas_view()->reset_cancel_status();
2350
2351         RendDesc desc=get_canvas()->rend_desc();
2352         //newdesc->set_flags(RendDesc::PX_ASPECT|RendDesc::IM_SPAN);
2353
2354         int w=(int)(desc.get_w()*zoom);
2355         int h=(int)(desc.get_h()*zoom);
2356
2357         // Setup the description parameters
2358         desc.set_antialias(1);
2359         desc.set_time(cur_time);
2360         //desc.set_wh(w,h);
2361
2362         set_rend_desc(desc);
2363
2364         // Create the render target
2365         handle<WorkAreaTarget> target(new class WorkAreaTarget(this,w,h));
2366
2367         target->set_rend_desc(&desc);
2368
2369         // We can rest assured that our time has already
2370         // been set, so there is no need to have to
2371         // recalculate that over again.
2372         target->set_avoid_time_sync(true);
2373
2374         if(cb)
2375                 cb->task(strprintf("Rendering canvas %s...",get_canvas()->get_name().c_str()));
2376
2377         bool ret = target->render(cb);
2378
2379         if(!ret && !get_canvas_view()->get_cancel_status() && dirty)
2380         {
2381                 rendering=false;
2382                 //canceled_=true;
2383                 goto again;
2384         }
2385         if(get_canvas_view()->get_cancel_status())
2386                 canceled_=true;
2387
2388         if(cb)
2389         {
2390                 if(ret)
2391                         cb->task("Idle");
2392                 else
2393                         cb->task("Render Failed");
2394                 cb->amount_complete(0,1);
2395         }
2396
2397         // Refresh the work area to make sure that
2398         // it is being displayed correctly
2399         drawing_area->queue_draw();
2400
2401         // If we completed successfully, then
2402         // we aren't dirty anymore
2403         if(ret)
2404         {
2405                 dirty=false;
2406                 //queued=false;
2407         }
2408         else dirty=true;
2409         rendering=false;
2410         //get_canvas_view()->reset_cancel_status();
2411         done_rendering();
2412         return ret;
2413 }
2414
2415 void
2416 studio::WorkArea::async_render_preview(Time time)
2417 {
2418         cur_time=time;
2419         //tile_book.clear();
2420
2421         refreshes+=5;
2422         if(!is_visible())return;
2423
2424         get_canvas()->set_time(get_time());
2425         get_canvas_view()->get_smach().process_event(EVENT_REFRESH_DUCKS);
2426         signal_rendering()();
2427
2428         async_update_preview();
2429 }
2430 void
2431 WorkArea::async_render_preview()
2432 {
2433         return async_render_preview(get_canvas_view()->get_time());
2434 }
2435
2436 bool
2437 studio::WorkArea::sync_render_preview(Time time)
2438 {
2439         cur_time=time;
2440         //tile_book.clear();
2441         refreshes+=5;
2442         if(!is_visible())return false;
2443         return sync_update_preview();
2444 }
2445
2446 bool
2447 WorkArea::sync_render_preview()
2448 {
2449         return sync_render_preview(get_canvas_view()->get_time());
2450 }
2451
2452 void
2453 WorkArea::sync_render_preview_hook()
2454 {
2455         sync_render_preview(get_canvas_view()->get_time());
2456 }
2457
2458 void
2459 WorkArea::queue_scroll()
2460 {
2461 //      const synfig::RendDesc &rend_desc(get_canvas()->rend_desc());
2462
2463         const synfig::Point focus_point(get_focus_point());
2464
2465         const synfig::Real
2466                 new_x(focus_point[0]/pw+drawing_area->get_width()/2-w/2),
2467                 new_y(focus_point[1]/ph+drawing_area->get_height()/2-h/2);
2468
2469         const synfig::Real
2470                 old_x(last_focus_point[0]/pw+drawing_area->get_width()/2-w/2),
2471                 old_y(last_focus_point[1]/ph+drawing_area->get_height()/2-h/2);
2472
2473         // If the coordinates didn't change, we shouldn't queue a draw
2474         if(old_x==new_x && old_y==new_y)
2475                 return;
2476
2477         const int
2478                 dx(round_to_int(old_x)-round_to_int(new_x)),
2479                 dy(round_to_int(old_y)-round_to_int(new_y));
2480
2481         drawing_area->get_window()->scroll(-dx,-dy);
2482
2483         if (timecode_width && timecode_height)
2484         {
2485                 drawing_area->queue_draw_area(4,       4,    4+timecode_width,    4+timecode_height);
2486                 drawing_area->queue_draw_area(4-dx, 4-dy, 4-dx+timecode_width, 4-dy+timecode_height);
2487         }
2488
2489 #ifndef USE_FRAME_BACKGROUND_TO_SHOW_EDIT_MODE
2490         if(canvas_interface->get_mode()&synfigapp::MODE_ANIMATE)
2491         {
2492                 int maxx = drawing_area->get_width()-1;
2493                 int maxy = drawing_area->get_height()-1;
2494
2495                 if (dx > 0)
2496                 {
2497                         drawing_area->queue_draw_area(      0, 0,       1, maxy);
2498                         drawing_area->queue_draw_area(maxx-dx, 0, maxx-dx, maxy);
2499                 }
2500                 else if (dx < 0) 
2501                 {
2502                         drawing_area->queue_draw_area(   maxx, 0,    maxx, maxy);
2503                         drawing_area->queue_draw_area(    -dx, 0,     -dx, maxy);
2504                 }
2505                 if (dy > 0)
2506                 {
2507                         drawing_area->queue_draw_area(0,       0, maxx,       1);
2508                         drawing_area->queue_draw_area(0, maxy-dy, maxx, maxy-dy);
2509                 }
2510                 else if (dy < 0) 
2511                 {
2512                         drawing_area->queue_draw_area(0,    maxy, maxx,    maxy);
2513                         drawing_area->queue_draw_area(0,     -dy, maxx,     -dy);
2514                 }
2515         }
2516 #endif // USE_FRAME_BACKGROUND_TO_SHOW_EDIT_MODE
2517
2518         last_focus_point=focus_point;
2519 }
2520
2521 void
2522 studio::WorkArea::zoom_in()
2523 {
2524         set_zoom(zoom*1.25);
2525 }
2526
2527 void
2528 studio::WorkArea::zoom_out()
2529 {
2530         set_zoom(zoom/1.25);
2531 }
2532
2533 void
2534 studio::WorkArea::zoom_fit()
2535 {
2536         // This really doesn't zoom to fit. Bug.
2537         zoom_norm();
2538 }
2539
2540 void
2541 studio::WorkArea::zoom_norm()
2542 {
2543         if(zoom==1.0)
2544                 set_zoom(prev_zoom);
2545         else
2546         {
2547                 prev_zoom=zoom;
2548                 set_zoom(1.0f);
2549         }
2550 }
2551
2552 gboolean
2553 studio::WorkArea::__render_preview(gpointer data)
2554 {
2555         WorkArea *work_area(static_cast<WorkArea*>(data));
2556
2557         // there's no point anyone trying to cancel the timer now - it's gone off already
2558         work_area->render_idle_func_id = 0;
2559
2560         work_area->queued=false;
2561         work_area->async_render_preview(work_area->get_canvas_view()->get_time());
2562
2563         return 0;
2564 }
2565
2566 void
2567 studio::WorkArea::queue_render_preview()
2568 {
2569         //synfig::info("queue_render_preview(): called for %s", get_canvas_view()->get_time().get_string().c_str());
2570
2571         if(queued==true)
2572         {
2573                 return;
2574                 //synfig::info("queue_render_preview(): already queued, unqueuing");
2575 /*              if(render_idle_func_id)
2576                         g_source_remove(render_idle_func_id);
2577                 render_idle_func_id=0;
2578                 queued=false;
2579 */
2580                 //async_renderer=0;
2581         }
2582
2583         if(dirty_trap_enabled)
2584         {
2585                 dirty_trap_queued++;
2586                 return;
2587         }
2588
2589         int queue_time=50;
2590
2591         if(rendering)
2592                 queue_time+=250;
2593
2594
2595         if(queued==false)
2596         {
2597                 //synfig::info("queue_render_preview(): (re)queuing...");
2598                 //render_idle_func_id=g_idle_add_full(G_PRIORITY_DEFAULT,__render_preview,this,NULL);
2599                 render_idle_func_id=g_timeout_add_full(
2600                         G_PRIORITY_DEFAULT,     // priority - 
2601                         queue_time,                     // interval - the time between calls to the function, in milliseconds (1/1000ths of a second)
2602                         __render_preview,       // function - function to call
2603                         this,                           // data     - data to pass to function
2604                         NULL);                          // notify   - function to call when the idle is removed, or NULL
2605                 queued=true;
2606         }
2607 /*      else if(rendering)
2608         {
2609                 refreshes+=5;
2610                 dirty=true;
2611                 queue_draw();
2612         }
2613 */
2614 }
2615
2616 DirtyTrap::DirtyTrap(WorkArea *work_area):work_area(work_area)
2617 {
2618         work_area->dirty_trap_enabled=true;
2619
2620         work_area->dirty_trap_queued=0;
2621 }
2622
2623 DirtyTrap::~DirtyTrap()
2624 {
2625         work_area->dirty_trap_enabled=false;
2626         if(work_area->dirty_trap_queued)
2627                 work_area->queue_render_preview();
2628 }
2629
2630 void
2631 studio::WorkArea::queue_draw_preview()
2632 {
2633         drawing_area->queue_draw();
2634 }
2635
2636 void
2637 studio::WorkArea::set_cursor(const Gdk::Cursor& x)
2638 {
2639         drawing_area->get_window()->set_cursor(x);
2640 }
2641 void
2642 studio::WorkArea::set_cursor(Gdk::CursorType x)
2643 {
2644         drawing_area->get_window()->set_cursor(Gdk::Cursor(x));
2645 }
2646
2647 #include "iconcontroler.h"
2648
2649 void
2650 studio::WorkArea::refresh_cursor()
2651 {
2652 //      set_cursor(IconControler::get_tool_cursor(canvas_view->get_smach().get_state_name(),drawing_area->get_window()));
2653 }
2654
2655 void
2656 studio::WorkArea::reset_cursor()
2657 {
2658         drawing_area->get_window()->set_cursor(Gdk::Cursor(Gdk::TOP_LEFT_ARROW));
2659 //      set_cursor(Gdk::TOP_LEFT_ARROW);
2660 }
2661
2662 void
2663 studio::WorkArea::set_zoom(float z)
2664 {
2665         z=max(1.0f/128.0f,min(128.0f,z));
2666         if(z==zoom)
2667                 return;
2668         zoom = z;
2669         refresh_dimension_info();
2670         /*if(async_renderer)
2671         {
2672                 async_renderer->stop();
2673                 async_renderer=0;
2674         }*/
2675         refreshes+=5;
2676         async_update_preview();
2677         //queue_render_preview();
2678 }
2679
2680 void
2681 WorkArea::set_selected_value_node(etl::loose_handle<synfig::ValueNode> x)
2682 {
2683         if(x!=selected_value_node_)
2684         {
2685                 selected_value_node_=x;
2686                 queue_draw();
2687         }
2688 }
2689
2690 void
2691 WorkArea::insert_renderer(const etl::handle<WorkAreaRenderer> &x)
2692 {
2693         renderer_set_.insert(x);
2694         x->set_work_area(this);
2695         queue_draw();
2696 }
2697
2698 void
2699 WorkArea::insert_renderer(const etl::handle<WorkAreaRenderer> &x, int priority)
2700 {
2701         x->set_priority(priority);
2702         insert_renderer(x);
2703 }
2704
2705 void
2706 WorkArea::erase_renderer(const etl::handle<WorkAreaRenderer> &x)
2707 {
2708         x->set_work_area(0);
2709         renderer_set_.erase(x);
2710         queue_draw();
2711 }
2712
2713 void
2714 WorkArea::resort_render_set()
2715 {
2716         std::set<etl::handle<WorkAreaRenderer> > tmp(
2717                 renderer_set_.begin(),
2718                 renderer_set_.end()
2719         );
2720         renderer_set_.swap(tmp);
2721         queue_draw();
2722 }