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