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