Fix a crash when running single-threaded and dragging the time slider.
[synfig.git] / synfig-studio / trunk / src / gtkmm / dock_navigator.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file dock_navigator.cpp
3 **      \brief Dock Nagivator File
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007 Chris Moore
10 **
11 **      This package is free software; you can redistribute it and/or
12 **      modify it under the terms of the GNU General Public License as
13 **      published by the Free Software Foundation; either version 2 of
14 **      the License, or (at your option) any later version.
15 **
16 **      This package is distributed in the hope that it will be useful,
17 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
18 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 **      General Public License for more details.
20 **      \endlegal
21 */
22 /* ========================================================================= */
23
24 /* === H E A D E R S ======================================================= */
25
26 #ifdef USING_PCH
27 #       include "pch.h"
28 #else
29 #ifdef HAVE_CONFIG_H
30 #       include <config.h>
31 #endif
32
33 #include "dock_navigator.h"
34 #include "canvasview.h"
35 #include "workarea.h"
36
37 #include <cassert>
38 #include <synfig/canvas.h>
39 #include <synfig/context.h>
40 #include <synfig/target_scanline.h>
41 #include <synfig/surface.h>
42
43 #include <gtkmm/separator.h>
44
45 #include "asyncrenderer.h"
46
47 #endif
48
49 /* === U S I N G =========================================================== */
50
51 using namespace std;
52 using namespace etl;
53 using namespace synfig;
54
55 /* === M A C R O S ========================================================= */
56
57 const double log_10_2 = log(2.0);
58
59 /* === G L O B A L S ======================================================= */
60
61 /* === P R O C E D U R E S ================================================= */
62
63 /* === M E T H O D S ======================================================= */
64
65 /* === E N T R Y P O I N T ================================================= */
66 studio::Widget_NavView::Widget_NavView(CanvasView::LooseHandle cv)
67 :canvview(cv),
68 adj_zoom(0,-4,4,1,2),
69 scrolling(false),
70 surface(new synfig::Surface)
71 {
72         attach(drawto,0,4,0,1);
73
74         attach(*manage(new Gtk::HSeparator),0,4,1,2,Gtk::SHRINK|Gtk::FILL,Gtk::SHRINK|Gtk::FILL);
75
76         //zooming stuff
77         attach(zoom_print,0,1,2,3,Gtk::SHRINK|Gtk::FILL,Gtk::SHRINK|Gtk::FILL);
78         zoom_print.set_size_request(40,-1);
79
80         Gtk::HScale *s = manage(new Gtk::HScale(adj_zoom));
81         s->set_draw_value(false);
82         //s->set_update_policy(Gtk::UPDATE_DELAYED);
83         //s->signal_event().connect(sigc::mem_fun(*this,&Dock_Navigator::on_scroll_event));
84         attach(*s,1,4,2,3,Gtk::EXPAND|Gtk::FILL,Gtk::SHRINK|Gtk::FILL);
85
86         show_all();
87
88         adj_zoom.signal_value_changed().connect(sigc::mem_fun(*this,&Widget_NavView::on_number_modify));
89
90         if(cv)
91         {
92                 drawto.signal_expose_event().connect(sigc::mem_fun(*this,&Widget_NavView::on_expose_draw));
93                 drawto.signal_event().connect(sigc::mem_fun(*this,&Widget_NavView::on_mouse_event));
94
95                 drawto.add_events(Gdk::BUTTON_MOTION_MASK|Gdk::BUTTON_PRESS_MASK);
96
97                 //get_canvas_view()->canvas_interface()->signal_dirty_preview()
98                 //                              .connect(sigc::mem_fun(*this,&Widget_NavView::on_dirty_preview));
99                 get_canvas_view()->work_area->signal_rendering()
100                                                 .connect(sigc::mem_fun(*this,&Widget_NavView::on_dirty_preview));
101
102                 get_canvas_view()->work_area->signal_view_window_changed()
103                                                 .connect(sigc::mem_fun(*this,&Widget_NavView::on_workarea_view_change));
104
105                 //update with this canvas' view
106                 on_workarea_view_change();
107
108                 dirty = true;
109                 queue_draw();
110         }
111
112         adj_zoom.set_value(0);
113 }
114
115 studio::Widget_NavView::~Widget_NavView()
116 {
117 }
118
119
120 static void freegu8(const guint8 *p)
121 {
122         delete [] p;
123 }
124
125 void studio::Widget_NavView::on_start_render()
126 {
127         if(dirty)
128         {
129                 //synfig::warning("Nav: Starting render");
130                 //synfig::warning("Nav: Rendering canvas");
131                 etl::handle<Target_Scanline>    targ = surface_target(surface.get());
132
133                 targ->set_canvas(get_canvas_view()->get_canvas());
134                 targ->set_remove_alpha();
135                 targ->set_avoid_time_sync();
136                 targ->set_quality(get_canvas_view()->get_work_area()->get_quality());
137                 //synfig::info("Set the quality level to: %d", get_canvas_view()->get_work_area()->get_quality());
138
139                 //this should set it to render a single frame
140                 RendDesc        r = get_canvas_view()->get_canvas()->rend_desc();
141                 r.set_time(get_canvas_view()->canvas_interface()->get_time());
142
143                 //this changes the size of the canvas to the closest thing we can find
144                 int sw = r.get_w(), sh = r.get_h();
145
146                 //synfig::warning("Nav: source image is %d x %d", sw,sh);
147
148                 //resize so largest dimension is 128
149                 int dw = sw > sh ? 128 : sw*128/sh,
150                         dh = sh > sw ? 128 : sh*128/sw;
151
152                 //synfig::warning("Nav: dest image is %d x %d", dw,dh);
153
154                 r.set_w(dw);
155                 r.set_h(dh);
156
157                 //get the pw and ph
158                 //float pw = r.get_pw();
159                 //float ph = r.get_ph();
160
161                 //synfig::warning("Nav: pixel size is %f x %f", pw,ph);
162
163                 //this renders that single frame
164                 targ->set_rend_desc(&r);
165
166                 //synfig::warning("Nav: Building async renderer and starting it...");
167
168                 renderer = new AsyncRenderer(targ);
169                 renderer->signal_success().connect(sigc::mem_fun(*this,&Widget_NavView::on_finish_render));
170                 dirty = false;
171                 renderer->start();
172         }
173 }
174
175 void studio::Widget_NavView::on_finish_render()
176 {
177         //convert it into our pixmap
178         PixelFormat pf(PF_RGB);
179
180         //synfig::warning("Nav: It hath succeeded!!!");
181
182         //assert(renderer && renderer->has_success());
183         DEBUGPOINT();
184         //synfig::warning("Nav: now we know it really succeeded");
185         if(!*surface)
186         {
187                 synfig::warning("dock_navigator: Bad surface");
188                 return;
189         }
190
191         int w = 0, h = 0;
192         int dw = surface->get_w();
193         int dh = surface->get_h();
194
195         if(prev)
196         {
197                 w = prev->get_width();
198                 h = prev->get_height();
199         }
200
201         if(w != dw || h != dh || !prev)
202         {
203                 const int total_bytes(dw*dh*synfig::channels(pf));
204
205                 //synfig::warning("Nav: Updating the pixbuf to be the right size, etc. (%d bytes)", total_bytes);
206
207                 prev.clear();
208                 guint8 *bytes = new guint8[total_bytes]; //24 bits per pixel
209
210                 //convert into our buffered dataS
211                 //synfig::warning("Nav: converting color format into buffer");
212                 convert_color_format((unsigned char *)bytes, (*surface)[0], dw*dh, pf, App::gamma);
213
214                 prev =
215                 Gdk::Pixbuf::create_from_data(
216                         bytes,  // pointer to the data
217                         Gdk::COLORSPACE_RGB, // the colorspace
218                         ((pf&PF_A)==PF_A), // has alpha?
219                         8, // bits per sample
220                         dw,     // width
221                         dh,     // height
222                         dw*synfig::channels(pf), // stride (pitch)
223                         SigC::slot(freegu8)
224                 );
225         }
226         else
227         {
228                 //synfig::warning("Nav: Don't need to resize");
229                 //convert into our buffered dataS
230                 //synfig::warning("Nav: converting color format into buffer");
231                 if(prev) //just in case we're stupid
232                 {
233                         convert_color_format((unsigned char *)prev->get_pixels(), (*surface)[0], dw*dh, pf, App::gamma);
234                 }
235         }
236         queue_draw();
237 }
238
239 /*      zoom slider is on exponential scale
240
241         map: -4,4 -> small number,1600 with 100 at 0
242
243         f(x) = 100*2^x
244 */
245
246 static double unit_to_zoom(double f)
247 {
248         return pow(2.0,f);
249 }
250
251 static double zoom_to_unit(double f)
252 {
253         if(f > 0)
254         {
255                 return log(f) / log_10_2;
256         }else return -999999.0;
257 }
258
259 bool studio::Widget_NavView::on_expose_draw(GdkEventExpose */*exp*/)
260 {
261         // don't redraw if the previous redraw is still running single-threaded
262         // or we end up destroying the renderer that's rendering it
263         if (App::single_threaded && renderer && renderer->updating)
264                 return false;
265
266         //print out the zoom
267         //HACK kind of...
268         //zoom_print.set_text(strprintf("%.1f%%",100*unit_to_zoom(adj_zoom.get_value())));
269
270         //draw the good stuff
271         on_start_render();
272
273         //if we've got a preview etc. display it...
274         if(get_canvas_view() && prev)
275         {
276                 //axis transform from units to pixel coords
277                 float xaxis = 0, yaxis = 0;
278
279                 int canvw = get_canvas_view()->get_canvas()->rend_desc().get_w();
280                 //int canvh = get_canvas_view()->get_canvas()->rend_desc().get_h();
281
282                 float pw = get_canvas_view()->get_canvas()->rend_desc().get_pw();
283                 float ph = get_canvas_view()->get_canvas()->rend_desc().get_ph();
284
285                 int w = prev->get_width();
286                 int h = prev->get_height();
287
288                 //scale up/down to the nearest pixel ratio...
289                 //and center in center
290                 int offx=0, offy=0;
291
292                 float sx, sy;
293                 int nw,nh;
294
295                 sx = drawto.get_width() / (float)w;
296                 sy = drawto.get_height() / (float)h;
297
298                 //synfig::warning("Nav redraw: now to scale the bitmap: %.3f x %.3f",sx,sy);
299
300                 //round to smallest scale (fit entire thing in window without distortion)
301                 if(sx > sy) sx = sy;
302                 //else sy = sx;
303
304                 //scaling and stuff
305                 // the point to navpixel space conversion should be:
306                 //              (navpixels / canvpixels) * (canvpixels / canvsize)
307                 //      or (navpixels / prevpixels) * (prevpixels / navpixels)
308                 xaxis = sx * w / (float)canvw;
309                 yaxis = xaxis/ph;
310                 xaxis /= pw;
311
312                 //scale to a new pixmap and then copy over to the window
313                 nw = (int)(w*sx);
314                 nh = (int)(h*sx);
315
316                 //must now center to be cool
317                 offx = (drawto.get_width() - nw)/2;
318                 offy = (drawto.get_height() - nh)/2;
319
320                 //trivial escape
321                 if(nw == 0 || nh == 0)return true;
322
323                 //draw to drawing area
324                 Glib::RefPtr<Gdk::GC>   gc = Gdk::GC::create(drawto.get_window());
325
326                 //synfig::warning("Nav: Scaling pixmap to off (%d,%d) with size (%d,%d)", offx,offy,nw, nh);
327                 Glib::RefPtr<Gdk::Pixbuf> scalepx = prev->scale_simple(nw,nh,Gdk::INTERP_NEAREST);
328
329                 //synfig::warning("Nav: Drawing scaled bitmap");
330                 drawto.get_window()->draw_pixbuf(
331                         gc, //GC
332                         scalepx, //pixbuf
333                         0, 0,   // Source X and Y
334                         offx, offy,     // Dest X and Y
335                         -1,-1,  // Width and Height
336                         Gdk::RGB_DITHER_MAX, // RgbDither
337                         2, 2 // Dither offset X and Y
338                 );
339
340                 //draw fancy red rectangle around focus point
341                 const Point &wtl = get_canvas_view()->work_area->get_window_tl(),
342                                         &wbr = get_canvas_view()->work_area->get_window_br();
343
344                 gc->set_rgb_fg_color(Gdk::Color("#ff0000"));
345                 gc->set_line_attributes(2,Gdk::LINE_SOLID,Gdk::CAP_BUTT,Gdk::JOIN_MITER);
346
347                 //it must be clamped to the drawing area though
348                 int l=0,rw=0,t=0,rh=0;
349                 const Point fp = -get_canvas_view()->work_area->get_focus_point();
350
351                 //get focus point in normal space
352                 rw = (int)(abs((wtl[0]-wbr[0])*xaxis));
353                 rh = (int)(abs((wtl[1]-wbr[1])*yaxis));
354
355                 //transform into pixel space
356                 l = (int)(drawto.get_width()/2 + fp[0]*xaxis - rw/2);
357                 t = (int)(drawto.get_height()/2 + fp[1]*yaxis - rh/2);
358
359                 //coord system:
360                 // tl : (offx,offy)
361                 // axis multipliers = xaxis,yaxis
362                 //synfig::warning("Nav: tl (%f,%f), br (%f,%f)", wtl[0],wtl[1],wbr[0],wbr[1]);
363                 //synfig::warning("Nav: tl (%f,%f), br (%f,%f)", wtl[0],wtl[1],wbr[0],wbr[1]);
364                 //synfig::warning("Nav: Drawing Rectangle (%d,%d) with dim (%d,%d)", l,t,rw,rh);
365                 drawto.get_window()->draw_rectangle(gc,false,l,t,rw,rh);
366         }
367
368         return false; //draw everything else too
369 }
370
371 void studio::Widget_NavView::on_dirty_preview()
372 {
373         dirty = true;
374         queue_draw();
375 }
376
377 bool studio::Widget_NavView::on_scroll_event(GdkEvent *event)
378 {
379         if(get_canvas_view() && get_canvas_view()->get_work_area())
380         {
381                 double z = unit_to_zoom(adj_zoom.get_value());
382
383                 switch(event->type)
384                 {
385                         case GDK_BUTTON_PRESS:
386                         {
387                                 if(event->button.button == 1)
388                                 {
389                                         scrolling = true;
390                                         get_canvas_view()->get_work_area()->set_zoom(z);
391                                         scrolling = false;
392                                 }
393                                 break;
394                         }
395
396                         case GDK_MOTION_NOTIFY:
397                         {
398                                 if(Gdk::ModifierType(event->motion.state) & Gdk::BUTTON1_MASK)
399                                 {
400                                         scrolling = true;
401                                         get_canvas_view()->get_work_area()->set_zoom(z);
402                                         scrolling = false;
403                                 }
404                                 break;
405                         }
406
407                         default:
408                                 break;
409                 }
410         }
411
412         return false;
413 }
414
415 void studio::Widget_NavView::on_number_modify()
416 {
417         double z = unit_to_zoom(adj_zoom.get_value());
418         zoom_print.set_text(strprintf("%.1f%%",z*100.0));
419         //synfig::warning("Updating zoom to %f",adj_zoom.get_value());
420
421         if(get_canvas_view() && z != get_canvas_view()->get_work_area()->get_zoom())
422         {
423                 scrolling = true;
424                 get_canvas_view()->get_work_area()->set_zoom(z);
425                 scrolling = false;
426         }
427 }
428
429 void studio::Widget_NavView::on_workarea_view_change()
430 {
431         double wz = get_canvas_view()->get_work_area()->get_zoom();
432         double z = zoom_to_unit(wz);
433
434         //synfig::warning("Updating zoom to %f -> %f",wz,z);
435         if(!scrolling && z != adj_zoom.get_value())
436         {
437                 adj_zoom.set_value(z);
438                 //adj_zoom.value_changed();
439         }
440         queue_draw();
441 }
442
443 bool studio::Widget_NavView::on_mouse_event(GdkEvent * e)
444 {
445         Point p;
446         bool    setpos = false;
447
448         if(e->type == GDK_BUTTON_PRESS && e->button.button == 1)
449         {
450                 p[0] = e->button.x - drawto.get_width()/2;
451                 p[1] = e->button.y - drawto.get_height()/2;
452
453                 setpos = true;
454         }
455
456         if(e->type == GDK_MOTION_NOTIFY && (Gdk::ModifierType(e->motion.state) & Gdk::BUTTON1_MASK))
457         {
458                 p[0] = e->motion.x - drawto.get_width()/2;
459                 p[1] = e->motion.y - drawto.get_height()/2;
460
461                 setpos = true;
462         }
463
464         if(setpos && prev && get_canvas_view())
465         {
466                 const Point &tl = get_canvas_view()->get_canvas()->rend_desc().get_tl();
467                 const Point &br = get_canvas_view()->get_canvas()->rend_desc().get_br();
468
469                 float max = abs((br[0]-tl[0]) / drawto.get_width());
470
471                 if((float(prev->get_width()) / drawto.get_width()) < (float(prev->get_height()) / drawto.get_height()))
472                         max = abs((br[1]-tl[1]) / drawto.get_height());
473
474                 float signx = (br[0]-tl[0]) < 0 ? -1 : 1;
475                 float signy = (br[1]-tl[1]) < 0 ? -1 : 1;
476
477                 Point pos;
478
479                 pos[0] = p[0] * max * signx;
480                 pos[1] = p[1] * max * signy;
481
482                 get_canvas_view()->get_work_area()->set_focus_point(-pos);
483
484                 return true;
485         }
486
487         return false;
488 }
489
490 //Navigator Dock Definitions
491
492 studio::Dock_Navigator::Dock_Navigator()
493 :Dock_CanvasSpecific("navigator",_("Navigator"),Gtk::StockID("synfig-navigator"))
494 {
495         add(dummy);
496 }
497
498 studio::Dock_Navigator::~Dock_Navigator()
499 {
500 }
501
502 void studio::Dock_Navigator::changed_canvas_view_vfunc(etl::loose_handle<CanvasView> canvas_view)
503 {
504         if(canvas_view)
505         {
506                 Widget *v = canvas_view->get_ext_widget("navview");
507
508                 if(!v)
509                 {
510                         v = new Widget_NavView(canvas_view);
511                         canvas_view->set_ext_widget("navview",v);
512                 }
513
514                 add(*v);
515         }else
516         {
517                 clear_previous();
518                 //add(dummy);
519         }
520 }