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