]> www.fi.muni.cz Git - evince.git/blob - libview/ev-view.c
[presentation] Fix fade animations
[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.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         N_SIGNALS
58 };
59
60 enum {
61         TARGET_DND_URI,
62         TARGET_DND_TEXT,
63         TARGET_DND_IMAGE
64 };
65
66 static guint signals[N_SIGNALS];
67
68 typedef enum {
69         EV_VIEW_FIND_NEXT,
70         EV_VIEW_FIND_PREV
71 } EvViewFindDirection;
72
73 #define ZOOM_IN_FACTOR  1.2
74 #define ZOOM_OUT_FACTOR (1.0/ZOOM_IN_FACTOR)
75
76 #define SCROLL_TIME 150
77
78 /*** Scrolling ***/
79 static void       ev_view_set_scroll_adjustments             (GtkLayout          *layout,
80                                                               GtkAdjustment      *hadjustment,
81                                                               GtkAdjustment      *vadjustment);
82 static void       view_update_range_and_current_page         (EvView             *view);
83 static void       set_scroll_adjustment                      (EvView             *view,
84                                                               GtkOrientation      orientation,
85                                                               GtkAdjustment      *adjustment);
86 static void       add_scroll_binding_keypad                  (GtkBindingSet      *binding_set,
87                                                               guint               keyval,
88                                                               GdkModifierType modifiers,
89                                                               GtkScrollType       scroll,
90                                                               gboolean            horizontal);
91 static void       ensure_rectangle_is_visible                (EvView             *view,
92                                                               GdkRectangle       *rect);
93
94 /*** Geometry computations ***/
95 static void       compute_border                             (EvView             *view,
96                                                               int                 width,
97                                                               int                 height,
98                                                               GtkBorder          *border);
99 static void       get_page_y_offset                          (EvView             *view,
100                                                               int                 page,
101                                                               int                *y_offset);
102 static gboolean   get_page_extents                           (EvView             *view,
103                                                               gint                page,
104                                                               GdkRectangle       *page_area,
105                                                               GtkBorder          *border);
106 static void       view_rect_to_doc_rect                      (EvView             *view,
107                                                               GdkRectangle       *view_rect,
108                                                               GdkRectangle       *page_area,
109                                                               EvRectangle        *doc_rect);
110 static void       doc_rect_to_view_rect                      (EvView             *view,
111                                                               int                 page,
112                                                               EvRectangle        *doc_rect,
113                                                               GdkRectangle       *view_rect);
114 static gboolean   get_dual_even_left                         (EvView             *view);
115 static void       find_page_at_location                      (EvView             *view,
116                                                               gdouble             x,
117                                                               gdouble             y,
118                                                               gint               *page,
119                                                               gint               *x_offset,
120                                                               gint               *y_offset);
121 static void       doc_point_to_view_point                    (EvView             *view,
122                                                               int                 page,
123                                                               EvPoint            *doc_point,
124                                                               GdkPoint           *view_point);
125 /*** Hyperrefs ***/
126 static EvLink *   ev_view_get_link_at_location               (EvView             *view,
127                                                               gdouble             x,
128                                                               gdouble             y);
129 static char*      tip_from_link                              (EvView             *view,
130                                                               EvLink             *link);
131 /*** Forms ***/
132 static EvFormField *ev_view_get_form_field_at_location       (EvView             *view,
133                                                                gdouble            x,
134                                                                gdouble            y);
135
136 /*** Annotations ***/
137 static EvAnnotation *ev_view_get_annotation_at_location      (EvView             *view,
138                                                               gdouble             x,
139                                                               gdouble             y);
140 static void          show_annotation_windows                 (EvView             *view,
141                                                               gint                page);
142 static void          hide_annotation_windows                 (EvView             *view,
143                                                               gint                page);
144 /*** GtkWidget implementation ***/
145 static void       ev_view_size_request_continuous_dual_page  (EvView             *view,
146                                                               GtkRequisition     *requisition);
147 static void       ev_view_size_request_continuous            (EvView             *view,
148                                                               GtkRequisition     *requisition);
149 static void       ev_view_size_request_dual_page             (EvView             *view,
150                                                               GtkRequisition     *requisition);
151 static void       ev_view_size_request_single_page           (EvView             *view,
152                                                               GtkRequisition     *requisition);
153 static void       ev_view_size_request                       (GtkWidget          *widget,
154                                                               GtkRequisition     *requisition);
155 static void       ev_view_size_allocate                      (GtkWidget          *widget,
156                                                               GtkAllocation      *allocation);
157 static void       ev_view_realize                            (GtkWidget          *widget);
158 static gboolean   ev_view_scroll_event                       (GtkWidget          *widget,
159                                                               GdkEventScroll     *event);
160 static gboolean   ev_view_expose_event                       (GtkWidget          *widget,
161                                                               GdkEventExpose     *event);
162 static gboolean   ev_view_popup_menu                         (GtkWidget          *widget);
163 static gboolean   ev_view_button_press_event                 (GtkWidget          *widget,
164                                                               GdkEventButton     *event);
165 static gboolean   ev_view_motion_notify_event                (GtkWidget          *widget,
166                                                               GdkEventMotion     *event);
167 static gboolean   ev_view_button_release_event               (GtkWidget          *widget,
168                                                               GdkEventButton     *event);
169 static gboolean   ev_view_enter_notify_event                 (GtkWidget          *widget,
170                                                               GdkEventCrossing   *event);
171 static gboolean   ev_view_leave_notify_event                 (GtkWidget          *widget,
172                                                               GdkEventCrossing   *event);
173 static void       ev_view_style_set                          (GtkWidget          *widget,
174                                                               GtkStyle           *old_style);
175 static void       ev_view_remove_all                         (EvView             *view);
176
177 static AtkObject *ev_view_get_accessible                     (GtkWidget *widget);
178
179 /*** Drawing ***/
180 static void       highlight_find_results                     (EvView             *view,
181                                                               int                 page);
182 static void       draw_one_page                              (EvView             *view,
183                                                               gint                page,
184                                                               cairo_t            *cr,
185                                                               GdkRectangle       *page_area,
186                                                               GtkBorder          *border,
187                                                               GdkRectangle       *expose_area,
188                                                               gboolean           *page_ready);
189 static void       show_loading_window                        (EvView             *view);
190 static void       hide_loading_window                        (EvView             *view);
191 static void       ev_view_reload_page                        (EvView             *view,
192                                                               gint                page,
193                                                               GdkRegion          *region);
194 static void       ev_view_loading_window_move                (EvView             *view);
195
196 /*** Callbacks ***/
197 static void       ev_view_change_page                        (EvView             *view,
198                                                               gint                new_page);
199 static void       job_finished_cb                            (EvPixbufCache      *pixbuf_cache,
200                                                               GdkRegion          *region,
201                                                               EvView             *view);
202 static void       ev_view_page_changed_cb                    (EvDocumentModel    *model,
203                                                               gint                old_page,
204                                                               gint                new_page,
205                                                               EvView             *view);
206 static void       on_adjustment_value_changed                (GtkAdjustment      *adjustment,
207                                                               EvView             *view);
208
209 /*** GObject ***/
210 static void       ev_view_finalize                           (GObject            *object);
211 static void       ev_view_destroy                            (GtkObject          *object);
212 static void       ev_view_class_init                         (EvViewClass        *class);
213 static void       ev_view_init                               (EvView             *view);
214
215 /*** Zoom and sizing ***/
216 static double   zoom_for_size_fit_width                      (gdouble doc_width,
217                                                               gdouble doc_height,
218                                                               int     target_width,
219                                                               int     target_height);
220 static double   zoom_for_size_fit_height                     (gdouble doc_width,
221                                                               gdouble doc_height,
222                                                               int     target_width,
223                                                               int     target_height);
224 static double   zoom_for_size_best_fit                       (gdouble doc_width,
225                                                               gdouble doc_height,
226                                                               int     target_width,
227                                                               int     target_height);
228 static void     ev_view_zoom_for_size                        (EvView *view,
229                                                               int     width,
230                                                               int     height);
231 static void     ev_view_zoom_for_size_continuous_and_dual_page (EvView *view,
232                                                                 int     width,
233                                                                 int     height);
234 static void     ev_view_zoom_for_size_continuous               (EvView *view,
235                                                                 int     width,
236                                                                 int     height);
237 static void     ev_view_zoom_for_size_dual_page                (EvView *view,
238                                                                 int     width,
239                                                                 int     height);
240 static void     ev_view_zoom_for_size_single_page              (EvView *view,
241                                                                 int     width,
242                                                                 int     height);
243 /*** Cursors ***/
244 static void       ev_view_set_cursor                         (EvView             *view,
245                                                               EvViewCursor        new_cursor);
246 static void       ev_view_handle_cursor_over_xy              (EvView *view,
247                                                               gint x,
248                                                               gint y);
249
250 /*** Find ***/
251 static gint         ev_view_find_get_n_results               (EvView             *view,
252                                                               gint                page);
253 static EvRectangle *ev_view_find_get_result                  (EvView             *view,
254                                                               gint                page,
255                                                               gint                result);
256 static void       jump_to_find_result                        (EvView             *view);
257 static void       jump_to_find_page                          (EvView             *view, 
258                                                               EvViewFindDirection direction,
259                                                               gint                shift);
260
261 /*** Selection ***/
262 static void       compute_selections                         (EvView             *view,
263                                                               EvSelectionStyle    style,
264                                                               GdkPoint           *start,
265                                                               GdkPoint           *stop);
266 static void       clear_selection                            (EvView             *view);
267 static void       clear_link_selected                        (EvView             *view);
268 static void       selection_free                             (EvViewSelection    *selection);
269 static char*      get_selected_text                          (EvView             *ev_view);
270 static void       ev_view_primary_get_cb                     (GtkClipboard       *clipboard,
271                                                               GtkSelectionData   *selection_data,
272                                                               guint               info,
273                                                               gpointer            data);
274 static void       ev_view_primary_clear_cb                   (GtkClipboard       *clipboard,
275                                                               gpointer            data);
276 static void       ev_view_update_primary_selection           (EvView             *ev_view);
277
278 G_DEFINE_TYPE (EvView, ev_view, GTK_TYPE_LAYOUT)
279
280 /* HeightToPage cache */
281 #define EV_HEIGHT_TO_PAGE_CACHE_KEY "ev-height-to-page-cache"
282
283 static void
284 build_height_to_page (EvHeightToPageCache *cache,
285                       EvDocument          *document,
286                       gint                 rotation)
287 {
288         gboolean swap, uniform, dual_even_left;
289         int i;
290         double uniform_height, page_height, next_page_height;
291         double saved_height;
292         gdouble u_width, u_height;
293         gint n_pages;
294
295         swap = (rotation == 90 || rotation == 270);
296
297         uniform = ev_document_is_page_size_uniform (document);
298         n_pages = ev_document_get_n_pages (document);
299         dual_even_left = (n_pages > 2);
300
301         g_free (cache->height_to_page);
302         g_free (cache->dual_height_to_page);
303
304         cache->rotation = rotation;
305         cache->height_to_page = g_new0 (gdouble, n_pages + 1);
306         cache->dual_height_to_page = g_new0 (gdouble, n_pages + 2);
307
308         if (uniform)
309                 ev_document_get_page_size (document, 0, &u_width, &u_height);
310
311         saved_height = 0;
312         for (i = 0; i <= n_pages; i++) {
313                 if (uniform) {
314                         uniform_height = swap ? u_width : u_height;
315                         cache->height_to_page[i] = i * uniform_height;
316                 } else {
317                         if (i < n_pages) {
318                                 gdouble w, h;
319
320                                 ev_document_get_page_size (document, i, &w, &h);
321                                 page_height = swap ? w : h;
322                         } else {
323                                 page_height = 0;
324                         }
325                         cache->height_to_page[i] = saved_height;
326                         saved_height += page_height;
327                 }
328         }
329
330         if (dual_even_left && !uniform) {
331                 gdouble w, h;
332
333                 ev_document_get_page_size (document, 0, &w, &h);
334                 saved_height = swap ? w : h;
335         } else {
336                 saved_height = 0;
337         }
338
339         for (i = dual_even_left; i < n_pages + 2; i += 2) {
340                 if (uniform) {
341                         uniform_height = swap ? u_width : u_height;
342                         cache->dual_height_to_page[i] = ((i + dual_even_left) / 2) * uniform_height;
343                         if (i + 1 < n_pages + 2)
344                                 cache->dual_height_to_page[i + 1] = ((i + dual_even_left) / 2) * uniform_height;
345                 } else {
346                         if (i + 1 < n_pages) {
347                                 gdouble w, h;
348
349                                 ev_document_get_page_size (document, i + 1, &w, &h);
350                                 next_page_height = swap ? w : h;
351                         } else {
352                                 next_page_height = 0;
353                         }
354
355                         if (i < n_pages) {
356                                 gdouble w, h;
357
358                                 ev_document_get_page_size (document, i, &w, &h);
359                                 page_height = swap ? w : h;
360                         } else {
361                                 page_height = 0;
362                         }
363
364                         if (i + 1 < n_pages + 2) {
365                                 cache->dual_height_to_page[i] = saved_height;
366                                 cache->dual_height_to_page[i + 1] = saved_height;
367                                 saved_height += MAX(page_height, next_page_height);
368                         } else {
369                                 cache->dual_height_to_page[i] = saved_height;
370                         }
371                 }
372         }
373 }
374
375 static void
376 ev_height_to_page_cache_get_height (EvHeightToPageCache *cache,
377                                     EvDocument          *document,
378                                     gint                 page,
379                                     gint                 rotation,
380                                     gdouble             *height,
381                                     gdouble             *dual_height)
382 {
383         if (cache->rotation != rotation)
384                 build_height_to_page (cache, document, rotation);
385
386         *height = cache->height_to_page[page];
387         *dual_height = cache->dual_height_to_page[page];
388 }
389
390 static void
391 ev_height_to_page_cache_free (EvHeightToPageCache *cache)
392 {
393         if (cache->height_to_page) {
394                 g_free (cache->height_to_page);
395                 cache->height_to_page = NULL;
396         }
397
398         if (cache->dual_height_to_page) {
399                 g_free (cache->dual_height_to_page);
400                 cache->dual_height_to_page = NULL;
401         }
402         g_free (cache);
403 }
404
405 static EvHeightToPageCache *
406 ev_view_get_height_to_page_cache (EvView *view)
407 {
408         EvHeightToPageCache *cache;
409
410         if (!view->document)
411                 return NULL;
412
413         cache = g_object_get_data (G_OBJECT (view->document), EV_HEIGHT_TO_PAGE_CACHE_KEY);
414         if (!cache) {
415                 cache = g_new0 (EvHeightToPageCache, 1);
416                 build_height_to_page (cache, view->document, view->rotation);
417                 g_object_set_data_full (G_OBJECT (view->document),
418                                         EV_HEIGHT_TO_PAGE_CACHE_KEY,
419                                         cache,
420                                         (GDestroyNotify)ev_height_to_page_cache_free);
421         }
422
423         return cache;
424 }
425
426 static void
427 ev_view_get_height_to_page (EvView *view,
428                             gint    page,
429                             gint   *height,
430                             gint   *dual_height)
431 {
432         gdouble h, dh;
433
434         if (!view->height_to_page_cache)
435                 return;
436
437         ev_height_to_page_cache_get_height (view->height_to_page_cache,
438                                             view->document,
439                                             page,
440                                             view->rotation,
441                                             &h, &dh);
442         if (height)
443                 *height = (gint)(h * view->scale + 0.5);
444
445         if (dual_height)
446                 *dual_height = (gint)(dh * view->scale + 0.5);
447 }
448
449 static gint
450 ev_view_get_scrollbar_size (EvView        *view,
451                             GtkOrientation orientation)
452 {
453         GtkWidget *widget = GTK_WIDGET (view);
454         GtkWidget *sb;
455         GtkWidget *swindow = gtk_widget_get_parent (GTK_WIDGET (view));
456         GtkAllocation allocation;
457         GtkRequisition req;
458         gint spacing;
459
460         if (!GTK_IS_SCROLLED_WINDOW (swindow))
461                 return 0;
462
463         gtk_widget_get_allocation (widget, &allocation);
464
465         if (orientation == GTK_ORIENTATION_VERTICAL) {
466                 if (allocation.height >= view->requisition.height)
467                         sb = gtk_scrolled_window_get_vscrollbar (GTK_SCROLLED_WINDOW (swindow));
468                 else
469                         return 0;
470         } else {
471                 if (allocation.width >= view->requisition.width)
472                         sb = gtk_scrolled_window_get_hscrollbar (GTK_SCROLLED_WINDOW (swindow));
473                 else
474                         return 0;
475         }
476
477         gtk_widget_style_get (swindow, "scrollbar_spacing", &spacing, NULL);
478         gtk_widget_size_request (sb, &req);
479
480         return (orientation == GTK_ORIENTATION_VERTICAL ? req.width : req.height) + spacing;
481 }
482
483 static void
484 scroll_to_point (EvView        *view,
485                  gdouble        x,
486                  gdouble        y,
487                  GtkOrientation orientation)
488 {
489         gdouble page_size;
490         gdouble upper, lower;
491
492         if (orientation == GTK_ORIENTATION_VERTICAL) {
493                 page_size = gtk_adjustment_get_page_size (view->vadjustment);
494                 upper = gtk_adjustment_get_upper (view->vadjustment);
495                 lower = gtk_adjustment_get_lower (view->vadjustment);
496
497                 if (view->continuous) {
498                         gtk_adjustment_clamp_page (view->vadjustment,
499                                                    y - view->spacing / 2,
500                                                    y + page_size);
501                 } else {
502                         gtk_adjustment_set_value (view->vadjustment,
503                                                   CLAMP (y, lower, upper - page_size));
504                 }
505         } else {
506                 page_size = gtk_adjustment_get_page_size (view->hadjustment);
507                 upper = gtk_adjustment_get_upper (view->hadjustment);
508                 lower = gtk_adjustment_get_lower (view->hadjustment);
509
510                 if (view->dual_page) {
511                         gtk_adjustment_clamp_page (view->hadjustment, x,
512                                                    x + page_size);
513                 } else {
514                         gtk_adjustment_set_value (view->hadjustment,
515                                                   CLAMP (x, lower, upper - page_size));
516                 }
517         }
518 }
519
520 static void
521 ev_view_scroll_to_page_position (EvView *view, GtkOrientation orientation)
522 {
523         gdouble x, y;
524
525         if (!view->document)
526                 return;
527
528         if ((orientation == GTK_ORIENTATION_VERTICAL && view->pending_point.y == 0) ||
529             (orientation == GTK_ORIENTATION_HORIZONTAL && view->pending_point.x == 0)) {
530                 GdkRectangle page_area;
531                 GtkBorder    border;
532
533                 get_page_extents (view, view->current_page, &page_area, &border);
534                 x = page_area.x;
535                 y = page_area.y;
536         } else {
537                 GdkPoint view_point;
538
539                 doc_point_to_view_point (view, view->current_page,
540                                          &view->pending_point, &view_point);
541                 x = view_point.x;
542                 y = view_point.y;
543         }
544
545         scroll_to_point (view, x, y, orientation);
546 }
547
548 static void
549 view_set_adjustment_values (EvView         *view,
550                             GtkOrientation  orientation)
551 {
552         GtkWidget *widget = GTK_WIDGET (view);
553         GtkAdjustment *adjustment;
554         GtkAllocation allocation;
555         int req_size;
556         int alloc_size;
557         gdouble page_size;
558         gdouble value;
559         gdouble upper;
560         double factor;
561         gint new_value;
562
563         gtk_widget_get_allocation (widget, &allocation);
564
565         if (orientation == GTK_ORIENTATION_HORIZONTAL)  {
566                 req_size = view->requisition.width;
567                 alloc_size = allocation.width;
568                 adjustment = view->hadjustment;
569         } else {
570                 req_size = view->requisition.height;
571                 alloc_size = allocation.height;
572                 adjustment = view->vadjustment;
573         }
574
575         if (!adjustment)
576                 return;
577
578         factor = 1.0;
579         value = gtk_adjustment_get_value (adjustment);
580         upper = gtk_adjustment_get_upper (adjustment);
581         page_size = gtk_adjustment_get_page_size (adjustment);
582
583         switch (view->pending_scroll) {
584                 case SCROLL_TO_KEEP_POSITION:
585                 case SCROLL_TO_FIND_LOCATION:
586                         factor = value / upper;
587                         break;
588                 case SCROLL_TO_PAGE_POSITION:
589                         break;
590                 case SCROLL_TO_CENTER:
591                         factor = (value + page_size * 0.5) / upper;
592                         break;
593         }
594
595         upper = MAX (alloc_size, req_size);
596         page_size = alloc_size;
597
598         gtk_adjustment_set_page_size (adjustment, page_size);
599         gtk_adjustment_set_step_increment (adjustment, alloc_size * 0.1);
600         gtk_adjustment_set_page_increment (adjustment, alloc_size * 0.9);
601         gtk_adjustment_set_lower (adjustment, 0);
602         gtk_adjustment_set_upper (adjustment, upper);
603
604         /*
605          * We add 0.5 to the values before to average out our rounding errors.
606          */
607         switch (view->pending_scroll) {
608                 case SCROLL_TO_KEEP_POSITION:
609                 case SCROLL_TO_FIND_LOCATION:
610                         new_value = CLAMP (upper * factor + 0.5, 0, upper - page_size);
611                         gtk_adjustment_set_value (adjustment, (int)new_value);
612                         break;
613                 case SCROLL_TO_PAGE_POSITION:
614                         ev_view_scroll_to_page_position (view, orientation);
615                         break;
616                 case SCROLL_TO_CENTER:
617                         new_value = CLAMP (upper * factor - page_size * 0.5 + 0.5,
618                                            0, upper - page_size);
619                         gtk_adjustment_set_value (adjustment, (int)new_value);
620                         break;
621         }
622
623         gtk_adjustment_changed (adjustment);
624 }
625
626 static void
627 view_update_range_and_current_page (EvView *view)
628 {
629         gint start = view->start_page;
630         gint end = view->end_page;
631
632         if (ev_document_get_n_pages (view->document) <= 0 ||
633             !ev_document_check_dimensions (view->document))
634                 return;
635
636         if (view->continuous) {
637                 GdkRectangle current_area, unused, page_area;
638                 GtkBorder border;
639                 gboolean found = FALSE;
640                 gint area_max = -1, area;
641                 gint best_current_page = -1;
642                 int i, j = 0;
643
644                 if (!(view->vadjustment && view->hadjustment))
645                         return;
646
647                 current_area.x = gtk_adjustment_get_value (view->hadjustment);
648                 current_area.width = gtk_adjustment_get_page_size (view->hadjustment);
649                 current_area.y = gtk_adjustment_get_value (view->vadjustment);
650                 current_area.height = gtk_adjustment_get_page_size (view->vadjustment);
651
652                 for (i = 0; i < ev_document_get_n_pages (view->document); i++) {
653
654                         get_page_extents (view, i, &page_area, &border);
655
656                         if (gdk_rectangle_intersect (&current_area, &page_area, &unused)) {
657                                 area = unused.width * unused.height;
658
659                                 if (!found) {
660                                         area_max = area;
661                                         view->start_page = i;
662                                         found = TRUE;
663                                         best_current_page = i;
664                                 }
665                                 if (area > area_max) {
666                                         best_current_page = (area == area_max) ? MIN (i, best_current_page) : i;
667                                         area_max = area;
668                                 }
669
670                                 view->end_page = i;
671                                 j = 0;
672                         } else if (found && view->current_page <= view->end_page) {
673                                 if (view->dual_page && j < 1) {
674                                         /* In dual mode  we stop searching
675                                          * after two consecutive non-visible pages.
676                                          */
677                                         j++;
678                                         continue;
679                                 }
680                                 break;
681                         }
682                 }
683
684                 if (view->pending_scroll == SCROLL_TO_KEEP_POSITION) {
685                         best_current_page = MAX (best_current_page, view->start_page);
686
687                         if (view->current_page != best_current_page) {
688                                 view->current_page = best_current_page;
689                                 hide_loading_window (view);
690                                 ev_document_model_set_page (view->model, best_current_page);
691                         }
692                 }
693         } else if (view->dual_page) {
694                 if (view->current_page % 2 == get_dual_even_left (view)) {
695                         view->start_page = view->current_page;
696                         if (view->current_page + 1 < ev_document_get_n_pages (view->document))
697                                 view->end_page = view->start_page + 1;
698                         else
699                                 view->end_page = view->start_page;
700                 } else {
701                         if (view->current_page < 1)
702                                 view->start_page = view->current_page;
703                         else
704                                 view->start_page = view->current_page - 1;
705                         view->end_page = view->current_page;
706                 }
707         } else {
708                 view->start_page = view->current_page;
709                 view->end_page = view->current_page;
710         }
711
712         if (view->start_page == -1 || view->end_page == -1)
713                 return;
714
715         if (start != view->start_page || end != view->end_page) {
716                 gint i;
717
718                 for (i = start; i < view->start_page && start != -1; i++) {
719                         hide_annotation_windows (view, i);
720                 }
721
722                 for (i = end; i > view->end_page && end != -1; i--) {
723                         hide_annotation_windows (view, i);
724                 }
725         }
726
727         ev_page_cache_set_page_range (view->page_cache,
728                                       view->start_page,
729                                       view->end_page);
730         ev_pixbuf_cache_set_page_range (view->pixbuf_cache,
731                                         view->start_page,
732                                         view->end_page,
733                                         view->selection_info.selections);
734
735         if (ev_pixbuf_cache_get_surface (view->pixbuf_cache, view->current_page))
736             gtk_widget_queue_draw (GTK_WIDGET (view));
737 }
738
739 static void
740 set_scroll_adjustment (EvView *view,
741                        GtkOrientation  orientation,
742                        GtkAdjustment  *adjustment)
743 {
744         GtkAdjustment **to_set;
745
746         if (orientation == GTK_ORIENTATION_HORIZONTAL)
747                 to_set = &view->hadjustment;
748         else
749                 to_set = &view->vadjustment;
750
751         if (*to_set != adjustment) {
752                 if (*to_set) {
753                         g_signal_handlers_disconnect_by_func (*to_set,
754                                                               (gpointer) on_adjustment_value_changed,
755                                                               view);
756                         g_object_unref (*to_set);
757                 }
758
759                 *to_set = adjustment;
760                 view_set_adjustment_values (view, orientation);
761
762                 if (*to_set) {
763                         g_object_ref (*to_set);
764                         g_signal_connect (*to_set, "value_changed",
765                                           G_CALLBACK (on_adjustment_value_changed), view);
766                 }
767         }
768 }
769
770 static void
771 ev_view_set_scroll_adjustments (GtkLayout      *layout,
772                                 GtkAdjustment  *hadjustment,
773                                 GtkAdjustment  *vadjustment)
774 {
775         EvView *view = EV_VIEW (layout);
776         
777         set_scroll_adjustment (view, GTK_ORIENTATION_HORIZONTAL, hadjustment);
778         set_scroll_adjustment (view, GTK_ORIENTATION_VERTICAL, vadjustment);
779         
780         on_adjustment_value_changed (NULL, view);
781 }
782
783 static void
784 add_scroll_binding_keypad (GtkBindingSet  *binding_set,
785                            guint           keyval,
786                            GdkModifierType modifiers,
787                            GtkScrollType   scroll,
788                            gboolean        horizontal)
789 {
790   guint keypad_keyval = keyval - GDK_Left + GDK_KP_Left;
791
792   gtk_binding_entry_add_signal (binding_set, keyval, modifiers,
793                                 "binding_activated", 2,
794                                 GTK_TYPE_SCROLL_TYPE, scroll,
795                                 G_TYPE_BOOLEAN, horizontal);
796   gtk_binding_entry_add_signal (binding_set, keypad_keyval, modifiers,
797                                 "binding_activated", 2,
798                                 GTK_TYPE_SCROLL_TYPE, scroll,
799                                 G_TYPE_BOOLEAN, horizontal);
800 }
801
802 static gdouble
803 compute_scroll_increment (EvView        *view,
804                           GtkScrollType  scroll)
805 {
806         GtkWidget *widget = GTK_WIDGET (view);
807         GtkAdjustment *adjustment = view->vadjustment;
808         GdkRegion *text_region, *region;
809         GtkAllocation allocation;
810         gint page;
811         GdkRectangle rect;
812         EvRectangle doc_rect;
813         GdkRectangle page_area;
814         GtkBorder border;
815         GdkRectangle *recs;
816         gint n_recs;
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 || gdk_region_empty (text_region))
826                 return gtk_adjustment_get_page_size (adjustment);
827
828         gtk_widget_get_allocation (widget, &allocation);
829         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 = gdk_region_rectangle (&rect);
842
843         gdk_region_intersect (region, text_region);
844         gdk_region_get_rectangles (region, &recs, &n_recs);
845         gdk_region_destroy (region);
846         if (n_recs > 0) {
847                 EvRenderContext *rc;
848                 EvPage  *ev_page;
849
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 = recs[0].x + 0.5;
855                 doc_rect.y1 = doc_rect.y2 = recs[0].y + 0.5;
856
857                 ev_document_doc_mutex_lock ();
858                 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                 g_free (recs);
865                 gdk_region_get_rectangles (region, &recs, &n_recs);
866                 gdk_region_destroy (region);
867                 if (n_recs > 0) {
868                         fraction = 1 - (recs[0].height / gtk_adjustment_get_page_size (adjustment));
869                 }
870                 g_free (recs);
871         }
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 static gboolean
1102 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         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         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 (! 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         GdkRegion *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 gdk_region_point_in (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                     gdk_region_point_in (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                                GList        *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         GList *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->drag_info.in_drag) {
1837                 if (view->cursor != EV_VIEW_CURSOR_DRAG)
1838                         ev_view_set_cursor (view, EV_VIEW_CURSOR_DRAG);
1839                 return;
1840         }
1841
1842         if (view->scroll_info.autoscrolling) {
1843                 if (view->cursor != EV_VIEW_CURSOR_AUTOSCROLL)
1844                         ev_view_set_cursor (view, EV_VIEW_CURSOR_AUTOSCROLL);
1845                 return;
1846         }
1847
1848         link = ev_view_get_link_at_location (view, x, y);
1849         if (link) {
1850                 ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1851         } else if ((field = ev_view_get_form_field_at_location (view, x, y))) {
1852                 if (field->is_read_only) {
1853                         if (view->cursor == EV_VIEW_CURSOR_LINK ||
1854                             view->cursor == EV_VIEW_CURSOR_IBEAM ||
1855                             view->cursor == EV_VIEW_CURSOR_DRAG)
1856                                 ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
1857                 } else if (EV_IS_FORM_FIELD_TEXT (field)) {
1858                         ev_view_set_cursor (view, EV_VIEW_CURSOR_IBEAM);
1859                 } else {
1860                         ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1861                 }
1862         } else if ((annot = ev_view_get_annotation_at_location (view, x, y))) {
1863                 ev_view_set_cursor (view, EV_VIEW_CURSOR_LINK);
1864         } else if (location_in_text (view, x + view->scroll_x, y + view->scroll_y)) {
1865                 ev_view_set_cursor (view, EV_VIEW_CURSOR_IBEAM);
1866         } else {
1867                 if (view->cursor == EV_VIEW_CURSOR_LINK ||
1868                     view->cursor == EV_VIEW_CURSOR_IBEAM ||
1869                     view->cursor == EV_VIEW_CURSOR_DRAG ||
1870                     view->cursor == EV_VIEW_CURSOR_AUTOSCROLL)
1871                         ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
1872         }
1873
1874         if (link || annot)
1875                 g_object_set (view, "has-tooltip", TRUE, NULL);
1876 }
1877
1878 /*** Images ***/
1879 static EvImage *
1880 ev_view_get_image_at_location (EvView  *view,
1881                                gdouble  x,
1882                                gdouble  y)
1883 {
1884         gint page = -1;
1885         gint x_new = 0, y_new = 0;
1886         GList *image_mapping;
1887
1888         if (!EV_IS_DOCUMENT_IMAGES (view->document))
1889                 return NULL;
1890
1891         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
1892                 return NULL;
1893
1894         image_mapping = ev_page_cache_get_image_mapping (view->page_cache, page);
1895
1896         if (image_mapping)
1897                 return ev_mapping_list_get_data (image_mapping, x_new, y_new);
1898         else
1899                 return NULL;
1900 }
1901
1902 /*** Forms ***/
1903 static EvFormField *
1904 ev_view_get_form_field_at_location (EvView  *view,
1905                                     gdouble  x,
1906                                     gdouble  y)
1907 {
1908         gint page = -1;
1909         gint x_new = 0, y_new = 0;
1910         GList *forms_mapping;
1911         
1912         if (!EV_IS_DOCUMENT_FORMS (view->document))
1913                 return NULL;
1914
1915         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
1916                 return NULL;
1917
1918         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache, page);
1919
1920         if (forms_mapping)
1921                 return ev_mapping_list_get_data (forms_mapping, x_new, y_new);
1922         else
1923                 return NULL;
1924 }
1925
1926 static GdkRegion *
1927 ev_view_form_field_get_region (EvView      *view,
1928                                EvFormField *field)
1929 {
1930         GdkRectangle view_area;
1931         GList       *forms_mapping;
1932
1933         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
1934                                                               field->page->index);
1935         ev_view_get_area_from_mapping (view, field->page->index,
1936                                        forms_mapping,
1937                                        field, &view_area);
1938
1939         return gdk_region_rectangle (&view_area);
1940 }
1941
1942 static gboolean
1943 ev_view_forms_remove_widgets (EvView *view)
1944 {
1945         ev_view_remove_all (view);
1946
1947         return FALSE;
1948 }
1949
1950 static void
1951 ev_view_form_field_destroy (GtkWidget *widget,
1952                             EvView    *view)
1953 {
1954         g_idle_add ((GSourceFunc)ev_view_forms_remove_widgets, view);
1955 }
1956
1957 static GtkWidget *
1958 ev_view_form_field_button_create_widget (EvView      *view,
1959                                          EvFormField *field)
1960 {
1961         EvFormFieldButton *field_button = EV_FORM_FIELD_BUTTON (field);
1962         GdkRegion         *field_region = NULL;
1963         
1964         switch (field_button->type) {
1965                 case EV_FORM_FIELD_BUTTON_PUSH:
1966                         return NULL;
1967                 case EV_FORM_FIELD_BUTTON_CHECK:
1968                 case EV_FORM_FIELD_BUTTON_RADIO: {
1969                         gboolean  state;
1970                         GList    *forms_mapping, *l;
1971
1972                         state = ev_document_forms_form_field_button_get_state (EV_DOCUMENT_FORMS (view->document),
1973                                                                                field);
1974
1975                         /* FIXME: it actually depends on NoToggleToOff flags */
1976                         if (field_button->type == EV_FORM_FIELD_BUTTON_RADIO &&
1977                             state && field_button->state)
1978                                 return NULL;
1979                         
1980                         field_region = ev_view_form_field_get_region (view, field);
1981
1982                         /* For radio buttons and checkbox buttons that are in a set
1983                          * we need to update also the region for the current selected item
1984                          */
1985                         forms_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
1986                                                                               field->page->index);
1987                         for (l = forms_mapping; l; l = g_list_next (l)) {
1988                                 EvFormField *button = ((EvMapping *)(l->data))->data;
1989                                 GdkRegion   *button_region;
1990
1991                                 if (button->id == field->id)
1992                                         continue;
1993
1994                                 /* FIXME: only buttons in the same group should be updated */
1995                                 if (!EV_IS_FORM_FIELD_BUTTON (button) ||
1996                                     EV_FORM_FIELD_BUTTON (button)->type != field_button->type ||
1997                                     EV_FORM_FIELD_BUTTON (button)->state != TRUE)
1998                                         continue;
1999
2000                                 button_region = ev_view_form_field_get_region (view, button);
2001                                 gdk_region_union (field_region, button_region);
2002                                 gdk_region_destroy (button_region);
2003                         }
2004                         
2005                         ev_document_forms_form_field_button_set_state (EV_DOCUMENT_FORMS (view->document),
2006                                                                        field, !state);
2007                         field_button->state = !state;
2008                 }
2009                         break;
2010         }
2011
2012         ev_view_reload_page (view, field->page->index, field_region);
2013         gdk_region_destroy (field_region);
2014         
2015         return NULL;
2016 }
2017
2018 static void
2019 ev_view_form_field_text_save (EvView    *view,
2020                               GtkWidget *widget)
2021 {
2022         EvFormField *field;
2023
2024         if (!view->document)
2025                 return;
2026         
2027         field = g_object_get_data (G_OBJECT (widget), "form-field");
2028         
2029         if (field->changed) {
2030                 EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2031                 GdkRegion       *field_region;
2032
2033                 field_region = ev_view_form_field_get_region (view, field);
2034                 
2035                 ev_document_forms_form_field_text_set_text (EV_DOCUMENT_FORMS (view->document),
2036                                                             field, field_text->text);
2037                 field->changed = FALSE;
2038                 ev_view_reload_page (view, field->page->index, field_region);
2039                 gdk_region_destroy (field_region);
2040         }
2041 }
2042
2043 static void
2044 ev_view_form_field_text_changed (GtkWidget   *widget,
2045                                  EvFormField *field)
2046 {
2047         EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2048         gchar           *text = NULL;
2049
2050         if (GTK_IS_ENTRY (widget)) {
2051                 text = g_strdup (gtk_entry_get_text (GTK_ENTRY (widget)));
2052         } else if (GTK_IS_TEXT_BUFFER (widget)) {
2053                 GtkTextIter start, end;
2054
2055                 gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (widget), &start, &end);
2056                 text = gtk_text_buffer_get_text (GTK_TEXT_BUFFER (widget),
2057                                                  &start, &end, FALSE);
2058         }
2059
2060         if (!field_text->text ||
2061             (field_text->text && g_ascii_strcasecmp (field_text->text, text) != 0)) {
2062                 g_free (field_text->text);
2063                 field_text->text = text;
2064                 field->changed = TRUE;
2065         }
2066 }
2067
2068 static GtkWidget *
2069 ev_view_form_field_text_create_widget (EvView      *view,
2070                                        EvFormField *field)
2071 {
2072         EvFormFieldText *field_text = EV_FORM_FIELD_TEXT (field);
2073         GtkWidget       *text = NULL;
2074         gchar           *txt;
2075
2076         txt = ev_document_forms_form_field_text_get_text (EV_DOCUMENT_FORMS (view->document),
2077                                                           field);
2078
2079         switch (field_text->type) {
2080                 case EV_FORM_FIELD_TEXT_FILE_SELECT:
2081                         /* TODO */
2082                 case EV_FORM_FIELD_TEXT_NORMAL:
2083                         text = gtk_entry_new ();
2084                         gtk_entry_set_has_frame (GTK_ENTRY (text), FALSE);
2085                         gtk_entry_set_max_length (GTK_ENTRY (text), field_text->max_len);
2086                         gtk_entry_set_visibility (GTK_ENTRY (text), !field_text->is_password);
2087                         
2088                         if (txt) {
2089                                 gtk_entry_set_text (GTK_ENTRY (text), txt);
2090                                 g_free (txt);
2091                         }
2092
2093                         g_signal_connect (text, "changed",
2094                                           G_CALLBACK (ev_view_form_field_text_changed),
2095                                           field);
2096                         g_signal_connect_after (text, "activate",
2097                                                 G_CALLBACK (ev_view_form_field_destroy),
2098                                                 view);
2099                         break;
2100                 case EV_FORM_FIELD_TEXT_MULTILINE: {
2101                         GtkTextBuffer *buffer;
2102                 
2103                         text = gtk_text_view_new ();
2104                         buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (text));
2105                         
2106                         if (txt) {
2107                                 gtk_text_buffer_set_text (buffer, txt, -1);
2108                                 g_free (txt);
2109                         }
2110                         
2111                         g_signal_connect (buffer, "changed",
2112                                           G_CALLBACK (ev_view_form_field_text_changed),
2113                                           field);
2114                 }
2115                         break;
2116         }                       
2117
2118         g_object_weak_ref (G_OBJECT (text),
2119                            (GWeakNotify)ev_view_form_field_text_save,
2120                            view);
2121
2122         return text;
2123 }
2124
2125 static void
2126 ev_view_form_field_choice_save (EvView    *view,
2127                                 GtkWidget *widget)
2128 {
2129         EvFormField *field;
2130
2131         if (!view->document)
2132                 return;
2133         
2134         field = g_object_get_data (G_OBJECT (widget), "form-field");
2135
2136         if (field->changed) {
2137                 GList             *l;
2138                 EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2139                 GdkRegion         *field_region;
2140
2141                 field_region = ev_view_form_field_get_region (view, field);
2142
2143                 if (field_choice->is_editable) {
2144                         ev_document_forms_form_field_choice_set_text (EV_DOCUMENT_FORMS (view->document),
2145                                                                       field, field_choice->text);
2146                 } else {
2147                         ev_document_forms_form_field_choice_unselect_all (EV_DOCUMENT_FORMS (view->document), field);
2148                         for (l = field_choice->selected_items; l; l = g_list_next (l)) {
2149                                 ev_document_forms_form_field_choice_select_item (EV_DOCUMENT_FORMS (view->document),
2150                                                                                  field,
2151                                                                                  GPOINTER_TO_INT (l->data));
2152                         }
2153                 }
2154                 field->changed = FALSE;
2155                 ev_view_reload_page (view, field->page->index, field_region);
2156                 gdk_region_destroy (field_region);
2157         }
2158 }
2159
2160 static void
2161 ev_view_form_field_choice_changed (GtkWidget   *widget,
2162                                    EvFormField *field)
2163 {
2164         EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2165         
2166         if (GTK_IS_COMBO_BOX (widget)) {
2167                 gint item;
2168                 
2169                 item = gtk_combo_box_get_active (GTK_COMBO_BOX (widget));
2170                 if (!field_choice->selected_items ||
2171                     GPOINTER_TO_INT (field_choice->selected_items->data) != item) {
2172                         g_list_free (field_choice->selected_items);
2173                         field_choice->selected_items = NULL;
2174                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2175                                                                        GINT_TO_POINTER (item));
2176                         field->changed = TRUE;
2177                 }
2178
2179                 if (GTK_IS_COMBO_BOX_ENTRY (widget)) {
2180                         gchar *text;
2181                         
2182                         text = gtk_combo_box_get_active_text (GTK_COMBO_BOX (widget));
2183                         if (!field_choice->text ||
2184                             (field_choice->text && g_ascii_strcasecmp (field_choice->text, text) != 0)) {
2185                                 g_free (field_choice->text);
2186                                 field_choice->text = text;
2187                                 field->changed = TRUE;
2188                         }
2189                 }
2190         } else if (GTK_IS_TREE_SELECTION (widget)) {
2191                 GtkTreeSelection *selection = GTK_TREE_SELECTION (widget);
2192                 GtkTreeModel     *model;
2193                 GList            *items, *l;
2194                 
2195                 items = gtk_tree_selection_get_selected_rows (selection, &model);
2196                 g_list_free (field_choice->selected_items);
2197                 field_choice->selected_items = NULL;
2198
2199                 for (l = items; l && l->data; l = g_list_next (l)) {
2200                         GtkTreeIter  iter;
2201                         GtkTreePath *path = (GtkTreePath *)l->data;
2202                         gint         item;
2203                         
2204                         gtk_tree_model_get_iter (model, &iter, path);
2205                         gtk_tree_model_get (model, &iter, 1, &item, -1);
2206
2207                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2208                                                                        GINT_TO_POINTER (item));
2209
2210                         gtk_tree_path_free (path);
2211                 }
2212
2213                 g_list_free (items);
2214
2215                 field->changed = TRUE;
2216         }
2217 }
2218
2219 static GtkWidget *
2220 ev_view_form_field_choice_create_widget (EvView      *view,
2221                                          EvFormField *field)
2222 {
2223         EvFormFieldChoice *field_choice = EV_FORM_FIELD_CHOICE (field);
2224         GtkWidget         *choice;
2225         GtkTreeModel      *model;
2226         gint               n_items, i;
2227         gint               selected_item = 0;
2228
2229         n_items = ev_document_forms_form_field_choice_get_n_items (EV_DOCUMENT_FORMS (view->document),
2230                                                                    field);
2231         model = GTK_TREE_MODEL (gtk_list_store_new (2, G_TYPE_STRING, G_TYPE_INT));
2232         for (i = 0; i < n_items; i++) {
2233                 GtkTreeIter iter;
2234                 gchar      *item;
2235
2236                 item = ev_document_forms_form_field_choice_get_item (EV_DOCUMENT_FORMS (view->document),
2237                                                                      field, i);
2238                 if (ev_document_forms_form_field_choice_is_item_selected (
2239                             EV_DOCUMENT_FORMS (view->document), field, i)) {
2240                         selected_item = i;
2241                         /* FIXME: we need a get_selected_items function in poppler */
2242                         field_choice->selected_items = g_list_prepend (field_choice->selected_items,
2243                                                                        GINT_TO_POINTER (i));
2244                 }
2245                 
2246                 if (item) {
2247                         gtk_list_store_append (GTK_LIST_STORE (model), &iter);
2248                         gtk_list_store_set (GTK_LIST_STORE (model), &iter,
2249                                             0, item,
2250                                             1, i,
2251                                             -1);
2252                         g_free (item);
2253                 }
2254         }
2255
2256         if (field_choice->type == EV_FORM_FIELD_CHOICE_LIST) {
2257                 GtkCellRenderer  *renderer;
2258                 GtkWidget        *tree_view;
2259                 GtkTreeSelection *selection;
2260
2261                 tree_view = gtk_tree_view_new_with_model (model);
2262                 gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (tree_view), FALSE);
2263
2264                 selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (tree_view));
2265                 if (field_choice->multi_select) {
2266                         gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE);
2267                 }
2268
2269                 /* TODO: set selected items */
2270
2271                 renderer = gtk_cell_renderer_text_new ();
2272                 gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (tree_view),
2273                                                              0,
2274                                                              "choix", renderer,
2275                                                              "text", 0,
2276                                                              NULL);
2277
2278                 choice = gtk_scrolled_window_new (NULL, NULL);
2279                 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (choice),
2280                                                 GTK_POLICY_AUTOMATIC,
2281                                                 GTK_POLICY_AUTOMATIC);
2282                 gtk_container_add (GTK_CONTAINER (choice), tree_view);
2283                 gtk_widget_show (tree_view);
2284
2285                 g_signal_connect (selection, "changed",
2286                                   G_CALLBACK (ev_view_form_field_choice_changed),
2287                                   field);
2288                 g_signal_connect_after (selection, "changed",
2289                                         G_CALLBACK (ev_view_form_field_destroy),
2290                                         view);
2291         } else if (field_choice->is_editable) { /* ComboBoxEntry */
2292                 gchar *text;
2293                 
2294                 choice = gtk_combo_box_entry_new_with_model (model, 0);
2295                 text = ev_document_forms_form_field_choice_get_text (EV_DOCUMENT_FORMS (view->document), field);
2296                 if (text) {
2297                         gtk_entry_set_text (GTK_ENTRY (gtk_bin_get_child (GTK_BIN (choice))), text);
2298                         g_free (text);
2299                 }
2300
2301                 g_signal_connect (choice, "changed",
2302                                   G_CALLBACK (ev_view_form_field_choice_changed),
2303                                   field);
2304                 g_signal_connect_after (gtk_bin_get_child (GTK_BIN (choice)),
2305                                         "activate",
2306                                         G_CALLBACK (ev_view_form_field_destroy),
2307                                         view);
2308         } else { /* ComboBoxText */
2309                 GtkCellRenderer *renderer;
2310
2311                 choice = gtk_combo_box_new_with_model (model);
2312                 renderer = gtk_cell_renderer_text_new ();
2313                 gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (choice),
2314                                             renderer, TRUE);
2315                 gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (choice),
2316                                                 renderer,
2317                                                 "text", 0,
2318                                                 NULL);
2319                 gtk_combo_box_set_active (GTK_COMBO_BOX (choice), selected_item);
2320                 gtk_combo_box_popup (GTK_COMBO_BOX (choice));
2321                 
2322                 g_signal_connect (choice, "changed",
2323                                   G_CALLBACK (ev_view_form_field_choice_changed),
2324                                   field);
2325                 g_signal_connect_after (choice, "changed",
2326                                         G_CALLBACK (ev_view_form_field_destroy),
2327                                         view);
2328         }
2329
2330         g_object_unref (model);
2331
2332         g_object_weak_ref (G_OBJECT (choice),
2333                            (GWeakNotify)ev_view_form_field_choice_save,
2334                            view);
2335
2336         return choice;
2337 }
2338
2339 static void
2340 ev_view_handle_form_field (EvView      *view,
2341                            EvFormField *field,
2342                            gdouble      x,
2343                            gdouble      y)
2344 {
2345         GtkWidget   *field_widget = NULL;
2346         GList       *form_field_mapping;
2347         GdkRectangle view_area;
2348
2349         if (field->is_read_only)
2350                 return;
2351         
2352         if (EV_IS_FORM_FIELD_BUTTON (field)) {
2353                 field_widget = ev_view_form_field_button_create_widget (view, field);
2354         } else if (EV_IS_FORM_FIELD_TEXT (field)) {
2355                 field_widget = ev_view_form_field_text_create_widget (view, field);
2356         } else if (EV_IS_FORM_FIELD_CHOICE (field)) {
2357                 field_widget = ev_view_form_field_choice_create_widget (view, field);
2358         } else if (EV_IS_FORM_FIELD_SIGNATURE (field)) {
2359                 /* TODO */
2360         }
2361
2362         /* Form field doesn't require a widget */
2363         if (!field_widget)
2364                 return;
2365
2366         g_object_set_data_full (G_OBJECT (field_widget), "form-field",
2367                                 g_object_ref (field),
2368                                 (GDestroyNotify)g_object_unref);
2369
2370         form_field_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
2371                                                                    field->page->index);
2372         ev_view_get_area_from_mapping (view, field->page->index,
2373                                        form_field_mapping,
2374                                        field, &view_area);
2375
2376         gtk_layout_put (GTK_LAYOUT (view), field_widget, view_area.x, view_area.y);
2377         gtk_widget_show (field_widget);
2378         gtk_widget_grab_focus (field_widget);
2379 }
2380
2381 /* Annotations */
2382 static EvViewWindowChild *
2383 ev_view_get_window_child (EvView    *view,
2384                           GtkWidget *window)
2385 {
2386         GList *children = view->window_children;
2387
2388         while (children) {
2389                 EvViewWindowChild *child;
2390
2391                 child = (EvViewWindowChild *)children->data;
2392                 children = children->next;
2393
2394                 if (child->window == window)
2395                         return child;
2396         }
2397
2398         return NULL;
2399 }
2400
2401 static void
2402 ev_view_window_child_move (EvView            *view,
2403                            EvViewWindowChild *child,
2404                            gint               x,
2405                            gint               y)
2406 {
2407         child->x = x;
2408         child->y = y;
2409         gtk_window_move (GTK_WINDOW (child->window),
2410                          MAX (child->parent_x, x),
2411                          MAX (child->parent_y, y));
2412 }
2413
2414 static void
2415 ev_view_window_child_move_with_parent (EvView    *view,
2416                                        GtkWidget *window)
2417 {
2418         EvViewWindowChild *child;
2419         gint               root_x, root_y;
2420
2421         child = ev_view_get_window_child (view, window);
2422         gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
2423                                &root_x, &root_y);
2424         if (root_x != child->parent_x || root_y != child->parent_y) {
2425                 gint dest_x, dest_y;
2426
2427                 dest_x = child->x + (root_x - child->parent_x);
2428                 dest_y = child->y + (root_y - child->parent_y);
2429                 child->parent_x = root_x;
2430                 child->parent_y = root_y;
2431                 ev_view_window_child_move (view, child, dest_x, dest_y);
2432         }
2433
2434         if (child->visible && !gtk_widget_get_visible (window))
2435                 gtk_widget_show (window);
2436 }
2437
2438 static void
2439 ev_view_window_child_put (EvView    *view,
2440                           GtkWidget *window,
2441                           guint      page,
2442                           gint       x,
2443                           gint       y,
2444                           gdouble    orig_x,
2445                           gdouble    orig_y)
2446 {
2447         EvViewWindowChild *child;
2448         gint               root_x, root_y;
2449
2450         gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
2451                                &root_x, &root_y);
2452
2453         child = g_new0 (EvViewWindowChild, 1);
2454         child->window = window;
2455         child->page = page;
2456         child->orig_x = orig_x;
2457         child->orig_y = orig_y;
2458         child->parent_x = root_x;
2459         child->parent_y = root_y;
2460         child->visible = ev_annotation_window_is_open (EV_ANNOTATION_WINDOW (window));
2461         ev_view_window_child_move (view, child, x + root_x, y + root_y);
2462
2463         if (child->visible)
2464                 gtk_widget_show (window);
2465         else
2466                 gtk_widget_hide (window);
2467
2468         view->window_children = g_list_append (view->window_children, child);
2469 }
2470
2471 static EvViewWindowChild *
2472 ev_view_find_window_child_for_annot (EvView       *view,
2473                                      guint         page,
2474                                      EvAnnotation *annot)
2475 {
2476         GList *children = view->window_children;
2477
2478         while (children) {
2479                 EvViewWindowChild *child;
2480                 EvAnnotation      *wannot;
2481
2482                 child = (EvViewWindowChild *)children->data;
2483                 children = children->next;
2484
2485                 if (child->page != page)
2486                         continue;
2487
2488                 wannot = ev_annotation_window_get_annotation (EV_ANNOTATION_WINDOW (child->window));
2489                 if (wannot == annot || strcmp (wannot->name, annot->name) == 0)
2490                         return child;
2491         }
2492
2493         return NULL;
2494 }
2495
2496 static void
2497 ev_view_window_children_free (EvView *view)
2498 {
2499         GList *l;
2500
2501         if (!view->window_children)
2502                 return;
2503
2504         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
2505                 EvViewWindowChild *child;
2506
2507                 child = (EvViewWindowChild *)l->data;
2508                 gtk_widget_destroy (GTK_WIDGET (child->window));
2509                 g_free (child);
2510         }
2511         g_list_free (view->window_children);
2512         view->window_children = NULL;
2513         view->window_child_focus = NULL;
2514 }
2515
2516 static void
2517 annotation_window_grab_focus (GtkWidget *widget,
2518                               EvView    *view)
2519 {
2520         if (view->window_child_focus)
2521                 ev_annotation_window_ungrab_focus (EV_ANNOTATION_WINDOW (view->window_child_focus->window));
2522         view->window_child_focus = ev_view_get_window_child (view, widget);
2523 }
2524
2525 static void
2526 annotation_window_closed (EvAnnotationWindow *window,
2527                           EvView             *view)
2528 {
2529         EvViewWindowChild *child;
2530
2531         child = ev_view_get_window_child (view, GTK_WIDGET (window));
2532         child->visible = FALSE;
2533 }
2534
2535 static void
2536 annotation_window_moved (EvAnnotationWindow *window,
2537                          gint                x,
2538                          gint                y,
2539                          EvView             *view)
2540 {
2541         EvViewWindowChild *child;
2542         GdkRectangle       page_area;
2543         GtkBorder          border;
2544         GdkRectangle       view_rect;
2545         EvRectangle        doc_rect;
2546         gint               width, height;
2547
2548         child = ev_view_get_window_child (view, GTK_WIDGET (window));
2549         if (child->x == x && child->y == y)
2550                 return;
2551
2552         child->moved = TRUE;
2553         child->x = x;
2554         child->y = y;
2555
2556         /* Window has been moved by the user,
2557          * we have to set a new origin in doc coords
2558          */
2559         gtk_window_get_size (GTK_WINDOW (window), &width, &height);
2560         view_rect.x = (x - child->parent_x) + view->scroll_x;
2561         view_rect.y = (y - child->parent_y) + view->scroll_y;
2562         view_rect.width = width;
2563         view_rect.height = height;
2564
2565         get_page_extents (view, child->page, &page_area, &border);
2566         view_rect_to_doc_rect (view, &view_rect, &page_area, &doc_rect);
2567         child->orig_x = doc_rect.x1;
2568         child->orig_y = doc_rect.y1;
2569 }
2570
2571 static void
2572 ev_view_annotation_save (EvView       *view,
2573                          EvAnnotation *annot)
2574 {
2575         if (!view->document)
2576                 return;
2577
2578         if (!annot->changed)
2579                 return;
2580
2581         ev_document_annotations_annotation_set_contents (EV_DOCUMENT_ANNOTATIONS (view->document),
2582                                                          annot, annot->contents);
2583         annot->changed = FALSE;
2584 }
2585
2586 static void
2587 show_annotation_windows (EvView *view,
2588                          gint    page)
2589 {
2590         GList     *annots, *l;
2591         GtkWindow *parent;
2592
2593         parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view)));
2594
2595         annots = ev_page_cache_get_annot_mapping (view->page_cache, page);
2596
2597         for (l = annots; l && l->data; l = g_list_next (l)) {
2598                 EvAnnotation      *annot;
2599                 EvViewWindowChild *child;
2600                 GtkWidget         *window;
2601                 EvRectangle       *doc_rect;
2602                 GdkRectangle       view_rect;
2603
2604                 annot = ((EvMapping *)(l->data))->data;
2605
2606                 if (!EV_IS_ANNOTATION_MARKUP (annot))
2607                         continue;
2608
2609                 if (!ev_annotation_markup_has_popup (EV_ANNOTATION_MARKUP (annot)))
2610                         continue;
2611
2612                 window = g_object_get_data (G_OBJECT (annot), "popup");
2613                 if (window) {
2614                         ev_view_window_child_move_with_parent (view, window);
2615                         continue;
2616                 }
2617
2618                 /* Look if we already have a popup for this annot */
2619                 child = ev_view_find_window_child_for_annot (view, page, annot);
2620                 window = child ? child->window : NULL;
2621                 if (window) {
2622                         ev_annotation_window_set_annotation (EV_ANNOTATION_WINDOW (window), annot);
2623                         g_object_set_data (G_OBJECT (annot), "popup", window);
2624                         ev_view_window_child_move_with_parent (view, window);
2625                 } else {
2626                         window = ev_annotation_window_new (annot, parent);
2627                         g_signal_connect (window, "grab_focus",
2628                                           G_CALLBACK (annotation_window_grab_focus),
2629                                           view);
2630                         g_signal_connect (window, "closed",
2631                                           G_CALLBACK (annotation_window_closed),
2632                                           view);
2633                         g_signal_connect (window, "moved",
2634                                           G_CALLBACK (annotation_window_moved),
2635                                           view);
2636                         g_object_set_data (G_OBJECT (annot), "popup", window);
2637
2638                         doc_rect = (EvRectangle *)ev_annotation_window_get_rectangle (EV_ANNOTATION_WINDOW (window));
2639                         doc_rect_to_view_rect (view, page, doc_rect, &view_rect);
2640                         view_rect.x -= view->scroll_x;
2641                         view_rect.y -= view->scroll_y;
2642
2643                         ev_view_window_child_put (view, window, page,
2644                                                   view_rect.x, view_rect.y,
2645                                                   doc_rect->x1, doc_rect->y1);
2646
2647                         g_object_weak_ref (G_OBJECT (annot),
2648                                            (GWeakNotify)ev_view_annotation_save,
2649                                            view);
2650                 }
2651         }
2652 }
2653
2654 static void
2655 hide_annotation_windows (EvView *view,
2656                          gint    page)
2657 {
2658         GList *annots, *l;
2659
2660         annots = ev_page_cache_get_annot_mapping (view->page_cache, page);
2661
2662         for (l = annots; l && l->data; l = g_list_next (l)) {
2663                 EvAnnotation *annot;
2664                 GtkWidget    *window;
2665
2666                 annot = ((EvMapping *)(l->data))->data;
2667
2668                 if (!EV_IS_ANNOTATION_MARKUP (annot))
2669                         continue;
2670
2671                 window = g_object_get_data (G_OBJECT (annot), "popup");
2672                 if (window)
2673                         gtk_widget_hide (window);
2674         }
2675 }
2676
2677 static EvAnnotation *
2678 ev_view_get_annotation_at_location (EvView  *view,
2679                                     gdouble  x,
2680                                     gdouble  y)
2681 {
2682         gint page = -1;
2683         gint x_new = 0, y_new = 0;
2684         GList *annotations_mapping;
2685
2686         if (!EV_IS_DOCUMENT_ANNOTATIONS (view->document))
2687                 return NULL;
2688
2689         if (!get_doc_point_from_location (view, x, y, &page, &x_new, &y_new))
2690                 return NULL;
2691
2692         annotations_mapping = ev_page_cache_get_annot_mapping (view->page_cache, page);
2693
2694         if (annotations_mapping)
2695                 return ev_mapping_list_get_data (annotations_mapping, x_new, y_new);
2696         else
2697                 return NULL;
2698 }
2699
2700 static void
2701 ev_view_handle_annotation (EvView       *view,
2702                            EvAnnotation *annot,
2703                            gdouble       x,
2704                            gdouble       y,
2705                            guint32       timestamp)
2706 {
2707         if (EV_IS_ANNOTATION_MARKUP (annot)) {
2708                 GtkWidget *window;
2709
2710                 window = g_object_get_data (G_OBJECT (annot), "popup");
2711                 if (window) {
2712                         EvViewWindowChild *child;
2713
2714                         child = ev_view_get_window_child (view, window);
2715                         if (!child->visible) {
2716                                 child->visible = TRUE;
2717                                 ev_view_window_child_move (view, child, child->x, child->y);
2718                                 gtk_widget_show (window);
2719                         }
2720                 }
2721         }
2722
2723         if (EV_IS_ANNOTATION_ATTACHMENT (annot)) {
2724                 EvAttachment *attachment = EV_ANNOTATION_ATTACHMENT (annot)->attachment;
2725
2726                 if (attachment) {
2727                         GError *error = NULL;
2728
2729                         ev_attachment_open (attachment,
2730                                             gtk_widget_get_screen (GTK_WIDGET (view)),
2731                                             timestamp,
2732                                             &error);
2733
2734                         if (error) {
2735                                 g_warning ("%s", error->message);
2736                                 g_error_free (error);
2737                         }
2738                 }
2739         }
2740 }
2741
2742 /*** GtkWidget implementation ***/
2743
2744 static void
2745 ev_view_size_request_continuous_dual_page (EvView         *view,
2746                                            GtkRequisition *requisition)
2747 {
2748         gint n_pages;
2749
2750         n_pages = ev_document_get_n_pages (view->document) + 1;
2751         get_page_y_offset (view, n_pages, &requisition->height);
2752
2753         switch (view->sizing_mode) {
2754                 case EV_SIZING_FIT_WIDTH:
2755                 case EV_SIZING_BEST_FIT:
2756                         requisition->width = 1;
2757
2758                         break;
2759                 case EV_SIZING_FREE: {
2760                         gint max_width;
2761                         GtkBorder border;
2762
2763                         ev_view_get_max_page_size (view, &max_width, NULL);
2764                         compute_border (view, max_width, max_width, &border);
2765                         requisition->width = (max_width + border.left + border.right) * 2 + (view->spacing * 3);
2766                 }
2767                         break;
2768                 default:
2769                         g_assert_not_reached ();
2770         }
2771 }
2772
2773 static void
2774 ev_view_size_request_continuous (EvView         *view,
2775                                  GtkRequisition *requisition)
2776 {
2777         gint n_pages;
2778
2779         n_pages = ev_document_get_n_pages (view->document);
2780         get_page_y_offset (view, n_pages, &requisition->height);
2781
2782         switch (view->sizing_mode) {
2783                 case EV_SIZING_FIT_WIDTH:
2784                 case EV_SIZING_BEST_FIT:
2785                         requisition->width = 1;
2786
2787                         break;
2788                 case EV_SIZING_FREE: {
2789                         gint max_width;
2790                         GtkBorder border;
2791
2792                         ev_view_get_max_page_size (view, &max_width, NULL);
2793                         compute_border (view, max_width, max_width, &border);
2794                         requisition->width = max_width + (view->spacing * 2) + border.left + border.right;
2795                 }
2796                         break;
2797                 default:
2798                         g_assert_not_reached ();
2799         }
2800 }
2801
2802 static void
2803 ev_view_size_request_dual_page (EvView         *view,
2804                                 GtkRequisition *requisition)
2805 {
2806         GtkBorder border;
2807         gint width, height;
2808
2809         if (view->sizing_mode == EV_SIZING_BEST_FIT) {
2810                 requisition->width = 1;
2811                 requisition->height = 1;
2812
2813                 return;
2814         }
2815
2816         /* Find the largest of the two. */
2817         ev_view_get_page_size (view,
2818                                view->current_page,
2819                                &width, &height);
2820         if (view->current_page + 1 < ev_document_get_n_pages (view->document)) {
2821                 gint width_2, height_2;
2822                 ev_view_get_page_size (view,
2823                                        view->current_page + 1,
2824                                        &width_2, &height_2);
2825                 if (width_2 > width) {
2826                         width = width_2;
2827                         height = height_2;
2828                 }
2829         }
2830         compute_border (view, width, height, &border);
2831
2832         requisition->width = view->sizing_mode == EV_SIZING_FIT_WIDTH ? 1 :
2833                 ((width + border.left + border.right) * 2) + (view->spacing * 3);
2834         requisition->height = (height + border.top + border.bottom) + (view->spacing * 2);
2835 }
2836
2837 static void
2838 ev_view_size_request_single_page (EvView         *view,
2839                                   GtkRequisition *requisition)
2840 {
2841         GtkBorder border;
2842         gint width, height;
2843
2844         if (view->sizing_mode == EV_SIZING_BEST_FIT) {
2845                 requisition->width = 1;
2846                 requisition->height = 1;
2847
2848                 return;
2849         }
2850
2851         ev_view_get_page_size (view, view->current_page, &width, &height);
2852         compute_border (view, width, height, &border);
2853
2854         requisition->width = view->sizing_mode == EV_SIZING_FIT_WIDTH ? 1 :
2855                 width + border.left + border.right + (2 * view->spacing);
2856         requisition->height = height + border.top + border.bottom + (2 * view->spacing);
2857 }
2858
2859 static void
2860 ev_view_size_request (GtkWidget      *widget,
2861                       GtkRequisition *requisition)
2862 {
2863         EvView *view = EV_VIEW (widget);
2864
2865         if (view->document == NULL) {
2866                 view->requisition.width = 1;
2867                 view->requisition.height = 1;
2868
2869                 *requisition = view->requisition;
2870
2871                 return;
2872         }
2873
2874         /* Get zoom for size here when not called from
2875          * ev_view_size_allocate()
2876          */
2877         if (!view->internal_size_request &&
2878             (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
2879              view->sizing_mode == EV_SIZING_BEST_FIT)) {
2880                 GtkAllocation allocation;
2881
2882                 gtk_widget_get_allocation (widget, &allocation);
2883                 ev_view_zoom_for_size (view,
2884                                        allocation.width,
2885                                        allocation.height);
2886         }
2887
2888         if (view->continuous && view->dual_page)
2889                 ev_view_size_request_continuous_dual_page (view, &view->requisition);
2890         else if (view->continuous)
2891                 ev_view_size_request_continuous (view, &view->requisition);
2892         else if (view->dual_page)
2893                 ev_view_size_request_dual_page (view, &view->requisition);
2894         else
2895                 ev_view_size_request_single_page (view, &view->requisition);
2896
2897         *requisition = view->requisition;
2898 }
2899
2900 static void
2901 ev_view_size_allocate (GtkWidget      *widget,
2902                        GtkAllocation  *allocation)
2903 {
2904         EvView *view = EV_VIEW (widget);
2905         GList  *children, *l;
2906         gint    root_x, root_y;
2907
2908         GTK_WIDGET_CLASS (ev_view_parent_class)->size_allocate (widget, allocation);
2909
2910         if (!view->document)
2911                 return;
2912
2913         if (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
2914             view->sizing_mode == EV_SIZING_BEST_FIT) {
2915                 GtkRequisition req;
2916
2917                 ev_view_zoom_for_size (view,
2918                                        allocation->width,
2919                                        allocation->height);
2920                 view->internal_size_request = TRUE;
2921                 ev_view_size_request (widget, &req);
2922                 view->internal_size_request = FALSE;
2923         }
2924         
2925         view_set_adjustment_values (view, GTK_ORIENTATION_HORIZONTAL);
2926         view_set_adjustment_values (view, GTK_ORIENTATION_VERTICAL);
2927
2928         if (view->document)
2929                 view_update_range_and_current_page (view);
2930
2931         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
2932         view->pending_resize = FALSE;
2933         view->pending_point.x = 0;
2934         view->pending_point.y = 0;
2935
2936         children = gtk_container_get_children (GTK_CONTAINER (widget));
2937         for (l = children; l && l->data; l = g_list_next (l)) {
2938                 EvFormField   *field;
2939                 GdkRectangle   view_area;
2940                 GList         *form_field_mapping;
2941                 GtkAllocation  child_allocation;
2942                 GtkRequisition child_requisition;
2943                 GtkWidget     *child = (GtkWidget *)l->data;
2944                 
2945                 field = g_object_get_data (G_OBJECT (child), "form-field");
2946                 if (!field)
2947                         continue;
2948
2949                 form_field_mapping = ev_page_cache_get_form_field_mapping (view->page_cache,
2950                                                                            field->page->index);
2951                 ev_view_get_area_from_mapping (view, field->page->index,
2952                                                form_field_mapping,
2953                                                field, &view_area);
2954
2955                 gtk_widget_size_request (child, &child_requisition);
2956                 if (child_requisition.width != view_area.width ||
2957                     child_requisition.height != view_area.height)
2958                         gtk_widget_set_size_request (child, view_area.width, view_area.height);
2959
2960                 gtk_container_child_get (GTK_CONTAINER (widget),
2961                                          child,
2962                                          "x", &child_allocation.x,
2963                                          "y", &child_allocation.y,
2964                                          NULL);
2965                 if (child_allocation.x != view_area.x ||
2966                     child_allocation.y != view_area.y) {
2967                         gtk_layout_move (GTK_LAYOUT (widget), child, view_area.x, view_area.y);
2968                 }
2969         }
2970         g_list_free (children);
2971
2972         if (view->window_children)
2973                 gdk_window_get_origin (gtk_widget_get_window (GTK_WIDGET (view)),
2974                                        &root_x, &root_y);
2975
2976         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
2977                 EvViewWindowChild *child;
2978                 EvRectangle        doc_rect;
2979                 GdkRectangle       view_rect;
2980
2981                 child = (EvViewWindowChild *)l->data;
2982
2983                 doc_rect = *ev_annotation_window_get_rectangle (EV_ANNOTATION_WINDOW (child->window));
2984                 if (child->moved) {
2985                         doc_rect.x1 = child->orig_x;
2986                         doc_rect.y1 = child->orig_y;
2987                 }
2988                 doc_rect_to_view_rect (view, child->page, &doc_rect, &view_rect);
2989                 view_rect.x -= view->scroll_x;
2990                 view_rect.y -= view->scroll_y;
2991
2992                 if (view_rect.x != child->orig_x || view_rect.y != child->orig_y) {
2993                         child->parent_x = root_x;
2994                         child->parent_y = root_y;
2995                         ev_view_window_child_move (view, child, view_rect.x + root_x, view_rect.y + root_y);
2996                 }
2997         }
2998 }
2999
3000 static void
3001 ev_view_realize (GtkWidget *widget)
3002 {
3003         EvView    *view = EV_VIEW (widget);
3004         GdkWindow *bin_window;
3005         GtkStyle  *style;
3006
3007         if (GTK_WIDGET_CLASS (ev_view_parent_class)->realize)
3008                 (* GTK_WIDGET_CLASS (ev_view_parent_class)->realize) (widget);
3009
3010         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
3011         gdk_window_set_events (bin_window,
3012                                (gdk_window_get_events (bin_window) |
3013                                 GDK_EXPOSURE_MASK |
3014                                 GDK_BUTTON_PRESS_MASK |
3015                                 GDK_BUTTON_RELEASE_MASK |
3016                                 GDK_SCROLL_MASK |
3017                                 GDK_KEY_PRESS_MASK |
3018                                 GDK_POINTER_MOTION_MASK |
3019                                 GDK_POINTER_MOTION_HINT_MASK |
3020                                 GDK_ENTER_NOTIFY_MASK |
3021                                 GDK_LEAVE_NOTIFY_MASK));
3022
3023         style = gtk_widget_get_style (widget);
3024         gdk_window_set_background (bin_window, &style->mid[GTK_STATE_NORMAL]);
3025
3026         on_adjustment_value_changed (NULL, view);
3027 }
3028
3029 static gboolean
3030 ev_view_scroll_event (GtkWidget *widget, GdkEventScroll *event)
3031 {
3032         EvView *view = EV_VIEW (widget);
3033         guint state;
3034
3035         state = event->state & gtk_accelerator_get_default_mod_mask ();
3036
3037         if (state == GDK_CONTROL_MASK) {
3038                 ev_document_model_set_sizing_mode (view->model, EV_SIZING_FREE);
3039                 if (event->direction == GDK_SCROLL_UP ||
3040                     event->direction == GDK_SCROLL_LEFT) {
3041                         if (ev_view_can_zoom_in (view)) {
3042                                 ev_view_zoom_in (view);
3043                         }
3044                 } else {
3045                         if (ev_view_can_zoom_out (view)) {
3046                                 ev_view_zoom_out (view);
3047                         }
3048                 }
3049
3050                 return TRUE;
3051         }
3052
3053         view->jump_to_find_result = FALSE;
3054
3055         /* Shift+Wheel scrolls the in the perpendicular direction */
3056         if (state & GDK_SHIFT_MASK) {
3057                 if (event->direction == GDK_SCROLL_UP)
3058                         event->direction = GDK_SCROLL_LEFT;
3059                 else if (event->direction == GDK_SCROLL_LEFT)
3060                         event->direction = GDK_SCROLL_UP;
3061                 else if (event->direction == GDK_SCROLL_DOWN)
3062                         event->direction = GDK_SCROLL_RIGHT;
3063                 else if (event->direction == GDK_SCROLL_RIGHT)
3064                         event->direction = GDK_SCROLL_DOWN;
3065
3066                 event->state &= ~GDK_SHIFT_MASK;
3067                 state &= ~GDK_SHIFT_MASK;
3068         }
3069
3070         if (state == 0 && view->sizing_mode == EV_SIZING_BEST_FIT && !view->continuous) {
3071                 switch (event->direction) {
3072                         case GDK_SCROLL_DOWN:
3073                         case GDK_SCROLL_RIGHT:
3074                                 ev_view_next_page (view);       
3075                                 break;
3076                         case GDK_SCROLL_UP:
3077                         case GDK_SCROLL_LEFT:
3078                                 ev_view_previous_page (view);
3079                                 break;
3080                 }
3081
3082                 return TRUE;
3083         }
3084
3085         return FALSE;
3086 }
3087
3088 static EvViewSelection *
3089 find_selection_for_page (EvView *view,
3090                          gint    page)
3091 {
3092         GList *list;
3093
3094         for (list = view->selection_info.selections; list != NULL; list = list->next) {
3095                 EvViewSelection *selection;
3096
3097                 selection = (EvViewSelection *) list->data;
3098
3099                 if (selection->page == page)
3100                         return selection;
3101         }
3102
3103         return NULL;
3104 }
3105
3106 static gboolean
3107 ev_view_expose_event (GtkWidget      *widget,
3108                       GdkEventExpose *event)
3109 {
3110         EvView    *view = EV_VIEW (widget);
3111         GdkWindow *bin_window;
3112         cairo_t   *cr;
3113         gint       i;
3114
3115         if (view->loading) {
3116                 show_loading_window (view);
3117         } else if (view->loading_window &&
3118                    gtk_widget_get_visible (view->loading_window)) {
3119                 ev_view_loading_window_move (view);
3120         }
3121
3122         if (view->document == NULL)
3123                 return FALSE;
3124
3125         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
3126         cr = gdk_cairo_create (bin_window);
3127
3128         for (i = view->start_page; i >= 0 && i <= view->end_page; i++) {
3129                 GdkRectangle page_area;
3130                 GtkBorder border;
3131                 gboolean page_ready = TRUE;
3132
3133                 if (!get_page_extents (view, i, &page_area, &border))
3134                         continue;
3135
3136                 page_area.x -= view->scroll_x;
3137                 page_area.y -= view->scroll_y;
3138
3139                 draw_one_page (view, i, cr, &page_area, &border, &(event->area), &page_ready);
3140
3141                 if (page_ready && view->find_pages && view->highlight_find_results)
3142                         highlight_find_results (view, i);
3143                 if (page_ready && EV_IS_DOCUMENT_ANNOTATIONS (view->document))
3144                         show_annotation_windows (view, i);
3145         }
3146
3147         cairo_destroy (cr);
3148
3149         if (GTK_WIDGET_CLASS (ev_view_parent_class)->expose_event)
3150                 (* GTK_WIDGET_CLASS (ev_view_parent_class)->expose_event) (widget, event);
3151
3152         return FALSE;
3153 }
3154
3155 static gboolean
3156 ev_view_do_popup_menu (EvView *view,
3157                        gdouble x,
3158                        gdouble y)
3159 {
3160         GList        *items = NULL;
3161         EvLink       *link;
3162         EvImage      *image;
3163         EvAnnotation *annot;
3164
3165         image = ev_view_get_image_at_location (view, x, y);
3166         if (image)
3167                 items = g_list_prepend (items, image);
3168
3169         link = ev_view_get_link_at_location (view, x, y);
3170         if (link)
3171                 items = g_list_prepend (items, link);
3172
3173         annot = ev_view_get_annotation_at_location (view, x, y);
3174         if (annot)
3175                 items = g_list_prepend (items, annot);
3176
3177         g_signal_emit (view, signals[SIGNAL_POPUP_MENU], 0, items);
3178
3179         g_list_free (items);
3180
3181         return TRUE;
3182 }
3183
3184 static gboolean
3185 ev_view_popup_menu (GtkWidget *widget)
3186 {
3187         gint x, y;
3188         
3189         gtk_widget_get_pointer (widget, &x, &y);
3190         return ev_view_do_popup_menu (EV_VIEW (widget), x, y);
3191 }
3192
3193 static void
3194 get_link_area (EvView       *view,
3195                gint          x,
3196                gint          y,
3197                EvLink       *link,
3198                GdkRectangle *area)
3199 {
3200         GList *link_mapping;
3201         gint   page;
3202         gint   x_offset = 0, y_offset = 0;
3203
3204         x += view->scroll_x;
3205         y += view->scroll_y;
3206         
3207         find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
3208         
3209         link_mapping = ev_page_cache_get_link_mapping (view->page_cache, page);
3210         ev_view_get_area_from_mapping (view, page,
3211                                        link_mapping,
3212                                        link, area);
3213 }
3214
3215 static void
3216 get_annot_area (EvView       *view,
3217                gint          x,
3218                gint          y,
3219                EvAnnotation *annot,
3220                GdkRectangle *area)
3221 {
3222         GList *annot_mapping;
3223         gint   page;
3224         gint   x_offset = 0, y_offset = 0;
3225
3226         x += view->scroll_x;
3227         y += view->scroll_y;
3228
3229         find_page_at_location (view, x, y, &page, &x_offset, &y_offset);
3230
3231         annot_mapping = ev_page_cache_get_annot_mapping (view->page_cache, page);
3232         ev_view_get_area_from_mapping (view, page,
3233                                        annot_mapping,
3234                                        annot, area);
3235 }
3236
3237 static gboolean
3238 ev_view_query_tooltip (GtkWidget  *widget,
3239                        gint        x,
3240                        gint        y,
3241                        gboolean    keyboard_tip,
3242                        GtkTooltip *tooltip)
3243 {
3244         EvView       *view = EV_VIEW (widget);
3245         EvLink       *link;
3246         EvAnnotation *annot;
3247         gchar        *text;
3248
3249         annot = ev_view_get_annotation_at_location (view, x, y);
3250         if (annot && annot->contents) {
3251                 GdkRectangle annot_area;
3252
3253                 get_annot_area (view, x, y, annot, &annot_area);
3254                 gtk_tooltip_set_text (tooltip, annot->contents);
3255                 gtk_tooltip_set_tip_area (tooltip, &annot_area);
3256
3257                 return TRUE;
3258         }
3259
3260         link = ev_view_get_link_at_location (view, x, y);
3261         if (!link)
3262                 return FALSE;
3263
3264         text = tip_from_link (view, link);
3265         if (text && g_utf8_validate (text, -1, NULL)) {
3266                 GdkRectangle link_area;
3267
3268                 get_link_area (view, x, y, link, &link_area);
3269                 gtk_tooltip_set_text (tooltip, text);
3270                 gtk_tooltip_set_tip_area (tooltip, &link_area);
3271         }
3272         g_free (text);
3273
3274         return TRUE;
3275 }
3276
3277 static void
3278 start_selection_for_event (EvView         *view,
3279                            GdkEventButton *event)
3280 {
3281         clear_selection (view);
3282
3283         view->selection_info.start.x = event->x + view->scroll_x;
3284         view->selection_info.start.y = event->y + view->scroll_y;
3285
3286         switch (event->type) {
3287                 case GDK_2BUTTON_PRESS:
3288                         view->selection_info.style = EV_SELECTION_STYLE_WORD;
3289                         break;
3290                 case GDK_3BUTTON_PRESS:
3291                         view->selection_info.style = EV_SELECTION_STYLE_LINE;
3292                         break;
3293                 default:
3294                         view->selection_info.style = EV_SELECTION_STYLE_GLYPH;
3295                         return;
3296         }
3297
3298         /* In case of WORD or LINE, compute selections now */
3299         compute_selections (view,
3300                             view->selection_info.style,
3301                             &(view->selection_info.start),
3302                             &(view->selection_info.start));
3303 }
3304
3305 static gboolean
3306 ev_view_button_press_event (GtkWidget      *widget,
3307                             GdkEventButton *event)
3308 {
3309         EvView *view = EV_VIEW (widget);
3310
3311         if (!view->document)
3312                 return FALSE;
3313         
3314         if (!gtk_widget_has_focus (widget)) {
3315                 gtk_widget_grab_focus (widget);
3316         }
3317
3318         if (view->window_child_focus) {
3319                 EvAnnotationWindow *window;
3320                 EvAnnotation       *annot;
3321
3322                 window = EV_ANNOTATION_WINDOW (view->window_child_focus->window);
3323                 annot = ev_annotation_window_get_annotation (window);
3324                 ev_annotation_window_ungrab_focus (window);
3325                 ev_view_annotation_save (view, annot);
3326                 view->window_child_focus = NULL;
3327         }
3328         
3329         view->pressed_button = event->button;
3330         view->selection_info.in_drag = FALSE;
3331
3332         if (view->scroll_info.autoscrolling)
3333                 return TRUE;
3334         
3335         switch (event->button) {
3336                 case 1: {
3337                         EvImage *image;
3338                         EvAnnotation *annot;
3339                         EvFormField *field;
3340
3341                         if (EV_IS_SELECTION (view->document) && view->selection_info.selections) {
3342                                 if (event->type == GDK_3BUTTON_PRESS) {
3343                                         start_selection_for_event (view, event);
3344                                 } else if (location_in_selected_text (view,
3345                                                                event->x + view->scroll_x,
3346                                                                event->y + view->scroll_y)) {
3347                                         view->selection_info.in_drag = TRUE;
3348                                 } else {
3349                                         start_selection_for_event (view, event);
3350                                 }
3351
3352                                 gtk_widget_queue_draw (widget);
3353                         } else if ((annot = ev_view_get_annotation_at_location (view, event->x, event->y))) {
3354                                 ev_view_handle_annotation (view, annot, event->x, event->y, event->time);
3355                         } else if ((field = ev_view_get_form_field_at_location (view, event->x, event->y))) {
3356                                 ev_view_remove_all (view);
3357                                 ev_view_handle_form_field (view, field, event->x, event->y);
3358                         } else if (!location_in_text (view, event->x + view->scroll_x, event->y + view->scroll_y) &&
3359                                    (image = ev_view_get_image_at_location (view, event->x, event->y))) {
3360                                 if (view->image_dnd_info.image)
3361                                         g_object_unref (view->image_dnd_info.image);
3362                                 view->image_dnd_info.image = g_object_ref (image);
3363                                 view->image_dnd_info.in_drag = TRUE;
3364
3365                                 view->image_dnd_info.start.x = event->x + view->scroll_x;
3366                                 view->image_dnd_info.start.y = event->y + view->scroll_y;
3367                         } else {
3368                                 ev_view_remove_all (view);
3369                                 
3370                                 if (EV_IS_SELECTION (view->document))
3371                                         start_selection_for_event (view, event);
3372                         }
3373                 }                       
3374                         return TRUE;
3375                 case 2:
3376                         /* use root coordinates as reference point because
3377                          * scrolling changes window relative coordinates */
3378                         view->drag_info.start.x = event->x_root;
3379                         view->drag_info.start.y = event->y_root;
3380                         view->drag_info.hadj = gtk_adjustment_get_value (view->hadjustment);
3381                         view->drag_info.vadj = gtk_adjustment_get_value (view->vadjustment);
3382
3383                         ev_view_set_cursor (view, EV_VIEW_CURSOR_DRAG);
3384
3385                         return TRUE;
3386                 case 3:
3387                         view->scroll_info.start_y = event->y;
3388                         return ev_view_do_popup_menu (view, event->x, event->y);
3389         }
3390         
3391         return FALSE;
3392 }
3393
3394 static void
3395 ev_view_remove_all (EvView *view)
3396 {
3397         GList *children, *child;
3398
3399         children = gtk_container_get_children (GTK_CONTAINER (view));
3400         for (child = children; child && child->data; child = g_list_next (child)) {
3401                 gtk_container_remove (GTK_CONTAINER (view),
3402                                       GTK_WIDGET (child->data));
3403         }
3404         g_list_free (children);
3405 }
3406
3407 /*** Drag and Drop ***/
3408 static void
3409 ev_view_drag_data_get (GtkWidget        *widget,
3410                        GdkDragContext   *context,
3411                        GtkSelectionData *selection_data,
3412                        guint             info,
3413                        guint             time)
3414 {
3415         EvView *view = EV_VIEW (widget);
3416
3417         switch (info) {
3418                 case TARGET_DND_TEXT:
3419                         if (EV_IS_SELECTION (view->document) &&
3420                             view->selection_info.selections) {
3421                                 gchar *text;
3422
3423                                 text = get_selected_text (view);
3424                                 gtk_selection_data_set_text (selection_data,
3425                                                              text,
3426                                                              strlen (text));
3427                                 g_free (text);
3428                         }
3429                         break;
3430                 case TARGET_DND_IMAGE:
3431                         if (view->image_dnd_info.image) {
3432                                 GdkPixbuf *pixbuf;
3433
3434                                 ev_document_doc_mutex_lock ();
3435                                 pixbuf = ev_document_images_get_image (EV_DOCUMENT_IMAGES (view->document),
3436                                                                        view->image_dnd_info.image);
3437                                 ev_document_doc_mutex_unlock ();
3438                                 
3439                                 gtk_selection_data_set_pixbuf (selection_data, pixbuf);
3440                                 g_object_unref (pixbuf);
3441                         }
3442                         break;
3443                 case TARGET_DND_URI:
3444                         if (view->image_dnd_info.image) {
3445                                 GdkPixbuf   *pixbuf;
3446                                 const gchar *tmp_uri;
3447                                 gchar       *uris[2];
3448
3449                                 ev_document_doc_mutex_lock ();
3450                                 pixbuf = ev_document_images_get_image (EV_DOCUMENT_IMAGES (view->document),
3451                                                                        view->image_dnd_info.image);
3452                                 ev_document_doc_mutex_unlock ();
3453                                 
3454                                 tmp_uri = ev_image_save_tmp (view->image_dnd_info.image, pixbuf);
3455                                 g_object_unref (pixbuf);
3456
3457                                 uris[0] = (gchar *)tmp_uri;
3458                                 uris[1] = NULL;
3459                                 gtk_selection_data_set_uris (selection_data, uris);
3460                         }
3461         }
3462 }
3463
3464 static gboolean
3465 ev_view_drag_motion (GtkWidget      *widget,
3466                      GdkDragContext *context,
3467                      gint            x,
3468                      gint            y,
3469                      guint           time)
3470 {
3471         if (gtk_drag_get_source_widget (context) == widget)
3472                 gdk_drag_status (context, 0, time);
3473         else
3474                 gdk_drag_status (context, gdk_drag_context_get_suggested_action (context), time);
3475         
3476         return TRUE;
3477 }
3478                      
3479 static gboolean
3480 selection_update_idle_cb (EvView *view)
3481 {
3482         compute_selections (view,
3483                             view->selection_info.style,
3484                             &view->selection_info.start,
3485                             &view->motion);
3486         view->selection_update_id = 0;
3487         return FALSE;
3488 }
3489
3490 static gboolean
3491 selection_scroll_timeout_cb (EvView *view)
3492 {       
3493         gint x, y, shift = 0;
3494         GtkWidget *widget = GTK_WIDGET (view);
3495         GtkAllocation allocation;
3496
3497         gtk_widget_get_allocation (widget, &allocation);
3498         gtk_widget_get_pointer (widget, &x, &y);
3499
3500         if (y > allocation.height) {
3501                 shift = (y - allocation.height) / 2;
3502         } else if (y < 0) {
3503                 shift = y / 2;
3504         }
3505
3506         if (shift)
3507                 gtk_adjustment_set_value (view->vadjustment,
3508                                           CLAMP (gtk_adjustment_get_value (view->vadjustment) + shift,
3509                                                  gtk_adjustment_get_lower (view->vadjustment),
3510                                                  gtk_adjustment_get_upper (view->vadjustment) -
3511                                                  gtk_adjustment_get_page_size (view->vadjustment)));
3512
3513         if (x > allocation.width) {
3514                 shift = (x - allocation.width) / 2;
3515         } else if (x < 0) {
3516                 shift = x / 2;
3517         }
3518
3519         if (shift)
3520                 gtk_adjustment_set_value (view->hadjustment,
3521                                           CLAMP (gtk_adjustment_get_value (view->hadjustment) + shift,
3522                                                  gtk_adjustment_get_lower (view->hadjustment),
3523                                                  gtk_adjustment_get_upper (view->hadjustment) -
3524                                                  gtk_adjustment_get_page_size (view->hadjustment)));
3525
3526         return TRUE;
3527 }
3528
3529 static gboolean
3530 ev_view_drag_update_momentum (EvView *view)
3531 {
3532         int i;
3533         if (!view->drag_info.in_drag)
3534                 return FALSE;
3535         
3536         for (i = DRAG_HISTORY - 1; i > 0; i--) {
3537                 view->drag_info.buffer[i].x = view->drag_info.buffer[i-1].x;
3538                 view->drag_info.buffer[i].y = view->drag_info.buffer[i-1].y;
3539         }
3540
3541         /* Momentum is a moving average of 10ms granularity over
3542          * the last 100ms with each 10ms stored in buffer. 
3543          */
3544         
3545         view->drag_info.momentum.x = (view->drag_info.buffer[DRAG_HISTORY - 1].x - view->drag_info.buffer[0].x);
3546         view->drag_info.momentum.y = (view->drag_info.buffer[DRAG_HISTORY - 1].y - view->drag_info.buffer[0].y);
3547
3548         return TRUE;
3549 }
3550
3551 static gboolean
3552 ev_view_scroll_drag_release (EvView *view)
3553 {
3554         gdouble dhadj_value, dvadj_value;
3555         gdouble oldhadjustment, oldvadjustment;
3556         gdouble h_page_size, v_page_size;
3557         gdouble h_upper, v_upper;
3558         GtkAllocation allocation;
3559
3560         view->drag_info.momentum.x /= 1.2;
3561         view->drag_info.momentum.y /= 1.2; /* Alter these constants to change "friction" */
3562
3563         gtk_widget_get_allocation (GTK_WIDGET (view), &allocation);
3564
3565         h_page_size = gtk_adjustment_get_page_size (view->hadjustment);
3566         v_page_size = gtk_adjustment_get_page_size (view->vadjustment);
3567
3568         dhadj_value = h_page_size *
3569                       (gdouble)view->drag_info.momentum.x / allocation.width;
3570         dvadj_value = v_page_size *
3571                       (gdouble)view->drag_info.momentum.y / allocation.height;
3572
3573         oldhadjustment = gtk_adjustment_get_value (view->hadjustment);
3574         oldvadjustment = gtk_adjustment_get_value (view->vadjustment);
3575
3576         h_upper = gtk_adjustment_get_upper (view->hadjustment);
3577         v_upper = gtk_adjustment_get_upper (view->vadjustment);
3578
3579         /* When we reach the edges, we need either to absorb some momentum and bounce by
3580          * multiplying it on -0.5 or stop scrolling by setting momentum to 0. */
3581         if (((oldhadjustment + dhadj_value) > (h_upper - h_page_size)) ||
3582             ((oldhadjustment + dhadj_value) < 0))
3583                 view->drag_info.momentum.x = 0;
3584         if (((oldvadjustment + dvadj_value) > (v_upper - v_page_size)) ||
3585             ((oldvadjustment + dvadj_value) < 0))
3586                 view->drag_info.momentum.y = 0;
3587
3588         gtk_adjustment_set_value (view->hadjustment,
3589                                   MIN (oldhadjustment + dhadj_value,
3590                                        h_upper - h_page_size));
3591         gtk_adjustment_set_value (view->vadjustment,
3592                                   MIN (oldvadjustment + dvadj_value,
3593                                        v_upper - v_page_size));
3594
3595         if (((view->drag_info.momentum.x < 1) && (view->drag_info.momentum.x > -1)) &&
3596             ((view->drag_info.momentum.y < 1) && (view->drag_info.momentum.y > -1)))
3597                 return FALSE;
3598         else
3599                 return TRUE;
3600 }
3601
3602 static gboolean
3603 ev_view_motion_notify_event (GtkWidget      *widget,
3604                              GdkEventMotion *event)
3605 {
3606         EvView    *view = EV_VIEW (widget);
3607         GdkWindow *bin_window;
3608         gint       x, y;
3609
3610         if (!view->document)
3611                 return FALSE;
3612
3613         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
3614
3615         if (event->is_hint || event->window != bin_window) {
3616             gtk_widget_get_pointer (widget, &x, &y);
3617         } else {
3618             x = event->x;
3619             y = event->y;
3620         }
3621
3622         if (view->scroll_info.autoscrolling) {
3623                 view->scroll_info.last_y = y;
3624                 return TRUE;
3625         }
3626
3627         if (view->selection_info.in_drag) {
3628                 if (gtk_drag_check_threshold (widget,
3629                                               view->selection_info.start.x,
3630                                               view->selection_info.start.y,
3631                                               x, y)) {
3632                         GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
3633
3634                         gtk_target_list_add_text_targets (target_list, TARGET_DND_TEXT);
3635
3636                         gtk_drag_begin (widget, target_list,
3637                                         GDK_ACTION_COPY,
3638                                         1, (GdkEvent *)event);
3639
3640                         view->selection_info.in_drag = FALSE;
3641
3642                         gtk_target_list_unref (target_list);
3643
3644                         return TRUE;
3645                 }
3646         } else if (view->image_dnd_info.in_drag) {
3647                 if (gtk_drag_check_threshold (widget,
3648                                               view->selection_info.start.x,
3649                                               view->selection_info.start.y,
3650                                               x, y)) {
3651                         GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
3652
3653                         gtk_target_list_add_uri_targets (target_list, TARGET_DND_URI);
3654                         gtk_target_list_add_image_targets (target_list, TARGET_DND_IMAGE, TRUE);
3655
3656                         gtk_drag_begin (widget, target_list,
3657                                         GDK_ACTION_COPY,
3658                                         1, (GdkEvent *)event);
3659
3660                         view->image_dnd_info.in_drag = FALSE;
3661
3662                         gtk_target_list_unref (target_list);
3663
3664                         return TRUE;
3665                 }
3666         }
3667         
3668         switch (view->pressed_button) {
3669         case 1:
3670                 /* For the Evince 0.4.x release, we limit selection to un-rotated
3671                  * documents only.
3672                  */
3673                 if (view->rotation != 0)
3674                         return FALSE;
3675
3676                 /* Schedule timeout to scroll during selection and additionally 
3677                  * scroll once to allow arbitrary speed. */
3678                 if (!view->selection_scroll_id)
3679                     view->selection_scroll_id = g_timeout_add (SCROLL_TIME,
3680                                                                (GSourceFunc)selection_scroll_timeout_cb,
3681                                                                view);
3682                 else 
3683                     selection_scroll_timeout_cb (view);
3684
3685                 view->selection_info.in_selection = TRUE;
3686                 view->motion.x = x + view->scroll_x;
3687                 view->motion.y = y + view->scroll_y;
3688
3689                 /* Queue an idle to handle the motion.  We do this because      
3690                  * handling any selection events in the motion could be slower  
3691                  * than new motion events reach us.  We always put it in the    
3692                  * idle to make sure we catch up and don't visibly lag the      
3693                  * mouse. */
3694                 if (!view->selection_update_id)
3695                         view->selection_update_id = g_idle_add ((GSourceFunc)selection_update_idle_cb, view);
3696
3697                 return TRUE;
3698         case 2:
3699                 if (!view->drag_info.in_drag) {
3700                         gboolean start;
3701                         int i;
3702
3703                         start = gtk_drag_check_threshold (widget,
3704                                                           view->drag_info.start.x,
3705                                                           view->drag_info.start.y,
3706                                                           event->x_root,
3707                                                           event->y_root);
3708                         view->drag_info.in_drag = start;
3709                         view->drag_info.drag_timeout_id = g_timeout_add (10,
3710                                 (GSourceFunc)ev_view_drag_update_momentum, view);
3711                         /* Set 100 to choose how long it takes to build up momentum */
3712                         /* Clear out previous momentum info: */
3713                         for (i = 0; i < DRAG_HISTORY; i++) {
3714                                 view->drag_info.buffer[i].x = event->x;
3715                                 view->drag_info.buffer[i].y = event->y;
3716                         }
3717                         view->drag_info.momentum.x = 0;
3718                         view->drag_info.momentum.y = 0;
3719                 }
3720
3721                 if (view->drag_info.in_drag) {
3722                         int dx, dy;
3723                         gdouble dhadj_value, dvadj_value;
3724                         GtkAllocation allocation;
3725
3726                         view->drag_info.buffer[0].x = event->x;
3727                         view->drag_info.buffer[0].y = event->y;
3728
3729                         dx = event->x_root - view->drag_info.start.x;
3730                         dy = event->y_root - view->drag_info.start.y;
3731
3732                         gtk_widget_get_allocation (widget, &allocation);
3733
3734                         dhadj_value = gtk_adjustment_get_page_size (view->hadjustment) *
3735                                       (gdouble)dx / allocation.width;
3736                         dvadj_value = gtk_adjustment_get_page_size (view->vadjustment) *
3737                                       (gdouble)dy / allocation.height;
3738
3739                         /* clamp scrolling to visible area */
3740                         gtk_adjustment_set_value (view->hadjustment,
3741                                                   MIN (view->drag_info.hadj - dhadj_value,
3742                                                        gtk_adjustment_get_upper (view->hadjustment) -
3743                                                        gtk_adjustment_get_page_size (view->hadjustment)));
3744                         gtk_adjustment_set_value (view->vadjustment,
3745                                                   MIN (view->drag_info.vadj - dvadj_value,
3746                                                        gtk_adjustment_get_upper (view->vadjustment) -
3747                                                        gtk_adjustment_get_page_size (view->vadjustment)));
3748
3749                         return TRUE;
3750                 }
3751
3752                 break;
3753         default:
3754                 ev_view_handle_cursor_over_xy (view, x, y);
3755         } 
3756
3757         return FALSE;
3758 }
3759
3760 static gboolean
3761 ev_view_button_release_event (GtkWidget      *widget,
3762                               GdkEventButton *event)
3763 {
3764         EvView *view = EV_VIEW (widget);
3765         EvLink *link = NULL;
3766
3767         view->image_dnd_info.in_drag = FALSE;
3768
3769         if (view->scroll_info.autoscrolling) {
3770                 ev_view_autoscroll_stop (view);
3771                 view->pressed_button = -1;
3772
3773                 return TRUE;
3774         } 
3775
3776         if (view->drag_info.in_drag) {
3777                 view->drag_info.release_timeout_id =
3778                         g_timeout_add (20,
3779                                        (GSourceFunc)ev_view_scroll_drag_release, view);
3780         }
3781
3782         if (view->document && !view->drag_info.in_drag && view->pressed_button != 3) {
3783                 link = ev_view_get_link_at_location (view, event->x, event->y);
3784         }
3785
3786         view->drag_info.in_drag = FALSE;
3787
3788         if (view->pressed_button == 2) {
3789                 ev_view_handle_cursor_over_xy (view, event->x, event->y);
3790         }
3791
3792         view->pressed_button = -1;
3793
3794         if (view->selection_scroll_id) {
3795             g_source_remove (view->selection_scroll_id);
3796             view->selection_scroll_id = 0;
3797         }
3798         if (view->selection_update_id) {
3799             g_source_remove (view->selection_update_id);
3800             view->selection_update_id = 0;
3801         }
3802
3803         if (view->selection_info.selections) {
3804                 clear_link_selected (view);
3805                 ev_view_update_primary_selection (view);
3806                 
3807                 if (view->selection_info.in_drag) {
3808                         clear_selection (view);
3809                         gtk_widget_queue_draw (widget);
3810                 }
3811                 
3812                 view->selection_info.in_drag = FALSE;
3813         } else if (link) {
3814                 if (event->button == 2) {
3815                         EvLinkAction    *action;
3816                         EvLinkActionType type;
3817
3818                         action = ev_link_get_action (link);
3819                         if (!action)
3820                                 return FALSE;
3821
3822                         type = ev_link_action_get_action_type (action);
3823                         if (type == EV_LINK_ACTION_TYPE_GOTO_DEST) {
3824                                 g_signal_emit (view,
3825                                                signals[SIGNAL_EXTERNAL_LINK],
3826                                                0, action);
3827                         }
3828                 } else {
3829                         ev_view_handle_link (view, link);
3830                 }
3831         }
3832
3833         return FALSE;
3834 }
3835
3836 static gboolean
3837 ev_view_key_press_event (GtkWidget   *widget,
3838                          GdkEventKey *event)
3839 {
3840         EvView *view = EV_VIEW (widget);
3841
3842         if (!view->document)
3843                 return FALSE;
3844
3845         if (!gtk_widget_has_focus (widget)) {
3846                 /* Forward key events to current focused window child */
3847                 if (view->window_child_focus) {
3848                         GdkEventKey *new_event;
3849                         gboolean     handled;
3850
3851                         new_event = (GdkEventKey *) gdk_event_copy ((GdkEvent *)event);
3852                         g_object_unref (new_event->window);
3853                         new_event->window = gtk_widget_get_window (view->window_child_focus->window);
3854                         if (new_event->window)
3855                                 g_object_ref (new_event->window);
3856                         gtk_widget_realize (view->window_child_focus->window);
3857                         handled = gtk_widget_event (view->window_child_focus->window, (GdkEvent *)new_event);
3858                         gdk_event_free ((GdkEvent *)new_event);
3859
3860                         return handled;
3861                 }
3862
3863                 return FALSE;
3864         }
3865
3866         return gtk_bindings_activate_event (GTK_OBJECT (widget), event);
3867 }
3868
3869 static gint
3870 ev_view_focus_in (GtkWidget     *widget,
3871                   GdkEventFocus *event)
3872 {
3873         if (EV_VIEW (widget)->pixbuf_cache)
3874                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
3875         gtk_widget_queue_draw (widget);
3876
3877         return FALSE;
3878 }
3879
3880 static gint
3881 ev_view_focus_out (GtkWidget     *widget,
3882                    GdkEventFocus *event)
3883 {
3884         if (EV_VIEW (widget)->pixbuf_cache)
3885                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
3886         gtk_widget_queue_draw (widget);
3887
3888         return FALSE;
3889 }
3890
3891 static gboolean
3892 ev_view_leave_notify_event (GtkWidget *widget, GdkEventCrossing   *event)
3893 {
3894         EvView *view = EV_VIEW (widget);
3895
3896         if (view->cursor != EV_VIEW_CURSOR_NORMAL)
3897                 ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
3898
3899         return FALSE;
3900 }
3901
3902 static gboolean
3903 ev_view_enter_notify_event (GtkWidget *widget, GdkEventCrossing   *event)
3904 {
3905         EvView *view = EV_VIEW (widget);
3906
3907         ev_view_handle_cursor_over_xy (view, event->x, event->y);
3908     
3909         return FALSE;
3910 }
3911
3912 static void
3913 ev_view_style_set (GtkWidget *widget,
3914                    GtkStyle  *old_style)
3915 {
3916         if (EV_VIEW (widget)->pixbuf_cache)
3917                 ev_pixbuf_cache_style_changed (EV_VIEW (widget)->pixbuf_cache);
3918
3919         GTK_WIDGET_CLASS (ev_view_parent_class)->style_set (widget, old_style);
3920 }
3921
3922 /*** Drawing ***/
3923
3924 static void
3925 draw_rubberband (EvView             *view,
3926                  GdkWindow          *window,
3927                  const GdkRectangle *rect,
3928                  gdouble             alpha)
3929 {
3930         GtkStyle *style;
3931         GdkColor *fill_color_gdk;
3932         gdouble   r, g, b;
3933         cairo_t  *cr;
3934
3935         style = gtk_widget_get_style (GTK_WIDGET (view));
3936         fill_color_gdk = gdk_color_copy (&style->base[GTK_STATE_SELECTED]);
3937         r = fill_color_gdk->red / 65535.;
3938         g = fill_color_gdk->green / 65535.;
3939         b = fill_color_gdk->blue / 65535.;
3940
3941         cr = gdk_cairo_create (window);
3942
3943         cairo_set_source_rgba (cr, r, g, b, alpha);
3944         cairo_rectangle (cr,
3945                          rect->x - view->scroll_x,
3946                          rect->y - view->scroll_y,
3947                          rect->width, rect->height);
3948         cairo_fill_preserve (cr);
3949
3950         cairo_set_line_width (cr, 0.5);
3951         cairo_set_source_rgb (cr, r, g, b);
3952         cairo_stroke (cr);
3953
3954         cairo_destroy (cr);
3955
3956         gdk_color_free (fill_color_gdk);
3957 }
3958
3959
3960 static void
3961 highlight_find_results (EvView *view, int page)
3962 {
3963         gint       i, n_results = 0;
3964         GdkWindow *bin_window;
3965
3966         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
3967
3968         n_results = ev_view_find_get_n_results (view, page);
3969
3970         for (i = 0; i < n_results; i++) {
3971                 EvRectangle *rectangle;
3972                 GdkRectangle view_rectangle;
3973                 gdouble      alpha;
3974
3975                 if (i == view->find_result && page == view->current_page) {
3976                         alpha = 0.6;
3977                 } else {
3978                         alpha = 0.3;
3979                 }
3980
3981                 rectangle = ev_view_find_get_result (view, page, i);
3982                 doc_rect_to_view_rect (view, page, rectangle, &view_rectangle);
3983                 draw_rubberband (view, bin_window, &view_rectangle, alpha);
3984         }
3985 }
3986
3987 static void
3988 ev_view_loading_window_move (EvView *view)
3989 {
3990         GtkWidget       *widget = GTK_WIDGET (view);
3991         EvLoadingWindow *window = EV_LOADING_WINDOW (view->loading_window);
3992         gint             root_x, root_y;
3993         gint             window_width;
3994         GtkAllocation    allocation;
3995
3996         gtk_widget_get_allocation (widget, &allocation);
3997         gdk_window_get_origin (gtk_widget_get_window (widget), &root_x, &root_y);
3998         ev_loading_window_get_size (window, &window_width, NULL);
3999
4000         root_x += allocation.width - window_width - 10;
4001         root_y += 10;
4002
4003         ev_loading_window_move (window, root_x, root_y);
4004 }
4005
4006 static gboolean
4007 show_loading_window_cb (EvView *view)
4008 {
4009         if (!view->loading_window) {
4010                 GtkWindow *parent;
4011                 GdkScreen *screen;
4012
4013                 parent = GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET (view)));
4014                 view->loading_window = ev_loading_window_new (parent);
4015
4016                 /* Show the window off screen to get a valid size asap */
4017                 screen = gtk_widget_get_screen (GTK_WIDGET (view));
4018                 gtk_window_move (GTK_WINDOW (view->loading_window),
4019                                  gdk_screen_get_width (screen) + 1,
4020                                  gdk_screen_get_height (screen) + 1);
4021                 gtk_widget_show (view->loading_window);
4022         }
4023
4024         ev_view_loading_window_move (view);
4025
4026         gtk_widget_show (view->loading_window);
4027
4028         view->loading_timeout = 0;
4029
4030         return FALSE;
4031 }
4032
4033 static void
4034 show_loading_window (EvView *view)
4035 {
4036         if (view->loading_window && gtk_widget_get_visible (view->loading_window)) {
4037                 ev_view_loading_window_move (view);
4038                 return;
4039         }
4040
4041         if (!view->loading_timeout) {
4042                 view->loading_timeout =
4043                         g_timeout_add_full (G_PRIORITY_LOW,
4044                                             0.5, (GSourceFunc)show_loading_window_cb,
4045                                             view, NULL);
4046         }
4047 }
4048
4049 static void
4050 hide_loading_window (EvView *view)
4051 {
4052         if (view->loading_timeout) {
4053                 g_source_remove (view->loading_timeout);
4054                 view->loading_timeout = 0;
4055         }
4056
4057         if (view->loading_window && gtk_widget_get_visible (view->loading_window)) {
4058                 gtk_widget_hide (view->loading_window);
4059         }
4060 }
4061
4062 static void
4063 draw_one_page (EvView       *view,
4064                gint          page,
4065                cairo_t      *cr,
4066                GdkRectangle *page_area,
4067                GtkBorder    *border,
4068                GdkRectangle *expose_area,
4069                gboolean     *page_ready)
4070 {
4071         GdkWindow   *bin_window;
4072         GdkRectangle overlap;
4073         GdkRectangle real_page_area;
4074         gint         current_page;
4075         gboolean     inverted_colors;
4076
4077         g_assert (view->document);
4078
4079         if (! gdk_rectangle_intersect (page_area, expose_area, &overlap))
4080                 return;
4081
4082         /* Render the document itself */
4083         real_page_area = *page_area;
4084
4085         real_page_area.x += border->left;
4086         real_page_area.y += border->top;
4087         real_page_area.width -= (border->left + border->right);
4088         real_page_area.height -= (border->top + border->bottom);
4089         *page_ready = TRUE;
4090
4091         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
4092         current_page = ev_document_model_get_page (view->model);
4093         inverted_colors = ev_document_model_get_inverted_colors (view->model);
4094         ev_document_misc_paint_one_page (bin_window,
4095                                          GTK_WIDGET (view),
4096                                          page_area, border,
4097                                          page == current_page,
4098                                          inverted_colors);
4099
4100         if (gdk_rectangle_intersect (&real_page_area, expose_area, &overlap)) {
4101                 gint             width, height;
4102                 gint             page_width, page_height;
4103                 cairo_surface_t *page_surface = NULL;
4104                 gint             selection_width, selection_height;
4105                 cairo_surface_t *selection_surface = NULL;
4106
4107                 page_surface = ev_pixbuf_cache_get_surface (view->pixbuf_cache, page);
4108
4109                 if (!page_surface) {
4110                         if (page == current_page)
4111                                 show_loading_window (view);
4112
4113                         *page_ready = FALSE;
4114
4115                         return;
4116                 }
4117
4118                 if (page == current_page)
4119                         hide_loading_window (view);
4120
4121                 ev_view_get_page_size (view, page, &width, &height);
4122
4123                 page_width = cairo_image_surface_get_width (page_surface);
4124                 page_height = cairo_image_surface_get_height (page_surface);
4125
4126                 cairo_save (cr);
4127                 cairo_translate (cr, overlap.x, overlap.y);
4128
4129                 if (width != page_width || height != page_height) {
4130                         cairo_pattern_set_filter (cairo_get_source (cr),
4131                                                   CAIRO_FILTER_FAST);
4132                         cairo_scale (cr,
4133                                      (gdouble)width / page_width,
4134                                      (gdouble)height / page_height);
4135                 }
4136
4137                 cairo_surface_set_device_offset (page_surface,
4138                                                  overlap.x - real_page_area.x,
4139                                                  overlap.y - real_page_area.y);
4140                 cairo_set_source_surface (cr, page_surface, 0, 0);
4141                 cairo_paint (cr);
4142                 cairo_restore (cr);
4143                 
4144                 /* Get the selection pixbuf iff we have something to draw */
4145                 if (find_selection_for_page (view, page) &&
4146                     view->selection_mode == EV_VIEW_SELECTION_TEXT) {
4147                         selection_surface =
4148                                 ev_pixbuf_cache_get_selection_surface (view->pixbuf_cache,
4149                                                                        page,
4150                                                                        view->scale,
4151                                                                        NULL);
4152                 }
4153
4154                 if (!selection_surface) {
4155                         return;
4156                 }
4157
4158                 selection_width = cairo_image_surface_get_width (selection_surface);
4159                 selection_height = cairo_image_surface_get_height (selection_surface);
4160
4161                 cairo_save (cr);
4162                 cairo_translate (cr, overlap.x, overlap.y);
4163
4164                 if (width != selection_width || height != selection_height) {
4165                         cairo_pattern_set_filter (cairo_get_source (cr),
4166                                                   CAIRO_FILTER_FAST);
4167                         cairo_scale (cr,
4168                                      (gdouble)width / selection_width,
4169                                      (gdouble)height / selection_height);
4170                 }
4171
4172                 cairo_surface_set_device_offset (selection_surface,
4173                                                  overlap.x - real_page_area.x,
4174                                                  overlap.y - real_page_area.y);
4175                 cairo_set_source_surface (cr, selection_surface, 0, 0);
4176                 cairo_paint (cr);
4177                 cairo_restore (cr);
4178         }
4179 }
4180
4181 /*** GObject functions ***/
4182
4183 static void
4184 ev_view_finalize (GObject *object)
4185 {
4186         EvView *view = EV_VIEW (object);
4187
4188         clear_selection (view);
4189         clear_link_selected (view);
4190
4191         if (view->image_dnd_info.image)
4192                 g_object_unref (view->image_dnd_info.image);
4193         view->image_dnd_info.image = NULL;
4194
4195         G_OBJECT_CLASS (ev_view_parent_class)->finalize (object);
4196 }
4197
4198 static void
4199 ev_view_destroy (GtkObject *object)
4200 {
4201         EvView *view = EV_VIEW (object);
4202
4203         if (view->model) {
4204                 g_object_unref (view->model);
4205                 view->model = NULL;
4206         }
4207
4208         if (view->pixbuf_cache) {
4209                 g_object_unref (view->pixbuf_cache);
4210                 view->pixbuf_cache = NULL;
4211         }
4212
4213         if (view->document) {
4214                 g_object_unref (view->document);
4215                 view->document = NULL;
4216         }
4217
4218         if (view->page_cache) {
4219                 g_object_unref (view->page_cache);
4220                 view->page_cache = NULL;
4221         }
4222
4223         ev_view_window_children_free (view);
4224
4225         if (view->selection_scroll_id) {
4226             g_source_remove (view->selection_scroll_id);
4227             view->selection_scroll_id = 0;
4228         }
4229
4230         if (view->selection_update_id) {
4231             g_source_remove (view->selection_update_id);
4232             view->selection_update_id = 0;
4233         }
4234
4235         if (view->scroll_info.timeout_id) {
4236             g_source_remove (view->scroll_info.timeout_id);
4237             view->scroll_info.timeout_id = 0;
4238         }
4239
4240         if (view->drag_info.drag_timeout_id) {
4241                 g_source_remove (view->drag_info.drag_timeout_id);
4242                 view->drag_info.drag_timeout_id = 0;
4243         }
4244
4245         if (view->drag_info.release_timeout_id) {
4246                 g_source_remove (view->drag_info.release_timeout_id);
4247                 view->drag_info.release_timeout_id = 0;
4248         }
4249
4250         if (view->loading_timeout) {
4251                 g_source_remove (view->loading_timeout);
4252                 view->loading_timeout = 0;
4253         }
4254
4255         ev_view_set_scroll_adjustments (GTK_LAYOUT (view), NULL, NULL);
4256
4257         GTK_OBJECT_CLASS (ev_view_parent_class)->destroy (object);
4258 }
4259
4260 static AtkObject *
4261 ev_view_get_accessible (GtkWidget *widget)
4262 {
4263         static gboolean first_time = TRUE;
4264
4265         if (first_time) {
4266                 AtkObjectFactory *factory;
4267                 AtkRegistry *registry;
4268                 GType derived_type; 
4269                 GType derived_atk_type; 
4270
4271                 /*
4272                  * Figure out whether accessibility is enabled by looking at the
4273                  * type of the accessible object which would be created for
4274                  * the parent type of EvView.
4275                  */
4276                 derived_type = g_type_parent (EV_TYPE_VIEW);
4277
4278                 registry = atk_get_default_registry ();
4279                 factory = atk_registry_get_factory (registry,
4280                                                     derived_type);
4281                 derived_atk_type = atk_object_factory_get_accessible_type (factory);
4282                 if (g_type_is_a (derived_atk_type, GTK_TYPE_ACCESSIBLE)) 
4283                         atk_registry_set_factory_type (registry, 
4284                                                        EV_TYPE_VIEW,
4285                                                        ev_view_accessible_factory_get_type ());
4286                 first_time = FALSE;
4287         } 
4288         return GTK_WIDGET_CLASS (ev_view_parent_class)->get_accessible (widget);
4289 }
4290
4291 static void
4292 ev_view_class_init (EvViewClass *class)
4293 {
4294         GObjectClass *object_class = G_OBJECT_CLASS (class);
4295         GtkObjectClass *gtk_object_class = GTK_OBJECT_CLASS (class);
4296         GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
4297         GtkLayoutClass *layout_class = GTK_LAYOUT_CLASS (class);
4298         GtkBindingSet *binding_set;
4299
4300         object_class->finalize = ev_view_finalize;
4301
4302         widget_class->expose_event = ev_view_expose_event;
4303         widget_class->button_press_event = ev_view_button_press_event;
4304         widget_class->motion_notify_event = ev_view_motion_notify_event;
4305         widget_class->button_release_event = ev_view_button_release_event;
4306         widget_class->key_press_event = ev_view_key_press_event;
4307         widget_class->focus_in_event = ev_view_focus_in;
4308         widget_class->focus_out_event = ev_view_focus_out;
4309         widget_class->get_accessible = ev_view_get_accessible;
4310         widget_class->size_request = ev_view_size_request;
4311         widget_class->size_allocate = ev_view_size_allocate;
4312         widget_class->realize = ev_view_realize;
4313         widget_class->scroll_event = ev_view_scroll_event;
4314         widget_class->enter_notify_event = ev_view_enter_notify_event;
4315         widget_class->leave_notify_event = ev_view_leave_notify_event;
4316         widget_class->style_set = ev_view_style_set;
4317         widget_class->drag_data_get = ev_view_drag_data_get;
4318         widget_class->drag_motion = ev_view_drag_motion;
4319         widget_class->popup_menu = ev_view_popup_menu;
4320         widget_class->query_tooltip = ev_view_query_tooltip;
4321
4322         gtk_object_class->destroy = ev_view_destroy;
4323
4324         layout_class->set_scroll_adjustments = ev_view_set_scroll_adjustments;
4325         
4326         class->binding_activated = ev_view_scroll;
4327
4328         signals[SIGNAL_BINDING_ACTIVATED] = g_signal_new ("binding_activated",
4329                          G_TYPE_FROM_CLASS (object_class),
4330                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4331                          G_STRUCT_OFFSET (EvViewClass, binding_activated),
4332                          NULL, NULL,
4333                          ev_view_marshal_VOID__ENUM_BOOLEAN,
4334                          G_TYPE_NONE, 2,
4335                          GTK_TYPE_SCROLL_TYPE,
4336                          G_TYPE_BOOLEAN);
4337         signals[SIGNAL_HANDLE_LINK] = g_signal_new ("handle-link",
4338                          G_TYPE_FROM_CLASS (object_class),
4339                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4340                          G_STRUCT_OFFSET (EvViewClass, handle_link),
4341                          NULL, NULL,
4342                          g_cclosure_marshal_VOID__OBJECT,
4343                          G_TYPE_NONE, 1,
4344                          G_TYPE_OBJECT);
4345         signals[SIGNAL_EXTERNAL_LINK] = g_signal_new ("external-link",
4346                          G_TYPE_FROM_CLASS (object_class),
4347                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4348                          G_STRUCT_OFFSET (EvViewClass, external_link),
4349                          NULL, NULL,
4350                          g_cclosure_marshal_VOID__OBJECT,
4351                          G_TYPE_NONE, 1,
4352                          G_TYPE_OBJECT);
4353         signals[SIGNAL_POPUP_MENU] = g_signal_new ("popup",
4354                          G_TYPE_FROM_CLASS (object_class),
4355                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4356                          G_STRUCT_OFFSET (EvViewClass, popup_menu),
4357                          NULL, NULL,
4358                          g_cclosure_marshal_VOID__POINTER,
4359                          G_TYPE_NONE, 1,
4360                          G_TYPE_POINTER);
4361         signals[SIGNAL_SELECTION_CHANGED] = g_signal_new ("selection-changed",
4362                          G_TYPE_FROM_CLASS (object_class),
4363                          G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
4364                          G_STRUCT_OFFSET (EvViewClass, selection_changed),
4365                          NULL, NULL,
4366                          g_cclosure_marshal_VOID__VOID,
4367                          G_TYPE_NONE, 0,
4368                          G_TYPE_NONE);
4369
4370         binding_set = gtk_binding_set_by_class (class);
4371
4372         add_scroll_binding_keypad (binding_set, GDK_Left,  0, GTK_SCROLL_STEP_BACKWARD, TRUE);
4373         add_scroll_binding_keypad (binding_set, GDK_Right, 0, GTK_SCROLL_STEP_FORWARD,  TRUE);
4374         add_scroll_binding_keypad (binding_set, GDK_Left,  GDK_MOD1_MASK, GTK_SCROLL_STEP_DOWN, TRUE);
4375         add_scroll_binding_keypad (binding_set, GDK_Right, GDK_MOD1_MASK, GTK_SCROLL_STEP_UP,  TRUE);
4376         add_scroll_binding_keypad (binding_set, GDK_Up,    0, GTK_SCROLL_STEP_BACKWARD, FALSE);
4377         add_scroll_binding_keypad (binding_set, GDK_Down,  0, GTK_SCROLL_STEP_FORWARD,  FALSE);
4378         add_scroll_binding_keypad (binding_set, GDK_Up,    GDK_MOD1_MASK, GTK_SCROLL_STEP_DOWN, FALSE);
4379         add_scroll_binding_keypad (binding_set, GDK_Down,  GDK_MOD1_MASK, GTK_SCROLL_STEP_UP,  FALSE);
4380         gtk_binding_entry_add_signal (binding_set, GDK_H, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4381                                       GTK_SCROLL_STEP_BACKWARD, G_TYPE_BOOLEAN, TRUE);
4382         gtk_binding_entry_add_signal (binding_set, GDK_J, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4383                                       GTK_SCROLL_STEP_FORWARD, G_TYPE_BOOLEAN, FALSE);
4384         gtk_binding_entry_add_signal (binding_set, GDK_K, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4385                                       GTK_SCROLL_STEP_BACKWARD, G_TYPE_BOOLEAN, FALSE);
4386         gtk_binding_entry_add_signal (binding_set, GDK_L, 0, "binding_activated", 2, GTK_TYPE_SCROLL_TYPE,
4387                                       GTK_SCROLL_STEP_FORWARD, G_TYPE_BOOLEAN, TRUE);
4388         
4389 }
4390
4391 static void
4392 ev_view_init (EvView *view)
4393 {
4394         gtk_widget_set_can_focus (GTK_WIDGET (view), TRUE);
4395
4396         view->start_page = -1;
4397         view->end_page = -1;
4398         view->spacing = 5;
4399         view->scale = 1.0;
4400         view->current_page = 0;
4401         view->pressed_button = -1;
4402         view->cursor = EV_VIEW_CURSOR_NORMAL;
4403         view->drag_info.in_drag = FALSE;
4404         view->scroll_info.autoscrolling = FALSE;
4405         view->selection_info.selections = NULL;
4406         view->selection_info.in_selection = FALSE;
4407         view->selection_info.in_drag = FALSE;
4408         view->selection_mode = EV_VIEW_SELECTION_TEXT;
4409         view->continuous = TRUE;
4410         view->dual_page = FALSE;
4411         view->fullscreen = FALSE;
4412         view->sizing_mode = EV_SIZING_FIT_WIDTH;
4413         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
4414         view->jump_to_find_result = TRUE;
4415         view->highlight_find_results = FALSE;
4416
4417         gtk_layout_set_hadjustment (GTK_LAYOUT (view), NULL);
4418         gtk_layout_set_vadjustment (GTK_LAYOUT (view), NULL);
4419 }
4420
4421 /*** Callbacks ***/
4422
4423 static void
4424 ev_view_change_page (EvView *view,
4425                      gint    new_page)
4426 {
4427         gint x, y;
4428
4429         view->current_page = new_page;
4430         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
4431
4432         hide_loading_window (view);
4433
4434         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
4435         ev_view_handle_cursor_over_xy (view, x, y);
4436
4437         gtk_widget_queue_resize (GTK_WIDGET (view));
4438 }
4439
4440 static void
4441 job_finished_cb (EvPixbufCache *pixbuf_cache,
4442                  GdkRegion     *region,
4443                  EvView        *view)
4444 {
4445         if (region) {
4446                 GdkWindow *bin_window;
4447
4448                 bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
4449                 gdk_window_invalidate_region (bin_window, region, TRUE);
4450         } else {
4451                 gtk_widget_queue_draw (GTK_WIDGET (view));
4452         }
4453 }
4454
4455 static void
4456 ev_view_page_changed_cb (EvDocumentModel *model,
4457                          gint             old_page,
4458                          gint             new_page,
4459                          EvView          *view)
4460 {
4461         if (!view->document)
4462                 return;
4463
4464         if (view->current_page != new_page) {
4465                 ev_view_change_page (view, new_page);
4466         } else {
4467                 gtk_widget_queue_draw (GTK_WIDGET (view));
4468         }
4469
4470         view->find_result = 0;
4471 }
4472
4473 static void
4474 on_adjustment_value_changed (GtkAdjustment *adjustment,
4475                              EvView        *view)
4476 {
4477         int dx = 0, dy = 0;
4478         gint x, y;
4479         gint value;
4480         GList *children, *l;
4481
4482         if (!gtk_widget_get_realized (GTK_WIDGET (view)))
4483                 return;
4484
4485         if (view->hadjustment) {
4486                 value = (gint) gtk_adjustment_get_value (view->hadjustment);
4487                 dx = view->scroll_x - value;
4488                 view->scroll_x = value;
4489         } else {
4490                 view->scroll_x = 0;
4491         }
4492
4493         if (view->vadjustment) {
4494                 value = (gint) gtk_adjustment_get_value (view->vadjustment);
4495                 dy = view->scroll_y - value;
4496                 view->scroll_y = value;
4497         } else {
4498                 view->scroll_y = 0;
4499         }
4500
4501         children = gtk_container_get_children (GTK_CONTAINER (view));
4502         for (l = children; l && l->data; l = g_list_next (l)) {
4503                 gint       child_x, child_y;
4504                 GtkWidget *child = (GtkWidget *)l->data;
4505                 
4506                 gtk_container_child_get (GTK_CONTAINER (view),
4507                                          child,
4508                                          "x", &child_x,
4509                                          "y", &child_y,
4510                                          NULL);
4511                 gtk_layout_move (GTK_LAYOUT (view), child, child_x + dx, child_y + dy);
4512         }
4513         g_list_free (children);
4514
4515         for (l = view->window_children; l && l->data; l = g_list_next (l)) {
4516                 EvViewWindowChild *child;
4517
4518                 child = (EvViewWindowChild *)l->data;
4519
4520                 ev_view_window_child_move (view, child, child->x + dx, child->y + dy);
4521         }
4522         
4523         if (view->pending_resize) {
4524                 gtk_widget_queue_draw (GTK_WIDGET (view));
4525         } else {
4526                 GdkWindow *bin_window;
4527
4528                 bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
4529                 gdk_window_scroll (bin_window, dx, dy);
4530         }
4531
4532         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
4533         ev_view_handle_cursor_over_xy (view, x, y);
4534
4535         if (view->document)
4536                 view_update_range_and_current_page (view);
4537 }
4538
4539 GtkWidget*
4540 ev_view_new (void)
4541 {
4542         GtkWidget *view;
4543
4544         view = g_object_new (EV_TYPE_VIEW, NULL);
4545
4546         return view;
4547 }
4548
4549 static void
4550 setup_caches (EvView *view)
4551 {
4552         gboolean inverted_colors;
4553
4554         view->height_to_page_cache = ev_view_get_height_to_page_cache (view);
4555         view->pixbuf_cache = ev_pixbuf_cache_new (GTK_WIDGET (view), view->model, view->pixbuf_cache_size);
4556         view->page_cache = ev_page_cache_new (view->document);
4557         inverted_colors = ev_document_model_get_inverted_colors (view->model);
4558         ev_pixbuf_cache_set_inverted_colors (view->pixbuf_cache, inverted_colors);
4559         g_signal_connect (view->pixbuf_cache, "job-finished", G_CALLBACK (job_finished_cb), view);
4560 }
4561
4562 static void
4563 clear_caches (EvView *view)
4564 {
4565         if (view->pixbuf_cache) {
4566                 g_object_unref (view->pixbuf_cache);
4567                 view->pixbuf_cache = NULL;
4568         }
4569
4570         if (view->page_cache) {
4571                 g_object_unref (view->page_cache);
4572                 view->page_cache = NULL;
4573         }
4574 }
4575
4576 /**
4577  * ev_view_set_page_cache_size:
4578  * @view:
4579  * @cache_size:
4580  *
4581  * Sets the maximum size in bytes that will be used to cache
4582  * rendered pages. Use 0 to disable caching rendered pages.
4583  *
4584  * Note that this limit doesn't affect the current visible page range,
4585  * which will always be rendered. In order to limit the total memory used
4586  * you have to use ev_document_model_set_max_scale() too.
4587  *
4588  */
4589 void
4590 ev_view_set_page_cache_size (EvView *view,
4591                              gsize   cache_size)
4592 {
4593         if (view->pixbuf_cache_size == cache_size)
4594                 return;
4595
4596         view->pixbuf_cache_size = cache_size;
4597         if (view->pixbuf_cache)
4598                 ev_pixbuf_cache_set_max_size (view->pixbuf_cache, cache_size);
4599 }
4600
4601 void
4602 ev_view_set_loading (EvView       *view,
4603                      gboolean      loading)
4604 {
4605         if (view->loading && !loading)
4606                 hide_loading_window (view);
4607         view->loading = loading;
4608         gtk_widget_queue_draw (GTK_WIDGET (view));
4609 }
4610
4611 static gboolean
4612 ev_view_autoscroll_cb (EvView *view)
4613 {
4614         gdouble speed, value;
4615
4616         /* If the user stops autoscrolling, autoscrolling will be
4617          * set to false but the timeout will continue; stop the timeout: */
4618         if (!view->scroll_info.autoscrolling) {
4619                 view->scroll_info.timeout_id = 0;
4620                 return FALSE;
4621         }
4622         
4623         if (view->scroll_info.last_y > view->scroll_info.start_y && 
4624                 (view->scroll_info.last_y < view->scroll_info.start_y))
4625                 return TRUE; 
4626
4627         /* Replace 100 with your speed of choice: The lower the faster.
4628          * Replace 3 with another speed of choice: The higher, the faster it accelerated
4629          *      based on the distance of the starting point from the mouse
4630          * (All also effected by the timeout interval of this callback) */
4631
4632         if (view->scroll_info.start_y > view->scroll_info.last_y)
4633                 speed = -pow ((((gdouble)view->scroll_info.start_y - view->scroll_info.last_y) / 100), 3);
4634         else
4635                 speed = pow ((((gdouble)view->scroll_info.last_y - view->scroll_info.start_y) / 100), 3);
4636         
4637         value = gtk_adjustment_get_value (view->vadjustment);
4638         value = CLAMP (value + speed, 0,
4639                        gtk_adjustment_get_upper (view->vadjustment) -
4640                        gtk_adjustment_get_page_size (view->vadjustment));
4641         gtk_adjustment_set_value (view->vadjustment, value);
4642         
4643         return TRUE;
4644
4645 }
4646
4647 void
4648 ev_view_autoscroll_start (EvView *view)
4649 {
4650         gint x, y;
4651         
4652         g_return_if_fail (EV_IS_VIEW (view));
4653
4654         if (view->scroll_info.autoscrolling)
4655                 return;
4656         
4657         view->scroll_info.autoscrolling = TRUE;
4658         view->scroll_info.timeout_id =
4659                 g_timeout_add (20, (GSourceFunc)ev_view_autoscroll_cb,
4660                                view);
4661         
4662         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
4663         ev_view_handle_cursor_over_xy (view, x, y);
4664 }
4665
4666 void
4667 ev_view_autoscroll_stop (EvView *view)
4668 {
4669         gint x, y;
4670         
4671         g_return_if_fail (EV_IS_VIEW (view));
4672
4673         if (!view->scroll_info.autoscrolling)
4674                 return;
4675
4676         view->scroll_info.autoscrolling = FALSE;
4677         if (view->scroll_info.timeout_id) {
4678                 g_source_remove (view->scroll_info.timeout_id);
4679                 view->scroll_info.timeout_id = 0;
4680         }
4681
4682         gtk_widget_get_pointer (GTK_WIDGET (view), &x, &y);
4683         ev_view_handle_cursor_over_xy (view, x, y);
4684 }
4685
4686 static void
4687 ev_view_document_changed_cb (EvDocumentModel *model,
4688                              GParamSpec      *pspec,
4689                              EvView          *view)
4690 {
4691         EvDocument *document = ev_document_model_get_document (model);
4692
4693         if (document != view->document) {
4694                 gint current_page;
4695
4696                 clear_caches (view);
4697
4698                 if (view->document) {
4699                         g_object_unref (view->document);
4700                 }
4701
4702                 view->document = document;
4703                 view->find_result = 0;
4704
4705                 if (view->document) {
4706                         view->loading = FALSE;
4707                         g_object_ref (view->document);
4708                         setup_caches (view);
4709                 }
4710
4711                 current_page = ev_document_model_get_page (model);
4712                 if (view->current_page != current_page) {
4713                         ev_view_change_page (view, current_page);
4714                 } else {
4715                         view->pending_scroll = SCROLL_TO_KEEP_POSITION;
4716                         gtk_widget_queue_resize (GTK_WIDGET (view));
4717                 }
4718         }
4719 }
4720
4721 static void
4722 ev_view_rotation_changed_cb (EvDocumentModel *model,
4723                              GParamSpec      *pspec,
4724                              EvView          *view)
4725 {
4726         gint rotation = ev_document_model_get_rotation (model);
4727
4728         view->rotation = rotation;
4729
4730         if (view->pixbuf_cache) {
4731                 ev_pixbuf_cache_clear (view->pixbuf_cache);
4732                 if (!ev_document_is_page_size_uniform (view->document))
4733                         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
4734                 gtk_widget_queue_resize (GTK_WIDGET (view));
4735         }
4736
4737         ev_view_remove_all (view);
4738
4739         if (rotation != 0)
4740                 clear_selection (view);
4741 }
4742
4743 static void
4744 ev_view_inverted_colors_changed_cb (EvDocumentModel *model,
4745                                     GParamSpec      *pspec,
4746                                     EvView          *view)
4747 {
4748         if (view->pixbuf_cache) {
4749                 gboolean inverted_colors;
4750
4751                 inverted_colors = ev_document_model_get_inverted_colors (model);
4752                 ev_pixbuf_cache_set_inverted_colors (view->pixbuf_cache, inverted_colors);
4753                 gtk_widget_queue_draw (GTK_WIDGET (view));
4754         }
4755 }
4756
4757 static void
4758 ev_view_sizing_mode_changed_cb (EvDocumentModel *model,
4759                                 GParamSpec      *pspec,
4760                                 EvView          *view)
4761 {
4762         EvSizingMode mode = ev_document_model_get_sizing_mode (model);
4763
4764         view->sizing_mode = mode;
4765         if (mode != EV_SIZING_FREE)
4766                 gtk_widget_queue_resize (GTK_WIDGET (view));
4767 }
4768
4769 #define EPSILON 0.0000001
4770 static void
4771 ev_view_scale_changed_cb (EvDocumentModel *model,
4772                           GParamSpec      *pspec,
4773                           EvView          *view)
4774 {
4775         gdouble scale = ev_document_model_get_scale (model);
4776
4777         if (ABS (view->scale - scale) < EPSILON)
4778                 return;
4779
4780         view->scale = scale;
4781
4782         view->pending_resize = TRUE;
4783         if (view->sizing_mode == EV_SIZING_FREE)
4784                 gtk_widget_queue_resize (GTK_WIDGET (view));
4785 }
4786
4787 static void
4788 ev_view_continuous_changed_cb (EvDocumentModel *model,
4789                                GParamSpec      *pspec,
4790                                EvView          *view)
4791 {
4792         gboolean continuous = ev_document_model_get_continuous (model);
4793
4794         view->continuous = continuous;
4795         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
4796         gtk_widget_queue_resize (GTK_WIDGET (view));
4797 }
4798
4799 static void
4800 ev_view_dual_page_changed_cb (EvDocumentModel *model,
4801                               GParamSpec      *pspec,
4802                               EvView          *view)
4803 {
4804         gboolean dual_page = ev_document_model_get_dual_page (model);
4805
4806         view->dual_page = dual_page;
4807         view->pending_scroll = SCROLL_TO_PAGE_POSITION;
4808         /* FIXME: if we're keeping the pixbuf cache around, we should extend the
4809          * preload_cache_size to be 2 if dual_page is set.
4810          */
4811         gtk_widget_queue_resize (GTK_WIDGET (view));
4812 }
4813
4814 static void
4815 ev_view_fullscreen_changed_cb (EvDocumentModel *model,
4816                                GParamSpec      *pspec,
4817                                EvView          *view)
4818 {
4819         gboolean fullscreen = ev_document_model_get_fullscreen (model);
4820
4821         view->fullscreen = fullscreen;
4822         gtk_widget_queue_resize (GTK_WIDGET (view));
4823 }
4824
4825 void
4826 ev_view_set_model (EvView          *view,
4827                    EvDocumentModel *model)
4828 {
4829         g_return_if_fail (EV_IS_VIEW (view));
4830         g_return_if_fail (EV_IS_DOCUMENT_MODEL (model));
4831
4832         if (model == view->model)
4833                 return;
4834
4835         if (view->model) {
4836                 g_signal_handlers_disconnect_by_func (view->model,
4837                                                       ev_view_document_changed_cb,
4838                                                       view);
4839                 g_signal_handlers_disconnect_by_func (view->model,
4840                                                       ev_view_page_changed_cb,
4841                                                       view);
4842                 g_object_unref (view->model);
4843         }
4844         view->model = g_object_ref (model);
4845
4846         /* Initialize view from model */
4847         view->rotation = ev_document_model_get_rotation (view->model);
4848         view->sizing_mode = ev_document_model_get_sizing_mode (view->model);
4849         view->scale = ev_document_model_get_scale (view->model);
4850         view->continuous = ev_document_model_get_continuous (view->model);
4851         view->dual_page = ev_document_model_get_dual_page (view->model);
4852         view->fullscreen = ev_document_model_get_fullscreen (view->model);
4853         ev_view_document_changed_cb (view->model, NULL, view);
4854
4855         g_signal_connect (view->model, "notify::document",
4856                           G_CALLBACK (ev_view_document_changed_cb),
4857                           view);
4858         g_signal_connect (view->model, "notify::rotation",
4859                           G_CALLBACK (ev_view_rotation_changed_cb),
4860                           view);
4861         g_signal_connect (view->model, "notify::inverted-colors",
4862                           G_CALLBACK (ev_view_inverted_colors_changed_cb),
4863                           view);
4864         g_signal_connect (view->model, "notify::sizing-mode",
4865                           G_CALLBACK (ev_view_sizing_mode_changed_cb),
4866                           view);
4867         g_signal_connect (view->model, "notify::scale",
4868                           G_CALLBACK (ev_view_scale_changed_cb),
4869                           view);
4870         g_signal_connect (view->model, "notify::continuous",
4871                           G_CALLBACK (ev_view_continuous_changed_cb),
4872                           view);
4873         g_signal_connect (view->model, "notify::dual-page",
4874                           G_CALLBACK (ev_view_dual_page_changed_cb),
4875                           view);
4876         g_signal_connect (view->model, "notify::fullscreen",
4877                           G_CALLBACK (ev_view_fullscreen_changed_cb),
4878                           view);
4879         g_signal_connect (view->model, "page-changed",
4880                           G_CALLBACK (ev_view_page_changed_cb),
4881                           view);
4882 }
4883
4884 static void
4885 ev_view_reload_page (EvView    *view,
4886                      gint       page,
4887                      GdkRegion *region)
4888 {
4889         ev_pixbuf_cache_reload_page (view->pixbuf_cache,
4890                                      region,
4891                                      page,
4892                                      view->rotation,
4893                                      view->scale);
4894 }
4895
4896 void
4897 ev_view_reload (EvView *view)
4898 {
4899         ev_pixbuf_cache_clear (view->pixbuf_cache);
4900         view_update_range_and_current_page (view);
4901 }
4902
4903 /*** Zoom and sizing mode ***/
4904
4905 gboolean
4906 ev_view_can_zoom_in (EvView *view)
4907 {
4908         return view->scale * ZOOM_IN_FACTOR <= ev_document_model_get_max_scale (view->model);
4909 }
4910
4911 gboolean
4912 ev_view_can_zoom_out (EvView *view)
4913 {
4914         return view->scale * ZOOM_OUT_FACTOR >= ev_document_model_get_min_scale (view->model);
4915 }
4916
4917 void
4918 ev_view_zoom_in (EvView *view)
4919 {
4920         gdouble scale;
4921
4922         g_return_if_fail (view->sizing_mode == EV_SIZING_FREE);
4923
4924         view->pending_scroll = SCROLL_TO_CENTER;
4925         scale = ev_document_model_get_scale (view->model) * ZOOM_IN_FACTOR;
4926         ev_document_model_set_scale (view->model, scale);
4927 }
4928
4929 void
4930 ev_view_zoom_out (EvView *view)
4931 {
4932         gdouble scale;
4933
4934         g_return_if_fail (view->sizing_mode == EV_SIZING_FREE);
4935
4936         view->pending_scroll = SCROLL_TO_CENTER;
4937         scale = ev_document_model_get_scale (view->model) * ZOOM_OUT_FACTOR;
4938         ev_document_model_set_scale (view->model, scale);
4939 }
4940
4941 static double
4942 zoom_for_size_fit_width (gdouble doc_width,
4943                          gdouble doc_height,
4944                          int     target_width,
4945                          int     target_height)
4946 {
4947         return (double)target_width / doc_width;
4948 }
4949
4950 static double
4951 zoom_for_size_fit_height (gdouble doc_width,
4952                           gdouble doc_height,
4953                           int     target_width,
4954                           int     target_height)
4955 {
4956         return (double)target_height / doc_height;
4957 }
4958
4959 static double
4960 zoom_for_size_best_fit (gdouble doc_width,
4961                         gdouble doc_height,
4962                         int     target_width,
4963                         int     target_height)
4964 {
4965         double w_scale;
4966         double h_scale;
4967
4968         w_scale = (double)target_width / doc_width;
4969         h_scale = (double)target_height / doc_height;
4970
4971         return MIN (w_scale, h_scale);
4972 }
4973
4974 static void
4975 ev_view_zoom_for_size_continuous_and_dual_page (EvView *view,
4976                                                 int     width,
4977                                                 int     height)
4978 {
4979         gdouble doc_width, doc_height;
4980         GtkBorder border;
4981         gdouble scale;
4982         gint sb_size;
4983
4984         ev_document_get_max_page_size (view->document, &doc_width, &doc_height);
4985         if (view->rotation == 90 || view->rotation == 270) {
4986                 gdouble tmp;
4987
4988                 tmp = doc_width;
4989                 doc_width = doc_height;
4990                 doc_height = tmp;
4991         }
4992
4993         compute_border (view, doc_width, doc_height, &border);
4994
4995         doc_width *= 2;
4996         width -= (2 * (border.left + border.right) + 3 * view->spacing);
4997         height -= (border.top + border.bottom + 2 * view->spacing - 1);
4998
4999         sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5000
5001         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5002                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5003         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5004                 scale = zoom_for_size_best_fit (doc_width, doc_height, width - sb_size, height);
5005         else
5006                 g_assert_not_reached ();
5007
5008         ev_document_model_set_scale (view->model, scale);
5009 }
5010
5011 static void
5012 ev_view_zoom_for_size_continuous (EvView *view,
5013                                   int     width,
5014                                   int     height)
5015 {
5016         gdouble doc_width, doc_height;
5017         GtkBorder border;
5018         gdouble scale;
5019         gint sb_size;
5020
5021         ev_document_get_max_page_size (view->document, &doc_width, &doc_height);
5022         if (view->rotation == 90 || view->rotation == 270) {
5023                 gdouble tmp;
5024
5025                 tmp = doc_width;
5026                 doc_width = doc_height;
5027                 doc_height = tmp;
5028         }
5029
5030         compute_border (view, doc_width, doc_height, &border);
5031
5032         width -= (border.left + border.right + 2 * view->spacing);
5033         height -= (border.top + border.bottom + 2 * view->spacing - 1);
5034
5035         sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5036
5037         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5038                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5039         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5040                 scale = zoom_for_size_best_fit (doc_width, doc_height, width - sb_size, height);
5041         else
5042                 g_assert_not_reached ();
5043
5044         ev_document_model_set_scale (view->model, scale);
5045 }
5046
5047 static void
5048 ev_view_zoom_for_size_dual_page (EvView *view,
5049                                  int     width,
5050                                  int     height)
5051 {
5052         GtkBorder border;
5053         gdouble doc_width, doc_height;
5054         gdouble scale;
5055         gint other_page;
5056
5057         other_page = view->current_page ^ 1;
5058
5059         /* Find the largest of the two. */
5060         get_doc_page_size (view, view->current_page, &doc_width, &doc_height);
5061         if (other_page < ev_document_get_n_pages (view->document)) {
5062                 gdouble width_2, height_2;
5063
5064                 get_doc_page_size (view, other_page, &width_2, &height_2);
5065                 if (width_2 > doc_width)
5066                         doc_width = width_2;
5067                 if (height_2 > doc_height)
5068                         doc_height = height_2;
5069         }
5070         compute_border (view, width, height, &border);
5071
5072         doc_width = doc_width * 2;
5073         width -= ((border.left + border.right)* 2 + 3 * view->spacing);
5074         height -= (border.top + border.bottom + 2 * view->spacing);
5075
5076         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5077                 gint sb_size;
5078
5079                 sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5080                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5081         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5082                 scale = zoom_for_size_best_fit (doc_width, doc_height, width, height);
5083         else
5084                 g_assert_not_reached ();
5085
5086         ev_document_model_set_scale (view->model, scale);
5087 }
5088
5089 static void
5090 ev_view_zoom_for_size_single_page (EvView *view,
5091                                    int     width,
5092                                    int     height)
5093 {
5094         gdouble doc_width, doc_height;
5095         GtkBorder border;
5096         gdouble scale;
5097
5098         get_doc_page_size (view, view->current_page, &doc_width, &doc_height);
5099
5100         /* Get an approximate border */
5101         compute_border (view, width, height, &border);
5102
5103         width -= (border.left + border.right + 2 * view->spacing);
5104         height -= (border.top + border.bottom + 2 * view->spacing);
5105
5106         if (view->sizing_mode == EV_SIZING_FIT_WIDTH) {
5107                 gint sb_size;
5108
5109                 sb_size = ev_view_get_scrollbar_size (view, GTK_ORIENTATION_VERTICAL);
5110                 scale = zoom_for_size_fit_width (doc_width, doc_height, width - sb_size, height);
5111         } else if (view->sizing_mode == EV_SIZING_BEST_FIT)
5112                 scale = zoom_for_size_best_fit (doc_width, doc_height, width, height);
5113         else
5114                 g_assert_not_reached ();
5115
5116         ev_document_model_set_scale (view->model, scale);
5117 }
5118
5119 static void
5120 ev_view_zoom_for_size (EvView *view,
5121                        int     width,
5122                        int     height)
5123 {
5124         g_return_if_fail (EV_IS_VIEW (view));
5125         g_return_if_fail (view->sizing_mode == EV_SIZING_FIT_WIDTH ||
5126                           view->sizing_mode == EV_SIZING_BEST_FIT);
5127         g_return_if_fail (width >= 0);
5128         g_return_if_fail (height >= 0);
5129
5130         if (view->document == NULL)
5131                 return;
5132
5133         if (view->continuous && view->dual_page)
5134                 ev_view_zoom_for_size_continuous_and_dual_page (view, width, height);
5135         else if (view->continuous)
5136                 ev_view_zoom_for_size_continuous (view, width, height);
5137         else if (view->dual_page)
5138                 ev_view_zoom_for_size_dual_page (view, width, height);
5139         else
5140                 ev_view_zoom_for_size_single_page (view, width, height);
5141 }
5142
5143 /*** Find ***/
5144 static gint
5145 ev_view_find_get_n_results (EvView *view, gint page)
5146 {
5147         return view->find_pages ? g_list_length (view->find_pages[page]) : 0;
5148 }
5149
5150 static EvRectangle *
5151 ev_view_find_get_result (EvView *view, gint page, gint result)
5152 {
5153         return view->find_pages ? (EvRectangle *) g_list_nth_data (view->find_pages[page], result) : NULL;
5154 }
5155
5156 static void
5157 jump_to_find_result (EvView *view)
5158 {
5159         gint n_results;
5160         gint page = view->current_page;
5161
5162         n_results = ev_view_find_get_n_results (view, page);
5163
5164         if (n_results > 0 && view->find_result < n_results) {
5165                 EvRectangle *rect;
5166                 GdkRectangle view_rect;
5167
5168                 rect = ev_view_find_get_result (view, page, view->find_result);
5169                 doc_rect_to_view_rect (view, page, rect, &view_rect);
5170                 ensure_rectangle_is_visible (view, &view_rect);
5171                 view->jump_to_find_result = FALSE;
5172         }
5173 }
5174
5175 /**
5176  * jump_to_find_page
5177  * @view: #EvView instance
5178  * @direction: Direction to look
5179  * @shift: Shift from current page
5180  *
5181  * Jumps to the first page that has occurences of searched word.
5182  * Uses a direction where to look and a shift from current page. 
5183  *
5184  */
5185 static void
5186 jump_to_find_page (EvView *view, EvViewFindDirection direction, gint shift)
5187 {
5188         int n_pages, i;
5189
5190         n_pages = ev_document_get_n_pages (view->document);
5191
5192         for (i = 0; i < n_pages; i++) {
5193                 int page;
5194                 
5195                 if (direction == EV_VIEW_FIND_NEXT)
5196                         page = view->current_page + i;
5197                 else
5198                         page = view->current_page - i;          
5199                 page += shift;
5200                 
5201                 if (page >= n_pages) {
5202                         page = page - n_pages;
5203                 } else if (page < 0) 
5204                         page = page + n_pages;
5205
5206                 if (ev_view_find_get_n_results (view, page) > 0) {
5207                         ev_document_model_set_page (view->model, page);
5208                         break;
5209                 }
5210         }
5211 }
5212
5213 void
5214 ev_view_find_changed (EvView *view, GList **results, gint page)
5215 {
5216         view->find_pages = results;
5217         
5218         if (view->jump_to_find_result == TRUE) {
5219                 jump_to_find_page (view, EV_VIEW_FIND_NEXT, 0);
5220                 jump_to_find_result (view);
5221         }
5222
5223         if (view->current_page == page)
5224                 gtk_widget_queue_draw (GTK_WIDGET (view));
5225 }
5226
5227 void
5228 ev_view_find_next (EvView *view)
5229 {
5230         gint n_results;
5231
5232         n_results = ev_view_find_get_n_results (view, view->current_page);
5233         view->find_result++;
5234
5235         if (view->find_result >= n_results) {
5236                 view->find_result = 0;
5237                 jump_to_find_page (view, EV_VIEW_FIND_NEXT, 1);
5238                 jump_to_find_result (view);
5239         } else {
5240                 jump_to_find_result (view);
5241                 gtk_widget_queue_draw (GTK_WIDGET (view));
5242         }
5243 }
5244
5245 void
5246 ev_view_find_previous (EvView *view)
5247 {
5248         view->find_result--;
5249
5250         if (view->find_result < 0) {
5251                 jump_to_find_page (view, EV_VIEW_FIND_PREV, -1);
5252                 view->find_result = MAX (0, ev_view_find_get_n_results (view, view->current_page) - 1);
5253                 jump_to_find_result (view);
5254         } else {
5255                 jump_to_find_result (view);
5256                 gtk_widget_queue_draw (GTK_WIDGET (view));
5257         }
5258 }
5259
5260 void
5261 ev_view_find_search_changed (EvView *view)
5262 {
5263         /* search string has changed, focus on new search result */
5264         view->jump_to_find_result = TRUE;
5265         view->find_pages = NULL;
5266 }
5267
5268 void
5269 ev_view_find_set_highlight_search (EvView *view, gboolean value)
5270 {
5271         view->highlight_find_results = value;
5272         gtk_widget_queue_draw (GTK_WIDGET (view));
5273 }
5274
5275 void
5276 ev_view_find_cancel (EvView *view)
5277 {
5278         view->find_pages = NULL;
5279 }
5280
5281 /*** Selections ***/
5282
5283 /* compute_new_selection_rect/text calculates the area currently selected by
5284  * view_rect.  each handles a different mode;
5285  */
5286 static GList *
5287 compute_new_selection_rect (EvView       *view,
5288                             GdkPoint     *start,
5289                             GdkPoint     *stop)
5290 {
5291         GdkRectangle view_rect;
5292         int n_pages, i;
5293         GList *list = NULL;
5294
5295         g_assert (view->selection_mode == EV_VIEW_SELECTION_RECTANGLE);
5296         
5297         view_rect.x = MIN (start->x, stop->x);
5298         view_rect.y = MIN (start->y, stop->y);
5299         view_rect.width = MAX (start->x, stop->x) - view_rect.x;
5300         view_rect.width = MAX (start->y, stop->y) - view_rect.y;
5301
5302         n_pages = ev_document_get_n_pages (view->document);
5303
5304         for (i = 0; i < n_pages; i++) {
5305                 GdkRectangle page_area;
5306                 GtkBorder border;
5307                 
5308                 if (get_page_extents (view, i, &page_area, &border)) {
5309                         GdkRectangle overlap;
5310
5311                         if (gdk_rectangle_intersect (&page_area, &view_rect, &overlap)) {
5312                                 EvViewSelection *selection;
5313
5314                                 selection = g_new0 (EvViewSelection, 1);
5315                                 selection->page = i;
5316                                 view_rect_to_doc_rect (view, &overlap, &page_area,
5317                                                        &(selection->rect));
5318
5319                                 list = g_list_append (list, selection);
5320                         }
5321                 }
5322         }
5323
5324         return list;
5325 }
5326
5327 static gboolean
5328 gdk_rectangle_point_in (GdkRectangle *rectangle,
5329                         GdkPoint     *point)
5330 {
5331         return rectangle->x <= point->x &&
5332                 rectangle->y <= point->y &&
5333                 point->x < rectangle->x + rectangle->width &&
5334                 point->y < rectangle->y + rectangle->height;
5335 }
5336
5337 static GList *
5338 compute_new_selection_text (EvView          *view,
5339                             EvSelectionStyle style,
5340                             GdkPoint        *start,
5341                             GdkPoint        *stop)
5342 {
5343         int n_pages, i, first, last;
5344         GList *list = NULL;
5345         EvViewSelection *selection;
5346         gdouble width, height;
5347         int start_page, end_page;
5348
5349         g_assert (view->selection_mode == EV_VIEW_SELECTION_TEXT);
5350
5351         n_pages = ev_document_get_n_pages (view->document);
5352
5353         /* First figure out the range of pages the selection
5354          * affects. */
5355         first = n_pages;
5356         last = 0;
5357         if (view->continuous) {
5358                 start_page = 0;
5359                 end_page = n_pages;
5360         } else if (view->dual_page) {
5361                 start_page = view->start_page;
5362                 end_page = view->end_page + 1;
5363         } else {
5364                 start_page = view->current_page;
5365                 end_page = view->current_page + 1;
5366         }
5367
5368         for (i = start_page; i < end_page; i++) {
5369                 GdkRectangle page_area;
5370                 GtkBorder border;
5371                 
5372                 get_page_extents (view, i, &page_area, &border);
5373                 if (gdk_rectangle_point_in (&page_area, start) || 
5374                     gdk_rectangle_point_in (&page_area, stop)) {
5375                         if (first == n_pages)
5376                                 first = i;
5377                         last = i;
5378                 }
5379
5380         }
5381
5382         /* Now create a list of EvViewSelection's for the affected
5383          * pages.  This could be an empty list, a list of just one
5384          * page or a number of pages.*/
5385         for (i = first; i < last + 1; i++) {
5386                 GdkRectangle page_area;
5387                 GtkBorder border;
5388                 GdkPoint *point;
5389
5390                 get_doc_page_size (view, i, &width, &height);
5391
5392                 selection = g_new0 (EvViewSelection, 1);
5393                 selection->page = i;
5394                 selection->style = style;
5395                 selection->rect.x1 = selection->rect.y1 = 0;
5396                 selection->rect.x2 = width;
5397                 selection->rect.y2 = height;
5398
5399                 get_page_extents (view, i, &page_area, &border);
5400
5401                 if (gdk_rectangle_point_in (&page_area, start))
5402                         point = start;
5403                 else
5404                         point = stop;
5405
5406                 if (i == first)
5407                         view_point_to_doc_point (view, point, &page_area,
5408                                                  &selection->rect.x1,
5409                                                  &selection->rect.y1);
5410
5411                 /* If the selection is contained within just one page,
5412                  * make sure we don't write 'start' into both points
5413                  * in selection->rect. */
5414                 if (first == last)
5415                         point = stop;
5416
5417                 if (i == last)
5418                         view_point_to_doc_point (view, point, &page_area,
5419                                                  &selection->rect.x2,
5420                                                  &selection->rect.y2);
5421
5422                 list = g_list_append (list, selection);
5423         }
5424
5425         return list;
5426 }
5427
5428 /* This function takes the newly calculated list, and figures out which regions
5429  * have changed.  It then queues a redraw approporiately.
5430  */
5431 static void
5432 merge_selection_region (EvView *view,
5433                         GList  *new_list)
5434 {
5435         GList *old_list;
5436         GList *new_list_ptr, *old_list_ptr;
5437
5438         /* Update the selection */
5439         old_list = ev_pixbuf_cache_get_selection_list (view->pixbuf_cache);
5440         g_list_foreach (view->selection_info.selections, (GFunc)selection_free, NULL);
5441         g_list_free (view->selection_info.selections);
5442         view->selection_info.selections = new_list;
5443         ev_pixbuf_cache_set_selection_list (view->pixbuf_cache, new_list);
5444         g_signal_emit (view, signals[SIGNAL_SELECTION_CHANGED], 0, NULL);
5445
5446         new_list_ptr = new_list;
5447         old_list_ptr = old_list;
5448
5449         while (new_list_ptr || old_list_ptr) {
5450                 EvViewSelection *old_sel, *new_sel;
5451                 int cur_page;
5452                 GdkRegion *region = NULL;
5453
5454                 new_sel = (new_list_ptr) ? (new_list_ptr->data) : NULL;
5455                 old_sel = (old_list_ptr) ? (old_list_ptr->data) : NULL;
5456
5457                 /* Assume that the lists are in order, and we run through them
5458                  * comparing them, one page at a time.  We come out with the
5459                  * first page we see. */
5460                 if (new_sel && old_sel) {
5461                         if (new_sel->page < old_sel->page) {
5462                                 new_list_ptr = new_list_ptr->next;
5463                                 old_sel = NULL;
5464                         } else if (new_sel->page > old_sel->page) {
5465                                 old_list_ptr = old_list_ptr->next;
5466                                 new_sel = NULL;
5467                         } else {
5468                                 new_list_ptr = new_list_ptr->next;
5469                                 old_list_ptr = old_list_ptr->next;
5470                         }
5471                 } else if (new_sel) {
5472                         new_list_ptr = new_list_ptr->next;
5473                 } else if (old_sel) {
5474                         old_list_ptr = old_list_ptr->next;
5475                 }
5476
5477                 g_assert (new_sel || old_sel);
5478
5479                 /* is the page we're looking at on the screen?*/
5480                 cur_page = new_sel ? new_sel->page : old_sel->page;
5481                 if (cur_page < view->start_page || cur_page > view->end_page)
5482                         continue;
5483
5484                 /* seed the cache with a new page.  We are going to need the new
5485                  * region too. */
5486                 if (new_sel) {
5487                         GdkRegion *tmp_region = NULL;
5488
5489                         ev_pixbuf_cache_get_selection_surface (view->pixbuf_cache,
5490                                                                cur_page,
5491                                                                view->scale,
5492                                                                &tmp_region);
5493
5494                         if (tmp_region && !gdk_region_empty (tmp_region)) {
5495                                 new_sel->covered_region = gdk_region_copy (tmp_region);
5496                         }
5497                 }
5498
5499                 /* Now we figure out what needs redrawing */
5500                 if (old_sel && new_sel) {
5501                         if (old_sel->covered_region && new_sel->covered_region) {
5502                                 /* We only want to redraw the areas that have
5503                                  * changed, so we xor the old and new regions
5504                                  * and redraw if it's different */
5505                                 region = gdk_region_copy (old_sel->covered_region);
5506                                 gdk_region_xor (region, new_sel->covered_region);
5507                                 if (gdk_region_empty (region)) {
5508                                         gdk_region_destroy (region);
5509                                         region = NULL;
5510                                 }
5511                         } else if (old_sel->covered_region) {
5512                                 region = gdk_region_copy (old_sel->covered_region);
5513                         } else if (new_sel->covered_region) {
5514                                 region = gdk_region_copy (new_sel->covered_region);
5515                         }
5516                 } else if (old_sel && !new_sel) {
5517                         if (old_sel->covered_region && !gdk_region_empty (old_sel->covered_region)) {
5518                                 region = gdk_region_copy (old_sel->covered_region);
5519                         }
5520                 } else if (!old_sel && new_sel) {
5521                         if (new_sel->covered_region && !gdk_region_empty (new_sel->covered_region)) {
5522                                 region = gdk_region_copy (new_sel->covered_region);
5523                         }
5524                 } else {
5525                         g_assert_not_reached ();
5526                 }
5527
5528                 /* Redraw the damaged region! */
5529                 if (region) {
5530                         GdkWindow   *bin_window;
5531                         GdkRectangle page_area;
5532                         GtkBorder    border;
5533
5534                         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
5535
5536                         /* I don't know why but the region is smaller
5537                          * than expected. This hack fixes it, I guess
5538                          * 10 pixels more won't hurt
5539                          */
5540                         gdk_region_shrink (region, -5, -5);
5541
5542                         get_page_extents (view, cur_page, &page_area, &border);
5543                         gdk_region_offset (region,
5544                                            page_area.x + border.left - view->scroll_x,
5545                                            page_area.y + border.top - view->scroll_y);
5546                         gdk_window_invalidate_region (bin_window, region, TRUE);
5547                         gdk_region_destroy (region);
5548                 }
5549         }
5550
5551         /* Free the old list, now that we're done with it. */
5552         g_list_foreach (old_list, (GFunc) selection_free, NULL);
5553         g_list_free (old_list);
5554 }
5555
5556 static void
5557 compute_selections (EvView          *view,
5558                     EvSelectionStyle style,
5559                     GdkPoint        *start,
5560                     GdkPoint        *stop)
5561 {
5562         GList *list;
5563
5564         if (view->selection_mode == EV_VIEW_SELECTION_RECTANGLE)
5565                 list = compute_new_selection_rect (view, start, stop);
5566         else
5567                 list = compute_new_selection_text (view, style, start, stop);
5568         merge_selection_region (view, list);
5569 }
5570
5571 /* Free's the selection.  It's up to the caller to queue redraws if needed.
5572  */
5573 static void
5574 selection_free (EvViewSelection *selection)
5575 {
5576         if (selection->covered_region)
5577                 gdk_region_destroy (selection->covered_region);
5578         g_free (selection);
5579 }
5580
5581 static void
5582 clear_selection (EvView *view)
5583 {
5584         if (view->selection_info.selections) {
5585                 g_list_foreach (view->selection_info.selections, (GFunc)selection_free, NULL);
5586                 g_list_free (view->selection_info.selections);
5587                 view->selection_info.selections = NULL;
5588
5589                 g_signal_emit (view, signals[SIGNAL_SELECTION_CHANGED], 0, NULL);
5590         }
5591         view->selection_info.in_selection = FALSE;
5592         if (view->pixbuf_cache)
5593                 ev_pixbuf_cache_set_selection_list (view->pixbuf_cache, NULL);
5594 }
5595
5596 void
5597 ev_view_select_all (EvView *view)
5598 {
5599         GList *selections = NULL;
5600         int n_pages, i;
5601
5602         /* Disable selection on rotated pages for the 0.4.0 series */
5603         if (view->rotation != 0)
5604                 return;
5605
5606         clear_selection (view);
5607         
5608         n_pages = ev_document_get_n_pages (view->document);
5609         for (i = 0; i < n_pages; i++) {
5610                 gdouble width, height;
5611                 EvViewSelection *selection;
5612
5613                 get_doc_page_size (view, i, &width, &height);
5614
5615                 selection = g_new0 (EvViewSelection, 1);
5616                 selection->page = i;
5617                 selection->style = EV_SELECTION_STYLE_GLYPH;
5618                 selection->rect.x1 = selection->rect.y1 = 0;
5619                 selection->rect.x2 = width;
5620                 selection->rect.y2 = height;
5621
5622                 selections = g_list_append (selections, selection);
5623         }
5624
5625         merge_selection_region (view, selections);
5626         gtk_widget_queue_draw (GTK_WIDGET (view));
5627 }
5628
5629 gboolean
5630 ev_view_get_has_selection (EvView *view)
5631 {
5632         return view->selection_info.selections != NULL;
5633 }
5634
5635 static char *
5636 get_selected_text (EvView *view)
5637 {
5638         GString *text;
5639         GList *l;
5640         gchar *normalized_text;
5641
5642         text = g_string_new (NULL);
5643
5644         ev_document_doc_mutex_lock ();
5645
5646         for (l = view->selection_info.selections; l != NULL; l = l->next) {
5647                 EvViewSelection *selection = (EvViewSelection *)l->data;
5648                 EvPage *page;
5649                 gchar *tmp;
5650
5651                 page = ev_document_get_page (view->document, selection->page);
5652                 tmp = ev_selection_get_selected_text (EV_SELECTION (view->document),
5653                                                       page, selection->style,
5654                                                       &(selection->rect));
5655                 g_object_unref (page);
5656                 g_string_append (text, tmp);
5657                 g_free (tmp);
5658         }
5659
5660         ev_document_doc_mutex_unlock ();
5661         
5662         normalized_text = g_utf8_normalize (text->str, text->len, G_NORMALIZE_NFKC);
5663         g_string_free (text, TRUE);
5664         return normalized_text;
5665 }
5666
5667 static void
5668 ev_view_clipboard_copy (EvView      *view,
5669                         const gchar *text)
5670 {
5671         GtkClipboard *clipboard;
5672
5673         clipboard = gtk_widget_get_clipboard (GTK_WIDGET (view),
5674                                               GDK_SELECTION_CLIPBOARD);
5675         gtk_clipboard_set_text (clipboard, text, -1);
5676 }
5677
5678 void
5679 ev_view_copy (EvView *ev_view)
5680 {
5681         char *text;
5682
5683         if (!EV_IS_SELECTION (ev_view->document))
5684                 return;
5685
5686         text = get_selected_text (ev_view);
5687         ev_view_clipboard_copy (ev_view, text);
5688         g_free (text);
5689 }
5690
5691 static void
5692 ev_view_primary_get_cb (GtkClipboard     *clipboard,
5693                         GtkSelectionData *selection_data,
5694                         guint             info,
5695                         gpointer          data)
5696 {
5697         EvView *ev_view = EV_VIEW (data);
5698
5699         if (ev_view->link_selected) {
5700                 gtk_selection_data_set_text (selection_data,
5701                                              ev_link_action_get_uri (ev_view->link_selected),
5702                                              -1);
5703         } else if (EV_IS_SELECTION (ev_view->document) &&
5704                    ev_view->selection_info.selections) {
5705                 gchar *text;
5706                 
5707                 text = get_selected_text (ev_view);
5708                 if (text) {
5709                         gtk_selection_data_set_text (selection_data, text, -1);
5710                         g_free (text);
5711                 }
5712         }
5713 }
5714
5715 static void
5716 ev_view_primary_clear_cb (GtkClipboard *clipboard,
5717                           gpointer      data)
5718 {
5719         EvView *view = EV_VIEW (data);
5720
5721         clear_selection (view);
5722         clear_link_selected (view);
5723 }
5724
5725 static void
5726 ev_view_update_primary_selection (EvView *ev_view)
5727 {
5728         GtkClipboard *clipboard;
5729
5730         clipboard = gtk_widget_get_clipboard (GTK_WIDGET (ev_view),
5731                                               GDK_SELECTION_PRIMARY);
5732
5733         if (ev_view->selection_info.selections || ev_view->link_selected) {
5734                 GtkTargetList *target_list;
5735                 GtkTargetEntry *targets;
5736                 int n_targets;
5737
5738                 target_list = gtk_target_list_new (NULL, 0);
5739                 gtk_target_list_add_text_targets (target_list, 0);
5740                 targets = gtk_target_table_new_from_list (target_list, &n_targets);
5741                 gtk_target_list_unref (target_list);
5742                 
5743                 if (!gtk_clipboard_set_with_owner (clipboard,
5744                                                    targets, n_targets,
5745                                                    ev_view_primary_get_cb,
5746                                                    ev_view_primary_clear_cb,
5747                                                    G_OBJECT (ev_view)))
5748                         ev_view_primary_clear_cb (clipboard, ev_view);
5749
5750                 gtk_target_table_free (targets, n_targets);
5751         } else {
5752                 if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (ev_view))
5753                         gtk_clipboard_clear (clipboard);
5754         }
5755 }
5756
5757 static void
5758 clear_link_selected (EvView *view)
5759 {
5760         if (view->link_selected) {
5761                 g_object_unref (view->link_selected);
5762                 view->link_selected = NULL;
5763         }
5764 }
5765
5766 void
5767 ev_view_copy_link_address (EvView       *view,
5768                            EvLinkAction *action)
5769 {
5770         clear_link_selected (view);
5771         
5772         ev_view_clipboard_copy (view, ev_link_action_get_uri (action));
5773         
5774         view->link_selected = g_object_ref (action);
5775         ev_view_update_primary_selection (view);
5776 }
5777
5778 /*** Cursor operations ***/
5779 static void
5780 ev_view_set_cursor (EvView *view, EvViewCursor new_cursor)
5781 {
5782         GdkCursor *cursor = NULL;
5783         GtkWidget *widget;
5784         GdkWindow *bin_window;
5785
5786         if (view->cursor == new_cursor) {
5787                 return;
5788         }
5789
5790         view->cursor = new_cursor;
5791
5792         bin_window = gtk_layout_get_bin_window (GTK_LAYOUT (view));
5793         widget = gtk_widget_get_toplevel (GTK_WIDGET (view));
5794         cursor = ev_view_cursor_new (gtk_widget_get_display (widget), new_cursor);
5795         gdk_window_set_cursor (bin_window, cursor);
5796         gdk_flush ();
5797         if (cursor)
5798                 gdk_cursor_unref (cursor);
5799 }
5800
5801 void
5802 ev_view_hide_cursor (EvView *view)
5803 {
5804        ev_view_set_cursor (view, EV_VIEW_CURSOR_HIDDEN);
5805 }
5806
5807 void
5808 ev_view_show_cursor (EvView *view)
5809 {
5810        ev_view_set_cursor (view, EV_VIEW_CURSOR_NORMAL);
5811 }
5812
5813 gboolean
5814 ev_view_next_page (EvView *view)
5815 {
5816         int page, n_pages;
5817
5818         g_return_val_if_fail (EV_IS_VIEW (view), FALSE);
5819         
5820         if (!view->document)
5821                 return FALSE;
5822
5823         page = ev_document_model_get_page (view->model);
5824         n_pages = ev_document_get_n_pages (view->document);
5825
5826         if (view->dual_page)
5827                 page = page + 2; 
5828         else 
5829                 page = page + 1;
5830
5831         if (page < n_pages) {
5832                 ev_document_model_set_page (view->model, page);
5833                 return TRUE;
5834         } else if (view->dual_page && page == n_pages) {
5835                 ev_document_model_set_page (view->model, page - 1);
5836                 return TRUE;
5837         } else {
5838                 return FALSE;
5839         }
5840 }
5841
5842 gboolean
5843 ev_view_previous_page (EvView *view)
5844 {
5845         int page;
5846
5847         g_return_val_if_fail (EV_IS_VIEW (view), FALSE);
5848
5849         if (!view->document)
5850                 return FALSE;
5851
5852         page = ev_document_model_get_page (view->model);
5853
5854         if (view->dual_page)
5855                 page = page - 2; 
5856         else 
5857                 page = page - 1;
5858
5859         if (page >= 0) {
5860                 ev_document_model_set_page (view->model, page);
5861                 return TRUE;
5862         } else if (view->dual_page && page == -1) {
5863                 ev_document_model_set_page (view->model, 0);
5864                 return TRUE;
5865         } else {        
5866                 return FALSE;
5867         }
5868 }
5869