]> www.fi.muni.cz Git - evince.git/blob - libview/ev-view.c
help/C: updated section id's and screenshot
[evince.git] / libview / ev-view.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8; c-indent-level: 8 -*- */
2 /* this file is part of evince, a gnome document viewer
3  *
4  *  Copyright (C) 2004 Red Hat, Inc
5  *
6  * Evince is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * Evince is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24 #include <math.h>
25 #include <string.h>
26
27 #include <glib/gi18n-lib.h>
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30
31 #include "ev-mapping-list.h"
32 #include "ev-document-forms.h"
33 #include "ev-document-images.h"
34 #include "ev-document-links.h"
35 #include "ev-document-layers.h"
36 #include "ev-document-misc.h"
37 #include "ev-pixbuf-cache.h"
38 #include "ev-page-cache.h"
39 #include "ev-view-marshal.h"
40 #include "ev-document-annotations.h"
41 #include "ev-annotation-window.h"
42 #include "ev-loading-window.h"
43 #include "ev-view.h"
44 #include "ev-view-accessible.h"
45 #include "ev-view-private.h"
46 #include "ev-view-type-builtins.h"
47
48 #define EV_VIEW_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass), EV_TYPE_VIEW, EvViewClass))
49 #define EV_IS_VIEW_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), EV_TYPE_VIEW))
50 #define EV_VIEW_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), EV_TYPE_VIEW, EvViewClass))
51
52 enum {
53         SIGNAL_BINDING_ACTIVATED,
54         SIGNAL_HANDLE_LINK,
55         SIGNAL_EXTERNAL_LINK,
56         SIGNAL_POPUP_MENU,
57         SIGNAL_SELECTION_CHANGED,
58         SIGNAL_SYNC_SOURCE,
59         SIGNAL_ANNOT_ADDED,
60         SIGNAL_LAYERS_CHANGED,
61         N_SIGNALS
62 };
63
64 enum {
65         TARGET_DND_URI,
66         TARGET_DND_TEXT,
67         TARGET_DND_IMAGE
68 };
69
70 enum {
71         PROP_0,
72         PROP_HADJUSTMENT,
73         PROP_VADJUSTMENT,
74         PROP_HSCROLL_POLICY,
75         PROP_VSCROLL_POLICY
76 };
77
78 static guint signals[N_SIGNALS];
79
80 typedef enum {
81         EV_VIEW_FIND_NEXT,
82         EV_VIEW_FIND_PREV
83 } EvViewFindDirection;
84
85 typedef struct {
86         GtkWidget  *widget;
87
88         /* View coords */
89         gint        x;
90         gint        y;
91
92         /* Document */
93         guint       page;
94         EvRectangle doc_rect;
95 } EvViewChild;
96
97 #define ZOOM_IN_FACTOR  1.2
98 #define ZOOM_OUT_FACTOR (1.0/ZOOM_IN_FACTOR)
99
100 #define SCROLL_TIME 150
101
102 /*** Scrolling ***/
103 static void       view_update_range_and_current_page         (EvView             *view);
104 static void       add_scroll_binding_keypad                  (GtkBindingSet      *binding_set,
105                                                               guint               keyval,
106                                                               GdkModifierType modifiers,
107                                                               GtkScrollType       scroll,
108                                                               gboolean            horizontal);
109 static void       ensure_rectangle_is_visible                (EvView             *view,
110                                                               GdkRectangle       *rect);
111
112 /*** Geometry computations ***/
113 static void       compute_border                             (EvView             *view,
114                                                               int                 width,
115                                                               int                 height,
116                                                               GtkBorder          *border);
117 static void       get_page_y_offset                          (EvView             *view,
118                                                               int                 page,
119                                                               int                *y_offset);
120 static void       view_rect_to_doc_rect                      (EvView             *view,
121                                                               GdkRectangle       *view_rect,
122                                                               GdkRectangle       *page_area,
123                                                               EvRectangle        *doc_rect);
124 static void       doc_rect_to_view_rect                      (EvView             *view,
125                                                               int                 page,
126                                                               EvRectangle        *doc_rect,
127                                                               GdkRectangle       *view_rect);
128 static gboolean   get_dual_even_left                         (EvView             *view);
129 static void       find_page_at_location                      (EvView             *view,
130                                                               gdouble             x,
131                                                               gdouble             y,
132                                                               gint               *page,
133                                                               gint               *x_offset,
134                                                               gint               *y_offset);
135 static void       doc_point_to_view_point                    (EvView             *view,
136                                                               int                 page,
137                                                               EvPoint            *doc_point,
138                                                               GdkPoint           *view_point);
139 /*** Hyperrefs ***/
140 static EvLink *   ev_view_get_link_at_location               (EvView             *view,
141                                                               gdouble             x,
142                                                               gdouble             y);
143 static char*      tip_from_link                              (EvView             *view,
144                                                               EvLink             *link);
145 /*** Forms ***/
146 static EvFormField *ev_view_get_form_field_at_location       (EvView             *view,
147                                                                gdouble            x,
148                                                                gdouble            y);
149
150 /*** Annotations ***/
151 static EvAnnotation *ev_view_get_annotation_at_location      (EvView             *view,
152                                                               gdouble             x,
153                                                               gdouble             y);
154 static void          show_annotation_windows                 (EvView             *view,
155                                                               gint                page);
156 static void          hide_annotation_windows                 (EvView             *view,
157                                                               gint                page);
158 /*** GtkWidget implementation ***/
159 static void       ev_view_size_request_continuous_dual_page  (EvView             *view,
160                                                               GtkRequisition     *requisition);
161 static void       ev_view_size_request_continuous            (EvView             *view,
162                                                               GtkRequisition     *requisition);
163 static void       ev_view_size_request_dual_page             (EvView             *view,
164                                                               GtkRequisition     *requisition);
165 static void       ev_view_size_request_single_page           (EvView             *view,
166                                                               GtkRequisition     *requisition);
167 static void       ev_view_size_request                       (GtkWidget          *widget,
168                                                               GtkRequisition     *requisition);
169 static void       ev_view_size_allocate                      (GtkWidget          *widget,
170                                                               GtkAllocation      *allocation);
171 static gboolean   ev_view_scroll_event                       (GtkWidget          *widget,
172                                                               GdkEventScroll     *event);
173 static gboolean   ev_view_draw                               (GtkWidget          *widget,
174                                                               cairo_t            *cr);
175 static gboolean   ev_view_popup_menu                         (GtkWidget          *widget);
176 static gboolean   ev_view_button_press_event                 (GtkWidget          *widget,
177                                                               GdkEventButton     *event);
178 static gboolean   ev_view_motion_notify_event                (GtkWidget          *widget,
179                                                               GdkEventMotion     *event);
180 static gboolean   ev_view_button_release_event               (GtkWidget          *widget,
181                                                               GdkEventButton     *event);
182 static gboolean   ev_view_enter_notify_event                 (GtkWidget          *widget,
183                                                               GdkEventCrossing   *event);
184 static gboolean   ev_view_leave_notify_event                 (GtkWidget          *widget,
185                                                               GdkEventCrossing   *event);
186 static void       ev_view_style_updated                      (GtkWidget          *widget);
187 static void       ev_view_remove_all                         (EvView             *view);
188
189 static AtkObject *ev_view_get_accessible                     (GtkWidget *widget);
190
191 /*** Drawing ***/
192 static void       highlight_find_results                     (EvView             *view,
193                                                               cairo_t            *cr,
194                                                               int                 page);
195 static void       highlight_forward_search_results           (EvView             *view,
196                                                               cairo_t            *cr,
197                                                               int                 page);
198 static void       focus_annotation                           (EvView             *view,
199                                                               cairo_t            *cr,
200                                                               int                 page,
201                                                               GdkRectangle       *clip);
202 static void       draw_one_page                              (EvView             *view,
203                                                               gint                page,
204                                                               cairo_t            *cr,
205                                                               GdkRectangle       *page_area,
206                                                               GtkBorder          *border,
207                                                               GdkRectangle       *expose_area,
208                                                               gboolean           *page_ready);
209 static void       show_loading_window                        (EvView             *view);
210 static void       hide_loading_window                        (EvView             *view);
211 static void       ev_view_reload_page                        (EvView             *view,
212                                                               gint                page,
213                                                               cairo_region_t     *region);
214 static void       ev_view_loading_window_move                (EvView             *view);
215
216 /*** Callbacks ***/
217 static void       ev_view_change_page                        (EvView             *view,
218                                                               gint                new_page);
219 static void       job_finished_cb                            (EvPixbufCache      *pixbuf_cache,
220                                                               cairo_region_t     *region,
221                                                               EvView             *view);
222 static void       ev_view_page_changed_cb                    (EvDocumentModel    *model,
223                                                               gint                old_page,
224                                                               gint                new_page,
225                                                               EvView             *view);
226 static void       on_adjustment_value_changed                (GtkAdjustment      *adjustment,
227                                                               EvView             *view);
228
229 /*** GObject ***/
230 static void       ev_view_finalize                           (GObject            *object);
231 static void       ev_view_dispose                            (GObject            *object);
232 static void       ev_view_class_init                         (EvViewClass        *class);
233 static void       ev_view_init                               (EvView             *view);
234
235 /*** Zoom and sizing ***/
236 static double   zoom_for_size_fit_width                      (gdouble doc_width,
237                                                               gdouble doc_height,
238                                                               int     target_width,
239                                                               int     target_height);
240 static double   zoom_for_size_fit_height                     (gdouble doc_width,
241                                                               gdouble doc_height,
242                                                               int     target_width,
243                                                               int     target_height);
244 static double   zoom_for_size_best_fit                       (gdouble doc_width,
245                                                               gdouble doc_height,
246                                                               int     target_width,
247                                                               int     target_height);
248 static void     ev_view_zoom_for_size                        (EvView *view,
249                                                               int     width,
250                                                               int     height);
251 static void     ev_view_zoom_for_size_continuous_and_dual_page (EvView *view,
252                                                                 int     width,
253                                                                 int     height);
254 static void     ev_view_zoom_for_size_continuous               (EvView *view,
255                                                                 int     width,
256                                                                 int     height);
257 static void     ev_view_zoom_for_size_dual_page                (EvView *view,
258                                                                 int     width,
259                                                                 int     height);
260 static void     ev_view_zoom_for_size_single_page              (EvView *view,
261                                                                 int     width,
262                                                                 int     height);
263 /*** Cursors ***/
264 static void       ev_view_set_cursor                         (EvView             *view,
265                                                               EvViewCursor        new_cursor);
266 static void       ev_view_handle_cursor_over_xy              (EvView *view,
267                                                               gint x,
268                                                               gint y);
269
270 /*** Find ***/
271 static gint         ev_view_find_get_n_results               (EvView             *view,
272                                                               gint                page);
273 static EvRectangle *ev_view_find_get_result                  (EvView             *view,
274                                                               gint                page,
275                                                               gint                result);
276 static void       jump_to_find_result                        (EvView             *view);
277 static void       jump_to_find_page                          (EvView             *view, 
278                                                               EvViewFindDirection direction,
279                                                               gint                shift);
280 /*** Selection ***/
281 static void       compute_selections                         (EvView             *view,
282                                                               EvSelectionStyle    style,
283                                                               GdkPoint           *start,
284                                                               GdkPoint           *stop);
285 static void       clear_selection                            (EvView             *view);
286 static void       clear_link_selected                        (EvView             *view);
287 static void       selection_free                             (EvViewSelection    *selection);
288 static char*      get_selected_text                          (EvView             *ev_view);
289 static void       ev_view_primary_get_cb                     (GtkClipboard       *clipboard,
290                                                               GtkSelectionData   *selection_data,
291                                                               guint               info,
292                                                               gpointer            data);
293 static void       ev_view_primary_clear_cb                   (GtkClipboard       *clipboard,
294                                                               gpointer            data);
295 static void       ev_view_update_primary_selection           (EvView             *ev_view);
296
297 G_DEFINE_TYPE_WITH_CODE (EvView, ev_view, GTK_TYPE_CONTAINER,
298                          G_IMPLEMENT_INTERFACE (GTK_TYPE_SCROLLABLE, NULL))
299
300 /* HeightToPage cache */
301 #define EV_HEIGHT_TO_PAGE_CACHE_KEY "ev-height-to-page-cache"
302
303 static void
304 build_height_to_page (EvHeightToPageCache *cache,
305                       EvDocument          *document,
306                       gint                 rotation)
307 {
308         gboolean swap, uniform, dual_even_left;
309         int i;
310         double uniform_height, page_height, next_page_height;
311         double saved_height;
312         gdouble u_width, u_height;
313         gint n_pages;
314
315         swap = (rotation == 90 || rotation == 270);
316
317         uniform = ev_document_is_page_size_uniform (document);
318         n_pages = ev_document_get_n_pages (document);
319         dual_even_left = (n_pages > 2);
320
321         g_free (cache->height_to_page);
322         g_free (cache->dual_height_to_page);
323
324         cache->rotation = rotation;
325         cache->height_to_page = g_new0 (gdouble, n_pages + 1);
326         cache->dual_height_to_page = g_new0 (gdouble, n_pages + 2);
327
328         if (uniform)
329                 ev_document_get_page_size (document, 0, &u_width, &u_height);
330
331         saved_height = 0;
332         for (i = 0; i <= n_pages; i++) {
333                 if (uniform) {
334                         uniform_height = swap ? u_width : u_height;
335                         cache->height_to_page[i] = i * uniform_height;
336                 } else {
337                         if (i < n_pages) {
338                                 gdouble w, h;
339
340                                 ev_document_get_page_size (document, i, &w, &h);
341                                 page_height = swap ? w : h;
342                         } else {
343                                 page_height = 0;
344                         }
345                         cache->height_to_page[i] = saved_height;
346                         saved_height += page_height;
347                 }
348         }
349
350         if (dual_even_left && !uniform) {
351                 gdouble w, h;
352
353                 ev_document_get_page_size (document, 0, &w, &h);
354                 saved_height = swap ? w : h;
355         } else {
356                 saved_height = 0;
357         }
358
359         for (i = dual_even_left; i < n_pages + 2; i += 2) {
360                 if (uniform) {
361                         uniform_height = swap ? u_width : u_height;
362                         cache->dual_height_to_page[i] = ((i + dual_even_left) / 2) * uniform_height;
363                         if (i + 1 < n_pages + 2)
364                                 cache->dual_height_to_page[i + 1] = ((i + dual_even_left) / 2) * uniform_height;
365                 } else {
366                         if (i + 1 < n_pages) {
367                                 gdouble w, h;
368
369                                 ev_document_get_page_size (document, i + 1, &w, &h);
370                                 next_page_height = swap ? w : h;
371                         } else {
372                                 next_page_height = 0;
373                         }
374
375                         if (i < n_pages) {
376                                 gdouble w, h;
377
378                                 ev_document_get_page_size (document, i, &w, &h);
379                                 page_height = swap ? w : h;
380                         } else {
381                                 page_height = 0;
382                         }
383
384                         if (i + 1 < n_pages + 2) {
385                                 cache->dual_height_to_page[i] = saved_height;
386                                 cache->dual_height_to_page[i + 1] = saved_height;
387                                 saved_height += MAX(page_height, next_page_height);
388                         } else {
389                                 cache->dual_height_to_page[i] = saved_height;
390                         }
391                 }
392         }
393 }
394
395 static void
396 ev_height_to_page_cache_get_height (EvHeightToPageCache *cache,
397                                     EvDocument          *document,
398                                     gint                 page,
399                                     gint                 rotation,
400                                     gdouble             *height,
401                                     gdouble             *dual_height)
402 {
403         if (cache->rotation != rotation)
404                 build_height_to_page (cache, document, rotation);
405
406         *height = cache->height_to_page[page];
407         *dual_height = cache->dual_height_to_page[page];
408 }
409
410 static void
411 ev_height_to_page_cache_free (EvHeightToPageCache *cache)
412 {
413         if (cache->height_to_page) {
414                 g_free (cache->height_to_page);
415                 cache->height_to_page = NULL;
416         }
417
418         if (cache->dual_height_to_page) {
419                 g_free (cache->dual_height_to_page);
420                 cache->dual_height_to_page = NULL;
421         }
422         g_free (cache);
423 }
424
425 static EvHeightToPageCache *
426 ev_view_get_height_to_page_cache (EvView *view)
427 {
428         EvHeightToPageCache *cache;
429
430         if (!view->document)
431                 return NULL;
432
433         cache = g_object_get_data (G_OBJECT (view->document), EV_HEIGHT_TO_PAGE_CACHE_KEY);
434         if (!cache) {
435                 cache = g_new0 (EvHeightToPageCache, 1);
436                 build_height_to_page (cache, view->document, view->rotation);
437                 g_object_set_data_full (G_OBJECT (view->document),
438                                         EV_HEIGHT_TO_PAGE_CACHE_KEY,
439                                         cache,
440                                         (GDestroyNotify)ev_height_to_page_cache_free);
441         }
442
443         return cache;
444 }
445
446 static void
447 ev_view_get_height_to_page (EvView *view,
448                             gint    page,
449                             gint   *height,
450                             gint   *dual_height)
451 {
452         gdouble h, dh;
453
454         if (!view->height_to_page_cache)
455                 return;
456
457         ev_height_to_page_cache_get_height (view->height_to_page_cache,
458                                             view->document,
459                                             page,
460                                             view->rotation,
461                                             &h, &dh);
462         if (height)
463                 *height = (gint)(h * view->scale + 0.5);
464
465         if (dual_height)
466                 *dual_height = (gint)(dh * view->scale + 0.5);
467 }
468
469 static gint
470 ev_view_get_scrollbar_size (EvView        *view,
471                             GtkOrientation orientation)
472 {
473         GtkWidget *widget = GTK_WIDGET (view);
474         GtkWidget *sb;
475         GtkWidget *swindow = gtk_widget_get_parent (GTK_WIDGET (view));
476         GtkAllocation allocation;
477         GtkRequisition req;
478         gint spacing;
479
480         if (!GTK_IS_SCROLLED_WINDOW (swindow))
481                 return 0;
482
483         gtk_widget_get_allocation (widget, &allocation);
484
485         if (orientation == GTK_ORIENTATION_VERTICAL) {
486                 if (allocation.height >= view->requisition.height)
487                         sb = gtk_scrolled_window_get_vscrollbar (GTK_SCROLLED_WINDOW (swindow));
488                 else
489                         return 0;
490         } else {
491                 if (allocation.width >= view->requisition.width)
492                         sb = gtk_scrolled_window_get_hscrollbar (GTK_SCROLLED_WINDOW (swindow));
493                 else
494                         return 0;
495         }
496
497         gtk_widget_style_get (swindow, "scrollbar_spacing", &spacing, NULL);
498         gtk_widget_get_preferred_size (sb, &req, NULL);
499
500         return (orientation == GTK_ORIENTATION_VERTICAL ? req.width : req.height) + spacing;
501 }
502
503 static void
504 scroll_to_point (EvView        *view,
505                  gdouble        x,
506                  gdouble        y,
507                  GtkOrientation orientation)
508 {
509         gdouble page_size;
510         gdouble upper, lower;
511
512         if (orientation == GTK_ORIENTATION_VERTICAL) {
513                 page_size = gtk_adjustment_get_page_size (view->vadjustment);
514                 upper = gtk_adjustment_get_upper (view->vadjustment);
515                 lower = gtk_adjustment_get_lower (view->vadjustment);
516
517                 if (view->continuous) {
518                         gtk_adjustment_clamp_page (view->vadjustment,
519                                                    y - view->spacing / 2,
520                                                    y + page_size);
521                 } else {
522                         gtk_adjustment_set_value (view->vadjustment,
523                                                   CLAMP (y, lower, upper - page_size));
524                 }
525         } else {
526                 page_size = gtk_adjustment_get_page_size (view->hadjustment);
527                 upper = gtk_adjustment_get_upper (view->hadjustment);
528                 lower = gtk_adjustment_get_lower (view->hadjustment);
529
530                 if (view->dual_page) {
531                         gtk_adjustment_clamp_page (view->hadjustment, x,
532                                                    x + page_size);
533                 } else {
534                         gtk_adjustment_set_value (view->hadjustment,
535                                                   CLAMP (x, lower, upper - page_size));
536                 }
537         }
538 }
539
540 static void
541 ev_view_scroll_to_page_position (EvView *view, GtkOrientation orientation)
542 {
543         gdouble x, y;
544
545         if (!view->document)
546                 return;
547
548         if ((orientation == GTK_ORIENTATION_VERTICAL && view->pending_point.y == 0) ||
549             (orientation == GTK_ORIENTATION_HORIZONTAL && view->pending_point.x == 0)) {
550                 GdkRectangle page_area;
551                 GtkBorder    border;
552
553                 ev_view_get_page_extents (view, view->current_page, &page_area, &border);
554                 x = page_area.x;
555                 y = page_area.y;
556         } else {
557                 GdkPoint view_point;
558
559                 doc_point_to_view_point (view, view->current_page,
560                                          &view->pending_point, &view_point);
561                 x = view_point.x;
562                 y = view_point.y;
563         }
564
565         scroll_to_point (view, x, y, orientation);
566 }
567
568 static void
569 ev_view_set_adjustment_values (EvView         *view,
570                                GtkOrientation  orientation)
571 {
572         GtkWidget *widget = GTK_WIDGET (view);
573         GtkAdjustment *adjustment;
574         GtkAllocation allocation;
575         int req_size;
576         int alloc_size;
577         gdouble page_size;
578         gdouble value;
579         gdouble upper;
580         double factor;
581         gint new_value;
582
583         gtk_widget_get_allocation (widget, &allocation);
584
585         if (orientation == GTK_ORIENTATION_HORIZONTAL)  {
586                 req_size = view->requisition.width;
587                 alloc_size = allocation.width;
588                 adjustment = view->hadjustment;
589         } else {
590                 req_size = view->requisition.height;
591                 alloc_size = allocation.height;
592                 adjustment = view->vadjustment;
593         }
594
595         if (!adjustment)
596                 return;
597
598         factor = 1.0;
599         value = gtk_adjustment_get_value (adjustment);
600         upper = gtk_adjustment_get_upper (adjustment);
601         page_size = gtk_adjustment_get_page_size (adjustment);
602
603         switch (view->pending_scroll) {
604                 case SCROLL_TO_KEEP_POSITION:
605                 case SCROLL_TO_FIND_LOCATION:
606                         factor = value / upper;
607                         break;
608                 case SCROLL_TO_PAGE_POSITION:
609                         break;
610                 case SCROLL_TO_CENTER:
611                         factor = (value + page_size * 0.5) / upper;
612                         break;
613         }
614
615         upper = MAX (alloc_size, req_size);
616         page_size = alloc_size;
617
618         gtk_adjustment_set_page_size (adjustment, page_size);
619         gtk_adjustment_set_step_increment (adjustment, alloc_size * 0.1);
620         gtk_adjustment_set_page_increment (adjustment, alloc_size * 0.9);
621         gtk_adjustment_set_lower (adjustment, 0);
622         gtk_adjustment_set_upper (adjustment, upper);
623
624         /*
625          * We add 0.5 to the values before to average out our rounding errors.
626          */
627         switch (view->pending_scroll) {
628                 case SCROLL_TO_KEEP_POSITION:
629                 case SCROLL_TO_FIND_LOCATION:
630                         new_value = CLAMP (upper * factor + 0.5, 0, upper - page_size);
631                         gtk_adjustment_set_value (adjustment, (int)new_value);
632                         break;
633                 case SCROLL_TO_PAGE_POSITION:
634                         ev_view_scroll_to_page_position (view, orientation);
635                         break;
636                 case SCROLL_TO_CENTER:
637                         new_value = CLAMP (upper * factor - page_size * 0.5 + 0.5,
638                                            0, upper - page_size);
639                         gtk_adjustment_set_value (adjustment, (int)new_value);
640                         break;
641         }
642
643         gtk_adjustment_changed (adjustment);
644 }
645
646 static void
647 view_update_range_and_current_page (EvView *view)
648 {
649         gint start = view->start_page;
650         gint end = view->end_page;
651
652         if (ev_document_get_n_pages (view->document) <= 0 ||
653             !ev_document_check_dimensions (view->document))
654                 return;
655
656         if (view->continuous) {
657                 GdkRectangle current_area, unused, page_area;
658                 GtkBorder border;
659                 gboolean found = FALSE;
660                 gint area_max = -1, area;
661                 gint best_current_page = -1;
662                 int i, j = 0;
663
664                 if (!(view->vadjustment && view->hadjustment))
665                         return;
666
667                 current_area.x = gtk_adjustment_get_value (view->hadjustment);
668                 current_area.width = gtk_adjustment_get_page_size (view->hadjustment);
669                 current_area.y = gtk_adjustment_get_value (view->vadjustment);
670                 current_area.height = gtk_adjustment_get_page_size (view->vadjustment);
671
672                 for (i = 0; i < ev_document_get_n_pages (view->document); i++) {
673
674                         ev_view_get_page_extents (view, i, &page_area, &border);
675
676                         if (gdk_rectangle_intersect (&current_area, &page_area, &unused)) {
677                                 area = unused.width * unused.height;
678
679                                 if (!found) {
680                                         area_max = area;
681                                         view->start_page = i;
682                                         found = TRUE;
683                                         best_current_page = i;
684                                 }
685                                 if (area > area_max) {
686                                         best_current_page = (area == area_max) ? MIN (i, best_current_page) : i;
687                                         area_max = area;
688                                 }
689
690                                 view->end_page = i;
691                                 j = 0;
692                         } else if (found && view->current_page <= view->end_page) {
693                                 if (view->dual_page && j < 1) {
694                                         /* In dual mode  we stop searching
695                                          * after two consecutive non-visible pages.
696                                          */
697                                         j++;
698                                         continue;
699                                 }
700                                 break;
701                         }
702                 }
703
704                 if (view->pending_scroll == SCROLL_TO_KEEP_POSITION) {
705                         best_current_page = MAX (best_current_page, view->start_page);
706
707                         if (view->current_page != best_current_page) {
708                                 view->current_page = best_current_page;
709                                 hide_loading_window (view);
710                                 ev_document_model_set_page (view->model, best_current_page);
711                         }
712                 }
713         } else if (view->dual_page) {
714                 if (view->current_page % 2 == get_dual_even_left (view)) {
715                         view->start_page = view->current_page;
716                         if (view->current_page + 1 < ev_document_get_n_pages (view->document))
717                                 view->end_page = view->start_page + 1;
718                         else
719                                 view->end_page = view->start_page;
720                 } else {
721                         if (view->current_page < 1)
722                                 view->start_page = view->current_page;
723                         else
724                                 view->start_page = view->current_page - 1;
725                         view->end_page = view->current_page;
726                 }
727         } else {
728                 view->start_page = view->current_page;
729                 view->end_page = view->current_page;
730         }
731
732         if (view->start_page == -1 || view->end_page == -1)
733                 return;
734
735         if (start != view->start_page || end != view->end_page) {
736                 gint i;
737
738                 for (i = start; i < view->start_page && start != -1; i++) {
739                         hide_annotation_windows (view, i);
740                 }
741
742                 for (i = end; i > view->end_page && end != -1; i--) {
743                         hide_annotation_windows (view, i);
744                 }
745         }
746
747         ev_page_cache_set_page_range (view->page_cache,
748                                       view->start_page,
749                                       view->end_page);
750         ev_pixbuf_cache_set_page_range (view->pixbuf_cache,
751                                         view->start_page,
752                                         view->end_page,
753                                         view->selection_info.selections);
754
755         if (ev_pixbuf_cache_get_surface (view->pixbuf_cache, view->current_page))
756             gtk_widget_queue_draw (GTK_WIDGET (view));
757 }
758
759 static void
760 ev_view_set_scroll_adjustment (EvView         *view,
761                                GtkOrientation  orientation,
762                                GtkAdjustment  *adjustment)
763 {
764         GtkAdjustment **to_set;
765         const gchar    *prop_name;
766
767         if (orientation == GTK_ORIENTATION_HORIZONTAL) {
768                 to_set = &view->hadjustment;
769                 prop_name = "hadjustment";
770         } else {
771                 to_set = &view->vadjustment;
772                 prop_name = "vadjustment";
773         }
774
775         if (adjustment && adjustment == *to_set)
776                 return;
777
778         if (*to_set) {
779                 g_signal_handlers_disconnect_by_func (*to_set,
780                                                       (gpointer) on_adjustment_value_changed,
781                                                       view);
782                 g_object_unref (*to_set);
783         }
784
785         if (!adjustment)
786                 adjustment = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
787         g_signal_connect (adjustment, "value_changed",
788                           G_CALLBACK (on_adjustment_value_changed),
789                           view);
790         *to_set = g_object_ref_sink (adjustment);
791         ev_view_set_adjustment_values (view, orientation);
792
793         g_object_notify (G_OBJECT (view), prop_name);
794 }
795
796 static void
797 add_scroll_binding_keypad (GtkBindingSet  *binding_set,
798                            guint           keyval,
799                            GdkModifierType modifiers,
800                            GtkScrollType   scroll,
801                            gboolean        horizontal)
802 {
803   guint keypad_keyval = keyval - GDK_KEY_Left + GDK_KEY_KP_Left;
804
805   gtk_binding_entry_add_signal (binding_set, keyval, modifiers,
806                                 "binding_activated", 2,
807                                 GTK_TYPE_SCROLL_TYPE, scroll,
808                                 G_TYPE_BOOLEAN, horizontal);
809   gtk_binding_entry_add_signal (binding_set, keypad_keyval, modifiers,
810                                 "binding_activated", 2,
811                                 GTK_TYPE_SCROLL_TYPE, scroll,
812                                 G_TYPE_BOOLEAN, horizontal);
813 }
814
815 static gdouble
816 compute_scroll_increment (EvView        *view,
817                           GtkScrollType  scroll)
818 {
819         GtkWidget *widget = GTK_WIDGET (view);
820         GtkAdjustment *adjustment = view->vadjustment;
821         cairo_region_t *text_region, *region;
822         GtkAllocation allocation;
823         gint page;
824         GdkRectangle rect;
825         EvRectangle doc_rect;
826         GdkRectangle page_area;
827         GtkBorder border;
828         gdouble fraction = 1.0;
829
830         if (scroll != GTK_SCROLL_PAGE_BACKWARD && scroll != GTK_SCROLL_PAGE_FORWARD)
831                 return gtk_adjustment_get_page_size (adjustment);
832
833         page = scroll == GTK_SCROLL_PAGE_BACKWARD ? view->start_page : view->end_page;
834
835         text_region = ev_page_cache_get_text_mapping (view->page_cache, page);
836         if (!text_region || cairo_region_is_empty (text_region))
837                 return gtk_adjustment_get_page_size (adjustment);
838
839         gtk_widget_get_allocation (widget, &allocation);
840         ev_view_get_page_extents (view, page, &page_area, &border);
841         rect.x = page_area.x + view->scroll_x;
842         rect.y = view->scroll_y + (scroll == GTK_SCROLL_PAGE_BACKWARD ? 5 : allocation.height - 5);
843         rect.width = page_area.width;
844         rect.height = 1;
845         view_rect_to_doc_rect (view, &rect, &page_area, &doc_rect);
846
847         /* Convert the doc rectangle into a GdkRectangle */
848         rect.x = doc_rect.x1;
849         rect.y = doc_rect.y1;
850         rect.width = doc_rect.x2 - doc_rect.x1;
851         rect.height = MAX (1, doc_rect.y2 - doc_rect.y1);
852         region = cairo_region_create_rectangle (&rect);
853
854         cairo_region_intersect (region, text_region);
855         if (cairo_region_num_rectangles (region)) {
856                 EvRenderContext *rc;
857                 EvPage  *ev_page;
858                 cairo_region_t *sel_region;
859
860                 cairo_region_get_rectangle (region, 0, &rect);
861                 ev_page = ev_document_get_page (view->document, page);
862                 rc = ev_render_context_new (ev_page, view->rotation, view->scale);
863                 g_object_unref (ev_page);
864                 /* Get the selection region to know the height of the line */
865                 doc_rect.x1 = doc_rect.x2 = rect.x + 0.5;
866                 doc_rect.y1 = doc_rect.y2 = rect.y + 0.5;
867
868                 ev_document_doc_mutex_lock ();
869                 sel_region = ev_selection_get_selection_region (EV_SELECTION (view->document),
870                                                                 rc, EV_SELECTION_STYLE_LINE,
871                                                                 &doc_rect);
872                 ev_document_doc_mutex_unlock ();
873
874                 g_object_unref (rc);
875
876                 if (cairo_region_num_rectangles (sel_region) > 0) {
877                         cairo_region_get_rectangle (sel_region, 0, &rect);
878                         fraction = 1 - (rect.height / gtk_adjustment_get_page_size (adjustment));
879                 }
880                 cairo_region_destroy (sel_region);
881         }
882         cairo_region_destroy (region);
883
884         return gtk_adjustment_get_page_size (adjustment) * fraction;
885
886 }
887
888 void
889 ev_view_scroll (EvView        *view,
890                 GtkScrollType  scroll,
891                 gboolean       horizontal)
892 {
893         GtkAdjustment *adjustment;
894         double value, increment;
895         gdouble upper, lower;
896         gdouble page_size;
897         gdouble step_increment;
898         gboolean first_page = FALSE;
899         gboolean last_page = FALSE;
900
901         view->jump_to_find_result = FALSE;
902
903         if (view->sizing_mode == EV_SIZING_BEST_FIT) {
904                 switch (scroll) {
905                         case GTK_SCROLL_PAGE_BACKWARD:
906                         case GTK_SCROLL_STEP_BACKWARD:
907                                 ev_view_previous_page (view);
908                                 break;
909                         case GTK_SCROLL_PAGE_FORWARD:
910                         case GTK_SCROLL_STEP_FORWARD:
911                                 ev_view_next_page (view);
912                                 break;
913                         default:
914                                 break;
915                 }
916                 return;
917         }
918
919         /* Assign values for increment and vertical adjustment */
920         adjustment = horizontal ? view->hadjustment : view->vadjustment;
921         value = gtk_adjustment_get_value (adjustment);
922         upper = gtk_adjustment_get_upper (adjustment);
923         lower = gtk_adjustment_get_lower (adjustment);
924         page_size = gtk_adjustment_get_page_size (adjustment);
925         step_increment = gtk_adjustment_get_step_increment (adjustment);
926
927         /* Assign boolean for first and last page */
928         if (view->current_page == 0)
929                 first_page = TRUE;
930         if (view->current_page == ev_document_get_n_pages (view->document) - 1)
931                 last_page = TRUE;
932
933         switch (scroll) {
934                 case GTK_SCROLL_PAGE_BACKWARD:
935                         /* Do not jump backwards if at the first page */
936                         if (value == lower && first_page) {
937                                 /* Do nothing */
938                                 /* At the top of a page, assign the upper bound limit of previous page */
939                         } else if (value == lower) {
940                                 value = upper - page_size;
941                                 ev_view_previous_page (view);
942                                 /* Jump to the top */
943                         } else {
944                                 increment = compute_scroll_increment (view, GTK_SCROLL_PAGE_BACKWARD);
945                                 value = MAX (value - increment, lower);
946                         }
947                         break;
948                 case GTK_SCROLL_PAGE_FORWARD:
949                         /* Do not jump forward if at the last page */
950                         if (value == (upper - page_size) && last_page) {
951                                 /* Do nothing */
952                         /* At the bottom of a page, assign the lower bound limit of next page */
953                         } else if (value == (upper - page_size)) {
954                                 value = 0;
955                                 ev_view_next_page (view);
956                         /* Jump to the bottom */
957                         } else {
958                                 increment = compute_scroll_increment (view, GTK_SCROLL_PAGE_FORWARD);
959                                 value = MIN (value + increment, upper - page_size);
960                         }
961                         break;
962                 case GTK_SCROLL_STEP_BACKWARD:
963                         value -= step_increment;
964                         break;
965                 case GTK_SCROLL_STEP_FORWARD:
966                         value += step_increment;
967                         break;
968                 case GTK_SCROLL_STEP_DOWN:
969                         value -= step_increment / 10;
970                         break;
971                 case GTK_SCROLL_STEP_UP:
972                         value += step_increment / 10;
973                         break;
974                 default:
975                         break;
976         }
977
978         value = CLAMP (value, lower, upper - page_size);
979
980         gtk_adjustment_set_value (adjustment, value);
981 }
982
983 #define MARGIN 5
984
985 static void
986 ensure_rectangle_is_visible (EvView *view, GdkRectangle *rect)
987 {
988         GtkWidget *widget = GTK_WIDGET (view);
989         GtkAdjustment *adjustment;
990         GtkAllocation allocation;
991         gdouble adj_value;
992         int value;
993
994         view->pending_scroll = SCROLL_TO_FIND_LOCATION;
995
996         gtk_widget_get_allocation (widget, &allocation);
997
998         adjustment = view->vadjustment;
999         adj_value = gtk_adjustment_get_value (adjustment);
1000
1001         if (rect->y < adj_value) {
1002                 value = MAX (gtk_adjustment_get_lower (adjustment), rect->y - MARGIN);
1003                 gtk_adjustment_set_value (view->vadjustment, value);
1004         } else if (rect->y + rect->height > adj_value + allocation.height) {
1005                 value = MIN (gtk_adjustment_get_upper (adjustment), rect->y + rect->height -
1006                              allocation.height + MARGIN);
1007                 gtk_adjustment_set_value (view->vadjustment, value);
1008         }
1009
1010         adjustment = view->hadjustment;
1011         adj_value = gtk_adjustment_get_value (adjustment);
1012
1013         if (rect->x < adj_value) {
1014                 value = MAX (gtk_adjustment_get_lower (adjustment), rect->x - MARGIN);
1015                 gtk_adjustment_set_value (view->hadjustment, value);
1016         } else if (rect->x + rect->height > adj_value + allocation.width) {
1017                 value = MIN (gtk_adjustment_get_upper (adjustment), rect->x + rect->width -
1018                              allocation.width + MARGIN);
1019                 gtk_adjustment_set_value (view->hadjustment, value);
1020         }
1021
1022         gtk_widget_queue_resize (GTK_WIDGET (view));
1023 }
1024
1025 /*** Geometry computations ***/
1026
1027 static void
1028 compute_border (EvView *view, int width, int height, GtkBorder *border)
1029 {
1030         ev_document_misc_get_page_border_size (width, height, border);
1031 }
1032
1033 void
1034 _get_page_size_for_scale_and_rotation (EvDocument *document,
1035                                        gint        page,
1036                                        gdouble     scale,
1037                                        gint        rotation,
1038                                        gint       *page_width,
1039                                        gint       *page_height)
1040 {
1041         gdouble w, h;
1042         gint    width, height;
1043
1044         ev_document_get_page_size (document, page, &w, &h);
1045
1046         width = (gint)(w * scale + 0.5);
1047         height = (gint)(h * scale + 0.5);
1048
1049         if (page_width)
1050                 *page_width = (rotation == 0 || rotation == 180) ? width : height;
1051         if (page_height)
1052                 *page_height = (rotation == 0 || rotation == 180) ? height : width;
1053 }
1054
1055 static void
1056 ev_view_get_page_size (EvView *view,
1057                        gint    page,
1058                        gint   *page_width,
1059                        gint   *page_height)
1060 {
1061         _get_page_size_for_scale_and_rotation (view->document,
1062                                                page,
1063                                                view->scale,
1064                                                view->rotation,
1065                                                page_width,
1066                                                page_height);
1067 }
1068
1069 static void
1070 ev_view_get_max_page_size (EvView *view,
1071                            gint   *max_width,
1072                            gint   *max_height)
1073 {
1074         double w, h;
1075         gint   width, height;
1076
1077         ev_document_get_max_page_size (view->document, &w, &h);
1078
1079         width = (gint)(w * view->scale + 0.5);
1080         height = (gint)(h * view->scale + 0.5);
1081
1082         if (max_width)
1083                 *max_width = (view->rotation == 0 || view->rotation == 180) ? width : height;
1084         if (max_height)
1085                 *max_height = (view->rotation == 0 || view->rotation == 180) ? height : width;
1086 }
1087
1088 static void
1089 get_page_y_offset (EvView *view, int page, int *y_offset)
1090 {
1091         int max_width, offset;
1092         GtkBorder border;
1093
1094         g_return_if_fail (y_offset != NULL);
1095
1096         ev_view_get_max_page_size (view, &max_width, NULL);
1097         compute_border (view, max_width, max_width, &border);
1098
1099         if (view->dual_page) {
1100                 ev_view_get_height_to_page (view, page, NULL, &offset);
1101                 offset += ((page + get_dual_even_left (view)) / 2 + 1) * view->spacing +
1102                         ((page + get_dual_even_left (view)) / 2 ) * (border.top + border.bottom);
1103         } else {
1104                 ev_view_get_height_to_page (view, page, &offset, NULL);
1105                 offset += (page + 1) * view->spacing + page * (border.top + border.bottom);
1106         }
1107
1108         *y_offset = offset;
1109         return;
1110 }
1111
1112 gboolean
1113 ev_view_get_page_extents (EvView       *view,
1114                           gint          page,
1115                           GdkRectangle *page_area,
1116                           GtkBorder    *border)
1117 {
1118         GtkWidget *widget;
1119         int width, height;
1120         GtkAllocation allocation;
1121
1122         widget = GTK_WIDGET (view);
1123         gtk_widget_get_allocation (widget, &allocation);
1124
1125         /* Get the size of the page */
1126         ev_view_get_page_size (view, page, &width, &height);
1127         compute_border (view, width, height, border);
1128         page_area->width = width + border->left + border->right;
1129         page_area->height = height + border->top + border->bottom;
1130
1131         if (view->continuous) {
1132                 gint max_width;
1133                 gint x, y;
1134
1135                 ev_view_get_max_page_size (view, &max_width, NULL);
1136                 max_width = max_width + border->left + border->right;
1137                 /* Get the location of the bounding box */
1138                 if (view->dual_page) {
1139                         x = view->spacing + ((page % 2 == get_dual_even_left (view)) ? 0 : 1) * (max_width + view->spacing);
1140                         x = x + MAX (0, allocation.width - (max_width * 2 + view->spacing * 3)) / 2;
1141                         if (page % 2 == get_dual_even_left (view))
1142                                 x = x + (max_width - width - border->left - border->right);
1143                 } else {
1144                         x = view->spacing;
1145                         x = x + MAX (0, allocation.width - (width + view->spacing * 2)) / 2;
1146                 }
1147
1148                 get_page_y_offset (view, page, &y);
1149
1150                 page_area->x = x;
1151                 page_area->y = y;
1152         } else {
1153                 gint x, y;
1154                 if (view->dual_page) {
1155                         gint width_2, height_2;
1156                         gint max_width = width;
1157                         gint max_height = height;
1158                         GtkBorder overall_border;
1159                         gint other_page;
1160
1161                         other_page = (page % 2 == get_dual_even_left (view)) ? page + 1: page - 1;
1162
1163                         /* First, we get the bounding box of the two pages */
1164                         if (other_page < ev_document_get_n_pages (view->document)
1165                             && (0 <= other_page)) {
1166                                 ev_view_get_page_size (view, other_page,
1167                                                        &width_2, &height_2);
1168                                 if (width_2 > width)
1169                                         max_width = width_2;
1170                                 if (height_2 > height)
1171                                         max_height = height_2;
1172                         }
1173                         compute_border (view, max_width, max_height, &overall_border);
1174
1175                         /* Find the offsets */
1176                         x = view->spacing;
1177                         y = view->spacing;
1178
1179                         /* Adjust for being the left or right page */
1180                         if (page % 2 == get_dual_even_left (view))
1181                                 x = x + max_width - width;
1182                         else
1183                                 x = x + (max_width + overall_border.left + overall_border.right) + view->spacing;
1184
1185                         y = y + (max_height - height)/2;
1186
1187                         /* Adjust for extra allocation */
1188                         x = x + MAX (0, allocation.width -
1189                                      ((max_width + overall_border.left + overall_border.right) * 2 + view->spacing * 3))/2;
1190                         y = y + MAX (0, allocation.height - (height + view->spacing * 2))/2;
1191                 } else {
1192                         x = view->spacing;
1193                         y = view->spacing;
1194
1195                         /* Adjust for extra allocation */
1196                         x = x + MAX (0, allocation.width - (width + border->left + border->right + view->spacing * 2))/2;
1197                         y = y + MAX (0, allocation.height - (height + border->top + border->bottom +  view->spacing * 2))/2;
1198                 }
1199
1200                 page_area->x = x;
1201                 page_area->y = y;
1202         }
1203
1204         return TRUE;
1205 }
1206
1207 static void
1208 get_doc_page_size (EvView  *view,
1209                    gint     page,
1210                    gdouble *width,
1211                    gdouble *height)
1212 {
1213         double w, h;
1214
1215         ev_document_get_page_size (view->document, page, &w, &h);
1216         if (view->rotation == 0 || view->rotation == 180) {
1217                 if (width) *width = w;
1218                 if (height) *height = h;
1219         } else {
1220                 if (width) *width = h;
1221                 if (height) *height = w;
1222         }
1223 }
1224
1225 static void
1226 view_point_to_doc_point (EvView *view,
1227                          GdkPoint *view_point,
1228                          GdkRectangle *page_area,
1229                          double  *doc_point_x,
1230                          double  *doc_point_y)
1231 {
1232         *doc_point_x = (double) (view_point->x - page_area->x) / view->scale;
1233         *doc_point_y = (double) (view_point->y - page_area->y) / view->scale;
1234 }
1235
1236 static void
1237 view_rect_to_doc_rect (EvView *view,
1238                        GdkRectangle *view_rect,
1239                        GdkRectangle *page_area,
1240                        EvRectangle  *doc_rect)
1241 {
1242         doc_rect->x1 = (double) (view_rect->x - page_area->x) / view->scale;
1243         doc_rect->y1 = (double) (view_rect->y - page_area->y) / view->scale;
1244         doc_rect->x2 = doc_rect->x1 + (double) view_rect->width / view->scale;
1245         doc_rect->y2 = doc_rect->y1 + (double) view_rect->height / view->scale;
1246 }
1247
1248 static void
1249 doc_point_to_view_point (EvView       *view,
1250                          int           page,
1251                          EvPoint      *doc_point,
1252                          GdkPoint     *view_point)
1253 {
1254         GdkRectangle page_area;
1255         GtkBorder border;
1256         double x, y, view_x, view_y;
1257         gdouble width, height;
1258
1259         get_doc_page_size (view, page, &width, &height);
1260
1261         if (view->rotation == 0) {
1262                 x = doc_point->x;
1263                 y = doc_point->y;
1264         } else if (view->rotation == 90) {
1265                 x = width - doc_point->y;
1266                 y = doc_point->x;
1267         } else if (view->rotation == 180) {
1268                 x = width - doc_point->x;
1269                 y = height - doc_point->y;
1270         } else if (view->rotation == 270) {
1271                 x = doc_point->y;
1272                 y = height - doc_point->x;
1273         } else {
1274                 g_assert_not_reached ();
1275         }
1276
1277         ev_view_get_page_extents (view, page, &page_area, &border);
1278
1279         view_x = CLAMP (x * view->scale, 0, page_area.width);
1280         view_y = CLAMP (y * view->scale, 0, page_area.height);
1281         view_point->x = view_x + page_area.x;
1282         view_point->y = view_y + page_area.y;
1283 }
1284
1285 static void
1286 doc_rect_to_view_rect (EvView       *view,
1287                        int           page,
1288                        EvRectangle  *doc_rect,
1289                        GdkRectangle *view_rect)
1290 {
1291         GdkRectangle page_area;
1292         GtkBorder border;
1293         double x, y, w, h;
1294         gdouble width, height;
1295
1296         get_doc_page_size (view, page, &width, &height);
1297
1298         if (view->rotation == 0) {
1299                 x = doc_rect->x1;
1300                 y = doc_rect->y1;
1301                 w = doc_rect->x2 - doc_rect->x1;
1302                 h = doc_rect->y2 - doc_rect->y1;
1303         } else if (view->rotation == 90) {
1304                 x = width - doc_rect->y2;
1305                 y = doc_rect->x1;
1306                 w = doc_rect->y2 - doc_rect->y1;
1307                 h = doc_rect->x2 - doc_rect->x1;
1308         } else if (view->rotation == 180) {
1309                 x = width - doc_rect->x2;
1310                 y = height - doc_rect->y2;
1311                 w = doc_rect->x2 - doc_rect->x1;
1312                 h = doc_rect->y2 - doc_rect->y1;
1313         } else if (view->rotation == 270) {
1314                 x = doc_rect->y1;
1315                 y = height - doc_rect->x2;
1316                 w = doc_rect->y2 - doc_rect->y1;
1317                 h = doc_rect->x2 - doc_rect->x1;
1318         } else {
1319                 g_assert_not_reached ();
1320         }
1321
1322         ev_view_get_page_extents (view, page, &page_area, &border);
1323
1324         view_rect->x = x * view->scale + page_area.x;
1325         view_rect->y = y * view->scale + page_area.y;
1326         view_rect->width = w * view->scale;
1327         view_rect->height = h * view->scale;
1328 }
1329
1330 static gboolean
1331 get_dual_even_left (EvView *view)
1332 {
1333         return (ev_document_get_n_pages (view->document) > 2);
1334 }
1335
1336 static void
1337 find_page_at_location (EvView  *view,
1338                        gdouble  x,
1339                        gdouble  y,
1340                        gint    *page,
1341                        gint    *x_offset,
1342                        gint    *y_offset)
1343 {
1344         int i;
1345
1346         if (view->document == NULL)
1347                 return;
1348
1349         g_assert (page);
1350         g_assert (x_offset);
1351         g_assert (y_offset);
1352
1353         for (i = view->start_page; i >= 0 && i <= view->end_page; i++) {
1354                 GdkRectangle page_area;
1355                 GtkBorder border;
1356
1357                 if (! ev_view_get_page_extents (view, i, &page_area, &border))
1358                         continue;
1359
1360                 if ((x >= page_area.x + border.left) &&
1361                     (x < page_area.x + page_area.width - border.right) &&
1362                     (y >= page_area.y + border.top) &&
1363                     (y < page_area.y + page_area.height - border.bottom)) {
1364                         *page = i;
1365                         *x_offset = x - (page_area.x + border.left);
1366                         *y_offset = y - (page_area.y + border.top);
1367                         return;
1368                 }
1369         }
1370
1371         *page = -1;
1372 }
1373
1374 static gboolean
1375 location_in_text (EvView  *view,
1376                   gdouble  x,
1377                   gdouble  y)
1378 {
1379         cairo_region_t *region;
1380         gint page = -1;
1381         gint x_offset = 0, y_offset = 0;
1382
1383         find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
1384
1385         if (page == -1)
1386                 return FALSE;
1387         
1388         region = ev_page_cache_get_text_mapping (view->page_cache, page);
1389
1390         if (region)
1391                 return cairo_region_contains_point (region, x_offset / view->scale, y_offset / view->scale);
1392         else
1393                 return FALSE;
1394 }
1395
1396 static gboolean
1397 location_in_selected_text (EvView  *view,
1398                            gdouble  x,
1399                            gdouble  y)
1400 {
1401         gint page = -1;
1402         gint x_offset = 0, y_offset = 0;
1403         EvViewSelection *selection;
1404         GList *l = NULL;
1405
1406         for (l = view->selection_info.selections; l != NULL; l = l->next) {
1407                 selection = (EvViewSelection *)l->data;
1408                 
1409                 find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
1410                 
1411                 if (page != selection->page)
1412                         continue;
1413                 
1414                 if (selection->covered_region &&
1415                     cairo_region_contains_point (selection->covered_region, x_offset, y_offset))
1416                         return TRUE;
1417         }
1418
1419         return FALSE;
1420 }
1421
1422 static gboolean
1423 get_doc_point_from_offset (EvView *view, 
1424                            gint    page, 
1425                            gint    x_offset, 
1426                            gint    y_offset, 
1427                            gint   *x_new, 
1428                            gint   *y_new)
1429 {
1430         gdouble width, height;
1431         double x, y;
1432
1433         get_doc_page_size (view, page, &width, &height);
1434
1435         x_offset = x_offset / view->scale;
1436         y_offset = y_offset / view->scale;
1437
1438         if (view->rotation == 0) {
1439                 x = x_offset;
1440                 y = y_offset;
1441         } else if (view->rotation == 90) {
1442                 x = y_offset;
1443                 y = width - x_offset;
1444         } else if (view->rotation == 180) {
1445                 x = width - x_offset;
1446                 y = height - y_offset;
1447         } else if (view->rotation == 270) {
1448                 x = height - y_offset; 
1449                 y = x_offset;
1450         } else {
1451                 g_assert_not_reached ();
1452         }
1453
1454         *x_new = x;
1455         *y_new = y;
1456         
1457         return TRUE;
1458 }
1459
1460 static gboolean
1461 get_doc_point_from_location (EvView  *view,
1462                              gdouble  x,
1463                              gdouble  y,
1464                              gint    *page,
1465                              gint    *x_new,
1466                              gint    *y_new)
1467 {
1468         gint x_offset = 0, y_offset = 0;
1469
1470         x += view->scroll_x;
1471         y += view->scroll_y;
1472         find_page_at_location (view, x, y, page, &x_offset, &y_offset);
1473         if (*page == -1)
1474                 return FALSE;
1475
1476         return get_doc_point_from_offset (view, *page, x_offset, y_offset, x_new, y_new);
1477 }
1478
1479 static void
1480 ev_view_get_area_from_mapping (EvView        *view,
1481                                guint          page,
1482                                EvMappingList *mapping_list,
1483                                gconstpointer  data,
1484                                GdkRectangle  *area)
1485 {
1486         EvMapping *mapping;
1487
1488         mapping = ev_mapping_list_find (mapping_list, data);
1489         doc_rect_to_view_rect (view, page, &mapping->area, area);
1490         area->x -= view->scroll_x;
1491         area->y -= view->scroll_y;
1492 }
1493
1494 static void
1495 ev_view_put (EvView      *view,
1496              GtkWidget   *child_widget,
1497              gint         x,
1498              gint         y,
1499              guint        page,
1500              EvRectangle *doc_rect)
1501 {
1502         EvViewChild *child;
1503
1504         child = g_slice_new (EvViewChild);
1505
1506         child->widget = child_widget;
1507         child->x = x;
1508         child->y = y;
1509         child->page = page;
1510         child->doc_rect = *doc_rect;
1511
1512         gtk_widget_set_parent (child_widget, GTK_WIDGET (view));
1513         view->children = g_list_append (view->children, child);
1514 }
1515
1516 static void
1517 ev_view_put_to_doc_rect (EvView      *view,
1518                          GtkWidget   *child_widget,
1519                          guint        page,
1520                          EvRectangle *doc_rect)
1521 {
1522         GdkRectangle area;
1523
1524         doc_rect_to_view_rect (view, page, doc_rect, &area);
1525         area.x -= view->scroll_x;
1526         area.y -= view->scroll_y;
1527         ev_view_put (view, child_widget, area.x, area.y, page, doc_rect);
1528 }
1529
1530 /*** Hyperref ***/
1531 static EvLink *
1532 ev_view_get_link_at_location (EvView  *view,
1533                               gdouble  x,
1534                               gdouble  y)
1535 {
1536         gint page = -1;
1537         gint x_new = 0, y_new = 0;
1538         EvMappingList *link_mapping;
1539
1540         if (!EV_IS_DOCUMENT_LINKS (view->document))
1541                 return NULL;
1542
1543         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
1544                 return NULL;
1545
1546         link_mapping = ev_page_cache_get_link_mapping (view->page_cache, page);
1547
1548         if (link_mapping)
1549                 return ev_mapping_list_get_data (link_mapping, x_new, y_new);
1550         else
1551                 return NULL;
1552 }
1553
1554 static void
1555 goto_fitr_dest (EvView *view, EvLinkDest *dest)
1556 {
1557         EvPoint doc_point;
1558         gdouble zoom, left, top;
1559         gboolean change_left, change_top;
1560         GtkAllocation allocation;
1561
1562         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
1563
1564         left = ev_link_dest_get_left (dest, &change_left);
1565         top = ev_link_dest_get_top (dest, &change_top);
1566
1567         zoom = zoom_for_size_best_fit (ev_link_dest_get_right (dest) - left,
1568                                        ev_link_dest_get_bottom (dest) - top,
1569                                        allocation.width,
1570                                        allocation.height);
1571
1572         ev_document_model_set_sizing_mode (view->model, EV_SIZING_FREE);
1573         ev_document_model_set_scale (view->model, zoom);
1574
1575         doc_point.x = change_left ? left : 0;
1576         doc_point.y = change_top ? top : 0;
1577         view->pending_point = doc_point;
1578
1579         ev_view_change_page (view, ev_link_dest_get_page (dest));
1580 }
1581
1582 static void
1583 goto_fitv_dest (EvView *view, EvLinkDest *dest)
1584 {
1585         EvPoint doc_point;
1586         gdouble doc_width, doc_height;
1587         gint page;
1588         double zoom, left;
1589         gboolean change_left;
1590         GtkAllocation allocation;
1591
1592         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
1593
1594         page = ev_link_dest_get_page (dest);
1595         ev_document_get_page_size (view->document, page, &doc_width, &doc_height);
1596
1597         left = ev_link_dest_get_left (dest, &change_left);
1598         doc_point.x = change_left ? left : 0;
1599         doc_point.y = 0;
1600
1601         zoom = zoom_for_size_fit_height (doc_width - doc_point.x , doc_height,
1602                                          allocation.width,
1603                                          allocation.height);
1604
1605         ev_document_model_set_sizing_mode (view->model, EV_SIZING_FREE);
1606         ev_document_model_set_scale (view->model, zoom);
1607
1608         view->pending_point = doc_point;
1609
1610         ev_view_change_page (view, page);
1611 }
1612
1613 static void
1614 goto_fith_dest (EvView *view, EvLinkDest *dest)
1615 {
1616         EvPoint doc_point;
1617         gdouble doc_width, doc_height;
1618         gint page;
1619         gdouble zoom, top;
1620         gboolean change_top;
1621         GtkAllocation allocation;
1622
1623         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
1624
1625         page = ev_link_dest_get_page (dest);
1626         ev_document_get_page_size (view->document, page, &doc_width, &doc_height);
1627
1628         top = ev_link_dest_get_top (dest, &change_top);
1629
1630         doc_point.x = 0;
1631         doc_point.y = change_top ? top : 0;
1632
1633         zoom = zoom_for_size_fit_width (doc_width, top,
1634                                         allocation.width,
1635                                         allocation.height);
1636
1637         ev_document_model_set_sizing_mode (view->model, EV_SIZING_FIT_WIDTH);
1638         ev_document_model_set_scale (view->model, zoom);
1639
1640         view->pending_point = doc_point;
1641
1642         ev_view_change_page (view, page);
1643 }
1644
1645 static void
1646 goto_fit_dest (EvView *view, EvLinkDest *dest)
1647 {
1648         double zoom;
1649         gdouble doc_width, doc_height;
1650         int page;
1651         GtkAllocation allocation;
1652
1653         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
1654
1655         page = ev_link_dest_get_page (dest);
1656         ev_document_get_page_size (view->document, page, &doc_width, &doc_height);
1657
1658         zoom = zoom_for_size_best_fit (doc_width, doc_height,
1659                                        allocation.width,
1660                                        allocation.height);
1661
1662         ev_document_model_set_sizing_mode (view->model, EV_SIZING_BEST_FIT);
1663         ev_document_model_set_scale (view->model, zoom);
1664
1665         ev_view_change_page (view, page);
1666 }
1667
1668 static void
1669 goto_xyz_dest (EvView *view, EvLinkDest *dest)
1670 {
1671         EvPoint doc_point;
1672         gint page;
1673         gdouble zoom, left, top;
1674         gboolean change_zoom, change_left, change_top; 
1675
1676         zoom = ev_link_dest_get_zoom (dest, &change_zoom);
1677         page = ev_link_dest_get_page (dest);
1678
1679         if (change_zoom && zoom > 1) {
1680                 ev_document_model_set_sizing_mode (view->model, EV_SIZING_FREE);
1681                 ev_document_model_set_scale (view->model, zoom);
1682         }
1683
1684         left = ev_link_dest_get_left (dest, &change_left);
1685         top = ev_link_dest_get_top (dest, &change_top);
1686
1687         doc_point.x = change_left ? left : 0;
1688         doc_point.y = change_top ? top : 0;
1689         view->pending_point = doc_point;
1690
1691         ev_view_change_page (view, page);
1692 }
1693
1694 static void
1695 goto_dest (EvView *view, EvLinkDest *dest)
1696 {
1697         EvLinkDestType type;
1698         int page, n_pages, current_page;
1699
1700         page = ev_link_dest_get_page (dest);
1701         n_pages = ev_document_get_n_pages (view->document);
1702
1703         if (page < 0 || page >= n_pages)
1704                 return;
1705
1706         current_page = view->current_page;
1707         
1708         type = ev_link_dest_get_dest_type (dest);
1709
1710         switch (type) {
1711                 case EV_LINK_DEST_TYPE_PAGE:
1712                         ev_document_model_set_page (view->model, page);
1713                         break;
1714                 case EV_LINK_DEST_TYPE_FIT:
1715                         goto_fit_dest (view, dest);
1716                         break;
1717                 case EV_LINK_DEST_TYPE_FITH:
1718                         goto_fith_dest (view, dest);
1719                         break;
1720                 case EV_LINK_DEST_TYPE_FITV:
1721                         goto_fitv_dest (view, dest);
1722                         break;
1723                 case EV_LINK_DEST_TYPE_FITR:
1724                         goto_fitr_dest (view, dest);
1725                         break;
1726                 case EV_LINK_DEST_TYPE_XYZ:
1727                         goto_xyz_dest (view, dest);
1728                         break;
1729                 case EV_LINK_DEST_TYPE_PAGE_LABEL:
1730                         ev_document_model_set_page_by_label (view->model, ev_link_dest_get_page_label (dest));
1731                         break;
1732                 default:
1733                         g_assert_not_reached ();
1734         }
1735
1736         if (current_page != view->current_page)
1737                 ev_document_model_set_page (view->model, view->current_page);
1738 }
1739
1740 static void
1741 ev_view_goto_dest (EvView *view, EvLinkDest *dest)
1742 {
1743         EvLinkDestType type;
1744
1745         type = ev_link_dest_get_dest_type (dest);
1746
1747         if (type == EV_LINK_DEST_TYPE_NAMED) {
1748                 EvLinkDest  *dest2;     
1749                 const gchar *named_dest;
1750
1751                 named_dest = ev_link_dest_get_named_dest (dest);
1752                 dest2 = ev_document_links_find_link_dest (EV_DOCUMENT_LINKS (view->document),
1753                                                           named_dest);
1754                 if (dest2) {
1755                         goto_dest (view, dest2);
1756                         g_object_unref (dest2);
1757                 }
1758
1759                 return;
1760         }
1761
1762         goto_dest (view, dest);
1763 }
1764         
1765 void
1766 ev_view_handle_link (EvView *view, EvLink *link)
1767 {
1768         EvLinkAction    *action = NULL;
1769         EvLinkActionType type;
1770
1771         action = ev_link_get_action (link);
1772         if (!action)
1773                 return;
1774
1775         type = ev_link_action_get_action_type (action);
1776
1777         switch (type) {
1778                 case EV_LINK_ACTION_TYPE_GOTO_DEST: {
1779                         EvLinkDest *dest;
1780                         
1781                         g_signal_emit (view, signals[SIGNAL_HANDLE_LINK], 0, link);
1782                 
1783                         dest = ev_link_action_get_dest (action);
1784                         ev_view_goto_dest (view, dest);
1785                 }
1786                         break;
1787                 case EV_LINK_ACTION_TYPE_LAYERS_STATE: {
1788                         GList            *show, *hide, *toggle;
1789                         GList            *l;
1790                         EvDocumentLayers *document_layers;
1791
1792                         document_layers = EV_DOCUMENT_LAYERS (view->document);
1793
1794                         show = ev_link_action_get_show_list (action);
1795                         for (l = show; l; l = g_list_next (l)) {
1796                                 ev_document_layers_show_layer (document_layers, EV_LAYER (l->data));
1797                         }
1798
1799                         hide = ev_link_action_get_hide_list (action);
1800                         for (l = hide; l; l = g_list_next (l)) {
1801                                 ev_document_layers_hide_layer (document_layers, EV_LAYER (l->data));
1802                         }
1803
1804                         toggle = ev_link_action_get_toggle_list (action);
1805                         for (l = toggle; l; l = g_list_next (l)) {
1806                                 EvLayer *layer = EV_LAYER (l->data);
1807
1808                                 if (ev_document_layers_layer_is_visible (document_layers, layer)) {
1809                                         ev_document_layers_hide_layer (document_layers, layer);
1810                                 } else {
1811                                         ev_document_layers_show_layer (document_layers, layer);
1812                                 }
1813                         }
1814
1815                         g_signal_emit (view, signals[SIGNAL_LAYERS_CHANGED], 0);
1816                         ev_view_reload_page (view, view->current_page, NULL);
1817                 }
1818                         break;
1819                 case EV_LINK_ACTION_TYPE_GOTO_REMOTE:
1820                 case EV_LINK_ACTION_TYPE_EXTERNAL_URI:
1821                 case EV_LINK_ACTION_TYPE_LAUNCH:
1822                 case EV_LINK_ACTION_TYPE_NAMED:
1823                         g_signal_emit (view, signals[SIGNAL_EXTERNAL_LINK], 0, action);
1824                         break;
1825         }
1826 }
1827
1828 static char *
1829 tip_from_action_named (EvLinkAction *action)
1830 {
1831         const gchar *name = ev_link_action_get_name (action);
1832         
1833         if (g_ascii_strcasecmp (name, "FirstPage") == 0) {
1834                 return g_strdup (_("Go to first page"));
1835         } else if (g_ascii_strcasecmp (name, "PrevPage") == 0) {
1836                 return g_strdup (_("Go to previous page"));
1837         } else if (g_ascii_strcasecmp (name, "NextPage") == 0) {
1838                 return g_strdup (_("Go to next page"));
1839         } else if (g_ascii_strcasecmp (name, "LastPage") == 0) {
1840                 return g_strdup (_("Go to last page"));
1841         } else if (g_ascii_strcasecmp (name, "GoToPage") == 0) {
1842                 return g_strdup (_("Go to page"));
1843         } else if (g_ascii_strcasecmp (name, "Find") == 0) {
1844                 return g_strdup (_("Find"));
1845         }
1846         
1847         return NULL;
1848 }
1849
1850 static char *
1851 tip_from_link (EvView *view, EvLink *link)
1852 {
1853         EvLinkAction *action;
1854         EvLinkActionType type;
1855         char *msg = NULL;
1856         char *page_label;
1857         const char *title;
1858
1859         action = ev_link_get_action (link);
1860         title = ev_link_get_title (link);
1861         
1862         if (!action)
1863                 return title ? g_strdup (title) : NULL;
1864                 
1865         type = ev_link_action_get_action_type (action);
1866
1867         switch (type) {
1868                 case EV_LINK_ACTION_TYPE_GOTO_DEST:
1869                         page_label = ev_document_links_get_dest_page_label (EV_DOCUMENT_LINKS (view->document),
1870                                                                             ev_link_action_get_dest (action));
1871                         if (page_label) {
1872                                 msg = g_strdup_printf (_("Go to page %s"), page_label);
1873                                 g_free (page_label);
1874                         }
1875                         break;
1876                 case EV_LINK_ACTION_TYPE_GOTO_REMOTE:
1877                         if (title) {
1878                                 msg = g_strdup_printf (_("Go to %s on file “%s”"), title,
1879                                                        ev_link_action_get_filename (action));
1880                         } else {
1881                                 msg = g_strdup_printf (_("Go to file “%s”"),
1882                                                        ev_link_action_get_filename (action));
1883                         }
1884                         break;
1885                 case EV_LINK_ACTION_TYPE_EXTERNAL_URI:
1886                         msg = g_strdup (ev_link_action_get_uri (action));
1887                         break;
1888                 case EV_LINK_ACTION_TYPE_LAUNCH:
1889                         msg = g_strdup_printf (_("Launch %s"),
1890                                                ev_link_action_get_filename (action));
1891                         break;
1892                 case EV_LINK_ACTION_TYPE_NAMED:
1893                         msg = tip_from_action_named (action);
1894                         break;
1895                 default:
1896                         if (title)
1897                                 msg = g_strdup (title);
1898                         break;
1899         }
1900         
1901         return msg;
1902 }
1903
1904 static void
1905 ev_view_handle_cursor_over_xy (EvView *view, gint x, gint y)
1906 {
1907         EvLink       *link;
1908         EvFormField  *field;
1909         EvAnnotation *annot = NULL;
1910
1911         if (view->cursor == EV_VIEW_CURSOR_HIDDEN)
1912                 return;
1913
1914         if (view->adding_annot) {
1915                 if (view->cursor != EV_VIEW_CURSOR_ADD)
1916                         ev_view_set_cursor (view, EV_VIEW_CURSOR_ADD);
1917                 return;
1918         }
1919
1920         if (view->drag_info.in_drag) {
1921                 if (view->cursor != EV_VIEW_CURSOR_DRAG)
1922                         ev_view_set_cursor (view, EV_VIEW_CURSOR_DRAG);
1923                 return;
1924         }
1925
1926         if (view->scroll_info.autoscrolling) {
1927                 if (view->cursor != EV_VIEW_CURSOR_AUTOSCROLL)
1928                         ev_view_set_cursor (view, EV_VIEW_CURSOR_AUTOSCROLL);
1929                 return;
1930         }
1931
1932         link = ev_view_get_link_at_location (view, x, y);
1933         if (link) {
1934                 ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1935         } else if ((field = ev_view_get_form_field_at_location (view, x, y))) {
1936                 if (field->is_read_only) {
1937                         if (view->cursor == EV_VIEW_CURSOR_LINK ||
1938                             view->cursor == EV_VIEW_CURSOR_IBEAM ||
1939                             view->cursor == EV_VIEW_CURSOR_DRAG)
1940                                 ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
1941                 } else if (EV_IS_FORM_FIELD_TEXT (field)) {
1942                         ev_view_set_cursor (view, EV_VIEW_CURSOR_IBEAM);
1943                 } else {
1944                         ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1945                 }
1946         } else if ((annot = ev_view_get_annotation_at_location (view, x, y))) {
1947                 ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1948         } else if (location_in_text (view, x + view->scroll_x, y + view->scroll_y)) {
1949                 ev_view_set_cursor (view, EV_VIEW_CURSOR_IBEAM);
1950         } else {
1951                 if (view->cursor == EV_VIEW_CURSOR_LINK ||
1952                     view->cursor == EV_VIEW_CURSOR_IBEAM ||
1953                     view->cursor == EV_VIEW_CURSOR_DRAG ||
1954                     view->cursor == EV_VIEW_CURSOR_AUTOSCROLL ||
1955                     view->cursor == EV_VIEW_CURSOR_ADD)
1956                         ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
1957         }
1958
1959         if (link || annot)
1960                 g_object_set (view, "has-tooltip", TRUE, NULL);
1961 }
1962
1963 /*** Images ***/
1964 static EvImage *
1965 ev_view_get_image_at_location (EvView  *view,
1966                                gdouble  x,
1967                                gdouble  y)
1968 {
1969         gint page = -1;
1970         gint x_new = 0, y_new = 0;
1971         EvMappingList *image_mapping;
1972
1973         if (!EV_IS_DOCUMENT_IMAGES (view->document))
1974                 return NULL;
1975
1976         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
1977                 return NULL;
1978
1979         image_mapping = ev_page_cache_get_image_mapping (view->page_cache, page);
1980
1981         if (image_mapping)
1982                 return ev_mapping_list_get_data (image_mapping, x_new, y_new);
1983         else
1984                 return NULL;
1985 }
1986
1987 /*** Forms ***/
1988 static EvFormField *
1989 ev_view_get_form_field_at_location (EvView  *view,
1990                                     gdouble  x,
1991                                     gdouble  y)
1992 {
1993         gint page = -1;
1994         gint x_new = 0, y_new = 0;
1995         EvMappingList *forms_mapping;
1996         
1997         if (!EV_IS_DOCUMENT_FORMS (view->document))
1998                 return NULL;
1999
2000         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
2001                 return NULL;
2002
2003         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache, page);
2004
2005         if (forms_mapping)
2006                 return ev_mapping_list_get_data (forms_mapping, x_new, y_new);
2007         else
2008                 return NULL;
2009 }
2010
2011 static cairo_region_t *
2012 ev_view_form_field_get_region (EvView      *view,
2013                                EvFormField *field)
2014 {
2015         GdkRectangle   view_area;
2016         EvMappingList *forms_mapping;
2017
2018         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
2019                                                               field->page->index);
2020         ev_view_get_area_from_mapping (view, field->page->index,
2021                                        forms_mapping,
2022                                        field, &view_area);
2023
2024         return cairo_region_create_rectangle (&view_area);
2025 }
2026
2027 static gboolean
2028 ev_view_forms_remove_widgets (EvView *view)
2029 {
2030         ev_view_remove_all (view);
2031
2032         return FALSE;
2033 }
2034
2035 static void
2036 ev_view_form_field_destroy (GtkWidget *widget,
2037                             EvView    *view)
2038 {
2039         g_idle_add ((GSourceFunc)ev_view_forms_remove_widgets, view);
2040 }
2041
2042 static GtkWidget *
2043 ev_view_form_field_button_create_widget (EvView      *view,
2044                                          EvFormField *field)
2045 {
2046         EvFormFieldButton *field_button = EV_FORM_FIELD_BUTTON (field);
2047         cairo_region_t    *field_region = NULL;
2048         
2049         switch (field_button->type) {
2050                 case EV_FORM_FIELD_BUTTON_PUSH:
2051                         return NULL;
2052                 case EV_FORM_FIELD_BUTTON_CHECK:
2053                 case EV_FORM_FIELD_BUTTON_RADIO: {
2054                         gboolean       state;
2055                         EvMappingList *forms_mapping;
2056                         GList         *l;
2057
2058                         state = ev_document_forms_form_field_button_get_state (EV_DOCUMENT_FORMS (view->document),
2059                                                                                field);
2060
2061                         /* FIXME: it actually depends on NoToggleToOff flags */
2062                         if (field_button->type == EV_FORM_FIELD_BUTTON_RADIO &&
2063                             state && field_button->state)
2064                                 return NULL;
2065                         
2066                         field_region = ev_view_form_field_get_region (view, field);
2067
2068                         /* For radio buttons and checkbox buttons that are in a set
2069                          * we need to update also the region for the current selected item
2070                          */
2071                         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
2072                                                                               field->page->index);
2073                         for (l = ev_mapping_list_get_list (forms_mapping); l; l = g_list_next (l)) {
2074                                 EvFormField *button = ((EvMapping *)(l->data))->data;
2075                                 cairo_region_t *button_region;
2076
2077                                 if (button->id == field->id)
2078                                         continue;
2079
2080                                 /* FIXME: only buttons in the same group should be updated */
2081                                 if (!EV_IS_FORM_FIELD_BUTTON (button) ||
2082                                     EV_FORM_FIELD_BUTTON (button)->type != field_button->type ||
2083                                     EV_FORM_FIELD_BUTTON (button)->state != TRUE)
2084                                         continue;
2085
2086                                 button_region = ev_view_form_field_get_region (view, button);
2087                                 cairo_region_union (field_region, button_region);
2088                                 cairo_region_destroy (button_region);
2089                         }
2090                         
2091                         ev_document_forms_form_field_button_set_state (EV_DOCUMENT_FORMS (view->document),
2092                                                                        field, !state);
2093                         field_button->state = !state;
2094                 }
2095                         break;
2096         }
2097
2098         ev_view_reload_page (view, field->page->index, field_region);
2099         cairo_region_destroy (field_region);
2100         
2101         return NULL;
2102 }
2103
2104 static void
2105 ev_view_form_field_text_save (EvView    *view,
2106                               GtkWidget *widget)
2107 {
2108         EvFormField *field;
2109
2110         if (!view->document)
2111                 return;
2112         
2113         field = g_object_get_data (G_OBJECT (widget), "form-field");
2114         
2115         if (field->changed) {
2116                 EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2117                 cairo_region_t  *field_region;
2118
2119                 field_region = ev_view_form_field_get_region (view, field);
2120                 
2121                 ev_document_forms_form_field_text_set_text (EV_DOCUMENT_FORMS (view->document),
2122                                                             field, field_text->text);
2123                 field->changed = FALSE;
2124                 ev_view_reload_page (view, field->page->index, field_region);
2125                 cairo_region_destroy (field_region);
2126         }
2127 }
2128
2129 static void
2130 ev_view_form_field_text_changed (GtkWidget   *widget,
2131                                  EvFormField *field)
2132 {
2133         EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2134         gchar           *text = NULL;
2135
2136         if (GTK_IS_ENTRY (widget)) {
2137                 text = g_strdup (gtk_entry_get_text (GTK_ENTRY (widget)));
2138         } else if (GTK_IS_TEXT_BUFFER (widget)) {
2139                 GtkTextIter start, end;
2140
2141                 gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (widget), &start, &end);
2142                 text = gtk_text_buffer_get_text (GTK_TEXT_BUFFER (widget),
2143                                                  &start, &end, FALSE);
2144         }
2145
2146         if (!field_text->text ||
2147             (field_text->text && g_ascii_strcasecmp (field_text->text, text) != 0)) {
2148                 g_free (field_text->text);
2149                 field_text->text = text;
2150                 field->changed = TRUE;
2151         }
2152 }
2153
2154 static gboolean
2155 ev_view_form_field_text_focus_out (GtkWidget     *widget,
2156                                    GdkEventFocus *event,
2157                                    EvView        *view)
2158 {
2159         ev_view_form_field_text_save (view, widget);
2160
2161         return FALSE;
2162 }
2163
2164 static GtkWidget *
2165 ev_view_form_field_text_create_widget (EvView      *view,
2166                                        EvFormField *field)
2167 {
2168         EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2169         GtkWidget       *text = NULL;
2170         gchar           *txt;
2171
2172         txt = ev_document_forms_form_field_text_get_text (EV_DOCUMENT_FORMS (view->document),
2173                                                           field);
2174
2175         switch (field_text->type) {
2176                 case EV_FORM_FIELD_TEXT_FILE_SELECT:
2177                         /* TODO */
2178                 case EV_FORM_FIELD_TEXT_NORMAL:
2179                         text = gtk_entry_new ();
2180                         gtk_entry_set_has_frame (GTK_ENTRY (text), FALSE);
2181                         gtk_entry_set_max_length (GTK_ENTRY (text), field_text->max_len);
2182                         gtk_entry_set_visibility (GTK_ENTRY (text), !field_text->is_password);
2183                         
2184                         if (txt) {
2185                                 gtk_entry_set_text (GTK_ENTRY (text), txt);
2186                                 g_free (txt);
2187                         }
2188
2189                         g_signal_connect (text, "focus-out-event",
2190                                           G_CALLBACK (ev_view_form_field_text_focus_out),
2191                                           view);
2192                         g_signal_connect (text, "changed",
2193                                           G_CALLBACK (ev_view_form_field_text_changed),
2194                                           field);
2195                         g_signal_connect_after (text, "activate",
2196                                                 G_CALLBACK (ev_view_form_field_destroy),
2197                                                 view);
2198                         break;
2199                 case EV_FORM_FIELD_TEXT_MULTILINE: {
2200                         GtkTextBuffer *buffer;
2201                 
2202                         text = gtk_text_view_new ();
2203                         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text));
2204                         
2205                         if (txt) {
2206                                 gtk_text_buffer_set_text (buffer, txt, -1);
2207                                 g_free (txt);
2208                         }
2209
2210                         g_signal_connect( buffer, "focus-out-event",
2211                                           G_CALLBACK (ev_view_form_field_text_focus_out),
2212                                           view);
2213                         g_signal_connect (buffer, "changed",
2214                                           G_CALLBACK (ev_view_form_field_text_changed),
2215                                           field);
2216                 }
2217                         break;
2218         }                       
2219
2220         g_object_weak_ref (G_OBJECT (text),
2221                            (GWeakNotify)ev_view_form_field_text_save,
2222                            view);
2223
2224         return text;
2225 }
2226
2227 static void
2228 ev_view_form_field_choice_save (EvView    *view,
2229                                 GtkWidget *widget)
2230 {
2231         EvFormField *field;
2232
2233         if (!view->document)
2234                 return;
2235         
2236         field = g_object_get_data (G_OBJECT (widget), "form-field");
2237
2238         if (field->changed) {
2239                 GList             *l;
2240                 EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2241                 cairo_region_t    *field_region;
2242
2243                 field_region = ev_view_form_field_get_region (view, field);
2244
2245                 if (field_choice->is_editable) {
2246                         ev_document_forms_form_field_choice_set_text (EV_DOCUMENT_FORMS (view->document),
2247                                                                       field, field_choice->text);
2248                 } else {
2249                         ev_document_forms_form_field_choice_unselect_all (EV_DOCUMENT_FORMS (view->document), field);
2250                         for (l = field_choice->selected_items; l; l = g_list_next (l)) {
2251                                 ev_document_forms_form_field_choice_select_item (EV_DOCUMENT_FORMS (view->document),
2252                                                                                  field,
2253                                                                                  GPOINTER_TO_INT (l->data));
2254                         }
2255                 }
2256                 field->changed = FALSE;
2257                 ev_view_reload_page (view, field->page->index, field_region);
2258                 cairo_region_destroy (field_region);
2259         }
2260 }
2261
2262 static void
2263 ev_view_form_field_choice_changed (GtkWidget   *widget,
2264                                    EvFormField *field)
2265 {
2266         EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2267         
2268         if (GTK_IS_COMBO_BOX (widget)) {
2269                 gint item;
2270                 
2271                 item = gtk_combo_box_get_active (GTK_COMBO_BOX (widget));
2272                 if (!field_choice->selected_items ||
2273                     GPOINTER_TO_INT (field_choice->selected_items->data) != item) {
2274                         g_list_free (field_choice->selected_items);
2275                         field_choice->selected_items = NULL;
2276                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2277                                                                        GINT_TO_POINTER (item));
2278                         field->changed = TRUE;
2279                 }
2280
2281                 if (gtk_combo_box_get_has_entry (GTK_COMBO_BOX (widget))) {
2282                         const gchar *text;
2283
2284                         text = gtk_entry_get_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (widget))));
2285                         if (!field_choice->text ||
2286                             (field_choice->text && g_ascii_strcasecmp (field_choice->text, text) != 0)) {
2287                                 g_free (field_choice->text);
2288                                 field_choice->text = g_strdup (text);
2289                                 field->changed = TRUE;
2290                         }
2291                 }
2292         } else if (GTK_IS_TREE_SELECTION (widget)) {
2293                 GtkTreeSelection *selection = GTK_TREE_SELECTION (widget);
2294                 GtkTreeModel     *model;
2295                 GList            *items, *l;
2296                 
2297                 items = gtk_tree_selection_get_selected_rows (selection, &model);
2298                 g_list_free (field_choice->selected_items);
2299                 field_choice->selected_items = NULL;
2300
2301                 for (l = items; l && l->data; l = g_list_next (l)) {
2302                         GtkTreeIter  iter;
2303                         GtkTreePath *path = (GtkTreePath *)l->data;
2304                         gint         item;
2305                         
2306                         gtk_tree_model_get_iter (model, &iter, path);
2307                         gtk_tree_model_get (model, &iter, 1, &item, -1);
2308
2309                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2310                                                                        GINT_TO_POINTER (item));
2311
2312                         gtk_tree_path_free (path);
2313                 }
2314
2315                 g_list_free (items);
2316
2317                 field->changed = TRUE;
2318         }
2319 }
2320
2321 static GtkWidget *
2322 ev_view_form_field_choice_create_widget (EvView      *view,
2323                                          EvFormField *field)
2324 {
2325         EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2326         GtkWidget         *choice;
2327         GtkTreeModel      *model;
2328         gint               n_items, i;
2329         gint               selected_item = 0;
2330
2331         n_items = ev_document_forms_form_field_choice_get_n_items (EV_DOCUMENT_FORMS (view->document),
2332                                                                    field);
2333         model = GTK_TREE_MODEL (gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT));
2334         for (i = 0; i < n_items; i++) {
2335                 GtkTreeIter iter;
2336                 gchar      *item;
2337
2338                 item = ev_document_forms_form_field_choice_get_item (EV_DOCUMENT_FORMS (view->document),
2339                                                                      field, i);
2340                 if (ev_document_forms_form_field_choice_is_item_selected (
2341                             EV_DOCUMENT_FORMS (view->document), field, i)) {
2342                         selected_item = i;
2343                         /* FIXME: we need a get_selected_items function in poppler */
2344                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2345                                                                        GINT_TO_POINTER (i));
2346                 }
2347                 
2348                 if (item) {
2349                         gtk_list_store_append (GTK_LIST_STORE (model), &iter);
2350                         gtk_list_store_set (GTK_LIST_STORE (model), &iter,
2351                                             0, item,
2352                                             1, i,
2353                                             -1);
2354                         g_free (item);
2355                 }
2356         }
2357
2358         if (field_choice->type == EV_FORM_FIELD_CHOICE_LIST) {
2359                 GtkCellRenderer  *renderer;
2360                 GtkWidget        *tree_view;
2361                 GtkTreeSelection *selection;
2362
2363                 tree_view = gtk_tree_view_new_with_model (model);
2364                 gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (tree_view), FALSE);
2365
2366                 selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view));
2367                 if (field_choice->multi_select) {
2368                         gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);
2369                 }
2370
2371                 /* TODO: set selected items */
2372
2373                 renderer = gtk_cell_renderer_text_new ();
2374                 gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (tree_view),
2375                                                              0,
2376                                                              "choix", renderer,
2377                                                              "text", 0,
2378                                                              NULL);
2379
2380                 choice = gtk_scrolled_window_new (NULL, NULL);
2381                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (choice),
2382                                                 GTK_POLICY_AUTOMATIC,
2383                                                 GTK_POLICY_AUTOMATIC);
2384                 gtk_container_add (GTK_CONTAINER (choice), tree_view);
2385                 gtk_widget_show (tree_view);
2386
2387                 g_signal_connect (selection, "changed",
2388                                   G_CALLBACK (ev_view_form_field_choice_changed),
2389                                   field);
2390                 g_signal_connect_after (selection, "changed",
2391                                         G_CALLBACK (ev_view_form_field_destroy),
2392                                         view);
2393         } else if (field_choice->is_editable) { /* ComboBoxEntry */
2394                 gchar *text;
2395
2396                 /* FIXME once gtk bug 633050 is fixed */
2397                 choice = g_object_new (GTK_TYPE_COMBO_BOX, "has-entry", TRUE, "model", model, NULL);
2398
2399                 text = ev_document_forms_form_field_choice_get_text (EV_DOCUMENT_FORMS (view->document), field);
2400                 if (text) {
2401                         gtk_entry_set_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (choice))), text);
2402                         g_free (text);
2403                 }
2404
2405                 g_signal_connect (choice, "changed",
2406                                   G_CALLBACK (ev_view_form_field_choice_changed),
2407                                   field);
2408                 g_signal_connect_after (gtk_bin_get_child (GTK_BIN (choice)),
2409                                         "activate",
2410                                         G_CALLBACK (ev_view_form_field_destroy),
2411                                         view);
2412         } else { /* ComboBoxText */
2413                 GtkCellRenderer *renderer;
2414
2415                 choice = gtk_combo_box_new_with_model (model);
2416                 renderer = gtk_cell_renderer_text_new ();
2417                 gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (choice),
2418                                             renderer, TRUE);
2419                 gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (choice),
2420                                                 renderer,
2421                                                 "text", 0,
2422                                                 NULL);
2423                 gtk_combo_box_set_active (GTK_COMBO_BOX (choice), selected_item);
2424                 gtk_combo_box_popup (GTK_COMBO_BOX (choice));
2425                 
2426                 g_signal_connect (choice, "changed",
2427                                   G_CALLBACK (ev_view_form_field_choice_changed),
2428                                   field);
2429                 g_signal_connect_after (choice, "changed",
2430                                         G_CALLBACK (ev_view_form_field_destroy),
2431                                         view);
2432         }
2433
2434         g_object_unref (model);
2435
2436         g_object_weak_ref (G_OBJECT (choice),
2437                            (GWeakNotify)ev_view_form_field_choice_save,
2438                            view);
2439
2440         return choice;
2441 }
2442
2443 static void
2444 ev_view_handle_form_field (EvView      *view,
2445                            EvFormField *field,
2446                            gdouble      x,
2447                            gdouble      y)
2448 {
2449         GtkWidget     *field_widget = NULL;
2450         EvMappingList *form_field_mapping;
2451         EvMapping     *mapping;
2452
2453         if (field->is_read_only)
2454                 return;
2455         
2456         if (EV_IS_FORM_FIELD_BUTTON (field)) {
2457                 field_widget = ev_view_form_field_button_create_widget (view, field);
2458         } else if (EV_IS_FORM_FIELD_TEXT (field)) {
2459                 field_widget = ev_view_form_field_text_create_widget (view, field);
2460         } else if (EV_IS_FORM_FIELD_CHOICE (field)) {
2461                 field_widget = ev_view_form_field_choice_create_widget (view, field);
2462         } else if (EV_IS_FORM_FIELD_SIGNATURE (field)) {
2463                 /* TODO */
2464         }
2465
2466         /* Form field doesn't require a widget */
2467         if (!field_widget)
2468                 return;
2469
2470         g_object_set_data_full (G_OBJECT (field_widget), "form-field",
2471                                 g_object_ref (field),
2472                                 (GDestroyNotify)g_object_unref);
2473
2474         form_field_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
2475                                                                    field->page->index);
2476         mapping = ev_mapping_list_find (form_field_mapping, field);
2477         ev_view_put_to_doc_rect (view, field_widget, field->page->index, &mapping->area);
2478         gtk_widget_show (field_widget);
2479         gtk_widget_grab_focus (field_widget);
2480 }
2481
2482 /* Annotations */
2483 static EvViewWindowChild *
2484 ev_view_get_window_child (EvView    *view,
2485                           GtkWidget *window)
2486 {
2487         GList *children = view->window_children;
2488
2489         while (children) {
2490                 EvViewWindowChild *child;
2491
2492                 child = (EvViewWindowChild *)children->data;
2493                 children = children->next;
2494
2495                 if (child->window == window)
2496                         return child;
2497         }
2498
2499         return NULL;
2500 }
2501
2502 static void
2503 ev_view_window_child_move (EvView            *view,
2504                            EvViewWindowChild *child,
2505                            gint               x,
2506                            gint               y)
2507 {
2508         GtkAllocation allocation;
2509         gint          width, height;
2510
2511         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
2512         gtk_window_get_size (GTK_WINDOW (child->window), &width, &height);
2513
2514         child->x = x;
2515         child->y = y;
2516         gtk_window_move (GTK_WINDOW (child->window),
2517                          CLAMP (x, child->parent_x,
2518                                 child->parent_x + allocation.width - width),
2519                          CLAMP (y, child->parent_y,
2520                                 child->parent_y + allocation.height - height));
2521 }
2522
2523 static void
2524 ev_view_window_child_move_with_parent (EvView    *view,
2525                                        GtkWidget *window)
2526 {
2527         EvViewWindowChild *child;
2528         gint               root_x, root_y;
2529
2530         child = ev_view_get_window_child (view, window);
2531         gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
2532                                &root_x, &root_y);
2533         if (root_x != child->parent_x || root_y != child->parent_y) {
2534                 gint dest_x, dest_y;
2535
2536                 dest_x = child->x + (root_x - child->parent_x);
2537                 dest_y = child->y + (root_y - child->parent_y);
2538                 child->parent_x = root_x;
2539                 child->parent_y = root_y;
2540                 ev_view_window_child_move (view, child, dest_x, dest_y);
2541         }
2542
2543         if (child->visible && !gtk_widget_get_visible (window))
2544                 gtk_widget_show (window);
2545 }
2546
2547 static void
2548 ev_view_window_child_put (EvView    *view,
2549                           GtkWidget *window,
2550                           guint      page,
2551                           gint       x,
2552                           gint       y,
2553                           gdouble    orig_x,
2554                           gdouble    orig_y)
2555 {
2556         EvViewWindowChild *child;
2557         gint               root_x, root_y;
2558
2559         gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
2560                                &root_x, &root_y);
2561
2562         child = g_new0 (EvViewWindowChild, 1);
2563         child->window = window;
2564         child->page = page;
2565         child->orig_x = orig_x;
2566         child->orig_y = orig_y;
2567         child->parent_x = root_x;
2568         child->parent_y = root_y;
2569         child->visible = ev_annotation_window_is_open (EV_ANNOTATION_WINDOW (window));
2570         ev_view_window_child_move (view, child, x + root_x, y + root_y);
2571
2572         if (child->visible)
2573                 gtk_widget_show (window);
2574         else
2575                 gtk_widget_hide (window);
2576
2577         view->window_children = g_list_append (view->window_children, child);
2578 }
2579
2580 static EvViewWindowChild *
2581 ev_view_find_window_child_for_annot (EvView       *view,
2582                                      guint         page,
2583                                      EvAnnotation *annot)
2584 {
2585         GList *children = view->window_children;
2586
2587         while (children) {
2588                 EvViewWindowChild *child;
2589                 EvAnnotation      *wannot;
2590
2591                 child = (EvViewWindowChild *)children->data;
2592                 children = children->next;
2593
2594                 if (child->page != page)
2595                         continue;
2596
2597                 wannot = ev_annotation_window_get_annotation (EV_ANNOTATION_WINDOW (child->window));
2598                 if (ev_annotation_equal (wannot, annot))
2599                         return child;
2600         }
2601
2602         return NULL;
2603 }
2604
2605 static void
2606 ev_view_window_children_free (EvView *view)
2607 {
2608         GList *l;
2609
2610         if (!view->window_children)
2611                 return;
2612
2613         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
2614                 EvViewWindowChild *child;
2615
2616                 child = (EvViewWindowChild *)l->data;
2617                 gtk_widget_destroy (GTK_WIDGET (child->window));
2618                 g_free (child);
2619         }
2620         g_list_free (view->window_children);
2621         view->window_children = NULL;
2622         view->window_child_focus = NULL;
2623 }
2624
2625 static void
2626 annotation_window_grab_focus (GtkWidget *widget,
2627                               EvView    *view)
2628 {
2629         if (view->window_child_focus)
2630                 ev_annotation_window_ungrab_focus (EV_ANNOTATION_WINDOW (view->window_child_focus->window));
2631         view->window_child_focus = ev_view_get_window_child (view, widget);
2632 }
2633
2634 static void
2635 annotation_window_closed (EvAnnotationWindow *window,
2636                           EvView             *view)
2637 {
2638         EvViewWindowChild *child;
2639
2640         child = ev_view_get_window_child (view, GTK_WIDGET (window));
2641         child->visible = FALSE;
2642 }
2643
2644 static void
2645 annotation_window_moved (EvAnnotationWindow *window,
2646                          gint                x,
2647                          gint                y,
2648                          EvView             *view)
2649 {
2650         EvViewWindowChild *child;
2651         GdkRectangle       page_area;
2652         GtkBorder          border;
2653         GdkRectangle       view_rect;
2654         EvRectangle        doc_rect;
2655         gint               width, height;
2656
2657         child = ev_view_get_window_child (view, GTK_WIDGET (window));
2658         if (child->x == x && child->y == y)
2659                 return;
2660
2661         child->moved = TRUE;
2662         child->x = x;
2663         child->y = y;
2664
2665         /* Window has been moved by the user,
2666          * we have to set a new origin in doc coords
2667          */
2668         gtk_window_get_size (GTK_WINDOW (window), &width, &height);
2669         view_rect.x = (x - child->parent_x) + view->scroll_x;
2670         view_rect.y = (y - child->parent_y) + view->scroll_y;
2671         view_rect.width = width;
2672         view_rect.height = height;
2673
2674         ev_view_get_page_extents (view, child->page, &page_area, &border);
2675         view_rect_to_doc_rect (view, &view_rect, &page_area, &doc_rect);
2676         child->orig_x = doc_rect.x1;
2677         child->orig_y = doc_rect.y1;
2678 }
2679
2680 static void
2681 ev_view_annotation_save_contents (EvView       *view,
2682                                   GParamSpec   *pspec,
2683                                   EvAnnotation *annot)
2684 {
2685         if (!view->document)
2686                 return;
2687
2688         ev_document_doc_mutex_lock ();
2689         ev_document_annotations_save_annotation (EV_DOCUMENT_ANNOTATIONS (view->document),
2690                                                  annot, EV_ANNOTATIONS_SAVE_CONTENTS);
2691         ev_document_doc_mutex_unlock ();
2692 }
2693
2694 static GtkWidget *
2695 ev_view_create_annotation_window (EvView       *view,
2696                                   EvAnnotation *annot,
2697                                   GtkWindow    *parent)
2698 {
2699         GtkWidget   *window;
2700         EvRectangle  doc_rect;
2701         GdkRectangle view_rect;
2702         guint        page;
2703
2704         window = ev_annotation_window_new (annot, parent);
2705         g_signal_connect (window, "grab_focus",
2706                           G_CALLBACK (annotation_window_grab_focus),
2707                           view);
2708         g_signal_connect (window, "closed",
2709                           G_CALLBACK (annotation_window_closed),
2710                           view);
2711         g_signal_connect (window, "moved",
2712                           G_CALLBACK (annotation_window_moved),
2713                           view);
2714         g_signal_connect_swapped (annot, "notify::contents",
2715                                   G_CALLBACK (ev_view_annotation_save_contents),
2716                                   view);
2717         g_object_set_data (G_OBJECT (annot), "popup", window);
2718
2719         page = ev_annotation_get_page_index (annot);
2720         ev_annotation_window_get_rectangle (EV_ANNOTATION_WINDOW (window), &doc_rect);
2721         doc_rect_to_view_rect (view, page, &doc_rect, &view_rect);
2722         view_rect.x -= view->scroll_x;
2723         view_rect.y -= view->scroll_y;
2724
2725         ev_view_window_child_put (view, window, page,
2726                                   view_rect.x, view_rect.y,
2727                                   doc_rect.x1, doc_rect.y1);
2728
2729         return window;
2730 }
2731
2732 static void
2733 show_annotation_windows (EvView *view,
2734                          gint    page)
2735 {
2736         EvMappingList *annots;
2737         GList         *l;
2738         GtkWindow     *parent;
2739
2740         parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view)));
2741
2742         annots = ev_page_cache_get_annot_mapping (view->page_cache, page);
2743
2744         for (l = ev_mapping_list_get_list (annots); l && l->data; l = g_list_next (l)) {
2745                 EvAnnotation      *annot;
2746                 EvViewWindowChild *child;
2747                 GtkWidget         *window;
2748
2749                 annot = ((EvMapping *)(l->data))->data;
2750
2751                 if (!EV_IS_ANNOTATION_MARKUP (annot))
2752                         continue;
2753
2754                 if (!ev_annotation_markup_has_popup (EV_ANNOTATION_MARKUP (annot)))
2755                         continue;
2756
2757                 window = g_object_get_data (G_OBJECT (annot), "popup");
2758                 if (window) {
2759                         ev_view_window_child_move_with_parent (view, window);
2760                         continue;
2761                 }
2762
2763                 /* Look if we already have a popup for this annot */
2764                 child = ev_view_find_window_child_for_annot (view, page, annot);
2765                 window = child ? child->window : NULL;
2766                 if (window) {
2767                         ev_annotation_window_set_annotation (EV_ANNOTATION_WINDOW (window), annot);
2768                         g_object_set_data (G_OBJECT (annot), "popup", window);
2769                         ev_view_window_child_move_with_parent (view, window);
2770                 } else {
2771                         ev_view_create_annotation_window (view, annot, parent);
2772                 }
2773         }
2774 }
2775
2776 static void
2777 hide_annotation_windows (EvView *view,
2778                          gint    page)
2779 {
2780         EvMappingList *annots;
2781         GList         *l;
2782
2783         annots = ev_page_cache_get_annot_mapping (view->page_cache, page);
2784
2785         for (l = ev_mapping_list_get_list (annots); l && l->data; l = g_list_next (l)) {
2786                 EvAnnotation *annot;
2787                 GtkWidget    *window;
2788
2789                 annot = ((EvMapping *)(l->data))->data;
2790
2791                 if (!EV_IS_ANNOTATION_MARKUP (annot))
2792                         continue;
2793
2794                 window = g_object_get_data (G_OBJECT (annot), "popup");
2795                 if (window)
2796                         gtk_widget_hide (window);
2797         }
2798 }
2799
2800 static EvAnnotation *
2801 ev_view_get_annotation_at_location (EvView  *view,
2802                                     gdouble  x,
2803                                     gdouble  y)
2804 {
2805         gint page = -1;
2806         gint x_new = 0, y_new = 0;
2807         EvMappingList *annotations_mapping;
2808
2809         if (!EV_IS_DOCUMENT_ANNOTATIONS (view->document))
2810                 return NULL;
2811
2812         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
2813                 return NULL;
2814
2815         annotations_mapping = ev_page_cache_get_annot_mapping (view->page_cache, page);
2816
2817         if (annotations_mapping)
2818                 return ev_mapping_list_get_data (annotations_mapping, x_new, y_new);
2819         else
2820                 return NULL;
2821 }
2822
2823 static void
2824 ev_view_annotation_show_popup_window (EvView    *view,
2825                                       GtkWidget *window)
2826 {
2827         EvViewWindowChild *child;
2828
2829         if (!window)
2830                 return;
2831
2832         child = ev_view_get_window_child (view, window);
2833         if (!child->visible) {
2834                 child->visible = TRUE;
2835                 ev_view_window_child_move (view, child, child->x, child->y);
2836                 gtk_widget_show (window);
2837         }
2838 }
2839
2840 static void
2841 ev_view_handle_annotation (EvView       *view,
2842                            EvAnnotation *annot,
2843                            gdouble       x,
2844                            gdouble       y,
2845                            guint32       timestamp)
2846 {
2847         if (EV_IS_ANNOTATION_MARKUP (annot)) {
2848                 GtkWidget *window;
2849
2850                 window = g_object_get_data (G_OBJECT (annot), "popup");
2851                 ev_view_annotation_show_popup_window (view, window);
2852         }
2853
2854         if (EV_IS_ANNOTATION_ATTACHMENT (annot)) {
2855                 EvAttachment *attachment;
2856
2857                 attachment = ev_annotation_attachment_get_attachment (EV_ANNOTATION_ATTACHMENT (annot));
2858                 if (attachment) {
2859                         GError *error = NULL;
2860
2861                         ev_attachment_open (attachment,
2862                                             gtk_widget_get_screen (GTK_WIDGET (view)),
2863                                             timestamp,
2864                                             &error);
2865
2866                         if (error) {
2867                                 g_warning ("%s", error->message);
2868                                 g_error_free (error);
2869                         }
2870                 }
2871         }
2872 }
2873
2874 static void
2875 ev_view_create_annotation (EvView          *view,
2876                            EvAnnotationType annot_type,
2877                            gint             x,
2878                            gint             y)
2879 {
2880         EvAnnotation   *annot;
2881         GdkPoint        point;
2882         GdkRectangle    page_area;
2883         GtkBorder       border;
2884         EvRectangle     doc_rect, popup_rect;
2885         EvPage         *page;
2886         GdkColor        color = { 0, 65535, 65535, 0 };
2887         GdkRectangle    view_rect;
2888         cairo_region_t *region;
2889
2890         point.x = x;
2891         point.y = y;
2892         ev_view_get_page_extents (view, view->current_page, &page_area, &border);
2893         view_point_to_doc_point (view, &point, &page_area,
2894                                  &doc_rect.x1, &doc_rect.y1);
2895         doc_rect.x2 = doc_rect.x1 + 24;
2896         doc_rect.y2 = doc_rect.y1 + 24;
2897
2898         ev_document_doc_mutex_lock ();
2899         page = ev_document_get_page (view->document, view->current_page);
2900         switch (annot_type) {
2901         case EV_ANNOTATION_TYPE_TEXT:
2902                 annot = ev_annotation_text_new (page);
2903                 break;
2904         case EV_ANNOTATION_TYPE_ATTACHMENT:
2905                 /* TODO */
2906                 g_object_unref (page);
2907                 ev_document_doc_mutex_unlock ();
2908                 return;
2909         default:
2910                 g_assert_not_reached ();
2911         }
2912         g_object_unref (page);
2913
2914         ev_annotation_set_color (annot, &color);
2915
2916         if (EV_IS_ANNOTATION_MARKUP (annot)) {
2917                 popup_rect.x1 = doc_rect.x2;
2918                 popup_rect.x2 = popup_rect.x1 + 200;
2919                 popup_rect.y1 = doc_rect.y2;
2920                 popup_rect.y2 = popup_rect.y1 + 150;
2921                 g_object_set (annot,
2922                               "rectangle", &popup_rect,
2923                               "has_popup", TRUE,
2924                               "popup_is_open", FALSE,
2925                               "label", g_get_real_name (),
2926                               "opacity", 1.0,
2927                               NULL);
2928         }
2929         ev_document_annotations_add_annotation (EV_DOCUMENT_ANNOTATIONS (view->document),
2930                                                 annot, &doc_rect);
2931         ev_document_doc_mutex_unlock ();
2932
2933         /* If the page didn't have annots, mark the cache as dirty */
2934         if (!ev_page_cache_get_annot_mapping (view->page_cache, view->current_page))
2935                 ev_page_cache_mark_dirty (view->page_cache, view->current_page);
2936
2937         if (EV_IS_ANNOTATION_MARKUP (annot)) {
2938                 GtkWindow *parent;
2939                 GtkWidget *window;
2940
2941                 parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view)));
2942                 window = ev_view_create_annotation_window (view, annot, parent);
2943
2944                 /* Show the annot window the first time */
2945                 ev_view_annotation_show_popup_window (view, window);
2946         }
2947
2948         doc_rect_to_view_rect (view, view->current_page, &doc_rect, &view_rect);
2949         view_rect.x -= view->scroll_x;
2950         view_rect.y -= view->scroll_y;
2951         region = cairo_region_create_rectangle (&view_rect);
2952         ev_view_reload_page (view, view->current_page, region);
2953         cairo_region_destroy (region);
2954
2955         g_signal_emit (view, signals[SIGNAL_ANNOT_ADDED], 0, annot);
2956 }
2957
2958 void
2959 ev_view_focus_annotation (EvView    *view,
2960                           EvMapping *annot_mapping)
2961 {
2962         GdkRectangle  view_rect;
2963         EvAnnotation *annot;
2964         guint         page;
2965
2966         if (!EV_IS_DOCUMENT_ANNOTATIONS (view->document))
2967                 return;
2968
2969         if (view->focus_annotation == annot_mapping)
2970                 return;
2971
2972         view->focus_annotation = annot_mapping;
2973         annot = (EvAnnotation *)annot_mapping->data;
2974
2975         page = ev_annotation_get_page_index (annot);
2976         ev_document_model_set_page (view->model, page);
2977
2978         doc_rect_to_view_rect (view, page,
2979                                &annot_mapping->area, &view_rect);
2980         ensure_rectangle_is_visible (view, &view_rect);
2981         gtk_widget_queue_draw (GTK_WIDGET (view));
2982 }
2983
2984 void
2985 ev_view_begin_add_annotation (EvView          *view,
2986                               EvAnnotationType annot_type)
2987 {
2988         if (annot_type == EV_ANNOTATION_TYPE_UNKNOWN)
2989                 return;
2990
2991         if (view->adding_annot)
2992                 return;
2993
2994         view->adding_annot = TRUE;
2995         view->adding_annot_type = annot_type;
2996         ev_view_set_cursor (view, EV_VIEW_CURSOR_ADD);
2997 }
2998
2999 void
3000 ev_view_cancel_add_annotation (EvView *view)
3001 {
3002         gint x, y;
3003
3004         if (!view->adding_annot)
3005                 return;
3006
3007         view->adding_annot = FALSE;
3008         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
3009         ev_view_handle_cursor_over_xy (view, x, y);
3010 }
3011
3012 static gboolean
3013 ev_view_synctex_backward_search (EvView *view,
3014                                  gdouble x,
3015                                  gdouble y)
3016 {
3017         gint page = -1;
3018         gint x_new = 0, y_new = 0;
3019         EvSourceLink *link;
3020
3021         if (!ev_document_has_synctex (view->document))
3022                 return FALSE;
3023
3024         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
3025                 return FALSE;
3026
3027         link = ev_document_synctex_backward_search (view->document, page, x_new, y_new);
3028         if (link) {
3029                 g_signal_emit (view, signals[SIGNAL_SYNC_SOURCE], 0, link);
3030                 g_free (link);
3031
3032                 return TRUE;
3033         }
3034
3035         return FALSE;
3036 }
3037
3038 /*** GtkWidget implementation ***/
3039
3040 static void
3041 ev_view_size_request_continuous_dual_page (EvView         *view,
3042                                            GtkRequisition *requisition)
3043 {
3044         gint n_pages;
3045
3046         n_pages = ev_document_get_n_pages (view->document) + 1;
3047         get_page_y_offset (view, n_pages, &requisition->height);
3048
3049         switch (view->sizing_mode) {
3050                 case EV_SIZING_FIT_WIDTH:
3051                 case EV_SIZING_BEST_FIT:
3052                         requisition->width = 1;
3053
3054                         break;
3055                 case EV_SIZING_FREE: {
3056                         gint max_width;
3057                         GtkBorder border;
3058
3059                         ev_view_get_max_page_size (view, &max_width, NULL);
3060                         compute_border (view, max_width, max_width, &border);
3061                         requisition->width = (max_width + border.left + border.right) * 2 + (view->spacing * 3);
3062                 }
3063                         break;
3064                 default:
3065                         g_assert_not_reached ();
3066         }
3067 }
3068
3069 static void
3070 ev_view_size_request_continuous (EvView         *view,
3071                                  GtkRequisition *requisition)
3072 {
3073         gint n_pages;
3074
3075         n_pages = ev_document_get_n_pages (view->document);
3076         get_page_y_offset (view, n_pages, &requisition->height);
3077
3078         switch (view->sizing_mode) {
3079                 case EV_SIZING_FIT_WIDTH:
3080                 case EV_SIZING_BEST_FIT:
3081                         requisition->width = 1;
3082
3083                         break;
3084                 case EV_SIZING_FREE: {
3085                         gint max_width;
3086                         GtkBorder border;
3087
3088                         ev_view_get_max_page_size (view, &max_width, NULL);
3089                         compute_border (view, max_width, max_width, &border);
3090                         requisition->width = max_width + (view->spacing * 2) + border.left + border.right;
3091                 }
3092                         break;
3093                 default:
3094                         g_assert_not_reached ();
3095         }
3096 }
3097
3098 static void
3099 ev_view_size_request_dual_page (EvView         *view,
3100                                 GtkRequisition *requisition)
3101 {
3102         GtkBorder border;
3103         gint width, height;
3104
3105         if (view->sizing_mode == EV_SIZING_BEST_FIT) {
3106                 requisition->width = 1;
3107                 requisition->height = 1;
3108
3109                 return;
3110         }
3111
3112         /* Find the largest of the two. */
3113         ev_view_get_page_size (view,
3114                                view->current_page,
3115                                &width, &height);
3116         if (view->current_page + 1 < ev_document_get_n_pages (view->document)) {
3117                 gint width_2, height_2;
3118                 ev_view_get_page_size (view,
3119                                        view->current_page + 1,
3120                                        &width_2, &height_2);
3121                 if (width_2 > width) {
3122                         width = width_2;
3123                         height = height_2;
3124                 }
3125         }
3126         compute_border (view, width, height, &border);
3127
3128         requisition->width = view->sizing_mode == EV_SIZING_FIT_WIDTH ? 1 :
3129                 ((width + border.left + border.right) * 2) + (view->spacing * 3);
3130         requisition->height = (height + border.top + border.bottom) + (view->spacing * 2);
3131 }
3132
3133 static void
3134 ev_view_size_request_single_page (EvView         *view,
3135                                   GtkRequisition *requisition)
3136 {
3137         GtkBorder border;
3138         gint width, height;
3139
3140         if (view->sizing_mode == EV_SIZING_BEST_FIT) {
3141                 requisition->width = 1;
3142                 requisition->height = 1;
3143
3144                 return;
3145         }
3146
3147         ev_view_get_page_size (view, view->current_page, &width, &height);
3148         compute_border (view, width, height, &border);
3149
3150         requisition->width = view->sizing_mode == EV_SIZING_FIT_WIDTH ? 1 :
3151                 width + border.left + border.right + (2 * view->spacing);
3152         requisition->height = height + border.top + border.bottom + (2 * view->spacing);
3153 }
3154
3155 static void
3156 ev_view_size_request (GtkWidget      *widget,
3157                       GtkRequisition *requisition)
3158 {
3159         EvView *view = EV_VIEW (widget);
3160
3161         if (view->document == NULL) {
3162                 view->requisition.width = 1;
3163                 view->requisition.height = 1;
3164
3165                 *requisition = view->requisition;
3166
3167                 return;
3168         }
3169
3170         /* Get zoom for size here when not called from
3171          * ev_view_size_allocate()
3172          */
3173         if (!view->internal_size_request &&
3174             (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
3175              view->sizing_mode == EV_SIZING_BEST_FIT)) {
3176                 GtkAllocation allocation;
3177
3178                 gtk_widget_get_allocation (widget, &allocation);
3179                 ev_view_zoom_for_size (view,
3180                                        allocation.width,
3181                                        allocation.height);
3182         }
3183
3184         if (view->continuous && view->dual_page)
3185                 ev_view_size_request_continuous_dual_page (view, &view->requisition);
3186         else if (view->continuous)
3187                 ev_view_size_request_continuous (view, &view->requisition);
3188         else if (view->dual_page)
3189                 ev_view_size_request_dual_page (view, &view->requisition);
3190         else
3191                 ev_view_size_request_single_page (view, &view->requisition);
3192
3193         *requisition = view->requisition;
3194 }
3195
3196 static void
3197 ev_view_get_preferred_width (GtkWidget *widget,
3198                              gint      *minimum,
3199                              gint      *natural)
3200 {
3201         GtkRequisition requisition;
3202
3203         ev_view_size_request (widget, &requisition);
3204
3205         *minimum = *natural = requisition.width;
3206 }
3207
3208 static void
3209 ev_view_get_preferred_height (GtkWidget *widget,
3210                               gint      *minimum,
3211                               gint      *natural)
3212 {
3213         GtkRequisition requisition;
3214
3215         ev_view_size_request (widget, &requisition);
3216
3217         *minimum = *natural = requisition.height;
3218 }
3219
3220 static void
3221 ev_view_size_allocate (GtkWidget      *widget,
3222                        GtkAllocation  *allocation)
3223 {
3224         EvView *view = EV_VIEW (widget);
3225         GList  *l;
3226         gint    root_x, root_y;
3227
3228         gtk_widget_set_allocation (widget, allocation);
3229
3230         if (gtk_widget_get_realized (widget))
3231                 gdk_window_move_resize (gtk_widget_get_window (widget),
3232                                         allocation->x,
3233                                         allocation->y,
3234                                         allocation->width,
3235                                         allocation->height);
3236
3237         if (!view->document)
3238                 return;
3239
3240         if (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
3241             view->sizing_mode == EV_SIZING_BEST_FIT) {
3242                 GtkRequisition req;
3243
3244                 ev_view_zoom_for_size (view,
3245                                        allocation->width,
3246                                        allocation->height);
3247                 view->internal_size_request = TRUE;
3248                 ev_view_size_request (widget, &req);
3249                 view->internal_size_request = FALSE;
3250         }
3251
3252         ev_view_set_adjustment_values (view, GTK_ORIENTATION_HORIZONTAL);
3253         ev_view_set_adjustment_values (view, GTK_ORIENTATION_VERTICAL);
3254
3255         if (view->document)
3256                 view_update_range_and_current_page (view);
3257
3258         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
3259         view->pending_resize = FALSE;
3260         view->pending_point.x = 0;
3261         view->pending_point.y = 0;
3262
3263         for (l = view->children; l && l->data; l = g_list_next (l)) {
3264                 GdkRectangle view_area;
3265                 EvViewChild *child = (EvViewChild *)l->data;
3266
3267                 if (!gtk_widget_get_visible (child->widget))
3268                         continue;
3269
3270                 doc_rect_to_view_rect (view, child->page, &child->doc_rect, &view_area);
3271                 view_area.x -= view->scroll_x;
3272                 view_area.y -= view->scroll_y;
3273
3274                 gtk_widget_set_size_request (child->widget, view_area.width, view_area.height);
3275                 gtk_widget_size_allocate (child->widget, &view_area);
3276         }
3277
3278         if (view->window_children)
3279                 gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
3280                                        &root_x, &root_y);
3281
3282         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
3283                 EvViewWindowChild *child;
3284                 EvRectangle        doc_rect;
3285                 GdkRectangle       view_rect;
3286
3287                 child = (EvViewWindowChild *)l->data;
3288
3289                 ev_annotation_window_get_rectangle (EV_ANNOTATION_WINDOW (child->window), &doc_rect);
3290                 if (child->moved) {
3291                         doc_rect.x1 = child->orig_x;
3292                         doc_rect.y1 = child->orig_y;
3293                 }
3294                 doc_rect_to_view_rect (view, child->page, &doc_rect, &view_rect);
3295                 view_rect.x -= view->scroll_x;
3296                 view_rect.y -= view->scroll_y;
3297
3298                 if (view_rect.x != child->orig_x || view_rect.y != child->orig_y) {
3299                         child->parent_x = root_x;
3300                         child->parent_y = root_y;
3301                         ev_view_window_child_move (view, child, view_rect.x + root_x, view_rect.y + root_y);
3302                 }
3303         }
3304 }
3305
3306 static gboolean
3307 ev_view_scroll_event (GtkWidget *widget, GdkEventScroll *event)
3308 {
3309         EvView *view = EV_VIEW (widget);
3310         guint state;
3311
3312         state = event->state & gtk_accelerator_get_default_mod_mask ();
3313
3314         if (state == GDK_CONTROL_MASK) {
3315                 ev_document_model_set_sizing_mode (view->model, EV_SIZING_FREE);
3316                 if (event->direction == GDK_SCROLL_UP ||
3317                     event->direction == GDK_SCROLL_LEFT) {
3318                         if (ev_view_can_zoom_in (view)) {
3319                                 ev_view_zoom_in (view);
3320                         }
3321                 } else {
3322                         if (ev_view_can_zoom_out (view)) {
3323                                 ev_view_zoom_out (view);
3324                         }
3325                 }
3326
3327                 return TRUE;
3328         }
3329
3330         view->jump_to_find_result = FALSE;
3331
3332         /* Shift+Wheel scrolls the in the perpendicular direction */
3333         if (state & GDK_SHIFT_MASK) {
3334                 if (event->direction == GDK_SCROLL_UP)
3335                         event->direction = GDK_SCROLL_LEFT;
3336                 else if (event->direction == GDK_SCROLL_LEFT)
3337                         event->direction = GDK_SCROLL_UP;
3338                 else if (event->direction == GDK_SCROLL_DOWN)
3339                         event->direction = GDK_SCROLL_RIGHT;
3340                 else if (event->direction == GDK_SCROLL_RIGHT)
3341                         event->direction = GDK_SCROLL_DOWN;
3342
3343                 event->state &= ~GDK_SHIFT_MASK;
3344                 state &= ~GDK_SHIFT_MASK;
3345         }
3346
3347         if (state == 0 && view->sizing_mode == EV_SIZING_BEST_FIT && !view->continuous) {
3348                 switch (event->direction) {
3349                         case GDK_SCROLL_DOWN:
3350                         case GDK_SCROLL_RIGHT:
3351                                 ev_view_next_page (view);       
3352                                 break;
3353                         case GDK_SCROLL_UP:
3354                         case GDK_SCROLL_LEFT:
3355                                 ev_view_previous_page (view);
3356                                 break;
3357                 }
3358
3359                 return TRUE;
3360         }
3361
3362         return FALSE;
3363 }
3364
3365 static EvViewSelection *
3366 find_selection_for_page (EvView *view,
3367                          gint    page)
3368 {
3369         GList *list;
3370
3371         for (list = view->selection_info.selections; list != NULL; list = list->next) {
3372                 EvViewSelection *selection;
3373
3374                 selection = (EvViewSelection *) list->data;
3375
3376                 if (selection->page == page)
3377                         return selection;
3378         }
3379
3380         return NULL;
3381 }
3382
3383 static void
3384 ev_view_realize (GtkWidget *widget)
3385 {
3386         GtkAllocation allocation;
3387         GdkWindow *window;
3388         GdkWindowAttr attributes;
3389         gint attributes_mask;
3390
3391         gtk_widget_set_realized (widget, TRUE);
3392
3393         gtk_widget_get_allocation (widget, &allocation);
3394
3395         attributes.window_type = GDK_WINDOW_CHILD;
3396         attributes.x = allocation.x;
3397         attributes.y = allocation.y;
3398         attributes.width = allocation.width;
3399         attributes.height = allocation.height;
3400         attributes.wclass = GDK_INPUT_OUTPUT;
3401         attributes.visual = gtk_widget_get_visual (widget);
3402         attributes.event_mask = gtk_widget_get_events (widget);
3403
3404         attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
3405
3406         window = gdk_window_new (gtk_widget_get_parent_window (widget),
3407                                  &attributes, attributes_mask);
3408         gtk_widget_set_window (widget, window);
3409         gdk_window_set_user_data (window, widget);
3410
3411         gtk_style_context_set_background (gtk_widget_get_style_context (widget),
3412                                           window);
3413 }
3414
3415 static gboolean
3416 ev_view_draw (GtkWidget *widget,
3417               cairo_t   *cr)
3418 {
3419         EvView      *view = EV_VIEW (widget);
3420         gint         i;
3421         GdkRectangle clip_rect;
3422
3423         if (view->loading) {
3424                 show_loading_window (view);
3425         } else if (view->loading_window &&
3426                    gtk_widget_get_visible (view->loading_window)) {
3427                 ev_view_loading_window_move (view);
3428         }
3429
3430         if (view->document == NULL)
3431                 return FALSE;
3432
3433         if (!gdk_cairo_get_clip_rectangle (cr, &clip_rect))
3434                 return FALSE;
3435
3436         for (i = view->start_page; i >= 0 && i <= view->end_page; i++) {
3437                 GdkRectangle page_area;
3438                 GtkBorder border;
3439                 gboolean page_ready = TRUE;
3440
3441                 if (!ev_view_get_page_extents (view, i, &page_area, &border))
3442                         continue;
3443
3444                 page_area.x -= view->scroll_x;
3445                 page_area.y -= view->scroll_y;
3446
3447                 draw_one_page (view, i, cr, &page_area, &border, &clip_rect, &page_ready);
3448
3449                 if (page_ready && view->find_pages && view->highlight_find_results)
3450                         highlight_find_results (view, cr, i);
3451                 if (page_ready && EV_IS_DOCUMENT_ANNOTATIONS (view->document))
3452                         show_annotation_windows (view, i);
3453                 if (page_ready && view->focus_annotation)
3454                         focus_annotation (view, cr, i, &clip_rect);
3455                 if (page_ready && view->synctex_result)
3456                         highlight_forward_search_results (view, cr, i);
3457         }
3458
3459         if (GTK_WIDGET_CLASS (ev_view_parent_class)->draw)
3460                 GTK_WIDGET_CLASS (ev_view_parent_class)->draw (widget, cr);
3461
3462         return FALSE;
3463 }
3464
3465 static gboolean
3466 ev_view_do_popup_menu (EvView *view,
3467                        gdouble x,
3468                        gdouble y)
3469 {
3470         GList        *items = NULL;
3471         EvLink       *link;
3472         EvImage      *image;
3473         EvAnnotation *annot;
3474
3475         image = ev_view_get_image_at_location (view, x, y);
3476         if (image)
3477                 items = g_list_prepend (items, image);
3478
3479         link = ev_view_get_link_at_location (view, x, y);
3480         if (link)
3481                 items = g_list_prepend (items, link);
3482
3483         annot = ev_view_get_annotation_at_location (view, x, y);
3484         if (annot)
3485                 items = g_list_prepend (items, annot);
3486
3487         g_signal_emit (view, signals[SIGNAL_POPUP_MENU], 0, items);
3488
3489         g_list_free (items);
3490
3491         return TRUE;
3492 }
3493
3494 static gboolean
3495 ev_view_popup_menu (GtkWidget *widget)
3496 {
3497         gint x, y;
3498         
3499         gtk_widget_get_pointer (widget, &x, &y);
3500         return ev_view_do_popup_menu (EV_VIEW (widget), x, y);
3501 }
3502
3503 static void
3504 get_link_area (EvView       *view,
3505                gint          x,
3506                gint          y,
3507                EvLink       *link,
3508                GdkRectangle *area)
3509 {
3510         EvMappingList *link_mapping;
3511         gint           page;
3512         gint           x_offset = 0, y_offset = 0;
3513
3514         x += view->scroll_x;
3515         y += view->scroll_y;
3516         
3517         find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
3518         
3519         link_mapping = ev_page_cache_get_link_mapping (view->page_cache, page);
3520         ev_view_get_area_from_mapping (view, page,
3521                                        link_mapping,
3522                                        link, area);
3523 }
3524
3525 static void
3526 get_annot_area (EvView       *view,
3527                gint          x,
3528                gint          y,
3529                EvAnnotation *annot,
3530                GdkRectangle *area)
3531 {
3532         EvMappingList *annot_mapping;
3533         gint           page;
3534         gint           x_offset = 0, y_offset = 0;
3535
3536         x += view->scroll_x;
3537         y += view->scroll_y;
3538
3539         find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
3540
3541         annot_mapping = ev_page_cache_get_annot_mapping (view->page_cache, page);
3542         ev_view_get_area_from_mapping (view, page,
3543                                        annot_mapping,
3544                                        annot, area);
3545 }
3546
3547 static gboolean
3548 ev_view_query_tooltip (GtkWidget  *widget,
3549                        gint        x,
3550                        gint        y,
3551                        gboolean    keyboard_tip,
3552                        GtkTooltip *tooltip)
3553 {
3554         EvView       *view = EV_VIEW (widget);
3555         EvLink       *link;
3556         EvAnnotation *annot;
3557         gchar        *text;
3558
3559         annot = ev_view_get_annotation_at_location (view, x, y);
3560         if (annot) {
3561                 const gchar *contents;
3562
3563                 if ((contents = ev_annotation_get_contents (annot))) {
3564                         GdkRectangle annot_area;
3565
3566                         get_annot_area (view, x, y, annot, &annot_area);
3567                         gtk_tooltip_set_text (tooltip, contents);
3568                         gtk_tooltip_set_tip_area (tooltip, &annot_area);
3569
3570                         return TRUE;
3571                 }
3572         }
3573
3574         link = ev_view_get_link_at_location (view, x, y);
3575         if (!link)
3576                 return FALSE;
3577
3578         text = tip_from_link (view, link);
3579         if (text && g_utf8_validate (text, -1, NULL)) {
3580                 GdkRectangle link_area;
3581
3582                 get_link_area (view, x, y, link, &link_area);
3583                 gtk_tooltip_set_text (tooltip, text);
3584                 gtk_tooltip_set_tip_area (tooltip, &link_area);
3585                 g_free (text);
3586
3587                 return TRUE;
3588         }
3589         g_free (text);
3590
3591         return FALSE;
3592 }
3593
3594 static void
3595 start_selection_for_event (EvView         *view,
3596                            GdkEventButton *event)
3597 {
3598         clear_selection (view);
3599
3600         view->selection_info.start.x = event->x + view->scroll_x;
3601         view->selection_info.start.y = event->y + view->scroll_y;
3602
3603         switch (event->type) {
3604                 case GDK_2BUTTON_PRESS:
3605                         view->selection_info.style = EV_SELECTION_STYLE_WORD;
3606                         break;
3607                 case GDK_3BUTTON_PRESS:
3608                         view->selection_info.style = EV_SELECTION_STYLE_LINE;
3609                         break;
3610                 default:
3611                         view->selection_info.style = EV_SELECTION_STYLE_GLYPH;
3612                         return;
3613         }
3614
3615         /* In case of WORD or LINE, compute selections now */
3616         compute_selections (view,
3617                             view->selection_info.style,
3618                             &(view->selection_info.start),
3619                             &(view->selection_info.start));
3620 }
3621
3622 static gboolean
3623 ev_view_button_press_event (GtkWidget      *widget,
3624                             GdkEventButton *event)
3625 {
3626         EvView *view = EV_VIEW (widget);
3627
3628         if (!view->document)
3629                 return FALSE;
3630         
3631         if (!gtk_widget_has_focus (widget)) {
3632                 gtk_widget_grab_focus (widget);
3633         }
3634
3635         if (view->window_child_focus) {
3636                 EvAnnotationWindow *window;
3637                 EvAnnotation       *annot;
3638
3639                 window = EV_ANNOTATION_WINDOW (view->window_child_focus->window);
3640                 annot = ev_annotation_window_get_annotation (window);
3641                 ev_annotation_window_ungrab_focus (window);
3642                 view->window_child_focus = NULL;
3643         }
3644         
3645         view->pressed_button = event->button;
3646         view->selection_info.in_drag = FALSE;
3647
3648         if (view->adding_annot)
3649                 return FALSE;
3650
3651         if (view->scroll_info.autoscrolling)
3652                 return TRUE;
3653         
3654         switch (event->button) {
3655                 case 1: {
3656                         EvImage *image;
3657                         EvAnnotation *annot;
3658                         EvFormField *field;
3659
3660                         if (event->state & GDK_CONTROL_MASK)
3661                                 return ev_view_synctex_backward_search (view, event->x , event->y);
3662
3663                         if (EV_IS_SELECTION (view->document) && view->selection_info.selections) {
3664                                 if (event->type == GDK_3BUTTON_PRESS) {
3665                                         start_selection_for_event (view, event);
3666                                 } else if (location_in_selected_text (view,
3667                                                                event->x + view->scroll_x,
3668                                                                event->y + view->scroll_y)) {
3669                                         view->selection_info.in_drag = TRUE;
3670                                 } else {
3671                                         start_selection_for_event (view, event);
3672                                 }
3673
3674                                 gtk_widget_queue_draw (widget);
3675                         } else if ((annot = ev_view_get_annotation_at_location (view, event->x, event->y))) {
3676                                 ev_view_handle_annotation (view, annot, event->x, event->y, event->time);
3677                         } else if ((field = ev_view_get_form_field_at_location (view, event->x, event->y))) {
3678                                 ev_view_remove_all (view);
3679                                 ev_view_handle_form_field (view, field, event->x, event->y);
3680                         } else if (!location_in_text (view, event->x + view->scroll_x, event->y + view->scroll_y) &&
3681                                    (image = ev_view_get_image_at_location (view, event->x, event->y))) {
3682                                 if (view->image_dnd_info.image)
3683                                         g_object_unref (view->image_dnd_info.image);
3684                                 view->image_dnd_info.image = g_object_ref (image);
3685                                 view->image_dnd_info.in_drag = TRUE;
3686
3687                                 view->image_dnd_info.start.x = event->x + view->scroll_x;
3688                                 view->image_dnd_info.start.y = event->y + view->scroll_y;
3689                         } else {
3690                                 ev_view_remove_all (view);
3691
3692                                 if (view->synctex_result) {
3693                                         g_free (view->synctex_result);
3694                                         view->synctex_result = NULL;
3695                                         gtk_widget_queue_draw (widget);
3696                                 }
3697
3698                                 if (view->focus_annotation)
3699                                         view->focus_annotation = NULL;
3700
3701                                 if (EV_IS_SELECTION (view->document))
3702                                         start_selection_for_event (view, event);
3703                         }
3704                 }                       
3705                         return TRUE;
3706                 case 2:
3707                         /* use root coordinates as reference point because
3708                          * scrolling changes window relative coordinates */
3709                         view->drag_info.start.x = event->x_root;
3710                         view->drag_info.start.y = event->y_root;
3711                         view->drag_info.hadj = gtk_adjustment_get_value (view->hadjustment);
3712                         view->drag_info.vadj = gtk_adjustment_get_value (view->vadjustment);
3713
3714                         ev_view_set_cursor (view, EV_VIEW_CURSOR_DRAG);
3715
3716                         return TRUE;
3717                 case 3:
3718                         view->scroll_info.start_y = event->y;
3719                         return ev_view_do_popup_menu (view, event->x, event->y);
3720         }
3721         
3722         return FALSE;
3723 }
3724
3725 static void
3726 ev_view_remove_all (EvView *view)
3727 {
3728         gtk_container_foreach (GTK_CONTAINER (view), (GtkCallback) gtk_widget_destroy, NULL);
3729 }
3730
3731 /*** Drag and Drop ***/
3732 static void
3733 ev_view_drag_data_get (GtkWidget        *widget,
3734                        GdkDragContext   *context,
3735                        GtkSelectionData *selection_data,
3736                        guint             info,
3737                        guint             time)
3738 {
3739         EvView *view = EV_VIEW (widget);
3740
3741         switch (info) {
3742                 case TARGET_DND_TEXT:
3743                         if (EV_IS_SELECTION (view->document) &&
3744                             view->selection_info.selections) {
3745                                 gchar *text;
3746
3747                                 text = get_selected_text (view);
3748                                 gtk_selection_data_set_text (selection_data,
3749                                                              text,
3750                                                              strlen (text));
3751                                 g_free (text);
3752                         }
3753                         break;
3754                 case TARGET_DND_IMAGE:
3755                         if (view->image_dnd_info.image) {
3756                                 GdkPixbuf *pixbuf;
3757
3758                                 ev_document_doc_mutex_lock ();
3759                                 pixbuf = ev_document_images_get_image (EV_DOCUMENT_IMAGES (view->document),
3760                                                                        view->image_dnd_info.image);
3761                                 ev_document_doc_mutex_unlock ();
3762                                 
3763                                 gtk_selection_data_set_pixbuf (selection_data, pixbuf);
3764                                 g_object_unref (pixbuf);
3765                         }
3766                         break;
3767                 case TARGET_DND_URI:
3768                         if (view->image_dnd_info.image) {
3769                                 GdkPixbuf   *pixbuf;
3770                                 const gchar *tmp_uri;
3771                                 gchar       *uris[2];
3772
3773                                 ev_document_doc_mutex_lock ();
3774                                 pixbuf = ev_document_images_get_image (EV_DOCUMENT_IMAGES (view->document),
3775                                                                        view->image_dnd_info.image);
3776                                 ev_document_doc_mutex_unlock ();
3777                                 
3778                                 tmp_uri = ev_image_save_tmp (view->image_dnd_info.image, pixbuf);
3779                                 g_object_unref (pixbuf);
3780
3781                                 uris[0] = (gchar *)tmp_uri;
3782                                 uris[1] = NULL;
3783                                 gtk_selection_data_set_uris (selection_data, uris);
3784                         }
3785         }
3786 }
3787
3788 static gboolean
3789 ev_view_drag_motion (GtkWidget      *widget,
3790                      GdkDragContext *context,
3791                      gint            x,
3792                      gint            y,
3793                      guint           time)
3794 {
3795         if (gtk_drag_get_source_widget (context) == widget)
3796                 gdk_drag_status (context, 0, time);
3797         else
3798                 gdk_drag_status (context, gdk_drag_context_get_suggested_action (context), time);
3799         
3800         return TRUE;
3801 }
3802                      
3803 static gboolean
3804 selection_update_idle_cb (EvView *view)
3805 {
3806         compute_selections (view,
3807                             view->selection_info.style,
3808                             &view->selection_info.start,
3809                             &view->motion);
3810         view->selection_update_id = 0;
3811         return FALSE;
3812 }
3813
3814 static gboolean
3815 selection_scroll_timeout_cb (EvView *view)
3816 {       
3817         gint x, y, shift = 0;
3818         GtkWidget *widget = GTK_WIDGET (view);
3819         GtkAllocation allocation;
3820
3821         gtk_widget_get_allocation (widget, &allocation);
3822         gtk_widget_get_pointer (widget, &x, &y);
3823
3824         if (y > allocation.height) {
3825                 shift = (y - allocation.height) / 2;
3826         } else if (y < 0) {
3827                 shift = y / 2;
3828         }
3829
3830         if (shift)
3831                 gtk_adjustment_set_value (view->vadjustment,
3832                                           CLAMP (gtk_adjustment_get_value (view->vadjustment) + shift,
3833                                                  gtk_adjustment_get_lower (view->vadjustment),
3834                                                  gtk_adjustment_get_upper (view->vadjustment) -
3835                                                  gtk_adjustment_get_page_size (view->vadjustment)));
3836
3837         if (x > allocation.width) {
3838                 shift = (x - allocation.width) / 2;
3839         } else if (x < 0) {
3840                 shift = x / 2;
3841         }
3842
3843         if (shift)
3844                 gtk_adjustment_set_value (view->hadjustment,
3845                                           CLAMP (gtk_adjustment_get_value (view->hadjustment) + shift,
3846                                                  gtk_adjustment_get_lower (view->hadjustment),
3847                                                  gtk_adjustment_get_upper (view->hadjustment) -
3848                                                  gtk_adjustment_get_page_size (view->hadjustment)));
3849
3850         return TRUE;
3851 }
3852
3853 static gboolean
3854 ev_view_drag_update_momentum (EvView *view)
3855 {
3856         int i;
3857         if (!view->drag_info.in_drag)
3858                 return FALSE;
3859         
3860         for (i = DRAG_HISTORY - 1; i > 0; i--) {
3861                 view->drag_info.buffer[i].x = view->drag_info.buffer[i-1].x;
3862                 view->drag_info.buffer[i].y = view->drag_info.buffer[i-1].y;
3863         }
3864
3865         /* Momentum is a moving average of 10ms granularity over
3866          * the last 100ms with each 10ms stored in buffer. 
3867          */
3868         
3869         view->drag_info.momentum.x = (view->drag_info.buffer[DRAG_HISTORY - 1].x - view->drag_info.buffer[0].x);
3870         view->drag_info.momentum.y = (view->drag_info.buffer[DRAG_HISTORY - 1].y - view->drag_info.buffer[0].y);
3871
3872         return TRUE;
3873 }
3874
3875 static gboolean
3876 ev_view_scroll_drag_release (EvView *view)
3877 {
3878         gdouble dhadj_value, dvadj_value;
3879         gdouble oldhadjustment, oldvadjustment;
3880         gdouble h_page_size, v_page_size;
3881         gdouble h_upper, v_upper;
3882         GtkAllocation allocation;
3883
3884         view->drag_info.momentum.x /= 1.2;
3885         view->drag_info.momentum.y /= 1.2; /* Alter these constants to change "friction" */
3886
3887         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
3888
3889         h_page_size = gtk_adjustment_get_page_size (view->hadjustment);
3890         v_page_size = gtk_adjustment_get_page_size (view->vadjustment);
3891
3892         dhadj_value = h_page_size *
3893                       (gdouble)view->drag_info.momentum.x / allocation.width;
3894         dvadj_value = v_page_size *
3895                       (gdouble)view->drag_info.momentum.y / allocation.height;
3896
3897         oldhadjustment = gtk_adjustment_get_value (view->hadjustment);
3898         oldvadjustment = gtk_adjustment_get_value (view->vadjustment);
3899
3900         h_upper = gtk_adjustment_get_upper (view->hadjustment);
3901         v_upper = gtk_adjustment_get_upper (view->vadjustment);
3902
3903         /* When we reach the edges, we need either to absorb some momentum and bounce by
3904          * multiplying it on -0.5 or stop scrolling by setting momentum to 0. */
3905         if (((oldhadjustment + dhadj_value) > (h_upper - h_page_size)) ||
3906             ((oldhadjustment + dhadj_value) < 0))
3907                 view->drag_info.momentum.x = 0;
3908         if (((oldvadjustment + dvadj_value) > (v_upper - v_page_size)) ||
3909             ((oldvadjustment + dvadj_value) < 0))
3910                 view->drag_info.momentum.y = 0;
3911
3912         gtk_adjustment_set_value (view->hadjustment,
3913                                   MIN (oldhadjustment + dhadj_value,
3914                                        h_upper - h_page_size));
3915         gtk_adjustment_set_value (view->vadjustment,
3916                                   MIN (oldvadjustment + dvadj_value,
3917                                        v_upper - v_page_size));
3918
3919         if (((view->drag_info.momentum.x < 1) && (view->drag_info.momentum.x > -1)) &&
3920             ((view->drag_info.momentum.y < 1) && (view->drag_info.momentum.y > -1)))
3921                 return FALSE;
3922         else
3923                 return TRUE;
3924 }
3925
3926 static gboolean
3927 ev_view_motion_notify_event (GtkWidget      *widget,
3928                              GdkEventMotion *event)
3929 {
3930         EvView    *view = EV_VIEW (widget);
3931         GdkWindow *window;
3932         gint       x, y;
3933
3934         if (!view->document)
3935                 return FALSE;
3936
3937         window = gtk_widget_get_window (widget);
3938
3939         if (event->is_hint || event->window != window) {
3940             gtk_widget_get_pointer (widget, &x, &y);
3941         } else {
3942             x = event->x;
3943             y = event->y;
3944         }
3945
3946         if (view->scroll_info.autoscrolling) {
3947                 view->scroll_info.last_y = y;
3948                 return TRUE;
3949         }
3950
3951         if (view->selection_info.in_drag) {
3952                 if (gtk_drag_check_threshold (widget,
3953                                               view->selection_info.start.x,
3954                                               view->selection_info.start.y,
3955                                               x, y)) {
3956                         GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
3957
3958                         gtk_target_list_add_text_targets (target_list, TARGET_DND_TEXT);
3959
3960                         gtk_drag_begin (widget, target_list,
3961                                         GDK_ACTION_COPY,
3962                                         1, (GdkEvent *)event);
3963
3964                         view->selection_info.in_drag = FALSE;
3965
3966                         gtk_target_list_unref (target_list);
3967
3968                         return TRUE;
3969                 }
3970         } else if (view->image_dnd_info.in_drag) {
3971                 if (gtk_drag_check_threshold (widget,
3972                                               view->selection_info.start.x,
3973                                               view->selection_info.start.y,
3974                                               x, y)) {
3975                         GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
3976
3977                         gtk_target_list_add_uri_targets (target_list, TARGET_DND_URI);
3978                         gtk_target_list_add_image_targets (target_list, TARGET_DND_IMAGE, TRUE);
3979
3980                         gtk_drag_begin (widget, target_list,
3981                                         GDK_ACTION_COPY,
3982                                         1, (GdkEvent *)event);
3983
3984                         view->image_dnd_info.in_drag = FALSE;
3985
3986                         gtk_target_list_unref (target_list);
3987
3988                         return TRUE;
3989                 }
3990         }
3991         
3992         switch (view->pressed_button) {
3993         case 1:
3994                 /* For the Evince 0.4.x release, we limit selection to un-rotated
3995                  * documents only.
3996                  */
3997                 if (view->rotation != 0)
3998                         return FALSE;
3999
4000                 /* Schedule timeout to scroll during selection and additionally 
4001                  * scroll once to allow arbitrary speed. */
4002                 if (!view->selection_scroll_id)
4003                     view->selection_scroll_id = g_timeout_add (SCROLL_TIME,
4004                                                                (GSourceFunc)selection_scroll_timeout_cb,
4005                                                                view);
4006                 else 
4007                     selection_scroll_timeout_cb (view);
4008
4009                 view->selection_info.in_selection = TRUE;
4010                 view->motion.x = x + view->scroll_x;
4011                 view->motion.y = y + view->scroll_y;
4012
4013                 /* Queue an idle to handle the motion.  We do this because      
4014                  * handling any selection events in the motion could be slower  
4015                  * than new motion events reach us.  We always put it in the    
4016                  * idle to make sure we catch up and don't visibly lag the      
4017                  * mouse. */
4018                 if (!view->selection_update_id)
4019                         view->selection_update_id = g_idle_add ((GSourceFunc)selection_update_idle_cb, view);
4020
4021                 return TRUE;
4022         case 2:
4023                 if (!view->drag_info.in_drag) {
4024                         gboolean start;
4025                         int i;
4026
4027                         start = gtk_drag_check_threshold (widget,
4028                                                           view->drag_info.start.x,
4029                                                           view->drag_info.start.y,
4030                                                           event->x_root,
4031                                                           event->y_root);
4032                         view->drag_info.in_drag = start;
4033                         view->drag_info.drag_timeout_id = g_timeout_add (10,
4034                                 (GSourceFunc)ev_view_drag_update_momentum, view);
4035                         /* Set 100 to choose how long it takes to build up momentum */
4036                         /* Clear out previous momentum info: */
4037                         for (i = 0; i < DRAG_HISTORY; i++) {
4038                                 view->drag_info.buffer[i].x = event->x;
4039                                 view->drag_info.buffer[i].y = event->y;
4040                         }
4041                         view->drag_info.momentum.x = 0;
4042                         view->drag_info.momentum.y = 0;
4043                 }
4044
4045                 if (view->drag_info.in_drag) {
4046                         int dx, dy;
4047                         gdouble dhadj_value, dvadj_value;
4048                         GtkAllocation allocation;
4049
4050                         view->drag_info.buffer[0].x = event->x;
4051                         view->drag_info.buffer[0].y = event->y;
4052
4053                         dx = event->x_root - view->drag_info.start.x;
4054                         dy = event->y_root - view->drag_info.start.y;
4055
4056                         gtk_widget_get_allocation (widget, &allocation);
4057
4058                         dhadj_value = gtk_adjustment_get_page_size (view->hadjustment) *
4059                                       (gdouble)dx / allocation.width;
4060                         dvadj_value = gtk_adjustment_get_page_size (view->vadjustment) *
4061                                       (gdouble)dy / allocation.height;
4062
4063                         /* clamp scrolling to visible area */
4064                         gtk_adjustment_set_value (view->hadjustment,
4065                                                   MIN (view->drag_info.hadj - dhadj_value,
4066                                                        gtk_adjustment_get_upper (view->hadjustment) -
4067                                                        gtk_adjustment_get_page_size (view->hadjustment)));
4068                         gtk_adjustment_set_value (view->vadjustment,
4069                                                   MIN (view->drag_info.vadj - dvadj_value,
4070                                                        gtk_adjustment_get_upper (view->vadjustment) -
4071                                                        gtk_adjustment_get_page_size (view->vadjustment)));
4072
4073                         return TRUE;
4074                 }
4075
4076                 break;
4077         default:
4078                 ev_view_handle_cursor_over_xy (view, x, y);
4079         } 
4080
4081         return FALSE;
4082 }
4083
4084 static gboolean
4085 ev_view_button_release_event (GtkWidget      *widget,
4086                               GdkEventButton *event)
4087 {
4088         EvView *view = EV_VIEW (widget);
4089         EvLink *link = NULL;
4090
4091         view->image_dnd_info.in_drag = FALSE;
4092
4093         if (view->scroll_info.autoscrolling) {
4094                 ev_view_autoscroll_stop (view);
4095                 view->pressed_button = -1;
4096
4097                 return TRUE;
4098         }
4099
4100         if (view->pressed_button == 1 && event->state & GDK_CONTROL_MASK) {
4101                 view->pressed_button = -1;
4102                 return TRUE;
4103         }
4104
4105         if (view->drag_info.in_drag) {
4106                 view->drag_info.release_timeout_id =
4107                         g_timeout_add (20,
4108                                        (GSourceFunc)ev_view_scroll_drag_release, view);
4109         }
4110
4111         if (view->document && !view->drag_info.in_drag && view->pressed_button != 3) {
4112                 link = ev_view_get_link_at_location (view, event->x, event->y);
4113         }
4114
4115         view->drag_info.in_drag = FALSE;
4116
4117         if (view->adding_annot && view->pressed_button == 1) {
4118                 view->adding_annot = FALSE;
4119                 ev_view_handle_cursor_over_xy (view, event->x, event->y);
4120                 view->pressed_button = -1;
4121
4122                 ev_view_create_annotation (view,
4123                                            view->adding_annot_type,
4124                                            event->x + view->scroll_x,
4125                                            event->y + view->scroll_y);
4126
4127                 return FALSE;
4128         }
4129
4130         if (view->pressed_button == 2) {
4131                 ev_view_handle_cursor_over_xy (view, event->x, event->y);
4132         }
4133
4134         view->pressed_button = -1;
4135
4136         if (view->selection_scroll_id) {
4137             g_source_remove (view->selection_scroll_id);
4138             view->selection_scroll_id = 0;
4139         }
4140         if (view->selection_update_id) {
4141             g_source_remove (view->selection_update_id);
4142             view->selection_update_id = 0;
4143         }
4144
4145         if (view->selection_info.selections) {
4146                 clear_link_selected (view);
4147                 ev_view_update_primary_selection (view);
4148                 
4149                 if (view->selection_info.in_drag) {
4150                         clear_selection (view);
4151                         gtk_widget_queue_draw (widget);
4152                 }
4153                 
4154                 view->selection_info.in_drag = FALSE;
4155         } else if (link) {
4156                 if (event->button == 2) {
4157                         EvLinkAction    *action;
4158                         EvLinkActionType type;
4159
4160                         action = ev_link_get_action (link);
4161                         if (!action)
4162                                 return FALSE;
4163
4164                         type = ev_link_action_get_action_type (action);
4165                         if (type == EV_LINK_ACTION_TYPE_GOTO_DEST) {
4166                                 g_signal_emit (view,
4167                                                signals[SIGNAL_EXTERNAL_LINK],
4168                                                0, action);
4169                         }
4170                 } else {
4171                         ev_view_handle_link (view, link);
4172                 }
4173         }
4174
4175         return FALSE;
4176 }
4177
4178 static gboolean
4179 ev_view_key_press_event (GtkWidget   *widget,
4180                          GdkEventKey *event)
4181 {
4182         EvView *view = EV_VIEW (widget);
4183
4184         if (!view->document)
4185                 return FALSE;
4186
4187         if (!gtk_widget_has_focus (widget)) {
4188                 /* Forward key events to current focused window child */
4189                 if (view->window_child_focus) {
4190                         GdkEventKey *new_event;
4191                         gboolean     handled;
4192
4193                         new_event = (GdkEventKey *) gdk_event_copy ((GdkEvent *)event);
4194                         g_object_unref (new_event->window);
4195                         new_event->window = gtk_widget_get_window (view->window_child_focus->window);
4196                         if (new_event->window)
4197                                 g_object_ref (new_event->window);
4198                         gtk_widget_realize (view->window_child_focus->window);
4199                         handled = gtk_widget_event (view->window_child_focus->window, (GdkEvent *)new_event);
4200                         gdk_event_free ((GdkEvent *)new_event);
4201
4202                         return handled;
4203                 }
4204
4205                 return FALSE;
4206         }
4207
4208         return gtk_bindings_activate_event (G_OBJECT (widget), event);
4209 }
4210
4211 static gint
4212 ev_view_focus_in (GtkWidget     *widget,
4213                   GdkEventFocus *event)
4214 {
4215         if (EV_VIEW (widget)->pixbuf_cache)
4216                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
4217         gtk_widget_queue_draw (widget);
4218
4219         return FALSE;
4220 }
4221
4222 static gint
4223 ev_view_focus_out (GtkWidget     *widget,
4224                    GdkEventFocus *event)
4225 {
4226         if (EV_VIEW (widget)->pixbuf_cache)
4227                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
4228         gtk_widget_queue_draw (widget);
4229
4230         return FALSE;
4231 }
4232
4233 static gboolean
4234 ev_view_leave_notify_event (GtkWidget *widget, GdkEventCrossing   *event)
4235 {
4236         EvView *view = EV_VIEW (widget);
4237
4238         if (view->cursor != EV_VIEW_CURSOR_NORMAL)
4239                 ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
4240
4241         return FALSE;
4242 }
4243
4244 static gboolean
4245 ev_view_enter_notify_event (GtkWidget *widget, GdkEventCrossing   *event)
4246 {
4247         EvView *view = EV_VIEW (widget);
4248
4249         ev_view_handle_cursor_over_xy (view, event->x, event->y);
4250     
4251         return FALSE;
4252 }
4253
4254 static void
4255 ev_view_style_updated (GtkWidget *widget)
4256 {
4257         if (EV_VIEW (widget)->pixbuf_cache)
4258                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
4259
4260         GTK_WIDGET_CLASS (ev_view_parent_class)->style_updated (widget);
4261 }
4262
4263 /*** Drawing ***/
4264
4265 static void
4266 draw_rubberband (EvView             *view,
4267                  cairo_t            *cr,
4268                  const GdkRectangle *rect,
4269                  gdouble             alpha)
4270 {
4271         GtkStyleContext *context;
4272         GdkRGBA          color;
4273
4274         context = gtk_widget_get_style_context (GTK_WIDGET (view));
4275         gtk_style_context_get_background_color (context, GTK_STATE_FLAG_SELECTED, &color);
4276         cairo_save (cr);
4277
4278         cairo_set_source_rgba (cr, color.red, color.green, color.blue, alpha);
4279         cairo_rectangle (cr,
4280                          rect->x - view->scroll_x,
4281                          rect->y - view->scroll_y,
4282                          rect->width, rect->height);
4283         cairo_fill_preserve (cr);
4284
4285         cairo_set_line_width (cr, 0.5);
4286         cairo_set_source_rgb (cr, color.red, color.green, color.blue);
4287         cairo_stroke (cr);
4288
4289         cairo_restore (cr);
4290 }
4291
4292
4293 static void
4294 highlight_find_results (EvView *view,
4295                         cairo_t *cr,
4296                         int page)
4297 {
4298         gint       i, n_results = 0;
4299         n_results = ev_view_find_get_n_results (view, page);
4300
4301         for (i = 0; i < n_results; i++) {
4302                 EvRectangle *rectangle;
4303                 GdkRectangle view_rectangle;
4304                 gdouble      alpha;
4305
4306                 if (i == view->find_result && page == view->current_page) {
4307                         alpha = 0.6;
4308                 } else {
4309                         alpha = 0.3;
4310                 }
4311
4312                 rectangle = ev_view_find_get_result (view, page, i);
4313                 doc_rect_to_view_rect (view, page, rectangle, &view_rectangle);
4314                 draw_rubberband (view, cr, &view_rectangle, alpha);
4315         }
4316 }
4317
4318 static void
4319 highlight_forward_search_results (EvView *view,
4320                                   cairo_t *cr,
4321                                   int page)
4322 {
4323         GdkRectangle rect;
4324         EvMapping   *mapping = view->synctex_result;
4325
4326         if (GPOINTER_TO_INT (mapping->data) != page)
4327                 return;
4328
4329         doc_rect_to_view_rect (view, page, &mapping->area, &rect);
4330
4331         cairo_save (cr);
4332         cairo_set_source_rgb (cr, 1., 0., 0.);
4333         cairo_rectangle (cr,
4334                          rect.x - view->scroll_x,
4335                          rect.y - view->scroll_y,
4336                          rect.width, rect.height);
4337         cairo_stroke (cr);
4338         cairo_restore (cr);
4339 }
4340
4341 static void
4342 focus_annotation (EvView       *view,
4343                   cairo_t      *cr,
4344                   gint          page,
4345                   GdkRectangle *clip)
4346 {
4347         GtkWidget    *widget = GTK_WIDGET (view);
4348         GdkRectangle  rect;
4349         EvMapping    *mapping = view->focus_annotation;
4350         EvAnnotation *annot = (EvAnnotation *)mapping->data;
4351
4352         if (ev_annotation_get_page_index (annot) != page)
4353                 return;
4354
4355         doc_rect_to_view_rect (view, page, &mapping->area, &rect);
4356
4357         gtk_render_focus (gtk_widget_get_style_context (widget),
4358                           cr,
4359                           rect.x - view->scroll_x,
4360                           rect.y - view->scroll_y,
4361                           rect.width + 1, rect.height + 1);
4362 }
4363
4364 static void
4365 ev_view_loading_window_move (EvView *view)
4366 {
4367         GtkWidget       *widget = GTK_WIDGET (view);
4368         EvLoadingWindow *window = EV_LOADING_WINDOW (view->loading_window);
4369         gint             root_x, root_y;
4370         gint             window_width;
4371         GtkAllocation    allocation;
4372
4373         gtk_widget_get_allocation (widget, &allocation);
4374         gdk_window_get_origin (gtk_widget_get_window (widget), &root_x, &root_y);
4375         ev_loading_window_get_size (window, &window_width, NULL);
4376
4377         root_x += allocation.width - window_width - 10;
4378         root_y += 10;
4379
4380         ev_loading_window_move (window, root_x, root_y);
4381 }
4382
4383 static gboolean
4384 show_loading_window_cb (EvView *view)
4385 {
4386         if (!view->loading_window) {
4387                 GtkWindow *parent;
4388                 GdkScreen *screen;
4389
4390                 parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view)));
4391                 view->loading_window = ev_loading_window_new (parent);
4392
4393                 /* Show the window off screen to get a valid size asap */
4394                 screen = gtk_widget_get_screen (GTK_WIDGET (view));
4395                 gtk_window_move (GTK_WINDOW (view->loading_window),
4396                                  gdk_screen_get_width (screen) + 1,
4397                                  gdk_screen_get_height (screen) + 1);
4398                 gtk_widget_show (view->loading_window);
4399         }
4400
4401         ev_view_loading_window_move (view);
4402
4403         gtk_widget_show (view->loading_window);
4404
4405         view->loading_timeout = 0;
4406
4407         return FALSE;
4408 }
4409
4410 static void
4411 show_loading_window (EvView *view)
4412 {
4413         if (view->loading_window && gtk_widget_get_visible (view->loading_window)) {
4414                 ev_view_loading_window_move (view);
4415                 return;
4416         }
4417
4418         if (!view->loading_timeout) {
4419                 view->loading_timeout =
4420                         g_timeout_add_full (G_PRIORITY_LOW,
4421                                             0.5, (GSourceFunc)show_loading_window_cb,
4422                                             view, NULL);
4423         }
4424 }
4425
4426 static void
4427 hide_loading_window (EvView *view)
4428 {
4429         if (view->loading_timeout) {
4430                 g_source_remove (view->loading_timeout);
4431                 view->loading_timeout = 0;
4432         }
4433
4434         if (view->loading_window && gtk_widget_get_visible (view->loading_window)) {
4435                 gtk_widget_hide (view->loading_window);
4436         }
4437 }
4438
4439 static void
4440 draw_one_page (EvView       *view,
4441                gint          page,
4442                cairo_t      *cr,
4443                GdkRectangle *page_area,
4444                GtkBorder    *border,
4445                GdkRectangle *expose_area,
4446                gboolean     *page_ready)
4447 {
4448         GdkRectangle overlap;
4449         GdkRectangle real_page_area;
4450         gint         current_page;
4451         gboolean     inverted_colors;
4452
4453         g_assert (view->document);
4454
4455         if (! gdk_rectangle_intersect (page_area, expose_area, &overlap))
4456                 return;
4457
4458         /* Render the document itself */
4459         real_page_area = *page_area;
4460
4461         real_page_area.x += border->left;
4462         real_page_area.y += border->top;
4463         real_page_area.width -= (border->left + border->right);
4464         real_page_area.height -= (border->top + border->bottom);
4465         *page_ready = TRUE;
4466
4467         current_page = ev_document_model_get_page (view->model);
4468         inverted_colors = ev_document_model_get_inverted_colors (view->model);
4469         ev_document_misc_paint_one_page (cr,
4470                                          GTK_WIDGET (view),
4471                                          page_area, border,
4472                                          page == current_page,
4473                                          inverted_colors);
4474
4475         if (gdk_rectangle_intersect (&real_page_area, expose_area, &overlap)) {
4476                 gint             width, height;
4477                 gint             page_width, page_height;
4478                 cairo_surface_t *page_surface = NULL;
4479                 gint             selection_width, selection_height;
4480                 cairo_surface_t *selection_surface = NULL;
4481
4482                 page_surface = ev_pixbuf_cache_get_surface (view->pixbuf_cache, page);
4483
4484                 if (!page_surface) {
4485                         if (page == current_page)
4486                                 show_loading_window (view);
4487
4488                         *page_ready = FALSE;
4489
4490                         return;
4491                 }
4492
4493                 if (page == current_page)
4494                         hide_loading_window (view);
4495
4496                 ev_view_get_page_size (view, page, &width, &height);
4497
4498                 page_width = cairo_image_surface_get_width (page_surface);
4499                 page_height = cairo_image_surface_get_height (page_surface);
4500
4501                 cairo_save (cr);
4502                 cairo_translate (cr, overlap.x, overlap.y);
4503
4504                 if (width != page_width || height != page_height) {
4505                         cairo_pattern_set_filter (cairo_get_source (cr),
4506                                                   CAIRO_FILTER_FAST);
4507                         cairo_scale (cr,
4508                                      (gdouble)width / page_width,
4509                                      (gdouble)height / page_height);
4510                 }
4511
4512                 cairo_surface_set_device_offset (page_surface,
4513                                                  overlap.x - real_page_area.x,
4514                                                  overlap.y - real_page_area.y);
4515                 cairo_set_source_surface (cr, page_surface, 0, 0);
4516                 cairo_paint (cr);
4517                 cairo_restore (cr);
4518                 
4519                 /* Get the selection pixbuf iff we have something to draw */
4520                 if (find_selection_for_page (view, page) &&
4521                     view->selection_mode == EV_VIEW_SELECTION_TEXT) {
4522                         selection_surface =
4523                                 ev_pixbuf_cache_get_selection_surface (view->pixbuf_cache,
4524                                                                        page,
4525                                                                        view->scale,
4526                                                                        NULL);
4527                 }
4528
4529                 if (!selection_surface) {
4530                         return;
4531                 }
4532
4533                 selection_width = cairo_image_surface_get_width (selection_surface);
4534                 selection_height = cairo_image_surface_get_height (selection_surface);
4535
4536                 cairo_save (cr);
4537                 cairo_translate (cr, overlap.x, overlap.y);
4538
4539                 if (width != selection_width || height != selection_height) {
4540                         cairo_pattern_set_filter (cairo_get_source (cr),
4541                                                   CAIRO_FILTER_FAST);
4542                         cairo_scale (cr,
4543                                      (gdouble)width / selection_width,
4544                                      (gdouble)height / selection_height);
4545                 }
4546
4547                 cairo_surface_set_device_offset (selection_surface,
4548                                                  overlap.x - real_page_area.x,
4549                                                  overlap.y - real_page_area.y);
4550
4551                 cairo_set_source_surface (cr, selection_surface, 0, 0);
4552                 cairo_paint (cr);
4553                 cairo_restore (cr);
4554         }
4555 }
4556
4557 /*** GObject functions ***/
4558
4559 static void
4560 ev_view_finalize (GObject *object)
4561 {
4562         EvView *view = EV_VIEW (object);
4563
4564         clear_selection (view);
4565         clear_link_selected (view);
4566
4567         if (view->synctex_result) {
4568                 g_free (view->synctex_result);
4569                 view->synctex_result = NULL;
4570         }
4571
4572         if (view->image_dnd_info.image)
4573                 g_object_unref (view->image_dnd_info.image);
4574         view->image_dnd_info.image = NULL;
4575
4576         G_OBJECT_CLASS (ev_view_parent_class)->finalize (object);
4577 }
4578
4579 static void
4580 ev_view_dispose (GObject *object)
4581 {
4582         EvView *view = EV_VIEW (object);
4583
4584         if (view->model) {
4585                 g_object_unref (view->model);
4586                 view->model = NULL;
4587         }
4588
4589         if (view->pixbuf_cache) {
4590                 g_object_unref (view->pixbuf_cache);
4591                 view->pixbuf_cache = NULL;
4592         }
4593
4594         if (view->document) {
4595                 g_object_unref (view->document);
4596                 view->document = NULL;
4597         }
4598
4599         if (view->page_cache) {
4600                 g_object_unref (view->page_cache);
4601                 view->page_cache = NULL;
4602         }
4603
4604         ev_view_window_children_free (view);
4605
4606         if (view->selection_scroll_id) {
4607             g_source_remove (view->selection_scroll_id);
4608             view->selection_scroll_id = 0;
4609         }
4610
4611         if (view->selection_update_id) {
4612             g_source_remove (view->selection_update_id);
4613             view->selection_update_id = 0;
4614         }
4615
4616         if (view->scroll_info.timeout_id) {
4617             g_source_remove (view->scroll_info.timeout_id);
4618             view->scroll_info.timeout_id = 0;
4619         }
4620
4621         if (view->drag_info.drag_timeout_id) {
4622                 g_source_remove (view->drag_info.drag_timeout_id);
4623                 view->drag_info.drag_timeout_id = 0;
4624         }
4625
4626         if (view->drag_info.release_timeout_id) {
4627                 g_source_remove (view->drag_info.release_timeout_id);
4628                 view->drag_info.release_timeout_id = 0;
4629         }
4630
4631         if (view->loading_timeout) {
4632                 g_source_remove (view->loading_timeout);
4633                 view->loading_timeout = 0;
4634         }
4635
4636         gtk_scrollable_set_hadjustment (GTK_SCROLLABLE (view), NULL);
4637         gtk_scrollable_set_vadjustment (GTK_SCROLLABLE (view), NULL);
4638
4639         G_OBJECT_CLASS (ev_view_parent_class)->dispose (object);
4640 }
4641
4642 static void
4643 ev_view_get_property (GObject     *object,
4644                       guint        prop_id,
4645                       GValue      *value,
4646                       GParamSpec  *pspec)
4647 {
4648         EvView *view = EV_VIEW (object);
4649
4650         switch (prop_id) {
4651         case PROP_HADJUSTMENT:
4652                 g_value_set_object (value, view->hadjustment);
4653                 break;
4654         case PROP_VADJUSTMENT:
4655                 g_value_set_object (value, view->vadjustment);
4656                 break;
4657         case PROP_HSCROLL_POLICY:
4658                 g_value_set_enum (value, view->hscroll_policy);
4659                 break;
4660         case PROP_VSCROLL_POLICY:
4661                 g_value_set_enum (value, view->vscroll_policy);
4662                 break;
4663         default:
4664                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4665                 break;
4666         }
4667 }
4668
4669 static void
4670 ev_view_set_property (GObject      *object,
4671                       guint         prop_id,
4672                       const GValue *value,
4673                       GParamSpec   *pspec)
4674 {
4675         EvView *view = EV_VIEW (object);
4676
4677         switch (prop_id) {
4678         case PROP_HADJUSTMENT:
4679                 ev_view_set_scroll_adjustment (view, GTK_ORIENTATION_HORIZONTAL,
4680                                                (GtkAdjustment *) g_value_get_object (value));
4681                 break;
4682         case PROP_VADJUSTMENT:
4683                 ev_view_set_scroll_adjustment (view, GTK_ORIENTATION_VERTICAL,
4684                                                (GtkAdjustment *) g_value_get_object (value));
4685                 break;
4686         case PROP_HSCROLL_POLICY:
4687                 view->hscroll_policy = g_value_get_enum (value);
4688                 gtk_widget_queue_resize (GTK_WIDGET (view));
4689                 break;
4690         case PROP_VSCROLL_POLICY:
4691                 view->vscroll_policy = g_value_get_enum (value);
4692                 gtk_widget_queue_resize (GTK_WIDGET (view));
4693                 break;
4694         default:
4695                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
4696                 break;
4697         }
4698 }
4699
4700 /* Accessibility */
4701 static void
4702 ev_view_init_accessibility (EvView *view)
4703 {
4704         static gboolean first_time = TRUE;
4705
4706         if (first_time) {
4707                 AtkObjectFactory *factory;
4708                 AtkRegistry *registry;
4709                 GType derived_type;
4710                 GType derived_atk_type;
4711
4712                 /*
4713                  * Figure out whether accessibility is enabled by looking at the
4714                  * type of the accessible object which would be created for
4715                  * the parent type of EvView.
4716                  */
4717                 derived_type = g_type_parent (EV_TYPE_VIEW);
4718
4719                 registry = atk_get_default_registry ();
4720                 factory = atk_registry_get_factory (registry,
4721                                                     derived_type);
4722                 derived_atk_type = atk_object_factory_get_accessible_type (factory);
4723                 if (g_type_is_a (derived_atk_type, GTK_TYPE_ACCESSIBLE)) {
4724                         atk_registry_set_factory_type (registry,
4725                                                        EV_TYPE_VIEW,
4726                                                        ev_view_accessible_factory_get_type ());
4727                         view->a11y_enabled = TRUE;
4728                 }
4729                 first_time = FALSE;
4730         }
4731 }
4732
4733 static AtkObject *
4734 ev_view_get_accessible (GtkWidget *widget)
4735 {
4736         ev_view_init_accessibility (EV_VIEW (widget));
4737         return GTK_WIDGET_CLASS (ev_view_parent_class)->get_accessible (widget);
4738 }
4739
4740 static gboolean
4741 ev_view_is_a11y_enabled (EvView *view)
4742 {
4743         ev_view_init_accessibility (view);
4744         return view->a11y_enabled;
4745 }
4746
4747 /* GtkContainer */
4748 static void
4749 ev_view_remove (GtkContainer *container,
4750                 GtkWidget    *widget)
4751 {
4752         EvView *view = EV_VIEW (container);
4753         GList *tmp_list = view->children;
4754         EvViewChild *child;
4755
4756         while (tmp_list) {
4757                 child = tmp_list->data;
4758
4759                 if (child->widget == widget) {
4760                         gtk_widget_unparent (widget);
4761
4762                         view->children = g_list_remove_link (view->children, tmp_list);
4763                         g_list_free_1 (tmp_list);
4764                         g_slice_free (EvViewChild, child);
4765
4766                         return;
4767                 }
4768
4769                 tmp_list = tmp_list->next;
4770         }
4771 }
4772
4773 static void
4774 ev_view_forall (GtkContainer *container,
4775                 gboolean      include_internals,
4776                 GtkCallback   callback,
4777                 gpointer      callback_data)
4778 {
4779         EvView *view = EV_VIEW (container);
4780         GList *tmp_list = view->children;
4781         EvViewChild *child;
4782
4783         while (tmp_list) {
4784                 child = tmp_list->data;
4785                 tmp_list = tmp_list->next;
4786
4787                 (* callback) (child->widget, callback_data);
4788         }
4789 }
4790
4791 static void
4792 ev_view_class_init (EvViewClass *class)
4793 {
4794         GObjectClass *object_class = G_OBJECT_CLASS (class);
4795         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
4796         GtkContainerClass *container_class = GTK_CONTAINER_CLASS (class);
4797         GtkBindingSet *binding_set;
4798
4799         object_class->get_property = ev_view_get_property;
4800         object_class->set_property = ev_view_set_property;
4801         object_class->dispose = ev_view_dispose;
4802         object_class->finalize = ev_view_finalize;
4803
4804         widget_class->realize = ev_view_realize;
4805         widget_class->draw = ev_view_draw;
4806         widget_class->button_press_event = ev_view_button_press_event;
4807         widget_class->motion_notify_event = ev_view_motion_notify_event;
4808         widget_class->button_release_event = ev_view_button_release_event;
4809         widget_class->key_press_event = ev_view_key_press_event;
4810         widget_class->focus_in_event = ev_view_focus_in;
4811         widget_class->focus_out_event = ev_view_focus_out;
4812         widget_class->get_accessible = ev_view_get_accessible;
4813         widget_class->get_preferred_width = ev_view_get_preferred_width;
4814         widget_class->get_preferred_height = ev_view_get_preferred_height;
4815         widget_class->size_allocate = ev_view_size_allocate;
4816         widget_class->scroll_event = ev_view_scroll_event;
4817         widget_class->enter_notify_event = ev_view_enter_notify_event;
4818         widget_class->leave_notify_event = ev_view_leave_notify_event;
4819         widget_class->style_updated = ev_view_style_updated;
4820         widget_class->drag_data_get = ev_view_drag_data_get;
4821         widget_class->drag_motion = ev_view_drag_motion;
4822         widget_class->popup_menu = ev_view_popup_menu;
4823         widget_class->query_tooltip = ev_view_query_tooltip;
4824
4825         container_class->remove = ev_view_remove;
4826         container_class->forall = ev_view_forall;
4827
4828         class->binding_activated = ev_view_scroll;
4829
4830         /* Scrollable interface */
4831         g_object_class_override_property (object_class, PROP_HADJUSTMENT, "hadjustment");
4832         g_object_class_override_property (object_class, PROP_VADJUSTMENT, "vadjustment");
4833         g_object_class_override_property (object_class, PROP_HSCROLL_POLICY, "hscroll-policy");
4834         g_object_class_override_property (object_class, PROP_VSCROLL_POLICY, "vscroll-policy");
4835
4836         signals[SIGNAL_BINDING_ACTIVATED] = g_signal_new ("binding_activated",
4837                          G_TYPE_FROM_CLASS (object_class),
4838                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4839                          G_STRUCT_OFFSET (EvViewClass, binding_activated),
4840                          NULL, NULL,
4841                          ev_view_marshal_VOID__ENUM_BOOLEAN,
4842                          G_TYPE_NONE, 2,
4843                          GTK_TYPE_SCROLL_TYPE,
4844                          G_TYPE_BOOLEAN);
4845         signals[SIGNAL_HANDLE_LINK] = g_signal_new ("handle-link",
4846                          G_TYPE_FROM_CLASS (object_class),
4847                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4848                          G_STRUCT_OFFSET (EvViewClass, handle_link),
4849                          NULL, NULL,
4850                          g_cclosure_marshal_VOID__OBJECT,
4851                          G_TYPE_NONE, 1,
4852                          G_TYPE_OBJECT);
4853         signals[SIGNAL_EXTERNAL_LINK] = g_signal_new ("external-link",
4854                          G_TYPE_FROM_CLASS (object_class),
4855                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4856                          G_STRUCT_OFFSET (EvViewClass, external_link),
4857                          NULL, NULL,
4858                          g_cclosure_marshal_VOID__OBJECT,
4859                          G_TYPE_NONE, 1,
4860                          G_TYPE_OBJECT);
4861         signals[SIGNAL_POPUP_MENU] = g_signal_new ("popup",
4862                          G_TYPE_FROM_CLASS (object_class),
4863                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4864                          G_STRUCT_OFFSET (EvViewClass, popup_menu),
4865                          NULL, NULL,
4866                          g_cclosure_marshal_VOID__POINTER,
4867                          G_TYPE_NONE, 1,
4868                          G_TYPE_POINTER);
4869         signals[SIGNAL_SELECTION_CHANGED] = g_signal_new ("selection-changed",
4870                          G_TYPE_FROM_CLASS (object_class),
4871                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4872                          G_STRUCT_OFFSET (EvViewClass, selection_changed),
4873                          NULL, NULL,
4874                          g_cclosure_marshal_VOID__VOID,
4875                          G_TYPE_NONE, 0,
4876                          G_TYPE_NONE);
4877         signals[SIGNAL_SYNC_SOURCE] = g_signal_new ("sync-source",
4878                          G_TYPE_FROM_CLASS (object_class),
4879                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4880                          G_STRUCT_OFFSET (EvViewClass, sync_source),
4881                          NULL, NULL,
4882                          g_cclosure_marshal_VOID__POINTER,
4883                          G_TYPE_NONE, 1,
4884                          G_TYPE_POINTER);
4885         signals[SIGNAL_ANNOT_ADDED] = g_signal_new ("annot-added",
4886                          G_TYPE_FROM_CLASS (object_class),
4887                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4888                          G_STRUCT_OFFSET (EvViewClass, annot_added),
4889                          NULL, NULL,
4890                          g_cclosure_marshal_VOID__OBJECT,
4891                          G_TYPE_NONE, 1,
4892                          EV_TYPE_ANNOTATION);
4893         signals[SIGNAL_LAYERS_CHANGED] = g_signal_new ("layers-changed",
4894                          G_TYPE_FROM_CLASS (object_class),
4895                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4896                          G_STRUCT_OFFSET (EvViewClass, layers_changed),
4897                          NULL, NULL,
4898                          g_cclosure_marshal_VOID__VOID,
4899                          G_TYPE_NONE, 0,
4900                          G_TYPE_NONE);
4901
4902         binding_set = gtk_binding_set_by_class (class);
4903
4904         add_scroll_binding_keypad (binding_set, GDK_KEY_Left,  0, GTK_SCROLL_STEP_BACKWARD, TRUE);
4905         add_scroll_binding_keypad (binding_set, GDK_KEY_Right, 0, GTK_SCROLL_STEP_FORWARD,  TRUE);
4906         add_scroll_binding_keypad (binding_set, GDK_KEY_Left,  GDK_MOD1_MASK, GTK_SCROLL_STEP_DOWN, TRUE);
4907         add_scroll_binding_keypad (binding_set, GDK_KEY_Right, GDK_MOD1_MASK, GTK_SCROLL_STEP_UP,  TRUE);
4908         add_scroll_binding_keypad (binding_set, GDK_KEY_Up,    0, GTK_SCROLL_STEP_BACKWARD, FALSE);
4909         add_scroll_binding_keypad (binding_set, GDK_KEY_Down,  0, GTK_SCROLL_STEP_FORWARD,  FALSE);
4910         add_scroll_binding_keypad (binding_set, GDK_KEY_Up,    GDK_MOD1_MASK, GTK_SCROLL_STEP_DOWN, FALSE);
4911         add_scroll_binding_keypad (binding_set, GDK_KEY_Down,  GDK_MOD1_MASK, GTK_SCROLL_STEP_UP,  FALSE);
4912         gtk_binding_entry_add_signal (binding_set, GDK_KEY_H, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4913                                       GTK_SCROLL_STEP_BACKWARD, G_TYPE_BOOLEAN, TRUE);
4914         gtk_binding_entry_add_signal (binding_set, GDK_KEY_J, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4915                                       GTK_SCROLL_STEP_FORWARD, G_TYPE_BOOLEAN, FALSE);
4916         gtk_binding_entry_add_signal (binding_set, GDK_KEY_K, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4917                                       GTK_SCROLL_STEP_BACKWARD, G_TYPE_BOOLEAN, FALSE);
4918         gtk_binding_entry_add_signal (binding_set, GDK_KEY_L, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4919                                       GTK_SCROLL_STEP_FORWARD, G_TYPE_BOOLEAN, TRUE);
4920         
4921 }
4922
4923 static void
4924 ev_view_init (EvView *view)
4925 {
4926         gtk_widget_set_has_window (GTK_WIDGET (view), TRUE);
4927         gtk_widget_set_can_focus (GTK_WIDGET (view), TRUE);
4928         gtk_widget_set_redraw_on_allocate (GTK_WIDGET (view), FALSE);
4929         gtk_container_set_resize_mode (GTK_CONTAINER (view), GTK_RESIZE_QUEUE);
4930
4931         gtk_widget_set_events (GTK_WIDGET (view),
4932                                GDK_EXPOSURE_MASK |
4933                                GDK_BUTTON_PRESS_MASK |
4934                                GDK_BUTTON_RELEASE_MASK |
4935                                GDK_SCROLL_MASK |
4936                                GDK_KEY_PRESS_MASK |
4937                                GDK_POINTER_MOTION_MASK |
4938                                GDK_POINTER_MOTION_HINT_MASK |
4939                                GDK_ENTER_NOTIFY_MASK |
4940                                GDK_LEAVE_NOTIFY_MASK);
4941
4942         view->start_page = -1;
4943         view->end_page = -1;
4944         view->spacing = 5;
4945         view->scale = 1.0;
4946         view->current_page = 0;
4947         view->pressed_button = -1;
4948         view->cursor = EV_VIEW_CURSOR_NORMAL;
4949         view->drag_info.in_drag = FALSE;
4950         view->scroll_info.autoscrolling = FALSE;
4951         view->selection_info.selections = NULL;
4952         view->selection_info.in_selection = FALSE;
4953         view->selection_info.in_drag = FALSE;
4954         view->selection_mode = EV_VIEW_SELECTION_TEXT;
4955         view->continuous = TRUE;
4956         view->dual_page = FALSE;
4957         view->fullscreen = FALSE;
4958         view->sizing_mode = EV_SIZING_FIT_WIDTH;
4959         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
4960         view->jump_to_find_result = TRUE;
4961         view->highlight_find_results = FALSE;
4962 }
4963
4964 /*** Callbacks ***/
4965
4966 static void
4967 ev_view_change_page (EvView *view,
4968                      gint    new_page)
4969 {
4970         gint x, y;
4971
4972         view->current_page = new_page;
4973         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
4974
4975         hide_loading_window (view);
4976
4977         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
4978         ev_view_handle_cursor_over_xy (view, x, y);
4979
4980         gtk_widget_queue_resize (GTK_WIDGET (view));
4981 }
4982
4983 static void
4984 job_finished_cb (EvPixbufCache  *pixbuf_cache,
4985                  cairo_region_t *region,
4986                  EvView         *view)
4987 {
4988         if (region) {
4989                 gdk_window_invalidate_region (gtk_widget_get_window (GTK_WIDGET (view)), region, TRUE);
4990         } else {
4991                 gtk_widget_queue_draw (GTK_WIDGET (view));
4992         }
4993 }
4994
4995 static void
4996 ev_view_page_changed_cb (EvDocumentModel *model,
4997                          gint             old_page,
4998                          gint             new_page,
4999                          EvView          *view)
5000 {
5001         if (!view->document)
5002                 return;
5003
5004         if (view->current_page != new_page) {
5005                 ev_view_change_page (view, new_page);
5006         } else {
5007                 gtk_widget_queue_draw (GTK_WIDGET (view));
5008         }
5009
5010         view->find_result = 0;
5011 }
5012
5013 static void
5014 on_adjustment_value_changed (GtkAdjustment *adjustment,
5015                              EvView        *view)
5016 {
5017         GtkWidget *widget = GTK_WIDGET (view);
5018         int dx = 0, dy = 0;
5019         gint x, y;
5020         gint value;
5021         GList *l;
5022
5023         if (!gtk_widget_get_realized (widget))
5024                 return;
5025
5026         if (view->hadjustment) {
5027                 value = (gint) gtk_adjustment_get_value (view->hadjustment);
5028                 dx = view->scroll_x - value;
5029                 view->scroll_x = value;
5030         } else {
5031                 view->scroll_x = 0;
5032         }
5033
5034         if (view->vadjustment) {
5035                 value = (gint) gtk_adjustment_get_value (view->vadjustment);
5036                 dy = view->scroll_y - value;
5037                 view->scroll_y = value;
5038         } else {
5039                 view->scroll_y = 0;
5040         }
5041
5042         for (l = view->children; l && l->data; l = g_list_next (l)) {
5043                 EvViewChild *child = (EvViewChild *)l->data;
5044
5045                 child->x += dx;
5046                 child->y += dy;
5047                 if (gtk_widget_get_visible (child->widget) && gtk_widget_get_visible (widget))
5048                         gtk_widget_queue_resize (widget);
5049         }
5050
5051         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
5052                 EvViewWindowChild *child;
5053
5054                 child = (EvViewWindowChild *)l->data;
5055
5056                 ev_view_window_child_move (view, child, child->x + dx, child->y + dy);
5057         }
5058
5059         if (view->pending_resize) {
5060                 gtk_widget_queue_draw (widget);
5061         } else {
5062                 gdk_window_scroll (gtk_widget_get_window (widget), dx, dy);
5063         }
5064
5065         gtk_widget_get_pointer (widget, &x, &y);
5066         ev_view_handle_cursor_over_xy (view, x, y);
5067
5068         if (view->document)
5069                 view_update_range_and_current_page (view);
5070 }
5071
5072 GtkWidget*
5073 ev_view_new (void)
5074 {
5075         GtkWidget *view;
5076
5077         view = g_object_new (EV_TYPE_VIEW, NULL);
5078
5079         return view;
5080 }
5081
5082 static void
5083 setup_caches (EvView *view)
5084 {
5085         gboolean inverted_colors;
5086
5087         view->height_to_page_cache = ev_view_get_height_to_page_cache (view);
5088         view->pixbuf_cache = ev_pixbuf_cache_new (GTK_WIDGET (view), view->model, view->pixbuf_cache_size);
5089         view->page_cache = ev_page_cache_new (view->document);
5090         if (ev_view_is_a11y_enabled (view)) {
5091                 EvJobPageDataFlags flags = ev_page_cache_get_flags (view->page_cache);
5092
5093                 ev_page_cache_set_flags (view->page_cache,
5094                                          flags |
5095                                          EV_PAGE_DATA_INCLUDE_TEXT_LAYOUT |
5096                                          EV_PAGE_DATA_INCLUDE_TEXT);
5097         }
5098         inverted_colors = ev_document_model_get_inverted_colors (view->model);
5099         ev_pixbuf_cache_set_inverted_colors (view->pixbuf_cache, inverted_colors);
5100         g_signal_connect (view->pixbuf_cache, "job-finished", G_CALLBACK (job_finished_cb), view);
5101 }
5102
5103 static void
5104 clear_caches (EvView *view)
5105 {
5106         if (view->pixbuf_cache) {
5107                 g_object_unref (view->pixbuf_cache);
5108                 view->pixbuf_cache = NULL;
5109         }
5110
5111         if (view->page_cache) {
5112                 g_object_unref (view->page_cache);
5113                 view->page_cache = NULL;
5114         }
5115 }
5116
5117 /**
5118  * ev_view_set_page_cache_size:
5119  * @view:
5120  * @cache_size:
5121  *
5122  * Sets the maximum size in bytes that will be used to cache
5123  * rendered pages. Use 0 to disable caching rendered pages.
5124  *
5125  * Note that this limit doesn't affect the current visible page range,
5126  * which will always be rendered. In order to limit the total memory used
5127  * you have to use ev_document_model_set_max_scale() too.
5128  *
5129  */
5130 void
5131 ev_view_set_page_cache_size (EvView *view,
5132                              gsize   cache_size)
5133 {
5134         if (view->pixbuf_cache_size == cache_size)
5135                 return;
5136
5137         view->pixbuf_cache_size = cache_size;
5138         if (view->pixbuf_cache)
5139                 ev_pixbuf_cache_set_max_size (view->pixbuf_cache, cache_size);
5140 }
5141
5142 void
5143 ev_view_set_loading (EvView       *view,
5144                      gboolean      loading)
5145 {
5146         if (view->loading && !loading)
5147                 hide_loading_window (view);
5148         view->loading = loading;
5149         gtk_widget_queue_draw (GTK_WIDGET (view));
5150 }
5151
5152 static gboolean
5153 ev_view_autoscroll_cb (EvView *view)
5154 {
5155         gdouble speed, value;
5156
5157         /* If the user stops autoscrolling, autoscrolling will be
5158          * set to false but the timeout will continue; stop the timeout: */
5159         if (!view->scroll_info.autoscrolling) {
5160                 view->scroll_info.timeout_id = 0;
5161                 return FALSE;
5162         }
5163         
5164         if (view->scroll_info.last_y > view->scroll_info.start_y && 
5165                 (view->scroll_info.last_y < view->scroll_info.start_y))
5166                 return TRUE; 
5167
5168         /* Replace 100 with your speed of choice: The lower the faster.
5169          * Replace 3 with another speed of choice: The higher, the faster it accelerated
5170          *      based on the distance of the starting point from the mouse
5171          * (All also effected by the timeout interval of this callback) */
5172
5173         if (view->scroll_info.start_y > view->scroll_info.last_y)
5174                 speed = -pow ((((gdouble)view->scroll_info.start_y - view->scroll_info.last_y) / 100), 3);
5175         else
5176                 speed = pow ((((gdouble)view->scroll_info.last_y - view->scroll_info.start_y) / 100), 3);
5177         
5178         value = gtk_adjustment_get_value (view->vadjustment);
5179         value = CLAMP (value + speed, 0,
5180                        gtk_adjustment_get_upper (view->vadjustment) -
5181                        gtk_adjustment_get_page_size (view->vadjustment));
5182         gtk_adjustment_set_value (view->vadjustment, value);
5183         
5184         return TRUE;
5185
5186 }
5187
5188 void
5189 ev_view_autoscroll_start (EvView *view)
5190 {
5191         gint x, y;
5192         
5193         g_return_if_fail (EV_IS_VIEW (view));
5194
5195         if (view->scroll_info.autoscrolling)
5196                 return;
5197         
5198         view->scroll_info.autoscrolling = TRUE;
5199         view->scroll_info.timeout_id =
5200                 g_timeout_add (20, (GSourceFunc)ev_view_autoscroll_cb,
5201                                view);
5202         
5203         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
5204         ev_view_handle_cursor_over_xy (view, x, y);
5205 }
5206
5207 void
5208 ev_view_autoscroll_stop (EvView *view)
5209 {
5210         gint x, y;
5211         
5212         g_return_if_fail (EV_IS_VIEW (view));
5213
5214         if (!view->scroll_info.autoscrolling)
5215                 return;
5216
5217         view->scroll_info.autoscrolling = FALSE;
5218         if (view->scroll_info.timeout_id) {
5219                 g_source_remove (view->scroll_info.timeout_id);
5220                 view->scroll_info.timeout_id = 0;
5221         }
5222
5223         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
5224         ev_view_handle_cursor_over_xy (view, x, y);
5225 }
5226
5227 static void
5228 ev_view_document_changed_cb (EvDocumentModel *model,
5229                              GParamSpec      *pspec,
5230                              EvView          *view)
5231 {
5232         EvDocument *document = ev_document_model_get_document (model);
5233
5234         if (document != view->document) {
5235                 gint current_page;
5236
5237                 clear_caches (view);
5238                 ev_view_remove_all (view);
5239
5240                 if (view->document) {
5241                         g_object_unref (view->document);
5242                 }
5243
5244                 view->document = document;
5245                 view->find_result = 0;
5246
5247                 if (view->document) {
5248                         view->loading = FALSE;
5249                         g_object_ref (view->document);
5250                         setup_caches (view);
5251                 }
5252
5253                 current_page = ev_document_model_get_page (model);
5254                 if (view->current_page != current_page) {
5255                         ev_view_change_page (view, current_page);
5256                 } else {
5257                         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
5258                         gtk_widget_queue_resize (GTK_WIDGET (view));
5259                 }
5260         }
5261 }
5262
5263 static void
5264 ev_view_rotation_changed_cb (EvDocumentModel *model,
5265                              GParamSpec      *pspec,
5266                              EvView          *view)
5267 {
5268         gint rotation = ev_document_model_get_rotation (model);
5269
5270         view->rotation = rotation;
5271
5272         if (view->pixbuf_cache) {
5273                 ev_pixbuf_cache_clear (view->pixbuf_cache);
5274                 if (!ev_document_is_page_size_uniform (view->document))
5275                         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
5276                 gtk_widget_queue_resize (GTK_WIDGET (view));
5277         }
5278
5279         ev_view_remove_all (view);
5280
5281         if (rotation != 0)
5282                 clear_selection (view);
5283 }
5284
5285 static void
5286 ev_view_inverted_colors_changed_cb (EvDocumentModel *model,
5287                                     GParamSpec      *pspec,
5288                                     EvView          *view)
5289 {
5290         if (view->pixbuf_cache) {
5291                 gboolean inverted_colors;
5292
5293                 inverted_colors = ev_document_model_get_inverted_colors (model);
5294                 ev_pixbuf_cache_set_inverted_colors (view->pixbuf_cache, inverted_colors);
5295                 gtk_widget_queue_draw (GTK_WIDGET (view));
5296         }
5297 }
5298
5299 static void
5300 ev_view_sizing_mode_changed_cb (EvDocumentModel *model,
5301                                 GParamSpec      *pspec,
5302                                 EvView          *view)
5303 {
5304         EvSizingMode mode = ev_document_model_get_sizing_mode (model);
5305
5306         view->sizing_mode = mode;
5307         if (mode != EV_SIZING_FREE)
5308                 gtk_widget_queue_resize (GTK_WIDGET (view));
5309 }
5310
5311 #define EPSILON 0.0000001
5312 static void
5313 ev_view_scale_changed_cb (EvDocumentModel *model,
5314                           GParamSpec      *pspec,
5315                           EvView          *view)
5316 {
5317         gdouble scale = ev_document_model_get_scale (model);
5318
5319         if (ABS (view->scale - scale) < EPSILON)
5320                 return;
5321
5322         view->scale = scale;
5323
5324         view->pending_resize = TRUE;
5325         if (view->sizing_mode == EV_SIZING_FREE)
5326                 gtk_widget_queue_resize (GTK_WIDGET (view));
5327 }
5328
5329 static void
5330 ev_view_continuous_changed_cb (EvDocumentModel *model,
5331                                GParamSpec      *pspec,
5332                                EvView          *view)
5333 {
5334         gboolean continuous = ev_document_model_get_continuous (model);
5335
5336         view->continuous = continuous;
5337         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
5338         gtk_widget_queue_resize (GTK_WIDGET (view));
5339 }
5340
5341 static void
5342 ev_view_dual_page_changed_cb (EvDocumentModel *model,
5343                               GParamSpec      *pspec,
5344                               EvView          *view)
5345 {
5346         gboolean dual_page = ev_document_model_get_dual_page (model);
5347
5348         view->dual_page = dual_page;
5349         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
5350         /* FIXME: if we're keeping the pixbuf cache around, we should extend the
5351          * preload_cache_size to be 2 if dual_page is set.
5352          */
5353         gtk_widget_queue_resize (GTK_WIDGET (view));
5354 }
5355
5356 static void
5357 ev_view_fullscreen_changed_cb (EvDocumentModel *model,
5358                                GParamSpec      *pspec,
5359                                EvView          *view)
5360 {
5361         gboolean fullscreen = ev_document_model_get_fullscreen (model);
5362
5363         view->fullscreen = fullscreen;
5364         gtk_widget_queue_resize (GTK_WIDGET (view));
5365 }
5366
5367 void
5368 ev_view_set_model (EvView          *view,
5369                    EvDocumentModel *model)
5370 {
5371         g_return_if_fail (EV_IS_VIEW (view));
5372         g_return_if_fail (EV_IS_DOCUMENT_MODEL (model));
5373
5374         if (model == view->model)
5375                 return;
5376
5377         if (view->model) {
5378                 g_signal_handlers_disconnect_by_func (view->model,
5379                                                       ev_view_document_changed_cb,
5380                                                       view);
5381                 g_signal_handlers_disconnect_by_func (view->model,
5382                                                       ev_view_page_changed_cb,
5383                                                       view);
5384                 g_object_unref (view->model);
5385         }
5386         view->model = g_object_ref (model);
5387
5388         /* Initialize view from model */
5389         view->rotation = ev_document_model_get_rotation (view->model);
5390         view->sizing_mode = ev_document_model_get_sizing_mode (view->model);
5391         view->scale = ev_document_model_get_scale (view->model);
5392         view->continuous = ev_document_model_get_continuous (view->model);
5393         view->dual_page = ev_document_model_get_dual_page (view->model);
5394         view->fullscreen = ev_document_model_get_fullscreen (view->model);
5395         ev_view_document_changed_cb (view->model, NULL, view);
5396
5397         g_signal_connect (view->model, "notify::document",
5398                           G_CALLBACK (ev_view_document_changed_cb),
5399                           view);
5400         g_signal_connect (view->model, "notify::rotation",
5401                           G_CALLBACK (ev_view_rotation_changed_cb),
5402                           view);
5403         g_signal_connect (view->model, "notify::inverted-colors",
5404                           G_CALLBACK (ev_view_inverted_colors_changed_cb),
5405                           view);
5406         g_signal_connect (view->model, "notify::sizing-mode",
5407                           G_CALLBACK (ev_view_sizing_mode_changed_cb),
5408                           view);
5409         g_signal_connect (view->model, "notify::scale",
5410                           G_CALLBACK (ev_view_scale_changed_cb),
5411                           view);
5412         g_signal_connect (view->model, "notify::continuous",
5413                           G_CALLBACK (ev_view_continuous_changed_cb),
5414                           view);
5415         g_signal_connect (view->model, "notify::dual-page",
5416                           G_CALLBACK (ev_view_dual_page_changed_cb),
5417                           view);
5418         g_signal_connect (view->model, "notify::fullscreen",
5419                           G_CALLBACK (ev_view_fullscreen_changed_cb),
5420                           view);
5421         g_signal_connect (view->model, "page-changed",
5422                           G_CALLBACK (ev_view_page_changed_cb),
5423                           view);
5424 }
5425
5426 static void
5427 ev_view_reload_page (EvView         *view,
5428                      gint            page,
5429                      cairo_region_t *region)
5430 {
5431         ev_pixbuf_cache_reload_page (view->pixbuf_cache,
5432                                      region,
5433                                      page,
5434                                      view->rotation,
5435                                      view->scale);
5436 }
5437
5438 void
5439 ev_view_reload (EvView *view)
5440 {
5441         ev_pixbuf_cache_clear (view->pixbuf_cache);
5442         view_update_range_and_current_page (view);
5443 }
5444
5445 /*** Zoom and sizing mode ***/
5446
5447 gboolean
5448 ev_view_can_zoom_in (EvView *view)
5449 {
5450         return view->scale * ZOOM_IN_FACTOR <= ev_document_model_get_max_scale (view->model);
5451 }
5452
5453 gboolean
5454 ev_view_can_zoom_out (EvView *view)
5455 {
5456         return view->scale * ZOOM_OUT_FACTOR >= ev_document_model_get_min_scale (view->model);
5457 }
5458
5459 void
5460 ev_view_zoom_in (EvView *view)
5461 {
5462         gdouble scale;
5463
5464         g_return_if_fail (view->sizing_mode == EV_SIZING_FREE);
5465
5466         view->pending_scroll = SCROLL_TO_CENTER;
5467         scale = ev_document_model_get_scale (view->model) * ZOOM_IN_FACTOR;
5468         ev_document_model_set_scale (view->model, scale);
5469 }
5470
5471 void
5472 ev_view_zoom_out (EvView *view)
5473 {
5474         gdouble scale;
5475
5476         g_return_if_fail (view->sizing_mode == EV_SIZING_FREE);
5477
5478         view->pending_scroll = SCROLL_TO_CENTER;
5479         scale = ev_document_model_get_scale (view->model) * ZOOM_OUT_FACTOR;
5480         ev_document_model_set_scale (view->model, scale);
5481 }
5482
5483 static double
5484 zoom_for_size_fit_width (gdouble doc_width,
5485                          gdouble doc_height,
5486                          int     target_width,
5487                          int     target_height)
5488 {
5489         return (double)target_width / doc_width;
5490 }
5491
5492 static double
5493 zoom_for_size_fit_height (gdouble doc_width,
5494                           gdouble doc_height,
5495                           int     target_width,
5496                           int     target_height)
5497 {
5498         return (double)target_height / doc_height;
5499 }
5500
5501 static double
5502 zoom_for_size_best_fit (gdouble doc_width,
5503                         gdouble doc_height,
5504                         int     target_width,
5505                         int     target_height)
5506 {
5507         double w_scale;
5508         double h_scale;
5509
5510         w_scale = (double)target_width / doc_width;
5511         h_scale = (double)target_height / doc_height;
5512
5513         return MIN (w_scale, h_scale);
5514 }
5515
5516 static void
5517 ev_view_zoom_for_size_continuous_and_dual_page (EvView *view,
5518                                                 int     width,
5519                                                 int     height)
5520 {
5521         gdouble doc_width, doc_height;
5522         GtkBorder border;
5523         gdouble scale;
5524         gint sb_size;
5525
5526         ev_document_get_max_page_size (view->document, &doc_width, &doc_height);
5527         if (view->rotation == 90 || view->rotation == 270) {
5528                 gdouble tmp;
5529
5530                 tmp = doc_width;
5531                 doc_width = doc_height;
5532                 doc_height = tmp;
5533         }
5534
5535         compute_border (view, doc_width, doc_height, &border);
5536
5537         doc_width *= 2;
5538         width -= (2 * (border.left + border.right) + 3 * view->spacing);
5539         height -= (border.top + border.bottom + 2 * view->spacing - 1);
5540
5541         sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5542
5543         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5544                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5545         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5546                 scale = zoom_for_size_best_fit (doc_width, doc_height, width - sb_size, height);
5547         else
5548                 g_assert_not_reached ();
5549
5550         ev_document_model_set_scale (view->model, scale);
5551 }
5552
5553 static void
5554 ev_view_zoom_for_size_continuous (EvView *view,
5555                                   int     width,
5556                                   int     height)
5557 {
5558         gdouble doc_width, doc_height;
5559         GtkBorder border;
5560         gdouble scale;
5561         gint sb_size;
5562
5563         ev_document_get_max_page_size (view->document, &doc_width, &doc_height);
5564         if (view->rotation == 90 || view->rotation == 270) {
5565                 gdouble tmp;
5566
5567                 tmp = doc_width;
5568                 doc_width = doc_height;
5569                 doc_height = tmp;
5570         }
5571
5572         compute_border (view, doc_width, doc_height, &border);
5573
5574         width -= (border.left + border.right + 2 * view->spacing);
5575         height -= (border.top + border.bottom + 2 * view->spacing - 1);
5576
5577         sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5578
5579         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5580                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5581         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5582                 scale = zoom_for_size_best_fit (doc_width, doc_height, width - sb_size, height);
5583         else
5584                 g_assert_not_reached ();
5585
5586         ev_document_model_set_scale (view->model, scale);
5587 }
5588
5589 static void
5590 ev_view_zoom_for_size_dual_page (EvView *view,
5591                                  int     width,
5592                                  int     height)
5593 {
5594         GtkBorder border;
5595         gdouble doc_width, doc_height;
5596         gdouble scale;
5597         gint other_page;
5598
5599         other_page = view->current_page ^ 1;
5600
5601         /* Find the largest of the two. */
5602         get_doc_page_size (view, view->current_page, &doc_width, &doc_height);
5603         if (other_page < ev_document_get_n_pages (view->document)) {
5604                 gdouble width_2, height_2;
5605
5606                 get_doc_page_size (view, other_page, &width_2, &height_2);
5607                 if (width_2 > doc_width)
5608                         doc_width = width_2;
5609                 if (height_2 > doc_height)
5610                         doc_height = height_2;
5611         }
5612         compute_border (view, width, height, &border);
5613
5614         doc_width = doc_width * 2;
5615         width -= ((border.left + border.right)* 2 + 3 * view->spacing);
5616         height -= (border.top + border.bottom + 2 * view->spacing);
5617
5618         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5619                 gint sb_size;
5620
5621                 sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5622                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5623         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5624                 scale = zoom_for_size_best_fit (doc_width, doc_height, width, height);
5625         else
5626                 g_assert_not_reached ();
5627
5628         ev_document_model_set_scale (view->model, scale);
5629 }
5630
5631 static void
5632 ev_view_zoom_for_size_single_page (EvView *view,
5633                                    int     width,
5634                                    int     height)
5635 {
5636         gdouble doc_width, doc_height;
5637         GtkBorder border;
5638         gdouble scale;
5639
5640         get_doc_page_size (view, view->current_page, &doc_width, &doc_height);
5641
5642         /* Get an approximate border */
5643         compute_border (view, width, height, &border);
5644
5645         width -= (border.left + border.right + 2 * view->spacing);
5646         height -= (border.top + border.bottom + 2 * view->spacing);
5647
5648         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5649                 gint sb_size;
5650
5651                 sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5652                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5653         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5654                 scale = zoom_for_size_best_fit (doc_width, doc_height, width, height);
5655         else
5656                 g_assert_not_reached ();
5657
5658         ev_document_model_set_scale (view->model, scale);
5659 }
5660
5661 static void
5662 ev_view_zoom_for_size (EvView *view,
5663                        int     width,
5664                        int     height)
5665 {
5666         g_return_if_fail (EV_IS_VIEW (view));
5667         g_return_if_fail (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
5668                           view->sizing_mode == EV_SIZING_BEST_FIT);
5669         g_return_if_fail (width >= 0);
5670         g_return_if_fail (height >= 0);
5671
5672         if (view->document == NULL)
5673                 return;
5674
5675         if (view->continuous && view->dual_page)
5676                 ev_view_zoom_for_size_continuous_and_dual_page (view, width, height);
5677         else if (view->continuous)
5678                 ev_view_zoom_for_size_continuous (view, width, height);
5679         else if (view->dual_page)
5680                 ev_view_zoom_for_size_dual_page (view, width, height);
5681         else
5682                 ev_view_zoom_for_size_single_page (view, width, height);
5683 }
5684
5685 /*** Find ***/
5686 static gint
5687 ev_view_find_get_n_results (EvView *view, gint page)
5688 {
5689         return view->find_pages ? g_list_length (view->find_pages[page]) : 0;
5690 }
5691
5692 static EvRectangle *
5693 ev_view_find_get_result (EvView *view, gint page, gint result)
5694 {
5695         return view->find_pages ? (EvRectangle *) g_list_nth_data (view->find_pages[page], result) : NULL;
5696 }
5697
5698 static void
5699 jump_to_find_result (EvView *view)
5700 {
5701         gint n_results;
5702         gint page = view->current_page;
5703
5704         n_results = ev_view_find_get_n_results (view, page);
5705
5706         if (n_results > 0 && view->find_result < n_results) {
5707                 EvRectangle *rect;
5708                 GdkRectangle view_rect;
5709
5710                 rect = ev_view_find_get_result (view, page, view->find_result);
5711                 doc_rect_to_view_rect (view, page, rect, &view_rect);
5712                 ensure_rectangle_is_visible (view, &view_rect);
5713                 view->jump_to_find_result = FALSE;
5714         }
5715 }
5716
5717 /**
5718  * jump_to_find_page
5719  * @view: #EvView instance
5720  * @direction: Direction to look
5721  * @shift: Shift from current page
5722  *
5723  * Jumps to the first page that has occurences of searched word.
5724  * Uses a direction where to look and a shift from current page. 
5725  *
5726  */
5727 static void
5728 jump_to_find_page (EvView *view, EvViewFindDirection direction, gint shift)
5729 {
5730         int n_pages, i;
5731
5732         n_pages = ev_document_get_n_pages (view->document);
5733
5734         for (i = 0; i < n_pages; i++) {
5735                 int page;
5736                 
5737                 if (direction == EV_VIEW_FIND_NEXT)
5738                         page = view->current_page + i;
5739                 else
5740                         page = view->current_page - i;          
5741                 page += shift;
5742                 
5743                 if (page >= n_pages) {
5744                         page = page - n_pages;
5745                 } else if (page < 0) 
5746                         page = page + n_pages;
5747
5748                 if (ev_view_find_get_n_results (view, page) > 0) {
5749                         ev_document_model_set_page (view->model, page);
5750                         break;
5751                 }
5752         }
5753 }
5754
5755 void
5756 ev_view_find_changed (EvView *view, GList **results, gint page)
5757 {
5758         view->find_pages = results;
5759         
5760         if (view->jump_to_find_result == TRUE) {
5761                 jump_to_find_page (view, EV_VIEW_FIND_NEXT, 0);
5762                 jump_to_find_result (view);
5763         }
5764
5765         if (view->current_page == page)
5766                 gtk_widget_queue_draw (GTK_WIDGET (view));
5767 }
5768
5769 void
5770 ev_view_find_next (EvView *view)
5771 {
5772         gint n_results;
5773
5774         n_results = ev_view_find_get_n_results (view, view->current_page);
5775         view->find_result++;
5776
5777         if (view->find_result >= n_results) {
5778                 view->find_result = 0;
5779                 jump_to_find_page (view, EV_VIEW_FIND_NEXT, 1);
5780                 jump_to_find_result (view);
5781         } else {
5782                 jump_to_find_result (view);
5783                 gtk_widget_queue_draw (GTK_WIDGET (view));
5784         }
5785 }
5786
5787 void
5788 ev_view_find_previous (EvView *view)
5789 {
5790         view->find_result--;
5791
5792         if (view->find_result < 0) {
5793                 jump_to_find_page (view, EV_VIEW_FIND_PREV, -1);
5794                 view->find_result = MAX (0, ev_view_find_get_n_results (view, view->current_page) - 1);
5795                 jump_to_find_result (view);
5796         } else {
5797                 jump_to_find_result (view);
5798                 gtk_widget_queue_draw (GTK_WIDGET (view));
5799         }
5800 }
5801
5802 void
5803 ev_view_find_search_changed (EvView *view)
5804 {
5805         /* search string has changed, focus on new search result */
5806         view->jump_to_find_result = TRUE;
5807         view->find_pages = NULL;
5808 }
5809
5810 void
5811 ev_view_find_set_highlight_search (EvView *view, gboolean value)
5812 {
5813         view->highlight_find_results = value;
5814         gtk_widget_queue_draw (GTK_WIDGET (view));
5815 }
5816
5817 void
5818 ev_view_find_cancel (EvView *view)
5819 {
5820         view->find_pages = NULL;
5821 }
5822
5823 /*** Synctex ***/
5824 void
5825 ev_view_highlight_forward_search (EvView       *view,
5826                                   EvSourceLink *link)
5827 {
5828         EvMapping   *mapping;
5829         gint         page;
5830         GdkRectangle view_rect;
5831
5832         if (!ev_document_has_synctex (view->document))
5833                 return;
5834
5835         mapping = ev_document_synctex_forward_search (view->document, link);
5836         if (!mapping)
5837                 return;
5838
5839         if (view->synctex_result)
5840                 g_free (view->synctex_result);
5841         view->synctex_result = mapping;
5842
5843         page = GPOINTER_TO_INT (mapping->data);
5844         ev_document_model_set_page (view->model, page);
5845
5846         doc_rect_to_view_rect (view, page, &mapping->area, &view_rect);
5847         ensure_rectangle_is_visible (view, &view_rect);
5848         gtk_widget_queue_draw (GTK_WIDGET (view));
5849 }
5850
5851 /*** Selections ***/
5852
5853 /* compute_new_selection_rect/text calculates the area currently selected by
5854  * view_rect.  each handles a different mode;
5855  */
5856 static GList *
5857 compute_new_selection_rect (EvView       *view,
5858                             GdkPoint     *start,
5859                             GdkPoint     *stop)
5860 {
5861         GdkRectangle view_rect;
5862         int n_pages, i;
5863         GList *list = NULL;
5864
5865         g_assert (view->selection_mode == EV_VIEW_SELECTION_RECTANGLE);
5866         
5867         view_rect.x = MIN (start->x, stop->x);
5868         view_rect.y = MIN (start->y, stop->y);
5869         view_rect.width = MAX (start->x, stop->x) - view_rect.x;
5870         view_rect.width = MAX (start->y, stop->y) - view_rect.y;
5871
5872         n_pages = ev_document_get_n_pages (view->document);
5873
5874         for (i = 0; i < n_pages; i++) {
5875                 GdkRectangle page_area;
5876                 GtkBorder border;
5877                 
5878                 if (ev_view_get_page_extents (view, i, &page_area, &border)) {
5879                         GdkRectangle overlap;
5880
5881                         if (gdk_rectangle_intersect (&page_area, &view_rect, &overlap)) {
5882                                 EvViewSelection *selection;
5883
5884                                 selection = g_new0 (EvViewSelection, 1);
5885                                 selection->page = i;
5886                                 view_rect_to_doc_rect (view, &overlap, &page_area,
5887                                                        &(selection->rect));
5888
5889                                 list = g_list_append (list, selection);
5890                         }
5891                 }
5892         }
5893
5894         return list;
5895 }
5896
5897 static gboolean
5898 gdk_rectangle_point_in (GdkRectangle *rectangle,
5899                         GdkPoint     *point)
5900 {
5901         return rectangle->x <= point->x &&
5902                 rectangle->y <= point->y &&
5903                 point->x < rectangle->x + rectangle->width &&
5904                 point->y < rectangle->y + rectangle->height;
5905 }
5906
5907 static GList *
5908 compute_new_selection_text (EvView          *view,
5909                             EvSelectionStyle style,
5910                             GdkPoint        *start,
5911                             GdkPoint        *stop)
5912 {
5913         int n_pages, i, first, last;
5914         GList *list = NULL;
5915         EvViewSelection *selection;
5916         gdouble width, height;
5917         int start_page, end_page;
5918
5919         g_assert (view->selection_mode == EV_VIEW_SELECTION_TEXT);
5920
5921         n_pages = ev_document_get_n_pages (view->document);
5922
5923         /* First figure out the range of pages the selection
5924          * affects. */
5925         first = n_pages;
5926         last = 0;
5927         if (view->continuous) {
5928                 start_page = 0;
5929                 end_page = n_pages;
5930         } else if (view->dual_page) {
5931                 start_page = view->start_page;
5932                 end_page = view->end_page + 1;
5933         } else {
5934                 start_page = view->current_page;
5935                 end_page = view->current_page + 1;
5936         }
5937
5938         for (i = start_page; i < end_page; i++) {
5939                 GdkRectangle page_area;
5940                 GtkBorder border;
5941                 
5942                 ev_view_get_page_extents (view, i, &page_area, &border);
5943                 if (gdk_rectangle_point_in (&page_area, start) || 
5944                     gdk_rectangle_point_in (&page_area, stop)) {
5945                         if (first == n_pages)
5946                                 first = i;
5947                         last = i;
5948                 }
5949
5950         }
5951
5952         /* Now create a list of EvViewSelection's for the affected
5953          * pages.  This could be an empty list, a list of just one
5954          * page or a number of pages.*/
5955         for (i = first; i < last + 1; i++) {
5956                 GdkRectangle page_area;
5957                 GtkBorder border;
5958                 GdkPoint *point;
5959
5960                 get_doc_page_size (view, i, &width, &height);
5961
5962                 selection = g_new0 (EvViewSelection, 1);
5963                 selection->page = i;
5964                 selection->style = style;
5965                 selection->rect.x1 = selection->rect.y1 = 0;
5966                 selection->rect.x2 = width;
5967                 selection->rect.y2 = height;
5968
5969                 ev_view_get_page_extents (view, i, &page_area, &border);
5970
5971                 if (gdk_rectangle_point_in (&page_area, start))
5972                         point = start;
5973                 else
5974                         point = stop;
5975
5976                 if (i == first)
5977                         view_point_to_doc_point (view, point, &page_area,
5978                                                  &selection->rect.x1,
5979                                                  &selection->rect.y1);
5980
5981                 /* If the selection is contained within just one page,
5982                  * make sure we don't write 'start' into both points
5983                  * in selection->rect. */
5984                 if (first == last)
5985                         point = stop;
5986
5987                 if (i == last)
5988                         view_point_to_doc_point (view, point, &page_area,
5989                                                  &selection->rect.x2,
5990                                                  &selection->rect.y2);
5991
5992                 list = g_list_append (list, selection);
5993         }
5994
5995         return list;
5996 }
5997
5998 /* This function takes the newly calculated list, and figures out which regions
5999  * have changed.  It then queues a redraw approporiately.
6000  */
6001 static void
6002 merge_selection_region (EvView *view,
6003                         GList  *new_list)
6004 {
6005         GList *old_list;
6006         GList *new_list_ptr, *old_list_ptr;
6007
6008         /* Update the selection */
6009         old_list = ev_pixbuf_cache_get_selection_list (view->pixbuf_cache);
6010         g_list_foreach (view->selection_info.selections, (GFunc)selection_free, NULL);
6011         g_list_free (view->selection_info.selections);
6012         view->selection_info.selections = new_list;
6013         ev_pixbuf_cache_set_selection_list (view->pixbuf_cache, new_list);
6014         g_signal_emit (view, signals[SIGNAL_SELECTION_CHANGED], 0, NULL);
6015
6016         new_list_ptr = new_list;
6017         old_list_ptr = old_list;
6018
6019         while (new_list_ptr || old_list_ptr) {
6020                 EvViewSelection *old_sel, *new_sel;
6021                 int cur_page;
6022                 cairo_region_t *region = NULL;
6023
6024                 new_sel = (new_list_ptr) ? (new_list_ptr->data) : NULL;
6025                 old_sel = (old_list_ptr) ? (old_list_ptr->data) : NULL;
6026
6027                 /* Assume that the lists are in order, and we run through them
6028                  * comparing them, one page at a time.  We come out with the
6029                  * first page we see. */
6030                 if (new_sel && old_sel) {
6031                         if (new_sel->page < old_sel->page) {
6032                                 new_list_ptr = new_list_ptr->next;
6033                                 old_sel = NULL;
6034                         } else if (new_sel->page > old_sel->page) {
6035                                 old_list_ptr = old_list_ptr->next;
6036                                 new_sel = NULL;
6037                         } else {
6038                                 new_list_ptr = new_list_ptr->next;
6039                                 old_list_ptr = old_list_ptr->next;
6040                         }
6041                 } else if (new_sel) {
6042                         new_list_ptr = new_list_ptr->next;
6043                 } else if (old_sel) {
6044                         old_list_ptr = old_list_ptr->next;
6045                 }
6046
6047                 g_assert (new_sel || old_sel);
6048
6049                 /* is the page we're looking at on the screen?*/
6050                 cur_page = new_sel ? new_sel->page : old_sel->page;
6051                 if (cur_page < view->start_page || cur_page > view->end_page)
6052                         continue;
6053
6054                 /* seed the cache with a new page.  We are going to need the new
6055                  * region too. */
6056                 if (new_sel) {
6057                         cairo_region_t *tmp_region = NULL;
6058
6059                         ev_pixbuf_cache_get_selection_surface (view->pixbuf_cache,
6060                                                                cur_page,
6061                                                                view->scale,
6062                                                                &tmp_region);
6063
6064                         if (tmp_region && !cairo_region_is_empty (tmp_region)) {
6065                                 new_sel->covered_region = cairo_region_reference (tmp_region);
6066                         }
6067                 }
6068
6069                 /* Now we figure out what needs redrawing */
6070                 if (old_sel && new_sel) {
6071                         if (old_sel->covered_region && new_sel->covered_region) {
6072                                 /* We only want to redraw the areas that have
6073                                  * changed, so we xor the old and new regions
6074                                  * and redraw if it's different */
6075                                 region = cairo_region_copy (old_sel->covered_region);
6076 #if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1, 9, 12)
6077                                 cairo_region_xor (region, new_sel->covered_region);
6078 #else
6079                                 cairo_region_t *tbr;
6080                                 tbr = cairo_region_copy (new_sel->covered_region);
6081
6082                                 /* xor old_sel, new_sel*/
6083                                 cairo_region_subtract (tbr, region);
6084                                 cairo_region_subtract (region, new_sel->covered_region);
6085                                 cairo_region_union (region, tbr);
6086                                 cairo_region_destroy (tbr);
6087 #endif
6088
6089                                 if (cairo_region_is_empty (region)) {
6090                                         cairo_region_destroy (region);
6091                                         region = NULL;
6092                                 } else {
6093                                         gint num_rectangles = cairo_region_num_rectangles (region);
6094                                         GdkRectangle r;
6095
6096                                         /* We need to make the damage region a little bigger
6097                                          * because the edges of the old selection might change
6098                                          */
6099                                         cairo_region_get_rectangle (region, 0, &r);
6100                                         r.x -= 5;
6101                                         r.width = 5;
6102                                         cairo_region_union_rectangle (region, &r);
6103
6104                                         cairo_region_get_rectangle (region, num_rectangles - 1, &r);
6105                                         r.x += r.width;
6106                                         r.width = 5;
6107                                         cairo_region_union_rectangle (region, &r);
6108                                 }
6109                         } else if (old_sel->covered_region) {
6110                                 region = cairo_region_copy (old_sel->covered_region);
6111                         } else if (new_sel->covered_region) {
6112                                 region = cairo_region_copy (new_sel->covered_region);
6113                         }
6114                 } else if (old_sel && !new_sel) {
6115                         if (old_sel->covered_region && !cairo_region_is_empty (old_sel->covered_region)) {
6116                                 region = cairo_region_copy (old_sel->covered_region);
6117                         }
6118                 } else if (!old_sel && new_sel) {
6119                         if (new_sel->covered_region && !cairo_region_is_empty (new_sel->covered_region)) {
6120                                 region = cairo_region_copy (new_sel->covered_region);
6121                         }
6122                 } else {
6123                         g_assert_not_reached ();
6124                 }
6125
6126                 /* Redraw the damaged region! */
6127                 if (region) {
6128                         GdkRectangle page_area;
6129                         GtkBorder    border;
6130
6131                         ev_view_get_page_extents (view, cur_page, &page_area, &border);
6132                         cairo_region_translate (region,
6133                                            page_area.x + border.left - view->scroll_x,
6134                                            page_area.y + border.top - view->scroll_y);
6135                         gdk_window_invalidate_region (gtk_widget_get_window (GTK_WIDGET (view)), region, TRUE);
6136                         cairo_region_destroy (region);
6137                 }
6138         }
6139
6140         /* Free the old list, now that we're done with it. */
6141         g_list_foreach (old_list, (GFunc) selection_free, NULL);
6142         g_list_free (old_list);
6143 }
6144
6145 static void
6146 compute_selections (EvView          *view,
6147                     EvSelectionStyle style,
6148                     GdkPoint        *start,
6149                     GdkPoint        *stop)
6150 {
6151         GList *list;
6152
6153         if (view->selection_mode == EV_VIEW_SELECTION_RECTANGLE)
6154                 list = compute_new_selection_rect (view, start, stop);
6155         else
6156                 list = compute_new_selection_text (view, style, start, stop);
6157         merge_selection_region (view, list);
6158 }
6159
6160 /* Free's the selection.  It's up to the caller to queue redraws if needed.
6161  */
6162 static void
6163 selection_free (EvViewSelection *selection)
6164 {
6165         if (selection->covered_region)
6166                 cairo_region_destroy (selection->covered_region);
6167         g_free (selection);
6168 }
6169
6170 static void
6171 clear_selection (EvView *view)
6172 {
6173         if (view->selection_info.selections) {
6174                 g_list_foreach (view->selection_info.selections, (GFunc)selection_free, NULL);
6175                 g_list_free (view->selection_info.selections);
6176                 view->selection_info.selections = NULL;
6177
6178                 g_signal_emit (view, signals[SIGNAL_SELECTION_CHANGED], 0, NULL);
6179         }
6180         view->selection_info.in_selection = FALSE;
6181         if (view->pixbuf_cache)
6182                 ev_pixbuf_cache_set_selection_list (view->pixbuf_cache, NULL);
6183 }
6184
6185 void
6186 ev_view_select_all (EvView *view)
6187 {
6188         GList *selections = NULL;
6189         int n_pages, i;
6190
6191         /* Disable selection on rotated pages for the 0.4.0 series */
6192         if (view->rotation != 0)
6193                 return;
6194
6195         clear_selection (view);
6196         
6197         n_pages = ev_document_get_n_pages (view->document);
6198         for (i = 0; i < n_pages; i++) {
6199                 gdouble width, height;
6200                 EvViewSelection *selection;
6201
6202                 get_doc_page_size (view, i, &width, &height);
6203
6204                 selection = g_new0 (EvViewSelection, 1);
6205                 selection->page = i;
6206                 selection->style = EV_SELECTION_STYLE_GLYPH;
6207                 selection->rect.x1 = selection->rect.y1 = 0;
6208                 selection->rect.x2 = width;
6209                 selection->rect.y2 = height;
6210
6211                 selections = g_list_append (selections, selection);
6212         }
6213
6214         merge_selection_region (view, selections);
6215         gtk_widget_queue_draw (GTK_WIDGET (view));
6216 }
6217
6218 gboolean
6219 ev_view_get_has_selection (EvView *view)
6220 {
6221         return view->selection_info.selections != NULL;
6222 }
6223
6224 static char *
6225 get_selected_text (EvView *view)
6226 {
6227         GString *text;
6228         GList *l;
6229         gchar *normalized_text;
6230
6231         text = g_string_new (NULL);
6232
6233         ev_document_doc_mutex_lock ();
6234
6235         for (l = view->selection_info.selections; l != NULL; l = l->next) {
6236                 EvViewSelection *selection = (EvViewSelection *)l->data;
6237                 EvPage *page;
6238                 gchar *tmp;
6239
6240                 page = ev_document_get_page (view->document, selection->page);
6241                 tmp = ev_selection_get_selected_text (EV_SELECTION (view->document),
6242                                                       page, selection->style,
6243                                                       &(selection->rect));
6244                 g_object_unref (page);
6245                 g_string_append (text, tmp);
6246                 g_free (tmp);
6247         }
6248
6249         ev_document_doc_mutex_unlock ();
6250         
6251         normalized_text = g_utf8_normalize (text->str, text->len, G_NORMALIZE_NFKC);
6252         g_string_free (text, TRUE);
6253         return normalized_text;
6254 }
6255
6256 static void
6257 ev_view_clipboard_copy (EvView      *view,
6258                         const gchar *text)
6259 {
6260         GtkClipboard *clipboard;
6261
6262         clipboard = gtk_widget_get_clipboard (GTK_WIDGET (view),
6263                                               GDK_SELECTION_CLIPBOARD);
6264         gtk_clipboard_set_text (clipboard, text, -1);
6265 }
6266
6267 void
6268 ev_view_copy (EvView *ev_view)
6269 {
6270         char *text;
6271
6272         if (!EV_IS_SELECTION (ev_view->document))
6273                 return;
6274
6275         text = get_selected_text (ev_view);
6276         ev_view_clipboard_copy (ev_view, text);
6277         g_free (text);
6278 }
6279
6280 static void
6281 ev_view_primary_get_cb (GtkClipboard     *clipboard,
6282                         GtkSelectionData *selection_data,
6283                         guint             info,
6284                         gpointer          data)
6285 {
6286         EvView *ev_view = EV_VIEW (data);
6287
6288         if (ev_view->link_selected) {
6289                 gtk_selection_data_set_text (selection_data,
6290                                              ev_link_action_get_uri (ev_view->link_selected),
6291                                              -1);
6292         } else if (EV_IS_SELECTION (ev_view->document) &&
6293                    ev_view->selection_info.selections) {
6294                 gchar *text;
6295                 
6296                 text = get_selected_text (ev_view);
6297                 if (text) {
6298                         gtk_selection_data_set_text (selection_data, text, -1);
6299                         g_free (text);
6300                 }
6301         }
6302 }
6303
6304 static void
6305 ev_view_primary_clear_cb (GtkClipboard *clipboard,
6306                           gpointer      data)
6307 {
6308         EvView *view = EV_VIEW (data);
6309
6310         clear_selection (view);
6311         clear_link_selected (view);
6312 }
6313
6314 static void
6315 ev_view_update_primary_selection (EvView *ev_view)
6316 {
6317         GtkClipboard *clipboard;
6318
6319         clipboard = gtk_widget_get_clipboard (GTK_WIDGET (ev_view),
6320                                               GDK_SELECTION_PRIMARY);
6321
6322         if (ev_view->selection_info.selections || ev_view->link_selected) {
6323                 GtkTargetList *target_list;
6324                 GtkTargetEntry *targets;
6325                 int n_targets;
6326
6327                 target_list = gtk_target_list_new (NULL, 0);
6328                 gtk_target_list_add_text_targets (target_list, 0);
6329                 targets = gtk_target_table_new_from_list (target_list, &n_targets);
6330                 gtk_target_list_unref (target_list);
6331                 
6332                 if (!gtk_clipboard_set_with_owner (clipboard,
6333                                                    targets, n_targets,
6334                                                    ev_view_primary_get_cb,
6335                                                    ev_view_primary_clear_cb,
6336                                                    G_OBJECT (ev_view)))
6337                         ev_view_primary_clear_cb (clipboard, ev_view);
6338
6339                 gtk_target_table_free (targets, n_targets);
6340         } else {
6341                 if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (ev_view))
6342                         gtk_clipboard_clear (clipboard);
6343         }
6344 }
6345
6346 static void
6347 clear_link_selected (EvView *view)
6348 {
6349         if (view->link_selected) {
6350                 g_object_unref (view->link_selected);
6351                 view->link_selected = NULL;
6352         }
6353 }
6354
6355 void
6356 ev_view_copy_link_address (EvView       *view,
6357                            EvLinkAction *action)
6358 {
6359         clear_link_selected (view);
6360         
6361         ev_view_clipboard_copy (view, ev_link_action_get_uri (action));
6362         
6363         view->link_selected = g_object_ref (action);
6364         ev_view_update_primary_selection (view);
6365 }
6366
6367 /*** Cursor operations ***/
6368 static void
6369 ev_view_set_cursor (EvView *view, EvViewCursor new_cursor)
6370 {
6371         GdkCursor *cursor = NULL;
6372         GtkWidget *widget;
6373         GdkWindow *window;
6374
6375         if (view->cursor == new_cursor) {
6376                 return;
6377         }
6378
6379         view->cursor = new_cursor;
6380
6381         window = gtk_widget_get_window (GTK_WIDGET (view));
6382         widget = gtk_widget_get_toplevel (GTK_WIDGET (view));
6383         cursor = ev_view_cursor_new (gtk_widget_get_display (widget), new_cursor);
6384         gdk_window_set_cursor (window, cursor);
6385         gdk_flush ();
6386         if (cursor)
6387                 g_object_unref (cursor);
6388 }
6389
6390 void
6391 ev_view_hide_cursor (EvView *view)
6392 {
6393        ev_view_set_cursor (view, EV_VIEW_CURSOR_HIDDEN);
6394 }
6395
6396 void
6397 ev_view_show_cursor (EvView *view)
6398 {
6399        ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
6400 }
6401
6402 gboolean
6403 ev_view_next_page (EvView *view)
6404 {
6405         int page, n_pages;
6406
6407         g_return_val_if_fail (EV_IS_VIEW (view), FALSE);
6408         
6409         if (!view->document)
6410                 return FALSE;
6411
6412         page = ev_document_model_get_page (view->model);
6413         n_pages = ev_document_get_n_pages (view->document);
6414
6415         if (view->dual_page)
6416                 page = page + 2; 
6417         else 
6418                 page = page + 1;
6419
6420         if (page < n_pages) {
6421                 ev_document_model_set_page (view->model, page);
6422                 return TRUE;
6423         } else if (view->dual_page && page == n_pages) {
6424                 ev_document_model_set_page (view->model, page - 1);
6425                 return TRUE;
6426         } else {
6427                 return FALSE;
6428         }
6429 }
6430
6431 gboolean
6432 ev_view_previous_page (EvView *view)
6433 {
6434         int page;
6435
6436         g_return_val_if_fail (EV_IS_VIEW (view), FALSE);
6437
6438         if (!view->document)
6439                 return FALSE;
6440
6441         page = ev_document_model_get_page (view->model);
6442
6443         if (view->dual_page)
6444                 page = page - 2; 
6445         else 
6446                 page = page - 1;
6447
6448         if (page >= 0) {
6449                 ev_document_model_set_page (view->model, page);
6450                 return TRUE;
6451         } else if (view->dual_page && page == -1) {
6452                 ev_document_model_set_page (view->model, 0);
6453                 return TRUE;
6454         } else {        
6455                 return FALSE;
6456         }
6457 }
6458