]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
textview: Only clear the layout in style_update if the font actually changes
[~andy/gtk] / gtk / gtktextview.c
1 /* -*- Mode: C; c-file-style: "gnu"; tab-width: 8 -*- */
2 /* GTK - The GIMP Toolkit
3  * gtktextview.c Copyright (C) 2000 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /*
20  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
21  * file for a list of people on the GTK+ Team.  See the ChangeLog
22  * files for a list of changes.  These files are distributed with
23  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
24  */
25
26 #include "config.h"
27
28 #include <string.h>
29
30 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
31 #include "gtkbindings.h"
32 #include "gtkdnd.h"
33 #include "gtkimagemenuitem.h"
34 #include "gtkintl.h"
35 #include "gtkmain.h"
36 #include "gtkmarshalers.h"
37 #include "gtkmenu.h"
38 #include "gtkmenuitem.h"
39 #include "gtkseparatormenuitem.h"
40 #include "gtksettings.h"
41 #include "gtkselectionprivate.h"
42 #include "gtkstock.h"
43 #include "gtktextbufferrichtext.h"
44 #include "gtktextdisplay.h"
45 #include "gtktextview.h"
46 #include "gtkimmulticontext.h"
47 #include "gtkprivate.h"
48 #include "gtktextutil.h"
49 #include "gtkwidgetprivate.h"
50 #include "gtkwindow.h"
51 #include "gtkscrollable.h"
52 #include "gtktypebuiltins.h"
53 #include "gtktexthandleprivate.h"
54 #include "gtkstylecontextprivate.h"
55
56 #include "a11y/gtktextviewaccessible.h"
57
58 /**
59  * SECTION:gtktextview
60  * @Short_description: Widget that displays a GtkTextBuffer
61  * @Title: GtkTextView
62  * @See_also: #GtkTextBuffer, #GtkTextIter
63  *
64  * You may wish to begin by reading the <link linkend="TextWidget">text widget
65  * conceptual overview</link> which gives an overview of all the objects and data
66  * types related to the text widget and how they work together.
67  */
68
69
70 /* How scrolling, validation, exposes, etc. work.
71  *
72  * The expose_event handler has the invariant that the onscreen lines
73  * have been validated.
74  *
75  * There are two ways that onscreen lines can become invalid. The first
76  * is to change which lines are onscreen. This happens when the value
77  * of a scroll adjustment changes. So the code path begins in
78  * gtk_text_view_value_changed() and goes like this:
79  *   - gdk_window_scroll() to reflect the new adjustment value
80  *   - validate the lines that were moved onscreen
81  *   - gdk_window_process_updates() to handle the exposes immediately
82  *
83  * The second way is that you get the "invalidated" signal from the layout,
84  * indicating that lines have become invalid. This code path begins in
85  * invalidated_handler() and goes like this:
86  *   - install high-priority idle which does the rest of the steps
87  *   - if a scroll is pending from scroll_to_mark(), do the scroll,
88  *     jumping to the gtk_text_view_value_changed() code path
89  *   - otherwise, validate the onscreen lines
90  *   - DO NOT process updates
91  *
92  * In both cases, validating the onscreen lines can trigger a scroll
93  * due to maintaining the first_para on the top of the screen.
94  * If validation triggers a scroll, we jump to the top of the code path
95  * for value_changed, and bail out of the current code path.
96  *
97  * Also, in size_allocate, if we invalidate some lines from changing
98  * the layout width, we need to go ahead and run the high-priority idle,
99  * because GTK sends exposes right after doing the size allocates without
100  * returning to the main loop. This is also why the high-priority idle
101  * is at a higher priority than resizing.
102  *
103  */
104
105 #if 0
106 #define DEBUG_VALIDATION_AND_SCROLLING
107 #endif
108
109 #ifdef DEBUG_VALIDATION_AND_SCROLLING
110 #define DV(x) (x)
111 #else
112 #define DV(x)
113 #endif
114
115 #define SCREEN_WIDTH(widget) text_window_get_width (GTK_TEXT_VIEW (widget)->priv->text_window)
116 #define SCREEN_HEIGHT(widget) text_window_get_height (GTK_TEXT_VIEW (widget)->priv->text_window)
117
118 #define SPACE_FOR_CURSOR 1
119
120 #define GTK_TEXT_VIEW_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_TEXT_VIEW, GtkTextViewPrivate))
121
122 typedef struct _GtkTextWindow GtkTextWindow;
123 typedef struct _GtkTextPendingScroll GtkTextPendingScroll;
124
125 struct _GtkTextViewPrivate 
126 {
127   GtkTextLayout *layout;
128   GtkTextBuffer *buffer;
129
130   guint blink_time;  /* time in msec the cursor has blinked since last user event */
131   guint im_spot_idle;
132   gchar *im_module;
133   GdkDevice *grab_device;
134   GdkDevice *dnd_device;
135
136   gulong selection_drag_handler;
137   GtkTextHandle *text_handle;
138
139   GtkTextWindow *text_window;
140   GtkTextWindow *left_window;
141   GtkTextWindow *right_window;
142   GtkTextWindow *top_window;
143   GtkTextWindow *bottom_window;
144
145   GtkAdjustment *hadjustment;
146   GtkAdjustment *vadjustment;
147
148   gint xoffset;         /* Offsets between widget coordinates and buffer coordinates */
149   gint yoffset;
150   gint width;           /* Width and height of the buffer */
151   gint height;
152
153   /* This is used to monitor the overall size request 
154    * and decide whether we need to queue resizes when
155    * the buffer content changes. 
156    *
157    * FIXME: This could be done in a simpler way by 
158    * consulting the above width/height of the buffer + some
159    * padding values, however all of this request code needs
160    * to be changed to use GtkWidget     Iface and deserves
161    * more attention.
162    */
163   GtkRequisition cached_size_request;
164
165   /* The virtual cursor position is normally the same as the
166    * actual (strong) cursor position, except in two circumstances:
167    *
168    * a) When the cursor is moved vertically with the keyboard
169    * b) When the text view is scrolled with the keyboard
170    *
171    * In case a), virtual_cursor_x is preserved, but not virtual_cursor_y
172    * In case b), both virtual_cursor_x and virtual_cursor_y are preserved.
173    */
174   gint virtual_cursor_x;   /* -1 means use actual cursor position */
175   gint virtual_cursor_y;   /* -1 means use actual cursor position */
176
177   GtkTextMark *first_para_mark; /* Mark at the beginning of the first onscreen paragraph */
178   gint first_para_pixels;       /* Offset of top of screen in the first onscreen paragraph */
179
180   guint blink_timeout;
181   guint scroll_timeout;
182
183   guint first_validate_idle;        /* Idle to revalidate onscreen portion, runs before resize */
184   guint incremental_validate_idle;  /* Idle to revalidate offscreen portions, runs after redraw */
185
186   gint pending_place_cursor_button;
187
188   GtkTextMark *dnd_mark;
189
190   GtkIMContext *im_context;
191   GtkWidget *popup_menu;
192
193   gint drag_start_x;
194   gint drag_start_y;
195
196   GSList *children;
197
198   GtkTextPendingScroll *pending_scroll;
199
200   /* Default style settings */
201   gint pixels_above_lines;
202   gint pixels_below_lines;
203   gint pixels_inside_wrap;
204   GtkWrapMode wrap_mode;
205   GtkJustification justify;
206   gint left_margin;
207   gint right_margin;
208   gint indent;
209   PangoTabArray *tabs;
210   guint editable : 1;
211
212   guint overwrite_mode : 1;
213   guint cursor_visible : 1;
214
215   /* if we have reset the IM since the last character entered */
216   guint need_im_reset : 1;
217
218   guint accepts_tab : 1;
219
220   guint width_changed : 1;
221
222   /* debug flag - means that we've validated onscreen since the
223    * last "invalidate" signal from the layout
224    */
225   guint onscreen_validated : 1;
226
227   guint mouse_cursor_obscured : 1;
228
229   guint scroll_after_paste : 1;
230
231   /* GtkScrollablePolicy needs to be checked when
232    * driving the scrollable adjustment values */
233   guint hscroll_policy : 1;
234   guint vscroll_policy : 1;
235   guint cursor_handle_dragged : 1;
236   guint selection_handle_dragged : 1;
237 };
238
239 struct _GtkTextPendingScroll
240 {
241   GtkTextMark   *mark;
242   gdouble        within_margin;
243   gboolean       use_align;
244   gdouble        xalign;
245   gdouble        yalign;
246 };
247
248 enum
249 {
250   POPULATE_POPUP,
251   MOVE_CURSOR,
252   PAGE_HORIZONTALLY,
253   SET_ANCHOR,
254   INSERT_AT_CURSOR,
255   DELETE_FROM_CURSOR,
256   BACKSPACE,
257   CUT_CLIPBOARD,
258   COPY_CLIPBOARD,
259   PASTE_CLIPBOARD,
260   TOGGLE_OVERWRITE,
261   MOVE_VIEWPORT,
262   SELECT_ALL,
263   TOGGLE_CURSOR_VISIBLE,
264   PREEDIT_CHANGED,
265   LAST_SIGNAL
266 };
267
268 enum
269 {
270   PROP_0,
271   PROP_PIXELS_ABOVE_LINES,
272   PROP_PIXELS_BELOW_LINES,
273   PROP_PIXELS_INSIDE_WRAP,
274   PROP_EDITABLE,
275   PROP_WRAP_MODE,
276   PROP_JUSTIFICATION,
277   PROP_LEFT_MARGIN,
278   PROP_RIGHT_MARGIN,
279   PROP_INDENT,
280   PROP_TABS,
281   PROP_CURSOR_VISIBLE,
282   PROP_BUFFER,
283   PROP_OVERWRITE,
284   PROP_ACCEPTS_TAB,
285   PROP_IM_MODULE,
286   PROP_HADJUSTMENT,
287   PROP_VADJUSTMENT,
288   PROP_HSCROLL_POLICY,
289   PROP_VSCROLL_POLICY,
290   PROP_INPUT_PURPOSE,
291   PROP_INPUT_HINTS
292 };
293
294 static void gtk_text_view_finalize             (GObject          *object);
295 static void gtk_text_view_set_property         (GObject         *object,
296                                                 guint            prop_id,
297                                                 const GValue    *value,
298                                                 GParamSpec      *pspec);
299 static void gtk_text_view_get_property         (GObject         *object,
300                                                 guint            prop_id,
301                                                 GValue          *value,
302                                                 GParamSpec      *pspec);
303 static void gtk_text_view_destroy              (GtkWidget        *widget);
304 static void gtk_text_view_size_request         (GtkWidget        *widget,
305                                                 GtkRequisition   *requisition);
306 static void gtk_text_view_get_preferred_width  (GtkWidget        *widget,
307                                                 gint             *minimum,
308                                                 gint             *natural);
309 static void gtk_text_view_get_preferred_height (GtkWidget        *widget,
310                                                 gint             *minimum,
311                                                 gint             *natural);
312 static void gtk_text_view_size_allocate        (GtkWidget        *widget,
313                                                 GtkAllocation    *allocation);
314 static void gtk_text_view_realize              (GtkWidget        *widget);
315 static void gtk_text_view_unrealize            (GtkWidget        *widget);
316 static void gtk_text_view_style_updated        (GtkWidget        *widget);
317 static void gtk_text_view_direction_changed    (GtkWidget        *widget,
318                                                 GtkTextDirection  previous_direction);
319 static void gtk_text_view_grab_notify          (GtkWidget        *widget,
320                                                 gboolean         was_grabbed);
321 static void gtk_text_view_state_flags_changed  (GtkWidget        *widget,
322                                                 GtkStateFlags     previous_state);
323
324 static gint gtk_text_view_event                (GtkWidget        *widget,
325                                                 GdkEvent         *event);
326 static gint gtk_text_view_key_press_event      (GtkWidget        *widget,
327                                                 GdkEventKey      *event);
328 static gint gtk_text_view_key_release_event    (GtkWidget        *widget,
329                                                 GdkEventKey      *event);
330 static gint gtk_text_view_button_press_event   (GtkWidget        *widget,
331                                                 GdkEventButton   *event);
332 static gint gtk_text_view_button_release_event (GtkWidget        *widget,
333                                                 GdkEventButton   *event);
334 static gint gtk_text_view_focus_in_event       (GtkWidget        *widget,
335                                                 GdkEventFocus    *event);
336 static gint gtk_text_view_focus_out_event      (GtkWidget        *widget,
337                                                 GdkEventFocus    *event);
338 static gint gtk_text_view_motion_event         (GtkWidget        *widget,
339                                                 GdkEventMotion   *event);
340 static gint gtk_text_view_draw                 (GtkWidget        *widget,
341                                                 cairo_t          *cr);
342 static void gtk_text_view_draw_focus           (GtkWidget        *widget,
343                                                 cairo_t          *cr);
344 static gboolean gtk_text_view_focus            (GtkWidget        *widget,
345                                                 GtkDirectionType  direction);
346 static void gtk_text_view_select_all           (GtkWidget        *widget,
347                                                 gboolean          select);
348 static gboolean get_middle_click_paste         (GtkTextView      *text_view);
349
350 /* Source side drag signals */
351 static void gtk_text_view_drag_begin       (GtkWidget        *widget,
352                                             GdkDragContext   *context);
353 static void gtk_text_view_drag_end         (GtkWidget        *widget,
354                                             GdkDragContext   *context);
355 static void gtk_text_view_drag_data_get    (GtkWidget        *widget,
356                                             GdkDragContext   *context,
357                                             GtkSelectionData *selection_data,
358                                             guint             info,
359                                             guint             time);
360 static void gtk_text_view_drag_data_delete (GtkWidget        *widget,
361                                             GdkDragContext   *context);
362
363 /* Target side drag signals */
364 static void     gtk_text_view_drag_leave         (GtkWidget        *widget,
365                                                   GdkDragContext   *context,
366                                                   guint             time);
367 static gboolean gtk_text_view_drag_motion        (GtkWidget        *widget,
368                                                   GdkDragContext   *context,
369                                                   gint              x,
370                                                   gint              y,
371                                                   guint             time);
372 static gboolean gtk_text_view_drag_drop          (GtkWidget        *widget,
373                                                   GdkDragContext   *context,
374                                                   gint              x,
375                                                   gint              y,
376                                                   guint             time);
377 static void     gtk_text_view_drag_data_received (GtkWidget        *widget,
378                                                   GdkDragContext   *context,
379                                                   gint              x,
380                                                   gint              y,
381                                                   GtkSelectionData *selection_data,
382                                                   guint             info,
383                                                   guint             time);
384
385 static gboolean gtk_text_view_popup_menu         (GtkWidget     *widget);
386
387 static void gtk_text_view_move_cursor       (GtkTextView           *text_view,
388                                              GtkMovementStep        step,
389                                              gint                   count,
390                                              gboolean               extend_selection);
391 static void gtk_text_view_move_viewport     (GtkTextView           *text_view,
392                                              GtkScrollStep          step,
393                                              gint                   count);
394 static void gtk_text_view_set_anchor       (GtkTextView           *text_view);
395 static gboolean gtk_text_view_scroll_pages (GtkTextView           *text_view,
396                                             gint                   count,
397                                             gboolean               extend_selection);
398 static gboolean gtk_text_view_scroll_hpages(GtkTextView           *text_view,
399                                             gint                   count,
400                                             gboolean               extend_selection);
401 static void gtk_text_view_insert_at_cursor (GtkTextView           *text_view,
402                                             const gchar           *str);
403 static void gtk_text_view_delete_from_cursor (GtkTextView           *text_view,
404                                               GtkDeleteType          type,
405                                               gint                   count);
406 static void gtk_text_view_backspace        (GtkTextView           *text_view);
407 static void gtk_text_view_cut_clipboard    (GtkTextView           *text_view);
408 static void gtk_text_view_copy_clipboard   (GtkTextView           *text_view);
409 static void gtk_text_view_paste_clipboard  (GtkTextView           *text_view);
410 static void gtk_text_view_toggle_overwrite (GtkTextView           *text_view);
411 static void gtk_text_view_toggle_cursor_visible (GtkTextView      *text_view);
412
413 static void gtk_text_view_unselect         (GtkTextView           *text_view);
414
415 static void     gtk_text_view_validate_onscreen     (GtkTextView        *text_view);
416 static void     gtk_text_view_get_first_para_iter   (GtkTextView        *text_view,
417                                                      GtkTextIter        *iter);
418 static void     gtk_text_view_update_layout_width       (GtkTextView        *text_view);
419 static void     gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
420                                                          GtkTextAttributes  *values);
421 static void     gtk_text_view_ensure_layout          (GtkTextView        *text_view);
422 static void     gtk_text_view_destroy_layout         (GtkTextView        *text_view);
423 static void     gtk_text_view_check_keymap_direction (GtkTextView        *text_view);
424 static void     gtk_text_view_start_selection_drag   (GtkTextView        *text_view,
425                                                       const GtkTextIter  *iter,
426                                                       GdkEventButton     *event);
427 static gboolean gtk_text_view_end_selection_drag     (GtkTextView        *text_view);
428 static void     gtk_text_view_start_selection_dnd    (GtkTextView        *text_view,
429                                                       const GtkTextIter  *iter,
430                                                       GdkEventMotion     *event);
431 static void     gtk_text_view_check_cursor_blink     (GtkTextView        *text_view);
432 static void     gtk_text_view_pend_cursor_blink      (GtkTextView        *text_view);
433 static void     gtk_text_view_stop_cursor_blink      (GtkTextView        *text_view);
434 static void     gtk_text_view_reset_blink_time       (GtkTextView        *text_view);
435
436 static void     gtk_text_view_value_changed                (GtkAdjustment *adjustment,
437                                                             GtkTextView   *view);
438 static void     gtk_text_view_commit_handler               (GtkIMContext  *context,
439                                                             const gchar   *str,
440                                                             GtkTextView   *text_view);
441 static void     gtk_text_view_commit_text                  (GtkTextView   *text_view,
442                                                             const gchar   *text);
443 static void     gtk_text_view_preedit_changed_handler      (GtkIMContext  *context,
444                                                             GtkTextView   *text_view);
445 static gboolean gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
446                                                             GtkTextView   *text_view);
447 static gboolean gtk_text_view_delete_surrounding_handler   (GtkIMContext  *context,
448                                                             gint           offset,
449                                                             gint           n_chars,
450                                                             GtkTextView   *text_view);
451
452 static void gtk_text_view_mark_set_handler       (GtkTextBuffer     *buffer,
453                                                   const GtkTextIter *location,
454                                                   GtkTextMark       *mark,
455                                                   gpointer           data);
456 static void gtk_text_view_target_list_notify     (GtkTextBuffer     *buffer,
457                                                   const GParamSpec  *pspec,
458                                                   gpointer           data);
459 static void gtk_text_view_paste_done_handler     (GtkTextBuffer     *buffer,
460                                                   GtkClipboard      *clipboard,
461                                                   gpointer           data);
462 static void gtk_text_view_buffer_changed_handler (GtkTextBuffer     *buffer,
463                                                   gpointer           data);
464 static void gtk_text_view_get_virtual_cursor_pos (GtkTextView       *text_view,
465                                                   GtkTextIter       *cursor,
466                                                   gint              *x,
467                                                   gint              *y);
468 static void gtk_text_view_set_virtual_cursor_pos (GtkTextView       *text_view,
469                                                   gint               x,
470                                                   gint               y);
471
472 static void gtk_text_view_do_popup               (GtkTextView       *text_view,
473                                                   GdkEventButton    *event);
474
475 static void cancel_pending_scroll                (GtkTextView   *text_view);
476 static void gtk_text_view_queue_scroll           (GtkTextView   *text_view,
477                                                   GtkTextMark   *mark,
478                                                   gdouble        within_margin,
479                                                   gboolean       use_align,
480                                                   gdouble        xalign,
481                                                   gdouble        yalign);
482
483 static gboolean gtk_text_view_flush_scroll         (GtkTextView *text_view);
484 static void     gtk_text_view_update_adjustments   (GtkTextView *text_view);
485 static void     gtk_text_view_invalidate           (GtkTextView *text_view);
486 static void     gtk_text_view_flush_first_validate (GtkTextView *text_view);
487
488 static void     gtk_text_view_set_hadjustment        (GtkTextView   *text_view,
489                                                       GtkAdjustment *adjustment);
490 static void     gtk_text_view_set_vadjustment        (GtkTextView   *text_view,
491                                                       GtkAdjustment *adjustment);
492 static void     gtk_text_view_set_hadjustment_values (GtkTextView   *text_view);
493 static void     gtk_text_view_set_vadjustment_values (GtkTextView   *text_view);
494
495 static void gtk_text_view_update_im_spot_location (GtkTextView *text_view);
496
497 /* Container methods */
498 static void gtk_text_view_add    (GtkContainer *container,
499                                   GtkWidget    *child);
500 static void gtk_text_view_remove (GtkContainer *container,
501                                   GtkWidget    *child);
502 static void gtk_text_view_forall (GtkContainer *container,
503                                   gboolean      include_internals,
504                                   GtkCallback   callback,
505                                   gpointer      callback_data);
506
507 /* GtkTextHandle handlers */
508 static void gtk_text_view_handle_dragged       (GtkTextHandle         *handle,
509                                                 GtkTextHandlePosition  pos,
510                                                 gint                   x,
511                                                 gint                   y,
512                                                 GtkTextView           *text_view);
513 static void gtk_text_view_update_handles       (GtkTextView           *text_view,
514                                                 GtkTextHandleMode      mode);
515
516 /* FIXME probably need the focus methods. */
517
518 typedef struct _GtkTextViewChild GtkTextViewChild;
519
520 struct _GtkTextViewChild
521 {
522   GtkWidget *widget;
523
524   GtkTextChildAnchor *anchor;
525
526   gint from_top_of_line;
527   gint from_left_of_buffer;
528   
529   /* These are ignored if anchor != NULL */
530   GtkTextWindowType type;
531   gint x;
532   gint y;
533 };
534
535 static GtkTextViewChild* text_view_child_new_anchored      (GtkWidget          *child,
536                                                             GtkTextChildAnchor *anchor,
537                                                             GtkTextLayout      *layout);
538 static GtkTextViewChild* text_view_child_new_window        (GtkWidget          *child,
539                                                             GtkTextWindowType   type,
540                                                             gint                x,
541                                                             gint                y);
542 static void              text_view_child_free              (GtkTextViewChild   *child);
543 static void              text_view_child_set_parent_window (GtkTextView        *text_view,
544                                                             GtkTextViewChild   *child);
545
546 struct _GtkTextWindow
547 {
548   GtkTextWindowType type;
549   GtkWidget *widget;
550   GdkWindow *window;
551   GdkWindow *bin_window;
552   GtkRequisition requisition;
553   GdkRectangle allocation;
554 };
555
556 static GtkTextWindow *text_window_new             (GtkTextWindowType  type,
557                                                    GtkWidget         *widget,
558                                                    gint               width_request,
559                                                    gint               height_request);
560 static void           text_window_free            (GtkTextWindow     *win);
561 static void           text_window_realize         (GtkTextWindow     *win,
562                                                    GtkWidget         *widget);
563 static void           text_window_unrealize       (GtkTextWindow     *win);
564 static void           text_window_size_allocate   (GtkTextWindow     *win,
565                                                    GdkRectangle      *rect);
566 static void           text_window_scroll          (GtkTextWindow     *win,
567                                                    gint               dx,
568                                                    gint               dy);
569 static void           text_window_invalidate_rect (GtkTextWindow     *win,
570                                                    GdkRectangle      *rect);
571 static void           text_window_invalidate_cursors (GtkTextWindow  *win);
572
573 static gint           text_window_get_width       (GtkTextWindow     *win);
574 static gint           text_window_get_height      (GtkTextWindow     *win);
575
576
577 static guint signals[LAST_SIGNAL] = { 0 };
578 static gboolean test_touchscreen = FALSE;
579
580 G_DEFINE_TYPE_WITH_CODE (GtkTextView, gtk_text_view, GTK_TYPE_CONTAINER,
581                          G_IMPLEMENT_INTERFACE (GTK_TYPE_SCROLLABLE, NULL))
582
583 static void
584 add_move_binding (GtkBindingSet  *binding_set,
585                   guint           keyval,
586                   guint           modmask,
587                   GtkMovementStep step,
588                   gint            count)
589 {
590   g_assert ((modmask & GDK_SHIFT_MASK) == 0);
591
592   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
593                                 "move-cursor", 3,
594                                 G_TYPE_ENUM, step,
595                                 G_TYPE_INT, count,
596                                 G_TYPE_BOOLEAN, FALSE);
597
598   /* Selection-extending version */
599   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
600                                 "move-cursor", 3,
601                                 G_TYPE_ENUM, step,
602                                 G_TYPE_INT, count,
603                                 G_TYPE_BOOLEAN, TRUE);
604 }
605
606 static void
607 gtk_text_view_class_init (GtkTextViewClass *klass)
608 {
609   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
610   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
611   GtkContainerClass *container_class = GTK_CONTAINER_CLASS (klass);
612   GtkBindingSet *binding_set;
613
614   /* Default handlers and virtual methods
615    */
616   gobject_class->set_property = gtk_text_view_set_property;
617   gobject_class->get_property = gtk_text_view_get_property;
618   gobject_class->finalize = gtk_text_view_finalize;
619
620   widget_class->destroy = gtk_text_view_destroy;
621   widget_class->realize = gtk_text_view_realize;
622   widget_class->unrealize = gtk_text_view_unrealize;
623   widget_class->style_updated = gtk_text_view_style_updated;
624   widget_class->direction_changed = gtk_text_view_direction_changed;
625   widget_class->grab_notify = gtk_text_view_grab_notify;
626   widget_class->state_flags_changed = gtk_text_view_state_flags_changed;
627   widget_class->get_preferred_width = gtk_text_view_get_preferred_width;
628   widget_class->get_preferred_height = gtk_text_view_get_preferred_height;
629   widget_class->size_allocate = gtk_text_view_size_allocate;
630   widget_class->event = gtk_text_view_event;
631   widget_class->key_press_event = gtk_text_view_key_press_event;
632   widget_class->key_release_event = gtk_text_view_key_release_event;
633   widget_class->button_press_event = gtk_text_view_button_press_event;
634   widget_class->button_release_event = gtk_text_view_button_release_event;
635   widget_class->focus_in_event = gtk_text_view_focus_in_event;
636   widget_class->focus_out_event = gtk_text_view_focus_out_event;
637   widget_class->motion_notify_event = gtk_text_view_motion_event;
638   widget_class->draw = gtk_text_view_draw;
639   widget_class->focus = gtk_text_view_focus;
640   widget_class->drag_begin = gtk_text_view_drag_begin;
641   widget_class->drag_end = gtk_text_view_drag_end;
642   widget_class->drag_data_get = gtk_text_view_drag_data_get;
643   widget_class->drag_data_delete = gtk_text_view_drag_data_delete;
644
645   widget_class->drag_leave = gtk_text_view_drag_leave;
646   widget_class->drag_motion = gtk_text_view_drag_motion;
647   widget_class->drag_drop = gtk_text_view_drag_drop;
648   widget_class->drag_data_received = gtk_text_view_drag_data_received;
649
650   widget_class->popup_menu = gtk_text_view_popup_menu;
651   
652   container_class->add = gtk_text_view_add;
653   container_class->remove = gtk_text_view_remove;
654   container_class->forall = gtk_text_view_forall;
655
656   klass->move_cursor = gtk_text_view_move_cursor;
657   klass->set_anchor = gtk_text_view_set_anchor;
658   klass->insert_at_cursor = gtk_text_view_insert_at_cursor;
659   klass->delete_from_cursor = gtk_text_view_delete_from_cursor;
660   klass->backspace = gtk_text_view_backspace;
661   klass->cut_clipboard = gtk_text_view_cut_clipboard;
662   klass->copy_clipboard = gtk_text_view_copy_clipboard;
663   klass->paste_clipboard = gtk_text_view_paste_clipboard;
664   klass->toggle_overwrite = gtk_text_view_toggle_overwrite;
665
666   /*
667    * Properties
668    */
669  
670   g_object_class_install_property (gobject_class,
671                                    PROP_PIXELS_ABOVE_LINES,
672                                    g_param_spec_int ("pixels-above-lines",
673                                                      P_("Pixels Above Lines"),
674                                                      P_("Pixels of blank space above paragraphs"),
675                                                      0,
676                                                      G_MAXINT,
677                                                      0,
678                                                      GTK_PARAM_READWRITE));
679  
680   g_object_class_install_property (gobject_class,
681                                    PROP_PIXELS_BELOW_LINES,
682                                    g_param_spec_int ("pixels-below-lines",
683                                                      P_("Pixels Below Lines"),
684                                                      P_("Pixels of blank space below paragraphs"),
685                                                      0,
686                                                      G_MAXINT,
687                                                      0,
688                                                      GTK_PARAM_READWRITE));
689  
690   g_object_class_install_property (gobject_class,
691                                    PROP_PIXELS_INSIDE_WRAP,
692                                    g_param_spec_int ("pixels-inside-wrap",
693                                                      P_("Pixels Inside Wrap"),
694                                                      P_("Pixels of blank space between wrapped lines in a paragraph"),
695                                                      0,
696                                                      G_MAXINT,
697                                                      0,
698                                                      GTK_PARAM_READWRITE));
699
700   g_object_class_install_property (gobject_class,
701                                    PROP_EDITABLE,
702                                    g_param_spec_boolean ("editable",
703                                                          P_("Editable"),
704                                                          P_("Whether the text can be modified by the user"),
705                                                          TRUE,
706                                                          GTK_PARAM_READWRITE));
707
708   g_object_class_install_property (gobject_class,
709                                    PROP_WRAP_MODE,
710                                    g_param_spec_enum ("wrap-mode",
711                                                       P_("Wrap Mode"),
712                                                       P_("Whether to wrap lines never, at word boundaries, or at character boundaries"),
713                                                       GTK_TYPE_WRAP_MODE,
714                                                       GTK_WRAP_NONE,
715                                                       GTK_PARAM_READWRITE));
716  
717   g_object_class_install_property (gobject_class,
718                                    PROP_JUSTIFICATION,
719                                    g_param_spec_enum ("justification",
720                                                       P_("Justification"),
721                                                       P_("Left, right, or center justification"),
722                                                       GTK_TYPE_JUSTIFICATION,
723                                                       GTK_JUSTIFY_LEFT,
724                                                       GTK_PARAM_READWRITE));
725  
726   g_object_class_install_property (gobject_class,
727                                    PROP_LEFT_MARGIN,
728                                    g_param_spec_int ("left-margin",
729                                                      P_("Left Margin"),
730                                                      P_("Width of the left margin in pixels"),
731                                                      0,
732                                                      G_MAXINT,
733                                                      0,
734                                                      GTK_PARAM_READWRITE));
735
736   g_object_class_install_property (gobject_class,
737                                    PROP_RIGHT_MARGIN,
738                                    g_param_spec_int ("right-margin",
739                                                      P_("Right Margin"),
740                                                      P_("Width of the right margin in pixels"),
741                                                      0,
742                                                      G_MAXINT,
743                                                      0,
744                                                      GTK_PARAM_READWRITE));
745
746   g_object_class_install_property (gobject_class,
747                                    PROP_INDENT,
748                                    g_param_spec_int ("indent",
749                                                      P_("Indent"),
750                                                      P_("Amount to indent the paragraph, in pixels"),
751                                                      G_MININT,
752                                                      G_MAXINT,
753                                                      0,
754                                                      GTK_PARAM_READWRITE));
755
756   g_object_class_install_property (gobject_class,
757                                    PROP_TABS,
758                                    g_param_spec_boxed ("tabs",
759                                                        P_("Tabs"),
760                                                        P_("Custom tabs for this text"),
761                                                        PANGO_TYPE_TAB_ARRAY,
762                                                        GTK_PARAM_READWRITE));
763
764   g_object_class_install_property (gobject_class,
765                                    PROP_CURSOR_VISIBLE,
766                                    g_param_spec_boolean ("cursor-visible",
767                                                          P_("Cursor Visible"),
768                                                          P_("If the insertion cursor is shown"),
769                                                          TRUE,
770                                                          GTK_PARAM_READWRITE));
771
772   g_object_class_install_property (gobject_class,
773                                    PROP_BUFFER,
774                                    g_param_spec_object ("buffer",
775                                                         P_("Buffer"),
776                                                         P_("The buffer which is displayed"),
777                                                         GTK_TYPE_TEXT_BUFFER,
778                                                         GTK_PARAM_READWRITE));
779
780   g_object_class_install_property (gobject_class,
781                                    PROP_OVERWRITE,
782                                    g_param_spec_boolean ("overwrite",
783                                                          P_("Overwrite mode"),
784                                                          P_("Whether entered text overwrites existing contents"),
785                                                          FALSE,
786                                                          GTK_PARAM_READWRITE));
787
788   g_object_class_install_property (gobject_class,
789                                    PROP_ACCEPTS_TAB,
790                                    g_param_spec_boolean ("accepts-tab",
791                                                          P_("Accepts tab"),
792                                                          P_("Whether Tab will result in a tab character being entered"),
793                                                          TRUE,
794                                                          GTK_PARAM_READWRITE));
795
796    /**
797     * GtkTextView:im-module:
798     *
799     * Which IM (input method) module should be used for this text_view. 
800     * See #GtkIMContext.
801     *
802     * Setting this to a non-%NULL value overrides the
803     * system-wide IM module setting. See the GtkSettings 
804     * #GtkSettings:gtk-im-module property.
805     *
806     * Since: 2.16
807     */
808    g_object_class_install_property (gobject_class,
809                                     PROP_IM_MODULE,
810                                     g_param_spec_string ("im-module",
811                                                          P_("IM module"),
812                                                          P_("Which IM module should be used"),
813                                                          NULL,
814                                                          GTK_PARAM_READWRITE));
815
816   /**
817    * GtkTextView:input-purpose:
818    *
819    * The purpose of this text field.
820    *
821    * This property can be used by on-screen keyboards and other input
822    * methods to adjust their behaviour.
823    *
824    * Since: 3.6
825    */
826   g_object_class_install_property (gobject_class,
827                                    PROP_INPUT_PURPOSE,
828                                    g_param_spec_enum ("input-purpose",
829                                                       P_("Purpose"),
830                                                       P_("Purpose of the text field"),
831                                                       GTK_TYPE_INPUT_PURPOSE,
832                                                       GTK_INPUT_PURPOSE_FREE_FORM,
833                                                       G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
834
835   /**
836    * GtkTextView:input-hints:
837    *
838    * Additional hints (beyond #GtkTextView:input-purpose) that
839    * allow input methods to fine-tune their behaviour.
840    *
841    * Since: 3.6
842    */
843   g_object_class_install_property (gobject_class,
844                                    PROP_INPUT_HINTS,
845                                    g_param_spec_flags ("input-hints",
846                                                        P_("hints"),
847                                                        P_("Hints for the text field behaviour"),
848                                                        GTK_TYPE_INPUT_HINTS,
849                                                        GTK_INPUT_HINT_NONE,
850                                                        G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
851
852    /* GtkScrollable interface */
853    g_object_class_override_property (gobject_class, PROP_HADJUSTMENT,    "hadjustment");
854    g_object_class_override_property (gobject_class, PROP_VADJUSTMENT,    "vadjustment");
855    g_object_class_override_property (gobject_class, PROP_HSCROLL_POLICY, "hscroll-policy");
856    g_object_class_override_property (gobject_class, PROP_VSCROLL_POLICY, "vscroll-policy");
857
858   /*
859    * Style properties
860    */
861   gtk_widget_class_install_style_property (widget_class,
862                                            g_param_spec_boxed ("error-underline-color",
863                                                                P_("Error underline color"),
864                                                                P_("Color with which to draw error-indication underlines"),
865                                                                GDK_TYPE_COLOR,
866                                                                GTK_PARAM_READABLE));
867   
868   /*
869    * Signals
870    */
871
872   /**
873    * GtkTextView::move-cursor: 
874    * @text_view: the object which received the signal
875    * @step: the granularity of the move, as a #GtkMovementStep
876    * @count: the number of @step units to move
877    * @extend_selection: %TRUE if the move should extend the selection
878    *  
879    * The ::move-cursor signal is a 
880    * <link linkend="keybinding-signals">keybinding signal</link> 
881    * which gets emitted when the user initiates a cursor movement. 
882    * If the cursor is not visible in @text_view, this signal causes
883    * the viewport to be moved instead.
884    *
885    * Applications should not connect to it, but may emit it with 
886    * g_signal_emit_by_name() if they need to control the cursor
887    * programmatically.
888    *
889    * The default bindings for this signal come in two variants,
890    * the variant with the Shift modifier extends the selection,
891    * the variant without the Shift modifer does not.
892    * There are too many key combinations to list them all here.
893    * <itemizedlist>
894    * <listitem>Arrow keys move by individual characters/lines</listitem>
895    * <listitem>Ctrl-arrow key combinations move by words/paragraphs</listitem>
896    * <listitem>Home/End keys move to the ends of the buffer</listitem>
897    * <listitem>PageUp/PageDown keys move vertically by pages</listitem>
898    * <listitem>Ctrl-PageUp/PageDown keys move horizontally by pages</listitem>
899    * </itemizedlist>
900    */
901   signals[MOVE_CURSOR] = 
902     g_signal_new (I_("move-cursor"),
903                   G_OBJECT_CLASS_TYPE (gobject_class), 
904                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION, 
905                   G_STRUCT_OFFSET (GtkTextViewClass, move_cursor),
906                   NULL, NULL, 
907                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN, 
908                   G_TYPE_NONE, 3,
909                   GTK_TYPE_MOVEMENT_STEP, 
910                   G_TYPE_INT, 
911                   G_TYPE_BOOLEAN);
912
913   /**
914    * GtkTextView::move-viewport:
915    * @text_view: the object which received the signal
916    * @step: the granularity of the move, as a #GtkMovementStep
917    * @count: the number of @step units to move
918    *
919    * The ::move-viewport signal is a 
920    * <link linkend="keybinding-signals">keybinding signal</link> 
921    * which can be bound to key combinations to allow the user
922    * to move the viewport, i.e. change what part of the text view
923    * is visible in a containing scrolled window.
924    *
925    * There are no default bindings for this signal.
926    */
927   signals[MOVE_VIEWPORT] =
928     g_signal_new_class_handler (I_("move-viewport"),
929                                 G_OBJECT_CLASS_TYPE (gobject_class),
930                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
931                                 G_CALLBACK (gtk_text_view_move_viewport),
932                                 NULL, NULL,
933                                 _gtk_marshal_VOID__ENUM_INT,
934                                 G_TYPE_NONE, 2,
935                                 GTK_TYPE_SCROLL_STEP,
936                                 G_TYPE_INT);
937
938   /**
939    * GtkTextView::set-anchor:
940    * @text_view: the object which received the signal
941    *
942    * The ::set-anchor signal is a
943    * <link linkend="keybinding-signals">keybinding signal</link>
944    * which gets emitted when the user initiates setting the "anchor" 
945    * mark. The "anchor" mark gets placed at the same position as the
946    * "insert" mark.
947    *
948    * This signal has no default bindings.
949    */   
950   signals[SET_ANCHOR] =
951     g_signal_new (I_("set-anchor"),
952                   G_OBJECT_CLASS_TYPE (gobject_class),
953                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
954                   G_STRUCT_OFFSET (GtkTextViewClass, set_anchor),
955                   NULL, NULL,
956                   _gtk_marshal_VOID__VOID,
957                   G_TYPE_NONE, 0);
958
959   /**
960    * GtkTextView::insert-at-cursor:
961    * @text_view: the object which received the signal
962    * @string: the string to insert
963    *
964    * The ::insert-at-cursor signal is a
965    * <link linkend="keybinding-signals">keybinding signal</link>
966    * which gets emitted when the user initiates the insertion of a 
967    * fixed string at the cursor.
968    *
969    * This signal has no default bindings.
970    */
971   signals[INSERT_AT_CURSOR] =
972     g_signal_new (I_("insert-at-cursor"),
973                   G_OBJECT_CLASS_TYPE (gobject_class),
974                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
975                   G_STRUCT_OFFSET (GtkTextViewClass, insert_at_cursor),
976                   NULL, NULL,
977                   _gtk_marshal_VOID__STRING,
978                   G_TYPE_NONE, 1,
979                   G_TYPE_STRING);
980
981   /**
982    * GtkTextView::delete-from-cursor:
983    * @text_view: the object which received the signal
984    * @type: the granularity of the deletion, as a #GtkDeleteType
985    * @count: the number of @type units to delete
986    *
987    * The ::delete-from-cursor signal is a 
988    * <link linkend="keybinding-signals">keybinding signal</link> 
989    * which gets emitted when the user initiates a text deletion.
990    *
991    * If the @type is %GTK_DELETE_CHARS, GTK+ deletes the selection
992    * if there is one, otherwise it deletes the requested number
993    * of characters.
994    *
995    * The default bindings for this signal are
996    * Delete for deleting a character, Ctrl-Delete for 
997    * deleting a word and Ctrl-Backspace for deleting a word 
998    * backwords.
999    */
1000   signals[DELETE_FROM_CURSOR] =
1001     g_signal_new (I_("delete-from-cursor"),
1002                   G_OBJECT_CLASS_TYPE (gobject_class),
1003                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1004                   G_STRUCT_OFFSET (GtkTextViewClass, delete_from_cursor),
1005                   NULL, NULL,
1006                   _gtk_marshal_VOID__ENUM_INT,
1007                   G_TYPE_NONE, 2,
1008                   GTK_TYPE_DELETE_TYPE,
1009                   G_TYPE_INT);
1010
1011   /**
1012    * GtkTextView::backspace:
1013    * @text_view: the object which received the signal
1014    *
1015    * The ::backspace signal is a 
1016    * <link linkend="keybinding-signals">keybinding signal</link> 
1017    * which gets emitted when the user asks for it.
1018    * 
1019    * The default bindings for this signal are
1020    * Backspace and Shift-Backspace.
1021    */
1022   signals[BACKSPACE] =
1023     g_signal_new (I_("backspace"),
1024                   G_OBJECT_CLASS_TYPE (gobject_class),
1025                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1026                   G_STRUCT_OFFSET (GtkTextViewClass, backspace),
1027                   NULL, NULL,
1028                   _gtk_marshal_VOID__VOID,
1029                   G_TYPE_NONE, 0);
1030
1031   /**
1032    * GtkTextView::cut-clipboard:
1033    * @text_view: the object which received the signal
1034    *
1035    * The ::cut-clipboard signal is a 
1036    * <link linkend="keybinding-signals">keybinding signal</link> 
1037    * which gets emitted to cut the selection to the clipboard.
1038    * 
1039    * The default bindings for this signal are
1040    * Ctrl-x and Shift-Delete.
1041    */
1042   signals[CUT_CLIPBOARD] =
1043     g_signal_new (I_("cut-clipboard"),
1044                   G_OBJECT_CLASS_TYPE (gobject_class),
1045                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1046                   G_STRUCT_OFFSET (GtkTextViewClass, cut_clipboard),
1047                   NULL, NULL,
1048                   _gtk_marshal_VOID__VOID,
1049                   G_TYPE_NONE, 0);
1050
1051   /**
1052    * GtkTextView::copy-clipboard:
1053    * @text_view: the object which received the signal
1054    *
1055    * The ::copy-clipboard signal is a 
1056    * <link linkend="keybinding-signals">keybinding signal</link> 
1057    * which gets emitted to copy the selection to the clipboard.
1058    * 
1059    * The default bindings for this signal are
1060    * Ctrl-c and Ctrl-Insert.
1061    */
1062   signals[COPY_CLIPBOARD] =
1063     g_signal_new (I_("copy-clipboard"),
1064                   G_OBJECT_CLASS_TYPE (gobject_class),
1065                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1066                   G_STRUCT_OFFSET (GtkTextViewClass, copy_clipboard),
1067                   NULL, NULL,
1068                   _gtk_marshal_VOID__VOID,
1069                   G_TYPE_NONE, 0);
1070
1071   /**
1072    * GtkTextView::paste-clipboard:
1073    * @text_view: the object which received the signal
1074    *
1075    * The ::paste-clipboard signal is a 
1076    * <link linkend="keybinding-signals">keybinding signal</link> 
1077    * which gets emitted to paste the contents of the clipboard 
1078    * into the text view.
1079    * 
1080    * The default bindings for this signal are
1081    * Ctrl-v and Shift-Insert.
1082    */
1083   signals[PASTE_CLIPBOARD] =
1084     g_signal_new (I_("paste-clipboard"),
1085                   G_OBJECT_CLASS_TYPE (gobject_class),
1086                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1087                   G_STRUCT_OFFSET (GtkTextViewClass, paste_clipboard),
1088                   NULL, NULL,
1089                   _gtk_marshal_VOID__VOID,
1090                   G_TYPE_NONE, 0);
1091
1092   /**
1093    * GtkTextView::toggle-overwrite:
1094    * @text_view: the object which received the signal
1095    *
1096    * The ::toggle-overwrite signal is a 
1097    * <link linkend="keybinding-signals">keybinding signal</link> 
1098    * which gets emitted to toggle the overwrite mode of the text view.
1099    * 
1100    * The default bindings for this signal is Insert.
1101    */ 
1102   signals[TOGGLE_OVERWRITE] =
1103     g_signal_new (I_("toggle-overwrite"),
1104                   G_OBJECT_CLASS_TYPE (gobject_class),
1105                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1106                   G_STRUCT_OFFSET (GtkTextViewClass, toggle_overwrite),
1107                   NULL, NULL,
1108                   _gtk_marshal_VOID__VOID,
1109                   G_TYPE_NONE, 0);
1110
1111   /**
1112    * GtkTextView::populate-popup:
1113    * @text_view: The text view on which the signal is emitted
1114    * @menu: the menu that is being populated
1115    *
1116    * The ::populate-popup signal gets emitted before showing the 
1117    * context menu of the text view.
1118    *
1119    * If you need to add items to the context menu, connect
1120    * to this signal and append your menuitems to the @menu.
1121    */
1122   signals[POPULATE_POPUP] =
1123     g_signal_new (I_("populate-popup"),
1124                   G_OBJECT_CLASS_TYPE (gobject_class),
1125                   G_SIGNAL_RUN_LAST,
1126                   G_STRUCT_OFFSET (GtkTextViewClass, populate_popup),
1127                   NULL, NULL,
1128                   _gtk_marshal_VOID__OBJECT,
1129                   G_TYPE_NONE, 1,
1130                   GTK_TYPE_MENU);
1131   
1132   /**
1133    * GtkTextView::select-all:
1134    * @text_view: the object which received the signal
1135    * @select: %TRUE to select, %FALSE to unselect
1136    *
1137    * The ::select-all signal is a 
1138    * <link linkend="keybinding-signals">keybinding signal</link> 
1139    * which gets emitted to select or unselect the complete
1140    * contents of the text view.
1141    *
1142    * The default bindings for this signal are Ctrl-a and Ctrl-/ 
1143    * for selecting and Shift-Ctrl-a and Ctrl-\ for unselecting.
1144    */
1145   signals[SELECT_ALL] =
1146     g_signal_new_class_handler (I_("select-all"),
1147                                 G_OBJECT_CLASS_TYPE (gobject_class),
1148                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1149                                 G_CALLBACK (gtk_text_view_select_all),
1150                                 NULL, NULL,
1151                                 _gtk_marshal_VOID__BOOLEAN,
1152                                 G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
1153
1154   /**
1155    * GtkTextView::toggle-cursor-visible:
1156    * @text_view: the object which received the signal
1157    *
1158    * The ::toggle-cursor-visible signal is a 
1159    * <link linkend="keybinding-signals">keybinding signal</link> 
1160    * which gets emitted to toggle the visibility of the cursor.
1161    *
1162    * The default binding for this signal is F7.
1163    */ 
1164   signals[TOGGLE_CURSOR_VISIBLE] =
1165     g_signal_new_class_handler (I_("toggle-cursor-visible"),
1166                                 G_OBJECT_CLASS_TYPE (gobject_class),
1167                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1168                                 G_CALLBACK (gtk_text_view_toggle_cursor_visible),
1169                                 NULL, NULL,
1170                                 _gtk_marshal_VOID__VOID,
1171                                 G_TYPE_NONE, 0);
1172
1173   /**
1174    * GtkTextView::preedit-changed:
1175    * @text_view: the object which received the signal
1176    * @preedit: the current preedit string
1177    *
1178    * If an input method is used, the typed text will not immediately
1179    * be committed to the buffer. So if you are interested in the text,
1180    * connect to this signal.
1181    *
1182    * This signal is only emitted if the text at the given position
1183    * is actually editable.
1184    *
1185    * Since: 2.20
1186    */
1187   signals[PREEDIT_CHANGED] =
1188     g_signal_new_class_handler (I_("preedit-changed"),
1189                                 G_OBJECT_CLASS_TYPE (gobject_class),
1190                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1191                                 NULL,
1192                                 NULL, NULL,
1193                                 _gtk_marshal_VOID__STRING,
1194                                 G_TYPE_NONE, 1,
1195                                 G_TYPE_STRING);
1196
1197   /*
1198    * Key bindings
1199    */
1200
1201   binding_set = gtk_binding_set_by_class (klass);
1202   
1203   /* Moving the insertion point */
1204   add_move_binding (binding_set, GDK_KEY_Right, 0,
1205                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1206
1207   add_move_binding (binding_set, GDK_KEY_KP_Right, 0,
1208                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
1209   
1210   add_move_binding (binding_set, GDK_KEY_Left, 0,
1211                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1212
1213   add_move_binding (binding_set, GDK_KEY_KP_Left, 0,
1214                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
1215   
1216   add_move_binding (binding_set, GDK_KEY_Right, GDK_CONTROL_MASK,
1217                     GTK_MOVEMENT_WORDS, 1);
1218
1219   add_move_binding (binding_set, GDK_KEY_KP_Right, GDK_CONTROL_MASK,
1220                     GTK_MOVEMENT_WORDS, 1);
1221   
1222   add_move_binding (binding_set, GDK_KEY_Left, GDK_CONTROL_MASK,
1223                     GTK_MOVEMENT_WORDS, -1);
1224
1225   add_move_binding (binding_set, GDK_KEY_KP_Left, GDK_CONTROL_MASK,
1226                     GTK_MOVEMENT_WORDS, -1);
1227   
1228   add_move_binding (binding_set, GDK_KEY_Up, 0,
1229                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1230
1231   add_move_binding (binding_set, GDK_KEY_KP_Up, 0,
1232                     GTK_MOVEMENT_DISPLAY_LINES, -1);
1233   
1234   add_move_binding (binding_set, GDK_KEY_Down, 0,
1235                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1236
1237   add_move_binding (binding_set, GDK_KEY_KP_Down, 0,
1238                     GTK_MOVEMENT_DISPLAY_LINES, 1);
1239   
1240   add_move_binding (binding_set, GDK_KEY_Up, GDK_CONTROL_MASK,
1241                     GTK_MOVEMENT_PARAGRAPHS, -1);
1242
1243   add_move_binding (binding_set, GDK_KEY_KP_Up, GDK_CONTROL_MASK,
1244                     GTK_MOVEMENT_PARAGRAPHS, -1);
1245   
1246   add_move_binding (binding_set, GDK_KEY_Down, GDK_CONTROL_MASK,
1247                     GTK_MOVEMENT_PARAGRAPHS, 1);
1248
1249   add_move_binding (binding_set, GDK_KEY_KP_Down, GDK_CONTROL_MASK,
1250                     GTK_MOVEMENT_PARAGRAPHS, 1);
1251   
1252   add_move_binding (binding_set, GDK_KEY_Home, 0,
1253                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1254
1255   add_move_binding (binding_set, GDK_KEY_KP_Home, 0,
1256                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1257   
1258   add_move_binding (binding_set, GDK_KEY_End, 0,
1259                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1260
1261   add_move_binding (binding_set, GDK_KEY_KP_End, 0,
1262                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1263   
1264   add_move_binding (binding_set, GDK_KEY_Home, GDK_CONTROL_MASK,
1265                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1266
1267   add_move_binding (binding_set, GDK_KEY_KP_Home, GDK_CONTROL_MASK,
1268                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1269   
1270   add_move_binding (binding_set, GDK_KEY_End, GDK_CONTROL_MASK,
1271                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1272
1273   add_move_binding (binding_set, GDK_KEY_KP_End, GDK_CONTROL_MASK,
1274                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1275   
1276   add_move_binding (binding_set, GDK_KEY_Page_Up, 0,
1277                     GTK_MOVEMENT_PAGES, -1);
1278
1279   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, 0,
1280                     GTK_MOVEMENT_PAGES, -1);
1281   
1282   add_move_binding (binding_set, GDK_KEY_Page_Down, 0,
1283                     GTK_MOVEMENT_PAGES, 1);
1284
1285   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, 0,
1286                     GTK_MOVEMENT_PAGES, 1);
1287
1288   add_move_binding (binding_set, GDK_KEY_Page_Up, GDK_CONTROL_MASK,
1289                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1290
1291   add_move_binding (binding_set, GDK_KEY_KP_Page_Up, GDK_CONTROL_MASK,
1292                     GTK_MOVEMENT_HORIZONTAL_PAGES, -1);
1293   
1294   add_move_binding (binding_set, GDK_KEY_Page_Down, GDK_CONTROL_MASK,
1295                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1296
1297   add_move_binding (binding_set, GDK_KEY_KP_Page_Down, GDK_CONTROL_MASK,
1298                     GTK_MOVEMENT_HORIZONTAL_PAGES, 1);
1299
1300   /* Select all */
1301   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_CONTROL_MASK,
1302                                 "select-all", 1,
1303                                 G_TYPE_BOOLEAN, TRUE);
1304
1305   gtk_binding_entry_add_signal (binding_set, GDK_KEY_slash, GDK_CONTROL_MASK,
1306                                 "select-all", 1,
1307                                 G_TYPE_BOOLEAN, TRUE);
1308   
1309   /* Unselect all */
1310   gtk_binding_entry_add_signal (binding_set, GDK_KEY_backslash, GDK_CONTROL_MASK,
1311                                  "select-all", 1,
1312                                  G_TYPE_BOOLEAN, FALSE);
1313
1314   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1315                                  "select-all", 1,
1316                                  G_TYPE_BOOLEAN, FALSE);
1317
1318   /* Deleting text */
1319   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, 0,
1320                                 "delete-from-cursor", 2,
1321                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1322                                 G_TYPE_INT, 1);
1323
1324   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, 0,
1325                                 "delete-from-cursor", 2,
1326                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
1327                                 G_TYPE_INT, 1);
1328   
1329   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, 0,
1330                                 "backspace", 0);
1331
1332   /* Make this do the same as Backspace, to help with mis-typing */
1333   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK,
1334                                 "backspace", 0);
1335
1336   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_CONTROL_MASK,
1337                                 "delete-from-cursor", 2,
1338                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1339                                 G_TYPE_INT, 1);
1340
1341   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_CONTROL_MASK,
1342                                 "delete-from-cursor", 2,
1343                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1344                                 G_TYPE_INT, 1);
1345   
1346   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_CONTROL_MASK,
1347                                 "delete-from-cursor", 2,
1348                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
1349                                 G_TYPE_INT, -1);
1350
1351   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1352                                 "delete-from-cursor", 2,
1353                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1354                                 G_TYPE_INT, 1);
1355
1356   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Delete, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1357                                 "delete-from-cursor", 2,
1358                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1359                                 G_TYPE_INT, 1);
1360
1361   gtk_binding_entry_add_signal (binding_set, GDK_KEY_BackSpace, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1362                                 "delete-from-cursor", 2,
1363                                 G_TYPE_ENUM, GTK_DELETE_PARAGRAPH_ENDS,
1364                                 G_TYPE_INT, -1);
1365
1366   /* Cut/copy/paste */
1367
1368   gtk_binding_entry_add_signal (binding_set, GDK_KEY_x, GDK_CONTROL_MASK,
1369                                 "cut-clipboard", 0);
1370   gtk_binding_entry_add_signal (binding_set, GDK_KEY_c, GDK_CONTROL_MASK,
1371                                 "copy-clipboard", 0);
1372   gtk_binding_entry_add_signal (binding_set, GDK_KEY_v, GDK_CONTROL_MASK,
1373                                 "paste-clipboard", 0);
1374
1375   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Delete, GDK_SHIFT_MASK,
1376                                 "cut-clipboard", 0);
1377   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_CONTROL_MASK,
1378                                 "copy-clipboard", 0);
1379   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, GDK_SHIFT_MASK,
1380                                 "paste-clipboard", 0);
1381
1382   /* Overwrite */
1383   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Insert, 0,
1384                                 "toggle-overwrite", 0);
1385   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Insert, 0,
1386                                 "toggle-overwrite", 0);
1387
1388   /* Caret mode */
1389   gtk_binding_entry_add_signal (binding_set, GDK_KEY_F7, 0,
1390                                 "toggle-cursor-visible", 0);
1391
1392   /* Control-tab focus motion */
1393   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_CONTROL_MASK,
1394                                 "move-focus", 1,
1395                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1396   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_CONTROL_MASK,
1397                                 "move-focus", 1,
1398                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
1399   
1400   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1401                                 "move-focus", 1,
1402                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1403   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1404                                 "move-focus", 1,
1405                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
1406
1407   g_type_class_add_private (gobject_class, sizeof (GtkTextViewPrivate));
1408
1409   gtk_widget_class_set_accessible_type (widget_class, GTK_TYPE_TEXT_VIEW_ACCESSIBLE);
1410   test_touchscreen = g_getenv ("GTK_TEST_TOUCHSCREEN") != NULL;
1411 }
1412
1413 static void
1414 gtk_text_view_init (GtkTextView *text_view)
1415 {
1416   GtkWidget *widget = GTK_WIDGET (text_view);
1417   GtkTargetList *target_list;
1418   GtkTextViewPrivate *priv;
1419
1420   text_view->priv = GTK_TEXT_VIEW_GET_PRIVATE (text_view);
1421   priv = text_view->priv;
1422
1423   gtk_widget_set_can_focus (widget, TRUE);
1424
1425   /* Set up default style */
1426   priv->wrap_mode = GTK_WRAP_NONE;
1427   priv->pixels_above_lines = 0;
1428   priv->pixels_below_lines = 0;
1429   priv->pixels_inside_wrap = 0;
1430   priv->justify = GTK_JUSTIFY_LEFT;
1431   priv->left_margin = 0;
1432   priv->right_margin = 0;
1433   priv->indent = 0;
1434   priv->tabs = NULL;
1435   priv->editable = TRUE;
1436
1437   priv->scroll_after_paste = TRUE;
1438
1439   gtk_drag_dest_set (widget, 0, NULL, 0,
1440                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
1441
1442   target_list = gtk_target_list_new (NULL, 0);
1443   gtk_drag_dest_set_target_list (widget, target_list);
1444   gtk_target_list_unref (target_list);
1445
1446   priv->virtual_cursor_x = -1;
1447   priv->virtual_cursor_y = -1;
1448
1449   /* This object is completely private. No external entity can gain a reference
1450    * to it; so we create it here and destroy it in finalize ().
1451    */
1452   priv->im_context = gtk_im_multicontext_new ();
1453
1454   g_signal_connect (priv->im_context, "commit",
1455                     G_CALLBACK (gtk_text_view_commit_handler), text_view);
1456   g_signal_connect (priv->im_context, "preedit-changed",
1457                     G_CALLBACK (gtk_text_view_preedit_changed_handler), text_view);
1458   g_signal_connect (priv->im_context, "retrieve-surrounding",
1459                     G_CALLBACK (gtk_text_view_retrieve_surrounding_handler), text_view);
1460   g_signal_connect (priv->im_context, "delete-surrounding",
1461                     G_CALLBACK (gtk_text_view_delete_surrounding_handler), text_view);
1462
1463   priv->cursor_visible = TRUE;
1464
1465   priv->accepts_tab = TRUE;
1466
1467   priv->text_window = text_window_new (GTK_TEXT_WINDOW_TEXT,
1468                                        widget, 200, 200);
1469
1470   priv->drag_start_x = -1;
1471   priv->drag_start_y = -1;
1472
1473   priv->pending_place_cursor_button = 0;
1474
1475   /* We handle all our own redrawing */
1476   gtk_widget_set_redraw_on_allocate (widget, FALSE);
1477
1478   priv->text_handle = _gtk_text_handle_new (widget);
1479   g_signal_connect (priv->text_handle, "handle-dragged",
1480                     G_CALLBACK (gtk_text_view_handle_dragged), text_view);
1481 }
1482
1483 /**
1484  * gtk_text_view_new:
1485  *
1486  * Creates a new #GtkTextView. If you don't call gtk_text_view_set_buffer()
1487  * before using the text view, an empty default buffer will be created
1488  * for you. Get the buffer with gtk_text_view_get_buffer(). If you want
1489  * to specify your own buffer, consider gtk_text_view_new_with_buffer().
1490  *
1491  * Return value: a new #GtkTextView
1492  **/
1493 GtkWidget*
1494 gtk_text_view_new (void)
1495 {
1496   return g_object_new (GTK_TYPE_TEXT_VIEW, NULL);
1497 }
1498
1499 /**
1500  * gtk_text_view_new_with_buffer:
1501  * @buffer: a #GtkTextBuffer
1502  *
1503  * Creates a new #GtkTextView widget displaying the buffer
1504  * @buffer. One buffer can be shared among many widgets.
1505  * @buffer may be %NULL to create a default buffer, in which case
1506  * this function is equivalent to gtk_text_view_new(). The
1507  * text view adds its own reference count to the buffer; it does not
1508  * take over an existing reference.
1509  *
1510  * Return value: a new #GtkTextView.
1511  **/
1512 GtkWidget*
1513 gtk_text_view_new_with_buffer (GtkTextBuffer *buffer)
1514 {
1515   GtkTextView *text_view;
1516
1517   text_view = (GtkTextView*)gtk_text_view_new ();
1518
1519   gtk_text_view_set_buffer (text_view, buffer);
1520
1521   return GTK_WIDGET (text_view);
1522 }
1523
1524 /**
1525  * gtk_text_view_set_buffer:
1526  * @text_view: a #GtkTextView
1527  * @buffer: (allow-none): a #GtkTextBuffer
1528  *
1529  * Sets @buffer as the buffer being displayed by @text_view. The previous
1530  * buffer displayed by the text view is unreferenced, and a reference is
1531  * added to @buffer. If you owned a reference to @buffer before passing it
1532  * to this function, you must remove that reference yourself; #GtkTextView
1533  * will not "adopt" it.
1534  **/
1535 void
1536 gtk_text_view_set_buffer (GtkTextView   *text_view,
1537                           GtkTextBuffer *buffer)
1538 {
1539   GtkTextViewPrivate *priv;
1540   GtkTextBuffer *old_buffer;
1541
1542   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1543   g_return_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer));
1544
1545   priv = text_view->priv;
1546
1547   if (priv->buffer == buffer)
1548     return;
1549
1550   old_buffer = priv->buffer;
1551   if (priv->buffer != NULL)
1552     {
1553       /* Destroy all anchored children */
1554       GSList *tmp_list;
1555       GSList *copy;
1556
1557       copy = g_slist_copy (priv->children);
1558       tmp_list = copy;
1559       while (tmp_list != NULL)
1560         {
1561           GtkTextViewChild *vc = tmp_list->data;
1562
1563           if (vc->anchor)
1564             {
1565               gtk_widget_destroy (vc->widget);
1566               /* vc may now be invalid! */
1567             }
1568
1569           tmp_list = g_slist_next (tmp_list);
1570         }
1571
1572       g_slist_free (copy);
1573
1574       g_signal_handlers_disconnect_by_func (priv->buffer,
1575                                             gtk_text_view_mark_set_handler,
1576                                             text_view);
1577       g_signal_handlers_disconnect_by_func (priv->buffer,
1578                                             gtk_text_view_target_list_notify,
1579                                             text_view);
1580       g_signal_handlers_disconnect_by_func (priv->buffer,
1581                                             gtk_text_view_paste_done_handler,
1582                                             text_view);
1583       g_signal_handlers_disconnect_by_func (priv->buffer,
1584                                             gtk_text_view_buffer_changed_handler,
1585                                             text_view);
1586
1587       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1588         {
1589           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1590                                                               GDK_SELECTION_PRIMARY);
1591           gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
1592         }
1593
1594       if (priv->layout)
1595         gtk_text_layout_set_buffer (priv->layout, NULL);
1596
1597       priv->dnd_mark = NULL;
1598       priv->first_para_mark = NULL;
1599       cancel_pending_scroll (text_view);
1600     }
1601
1602   priv->buffer = buffer;
1603
1604   if (priv->layout)
1605     gtk_text_layout_set_buffer (priv->layout, buffer);
1606
1607   if (buffer != NULL)
1608     {
1609       GtkTextIter start;
1610
1611       g_object_ref (buffer);
1612
1613       gtk_text_buffer_get_iter_at_offset (priv->buffer, &start, 0);
1614
1615       priv->dnd_mark = gtk_text_buffer_create_mark (priv->buffer,
1616                                                     "gtk_drag_target",
1617                                                     &start, FALSE);
1618
1619       priv->first_para_mark = gtk_text_buffer_create_mark (priv->buffer,
1620                                                            NULL,
1621                                                            &start, TRUE);
1622
1623       priv->first_para_pixels = 0;
1624
1625
1626       g_signal_connect (priv->buffer, "mark-set",
1627                         G_CALLBACK (gtk_text_view_mark_set_handler),
1628                         text_view);
1629       g_signal_connect (priv->buffer, "notify::paste-target-list",
1630                         G_CALLBACK (gtk_text_view_target_list_notify),
1631                         text_view);
1632       g_signal_connect (priv->buffer, "paste-done",
1633                         G_CALLBACK (gtk_text_view_paste_done_handler),
1634                         text_view);
1635       g_signal_connect (priv->buffer, "changed",
1636                         G_CALLBACK (gtk_text_view_buffer_changed_handler),
1637                         text_view);
1638
1639       gtk_text_view_target_list_notify (priv->buffer, NULL, text_view);
1640
1641       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
1642         {
1643           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1644                                                               GDK_SELECTION_PRIMARY);
1645           gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
1646         }
1647
1648       gtk_text_view_update_handles (text_view, GTK_TEXT_HANDLE_MODE_NONE);
1649     }
1650
1651   _gtk_text_view_accessible_set_buffer (text_view, old_buffer);
1652   if (old_buffer)
1653     g_object_unref (old_buffer);
1654
1655   g_object_notify (G_OBJECT (text_view), "buffer");
1656   
1657   if (gtk_widget_get_visible (GTK_WIDGET (text_view)))
1658     gtk_widget_queue_draw (GTK_WIDGET (text_view));
1659
1660   DV(g_print ("Invalidating due to set_buffer\n"));
1661   gtk_text_view_invalidate (text_view);
1662 }
1663
1664 static GtkTextBuffer*
1665 get_buffer (GtkTextView *text_view)
1666 {
1667   if (text_view->priv->buffer == NULL)
1668     {
1669       GtkTextBuffer *b;
1670       b = gtk_text_buffer_new (NULL);
1671       gtk_text_view_set_buffer (text_view, b);
1672       g_object_unref (b);
1673     }
1674
1675   return text_view->priv->buffer;
1676 }
1677
1678 /**
1679  * gtk_text_view_get_buffer:
1680  * @text_view: a #GtkTextView
1681  *
1682  * Returns the #GtkTextBuffer being displayed by this text view.
1683  * The reference count on the buffer is not incremented; the caller
1684  * of this function won't own a new reference.
1685  *
1686  * Return value: (transfer none): a #GtkTextBuffer
1687  **/
1688 GtkTextBuffer*
1689 gtk_text_view_get_buffer (GtkTextView *text_view)
1690 {
1691   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
1692
1693   return get_buffer (text_view);
1694 }
1695
1696 /**
1697  * gtk_text_view_get_cursor_locations:
1698  * @text_view: a #GtkTextView
1699  * @iter: (allow-none): a #GtkTextIter
1700  * @strong: (out) (allow-none): location to store the strong
1701  *     cursor position (may be %NULL)
1702  * @weak: (out) (allow-none): location to store the weak
1703  *     cursor position (may be %NULL)
1704  *
1705  * Given an @iter within a text layout, determine the positions of the
1706  * strong and weak cursors if the insertion point is at that
1707  * iterator. The position of each cursor is stored as a zero-width
1708  * rectangle. The strong cursor location is the location where
1709  * characters of the directionality equal to the base direction of the
1710  * paragraph are inserted.  The weak cursor location is the location
1711  * where characters of the directionality opposite to the base
1712  * direction of the paragraph are inserted.
1713  *
1714  * If @iter is %NULL, the actual cursor position is used.
1715  *
1716  * Note that if @iter happens to be the actual cursor position, and
1717  * there is currently an IM preedit sequence being entered, the
1718  * returned locations will be adjusted to account for the preedit
1719  * cursor's offset within the preedit sequence.
1720  *
1721  * The rectangle position is in buffer coordinates; use
1722  * gtk_text_view_buffer_to_window_coords() to convert these
1723  * coordinates to coordinates for one of the windows in the text view.
1724  *
1725  * Since: 3.0
1726  **/
1727 void
1728 gtk_text_view_get_cursor_locations (GtkTextView       *text_view,
1729                                     const GtkTextIter *iter,
1730                                     GdkRectangle      *strong,
1731                                     GdkRectangle      *weak)
1732 {
1733   GtkTextIter insert;
1734
1735   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1736   g_return_if_fail (iter == NULL ||
1737                     gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1738
1739   gtk_text_view_ensure_layout (text_view);
1740
1741   if (iter)
1742     insert = *iter;
1743   else
1744     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
1745                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
1746
1747   gtk_text_layout_get_cursor_locations (text_view->priv->layout, &insert,
1748                                         strong, weak);
1749 }
1750
1751 /**
1752  * gtk_text_view_get_iter_at_location:
1753  * @text_view: a #GtkTextView
1754  * @iter: (out): a #GtkTextIter
1755  * @x: x position, in buffer coordinates
1756  * @y: y position, in buffer coordinates
1757  *
1758  * Retrieves the iterator at buffer coordinates @x and @y. Buffer
1759  * coordinates are coordinates for the entire buffer, not just the
1760  * currently-displayed portion.  If you have coordinates from an
1761  * event, you have to convert those to buffer coordinates with
1762  * gtk_text_view_window_to_buffer_coords().
1763  **/
1764 void
1765 gtk_text_view_get_iter_at_location (GtkTextView *text_view,
1766                                     GtkTextIter *iter,
1767                                     gint         x,
1768                                     gint         y)
1769 {
1770   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1771   g_return_if_fail (iter != NULL);
1772
1773   gtk_text_view_ensure_layout (text_view);
1774   
1775   gtk_text_layout_get_iter_at_pixel (text_view->priv->layout,
1776                                      iter, x, y);
1777 }
1778
1779 /**
1780  * gtk_text_view_get_iter_at_position:
1781  * @text_view: a #GtkTextView
1782  * @iter: (out): a #GtkTextIter
1783  * @trailing: (out) (allow-none): if non-%NULL, location to store an integer indicating where
1784  *    in the grapheme the user clicked. It will either be
1785  *    zero, or the number of characters in the grapheme. 
1786  *    0 represents the trailing edge of the grapheme.
1787  * @x: x position, in buffer coordinates
1788  * @y: y position, in buffer coordinates
1789  *
1790  * Retrieves the iterator pointing to the character at buffer 
1791  * coordinates @x and @y. Buffer coordinates are coordinates for 
1792  * the entire buffer, not just the currently-displayed portion.  
1793  * If you have coordinates from an event, you have to convert 
1794  * those to buffer coordinates with 
1795  * gtk_text_view_window_to_buffer_coords().
1796  *
1797  * Note that this is different from gtk_text_view_get_iter_at_location(),
1798  * which returns cursor locations, i.e. positions <emphasis>between</emphasis>
1799  * characters.
1800  *
1801  * Since: 2.6
1802  **/
1803 void
1804 gtk_text_view_get_iter_at_position (GtkTextView *text_view,
1805                                     GtkTextIter *iter,
1806                                     gint        *trailing,
1807                                     gint         x,
1808                                     gint         y)
1809 {
1810   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1811   g_return_if_fail (iter != NULL);
1812
1813   gtk_text_view_ensure_layout (text_view);
1814   
1815   gtk_text_layout_get_iter_at_position (text_view->priv->layout,
1816                                         iter, trailing, x, y);
1817 }
1818
1819 /**
1820  * gtk_text_view_get_iter_location:
1821  * @text_view: a #GtkTextView
1822  * @iter: a #GtkTextIter
1823  * @location: (out): bounds of the character at @iter
1824  *
1825  * Gets a rectangle which roughly contains the character at @iter.
1826  * The rectangle position is in buffer coordinates; use
1827  * gtk_text_view_buffer_to_window_coords() to convert these
1828  * coordinates to coordinates for one of the windows in the text view.
1829  **/
1830 void
1831 gtk_text_view_get_iter_location (GtkTextView       *text_view,
1832                                  const GtkTextIter *iter,
1833                                  GdkRectangle      *location)
1834 {
1835   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1836   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1837
1838   gtk_text_view_ensure_layout (text_view);
1839   
1840   gtk_text_layout_get_iter_location (text_view->priv->layout, iter, location);
1841 }
1842
1843 /**
1844  * gtk_text_view_get_line_yrange:
1845  * @text_view: a #GtkTextView
1846  * @iter: a #GtkTextIter
1847  * @y: (out): return location for a y coordinate
1848  * @height: (out): return location for a height
1849  *
1850  * Gets the y coordinate of the top of the line containing @iter,
1851  * and the height of the line. The coordinate is a buffer coordinate;
1852  * convert to window coordinates with gtk_text_view_buffer_to_window_coords().
1853  **/
1854 void
1855 gtk_text_view_get_line_yrange (GtkTextView       *text_view,
1856                                const GtkTextIter *iter,
1857                                gint              *y,
1858                                gint              *height)
1859 {
1860   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1861   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1862
1863   gtk_text_view_ensure_layout (text_view);
1864   
1865   gtk_text_layout_get_line_yrange (text_view->priv->layout,
1866                                    iter,
1867                                    y,
1868                                    height);
1869 }
1870
1871 /**
1872  * gtk_text_view_get_line_at_y:
1873  * @text_view: a #GtkTextView
1874  * @target_iter: (out): a #GtkTextIter
1875  * @y: a y coordinate
1876  * @line_top: (out): return location for top coordinate of the line
1877  *
1878  * Gets the #GtkTextIter at the start of the line containing
1879  * the coordinate @y. @y is in buffer coordinates, convert from
1880  * window coordinates with gtk_text_view_window_to_buffer_coords().
1881  * If non-%NULL, @line_top will be filled with the coordinate of the top
1882  * edge of the line.
1883  **/
1884 void
1885 gtk_text_view_get_line_at_y (GtkTextView *text_view,
1886                              GtkTextIter *target_iter,
1887                              gint         y,
1888                              gint        *line_top)
1889 {
1890   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1891
1892   gtk_text_view_ensure_layout (text_view);
1893   
1894   gtk_text_layout_get_line_at_y (text_view->priv->layout,
1895                                  target_iter,
1896                                  y,
1897                                  line_top);
1898 }
1899
1900 /**
1901  * gtk_text_view_scroll_to_iter:
1902  * @text_view: a #GtkTextView
1903  * @iter: a #GtkTextIter
1904  * @within_margin: margin as a [0.0,0.5) fraction of screen size
1905  * @use_align: whether to use alignment arguments (if %FALSE, 
1906  *    just get the mark onscreen)
1907  * @xalign: horizontal alignment of mark within visible area
1908  * @yalign: vertical alignment of mark within visible area
1909  *
1910  * Scrolls @text_view so that @iter is on the screen in the position
1911  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
1912  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
1913  * If @use_align is %FALSE, the text scrolls the minimal distance to 
1914  * get the mark onscreen, possibly not scrolling at all. The effective 
1915  * screen for purposes of this function is reduced by a margin of size 
1916  * @within_margin.
1917  *
1918  * Note that this function uses the currently-computed height of the
1919  * lines in the text buffer. Line heights are computed in an idle 
1920  * handler; so this function may not have the desired effect if it's 
1921  * called before the height computations. To avoid oddness, consider 
1922  * using gtk_text_view_scroll_to_mark() which saves a point to be 
1923  * scrolled to after line validation.
1924  *
1925  * Return value: %TRUE if scrolling occurred
1926  **/
1927 gboolean
1928 gtk_text_view_scroll_to_iter (GtkTextView   *text_view,
1929                               GtkTextIter   *iter,
1930                               gdouble        within_margin,
1931                               gboolean       use_align,
1932                               gdouble        xalign,
1933                               gdouble        yalign)
1934 {
1935   GdkRectangle rect;
1936   GdkRectangle screen;
1937   gint screen_bottom;
1938   gint screen_right;
1939   gint scroll_dest;
1940   GtkWidget *widget;
1941   gboolean retval = FALSE;
1942   gint scroll_inc;
1943   gint screen_xoffset, screen_yoffset;
1944   gint current_x_scroll, current_y_scroll;
1945
1946   /* FIXME why don't we do the validate-at-scroll-destination thing
1947    * from flush_scroll in this function? I think it wasn't done before
1948    * because changed_handler was screwed up, but I could be wrong.
1949    */
1950   
1951   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1952   g_return_val_if_fail (iter != NULL, FALSE);
1953   g_return_val_if_fail (within_margin >= 0.0 && within_margin < 0.5, FALSE);
1954   g_return_val_if_fail (xalign >= 0.0 && xalign <= 1.0, FALSE);
1955   g_return_val_if_fail (yalign >= 0.0 && yalign <= 1.0, FALSE);
1956   
1957   widget = GTK_WIDGET (text_view);
1958
1959   DV(g_print(G_STRLOC"\n"));
1960   
1961   gtk_text_layout_get_iter_location (text_view->priv->layout,
1962                                      iter,
1963                                      &rect);
1964
1965   DV (g_print (" target rect %d,%d  %d x %d\n", rect.x, rect.y, rect.width, rect.height));
1966   
1967   current_x_scroll = text_view->priv->xoffset;
1968   current_y_scroll = text_view->priv->yoffset;
1969
1970   screen.x = current_x_scroll;
1971   screen.y = current_y_scroll;
1972   screen.width = SCREEN_WIDTH (widget);
1973   screen.height = SCREEN_HEIGHT (widget);
1974   
1975   screen_xoffset = screen.width * within_margin;
1976   screen_yoffset = screen.height * within_margin;
1977   
1978   screen.x += screen_xoffset;
1979   screen.y += screen_yoffset;
1980   screen.width -= screen_xoffset * 2;
1981   screen.height -= screen_yoffset * 2;
1982
1983   /* paranoia check */
1984   if (screen.width < 1)
1985     screen.width = 1;
1986   if (screen.height < 1)
1987     screen.height = 1;
1988   
1989   /* The -1 here ensures that we leave enough space to draw the cursor
1990    * when this function is used for horizontal scrolling. 
1991    */
1992   screen_right = screen.x + screen.width - 1;
1993   screen_bottom = screen.y + screen.height;
1994   
1995   /* The alignment affects the point in the target character that we
1996    * choose to align. If we're doing right/bottom alignment, we align
1997    * the right/bottom edge of the character the mark is at; if we're
1998    * doing left/top we align the left/top edge of the character; if
1999    * we're doing center alignment we align the center of the
2000    * character.
2001    */
2002   
2003   /* Vertical scroll */
2004
2005   scroll_inc = 0;
2006   scroll_dest = current_y_scroll;
2007   
2008   if (use_align)
2009     {      
2010       scroll_dest = rect.y + (rect.height * yalign) - (screen.height * yalign);
2011       
2012       /* if scroll_dest < screen.y, we move a negative increment (up),
2013        * else a positive increment (down)
2014        */
2015       scroll_inc = scroll_dest - screen.y + screen_yoffset;
2016     }
2017   else
2018     {
2019       /* move minimum to get onscreen */
2020       if (rect.y < screen.y)
2021         {
2022           scroll_dest = rect.y;
2023           scroll_inc = scroll_dest - screen.y - screen_yoffset;
2024         }
2025       else if ((rect.y + rect.height) > screen_bottom)
2026         {
2027           scroll_dest = rect.y + rect.height;
2028           scroll_inc = scroll_dest - screen_bottom + screen_yoffset;
2029         }
2030     }  
2031   
2032   if (scroll_inc != 0)
2033     {
2034       gtk_adjustment_set_value (text_view->priv->vadjustment,
2035                                 current_y_scroll + scroll_inc);
2036
2037       DV (g_print (" vert increment %d\n", scroll_inc));
2038     }
2039
2040   /* Horizontal scroll */
2041   
2042   scroll_inc = 0;
2043   scroll_dest = current_x_scroll;
2044   
2045   if (use_align)
2046     {      
2047       scroll_dest = rect.x + (rect.width * xalign) - (screen.width * xalign);
2048
2049       /* if scroll_dest < screen.y, we move a negative increment (left),
2050        * else a positive increment (right)
2051        */
2052       scroll_inc = scroll_dest - screen.x + screen_xoffset;
2053     }
2054   else
2055     {
2056       /* move minimum to get onscreen */
2057       if (rect.x < screen.x)
2058         {
2059           scroll_dest = rect.x;
2060           scroll_inc = scroll_dest - screen.x - screen_xoffset;
2061         }
2062       else if ((rect.x + rect.width) > screen_right)
2063         {
2064           scroll_dest = rect.x + rect.width;
2065           scroll_inc = scroll_dest - screen_right + screen_xoffset;
2066         }
2067     }
2068   
2069   if (scroll_inc != 0)
2070     {
2071       gtk_adjustment_set_value (text_view->priv->hadjustment,
2072                                 current_x_scroll + scroll_inc);
2073
2074       DV (g_print (" horiz increment %d\n", scroll_inc));
2075     }
2076   
2077   retval = (current_y_scroll != gtk_adjustment_get_value (text_view->priv->vadjustment))
2078            || (current_x_scroll != gtk_adjustment_get_value (text_view->priv->hadjustment));
2079
2080   if (retval)
2081     {
2082       DV(g_print (">Actually scrolled ("G_STRLOC")\n"));
2083     }
2084   else
2085     {
2086       DV(g_print (">Didn't end up scrolling ("G_STRLOC")\n"));
2087     }
2088   
2089   return retval;
2090 }
2091
2092 static void
2093 free_pending_scroll (GtkTextPendingScroll *scroll)
2094 {
2095   if (!gtk_text_mark_get_deleted (scroll->mark))
2096     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (scroll->mark),
2097                                  scroll->mark);
2098   g_object_unref (scroll->mark);
2099   g_free (scroll);
2100 }
2101
2102 static void
2103 cancel_pending_scroll (GtkTextView *text_view)
2104 {
2105   if (text_view->priv->pending_scroll)
2106     {
2107       free_pending_scroll (text_view->priv->pending_scroll);
2108       text_view->priv->pending_scroll = NULL;
2109     }
2110 }
2111
2112 static void
2113 gtk_text_view_queue_scroll (GtkTextView   *text_view,
2114                             GtkTextMark   *mark,
2115                             gdouble        within_margin,
2116                             gboolean       use_align,
2117                             gdouble        xalign,
2118                             gdouble        yalign)
2119 {
2120   GtkTextIter iter;
2121   GtkTextPendingScroll *scroll;
2122
2123   DV(g_print(G_STRLOC"\n"));
2124   
2125   scroll = g_new (GtkTextPendingScroll, 1);
2126
2127   scroll->within_margin = within_margin;
2128   scroll->use_align = use_align;
2129   scroll->xalign = xalign;
2130   scroll->yalign = yalign;
2131   
2132   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2133
2134   scroll->mark = gtk_text_buffer_create_mark (get_buffer (text_view),
2135                                               NULL,
2136                                               &iter,
2137                                               gtk_text_mark_get_left_gravity (mark));
2138
2139   g_object_ref (scroll->mark);
2140   
2141   cancel_pending_scroll (text_view);
2142
2143   text_view->priv->pending_scroll = scroll;
2144 }
2145
2146 static gboolean
2147 gtk_text_view_flush_scroll (GtkTextView *text_view)
2148 {
2149   GtkAllocation allocation;
2150   GtkTextIter iter;
2151   GtkTextPendingScroll *scroll;
2152   gboolean retval;
2153   GtkWidget *widget;
2154
2155   widget = GTK_WIDGET (text_view);
2156   
2157   DV(g_print(G_STRLOC"\n"));
2158   
2159   if (text_view->priv->pending_scroll == NULL)
2160     {
2161       DV (g_print ("in flush scroll, no pending scroll\n"));
2162       return FALSE;
2163     }
2164
2165   scroll = text_view->priv->pending_scroll;
2166
2167   /* avoid recursion */
2168   text_view->priv->pending_scroll = NULL;
2169   
2170   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, scroll->mark);
2171
2172   /* Validate area around the scroll destination, so the adjustment
2173    * can meaningfully point into that area. We must validate
2174    * enough area to be sure that after we scroll, everything onscreen
2175    * is valid; otherwise, validation will maintain the first para
2176    * in one place, but may push the target iter off the bottom of
2177    * the screen.
2178    */
2179   DV(g_print (">Validating scroll destination ("G_STRLOC")\n"));
2180   gtk_widget_get_allocation (widget, &allocation);
2181   gtk_text_layout_validate_yrange (text_view->priv->layout, &iter,
2182                                    -(allocation.height * 2),
2183                                    allocation.height * 2);
2184
2185   DV(g_print (">Done validating scroll destination ("G_STRLOC")\n"));
2186
2187   /* Ensure we have updated width/height */
2188   gtk_text_view_update_adjustments (text_view);
2189   
2190   retval = gtk_text_view_scroll_to_iter (text_view,
2191                                          &iter,
2192                                          scroll->within_margin,
2193                                          scroll->use_align,
2194                                          scroll->xalign,
2195                                          scroll->yalign);
2196
2197   free_pending_scroll (scroll);
2198
2199   return retval;
2200 }
2201
2202 static void
2203 gtk_text_view_update_adjustments (GtkTextView *text_view)
2204 {
2205   GtkTextViewPrivate *priv;
2206   gint width = 0, height = 0;
2207
2208   DV(g_print(">Updating adjustments ("G_STRLOC")\n"));
2209
2210   priv = text_view->priv;
2211
2212   if (priv->layout)
2213     gtk_text_layout_get_size (priv->layout, &width, &height);
2214
2215   /* Make room for the cursor after the last character in the widest line */
2216   width += SPACE_FOR_CURSOR;
2217
2218   if (priv->width != width || priv->height != height)
2219     {
2220       if (priv->width != width)
2221         priv->width_changed = TRUE;
2222
2223       priv->width = width;
2224       priv->height = height;
2225
2226       gtk_text_view_set_hadjustment_values (text_view);
2227       gtk_text_view_set_vadjustment_values (text_view);
2228     }
2229 }
2230
2231 static void
2232 gtk_text_view_update_layout_width (GtkTextView *text_view)
2233 {
2234   DV(g_print(">Updating layout width ("G_STRLOC")\n"));
2235   
2236   gtk_text_view_ensure_layout (text_view);
2237
2238   gtk_text_layout_set_screen_width (text_view->priv->layout,
2239                                     MAX (1, SCREEN_WIDTH (text_view) - SPACE_FOR_CURSOR));
2240 }
2241
2242 static void
2243 gtk_text_view_update_im_spot_location (GtkTextView *text_view)
2244 {
2245   GdkRectangle area;
2246
2247   if (text_view->priv->layout == NULL)
2248     return;
2249   
2250   gtk_text_view_get_cursor_locations (text_view, NULL, &area, NULL);
2251
2252   area.x -= text_view->priv->xoffset;
2253   area.y -= text_view->priv->yoffset;
2254     
2255   /* Width returned by Pango indicates direction of cursor,
2256    * by its sign more than the size of cursor.
2257    */
2258   area.width = 0;
2259
2260   gtk_im_context_set_cursor_location (text_view->priv->im_context, &area);
2261 }
2262
2263 static gboolean
2264 do_update_im_spot_location (gpointer text_view)
2265 {
2266   GtkTextViewPrivate *priv;
2267
2268   priv = GTK_TEXT_VIEW (text_view)->priv;
2269   priv->im_spot_idle = 0;
2270
2271   gtk_text_view_update_im_spot_location (text_view);
2272   return FALSE;
2273 }
2274
2275 static void
2276 queue_update_im_spot_location (GtkTextView *text_view)
2277 {
2278   GtkTextViewPrivate *priv;
2279
2280   priv = text_view->priv;
2281
2282   /* Use priority a little higher than GTK_TEXT_VIEW_PRIORITY_VALIDATE,
2283    * so we don't wait until the entire buffer has been validated. */
2284   if (!priv->im_spot_idle)
2285     priv->im_spot_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE - 1,
2286                                                     do_update_im_spot_location,
2287                                                     text_view,
2288                                                     NULL);
2289 }
2290
2291 static void
2292 flush_update_im_spot_location (GtkTextView *text_view)
2293 {
2294   GtkTextViewPrivate *priv;
2295
2296   priv = text_view->priv;
2297
2298   if (priv->im_spot_idle)
2299     {
2300       g_source_remove (priv->im_spot_idle);
2301       priv->im_spot_idle = 0;
2302       gtk_text_view_update_im_spot_location (text_view);
2303     }
2304 }
2305
2306 /**
2307  * gtk_text_view_scroll_to_mark:
2308  * @text_view: a #GtkTextView
2309  * @mark: a #GtkTextMark
2310  * @within_margin: margin as a [0.0,0.5) fraction of screen size
2311  * @use_align: whether to use alignment arguments (if %FALSE, just 
2312  *    get the mark onscreen)
2313  * @xalign: horizontal alignment of mark within visible area
2314  * @yalign: vertical alignment of mark within visible area
2315  *
2316  * Scrolls @text_view so that @mark is on the screen in the position
2317  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
2318  * left or top, 1.0 indicates right or bottom, 0.5 means center. 
2319  * If @use_align is %FALSE, the text scrolls the minimal distance to 
2320  * get the mark onscreen, possibly not scrolling at all. The effective 
2321  * screen for purposes of this function is reduced by a margin of size 
2322  * @within_margin.
2323  **/
2324 void
2325 gtk_text_view_scroll_to_mark (GtkTextView *text_view,
2326                               GtkTextMark *mark,
2327                               gdouble      within_margin,
2328                               gboolean     use_align,
2329                               gdouble      xalign,
2330                               gdouble      yalign)
2331 {  
2332   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2333   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2334   g_return_if_fail (within_margin >= 0.0 && within_margin < 0.5);
2335   g_return_if_fail (xalign >= 0.0 && xalign <= 1.0);
2336   g_return_if_fail (yalign >= 0.0 && yalign <= 1.0);
2337
2338   /* We need to verify that the buffer contains the mark, otherwise this
2339    * can lead to data structure corruption later on.
2340    */
2341   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2342
2343   gtk_text_view_queue_scroll (text_view, mark,
2344                               within_margin,
2345                               use_align,
2346                               xalign,
2347                               yalign);
2348
2349   /* If no validation is pending, we need to go ahead and force an
2350    * immediate scroll.
2351    */
2352   if (text_view->priv->layout &&
2353       gtk_text_layout_is_valid (text_view->priv->layout))
2354     gtk_text_view_flush_scroll (text_view);
2355 }
2356
2357 /**
2358  * gtk_text_view_scroll_mark_onscreen:
2359  * @text_view: a #GtkTextView
2360  * @mark: a mark in the buffer for @text_view
2361  * 
2362  * Scrolls @text_view the minimum distance such that @mark is contained
2363  * within the visible area of the widget.
2364  **/
2365 void
2366 gtk_text_view_scroll_mark_onscreen (GtkTextView *text_view,
2367                                     GtkTextMark *mark)
2368 {
2369   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2370   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
2371
2372   /* We need to verify that the buffer contains the mark, otherwise this
2373    * can lead to data structure corruption later on.
2374    */
2375   g_return_if_fail (get_buffer (text_view) == gtk_text_mark_get_buffer (mark));
2376
2377   gtk_text_view_scroll_to_mark (text_view, mark, 0.0, FALSE, 0.0, 0.0);
2378 }
2379
2380 static gboolean
2381 clamp_iter_onscreen (GtkTextView *text_view, GtkTextIter *iter)
2382 {
2383   GdkRectangle visible_rect;
2384   gtk_text_view_get_visible_rect (text_view, &visible_rect);
2385
2386   return gtk_text_layout_clamp_iter_to_vrange (text_view->priv->layout, iter,
2387                                                visible_rect.y,
2388                                                visible_rect.y + visible_rect.height);
2389 }
2390
2391 /**
2392  * gtk_text_view_move_mark_onscreen:
2393  * @text_view: a #GtkTextView
2394  * @mark: a #GtkTextMark
2395  *
2396  * Moves a mark within the buffer so that it's
2397  * located within the currently-visible text area.
2398  *
2399  * Return value: %TRUE if the mark moved (wasn't already onscreen)
2400  **/
2401 gboolean
2402 gtk_text_view_move_mark_onscreen (GtkTextView *text_view,
2403                                   GtkTextMark *mark)
2404 {
2405   GtkTextIter iter;
2406
2407   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2408   g_return_val_if_fail (mark != NULL, FALSE);
2409
2410   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
2411
2412   if (clamp_iter_onscreen (text_view, &iter))
2413     {
2414       gtk_text_buffer_move_mark (get_buffer (text_view), mark, &iter);
2415       return TRUE;
2416     }
2417   else
2418     return FALSE;
2419 }
2420
2421 /**
2422  * gtk_text_view_get_visible_rect:
2423  * @text_view: a #GtkTextView
2424  * @visible_rect: (out): rectangle to fill
2425  *
2426  * Fills @visible_rect with the currently-visible
2427  * region of the buffer, in buffer coordinates. Convert to window coordinates
2428  * with gtk_text_view_buffer_to_window_coords().
2429  **/
2430 void
2431 gtk_text_view_get_visible_rect (GtkTextView  *text_view,
2432                                 GdkRectangle *visible_rect)
2433 {
2434   GtkWidget *widget;
2435
2436   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2437
2438   widget = GTK_WIDGET (text_view);
2439
2440   if (visible_rect)
2441     {
2442       visible_rect->x = text_view->priv->xoffset;
2443       visible_rect->y = text_view->priv->yoffset;
2444       visible_rect->width = SCREEN_WIDTH (widget);
2445       visible_rect->height = SCREEN_HEIGHT (widget);
2446
2447       DV(g_print(" visible rect: %d,%d %d x %d\n",
2448                  visible_rect->x,
2449                  visible_rect->y,
2450                  visible_rect->width,
2451                  visible_rect->height));
2452     }
2453 }
2454
2455 /**
2456  * gtk_text_view_set_wrap_mode:
2457  * @text_view: a #GtkTextView
2458  * @wrap_mode: a #GtkWrapMode
2459  *
2460  * Sets the line wrapping for the view.
2461  **/
2462 void
2463 gtk_text_view_set_wrap_mode (GtkTextView *text_view,
2464                              GtkWrapMode  wrap_mode)
2465 {
2466   GtkTextViewPrivate *priv;
2467
2468   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2469
2470   priv = text_view->priv;
2471
2472   if (priv->wrap_mode != wrap_mode)
2473     {
2474       priv->wrap_mode = wrap_mode;
2475
2476       if (priv->layout && priv->layout->default_style)
2477         {
2478           priv->layout->default_style->wrap_mode = wrap_mode;
2479           gtk_text_layout_default_style_changed (priv->layout);
2480         }
2481     }
2482
2483   g_object_notify (G_OBJECT (text_view), "wrap-mode");
2484 }
2485
2486 /**
2487  * gtk_text_view_get_wrap_mode:
2488  * @text_view: a #GtkTextView
2489  *
2490  * Gets the line wrapping for the view.
2491  *
2492  * Return value: the line wrap setting
2493  **/
2494 GtkWrapMode
2495 gtk_text_view_get_wrap_mode (GtkTextView *text_view)
2496 {
2497   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_WRAP_NONE);
2498
2499   return text_view->priv->wrap_mode;
2500 }
2501
2502 /**
2503  * gtk_text_view_set_editable:
2504  * @text_view: a #GtkTextView
2505  * @setting: whether it's editable
2506  *
2507  * Sets the default editability of the #GtkTextView. You can override
2508  * this default setting with tags in the buffer, using the "editable"
2509  * attribute of tags.
2510  **/
2511 void
2512 gtk_text_view_set_editable (GtkTextView *text_view,
2513                             gboolean     setting)
2514 {
2515   GtkTextViewPrivate *priv;
2516
2517   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2518
2519   priv = text_view->priv;
2520   setting = setting != FALSE;
2521
2522   if (priv->editable != setting)
2523     {
2524       if (!setting)
2525         {
2526           gtk_text_view_reset_im_context(text_view);
2527           if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2528             gtk_im_context_focus_out (priv->im_context);
2529         }
2530
2531       priv->editable = setting;
2532
2533       if (setting && gtk_widget_has_focus (GTK_WIDGET (text_view)))
2534         gtk_im_context_focus_in (priv->im_context);
2535
2536       if (priv->layout && priv->layout->default_style)
2537         {
2538           gtk_text_layout_set_overwrite_mode (priv->layout,
2539                                               priv->overwrite_mode && priv->editable);
2540           priv->layout->default_style->editable = priv->editable;
2541           gtk_text_layout_default_style_changed (priv->layout);
2542         }
2543
2544       g_object_notify (G_OBJECT (text_view), "editable");
2545     }
2546 }
2547
2548 /**
2549  * gtk_text_view_get_editable:
2550  * @text_view: a #GtkTextView
2551  *
2552  * Returns the default editability of the #GtkTextView. Tags in the
2553  * buffer may override this setting for some ranges of text.
2554  *
2555  * Return value: whether text is editable by default
2556  **/
2557 gboolean
2558 gtk_text_view_get_editable (GtkTextView *text_view)
2559 {
2560   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2561
2562   return text_view->priv->editable;
2563 }
2564
2565 /**
2566  * gtk_text_view_set_pixels_above_lines:
2567  * @text_view: a #GtkTextView
2568  * @pixels_above_lines: pixels above paragraphs
2569  * 
2570  * Sets the default number of blank pixels above paragraphs in @text_view.
2571  * Tags in the buffer for @text_view may override the defaults.
2572  **/
2573 void
2574 gtk_text_view_set_pixels_above_lines (GtkTextView *text_view,
2575                                       gint         pixels_above_lines)
2576 {
2577   GtkTextViewPrivate *priv;
2578
2579   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2580
2581   priv = text_view->priv;
2582
2583   if (priv->pixels_above_lines != pixels_above_lines)
2584     {
2585       priv->pixels_above_lines = pixels_above_lines;
2586
2587       if (priv->layout && priv->layout->default_style)
2588         {
2589           priv->layout->default_style->pixels_above_lines = pixels_above_lines;
2590           gtk_text_layout_default_style_changed (priv->layout);
2591         }
2592
2593       g_object_notify (G_OBJECT (text_view), "pixels-above-lines");
2594     }
2595 }
2596
2597 /**
2598  * gtk_text_view_get_pixels_above_lines:
2599  * @text_view: a #GtkTextView
2600  * 
2601  * Gets the default number of pixels to put above paragraphs.
2602  * 
2603  * Return value: default number of pixels above paragraphs
2604  **/
2605 gint
2606 gtk_text_view_get_pixels_above_lines (GtkTextView *text_view)
2607 {
2608   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2609
2610   return text_view->priv->pixels_above_lines;
2611 }
2612
2613 /**
2614  * gtk_text_view_set_pixels_below_lines:
2615  * @text_view: a #GtkTextView
2616  * @pixels_below_lines: pixels below paragraphs 
2617  *
2618  * Sets the default number of pixels of blank space
2619  * to put below paragraphs in @text_view. May be overridden
2620  * by tags applied to @text_view's buffer. 
2621  **/
2622 void
2623 gtk_text_view_set_pixels_below_lines (GtkTextView *text_view,
2624                                       gint         pixels_below_lines)
2625 {
2626   GtkTextViewPrivate *priv;
2627
2628   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2629
2630   priv = text_view->priv;
2631
2632   if (priv->pixels_below_lines != pixels_below_lines)
2633     {
2634       priv->pixels_below_lines = pixels_below_lines;
2635
2636       if (priv->layout && priv->layout->default_style)
2637         {
2638           priv->layout->default_style->pixels_below_lines = pixels_below_lines;
2639           gtk_text_layout_default_style_changed (priv->layout);
2640         }
2641
2642       g_object_notify (G_OBJECT (text_view), "pixels-below-lines");
2643     }
2644 }
2645
2646 /**
2647  * gtk_text_view_get_pixels_below_lines:
2648  * @text_view: a #GtkTextView
2649  * 
2650  * Gets the value set by gtk_text_view_set_pixels_below_lines().
2651  * 
2652  * Return value: default number of blank pixels below paragraphs
2653  **/
2654 gint
2655 gtk_text_view_get_pixels_below_lines (GtkTextView *text_view)
2656 {
2657   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2658
2659   return text_view->priv->pixels_below_lines;
2660 }
2661
2662 /**
2663  * gtk_text_view_set_pixels_inside_wrap:
2664  * @text_view: a #GtkTextView
2665  * @pixels_inside_wrap: default number of pixels between wrapped lines
2666  *
2667  * Sets the default number of pixels of blank space to leave between
2668  * display/wrapped lines within a paragraph. May be overridden by
2669  * tags in @text_view's buffer.
2670  **/
2671 void
2672 gtk_text_view_set_pixels_inside_wrap (GtkTextView *text_view,
2673                                       gint         pixels_inside_wrap)
2674 {
2675   GtkTextViewPrivate *priv;
2676
2677   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2678
2679   priv = text_view->priv;
2680
2681   if (priv->pixels_inside_wrap != pixels_inside_wrap)
2682     {
2683       priv->pixels_inside_wrap = pixels_inside_wrap;
2684
2685       if (priv->layout && priv->layout->default_style)
2686         {
2687           priv->layout->default_style->pixels_inside_wrap = pixels_inside_wrap;
2688           gtk_text_layout_default_style_changed (priv->layout);
2689         }
2690
2691       g_object_notify (G_OBJECT (text_view), "pixels-inside-wrap");
2692     }
2693 }
2694
2695 /**
2696  * gtk_text_view_get_pixels_inside_wrap:
2697  * @text_view: a #GtkTextView
2698  * 
2699  * Gets the value set by gtk_text_view_set_pixels_inside_wrap().
2700  * 
2701  * Return value: default number of pixels of blank space between wrapped lines
2702  **/
2703 gint
2704 gtk_text_view_get_pixels_inside_wrap (GtkTextView *text_view)
2705 {
2706   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2707
2708   return text_view->priv->pixels_inside_wrap;
2709 }
2710
2711 /**
2712  * gtk_text_view_set_justification:
2713  * @text_view: a #GtkTextView
2714  * @justification: justification
2715  *
2716  * Sets the default justification of text in @text_view.
2717  * Tags in the view's buffer may override the default.
2718  * 
2719  **/
2720 void
2721 gtk_text_view_set_justification (GtkTextView     *text_view,
2722                                  GtkJustification justification)
2723 {
2724   GtkTextViewPrivate *priv;
2725
2726   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2727
2728   priv = text_view->priv;
2729
2730   if (priv->justify != justification)
2731     {
2732       priv->justify = justification;
2733
2734       if (priv->layout && priv->layout->default_style)
2735         {
2736           priv->layout->default_style->justification = justification;
2737           gtk_text_layout_default_style_changed (priv->layout);
2738         }
2739
2740       g_object_notify (G_OBJECT (text_view), "justification");
2741     }
2742 }
2743
2744 /**
2745  * gtk_text_view_get_justification:
2746  * @text_view: a #GtkTextView
2747  * 
2748  * Gets the default justification of paragraphs in @text_view.
2749  * Tags in the buffer may override the default.
2750  * 
2751  * Return value: default justification
2752  **/
2753 GtkJustification
2754 gtk_text_view_get_justification (GtkTextView *text_view)
2755 {
2756   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_JUSTIFY_LEFT);
2757
2758   return text_view->priv->justify;
2759 }
2760
2761 /**
2762  * gtk_text_view_set_left_margin:
2763  * @text_view: a #GtkTextView
2764  * @left_margin: left margin in pixels
2765  * 
2766  * Sets the default left margin for text in @text_view.
2767  * Tags in the buffer may override the default.
2768  **/
2769 void
2770 gtk_text_view_set_left_margin (GtkTextView *text_view,
2771                                gint         left_margin)
2772 {
2773   GtkTextViewPrivate *priv;
2774
2775   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2776
2777   priv = text_view->priv;
2778
2779   if (priv->left_margin != left_margin)
2780     {
2781       priv->left_margin = left_margin;
2782
2783       if (priv->layout && priv->layout->default_style)
2784         {
2785           priv->layout->default_style->left_margin = left_margin;
2786           gtk_text_layout_default_style_changed (priv->layout);
2787         }
2788
2789       g_object_notify (G_OBJECT (text_view), "left-margin");
2790     }
2791 }
2792
2793 /**
2794  * gtk_text_view_get_left_margin:
2795  * @text_view: a #GtkTextView
2796  * 
2797  * Gets the default left margin size of paragraphs in the @text_view.
2798  * Tags in the buffer may override the default.
2799  * 
2800  * Return value: left margin in pixels
2801  **/
2802 gint
2803 gtk_text_view_get_left_margin (GtkTextView *text_view)
2804 {
2805   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2806
2807   return text_view->priv->left_margin;
2808 }
2809
2810 /**
2811  * gtk_text_view_set_right_margin:
2812  * @text_view: a #GtkTextView
2813  * @right_margin: right margin in pixels
2814  *
2815  * Sets the default right margin for text in the text view.
2816  * Tags in the buffer may override the default.
2817  **/
2818 void
2819 gtk_text_view_set_right_margin (GtkTextView *text_view,
2820                                 gint         right_margin)
2821 {
2822   GtkTextViewPrivate *priv = text_view->priv;
2823
2824   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2825
2826   if (priv->right_margin != right_margin)
2827     {
2828       priv->right_margin = right_margin;
2829
2830       if (priv->layout && priv->layout->default_style)
2831         {
2832           priv->layout->default_style->right_margin = right_margin;
2833           gtk_text_layout_default_style_changed (priv->layout);
2834         }
2835
2836       g_object_notify (G_OBJECT (text_view), "right-margin");
2837     }
2838 }
2839
2840 /**
2841  * gtk_text_view_get_right_margin:
2842  * @text_view: a #GtkTextView
2843  * 
2844  * Gets the default right margin for text in @text_view. Tags
2845  * in the buffer may override the default.
2846  * 
2847  * Return value: right margin in pixels
2848  **/
2849 gint
2850 gtk_text_view_get_right_margin (GtkTextView *text_view)
2851 {
2852   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2853
2854   return text_view->priv->right_margin;
2855 }
2856
2857 /**
2858  * gtk_text_view_set_indent:
2859  * @text_view: a #GtkTextView
2860  * @indent: indentation in pixels
2861  *
2862  * Sets the default indentation for paragraphs in @text_view.
2863  * Tags in the buffer may override the default.
2864  **/
2865 void
2866 gtk_text_view_set_indent (GtkTextView *text_view,
2867                           gint         indent)
2868 {
2869   GtkTextViewPrivate *priv;
2870
2871   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2872
2873   priv = text_view->priv;
2874
2875   if (priv->indent != indent)
2876     {
2877       priv->indent = indent;
2878
2879       if (priv->layout && priv->layout->default_style)
2880         {
2881           priv->layout->default_style->indent = indent;
2882           gtk_text_layout_default_style_changed (priv->layout);
2883         }
2884
2885       g_object_notify (G_OBJECT (text_view), "indent");
2886     }
2887 }
2888
2889 /**
2890  * gtk_text_view_get_indent:
2891  * @text_view: a #GtkTextView
2892  * 
2893  * Gets the default indentation of paragraphs in @text_view.
2894  * Tags in the view's buffer may override the default.
2895  * The indentation may be negative.
2896  * 
2897  * Return value: number of pixels of indentation
2898  **/
2899 gint
2900 gtk_text_view_get_indent (GtkTextView *text_view)
2901 {
2902   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2903
2904   return text_view->priv->indent;
2905 }
2906
2907 /**
2908  * gtk_text_view_set_tabs:
2909  * @text_view: a #GtkTextView
2910  * @tabs: tabs as a #PangoTabArray
2911  *
2912  * Sets the default tab stops for paragraphs in @text_view.
2913  * Tags in the buffer may override the default.
2914  **/
2915 void
2916 gtk_text_view_set_tabs (GtkTextView   *text_view,
2917                         PangoTabArray *tabs)
2918 {
2919   GtkTextViewPrivate *priv;
2920
2921   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2922
2923   priv = text_view->priv;
2924
2925   if (priv->tabs)
2926     pango_tab_array_free (priv->tabs);
2927
2928   priv->tabs = tabs ? pango_tab_array_copy (tabs) : NULL;
2929
2930   if (priv->layout && priv->layout->default_style)
2931     {
2932       /* some unkosher futzing in internal struct details... */
2933       if (priv->layout->default_style->tabs)
2934         pango_tab_array_free (priv->layout->default_style->tabs);
2935
2936       priv->layout->default_style->tabs =
2937         priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
2938
2939       gtk_text_layout_default_style_changed (priv->layout);
2940     }
2941
2942   g_object_notify (G_OBJECT (text_view), "tabs");
2943 }
2944
2945 /**
2946  * gtk_text_view_get_tabs:
2947  * @text_view: a #GtkTextView
2948  * 
2949  * Gets the default tabs for @text_view. Tags in the buffer may
2950  * override the defaults. The returned array will be %NULL if
2951  * "standard" (8-space) tabs are used. Free the return value
2952  * with pango_tab_array_free().
2953  * 
2954  * Return value: copy of default tab array, or %NULL if "standard" 
2955  *    tabs are used; must be freed with pango_tab_array_free().
2956  **/
2957 PangoTabArray*
2958 gtk_text_view_get_tabs (GtkTextView *text_view)
2959 {
2960   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
2961
2962   return text_view->priv->tabs ? pango_tab_array_copy (text_view->priv->tabs) : NULL;
2963 }
2964
2965 static void
2966 gtk_text_view_toggle_cursor_visible (GtkTextView *text_view)
2967 {
2968   gtk_text_view_set_cursor_visible (text_view, !text_view->priv->cursor_visible);
2969 }
2970
2971 /**
2972  * gtk_text_view_set_cursor_visible:
2973  * @text_view: a #GtkTextView
2974  * @setting: whether to show the insertion cursor
2975  *
2976  * Toggles whether the insertion point is displayed. A buffer with no editable
2977  * text probably shouldn't have a visible cursor, so you may want to turn
2978  * the cursor off.
2979  **/
2980 void
2981 gtk_text_view_set_cursor_visible (GtkTextView *text_view,
2982                                   gboolean     setting)
2983 {
2984   GtkTextViewPrivate *priv;
2985
2986   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2987
2988   priv = text_view->priv;
2989   setting = (setting != FALSE);
2990
2991   if (priv->cursor_visible != setting)
2992     {
2993       priv->cursor_visible = setting;
2994
2995       if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
2996         {
2997           if (priv->layout)
2998             {
2999               gtk_text_layout_set_cursor_visible (priv->layout, setting);
3000               gtk_text_view_check_cursor_blink (text_view);
3001             }
3002         }
3003
3004       g_object_notify (G_OBJECT (text_view), "cursor-visible");
3005     }
3006 }
3007
3008 /**
3009  * gtk_text_view_get_cursor_visible:
3010  * @text_view: a #GtkTextView
3011  *
3012  * Find out whether the cursor is being displayed.
3013  *
3014  * Return value: whether the insertion mark is visible
3015  **/
3016 gboolean
3017 gtk_text_view_get_cursor_visible (GtkTextView *text_view)
3018 {
3019   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
3020
3021   return text_view->priv->cursor_visible;
3022 }
3023
3024
3025 /**
3026  * gtk_text_view_place_cursor_onscreen:
3027  * @text_view: a #GtkTextView
3028  *
3029  * Moves the cursor to the currently visible region of the
3030  * buffer, it it isn't there already.
3031  *
3032  * Return value: %TRUE if the cursor had to be moved.
3033  **/
3034 gboolean
3035 gtk_text_view_place_cursor_onscreen (GtkTextView *text_view)
3036 {
3037   GtkTextIter insert;
3038
3039   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
3040
3041   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
3042                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
3043
3044   if (clamp_iter_onscreen (text_view, &insert))
3045     {
3046       gtk_text_buffer_place_cursor (get_buffer (text_view), &insert);
3047       return TRUE;
3048     }
3049   else
3050     return FALSE;
3051 }
3052
3053 static void
3054 gtk_text_view_remove_validate_idles (GtkTextView *text_view)
3055 {
3056   GtkTextViewPrivate *priv = text_view->priv;
3057
3058   if (priv->first_validate_idle != 0)
3059     {
3060       DV (g_print ("Removing first validate idle: %s\n", G_STRLOC));
3061       g_source_remove (priv->first_validate_idle);
3062       priv->first_validate_idle = 0;
3063     }
3064
3065   if (priv->incremental_validate_idle != 0)
3066     {
3067       g_source_remove (priv->incremental_validate_idle);
3068       priv->incremental_validate_idle = 0;
3069     }
3070 }
3071
3072 static void
3073 gtk_text_view_destroy (GtkWidget *widget)
3074 {
3075   GtkTextView *text_view;
3076   GtkTextViewPrivate *priv;
3077
3078   text_view = GTK_TEXT_VIEW (widget);
3079   priv = text_view->priv;
3080
3081   gtk_text_view_remove_validate_idles (text_view);
3082   gtk_text_view_set_buffer (text_view, NULL);
3083   gtk_text_view_destroy_layout (text_view);
3084
3085   if (text_view->priv->scroll_timeout)
3086     {
3087       g_source_remove (text_view->priv->scroll_timeout);
3088       text_view->priv->scroll_timeout = 0;
3089     }
3090
3091   if (priv->im_spot_idle)
3092     {
3093       g_source_remove (priv->im_spot_idle);
3094       priv->im_spot_idle = 0;
3095     }
3096
3097   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->destroy (widget);
3098 }
3099
3100 static void
3101 gtk_text_view_finalize (GObject *object)
3102 {
3103   GtkTextView *text_view;
3104   GtkTextViewPrivate *priv;
3105
3106   text_view = GTK_TEXT_VIEW (object);
3107   priv = text_view->priv;
3108
3109   gtk_text_view_destroy_layout (text_view);
3110   gtk_text_view_set_buffer (text_view, NULL);
3111
3112   /* at this point, no "notify::buffer" handler should recreate the buffer. */
3113   g_assert (priv->buffer == NULL);
3114   
3115   cancel_pending_scroll (text_view);
3116
3117   if (priv->tabs)
3118     pango_tab_array_free (priv->tabs);
3119   
3120   if (priv->hadjustment)
3121     g_object_unref (priv->hadjustment);
3122   if (priv->vadjustment)
3123     g_object_unref (priv->vadjustment);
3124
3125   text_window_free (priv->text_window);
3126
3127   if (priv->left_window)
3128     text_window_free (priv->left_window);
3129
3130   if (priv->top_window)
3131     text_window_free (priv->top_window);
3132
3133   if (priv->right_window)
3134     text_window_free (priv->right_window);
3135
3136   if (priv->bottom_window)
3137     text_window_free (priv->bottom_window);
3138
3139   g_object_unref (priv->text_handle);
3140   g_object_unref (priv->im_context);
3141
3142   g_free (priv->im_module);
3143
3144   G_OBJECT_CLASS (gtk_text_view_parent_class)->finalize (object);
3145 }
3146
3147 static void
3148 gtk_text_view_set_property (GObject         *object,
3149                             guint            prop_id,
3150                             const GValue    *value,
3151                             GParamSpec      *pspec)
3152 {
3153   GtkTextView *text_view;
3154   GtkTextViewPrivate *priv;
3155
3156   text_view = GTK_TEXT_VIEW (object);
3157   priv = text_view->priv;
3158
3159   switch (prop_id)
3160     {
3161     case PROP_PIXELS_ABOVE_LINES:
3162       gtk_text_view_set_pixels_above_lines (text_view, g_value_get_int (value));
3163       break;
3164
3165     case PROP_PIXELS_BELOW_LINES:
3166       gtk_text_view_set_pixels_below_lines (text_view, g_value_get_int (value));
3167       break;
3168
3169     case PROP_PIXELS_INSIDE_WRAP:
3170       gtk_text_view_set_pixels_inside_wrap (text_view, g_value_get_int (value));
3171       break;
3172
3173     case PROP_EDITABLE:
3174       gtk_text_view_set_editable (text_view, g_value_get_boolean (value));
3175       break;
3176
3177     case PROP_WRAP_MODE:
3178       gtk_text_view_set_wrap_mode (text_view, g_value_get_enum (value));
3179       break;
3180       
3181     case PROP_JUSTIFICATION:
3182       gtk_text_view_set_justification (text_view, g_value_get_enum (value));
3183       break;
3184
3185     case PROP_LEFT_MARGIN:
3186       gtk_text_view_set_left_margin (text_view, g_value_get_int (value));
3187       break;
3188
3189     case PROP_RIGHT_MARGIN:
3190       gtk_text_view_set_right_margin (text_view, g_value_get_int (value));
3191       break;
3192
3193     case PROP_INDENT:
3194       gtk_text_view_set_indent (text_view, g_value_get_int (value));
3195       break;
3196
3197     case PROP_TABS:
3198       gtk_text_view_set_tabs (text_view, g_value_get_boxed (value));
3199       break;
3200
3201     case PROP_CURSOR_VISIBLE:
3202       gtk_text_view_set_cursor_visible (text_view, g_value_get_boolean (value));
3203       break;
3204
3205     case PROP_OVERWRITE:
3206       gtk_text_view_set_overwrite (text_view, g_value_get_boolean (value));
3207       break;
3208
3209     case PROP_BUFFER:
3210       gtk_text_view_set_buffer (text_view, GTK_TEXT_BUFFER (g_value_get_object (value)));
3211       break;
3212
3213     case PROP_ACCEPTS_TAB:
3214       gtk_text_view_set_accepts_tab (text_view, g_value_get_boolean (value));
3215       break;
3216       
3217     case PROP_IM_MODULE:
3218       g_free (priv->im_module);
3219       priv->im_module = g_value_dup_string (value);
3220       if (GTK_IS_IM_MULTICONTEXT (priv->im_context))
3221         gtk_im_multicontext_set_context_id (GTK_IM_MULTICONTEXT (priv->im_context), priv->im_module);
3222       break;
3223
3224     case PROP_HADJUSTMENT:
3225       gtk_text_view_set_hadjustment (text_view, g_value_get_object (value));
3226       break;
3227
3228     case PROP_VADJUSTMENT:
3229       gtk_text_view_set_vadjustment (text_view, g_value_get_object (value));
3230       break;
3231
3232     case PROP_HSCROLL_POLICY:
3233       priv->hscroll_policy = g_value_get_enum (value);
3234       gtk_widget_queue_resize (GTK_WIDGET (text_view));
3235       break;
3236
3237     case PROP_VSCROLL_POLICY:
3238       priv->vscroll_policy = g_value_get_enum (value);
3239       gtk_widget_queue_resize (GTK_WIDGET (text_view));
3240       break;
3241
3242     case PROP_INPUT_PURPOSE:
3243       gtk_text_view_set_input_purpose (text_view, g_value_get_enum (value));
3244       break;
3245
3246     case PROP_INPUT_HINTS:
3247       gtk_text_view_set_input_hints (text_view, g_value_get_flags (value));
3248       break;
3249
3250     default:
3251       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3252       break;
3253     }
3254 }
3255
3256 static void
3257 gtk_text_view_get_property (GObject         *object,
3258                             guint            prop_id,
3259                             GValue          *value,
3260                             GParamSpec      *pspec)
3261 {
3262   GtkTextView *text_view;
3263   GtkTextViewPrivate *priv;
3264
3265   text_view = GTK_TEXT_VIEW (object);
3266   priv = text_view->priv;
3267
3268   switch (prop_id)
3269     {
3270     case PROP_PIXELS_ABOVE_LINES:
3271       g_value_set_int (value, priv->pixels_above_lines);
3272       break;
3273
3274     case PROP_PIXELS_BELOW_LINES:
3275       g_value_set_int (value, priv->pixels_below_lines);
3276       break;
3277
3278     case PROP_PIXELS_INSIDE_WRAP:
3279       g_value_set_int (value, priv->pixels_inside_wrap);
3280       break;
3281
3282     case PROP_EDITABLE:
3283       g_value_set_boolean (value, priv->editable);
3284       break;
3285       
3286     case PROP_WRAP_MODE:
3287       g_value_set_enum (value, priv->wrap_mode);
3288       break;
3289
3290     case PROP_JUSTIFICATION:
3291       g_value_set_enum (value, priv->justify);
3292       break;
3293
3294     case PROP_LEFT_MARGIN:
3295       g_value_set_int (value, priv->left_margin);
3296       break;
3297
3298     case PROP_RIGHT_MARGIN:
3299       g_value_set_int (value, priv->right_margin);
3300       break;
3301
3302     case PROP_INDENT:
3303       g_value_set_int (value, priv->indent);
3304       break;
3305
3306     case PROP_TABS:
3307       g_value_set_boxed (value, priv->tabs);
3308       break;
3309
3310     case PROP_CURSOR_VISIBLE:
3311       g_value_set_boolean (value, priv->cursor_visible);
3312       break;
3313
3314     case PROP_BUFFER:
3315       g_value_set_object (value, get_buffer (text_view));
3316       break;
3317
3318     case PROP_OVERWRITE:
3319       g_value_set_boolean (value, priv->overwrite_mode);
3320       break;
3321
3322     case PROP_ACCEPTS_TAB:
3323       g_value_set_boolean (value, priv->accepts_tab);
3324       break;
3325       
3326     case PROP_IM_MODULE:
3327       g_value_set_string (value, priv->im_module);
3328       break;
3329
3330     case PROP_HADJUSTMENT:
3331       g_value_set_object (value, priv->hadjustment);
3332       break;
3333
3334     case PROP_VADJUSTMENT:
3335       g_value_set_object (value, priv->vadjustment);
3336       break;
3337
3338     case PROP_HSCROLL_POLICY:
3339       g_value_set_enum (value, priv->hscroll_policy);
3340       break;
3341
3342     case PROP_VSCROLL_POLICY:
3343       g_value_set_enum (value, priv->vscroll_policy);
3344       break;
3345
3346     case PROP_INPUT_PURPOSE:
3347       g_value_set_enum (value, gtk_text_view_get_input_purpose (text_view));
3348       break;
3349
3350     case PROP_INPUT_HINTS:
3351       g_value_set_flags (value, gtk_text_view_get_input_hints (text_view));
3352       break;
3353
3354     default:
3355       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3356       break;
3357     }
3358 }
3359
3360 static void
3361 gtk_text_view_size_request (GtkWidget      *widget,
3362                             GtkRequisition *requisition)
3363 {
3364   GtkTextView *text_view;
3365   GtkTextViewPrivate *priv;
3366   GSList *tmp_list;
3367   gint focus_edge_width;
3368   gint focus_width;
3369   guint border_width;
3370   gboolean interior_focus;
3371
3372   text_view = GTK_TEXT_VIEW (widget);
3373   priv = text_view->priv;
3374
3375   gtk_widget_style_get (widget,
3376                         "interior-focus", &interior_focus,
3377                         "focus-line-width", &focus_width,
3378                         NULL);
3379
3380   if (interior_focus)
3381     focus_edge_width = 0;
3382   else
3383     focus_edge_width = focus_width;
3384
3385   if (priv->layout)
3386     {
3387       priv->text_window->requisition.width = priv->layout->width;
3388       priv->text_window->requisition.height = priv->layout->height;
3389     }
3390   else
3391     {
3392       priv->text_window->requisition.width = 0;
3393       priv->text_window->requisition.height = 0;
3394     }
3395   
3396   requisition->width = priv->text_window->requisition.width + focus_edge_width * 2;
3397   requisition->height = priv->text_window->requisition.height + focus_edge_width * 2;
3398
3399   if (priv->left_window)
3400     requisition->width += priv->left_window->requisition.width;
3401
3402   if (priv->right_window)
3403     requisition->width += priv->right_window->requisition.width;
3404
3405   if (priv->top_window)
3406     requisition->height += priv->top_window->requisition.height;
3407
3408   if (priv->bottom_window)
3409     requisition->height += priv->bottom_window->requisition.height;
3410
3411   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3412   requisition->width += border_width * 2;
3413   requisition->height += border_width * 2;
3414   
3415   tmp_list = priv->children;
3416   while (tmp_list != NULL)
3417     {
3418       GtkTextViewChild *child = tmp_list->data;
3419
3420       if (child->anchor)
3421         {
3422           GtkRequisition child_req;
3423           GtkRequisition old_req;
3424
3425           gtk_widget_get_preferred_size (child->widget, &old_req, NULL);
3426
3427           gtk_widget_get_preferred_size (child->widget, &child_req, NULL);
3428
3429           /* Invalidate layout lines if required */
3430           if (priv->layout &&
3431               (old_req.width != child_req.width ||
3432                old_req.height != child_req.height))
3433             gtk_text_child_anchor_queue_resize (child->anchor,
3434                                                 priv->layout);
3435         }
3436       else
3437         {
3438           GtkRequisition child_req;
3439
3440           gtk_widget_get_preferred_size (child->widget,
3441                                          &child_req, NULL);
3442         }
3443
3444       tmp_list = g_slist_next (tmp_list);
3445     }
3446
3447   /* Cache the requested size of the text view so we can 
3448    * compare it in the changed_handler() */
3449   priv->cached_size_request = *requisition;
3450 }
3451
3452 static void
3453 gtk_text_view_get_preferred_width (GtkWidget *widget,
3454                                    gint      *minimum,
3455                                    gint      *natural)
3456 {
3457   GtkRequisition requisition;
3458
3459   gtk_text_view_size_request (widget, &requisition);
3460
3461   *minimum = *natural = requisition.width;
3462 }
3463
3464 static void
3465 gtk_text_view_get_preferred_height (GtkWidget *widget,
3466                                     gint      *minimum,
3467                                     gint      *natural)
3468 {
3469   GtkRequisition requisition;
3470
3471   gtk_text_view_size_request (widget, &requisition);
3472
3473   *minimum = *natural = requisition.height;
3474 }
3475
3476
3477 static void
3478 gtk_text_view_compute_child_allocation (GtkTextView      *text_view,
3479                                         GtkTextViewChild *vc,
3480                                         GtkAllocation    *allocation)
3481 {
3482   gint buffer_y;
3483   GtkTextIter iter;
3484   GtkRequisition req;
3485   
3486   gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3487                                             &iter,
3488                                             vc->anchor);
3489
3490   gtk_text_layout_get_line_yrange (text_view->priv->layout, &iter,
3491                                    &buffer_y, NULL);
3492
3493   buffer_y += vc->from_top_of_line;
3494
3495   allocation->x = vc->from_left_of_buffer - text_view->priv->xoffset;
3496   allocation->y = buffer_y - text_view->priv->yoffset;
3497
3498   gtk_widget_get_preferred_size (vc->widget, &req, NULL);
3499   allocation->width = req.width;
3500   allocation->height = req.height;
3501 }
3502
3503 static void
3504 gtk_text_view_update_child_allocation (GtkTextView      *text_view,
3505                                        GtkTextViewChild *vc)
3506 {
3507   GtkAllocation allocation;
3508
3509   gtk_text_view_compute_child_allocation (text_view, vc, &allocation);
3510   
3511   gtk_widget_size_allocate (vc->widget, &allocation);
3512
3513 #if 0
3514   g_print ("allocation for %p allocated to %d,%d yoffset = %d\n",
3515            vc->widget,
3516            vc->widget->allocation.x,
3517            vc->widget->allocation.y,
3518            text_view->priv->yoffset);
3519 #endif
3520 }
3521
3522 static void
3523 gtk_text_view_child_allocated (GtkTextLayout *layout,
3524                                GtkWidget     *child,
3525                                gint           x,
3526                                gint           y,
3527                                gpointer       data)
3528 {
3529   GtkTextViewChild *vc = NULL;
3530   GtkTextView *text_view = data;
3531   
3532   /* x,y is the position of the child from the top of the line, and
3533    * from the left of the buffer. We have to translate that into text
3534    * window coordinates, then size_allocate the child.
3535    */
3536
3537   vc = g_object_get_data (G_OBJECT (child),
3538                           "gtk-text-view-child");
3539
3540   g_assert (vc != NULL);
3541
3542   DV (g_print ("child allocated at %d,%d\n", x, y));
3543   
3544   vc->from_left_of_buffer = x;
3545   vc->from_top_of_line = y;
3546
3547   gtk_text_view_update_child_allocation (text_view, vc);
3548 }
3549
3550 static void
3551 gtk_text_view_allocate_children (GtkTextView *text_view)
3552 {
3553   GSList *tmp_list;
3554
3555   DV(g_print(G_STRLOC"\n"));
3556   
3557   tmp_list = text_view->priv->children;
3558   while (tmp_list != NULL)
3559     {
3560       GtkTextViewChild *child = tmp_list->data;
3561
3562       g_assert (child != NULL);
3563           
3564       if (child->anchor)
3565         {
3566           /* We need to force-validate the regions containing
3567            * children.
3568            */
3569           GtkTextIter child_loc;
3570           gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
3571                                                     &child_loc,
3572                                                     child->anchor);
3573
3574           /* Since anchored children are only ever allocated from
3575            * gtk_text_layout_get_line_display() we have to make sure
3576            * that the display line caching in the layout doesn't 
3577            * get in the way. Invalidating the layout around the anchor
3578            * achieves this.
3579            */ 
3580           if (_gtk_widget_get_alloc_needed (child->widget))
3581             {
3582               GtkTextIter end = child_loc;
3583               gtk_text_iter_forward_char (&end);
3584               gtk_text_layout_invalidate (text_view->priv->layout, &child_loc, &end);
3585             }
3586
3587           gtk_text_layout_validate_yrange (text_view->priv->layout,
3588                                            &child_loc,
3589                                            0, 1);
3590         }
3591       else
3592         {
3593           GtkAllocation allocation;
3594           GtkRequisition child_req;
3595              
3596           allocation.x = child->x;
3597           allocation.y = child->y;
3598
3599           gtk_widget_get_preferred_size (child->widget, &child_req, NULL);
3600
3601           allocation.width = child_req.width;
3602           allocation.height = child_req.height;
3603           
3604           gtk_widget_size_allocate (child->widget, &allocation);          
3605         }
3606
3607       tmp_list = g_slist_next (tmp_list);
3608     }
3609 }
3610
3611 static void
3612 gtk_text_view_size_allocate (GtkWidget *widget,
3613                              GtkAllocation *allocation)
3614 {
3615   GtkAllocation widget_allocation;
3616   GtkTextView *text_view;
3617   GtkTextViewPrivate *priv;
3618   gint width, height;
3619   GdkRectangle text_rect;
3620   GdkRectangle left_rect;
3621   GdkRectangle right_rect;
3622   GdkRectangle top_rect;
3623   GdkRectangle bottom_rect;
3624   gint focus_edge_width;
3625   gint focus_width;
3626   guint border_width;
3627   gboolean interior_focus;
3628   gboolean size_changed;
3629   
3630   text_view = GTK_TEXT_VIEW (widget);
3631   priv = text_view->priv;
3632
3633   DV(g_print(G_STRLOC"\n"));
3634
3635   gtk_widget_get_allocation (widget, &widget_allocation);
3636   size_changed =
3637     widget_allocation.width != allocation->width ||
3638     widget_allocation.height != allocation->height;
3639
3640   border_width = gtk_container_get_border_width (GTK_CONTAINER (text_view));
3641
3642   gtk_widget_set_allocation (widget, allocation);
3643
3644   if (gtk_widget_get_realized (widget))
3645     {
3646       gdk_window_move_resize (gtk_widget_get_window (widget),
3647                               allocation->x, allocation->y,
3648                               allocation->width, allocation->height);
3649     }
3650
3651   /* distribute width/height among child windows. Ensure all
3652    * windows get at least a 1x1 allocation.
3653    */
3654
3655   gtk_widget_style_get (widget,
3656                         "interior-focus", &interior_focus,
3657                         "focus-line-width", &focus_width,
3658                         NULL);
3659
3660   if (interior_focus)
3661     focus_edge_width = 0;
3662   else
3663     focus_edge_width = focus_width;
3664   
3665   width = allocation->width - focus_edge_width * 2 - border_width * 2;
3666
3667   if (priv->left_window)
3668     left_rect.width = priv->left_window->requisition.width;
3669   else
3670     left_rect.width = 0;
3671
3672   width -= left_rect.width;
3673
3674   if (priv->right_window)
3675     right_rect.width = priv->right_window->requisition.width;
3676   else
3677     right_rect.width = 0;
3678
3679   width -= right_rect.width;
3680
3681   text_rect.width = MAX (1, width);
3682
3683   top_rect.width = text_rect.width;
3684   bottom_rect.width = text_rect.width;
3685
3686
3687   height = allocation->height - focus_edge_width * 2 - border_width * 2;
3688
3689   if (priv->top_window)
3690     top_rect.height = priv->top_window->requisition.height;
3691   else
3692     top_rect.height = 0;
3693
3694   height -= top_rect.height;
3695
3696   if (priv->bottom_window)
3697     bottom_rect.height = priv->bottom_window->requisition.height;
3698   else
3699     bottom_rect.height = 0;
3700
3701   height -= bottom_rect.height;
3702
3703   text_rect.height = MAX (1, height);
3704
3705   left_rect.height = text_rect.height;
3706   right_rect.height = text_rect.height;
3707
3708   /* Origins */
3709   left_rect.x = focus_edge_width + border_width;
3710   top_rect.y = focus_edge_width + border_width;
3711
3712   text_rect.x = left_rect.x + left_rect.width;
3713   text_rect.y = top_rect.y + top_rect.height;
3714
3715   left_rect.y = text_rect.y;
3716   right_rect.y = text_rect.y;
3717
3718   top_rect.x = text_rect.x;
3719   bottom_rect.x = text_rect.x;
3720
3721   right_rect.x = text_rect.x + text_rect.width;
3722   bottom_rect.y = text_rect.y + text_rect.height;
3723
3724   text_window_size_allocate (priv->text_window,
3725                              &text_rect);
3726
3727   if (priv->left_window)
3728     text_window_size_allocate (priv->left_window,
3729                                &left_rect);
3730
3731   if (priv->right_window)
3732     text_window_size_allocate (priv->right_window,
3733                                &right_rect);
3734
3735   if (priv->top_window)
3736     text_window_size_allocate (priv->top_window,
3737                                &top_rect);
3738
3739   if (priv->bottom_window)
3740     text_window_size_allocate (priv->bottom_window,
3741                                &bottom_rect);
3742
3743   gtk_text_view_update_layout_width (text_view);
3744   
3745   /* Note that this will do some layout validation */
3746   gtk_text_view_allocate_children (text_view);
3747
3748   /* Update adjustments */
3749   gtk_text_view_set_hadjustment_values (text_view);
3750   gtk_text_view_set_vadjustment_values (text_view);
3751
3752   /* The GTK resize loop processes all the pending exposes right
3753    * after doing the resize stuff, so the idle sizer won't have a
3754    * chance to run. So we do the work here. 
3755    */
3756   gtk_text_view_flush_first_validate (text_view);
3757
3758   /* widget->window doesn't get auto-redrawn as the layout is computed, so has to
3759    * be invalidated
3760    */
3761   if (size_changed && gtk_widget_get_realized (widget))
3762     gdk_window_invalidate_rect (gtk_widget_get_window (widget), NULL, FALSE);
3763 }
3764
3765 static void
3766 gtk_text_view_get_first_para_iter (GtkTextView *text_view,
3767                                    GtkTextIter *iter)
3768 {
3769   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), iter,
3770                                     text_view->priv->first_para_mark);
3771 }
3772
3773 static void
3774 gtk_text_view_validate_onscreen (GtkTextView *text_view)
3775 {
3776   GtkWidget *widget;
3777   GtkTextViewPrivate *priv;
3778
3779   widget = GTK_WIDGET (text_view);
3780   priv = text_view->priv;
3781   
3782   DV(g_print(">Validating onscreen ("G_STRLOC")\n"));
3783   
3784   if (SCREEN_HEIGHT (widget) > 0)
3785     {
3786       GtkTextIter first_para;
3787
3788       /* Be sure we've validated the stuff onscreen; if we
3789        * scrolled, these calls won't have any effect, because
3790        * they were called in the recursive validate_onscreen
3791        */
3792       gtk_text_view_get_first_para_iter (text_view, &first_para);
3793
3794       gtk_text_layout_validate_yrange (priv->layout,
3795                                        &first_para,
3796                                        0,
3797                                        priv->first_para_pixels +
3798                                        SCREEN_HEIGHT (widget));
3799     }
3800
3801   priv->onscreen_validated = TRUE;
3802
3803   DV(g_print(">Done validating onscreen, onscreen_validated = TRUE ("G_STRLOC")\n"));
3804   
3805   /* This can have the odd side effect of triggering a scroll, which should
3806    * flip "onscreen_validated" back to FALSE, but should also get us
3807    * back into this function to turn it on again.
3808    */
3809   gtk_text_view_update_adjustments (text_view);
3810
3811   g_assert (priv->onscreen_validated);
3812 }
3813
3814 static void
3815 gtk_text_view_flush_first_validate (GtkTextView *text_view)
3816 {
3817   GtkTextViewPrivate *priv = text_view->priv;
3818
3819   if (priv->first_validate_idle == 0)
3820     return;
3821
3822   /* Do this first, which means that if an "invalidate"
3823    * occurs during any of this process, a new first_validate_callback
3824    * will be installed, and we'll start again.
3825    */
3826   DV (g_print ("removing first validate in %s\n", G_STRLOC));
3827   g_source_remove (priv->first_validate_idle);
3828   priv->first_validate_idle = 0;
3829   
3830   /* be sure we have up-to-date screen size set on the
3831    * layout.
3832    */
3833   gtk_text_view_update_layout_width (text_view);
3834
3835   /* Bail out if we invalidated stuff; scrolling right away will just
3836    * confuse the issue.
3837    */
3838   if (priv->first_validate_idle != 0)
3839     {
3840       DV(g_print(">Width change forced requeue ("G_STRLOC")\n"));
3841     }
3842   else
3843     {
3844       /* scroll to any marks, if that's pending. This can jump us to
3845        * the validation codepath used for scrolling onscreen, if so we
3846        * bail out.  It won't jump if already in that codepath since
3847        * value_changed is not recursive, so also validate if
3848        * necessary.
3849        */
3850       if (!gtk_text_view_flush_scroll (text_view) ||
3851           !priv->onscreen_validated)
3852         gtk_text_view_validate_onscreen (text_view);
3853       
3854       DV(g_print(">Leaving first validate idle ("G_STRLOC")\n"));
3855       
3856       g_assert (priv->onscreen_validated);
3857     }
3858 }
3859
3860 static gboolean
3861 first_validate_callback (gpointer data)
3862 {
3863   GtkTextView *text_view = data;
3864
3865   /* Note that some of this code is duplicated at the end of size_allocate,
3866    * keep in sync with that.
3867    */
3868   
3869   DV(g_print(G_STRLOC"\n"));
3870
3871   gtk_text_view_flush_first_validate (text_view);
3872   
3873   return FALSE;
3874 }
3875
3876 static gboolean
3877 incremental_validate_callback (gpointer data)
3878 {
3879   GtkTextView *text_view = data;
3880   gboolean result = TRUE;
3881
3882   DV(g_print(G_STRLOC"\n"));
3883   
3884   gtk_text_layout_validate (text_view->priv->layout, 2000);
3885
3886   gtk_text_view_update_adjustments (text_view);
3887   
3888   if (gtk_text_layout_is_valid (text_view->priv->layout))
3889     {
3890       text_view->priv->incremental_validate_idle = 0;
3891       result = FALSE;
3892     }
3893
3894   return result;
3895 }
3896
3897 static void
3898 gtk_text_view_invalidate (GtkTextView *text_view)
3899 {
3900   GtkTextViewPrivate *priv = text_view->priv;
3901
3902   DV (g_print (">Invalidate, onscreen_validated = %d now FALSE ("G_STRLOC")\n",
3903                priv->onscreen_validated));
3904
3905   priv->onscreen_validated = FALSE;
3906
3907   /* We'll invalidate when the layout is created */
3908   if (priv->layout == NULL)
3909     return;
3910   
3911   if (!priv->first_validate_idle)
3912     {
3913       priv->first_validate_idle = gdk_threads_add_idle_full (GTK_PRIORITY_RESIZE - 2, first_validate_callback, text_view, NULL);
3914       DV (g_print (G_STRLOC": adding first validate idle %d\n",
3915                    priv->first_validate_idle));
3916     }
3917       
3918   if (!priv->incremental_validate_idle)
3919     {
3920       priv->incremental_validate_idle = gdk_threads_add_idle_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE, incremental_validate_callback, text_view, NULL);
3921       DV (g_print (G_STRLOC": adding incremental validate idle %d\n",
3922                    priv->incremental_validate_idle));
3923     }
3924 }
3925
3926 static void
3927 invalidated_handler (GtkTextLayout *layout,
3928                      gpointer       data)
3929 {
3930   GtkTextView *text_view;
3931
3932   text_view = GTK_TEXT_VIEW (data);
3933
3934   DV (g_print ("Invalidating due to layout invalidate signal\n"));
3935   gtk_text_view_invalidate (text_view);
3936 }
3937
3938 static void
3939 changed_handler (GtkTextLayout     *layout,
3940                  gint               start_y,
3941                  gint               old_height,
3942                  gint               new_height,
3943                  gpointer           data)
3944 {
3945   GtkTextView *text_view;
3946   GtkTextViewPrivate *priv;
3947   GtkWidget *widget;
3948   GdkRectangle visible_rect;
3949   GdkRectangle redraw_rect;
3950   
3951   text_view = GTK_TEXT_VIEW (data);
3952   priv = text_view->priv;
3953   widget = GTK_WIDGET (data);
3954   
3955   DV(g_print(">Lines Validated ("G_STRLOC")\n"));
3956
3957   if (gtk_widget_get_realized (widget))
3958     {      
3959       gtk_text_view_get_visible_rect (text_view, &visible_rect);
3960
3961       redraw_rect.x = visible_rect.x;
3962       redraw_rect.width = visible_rect.width;
3963       redraw_rect.y = start_y;
3964
3965       if (old_height == new_height)
3966         redraw_rect.height = old_height;
3967       else if (start_y + old_height > visible_rect.y)
3968         redraw_rect.height = MAX (0, visible_rect.y + visible_rect.height - start_y);
3969       else
3970         redraw_rect.height = 0;
3971         
3972       if (gdk_rectangle_intersect (&redraw_rect, &visible_rect, &redraw_rect))
3973         {
3974           /* text_window_invalidate_rect() takes buffer coordinates */
3975           text_window_invalidate_rect (priv->text_window,
3976                                        &redraw_rect);
3977
3978           DV(g_print(" invalidated rect: %d,%d %d x %d\n",
3979                      redraw_rect.x,
3980                      redraw_rect.y,
3981                      redraw_rect.width,
3982                      redraw_rect.height));
3983           
3984           if (priv->left_window)
3985             text_window_invalidate_rect (priv->left_window,
3986                                          &redraw_rect);
3987           if (priv->right_window)
3988             text_window_invalidate_rect (priv->right_window,
3989                                          &redraw_rect);
3990           if (priv->top_window)
3991             text_window_invalidate_rect (priv->top_window,
3992                                          &redraw_rect);
3993           if (priv->bottom_window)
3994             text_window_invalidate_rect (priv->bottom_window,
3995                                          &redraw_rect);
3996
3997           queue_update_im_spot_location (text_view);
3998         }
3999     }
4000   
4001   if (old_height != new_height)
4002     {
4003       GSList *tmp_list;
4004       int new_first_para_top;
4005       int old_first_para_top;
4006       GtkTextIter first;
4007       
4008       /* If the bottom of the old area was above the top of the
4009        * screen, we need to scroll to keep the current top of the
4010        * screen in place.  Remember that first_para_pixels is the
4011        * position of the top of the screen in coordinates relative to
4012        * the first paragraph onscreen.
4013        *
4014        * In short we are adding the height delta of the portion of the
4015        * changed region above first_para_mark to priv->yoffset.
4016        */
4017       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &first,
4018                                         priv->first_para_mark);
4019
4020       gtk_text_layout_get_line_yrange (layout, &first, &new_first_para_top, NULL);
4021
4022       old_first_para_top = priv->yoffset - priv->first_para_pixels;
4023
4024       if (new_first_para_top != old_first_para_top)
4025         {
4026           priv->yoffset += new_first_para_top - old_first_para_top;
4027           
4028           gtk_adjustment_set_value (text_view->priv->vadjustment, priv->yoffset);
4029         }
4030
4031       /* FIXME be smarter about which anchored widgets we update */
4032
4033       tmp_list = priv->children;
4034       while (tmp_list != NULL)
4035         {
4036           GtkTextViewChild *child = tmp_list->data;
4037
4038           if (child->anchor)
4039             gtk_text_view_update_child_allocation (text_view, child);
4040
4041           tmp_list = g_slist_next (tmp_list);
4042         }
4043     }
4044
4045   {
4046     GtkRequisition old_req = priv->cached_size_request;
4047     GtkRequisition new_req;
4048
4049     /* Use this instead of gtk_widget_size_request wrapper
4050      * to avoid the optimization which just returns widget->requisition
4051      * if a resize hasn't been queued.
4052      */
4053     gtk_text_view_size_request (widget, &new_req);
4054
4055     if (old_req.width != new_req.width ||
4056         old_req.height != new_req.height)
4057       {
4058         gtk_widget_queue_resize_no_redraw (widget);
4059       }
4060   }
4061 }
4062
4063 static void
4064 gtk_text_view_realize (GtkWidget *widget)
4065 {
4066   GtkAllocation allocation;
4067   GtkTextView *text_view;
4068   GtkTextViewPrivate *priv;
4069   GtkStyleContext *context;
4070   GdkWindow *window;
4071   GdkWindowAttr attributes;
4072   gint attributes_mask;
4073   GSList *tmp_list;
4074
4075   text_view = GTK_TEXT_VIEW (widget);
4076   priv = text_view->priv;
4077
4078   gtk_widget_set_realized (widget, TRUE);
4079
4080   gtk_widget_get_allocation (widget, &allocation);
4081
4082   attributes.window_type = GDK_WINDOW_CHILD;
4083   attributes.x = allocation.x;
4084   attributes.y = allocation.y;
4085   attributes.width = allocation.width;
4086   attributes.height = allocation.height;
4087   attributes.wclass = GDK_INPUT_OUTPUT;
4088   attributes.visual = gtk_widget_get_visual (widget);
4089   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK | GDK_EXPOSURE_MASK;
4090
4091   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
4092
4093   window = gdk_window_new (gtk_widget_get_parent_window (widget),
4094                            &attributes, attributes_mask);
4095   gtk_widget_set_window (widget, window);
4096   gdk_window_set_user_data (window, widget);
4097
4098   context = gtk_widget_get_style_context (widget);
4099
4100   gtk_style_context_save (context);
4101   gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
4102   gtk_style_context_set_background (context, window);
4103   gtk_style_context_restore (context);
4104
4105   text_window_realize (priv->text_window, widget);
4106
4107   if (priv->left_window)
4108     text_window_realize (priv->left_window, widget);
4109
4110   if (priv->top_window)
4111     text_window_realize (priv->top_window, widget);
4112
4113   if (priv->right_window)
4114     text_window_realize (priv->right_window, widget);
4115
4116   if (priv->bottom_window)
4117     text_window_realize (priv->bottom_window, widget);
4118
4119   gtk_text_view_ensure_layout (text_view);
4120   gtk_text_view_invalidate (text_view);
4121
4122   if (priv->buffer)
4123     {
4124       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4125                                                           GDK_SELECTION_PRIMARY);
4126       gtk_text_buffer_add_selection_clipboard (priv->buffer, clipboard);
4127     }
4128
4129   tmp_list = priv->children;
4130   while (tmp_list != NULL)
4131     {
4132       GtkTextViewChild *vc = tmp_list->data;
4133       
4134       text_view_child_set_parent_window (text_view, vc);
4135       
4136       tmp_list = tmp_list->next;
4137     }
4138
4139   /* Ensure updating the spot location. */
4140   gtk_text_view_update_im_spot_location (text_view);
4141
4142   _gtk_text_handle_set_relative_to (priv->text_handle, priv->text_window->window);
4143 }
4144
4145 static void
4146 gtk_text_view_unrealize (GtkWidget *widget)
4147 {
4148   GtkTextView *text_view;
4149   GtkTextViewPrivate *priv;
4150
4151   text_view = GTK_TEXT_VIEW (widget);
4152   priv = text_view->priv;
4153
4154   if (priv->buffer)
4155     {
4156       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4157                                                           GDK_SELECTION_PRIMARY);
4158       gtk_text_buffer_remove_selection_clipboard (priv->buffer, clipboard);
4159     }
4160
4161   gtk_text_view_remove_validate_idles (text_view);
4162
4163   if (priv->popup_menu)
4164     {
4165       gtk_widget_destroy (priv->popup_menu);
4166       priv->popup_menu = NULL;
4167     }
4168
4169   text_window_unrealize (priv->text_window);
4170
4171   if (priv->left_window)
4172     text_window_unrealize (priv->left_window);
4173
4174   if (priv->top_window)
4175     text_window_unrealize (priv->top_window);
4176
4177   if (priv->right_window)
4178     text_window_unrealize (priv->right_window);
4179
4180   if (priv->bottom_window)
4181     text_window_unrealize (priv->bottom_window);
4182
4183   _gtk_text_handle_set_relative_to (priv->text_handle, NULL);
4184
4185   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->unrealize (widget);
4186 }
4187
4188 static void
4189 gtk_text_view_set_background (GtkTextView *text_view)
4190 {
4191   GtkStyleContext *context;
4192   GtkStateFlags state;
4193   GtkWidget *widget;
4194   GtkTextViewPrivate *priv;
4195   GdkRGBA color;
4196
4197   widget = GTK_WIDGET (text_view);
4198   priv = text_view->priv;
4199
4200   context = gtk_widget_get_style_context (widget);
4201   state = gtk_widget_get_state_flags (widget);
4202
4203   /* Set bin window background */
4204   gtk_style_context_save (context);
4205   gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
4206
4207   gtk_style_context_set_background (context, priv->text_window->bin_window);
4208   gtk_style_context_set_background (context, gtk_widget_get_window (widget));
4209
4210   gtk_style_context_restore (context);
4211
4212   /* Set lateral panes background */
4213   gtk_style_context_get_background_color (context, state, &color);
4214
4215   if (priv->left_window)
4216     gdk_window_set_background_rgba (priv->left_window->bin_window, &color);
4217
4218   if (priv->right_window)
4219     gdk_window_set_background_rgba (priv->right_window->bin_window, &color);
4220
4221   if (priv->top_window)
4222     gdk_window_set_background_rgba (priv->top_window->bin_window, &color);
4223
4224   if (priv->bottom_window)
4225     gdk_window_set_background_rgba (priv->bottom_window->bin_window, &color);
4226 }
4227
4228 static void
4229 gtk_text_view_style_updated (GtkWidget *widget)
4230 {
4231   GtkTextView *text_view;
4232   GtkTextViewPrivate *priv;
4233   PangoContext *ltr_context, *rtl_context;
4234   GtkStyleContext *style_context;
4235   const GtkBitmask *changes;
4236
4237   text_view = GTK_TEXT_VIEW (widget);
4238   priv = text_view->priv;
4239
4240   GTK_WIDGET_CLASS (gtk_text_view_parent_class)->style_updated (widget);
4241
4242   if (gtk_widget_get_realized (widget))
4243     {
4244       gtk_text_view_set_background (text_view);
4245     }
4246
4247
4248   style_context = gtk_widget_get_style_context (widget);
4249   changes = _gtk_style_context_get_changes (style_context);
4250   if ((changes == NULL || _gtk_css_style_property_changes_affect_font (changes)) &&
4251       priv->layout && priv->layout->default_style)
4252     {
4253       gtk_text_view_set_attributes_from_style (text_view,
4254                                                priv->layout->default_style);
4255
4256       ltr_context = gtk_widget_create_pango_context (widget);
4257       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
4258       rtl_context = gtk_widget_create_pango_context (widget);
4259       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
4260
4261       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
4262
4263       g_object_unref (ltr_context);
4264       g_object_unref (rtl_context);
4265     }
4266 }
4267
4268 static void
4269 gtk_text_view_direction_changed (GtkWidget        *widget,
4270                                  GtkTextDirection  previous_direction)
4271 {
4272   GtkTextViewPrivate *priv = GTK_TEXT_VIEW (widget)->priv;
4273
4274   if (priv->layout && priv->layout->default_style)
4275     {
4276       priv->layout->default_style->direction = gtk_widget_get_direction (widget);
4277
4278       gtk_text_layout_default_style_changed (priv->layout);
4279     }
4280 }
4281
4282 static void
4283 gtk_text_view_state_flags_changed (GtkWidget     *widget,
4284                                    GtkStateFlags  previous_state)
4285 {
4286   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
4287   GdkCursor *cursor;
4288
4289   if (gtk_widget_get_realized (widget))
4290     {
4291       gtk_text_view_set_background (text_view);
4292
4293       if (gtk_widget_is_sensitive (widget))
4294         cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
4295       else
4296         cursor = NULL;
4297
4298       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4299
4300       if (cursor)
4301       g_object_unref (cursor);
4302
4303       text_view->priv->mouse_cursor_obscured = FALSE;
4304     }
4305
4306   if (!gtk_widget_is_sensitive (widget))
4307     {
4308       /* Clear any selection */
4309       gtk_text_view_unselect (text_view);
4310     }
4311   
4312   gtk_widget_queue_draw (widget);
4313 }
4314
4315 static void
4316 set_invisible_cursor (GdkWindow *window)
4317 {
4318   GdkDisplay *display;
4319   GdkCursor *cursor;
4320
4321   display = gdk_window_get_display (window);
4322   cursor = gdk_cursor_new_for_display (display, GDK_BLANK_CURSOR);
4323  
4324   gdk_window_set_cursor (window, cursor);
4325   
4326   g_object_unref (cursor);
4327 }
4328
4329 static void
4330 gtk_text_view_obscure_mouse_cursor (GtkTextView *text_view)
4331 {
4332   if (text_view->priv->mouse_cursor_obscured)
4333     return;
4334
4335   set_invisible_cursor (text_view->priv->text_window->bin_window);
4336   
4337   text_view->priv->mouse_cursor_obscured = TRUE;
4338 }
4339
4340 static void
4341 gtk_text_view_unobscure_mouse_cursor (GtkTextView *text_view)
4342 {
4343   if (text_view->priv->mouse_cursor_obscured)
4344     {
4345       GdkCursor *cursor;
4346       
4347       cursor = gdk_cursor_new_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)),
4348                                            GDK_XTERM);
4349       gdk_window_set_cursor (text_view->priv->text_window->bin_window, cursor);
4350       g_object_unref (cursor);
4351       text_view->priv->mouse_cursor_obscured = FALSE;
4352     }
4353 }
4354
4355 static void
4356 gtk_text_view_grab_notify (GtkWidget *widget,
4357                            gboolean   was_grabbed)
4358 {
4359   GtkTextViewPrivate *priv;
4360
4361   priv = GTK_TEXT_VIEW (widget)->priv;
4362
4363   if (priv->grab_device &&
4364       gtk_widget_device_is_shadowed (widget, priv->grab_device))
4365     {
4366       if (priv->drag_start_x >= 0)
4367         {
4368           priv->drag_start_x = -1;
4369           priv->drag_start_y = -1;
4370         }
4371
4372       gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget));
4373       gtk_text_view_unobscure_mouse_cursor (GTK_TEXT_VIEW (widget));
4374       priv->grab_device = NULL;
4375     }
4376 }
4377
4378
4379 /*
4380  * Events
4381  */
4382
4383 static gboolean
4384 get_event_coordinates (GdkEvent *event, gint *x, gint *y)
4385 {
4386   if (event)
4387     switch (event->type)
4388       {
4389       case GDK_MOTION_NOTIFY:
4390         *x = event->motion.x;
4391         *y = event->motion.y;
4392         return TRUE;
4393         break;
4394
4395       case GDK_BUTTON_PRESS:
4396       case GDK_2BUTTON_PRESS:
4397       case GDK_3BUTTON_PRESS:
4398       case GDK_BUTTON_RELEASE:
4399         *x = event->button.x;
4400         *y = event->button.y;
4401         return TRUE;
4402         break;
4403
4404       case GDK_KEY_PRESS:
4405       case GDK_KEY_RELEASE:
4406       case GDK_ENTER_NOTIFY:
4407       case GDK_LEAVE_NOTIFY:
4408       case GDK_PROPERTY_NOTIFY:
4409       case GDK_SELECTION_CLEAR:
4410       case GDK_SELECTION_REQUEST:
4411       case GDK_SELECTION_NOTIFY:
4412       case GDK_PROXIMITY_IN:
4413       case GDK_PROXIMITY_OUT:
4414       case GDK_DRAG_ENTER:
4415       case GDK_DRAG_LEAVE:
4416       case GDK_DRAG_MOTION:
4417       case GDK_DRAG_STATUS:
4418       case GDK_DROP_START:
4419       case GDK_DROP_FINISHED:
4420       default:
4421         return FALSE;
4422         break;
4423       }
4424
4425   return FALSE;
4426 }
4427
4428 static gint
4429 emit_event_on_tags (GtkWidget   *widget,
4430                     GdkEvent    *event,
4431                     GtkTextIter *iter)
4432 {
4433   GSList *tags;
4434   GSList *tmp;
4435   gboolean retval = FALSE;
4436
4437   tags = gtk_text_iter_get_tags (iter);
4438
4439   tmp = tags;
4440   while (tmp != NULL)
4441     {
4442       GtkTextTag *tag = tmp->data;
4443
4444       if (gtk_text_tag_event (tag, G_OBJECT (widget), event, iter))
4445         {
4446           retval = TRUE;
4447           break;
4448         }
4449
4450       tmp = g_slist_next (tmp);
4451     }
4452
4453   g_slist_free (tags);
4454
4455   return retval;
4456 }
4457
4458 static void
4459 gtk_text_view_set_handle_position (GtkTextView           *text_view,
4460                                    GtkTextIter           *iter,
4461                                    GtkTextHandlePosition  pos)
4462 {
4463   GtkTextViewPrivate *priv;
4464   GdkRectangle rect;
4465   gint x, y;
4466
4467   priv = text_view->priv;
4468   gtk_text_view_get_cursor_locations (text_view, iter, &rect, NULL);
4469
4470   x = rect.x - priv->xoffset;
4471   y = rect.y - priv->yoffset;
4472
4473   if (!_gtk_text_handle_get_is_dragged (priv->text_handle, pos) &&
4474       (x < 0 || x > SCREEN_WIDTH (text_view) ||
4475        y < 0 || y > SCREEN_HEIGHT (text_view)))
4476     {
4477       /* Hide the handle if it's not being manipulated
4478        * and fell outside of the visible text area.
4479        */
4480       _gtk_text_handle_set_visible (priv->text_handle, pos, FALSE);
4481     }
4482   else
4483     {
4484       _gtk_text_handle_set_visible (priv->text_handle, pos, TRUE);
4485
4486       rect.x = CLAMP (x, 0, SCREEN_WIDTH (text_view));
4487       rect.y = CLAMP (y, 0, SCREEN_HEIGHT (text_view));
4488       _gtk_text_handle_set_position (priv->text_handle, pos, &rect);
4489     }
4490 }
4491
4492 static void
4493 gtk_text_view_handle_dragged (GtkTextHandle         *handle,
4494                               GtkTextHandlePosition  pos,
4495                               gint                   x,
4496                               gint                   y,
4497                               GtkTextView           *text_view)
4498 {
4499   GtkTextViewPrivate *priv;
4500   GtkTextIter old_cursor, old_bound;
4501   GtkTextIter cursor, bound, iter;
4502   GtkTextIter *min, *max;
4503   GtkTextHandleMode mode;
4504   GtkTextBuffer *buffer;
4505   GtkTextHandlePosition cursor_pos;
4506
4507   priv = text_view->priv;
4508   buffer = get_buffer (text_view);
4509   mode = _gtk_text_handle_get_mode (handle);
4510
4511   gtk_text_layout_get_iter_at_pixel (priv->layout, &iter,
4512                                      x + priv->xoffset,
4513                                      y + priv->yoffset);
4514   gtk_text_buffer_get_iter_at_mark (buffer, &old_cursor,
4515                                     gtk_text_buffer_get_insert (buffer));
4516   gtk_text_buffer_get_iter_at_mark (buffer, &old_bound,
4517                                     gtk_text_buffer_get_selection_bound (buffer));
4518   cursor = old_cursor;
4519   bound = old_bound;
4520
4521   if (mode == GTK_TEXT_HANDLE_MODE_CURSOR ||
4522       gtk_text_iter_compare (&cursor, &bound) >= 0)
4523     {
4524       cursor_pos = GTK_TEXT_HANDLE_POSITION_CURSOR;
4525       max = &cursor;
4526       min = &bound;
4527     }
4528   else
4529     {
4530       cursor_pos = GTK_TEXT_HANDLE_POSITION_SELECTION_START;
4531       max = &bound;
4532       min = &cursor;
4533     }
4534
4535   if (pos == GTK_TEXT_HANDLE_POSITION_SELECTION_END)
4536     {
4537       if (mode == GTK_TEXT_HANDLE_MODE_SELECTION &&
4538           gtk_text_iter_compare (&iter, min) <= 0)
4539         {
4540           iter = *min;
4541           gtk_text_iter_forward_char (&iter);
4542         }
4543
4544       *max = iter;
4545       gtk_text_view_set_handle_position (text_view, &iter, pos);
4546     }
4547   else
4548     {
4549       if (mode == GTK_TEXT_HANDLE_MODE_SELECTION &&
4550           gtk_text_iter_compare (&iter, max) >= 0)
4551         {
4552           iter = *max;
4553           gtk_text_iter_backward_char (&iter);
4554         }
4555
4556       *min = iter;
4557       gtk_text_view_set_handle_position (text_view, &iter, pos);
4558     }
4559
4560   if (gtk_text_iter_compare (&old_cursor, &cursor) != 0 ||
4561       gtk_text_iter_compare (&old_bound, &bound) != 0)
4562     {
4563       if (mode == GTK_TEXT_HANDLE_MODE_CURSOR)
4564         gtk_text_buffer_place_cursor (buffer, &cursor);
4565       else
4566         gtk_text_buffer_select_range (buffer, &cursor, &bound);
4567
4568       if (_gtk_text_handle_get_is_dragged (priv->text_handle, cursor_pos))
4569         gtk_text_view_scroll_mark_onscreen (text_view,
4570                                             gtk_text_buffer_get_insert (buffer));
4571       else
4572         gtk_text_view_scroll_mark_onscreen (text_view,
4573                                             gtk_text_buffer_get_selection_bound (buffer));
4574     }
4575 }
4576
4577 static void
4578 gtk_text_view_update_handles (GtkTextView       *text_view,
4579                               GtkTextHandleMode  mode)
4580 {
4581   GtkTextViewPrivate *priv = text_view->priv;
4582   GtkTextIter cursor, bound, min, max;
4583   GtkTextBuffer *buffer;
4584
4585   buffer = get_buffer (text_view);
4586
4587   gtk_text_buffer_get_iter_at_mark (buffer, &cursor,
4588                                     gtk_text_buffer_get_insert (buffer));
4589   gtk_text_buffer_get_iter_at_mark (buffer, &bound,
4590                                     gtk_text_buffer_get_selection_bound (buffer));
4591
4592   if (mode == GTK_TEXT_HANDLE_MODE_SELECTION &&
4593       gtk_text_iter_compare (&cursor, &bound) == 0)
4594     {
4595       mode = GTK_TEXT_HANDLE_MODE_CURSOR;
4596     }
4597
4598   if (mode == GTK_TEXT_HANDLE_MODE_CURSOR &&
4599       (!gtk_widget_is_sensitive (GTK_WIDGET (text_view)) || !priv->cursor_visible))
4600     {
4601       mode = GTK_TEXT_HANDLE_MODE_NONE;
4602     }
4603
4604   _gtk_text_handle_set_mode (priv->text_handle, mode);
4605
4606   if (gtk_text_iter_compare (&cursor, &bound) >= 0)
4607     {
4608       min = bound;
4609       max = cursor;
4610     }
4611   else
4612     {
4613       min = cursor;
4614       max = bound;
4615     }
4616
4617   if (mode != GTK_TEXT_HANDLE_MODE_NONE)
4618     gtk_text_view_set_handle_position (text_view, &max,
4619                                        GTK_TEXT_HANDLE_POSITION_SELECTION_END);
4620
4621   if (mode == GTK_TEXT_HANDLE_MODE_SELECTION)
4622     gtk_text_view_set_handle_position (text_view, &min,
4623                                        GTK_TEXT_HANDLE_POSITION_SELECTION_START);
4624 }
4625
4626 static gint
4627 gtk_text_view_event (GtkWidget *widget, GdkEvent *event)
4628 {
4629   GtkTextView *text_view;
4630   GtkTextViewPrivate *priv;
4631   gint x = 0, y = 0;
4632
4633   text_view = GTK_TEXT_VIEW (widget);
4634   priv = text_view->priv;
4635
4636   if (priv->layout == NULL ||
4637       get_buffer (text_view) == NULL)
4638     return FALSE;
4639
4640   if (event->any.window != priv->text_window->bin_window)
4641     return FALSE;
4642
4643   if (get_event_coordinates (event, &x, &y))
4644     {
4645       GtkTextIter iter;
4646
4647       x += priv->xoffset;
4648       y += priv->yoffset;
4649
4650       /* FIXME this is slow and we do it twice per event.
4651        * My favorite solution is to have GtkTextLayout cache
4652        * the last couple lookups.
4653        */
4654       gtk_text_layout_get_iter_at_pixel (priv->layout,
4655                                          &iter,
4656                                          x, y);
4657
4658       return emit_event_on_tags (widget, event, &iter);
4659     }
4660   else if (event->type == GDK_KEY_PRESS ||
4661            event->type == GDK_KEY_RELEASE)
4662     {
4663       GtkTextIter iter;
4664
4665       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter,
4666                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
4667
4668       return emit_event_on_tags (widget, event, &iter);
4669     }
4670   else
4671     return FALSE;
4672 }
4673
4674 static gint
4675 gtk_text_view_key_press_event (GtkWidget *widget, GdkEventKey *event)
4676 {
4677   GtkTextView *text_view;
4678   GtkTextViewPrivate *priv;
4679   GtkTextMark *insert;
4680   GtkTextIter iter;
4681   gboolean can_insert;
4682   gboolean retval = FALSE;
4683   gboolean obscure = FALSE;
4684
4685   text_view = GTK_TEXT_VIEW (widget);
4686   priv = text_view->priv;
4687   
4688   if (priv->layout == NULL ||
4689       get_buffer (text_view) == NULL)
4690     return FALSE;
4691
4692   /* Make sure input method knows where it is */
4693   flush_update_im_spot_location (text_view);
4694
4695   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4696   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4697   can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
4698   if (gtk_im_context_filter_keypress (priv->im_context, event))
4699     {
4700       priv->need_im_reset = TRUE;
4701       if (!can_insert)
4702         gtk_text_view_reset_im_context (text_view);
4703       obscure = can_insert;
4704       retval = TRUE;
4705     }
4706   /* Binding set */
4707   else if (GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_press_event (widget, event))
4708     {
4709       retval = TRUE;
4710     }
4711   /* use overall editability not can_insert, more predictable for users */
4712   else if (priv->editable &&
4713            (event->keyval == GDK_KEY_Return ||
4714             event->keyval == GDK_KEY_ISO_Enter ||
4715             event->keyval == GDK_KEY_KP_Enter))
4716     {
4717       /* this won't actually insert the newline if the cursor isn't
4718        * editable
4719        */
4720       gtk_text_view_reset_im_context (text_view);
4721       gtk_text_view_commit_text (text_view, "\n");
4722
4723       obscure = TRUE;
4724       retval = TRUE;
4725     }
4726   /* Pass through Tab as literal tab, unless Control is held down */
4727   else if ((event->keyval == GDK_KEY_Tab ||
4728             event->keyval == GDK_KEY_KP_Tab ||
4729             event->keyval == GDK_KEY_ISO_Left_Tab) &&
4730            !(event->state & GDK_CONTROL_MASK))
4731     {
4732       /* If the text widget isn't editable overall, or if the application
4733        * has turned off "accepts_tab", move the focus instead
4734        */
4735       if (priv->accepts_tab && priv->editable)
4736         {
4737           gtk_text_view_reset_im_context (text_view);
4738           gtk_text_view_commit_text (text_view, "\t");
4739           obscure = TRUE;
4740         }
4741       else
4742         g_signal_emit_by_name (text_view, "move-focus",
4743                                (event->state & GDK_SHIFT_MASK) ?
4744                                GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD);
4745
4746       retval = TRUE;
4747     }
4748   else
4749     retval = FALSE;
4750
4751   if (obscure)
4752     gtk_text_view_obscure_mouse_cursor (text_view);
4753   
4754   gtk_text_view_reset_blink_time (text_view);
4755   gtk_text_view_pend_cursor_blink (text_view);
4756
4757   _gtk_text_handle_set_mode (priv->text_handle,
4758                              GTK_TEXT_HANDLE_MODE_NONE);
4759
4760   return retval;
4761 }
4762
4763 static gint
4764 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
4765 {
4766   GtkTextView *text_view;
4767   GtkTextViewPrivate *priv;
4768   GtkTextMark *insert;
4769   GtkTextIter iter;
4770
4771   text_view = GTK_TEXT_VIEW (widget);
4772   priv = text_view->priv;
4773
4774   if (priv->layout == NULL || get_buffer (text_view) == NULL)
4775     return FALSE;
4776       
4777   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4778   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4779   if (gtk_text_iter_can_insert (&iter, priv->editable) &&
4780       gtk_im_context_filter_keypress (priv->im_context, event))
4781     {
4782       priv->need_im_reset = TRUE;
4783       return TRUE;
4784     }
4785   else
4786     return GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_release_event (widget, event);
4787 }
4788
4789 static gint
4790 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
4791 {
4792   GtkTextView *text_view;
4793   GtkTextViewPrivate *priv;
4794   GdkDevice *device;
4795   gboolean is_touchscreen;
4796
4797   text_view = GTK_TEXT_VIEW (widget);
4798   priv = text_view->priv;
4799
4800   gtk_widget_grab_focus (widget);
4801
4802   if (event->window != priv->text_window->bin_window)
4803     {
4804       /* Remove selection if any. */
4805       gtk_text_view_unselect (text_view);
4806       return FALSE;
4807     }
4808
4809   gtk_text_view_reset_blink_time (text_view);
4810
4811 #if 0
4812   /* debug hack */
4813   if (event->button == GDK_BUTTON_SECONDARY && (event->state & GDK_CONTROL_MASK) != 0)
4814     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
4815   else if (event->button == GDK_BUTTON_SECONDARY)
4816     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
4817 #endif
4818
4819   device = gdk_event_get_source_device ((GdkEvent *) event);
4820   is_touchscreen = test_touchscreen ||
4821                    gdk_device_get_source (device) == GDK_SOURCE_TOUCHSCREEN;
4822
4823   if (event->type == GDK_BUTTON_PRESS)
4824     {
4825       gtk_text_view_reset_im_context (text_view);
4826
4827       if (gdk_event_triggers_context_menu ((GdkEvent *) event))
4828         {
4829           gtk_text_view_do_popup (text_view, event);
4830           return TRUE;
4831         }
4832       else if (event->button == GDK_BUTTON_PRIMARY)
4833         {
4834           /* If we're in the selection, start a drag copy/move of the
4835            * selection; otherwise, start creating a new selection.
4836            */
4837           GtkTextIter iter;
4838           GtkTextIter start, end;
4839
4840           gtk_text_layout_get_iter_at_pixel (priv->layout,
4841                                              &iter,
4842                                              event->x + priv->xoffset,
4843                                              event->y + priv->yoffset);
4844
4845           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
4846                                                     &start, &end) &&
4847               gtk_text_iter_in_range (&iter, &start, &end) &&
4848               !(event->state &
4849                 gtk_widget_get_modifier_mask (widget,
4850                                               GDK_MODIFIER_INTENT_EXTEND_SELECTION)))
4851             {
4852               priv->grab_device = event->device;
4853               priv->drag_start_x = event->x;
4854               priv->drag_start_y = event->y;
4855               priv->pending_place_cursor_button = event->button;
4856             }
4857           else
4858             {
4859               GtkTextHandleMode mode;
4860
4861               gtk_text_view_start_selection_drag (text_view, &iter, event);
4862
4863               if (gtk_widget_is_sensitive (widget) && is_touchscreen)
4864                 mode = GTK_TEXT_HANDLE_MODE_CURSOR;
4865               else
4866                 mode = GTK_TEXT_HANDLE_MODE_NONE;
4867
4868               gtk_text_view_update_handles (text_view, mode);
4869             }
4870
4871           return TRUE;
4872         }
4873       else if (event->button == GDK_BUTTON_MIDDLE &&
4874                get_middle_click_paste (text_view))
4875         {
4876           GtkTextIter iter;
4877
4878           /* We do not want to scroll back to the insert iter when we paste
4879              with the middle button */
4880           priv->scroll_after_paste = FALSE;
4881
4882           gtk_text_layout_get_iter_at_pixel (priv->layout,
4883                                              &iter,
4884                                              event->x + priv->xoffset,
4885                                              event->y + priv->yoffset);
4886
4887           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4888                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
4889                                            &iter,
4890                                            priv->editable);
4891           return TRUE;
4892         }
4893     }
4894   else if ((event->type == GDK_2BUTTON_PRESS ||
4895             event->type == GDK_3BUTTON_PRESS) &&
4896            event->button == GDK_BUTTON_PRIMARY)
4897     {
4898       GtkTextIter iter;
4899       GtkTextHandleMode mode;
4900
4901       gtk_text_view_end_selection_drag (text_view);
4902
4903       gtk_text_layout_get_iter_at_pixel (priv->layout,
4904                                          &iter,
4905                                          event->x + priv->xoffset,
4906                                          event->y + priv->yoffset);
4907
4908       gtk_text_view_start_selection_drag (text_view, &iter, event);
4909
4910       if (gtk_widget_is_sensitive (widget) && is_touchscreen)
4911         mode = GTK_TEXT_HANDLE_MODE_SELECTION;
4912       else
4913         mode = GTK_TEXT_HANDLE_MODE_NONE;
4914
4915       gtk_text_view_update_handles (text_view, mode);
4916       return TRUE;
4917     }
4918
4919   return FALSE;
4920 }
4921
4922 static gint
4923 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
4924 {
4925   GtkTextView *text_view;
4926   GtkTextViewPrivate *priv;
4927
4928   text_view = GTK_TEXT_VIEW (widget);
4929   priv = text_view->priv;
4930
4931   if (event->window != priv->text_window->bin_window)
4932     return FALSE;
4933
4934   if (event->button == GDK_BUTTON_PRIMARY)
4935     {
4936       if (priv->drag_start_x >= 0)
4937         {
4938           priv->drag_start_x = -1;
4939           priv->drag_start_y = -1;
4940         }
4941
4942       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget)))
4943         return TRUE;
4944       else if (priv->pending_place_cursor_button == event->button)
4945         {
4946           GtkTextHandleMode mode;
4947           GdkDevice *device;
4948           GtkTextIter iter;
4949
4950           /* Unselect everything; we clicked inside selection, but
4951            * didn't move by the drag threshold, so just clear selection
4952            * and place cursor.
4953            */
4954           gtk_text_layout_get_iter_at_pixel (priv->layout,
4955                                              &iter,
4956                                              event->x + priv->xoffset,
4957                                              event->y + priv->yoffset);
4958
4959           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
4960           gtk_text_view_check_cursor_blink (text_view);
4961
4962           device = gdk_event_get_source_device ((GdkEvent *) event);
4963
4964           if (gtk_widget_is_sensitive (widget) &&
4965               (test_touchscreen ||
4966                gdk_device_get_source (device) == GDK_SOURCE_TOUCHSCREEN))
4967             mode = GTK_TEXT_HANDLE_MODE_CURSOR;
4968           else
4969             mode = GTK_TEXT_HANDLE_MODE_NONE;
4970
4971           gtk_text_view_update_handles (text_view, mode);
4972           priv->pending_place_cursor_button = 0;
4973
4974           return FALSE;
4975         }
4976     }
4977
4978   return FALSE;
4979 }
4980
4981 static void
4982 keymap_direction_changed (GdkKeymap   *keymap,
4983                           GtkTextView *text_view)
4984 {
4985   gtk_text_view_check_keymap_direction (text_view);
4986 }
4987
4988 static gint
4989 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
4990 {
4991   GtkTextView *text_view;
4992   GtkTextViewPrivate *priv;
4993
4994   text_view = GTK_TEXT_VIEW (widget);
4995   priv = text_view->priv;
4996
4997   gtk_widget_queue_draw (widget);
4998
4999   DV(g_print (G_STRLOC": focus_in_event\n"));
5000
5001   gtk_text_view_reset_blink_time (text_view);
5002
5003   if (priv->cursor_visible && priv->layout)
5004     {
5005       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5006       gtk_text_view_check_cursor_blink (text_view);
5007     }
5008
5009   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
5010                     "direction-changed",
5011                     G_CALLBACK (keymap_direction_changed), text_view);
5012   gtk_text_view_check_keymap_direction (text_view);
5013
5014   if (priv->editable)
5015     {
5016       priv->need_im_reset = TRUE;
5017       gtk_im_context_focus_in (priv->im_context);
5018     }
5019
5020   return FALSE;
5021 }
5022
5023 static gint
5024 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
5025 {
5026   GtkTextView *text_view;
5027   GtkTextViewPrivate *priv;
5028
5029   text_view = GTK_TEXT_VIEW (widget);
5030   priv = text_view->priv;
5031
5032   gtk_text_view_end_selection_drag (text_view);
5033
5034   gtk_widget_queue_draw (widget);
5035
5036   DV(g_print (G_STRLOC": focus_out_event\n"));
5037   
5038   if (priv->cursor_visible && priv->layout)
5039     {
5040       gtk_text_view_check_cursor_blink (text_view);
5041       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
5042     }
5043
5044   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
5045                                         keymap_direction_changed,
5046                                         text_view);
5047   _gtk_text_handle_set_mode (priv->text_handle,
5048                              GTK_TEXT_HANDLE_MODE_NONE);
5049
5050   if (priv->editable)
5051     {
5052       priv->need_im_reset = TRUE;
5053       gtk_im_context_focus_out (priv->im_context);
5054     }
5055
5056   return FALSE;
5057 }
5058
5059 static gint
5060 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
5061 {
5062   GtkTextView *text_view;
5063   GtkTextViewPrivate *priv;
5064
5065   text_view = GTK_TEXT_VIEW (widget);
5066   priv = text_view->priv;
5067
5068   gtk_text_view_unobscure_mouse_cursor (text_view);
5069
5070   if (event->window == priv->text_window->bin_window &&
5071       priv->drag_start_x >= 0)
5072     {
5073       gint x = event->x;
5074       gint y = event->y;
5075
5076       gdk_event_request_motions (event);
5077
5078       if (gtk_drag_check_threshold (widget,
5079                                     priv->drag_start_x, 
5080                                     priv->drag_start_y,
5081                                     x, y))
5082         {
5083           GtkTextIter iter;
5084           gint buffer_x, buffer_y;
5085
5086           gtk_text_view_window_to_buffer_coords (text_view,
5087                                                  GTK_TEXT_WINDOW_TEXT,
5088                                                  priv->drag_start_x,
5089                                                  priv->drag_start_y,
5090                                                  &buffer_x,
5091                                                  &buffer_y);
5092
5093           gtk_text_layout_get_iter_at_pixel (priv->layout,
5094                                              &iter,
5095                                              buffer_x, buffer_y);
5096
5097           gtk_text_view_start_selection_dnd (text_view, &iter, event);
5098           return TRUE;
5099         }
5100     }
5101
5102   return FALSE;
5103 }
5104
5105 static void
5106 gtk_text_view_paint (GtkWidget      *widget,
5107                      cairo_t        *cr)
5108 {
5109   GtkTextView *text_view;
5110   GtkTextViewPrivate *priv;
5111   
5112   text_view = GTK_TEXT_VIEW (widget);
5113   priv = text_view->priv;
5114
5115   g_return_if_fail (priv->layout != NULL);
5116   g_return_if_fail (priv->xoffset >= 0);
5117   g_return_if_fail (priv->yoffset >= 0);
5118
5119   while (priv->first_validate_idle != 0)
5120     {
5121       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
5122                    priv->first_validate_idle));
5123       gtk_text_view_flush_first_validate (text_view);
5124     }
5125
5126   if (!priv->onscreen_validated)
5127     {
5128       g_warning (G_STRLOC ": somehow some text lines were modified or scrolling occurred since the last validation of lines on the screen - may be a text widget bug.");
5129       g_assert_not_reached ();
5130     }
5131   
5132 #if 0
5133   printf ("painting %d,%d  %d x %d\n",
5134           area->x, area->y,
5135           area->width, area->height);
5136 #endif
5137
5138   cairo_save (cr);
5139   cairo_translate (cr, -priv->xoffset, -priv->yoffset);
5140
5141   gtk_text_layout_draw (priv->layout,
5142                         widget,
5143                         cr,
5144                         NULL);
5145
5146   cairo_restore (cr);
5147 }
5148
5149 static gboolean
5150 gtk_text_view_draw (GtkWidget *widget,
5151                     cairo_t   *cr)
5152 {
5153   GSList *tmp_list;
5154   GdkWindow *window;
5155   
5156   if (gtk_cairo_should_draw_window (cr, gtk_widget_get_window (widget)))
5157     gtk_text_view_draw_focus (widget, cr);
5158
5159   window = gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
5160                                      GTK_TEXT_WINDOW_TEXT);
5161   if (gtk_cairo_should_draw_window (cr, window))
5162     {
5163       DV(g_print (">Exposed ("G_STRLOC")\n"));
5164       cairo_save (cr);
5165       gtk_cairo_transform_to_window (cr, widget, window);
5166       gtk_text_view_paint (widget, cr);
5167       cairo_restore (cr);
5168     }
5169
5170   /* Propagate exposes to all unanchored children. 
5171    * Anchored children are handled in gtk_text_view_paint(). 
5172    */
5173   tmp_list = GTK_TEXT_VIEW (widget)->priv->children;
5174   while (tmp_list != NULL)
5175     {
5176       GtkTextViewChild *vc = tmp_list->data;
5177
5178       /* propagate_draw checks that event->window matches
5179        * child->window
5180        */
5181       gtk_container_propagate_draw (GTK_CONTAINER (widget),
5182                                     vc->widget,
5183                                     cr);
5184       
5185       tmp_list = tmp_list->next;
5186     }
5187   
5188   return FALSE;
5189 }
5190
5191 static void
5192 gtk_text_view_draw_focus (GtkWidget *widget,
5193                           cairo_t   *cr)
5194 {
5195   gboolean interior_focus;
5196
5197   /* We clear the focus if we are in interior focus mode. */
5198   gtk_widget_style_get (widget,
5199                         "interior-focus", &interior_focus,
5200                         NULL);
5201   
5202   if (gtk_widget_has_visible_focus (widget) && !interior_focus)
5203     {
5204       GtkStyleContext *context;
5205
5206       context = gtk_widget_get_style_context (widget);
5207
5208       gtk_render_focus (context, cr, 0, 0,
5209                         gtk_widget_get_allocated_width (widget),
5210                         gtk_widget_get_allocated_height (widget));
5211     }
5212 }
5213
5214 static gboolean
5215 gtk_text_view_focus (GtkWidget        *widget,
5216                      GtkDirectionType  direction)
5217 {
5218   GtkContainer *container;
5219   gboolean result;
5220   
5221   container = GTK_CONTAINER (widget);  
5222
5223   if (!gtk_widget_is_focus (widget) &&
5224       gtk_container_get_focus_child (container) == NULL)
5225     {
5226       gtk_widget_grab_focus (widget);
5227       return TRUE;
5228     }
5229   else
5230     {
5231       /*
5232        * Unset CAN_FOCUS flag so that gtk_container_focus() allows
5233        * children to get the focus
5234        */
5235       gtk_widget_set_can_focus (widget, FALSE);
5236       result = GTK_WIDGET_CLASS (gtk_text_view_parent_class)->focus (widget, direction);
5237       gtk_widget_set_can_focus (widget, TRUE);
5238
5239       return result;
5240     }
5241 }
5242
5243 /*
5244  * Container
5245  */
5246
5247 static void
5248 gtk_text_view_add (GtkContainer *container,
5249                    GtkWidget    *child)
5250 {
5251   /* This is pretty random. */
5252   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
5253                                      child,
5254                                      GTK_TEXT_WINDOW_WIDGET,
5255                                      0, 0);
5256 }
5257
5258 static void
5259 gtk_text_view_remove (GtkContainer *container,
5260                       GtkWidget    *child)
5261 {
5262   GtkTextView *text_view;
5263   GtkTextViewPrivate *priv;
5264   GtkTextViewChild *vc;
5265   GSList *iter;
5266
5267   text_view = GTK_TEXT_VIEW (container);
5268   priv = text_view->priv;
5269
5270   vc = NULL;
5271   iter = priv->children;
5272
5273   while (iter != NULL)
5274     {
5275       vc = iter->data;
5276
5277       if (vc->widget == child)
5278         break;
5279
5280       iter = g_slist_next (iter);
5281     }
5282
5283   g_assert (iter != NULL); /* be sure we had the child in the list */
5284
5285   priv->children = g_slist_remove (priv->children, vc);
5286
5287   gtk_widget_unparent (vc->widget);
5288
5289   text_view_child_free (vc);
5290 }
5291
5292 static void
5293 gtk_text_view_forall (GtkContainer *container,
5294                       gboolean      include_internals,
5295                       GtkCallback   callback,
5296                       gpointer      callback_data)
5297 {
5298   GSList *iter;
5299   GtkTextView *text_view;
5300   GSList *copy;
5301
5302   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
5303   g_return_if_fail (callback != NULL);
5304
5305   text_view = GTK_TEXT_VIEW (container);
5306
5307   copy = g_slist_copy (text_view->priv->children);
5308   iter = copy;
5309
5310   while (iter != NULL)
5311     {
5312       GtkTextViewChild *vc = iter->data;
5313
5314       (* callback) (vc->widget, callback_data);
5315
5316       iter = g_slist_next (iter);
5317     }
5318
5319   g_slist_free (copy);
5320 }
5321
5322 #define CURSOR_ON_MULTIPLIER 2
5323 #define CURSOR_OFF_MULTIPLIER 1
5324 #define CURSOR_PEND_MULTIPLIER 3
5325 #define CURSOR_DIVIDER 3
5326
5327 static gboolean
5328 cursor_blinks (GtkTextView *text_view)
5329 {
5330   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5331   gboolean blink;
5332
5333 #ifdef DEBUG_VALIDATION_AND_SCROLLING
5334   return FALSE;
5335 #endif
5336   if (gtk_get_debug_flags () & GTK_DEBUG_UPDATES)
5337     return FALSE;
5338
5339   g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
5340
5341   if (!blink)
5342     return FALSE;
5343
5344   if (text_view->priv->editable)
5345     {
5346       GtkTextMark *insert;
5347       GtkTextIter iter;
5348       
5349       insert = gtk_text_buffer_get_insert (get_buffer (text_view));
5350       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
5351       
5352       if (gtk_text_iter_editable (&iter, text_view->priv->editable))
5353         return blink;
5354     }
5355
5356   return FALSE;
5357 }
5358
5359 static gboolean
5360 get_middle_click_paste (GtkTextView *text_view)
5361 {
5362   GtkSettings *settings;
5363   gboolean paste;
5364
5365   settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5366   g_object_get (settings, "gtk-enable-primary-paste", &paste, NULL);
5367
5368   return paste;
5369 }
5370
5371 static gint
5372 get_cursor_time (GtkTextView *text_view)
5373 {
5374   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5375   gint time;
5376
5377   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
5378
5379   return time;
5380 }
5381
5382 static gint
5383 get_cursor_blink_timeout (GtkTextView *text_view)
5384 {
5385   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5386   gint time;
5387
5388   g_object_get (settings, "gtk-cursor-blink-timeout", &time, NULL);
5389
5390   return time;
5391 }
5392
5393
5394 /*
5395  * Blink!
5396  */
5397
5398 static gint
5399 blink_cb (gpointer data)
5400 {
5401   GtkTextView *text_view;
5402   GtkTextViewPrivate *priv;
5403   gboolean visible;
5404   gint blink_timeout;
5405
5406   text_view = GTK_TEXT_VIEW (data);
5407   priv = text_view->priv;
5408
5409   if (!gtk_widget_has_focus (GTK_WIDGET (text_view)))
5410     {
5411       g_warning ("GtkTextView - did not receive focus-out-event. If you\n"
5412                  "connect a handler to this signal, it must return\n"
5413                  "FALSE so the text view gets the event as well");
5414
5415       gtk_text_view_check_cursor_blink (text_view);
5416
5417       return FALSE;
5418     }
5419
5420   g_assert (priv->layout);
5421   g_assert (priv->cursor_visible);
5422
5423   visible = gtk_text_layout_get_cursor_visible (priv->layout);
5424
5425   blink_timeout = get_cursor_blink_timeout (text_view);
5426   if (priv->blink_time > 1000 * blink_timeout &&
5427       blink_timeout < G_MAXINT/1000) 
5428     {
5429       /* we've blinked enough without the user doing anything, stop blinking */
5430       visible = 0;
5431       priv->blink_timeout = 0;
5432     } 
5433   else if (visible)
5434     priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5435                                                    blink_cb,
5436                                                    text_view);
5437   else 
5438     {
5439       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_ON_MULTIPLIER / CURSOR_DIVIDER,
5440                                                      blink_cb,
5441                                                      text_view);
5442       priv->blink_time += get_cursor_time (text_view);
5443     }
5444
5445   /* Block changed_handler while changing the layout's cursor visibility
5446    * because it would expose the whole paragraph. Instead, we expose
5447    * the cursor's area(s) manually below.
5448    */
5449   g_signal_handlers_block_by_func (priv->layout,
5450                                    changed_handler,
5451                                    text_view);
5452   gtk_text_layout_set_cursor_visible (priv->layout, !visible);
5453   g_signal_handlers_unblock_by_func (priv->layout,
5454                                      changed_handler,
5455                                      text_view);
5456
5457   text_window_invalidate_cursors (priv->text_window);
5458
5459   /* Remove ourselves */
5460   return FALSE;
5461 }
5462
5463
5464 static void
5465 gtk_text_view_stop_cursor_blink (GtkTextView *text_view)
5466 {
5467   if (text_view->priv->blink_timeout)
5468     { 
5469       g_source_remove (text_view->priv->blink_timeout);
5470       text_view->priv->blink_timeout = 0;
5471     }
5472 }
5473
5474 static void
5475 gtk_text_view_check_cursor_blink (GtkTextView *text_view)
5476 {
5477   GtkTextViewPrivate *priv = text_view->priv;
5478
5479   if (priv->layout != NULL &&
5480       priv->cursor_visible &&
5481       gtk_widget_has_focus (GTK_WIDGET (text_view)))
5482     {
5483       if (cursor_blinks (text_view))
5484         {
5485           if (priv->blink_timeout == 0)
5486             {
5487               gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5488               
5489               priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5490                                                              blink_cb,
5491                                                              text_view);
5492             }
5493         }
5494       else
5495         {
5496           gtk_text_view_stop_cursor_blink (text_view);
5497           gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5498         }
5499     }
5500   else
5501     {
5502       gtk_text_view_stop_cursor_blink (text_view);
5503       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
5504     }
5505 }
5506
5507 static void
5508 gtk_text_view_pend_cursor_blink (GtkTextView *text_view)
5509 {
5510   GtkTextViewPrivate *priv = text_view->priv;
5511
5512   if (priv->layout != NULL &&
5513       priv->cursor_visible &&
5514       gtk_widget_has_focus (GTK_WIDGET (text_view)) &&
5515       cursor_blinks (text_view))
5516     {
5517       gtk_text_view_stop_cursor_blink (text_view);
5518       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5519       
5520       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_PEND_MULTIPLIER / CURSOR_DIVIDER,
5521                                                      blink_cb,
5522                                                      text_view);
5523     }
5524 }
5525
5526 static void
5527 gtk_text_view_reset_blink_time (GtkTextView *text_view)
5528 {
5529   GtkTextViewPrivate *priv = text_view->priv;
5530
5531   priv->blink_time = 0;
5532 }
5533
5534
5535 /*
5536  * Key binding handlers
5537  */
5538
5539 static gboolean
5540 gtk_text_view_move_iter_by_lines (GtkTextView *text_view,
5541                                   GtkTextIter *newplace,
5542                                   gint         count)
5543 {
5544   gboolean ret = TRUE;
5545
5546   while (count < 0)
5547     {
5548       ret = gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, newplace);
5549       count++;
5550     }
5551
5552   while (count > 0)
5553     {
5554       ret = gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, newplace);
5555       count--;
5556     }
5557
5558   return ret;
5559 }
5560
5561 static void
5562 move_cursor (GtkTextView       *text_view,
5563              const GtkTextIter *new_location,
5564              gboolean           extend_selection)
5565 {
5566   if (extend_selection)
5567     gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
5568                                        "insert",
5569                                        new_location);
5570   else
5571       gtk_text_buffer_place_cursor (get_buffer (text_view),
5572                                     new_location);
5573   gtk_text_view_check_cursor_blink (text_view);
5574 }
5575
5576 static void
5577 gtk_text_view_move_cursor_internal (GtkTextView     *text_view,
5578                                     GtkMovementStep  step,
5579                                     gint             count,
5580                                     gboolean         extend_selection)
5581 {
5582   GtkTextViewPrivate *priv;
5583   GtkTextIter insert;
5584   GtkTextIter newplace;
5585   gboolean cancel_selection = FALSE;
5586   gint cursor_x_pos = 0;
5587   GtkDirectionType leave_direction = -1;
5588
5589   priv = text_view->priv;
5590
5591   if (!priv->cursor_visible) 
5592     {
5593       GtkScrollStep scroll_step;
5594       gdouble old_xpos, old_ypos;
5595
5596       switch (step) 
5597         {
5598         case GTK_MOVEMENT_VISUAL_POSITIONS:
5599           leave_direction = count > 0 ? GTK_DIR_RIGHT : GTK_DIR_LEFT;
5600           /* fall through */
5601         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5602         case GTK_MOVEMENT_WORDS:
5603           scroll_step = GTK_SCROLL_HORIZONTAL_STEPS;
5604           break;
5605         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5606           scroll_step = GTK_SCROLL_HORIZONTAL_ENDS;
5607           break;          
5608         case GTK_MOVEMENT_DISPLAY_LINES:
5609           leave_direction = count > 0 ? GTK_DIR_DOWN : GTK_DIR_UP;
5610           /* fall through */
5611         case GTK_MOVEMENT_PARAGRAPHS:
5612         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5613           scroll_step = GTK_SCROLL_STEPS;
5614           break;
5615         case GTK_MOVEMENT_PAGES:
5616           scroll_step = GTK_SCROLL_PAGES;
5617           break;
5618         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5619           scroll_step = GTK_SCROLL_HORIZONTAL_PAGES;
5620           break;
5621         case GTK_MOVEMENT_BUFFER_ENDS:
5622           scroll_step = GTK_SCROLL_ENDS;
5623           break;
5624         default:
5625           scroll_step = GTK_SCROLL_PAGES;
5626           break;
5627         }
5628
5629       old_xpos = priv->xoffset;
5630       old_ypos = priv->yoffset;
5631       gtk_text_view_move_viewport (text_view, scroll_step, count);
5632       if ((old_xpos == priv->xoffset && old_ypos == priv->yoffset) &&
5633           leave_direction != -1 &&
5634           !gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5635                                      leave_direction))
5636         {
5637           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5638         }
5639
5640       return;
5641     }
5642
5643   gtk_text_view_reset_im_context (text_view);
5644
5645   if (step == GTK_MOVEMENT_PAGES)
5646     {
5647       if (!gtk_text_view_scroll_pages (text_view, count, extend_selection))
5648         gtk_widget_error_bell (GTK_WIDGET (text_view));
5649
5650       gtk_text_view_check_cursor_blink (text_view);
5651       gtk_text_view_pend_cursor_blink (text_view);
5652       return;
5653     }
5654   else if (step == GTK_MOVEMENT_HORIZONTAL_PAGES)
5655     {
5656       if (!gtk_text_view_scroll_hpages (text_view, count, extend_selection))
5657         gtk_widget_error_bell (GTK_WIDGET (text_view));
5658
5659       gtk_text_view_check_cursor_blink (text_view);
5660       gtk_text_view_pend_cursor_blink (text_view);
5661       return;
5662     }
5663
5664   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5665                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5666
5667   if (! extend_selection)
5668     {
5669       GtkTextIter sel_bound;
5670
5671       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &sel_bound,
5672                                         gtk_text_buffer_get_selection_bound (get_buffer (text_view)));
5673
5674       /* if we move forward, assume the cursor is at the end of the selection;
5675        * if we move backward, assume the cursor is at the start
5676        */
5677       if (count > 0)
5678         gtk_text_iter_order (&sel_bound, &insert);
5679       else
5680         gtk_text_iter_order (&insert, &sel_bound);
5681
5682       /* if we actually have a selection, just move *to* the beginning/end
5683        * of the selection and not *from* there on LOGICAL_POSITIONS
5684        * and VISUAL_POSITIONS movement
5685        */
5686       if (! gtk_text_iter_equal (&sel_bound, &insert))
5687         cancel_selection = TRUE;
5688     }
5689
5690   newplace = insert;
5691
5692   if (step == GTK_MOVEMENT_DISPLAY_LINES)
5693     gtk_text_view_get_virtual_cursor_pos (text_view, &insert, &cursor_x_pos, NULL);
5694
5695   switch (step)
5696     {
5697     case GTK_MOVEMENT_LOGICAL_POSITIONS:
5698       if (! cancel_selection)
5699         gtk_text_iter_forward_visible_cursor_positions (&newplace, count);
5700       break;
5701
5702     case GTK_MOVEMENT_VISUAL_POSITIONS:
5703       if (! cancel_selection)
5704         gtk_text_layout_move_iter_visually (priv->layout,
5705                                             &newplace, count);
5706       break;
5707
5708     case GTK_MOVEMENT_WORDS:
5709       if (count < 0)
5710         gtk_text_iter_backward_visible_word_starts (&newplace, -count);
5711       else if (count > 0) 
5712         {
5713           if (!gtk_text_iter_forward_visible_word_ends (&newplace, count))
5714             gtk_text_iter_forward_to_line_end (&newplace);
5715         }
5716       break;
5717
5718     case GTK_MOVEMENT_DISPLAY_LINES:
5719       if (count < 0)
5720         {
5721           leave_direction = GTK_DIR_UP;
5722
5723           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5724             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5725           else
5726             gtk_text_iter_set_line_offset (&newplace, 0);
5727         }
5728       if (count > 0)
5729         {
5730           leave_direction = GTK_DIR_DOWN;
5731
5732           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5733             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5734           else
5735             gtk_text_iter_forward_to_line_end (&newplace);
5736         }
5737       break;
5738
5739     case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5740       if (count > 1)
5741         gtk_text_view_move_iter_by_lines (text_view, &newplace, --count);
5742       else if (count < -1)
5743         gtk_text_view_move_iter_by_lines (text_view, &newplace, ++count);
5744
5745       if (count != 0)
5746         gtk_text_layout_move_iter_to_line_end (priv->layout, &newplace, count);
5747       break;
5748
5749     case GTK_MOVEMENT_PARAGRAPHS:
5750       if (count > 0)
5751         {
5752           if (!gtk_text_iter_ends_line (&newplace))
5753             {
5754               gtk_text_iter_forward_to_line_end (&newplace);
5755               --count;
5756             }
5757           gtk_text_iter_forward_visible_lines (&newplace, count);
5758           gtk_text_iter_forward_to_line_end (&newplace);
5759         }
5760       else if (count < 0)
5761         {
5762           if (gtk_text_iter_get_line_offset (&newplace) > 0)
5763             gtk_text_iter_set_line_offset (&newplace, 0);
5764           gtk_text_iter_forward_visible_lines (&newplace, count);
5765           gtk_text_iter_set_line_offset (&newplace, 0);
5766         }
5767       break;
5768
5769     case GTK_MOVEMENT_PARAGRAPH_ENDS:
5770       if (count > 0)
5771         {
5772           if (!gtk_text_iter_ends_line (&newplace))
5773             gtk_text_iter_forward_to_line_end (&newplace);
5774         }
5775       else if (count < 0)
5776         {
5777           gtk_text_iter_set_line_offset (&newplace, 0);
5778         }
5779       break;
5780
5781     case GTK_MOVEMENT_BUFFER_ENDS:
5782       if (count > 0)
5783         gtk_text_buffer_get_end_iter (get_buffer (text_view), &newplace);
5784       else if (count < 0)
5785         gtk_text_buffer_get_iter_at_offset (get_buffer (text_view), &newplace, 0);
5786      break;
5787       
5788     default:
5789       break;
5790     }
5791
5792   /* call move_cursor() even if the cursor hasn't moved, since it 
5793      cancels the selection
5794   */
5795   move_cursor (text_view, &newplace, extend_selection);
5796
5797   if (!gtk_text_iter_equal (&insert, &newplace))
5798     {
5799       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5800       gtk_text_view_scroll_mark_onscreen (text_view,
5801                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5802
5803       if (step == GTK_MOVEMENT_DISPLAY_LINES)
5804         gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, -1);
5805     }
5806   else if (leave_direction != -1)
5807     {
5808       if (!gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5809                                      leave_direction))
5810         {
5811           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5812         }
5813     }
5814   else if (! cancel_selection)
5815     {
5816       gtk_widget_error_bell (GTK_WIDGET (text_view));
5817     }
5818
5819   gtk_text_view_check_cursor_blink (text_view);
5820   gtk_text_view_pend_cursor_blink (text_view);
5821 }
5822
5823 static void
5824 gtk_text_view_move_cursor (GtkTextView     *text_view,
5825                            GtkMovementStep  step,
5826                            gint             count,
5827                            gboolean         extend_selection)
5828 {
5829   gtk_text_view_move_cursor_internal (text_view, step, count, extend_selection);
5830 }
5831
5832 static void
5833 gtk_text_view_move_viewport (GtkTextView     *text_view,
5834                              GtkScrollStep    step,
5835                              gint             count)
5836 {
5837   GtkAdjustment *adjustment;
5838   gdouble increment;
5839   
5840   switch (step) 
5841     {
5842     case GTK_SCROLL_STEPS:
5843     case GTK_SCROLL_PAGES:
5844     case GTK_SCROLL_ENDS:
5845       adjustment = text_view->priv->vadjustment;
5846       break;
5847     case GTK_SCROLL_HORIZONTAL_STEPS:
5848     case GTK_SCROLL_HORIZONTAL_PAGES:
5849     case GTK_SCROLL_HORIZONTAL_ENDS:
5850       adjustment = text_view->priv->hadjustment;
5851       break;
5852     default:
5853       adjustment = text_view->priv->vadjustment;
5854       break;
5855     }
5856
5857   switch (step) 
5858     {
5859     case GTK_SCROLL_STEPS:
5860     case GTK_SCROLL_HORIZONTAL_STEPS:
5861       increment = gtk_adjustment_get_step_increment (adjustment);
5862       break;
5863     case GTK_SCROLL_PAGES:
5864     case GTK_SCROLL_HORIZONTAL_PAGES:
5865       increment = gtk_adjustment_get_page_increment (adjustment);
5866       break;
5867     case GTK_SCROLL_ENDS:
5868     case GTK_SCROLL_HORIZONTAL_ENDS:
5869       increment = gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_lower (adjustment);
5870       break;
5871     default:
5872       increment = 0.0;
5873       break;
5874     }
5875
5876   gtk_adjustment_set_value (adjustment, gtk_adjustment_get_value (adjustment) + count * increment);
5877 }
5878
5879 static void
5880 gtk_text_view_set_anchor (GtkTextView *text_view)
5881 {
5882   GtkTextIter insert;
5883
5884   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5885                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5886
5887   gtk_text_buffer_create_mark (get_buffer (text_view), "anchor", &insert, TRUE);
5888 }
5889
5890 static gboolean
5891 gtk_text_view_scroll_pages (GtkTextView *text_view,
5892                             gint         count,
5893                             gboolean     extend_selection)
5894 {
5895   GtkTextViewPrivate *priv;
5896   GtkAdjustment *adjustment;
5897   gint cursor_x_pos, cursor_y_pos;
5898   GtkTextMark *insert_mark;
5899   GtkTextIter old_insert;
5900   GtkTextIter new_insert;
5901   GtkTextIter anchor;
5902   gdouble newval;
5903   gdouble oldval;
5904   gint y0, y1;
5905
5906   priv = text_view->priv;
5907
5908   g_return_val_if_fail (priv->vadjustment != NULL, FALSE);
5909   
5910   adjustment = priv->vadjustment;
5911
5912   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5913
5914   /* Make sure we start from the current cursor position, even
5915    * if it was offscreen, but don't queue more scrolls if we're
5916    * already behind.
5917    */
5918   if (priv->pending_scroll)
5919     cancel_pending_scroll (text_view);
5920   else
5921     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5922
5923   /* Validate the region that will be brought into view by the cursor motion
5924    */
5925   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5926                                     &old_insert, insert_mark);
5927
5928   if (count < 0)
5929     {
5930       gtk_text_view_get_first_para_iter (text_view, &anchor);
5931       y0 = gtk_adjustment_get_page_size (adjustment);
5932       y1 = gtk_adjustment_get_page_size (adjustment) + count * gtk_adjustment_get_page_increment (adjustment);
5933     }
5934   else
5935     {
5936       gtk_text_view_get_first_para_iter (text_view, &anchor);
5937       y0 = count * gtk_adjustment_get_page_increment (adjustment) + gtk_adjustment_get_page_size (adjustment);
5938       y1 = 0;
5939     }
5940
5941   gtk_text_layout_validate_yrange (priv->layout, &anchor, y0, y1);
5942   /* FIXME do we need to update the adjustment ranges here? */
5943
5944   new_insert = old_insert;
5945
5946   if (count < 0 && gtk_adjustment_get_value (adjustment) <= (gtk_adjustment_get_lower (adjustment) + 1e-12))
5947     {
5948       /* already at top, just be sure we are at offset 0 */
5949       gtk_text_buffer_get_start_iter (get_buffer (text_view), &new_insert);
5950       move_cursor (text_view, &new_insert, extend_selection);
5951     }
5952   else if (count > 0 && gtk_adjustment_get_value (adjustment) >= (gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment) - 1e-12))
5953     {
5954       /* already at bottom, just be sure we are at the end */
5955       gtk_text_buffer_get_end_iter (get_buffer (text_view), &new_insert);
5956       move_cursor (text_view, &new_insert, extend_selection);
5957     }
5958   else
5959     {
5960       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
5961
5962       oldval = gtk_adjustment_get_value (adjustment);
5963       newval = gtk_adjustment_get_value (adjustment);
5964
5965       newval += count * gtk_adjustment_get_page_increment (adjustment);
5966
5967       gtk_adjustment_set_value (adjustment, newval);
5968       cursor_y_pos += gtk_adjustment_get_value (adjustment) - oldval;
5969
5970       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5971       clamp_iter_onscreen (text_view, &new_insert);
5972       move_cursor (text_view, &new_insert, extend_selection);
5973
5974       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5975     }
5976   
5977   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5978    * only guarantees 1 pixel onscreen.
5979    */
5980   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5981   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5982
5983   return !gtk_text_iter_equal (&old_insert, &new_insert);
5984 }
5985
5986 static gboolean
5987 gtk_text_view_scroll_hpages (GtkTextView *text_view,
5988                              gint         count,
5989                              gboolean     extend_selection)
5990 {
5991   GtkTextViewPrivate *priv;
5992   GtkAdjustment *adjustment;
5993   gint cursor_x_pos, cursor_y_pos;
5994   GtkTextMark *insert_mark;
5995   GtkTextIter old_insert;
5996   GtkTextIter new_insert;
5997   gdouble newval;
5998   gdouble oldval;
5999   gint y, height;
6000
6001   priv = text_view->priv;
6002
6003   g_return_val_if_fail (priv->hadjustment != NULL, FALSE);
6004
6005   adjustment = priv->hadjustment;
6006
6007   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
6008
6009   /* Make sure we start from the current cursor position, even
6010    * if it was offscreen, but don't queue more scrolls if we're
6011    * already behind.
6012    */
6013   if (priv->pending_scroll)
6014     cancel_pending_scroll (text_view);
6015   else
6016     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
6017
6018   /* Validate the line that we're moving within.
6019    */
6020   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6021                                     &old_insert, insert_mark);
6022
6023   gtk_text_layout_get_line_yrange (priv->layout, &old_insert, &y, &height);
6024   gtk_text_layout_validate_yrange (priv->layout, &old_insert, y, y + height);
6025   /* FIXME do we need to update the adjustment ranges here? */
6026
6027   new_insert = old_insert;
6028
6029   if (count < 0 && gtk_adjustment_get_value (adjustment) <= (gtk_adjustment_get_lower (adjustment) + 1e-12))
6030     {
6031       /* already at far left, just be sure we are at offset 0 */
6032       gtk_text_iter_set_line_offset (&new_insert, 0);
6033       move_cursor (text_view, &new_insert, extend_selection);
6034     }
6035   else if (count > 0 && gtk_adjustment_get_value (adjustment) >= (gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment) - 1e-12))
6036     {
6037       /* already at far right, just be sure we are at the end */
6038       if (!gtk_text_iter_ends_line (&new_insert))
6039           gtk_text_iter_forward_to_line_end (&new_insert);
6040       move_cursor (text_view, &new_insert, extend_selection);
6041     }
6042   else
6043     {
6044       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
6045
6046       oldval = gtk_adjustment_get_value (adjustment);
6047       newval = gtk_adjustment_get_value (adjustment);
6048
6049       newval += count * gtk_adjustment_get_page_increment (adjustment);
6050
6051       gtk_adjustment_set_value (adjustment, newval);
6052       cursor_x_pos += gtk_adjustment_get_value (adjustment) - oldval;
6053
6054       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
6055       clamp_iter_onscreen (text_view, &new_insert);
6056       move_cursor (text_view, &new_insert, extend_selection);
6057
6058       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
6059     }
6060
6061   /*  FIXME for lines shorter than the overall widget width, this results in a
6062    *  "bounce" effect as we scroll to the right of the widget, then scroll
6063    *  back to get the end of the line onscreen.
6064    *      http://bugzilla.gnome.org/show_bug.cgi?id=68963
6065    */
6066   
6067   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
6068    * only guarantees 1 pixel onscreen.
6069    */
6070   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6071   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
6072
6073   return !gtk_text_iter_equal (&old_insert, &new_insert);
6074 }
6075
6076 static gboolean
6077 whitespace (gunichar ch, gpointer user_data)
6078 {
6079   return (ch == ' ' || ch == '\t');
6080 }
6081
6082 static gboolean
6083 not_whitespace (gunichar ch, gpointer user_data)
6084 {
6085   return !whitespace (ch, user_data);
6086 }
6087
6088 static gboolean
6089 find_whitepace_region (const GtkTextIter *center,
6090                        GtkTextIter *start, GtkTextIter *end)
6091 {
6092   *start = *center;
6093   *end = *center;
6094
6095   if (gtk_text_iter_backward_find_char (start, not_whitespace, NULL, NULL))
6096     gtk_text_iter_forward_char (start); /* we want the first whitespace... */
6097   if (whitespace (gtk_text_iter_get_char (end), NULL))
6098     gtk_text_iter_forward_find_char (end, not_whitespace, NULL, NULL);
6099
6100   return !gtk_text_iter_equal (start, end);
6101 }
6102
6103 static void
6104 gtk_text_view_insert_at_cursor (GtkTextView *text_view,
6105                                 const gchar *str)
6106 {
6107   if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
6108                                                      text_view->priv->editable))
6109     {
6110       gtk_widget_error_bell (GTK_WIDGET (text_view));
6111     }
6112 }
6113
6114 static void
6115 gtk_text_view_delete_from_cursor (GtkTextView   *text_view,
6116                                   GtkDeleteType  type,
6117                                   gint           count)
6118 {
6119   GtkTextViewPrivate *priv;
6120   GtkTextIter insert;
6121   GtkTextIter start;
6122   GtkTextIter end;
6123   gboolean leave_one = FALSE;
6124
6125   priv = text_view->priv;
6126
6127   gtk_text_view_reset_im_context (text_view);
6128
6129   if (type == GTK_DELETE_CHARS)
6130     {
6131       /* Char delete deletes the selection, if one exists */
6132       if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
6133                                             priv->editable))
6134         return;
6135     }
6136
6137   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6138                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6139
6140   start = insert;
6141   end = insert;
6142
6143   switch (type)
6144     {
6145     case GTK_DELETE_CHARS:
6146       gtk_text_iter_forward_cursor_positions (&end, count);
6147       break;
6148
6149     case GTK_DELETE_WORD_ENDS:
6150       if (count > 0)
6151         gtk_text_iter_forward_word_ends (&end, count);
6152       else if (count < 0)
6153         gtk_text_iter_backward_word_starts (&start, 0 - count);
6154       break;
6155
6156     case GTK_DELETE_WORDS:
6157       break;
6158
6159     case GTK_DELETE_DISPLAY_LINE_ENDS:
6160       break;
6161
6162     case GTK_DELETE_DISPLAY_LINES:
6163       break;
6164
6165     case GTK_DELETE_PARAGRAPH_ENDS:
6166       if (count > 0)
6167         {
6168           /* If we're already at a newline, we need to
6169            * simply delete that newline, instead of
6170            * moving to the next one.
6171            */
6172           if (gtk_text_iter_ends_line (&end))
6173             {
6174               gtk_text_iter_forward_line (&end);
6175               --count;
6176             }
6177
6178           while (count > 0)
6179             {
6180               if (!gtk_text_iter_forward_to_line_end (&end))
6181                 break;
6182
6183               --count;
6184             }
6185         }
6186       else if (count < 0)
6187         {
6188           if (gtk_text_iter_starts_line (&start))
6189             {
6190               gtk_text_iter_backward_line (&start);
6191               if (!gtk_text_iter_ends_line (&end))
6192                 gtk_text_iter_forward_to_line_end (&start);
6193             }
6194           else
6195             {
6196               gtk_text_iter_set_line_offset (&start, 0);
6197             }
6198           ++count;
6199
6200           gtk_text_iter_backward_lines (&start, -count);
6201         }
6202       break;
6203
6204     case GTK_DELETE_PARAGRAPHS:
6205       if (count > 0)
6206         {
6207           gtk_text_iter_set_line_offset (&start, 0);
6208           gtk_text_iter_forward_to_line_end (&end);
6209
6210           /* Do the lines beyond the first. */
6211           while (count > 1)
6212             {
6213               gtk_text_iter_forward_to_line_end (&end);
6214
6215               --count;
6216             }
6217         }
6218
6219       /* FIXME negative count? */
6220
6221       break;
6222
6223     case GTK_DELETE_WHITESPACE:
6224       {
6225         find_whitepace_region (&insert, &start, &end);
6226       }
6227       break;
6228
6229     default:
6230       break;
6231     }
6232
6233   if (!gtk_text_iter_equal (&start, &end))
6234     {
6235       gtk_text_buffer_begin_user_action (get_buffer (text_view));
6236
6237       if (gtk_text_buffer_delete_interactive (get_buffer (text_view), &start, &end,
6238                                               priv->editable))
6239         {
6240           if (leave_one)
6241             gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view),
6242                                                           " ", 1,
6243                                                           priv->editable);
6244         }
6245       else
6246         {
6247           gtk_widget_error_bell (GTK_WIDGET (text_view));
6248         }
6249
6250       gtk_text_buffer_end_user_action (get_buffer (text_view));
6251       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
6252
6253       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6254       gtk_text_view_scroll_mark_onscreen (text_view,
6255                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
6256     }
6257   else
6258     {
6259       gtk_widget_error_bell (GTK_WIDGET (text_view));
6260     }
6261 }
6262
6263 static void
6264 gtk_text_view_backspace (GtkTextView *text_view)
6265 {
6266   GtkTextViewPrivate *priv;
6267   GtkTextIter insert;
6268
6269   priv = text_view->priv;
6270
6271   gtk_text_view_reset_im_context (text_view);
6272
6273   /* Backspace deletes the selection, if one exists */
6274   if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
6275                                         priv->editable))
6276     return;
6277
6278   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6279                                     &insert,
6280                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6281
6282   if (gtk_text_buffer_backspace (get_buffer (text_view), &insert,
6283                                  TRUE, priv->editable))
6284     {
6285       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
6286       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6287       gtk_text_view_scroll_mark_onscreen (text_view,
6288                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
6289     }
6290   else
6291     {
6292       gtk_widget_error_bell (GTK_WIDGET (text_view));
6293     }
6294 }
6295
6296 static void
6297 gtk_text_view_cut_clipboard (GtkTextView *text_view)
6298 {
6299   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6300                                                       GDK_SELECTION_CLIPBOARD);
6301   
6302   gtk_text_buffer_cut_clipboard (get_buffer (text_view),
6303                                  clipboard,
6304                                  text_view->priv->editable);
6305   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6306   gtk_text_view_scroll_mark_onscreen (text_view,
6307                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6308 }
6309
6310 static void
6311 gtk_text_view_copy_clipboard (GtkTextView *text_view)
6312 {
6313   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6314                                                       GDK_SELECTION_CLIPBOARD);
6315   
6316   gtk_text_buffer_copy_clipboard (get_buffer (text_view),
6317                                   clipboard);
6318
6319   /* on copy do not scroll, we are already onscreen */
6320 }
6321
6322 static void
6323 gtk_text_view_paste_clipboard (GtkTextView *text_view)
6324 {
6325   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6326                                                       GDK_SELECTION_CLIPBOARD);
6327   
6328   gtk_text_buffer_paste_clipboard (get_buffer (text_view),
6329                                    clipboard,
6330                                    NULL,
6331                                    text_view->priv->editable);
6332 }
6333
6334 static void
6335 gtk_text_view_paste_done_handler (GtkTextBuffer *buffer,
6336                                   GtkClipboard  *clipboard,
6337                                   gpointer       data)
6338 {
6339   GtkTextView *text_view = data;
6340   GtkTextViewPrivate *priv;
6341
6342   priv = text_view->priv;
6343
6344   if (priv->scroll_after_paste)
6345     {
6346       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6347       gtk_text_view_scroll_mark_onscreen (text_view, gtk_text_buffer_get_insert (buffer));
6348     }
6349
6350   priv->scroll_after_paste = TRUE;
6351 }
6352
6353 static void
6354 gtk_text_view_buffer_changed_handler (GtkTextBuffer *buffer,
6355                                       gpointer       data)
6356 {
6357   GtkTextView *text_view = data;
6358   gtk_text_view_update_handles (text_view, GTK_TEXT_HANDLE_MODE_NONE);
6359 }
6360
6361 static void
6362 gtk_text_view_toggle_overwrite (GtkTextView *text_view)
6363 {
6364   GtkTextViewPrivate *priv = text_view->priv;
6365
6366   if (priv->text_window)
6367     text_window_invalidate_cursors (priv->text_window);
6368
6369   priv->overwrite_mode = !priv->overwrite_mode;
6370
6371   if (priv->layout)
6372     gtk_text_layout_set_overwrite_mode (priv->layout,
6373                                         priv->overwrite_mode && priv->editable);
6374
6375   if (priv->text_window)
6376     text_window_invalidate_cursors (priv->text_window);
6377
6378   gtk_text_view_pend_cursor_blink (text_view);
6379
6380   g_object_notify (G_OBJECT (text_view), "overwrite");
6381 }
6382
6383 /**
6384  * gtk_text_view_get_overwrite:
6385  * @text_view: a #GtkTextView
6386  *
6387  * Returns whether the #GtkTextView is in overwrite mode or not.
6388  *
6389  * Return value: whether @text_view is in overwrite mode or not.
6390  * 
6391  * Since: 2.4
6392  **/
6393 gboolean
6394 gtk_text_view_get_overwrite (GtkTextView *text_view)
6395 {
6396   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6397
6398   return text_view->priv->overwrite_mode;
6399 }
6400
6401 /**
6402  * gtk_text_view_set_overwrite:
6403  * @text_view: a #GtkTextView
6404  * @overwrite: %TRUE to turn on overwrite mode, %FALSE to turn it off
6405  *
6406  * Changes the #GtkTextView overwrite mode.
6407  *
6408  * Since: 2.4
6409  **/
6410 void
6411 gtk_text_view_set_overwrite (GtkTextView *text_view,
6412                              gboolean     overwrite)
6413 {
6414   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6415   overwrite = overwrite != FALSE;
6416
6417   if (text_view->priv->overwrite_mode != overwrite)
6418     gtk_text_view_toggle_overwrite (text_view);
6419 }
6420
6421 /**
6422  * gtk_text_view_set_accepts_tab:
6423  * @text_view: A #GtkTextView
6424  * @accepts_tab: %TRUE if pressing the Tab key should insert a tab 
6425  *    character, %FALSE, if pressing the Tab key should move the 
6426  *    keyboard focus.
6427  * 
6428  * Sets the behavior of the text widget when the Tab key is pressed. 
6429  * If @accepts_tab is %TRUE, a tab character is inserted. If @accepts_tab 
6430  * is %FALSE the keyboard focus is moved to the next widget in the focus 
6431  * chain.
6432  * 
6433  * Since: 2.4
6434  **/
6435 void
6436 gtk_text_view_set_accepts_tab (GtkTextView *text_view,
6437                                gboolean     accepts_tab)
6438 {
6439   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6440
6441   accepts_tab = accepts_tab != FALSE;
6442
6443   if (text_view->priv->accepts_tab != accepts_tab)
6444     {
6445       text_view->priv->accepts_tab = accepts_tab;
6446
6447       g_object_notify (G_OBJECT (text_view), "accepts-tab");
6448     }
6449 }
6450
6451 /**
6452  * gtk_text_view_get_accepts_tab:
6453  * @text_view: A #GtkTextView
6454  * 
6455  * Returns whether pressing the Tab key inserts a tab characters.
6456  * gtk_text_view_set_accepts_tab().
6457  * 
6458  * Return value: %TRUE if pressing the Tab key inserts a tab character, 
6459  *   %FALSE if pressing the Tab key moves the keyboard focus.
6460  * 
6461  * Since: 2.4
6462  **/
6463 gboolean
6464 gtk_text_view_get_accepts_tab (GtkTextView *text_view)
6465 {
6466   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6467
6468   return text_view->priv->accepts_tab;
6469 }
6470
6471 /*
6472  * Selections
6473  */
6474
6475 static void
6476 gtk_text_view_unselect (GtkTextView *text_view)
6477 {
6478   GtkTextIter insert;
6479
6480   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6481                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6482
6483   gtk_text_buffer_move_mark (get_buffer (text_view),
6484                              gtk_text_buffer_get_selection_bound (get_buffer (text_view)),
6485                              &insert);
6486 }
6487
6488 static void
6489 get_iter_at_pointer (GtkTextView *text_view,
6490                      GdkDevice   *device,
6491                      GtkTextIter *iter,
6492                      gint        *x,
6493                      gint        *y)
6494 {
6495   GtkTextViewPrivate *priv;
6496   gint xcoord, ycoord;
6497   GdkModifierType state;
6498
6499   priv = text_view->priv;
6500
6501   gdk_window_get_device_position (priv->text_window->bin_window,
6502                                   device, &xcoord, &ycoord, &state);
6503
6504   gtk_text_layout_get_iter_at_pixel (priv->layout,
6505                                      iter,
6506                                      xcoord + priv->xoffset,
6507                                      ycoord + priv->yoffset);
6508   if (x)
6509     *x = xcoord;
6510
6511   if (y)
6512     *y = ycoord;
6513 }
6514
6515 static void
6516 move_mark_to_pointer_and_scroll (GtkTextView    *text_view,
6517                                  const gchar    *mark_name,
6518                                  GdkDevice      *device,
6519                                  GdkInputSource  source)
6520 {
6521   GtkTextIter newplace;
6522   GtkTextBuffer *buffer;
6523   GtkTextMark *mark;
6524
6525   buffer = get_buffer (text_view);
6526   get_iter_at_pointer (text_view, device, &newplace, NULL, NULL);
6527
6528   mark = gtk_text_buffer_get_mark (buffer, mark_name);
6529
6530   /* This may invalidate the layout */
6531   DV(g_print (G_STRLOC": move mark\n"));
6532
6533   gtk_text_buffer_move_mark (buffer, mark, &newplace);
6534
6535   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6536   gtk_text_view_scroll_mark_onscreen (text_view, mark);
6537
6538   DV (g_print ("first validate idle leaving %s is %d\n",
6539                G_STRLOC, text_view->priv->first_validate_idle));
6540 }
6541
6542 static gboolean
6543 selection_scan_timeout (gpointer data)
6544 {
6545   GtkTextView *text_view;
6546
6547   text_view = GTK_TEXT_VIEW (data);
6548
6549   gtk_text_view_scroll_mark_onscreen (text_view, 
6550                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6551
6552   return TRUE; /* remain installed. */
6553 }
6554
6555 #define UPPER_OFFSET_ANCHOR 0.8
6556 #define LOWER_OFFSET_ANCHOR 0.2
6557
6558 static gboolean
6559 check_scroll (gdouble offset, GtkAdjustment *adjustment)
6560 {
6561   if ((offset > UPPER_OFFSET_ANCHOR &&
6562        gtk_adjustment_get_value (adjustment) + gtk_adjustment_get_page_size (adjustment) < gtk_adjustment_get_upper (adjustment)) ||
6563       (offset < LOWER_OFFSET_ANCHOR &&
6564        gtk_adjustment_get_value (adjustment) > gtk_adjustment_get_lower (adjustment)))
6565     return TRUE;
6566
6567   return FALSE;
6568 }
6569
6570 static gint
6571 drag_scan_timeout (gpointer data)
6572 {
6573   GtkTextView *text_view;
6574   GtkTextViewPrivate *priv;
6575   GtkTextIter newplace;
6576   gint x, y;
6577   gdouble pointer_xoffset, pointer_yoffset;
6578
6579   text_view = GTK_TEXT_VIEW (data);
6580   priv = text_view->priv;
6581
6582   get_iter_at_pointer (text_view, priv->dnd_device, &newplace, &x, &y);
6583
6584   gtk_text_buffer_move_mark (get_buffer (text_view),
6585                              priv->dnd_mark,
6586                              &newplace);
6587
6588   pointer_xoffset = (gdouble) x / gdk_window_get_width (priv->text_window->bin_window);
6589   pointer_yoffset = (gdouble) y / gdk_window_get_height (priv->text_window->bin_window);
6590
6591   if (check_scroll (pointer_xoffset, priv->hadjustment) ||
6592       check_scroll (pointer_yoffset, priv->vadjustment))
6593     {
6594       /* do not make offsets surpass lower nor upper anchors, this makes
6595        * scrolling speed relative to the distance of the pointer to the
6596        * anchors when it moves beyond them.
6597        */
6598       pointer_xoffset = CLAMP (pointer_xoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6599       pointer_yoffset = CLAMP (pointer_yoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6600
6601       gtk_text_view_scroll_to_mark (text_view,
6602                                     priv->dnd_mark,
6603                                     0., TRUE, pointer_xoffset, pointer_yoffset);
6604     }
6605
6606   return TRUE;
6607 }
6608
6609 typedef enum 
6610 {
6611   SELECT_CHARACTERS,
6612   SELECT_WORDS,
6613   SELECT_LINES
6614 } SelectionGranularity;
6615
6616 /*
6617  * Move @start and @end to the boundaries of the selection unit (indicated by 
6618  * @granularity) which contained @start initially.
6619  * If the selction unit is SELECT_WORDS and @start is not contained in a word
6620  * the selection is extended to all the white spaces between the end of the 
6621  * word preceding @start and the start of the one following.
6622  */
6623 static void
6624 extend_selection (GtkTextView *text_view, 
6625                   SelectionGranularity granularity, 
6626                   GtkTextIter *start, 
6627                   GtkTextIter *end)
6628 {
6629   *end = *start;
6630
6631   if (granularity == SELECT_WORDS) 
6632     {
6633       if (gtk_text_iter_inside_word (start))
6634         {
6635           if (!gtk_text_iter_starts_word (start))
6636             gtk_text_iter_backward_visible_word_start (start);
6637           
6638           if (!gtk_text_iter_ends_word (end))
6639             {
6640               if (!gtk_text_iter_forward_visible_word_end (end))
6641                 gtk_text_iter_forward_to_end (end);
6642             }
6643         }
6644       else
6645         {
6646           GtkTextIter tmp;
6647
6648           tmp = *start;
6649           if (gtk_text_iter_backward_visible_word_start (&tmp))
6650             gtk_text_iter_forward_visible_word_end (&tmp);
6651
6652           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (start))
6653             *start = tmp;
6654           else
6655             gtk_text_iter_set_line_offset (start, 0);
6656
6657           tmp = *end;
6658           if (!gtk_text_iter_forward_visible_word_end (&tmp))
6659             gtk_text_iter_forward_to_end (&tmp);
6660
6661           if (gtk_text_iter_ends_word (&tmp))
6662             gtk_text_iter_backward_visible_word_start (&tmp);
6663
6664           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (end))
6665             *end = tmp;
6666           else
6667             gtk_text_iter_forward_to_line_end (end);
6668         }
6669     }
6670   else if (granularity == SELECT_LINES) 
6671     {
6672       if (gtk_text_view_starts_display_line (text_view, start))
6673         {
6674           /* If on a display line boundary, we assume the user
6675            * clicked off the end of a line and we therefore select
6676            * the line before the boundary.
6677            */
6678           gtk_text_view_backward_display_line_start (text_view, start);
6679         }
6680       else
6681         {
6682           /* start isn't on the start of a line, so we move it to the
6683            * start, and move end to the end unless it's already there.
6684            */
6685           gtk_text_view_backward_display_line_start (text_view, start);
6686           
6687           if (!gtk_text_view_starts_display_line (text_view, end))
6688             gtk_text_view_forward_display_line_end (text_view, end);
6689         }
6690     }
6691 }
6692  
6693
6694 typedef struct
6695 {
6696   SelectionGranularity granularity;
6697   GtkTextMark *orig_start;
6698   GtkTextMark *orig_end;
6699 } SelectionData;
6700
6701 static void
6702 selection_data_free (SelectionData *data)
6703 {
6704   if (data->orig_start != NULL)
6705     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_start),
6706                                  data->orig_start);
6707   if (data->orig_end != NULL)
6708     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_end),
6709                                  data->orig_end);
6710   g_free (data);
6711 }
6712
6713 static gint
6714 selection_motion_event_handler (GtkTextView    *text_view, 
6715                                 GdkEventMotion *event, 
6716                                 SelectionData  *data)
6717 {
6718   GtkTextViewPrivate *priv;
6719   GdkInputSource input_source;
6720   GdkDevice *device;
6721
6722   priv = text_view->priv;
6723   gdk_event_request_motions (event);
6724
6725   device = gdk_event_get_source_device ((GdkEvent *) event);
6726   input_source = gdk_device_get_source (device);
6727
6728   if (priv->grab_device != event->device)
6729     return FALSE;
6730
6731   if (data->granularity == SELECT_CHARACTERS) 
6732     {
6733       move_mark_to_pointer_and_scroll (text_view, "insert",
6734                                        event->device, input_source);
6735     }
6736   else 
6737     {
6738       GtkTextIter cursor, start, end;
6739       GtkTextIter orig_start, orig_end;
6740       GtkTextBuffer *buffer;
6741       
6742       buffer = get_buffer (text_view);
6743
6744       gtk_text_buffer_get_iter_at_mark (buffer, &orig_start, data->orig_start);
6745       gtk_text_buffer_get_iter_at_mark (buffer, &orig_end, data->orig_end);
6746
6747       get_iter_at_pointer (text_view, event->device, &cursor, NULL, NULL);
6748       
6749       start = cursor;
6750       extend_selection (text_view, data->granularity, &start, &end);
6751
6752       /* either the selection extends to the front, or end (or not) */
6753       if (gtk_text_iter_compare (&cursor, &orig_start) < 0)
6754         gtk_text_buffer_select_range (buffer, &start, &orig_end);
6755       else
6756         gtk_text_buffer_select_range (buffer, &end, &orig_start);
6757
6758       gtk_text_view_scroll_mark_onscreen (text_view,
6759                                           gtk_text_buffer_get_insert (buffer));
6760     }
6761
6762   /* If we had to scroll offscreen, insert a timeout to do so
6763    * again. Note that in the timeout, even if the mouse doesn't
6764    * move, due to this scroll xoffset/yoffset will have changed
6765    * and we'll need to scroll again.
6766    */
6767   if (text_view->priv->scroll_timeout != 0) /* reset on every motion event */
6768     g_source_remove (text_view->priv->scroll_timeout);
6769   
6770   text_view->priv->scroll_timeout =
6771     gdk_threads_add_timeout (50, selection_scan_timeout, text_view);
6772
6773   if (test_touchscreen || input_source == GDK_SOURCE_TOUCHSCREEN)
6774     gtk_text_view_update_handles (text_view, GTK_TEXT_HANDLE_MODE_SELECTION);
6775
6776   return TRUE;
6777 }
6778
6779 static void
6780 gtk_text_view_start_selection_drag (GtkTextView       *text_view,
6781                                     const GtkTextIter *iter,
6782                                     GdkEventButton    *button)
6783 {
6784   GtkTextViewPrivate *priv;
6785   GtkTextIter cursor, ins, bound;
6786   GtkTextIter orig_start, orig_end;
6787   GtkTextBuffer *buffer;
6788   SelectionData *data;
6789
6790   if (text_view->priv->selection_drag_handler != 0)
6791     return;
6792
6793   priv = text_view->priv;
6794   data = g_new0 (SelectionData, 1);
6795
6796   if (button->type == GDK_2BUTTON_PRESS)
6797     data->granularity = SELECT_WORDS;
6798   else if (button->type == GDK_3BUTTON_PRESS)
6799     data->granularity = SELECT_LINES;
6800   else 
6801     data->granularity = SELECT_CHARACTERS;
6802
6803   priv->grab_device = button->device;
6804   gtk_device_grab_add (GTK_WIDGET (text_view),
6805                        priv->grab_device,
6806                        TRUE);
6807
6808   buffer = get_buffer (text_view);
6809   
6810   cursor = *iter;
6811   ins = cursor;
6812   
6813   extend_selection (text_view, data->granularity, &ins, &bound);
6814   orig_start = ins;
6815   orig_end = bound;
6816
6817   if (button->state &
6818       gtk_widget_get_modifier_mask (GTK_WIDGET (text_view),
6819                                     GDK_MODIFIER_INTENT_EXTEND_SELECTION))
6820     {
6821       /* Extend selection */
6822       GtkTextIter old_ins, old_bound;
6823       GtkTextIter old_start, old_end;
6824
6825       gtk_text_buffer_get_iter_at_mark (buffer, &old_ins, gtk_text_buffer_get_insert (buffer));
6826       gtk_text_buffer_get_iter_at_mark (buffer, &old_bound, gtk_text_buffer_get_selection_bound (buffer));
6827       old_start = old_ins;
6828       old_end = old_bound;
6829       gtk_text_iter_order (&old_start, &old_end);
6830       
6831       /* move the front cursor, if the mouse is in front of the selection. Should the
6832        * cursor however be inside the selection (this happens on tripple click) then we
6833        * move the side which was last moved (current insert mark) */
6834       if (gtk_text_iter_compare (&cursor, &old_start) <= 0 ||
6835           (gtk_text_iter_compare (&cursor, &old_end) < 0 && 
6836            gtk_text_iter_compare (&old_ins, &old_bound) <= 0))
6837         {
6838           bound = old_end;
6839           orig_start = old_end;
6840           orig_end = old_end;
6841         }
6842       else
6843         {
6844           ins = bound;
6845           bound = old_start;
6846           orig_end = bound;
6847           orig_start = bound;
6848         }
6849     }
6850
6851   gtk_text_buffer_select_range (buffer, &ins, &bound);
6852
6853   gtk_text_iter_order (&orig_start, &orig_end);
6854   data->orig_start = gtk_text_buffer_create_mark (buffer, NULL,
6855                                                   &orig_start, TRUE);
6856   data->orig_end = gtk_text_buffer_create_mark (buffer, NULL,
6857                                                 &orig_end, TRUE);
6858   gtk_text_view_check_cursor_blink (text_view);
6859
6860   text_view->priv->selection_drag_handler = g_signal_connect_data (text_view,
6861                                                                    "motion-notify-event",
6862                                                                    G_CALLBACK (selection_motion_event_handler),
6863                                                                    data,
6864                                                                    (GClosureNotify) selection_data_free, 0);
6865 }
6866
6867 /* returns whether we were really dragging */
6868 static gboolean
6869 gtk_text_view_end_selection_drag (GtkTextView *text_view)
6870 {
6871   GtkTextViewPrivate *priv;
6872
6873   priv = text_view->priv;
6874
6875   if (!priv->grab_device)
6876     return FALSE;
6877
6878   if (priv->selection_drag_handler == 0)
6879     return FALSE;
6880
6881   g_signal_handler_disconnect (text_view, priv->selection_drag_handler);
6882   priv->selection_drag_handler = 0;
6883
6884   if (priv->scroll_timeout != 0)
6885     {
6886       g_source_remove (priv->scroll_timeout);
6887       priv->scroll_timeout = 0;
6888     }
6889
6890   gtk_device_grab_remove (GTK_WIDGET (text_view),
6891                           priv->grab_device);
6892   priv->grab_device = NULL;
6893
6894   return TRUE;
6895 }
6896
6897 /*
6898  * Layout utils
6899  */
6900
6901 static void
6902 gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
6903                                          GtkTextAttributes  *values)
6904 {
6905   GtkStyleContext *context;
6906   GdkRGBA bg_color, fg_color;
6907   GtkStateFlags state;
6908
6909   context = gtk_widget_get_style_context (GTK_WIDGET (text_view));
6910   state = gtk_widget_get_state_flags (GTK_WIDGET (text_view));
6911
6912   gtk_style_context_save (context);
6913   gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
6914
6915   gtk_style_context_get_background_color (context, state, &bg_color);
6916   gtk_style_context_get_color (context, state, &fg_color);
6917
6918   values->appearance.bg_color.red = CLAMP (bg_color.red * 65535. + 0.5, 0, 65535);
6919   values->appearance.bg_color.green = CLAMP (bg_color.green * 65535. + 0.5, 0, 65535);
6920   values->appearance.bg_color.blue = CLAMP (bg_color.blue * 65535. + 0.5, 0, 65535);
6921
6922   values->appearance.fg_color.red = CLAMP (fg_color.red * 65535. + 0.5, 0, 65535);
6923   values->appearance.fg_color.green = CLAMP (fg_color.green * 65535. + 0.5, 0, 65535);
6924   values->appearance.fg_color.blue = CLAMP (fg_color.blue * 65535. + 0.5, 0, 65535);
6925
6926   if (values->font)
6927     pango_font_description_free (values->font);
6928
6929   gtk_style_context_get (context, state, "font", &values->font, NULL);
6930
6931   gtk_style_context_restore (context);
6932 }
6933
6934 static void
6935 gtk_text_view_check_keymap_direction (GtkTextView *text_view)
6936 {
6937   GtkTextViewPrivate *priv = text_view->priv;
6938
6939   if (priv->layout)
6940     {
6941       GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
6942       GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)));
6943       GtkTextDirection new_cursor_dir;
6944       GtkTextDirection new_keyboard_dir;
6945       gboolean split_cursor;
6946
6947       g_object_get (settings,
6948                     "gtk-split-cursor", &split_cursor,
6949                     NULL);
6950       
6951       if (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_RTL)
6952         new_keyboard_dir = GTK_TEXT_DIR_RTL;
6953       else
6954         new_keyboard_dir  = GTK_TEXT_DIR_LTR;
6955   
6956       if (split_cursor)
6957         new_cursor_dir = GTK_TEXT_DIR_NONE;
6958       else
6959         new_cursor_dir = new_keyboard_dir;
6960       
6961       gtk_text_layout_set_cursor_direction (priv->layout, new_cursor_dir);
6962       gtk_text_layout_set_keyboard_direction (priv->layout, new_keyboard_dir);
6963     }
6964 }
6965
6966 static void
6967 gtk_text_view_ensure_layout (GtkTextView *text_view)
6968 {
6969   GtkWidget *widget;
6970   GtkTextViewPrivate *priv;
6971
6972   widget = GTK_WIDGET (text_view);
6973   priv = text_view->priv;
6974
6975   if (priv->layout == NULL)
6976     {
6977       GtkTextAttributes *style;
6978       PangoContext *ltr_context, *rtl_context;
6979       GSList *tmp_list;
6980
6981       DV(g_print(G_STRLOC"\n"));
6982       
6983       priv->layout = gtk_text_layout_new ();
6984
6985       g_signal_connect (priv->layout,
6986                         "invalidated",
6987                         G_CALLBACK (invalidated_handler),
6988                         text_view);
6989
6990       g_signal_connect (priv->layout,
6991                         "changed",
6992                         G_CALLBACK (changed_handler),
6993                         text_view);
6994
6995       g_signal_connect (priv->layout,
6996                         "allocate-child",
6997                         G_CALLBACK (gtk_text_view_child_allocated),
6998                         text_view);
6999       
7000       if (get_buffer (text_view))
7001         gtk_text_layout_set_buffer (priv->layout, get_buffer (text_view));
7002
7003       if ((gtk_widget_has_focus (widget) && priv->cursor_visible))
7004         gtk_text_view_pend_cursor_blink (text_view);
7005       else
7006         gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
7007
7008       gtk_text_layout_set_overwrite_mode (priv->layout,
7009                                           priv->overwrite_mode && priv->editable);
7010
7011       ltr_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
7012       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
7013       rtl_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
7014       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
7015
7016       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
7017
7018       g_object_unref (ltr_context);
7019       g_object_unref (rtl_context);
7020
7021       gtk_text_view_check_keymap_direction (text_view);
7022
7023       style = gtk_text_attributes_new ();
7024
7025       gtk_text_view_set_attributes_from_style (text_view, style);
7026
7027       style->pixels_above_lines = priv->pixels_above_lines;
7028       style->pixels_below_lines = priv->pixels_below_lines;
7029       style->pixels_inside_wrap = priv->pixels_inside_wrap;
7030       style->left_margin = priv->left_margin;
7031       style->right_margin = priv->right_margin;
7032       style->indent = priv->indent;
7033       style->tabs = priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
7034
7035       style->wrap_mode = priv->wrap_mode;
7036       style->justification = priv->justify;
7037       style->direction = gtk_widget_get_direction (GTK_WIDGET (text_view));
7038
7039       gtk_text_layout_set_default_style (priv->layout, style);
7040
7041       gtk_text_attributes_unref (style);
7042
7043       /* Set layout for all anchored children */
7044
7045       tmp_list = priv->children;
7046       while (tmp_list != NULL)
7047         {
7048           GtkTextViewChild *vc = tmp_list->data;
7049
7050           if (vc->anchor)
7051             {
7052               gtk_text_anchored_child_set_layout (vc->widget,
7053                                                   priv->layout);
7054               /* vc may now be invalid! */
7055             }
7056
7057           tmp_list = g_slist_next (tmp_list);
7058         }
7059     }
7060 }
7061
7062 /**
7063  * gtk_text_view_get_default_attributes:
7064  * @text_view: a #GtkTextView
7065  * 
7066  * Obtains a copy of the default text attributes. These are the
7067  * attributes used for text unless a tag overrides them.
7068  * You'd typically pass the default attributes in to
7069  * gtk_text_iter_get_attributes() in order to get the
7070  * attributes in effect at a given text position.
7071  *
7072  * The return value is a copy owned by the caller of this function,
7073  * and should be freed.
7074  * 
7075  * Return value: a new #GtkTextAttributes
7076  **/
7077 GtkTextAttributes*
7078 gtk_text_view_get_default_attributes (GtkTextView *text_view)
7079 {
7080   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7081   
7082   gtk_text_view_ensure_layout (text_view);
7083
7084   return gtk_text_attributes_copy (text_view->priv->layout->default_style);
7085 }
7086
7087 static void
7088 gtk_text_view_destroy_layout (GtkTextView *text_view)
7089 {
7090   GtkTextViewPrivate *priv = text_view->priv;
7091
7092   if (priv->layout)
7093     {
7094       GSList *tmp_list;
7095
7096       gtk_text_view_remove_validate_idles (text_view);
7097
7098       g_signal_handlers_disconnect_by_func (priv->layout,
7099                                             invalidated_handler,
7100                                             text_view);
7101       g_signal_handlers_disconnect_by_func (priv->layout,
7102                                             changed_handler,
7103                                             text_view);
7104
7105       /* Remove layout from all anchored children */
7106       tmp_list = priv->children;
7107       while (tmp_list != NULL)
7108         {
7109           GtkTextViewChild *vc = tmp_list->data;
7110
7111           if (vc->anchor)
7112             {
7113               gtk_text_anchored_child_set_layout (vc->widget, NULL);
7114               /* vc may now be invalid! */
7115             }
7116
7117           tmp_list = g_slist_next (tmp_list);
7118         }
7119
7120       gtk_text_view_stop_cursor_blink (text_view);
7121       gtk_text_view_end_selection_drag (text_view);
7122
7123       g_object_unref (priv->layout);
7124       priv->layout = NULL;
7125     }
7126 }
7127
7128 /**
7129  * gtk_text_view_reset_im_context:
7130  * @text_view: a #GtkTextView
7131  *
7132  * Reset the input method context of the text view if needed.
7133  *
7134  * This can be necessary in the case where modifying the buffer
7135  * would confuse on-going input method behavior.
7136  *
7137  * Since: 2.22
7138  */
7139 void
7140 gtk_text_view_reset_im_context (GtkTextView *text_view)
7141 {
7142   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7143
7144   if (text_view->priv->need_im_reset)
7145     {
7146       text_view->priv->need_im_reset = FALSE;
7147       gtk_im_context_reset (text_view->priv->im_context);
7148     }
7149 }
7150
7151 /**
7152  * gtk_text_view_im_context_filter_keypress:
7153  * @text_view: a #GtkTextView
7154  * @event: the key event
7155  *
7156  * Allow the #GtkTextView input method to internally handle key press
7157  * and release events. If this function returns %TRUE, then no further
7158  * processing should be done for this key event. See
7159  * gtk_im_context_filter_keypress().
7160  *
7161  * Note that you are expected to call this function from your handler
7162  * when overriding key event handling. This is needed in the case when
7163  * you need to insert your own key handling between the input method
7164  * and the default key event handling of the #GtkTextView.
7165  *
7166  * |[
7167  * static gboolean
7168  * gtk_foo_bar_key_press_event (GtkWidget   *widget,
7169  *                              GdkEventKey *event)
7170  * {
7171  *   if ((key->keyval == GDK_KEY_Return || key->keyval == GDK_KEY_KP_Enter))
7172  *     {
7173  *       if (gtk_text_view_im_context_filter_keypress (GTK_TEXT_VIEW (view), event))
7174  *         return TRUE;
7175  *     }
7176  *
7177  *     /&ast; Do some stuff &ast;/
7178  *
7179  *   return GTK_WIDGET_CLASS (gtk_foo_bar_parent_class)->key_press_event (widget, event);
7180  * }
7181  * ]|
7182  *
7183  * Return value: %TRUE if the input method handled the key event.
7184  *
7185  * Since: 2.22
7186  */
7187 gboolean
7188 gtk_text_view_im_context_filter_keypress (GtkTextView  *text_view,
7189                                           GdkEventKey  *event)
7190 {
7191   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7192
7193   return gtk_im_context_filter_keypress (text_view->priv->im_context, event);
7194 }
7195
7196 /*
7197  * DND feature
7198  */
7199
7200 static void
7201 drag_begin_cb (GtkWidget      *widget,
7202                GdkDragContext *context,
7203                gpointer        data)
7204 {
7205   GtkTextView     *text_view = GTK_TEXT_VIEW (widget);
7206   GtkTextBuffer   *buffer = gtk_text_view_get_buffer (text_view);
7207   GtkTextIter      start;
7208   GtkTextIter      end;
7209   cairo_surface_t *surface = NULL;
7210
7211   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
7212
7213   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7214     surface = _gtk_text_util_create_rich_drag_icon (widget, buffer, &start, &end);
7215
7216   if (surface)
7217     {
7218       gtk_drag_set_icon_surface (context, surface);
7219       cairo_surface_destroy (surface);
7220     }
7221   else
7222     {
7223       gtk_drag_set_icon_default (context);
7224     }
7225 }
7226
7227 static void
7228 gtk_text_view_start_selection_dnd (GtkTextView       *text_view,
7229                                    const GtkTextIter *iter,
7230                                    GdkEventMotion    *event)
7231 {
7232   GtkTargetList *target_list;
7233
7234   text_view->priv->drag_start_x = -1;
7235   text_view->priv->drag_start_y = -1;
7236   text_view->priv->pending_place_cursor_button = 0;
7237
7238   target_list = gtk_text_buffer_get_copy_target_list (get_buffer (text_view));
7239
7240   g_signal_connect (text_view, "drag-begin",
7241                     G_CALLBACK (drag_begin_cb), NULL);
7242   gtk_drag_begin (GTK_WIDGET (text_view), target_list,
7243                   GDK_ACTION_COPY | GDK_ACTION_MOVE,
7244                   1, (GdkEvent*)event);
7245 }
7246
7247 static void
7248 gtk_text_view_drag_begin (GtkWidget        *widget,
7249                           GdkDragContext   *context)
7250 {
7251   /* do nothing */
7252 }
7253
7254 static void
7255 gtk_text_view_drag_end (GtkWidget        *widget,
7256                         GdkDragContext   *context)
7257 {
7258 }
7259
7260 static void
7261 gtk_text_view_drag_data_get (GtkWidget        *widget,
7262                              GdkDragContext   *context,
7263                              GtkSelectionData *selection_data,
7264                              guint             info,
7265                              guint             time)
7266 {
7267   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
7268   GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
7269
7270   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7271     {
7272       gtk_selection_data_set (selection_data,
7273                               gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
7274                               8, /* bytes */
7275                               (void*)&buffer,
7276                               sizeof (buffer));
7277     }
7278   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
7279     {
7280       GtkTextIter start;
7281       GtkTextIter end;
7282       guint8 *str = NULL;
7283       gsize len;
7284
7285       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7286         {
7287           /* Extract the selected text */
7288           str = gtk_text_buffer_serialize (buffer, buffer,
7289                                            gtk_selection_data_get_target (selection_data),
7290                                            &start, &end,
7291                                            &len);
7292         }
7293
7294       if (str)
7295         {
7296           gtk_selection_data_set (selection_data,
7297                                   gtk_selection_data_get_target (selection_data),
7298                                   8, /* bytes */
7299                                   (guchar *) str, len);
7300           g_free (str);
7301         }
7302     }
7303   else
7304     {
7305       GtkTextIter start;
7306       GtkTextIter end;
7307       gchar *str = NULL;
7308
7309       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7310         {
7311           /* Extract the selected text */
7312           str = gtk_text_iter_get_visible_text (&start, &end);
7313         }
7314
7315       if (str)
7316         {
7317           gtk_selection_data_set_text (selection_data, str, -1);
7318           g_free (str);
7319         }
7320     }
7321 }
7322
7323 static void
7324 gtk_text_view_drag_data_delete (GtkWidget        *widget,
7325                                 GdkDragContext   *context)
7326 {
7327   gtk_text_buffer_delete_selection (GTK_TEXT_VIEW (widget)->priv->buffer,
7328                                     TRUE, GTK_TEXT_VIEW (widget)->priv->editable);
7329 }
7330
7331 static void
7332 gtk_text_view_drag_leave (GtkWidget        *widget,
7333                           GdkDragContext   *context,
7334                           guint             time)
7335 {
7336   GtkTextView *text_view;
7337   GtkTextViewPrivate *priv;
7338
7339   text_view = GTK_TEXT_VIEW (widget);
7340   priv = text_view->priv;
7341
7342   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7343
7344   if (priv->dnd_device)
7345     priv->dnd_device = NULL;
7346
7347   if (priv->scroll_timeout != 0)
7348     g_source_remove (priv->scroll_timeout);
7349
7350   priv->scroll_timeout = 0;
7351 }
7352
7353 static gboolean
7354 gtk_text_view_drag_motion (GtkWidget        *widget,
7355                            GdkDragContext   *context,
7356                            gint              x,
7357                            gint              y,
7358                            guint             time)
7359 {
7360   GtkTextIter newplace;
7361   GtkTextView *text_view;
7362   GtkTextViewPrivate *priv;
7363   GtkTextIter start;
7364   GtkTextIter end;
7365   GdkRectangle target_rect;
7366   gint bx, by;
7367   GdkAtom target;
7368   GdkDragAction suggested_action = 0;
7369   
7370   text_view = GTK_TEXT_VIEW (widget);
7371   priv = text_view->priv;
7372
7373   target_rect = priv->text_window->allocation;
7374   
7375   if (x < target_rect.x ||
7376       y < target_rect.y ||
7377       x > (target_rect.x + target_rect.width) ||
7378       y > (target_rect.y + target_rect.height))
7379     return FALSE; /* outside the text window, allow parent widgets to handle event */
7380
7381   gtk_text_view_window_to_buffer_coords (text_view,
7382                                          GTK_TEXT_WINDOW_WIDGET,
7383                                          x, y,
7384                                          &bx, &by);
7385
7386   gtk_text_layout_get_iter_at_pixel (priv->layout,
7387                                      &newplace,
7388                                      bx, by);  
7389
7390   target = gtk_drag_dest_find_target (widget, context,
7391                                       gtk_drag_dest_get_target_list (widget));
7392
7393   if (target == GDK_NONE)
7394     {
7395       /* can't accept any of the offered targets */
7396     }                                 
7397   else if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7398                                                  &start, &end) &&
7399            gtk_text_iter_compare (&newplace, &start) >= 0 &&
7400            gtk_text_iter_compare (&newplace, &end) <= 0)
7401     {
7402       /* We're inside the selection. */
7403     }
7404   else
7405     {      
7406       if (gtk_text_iter_can_insert (&newplace, priv->editable))
7407         {
7408           GtkWidget *source_widget;
7409           
7410           suggested_action = gdk_drag_context_get_suggested_action (context);
7411           
7412           source_widget = gtk_drag_get_source_widget (context);
7413           
7414           if (source_widget == widget)
7415             {
7416               /* Default to MOVE, unless the user has
7417                * pressed ctrl or alt to affect available actions
7418                */
7419               if ((gdk_drag_context_get_actions (context) & GDK_ACTION_MOVE) != 0)
7420                 suggested_action = GDK_ACTION_MOVE;
7421             }
7422         }
7423       else
7424         {
7425           /* Can't drop here. */
7426         }
7427     }
7428
7429   if (suggested_action != 0)
7430     {
7431       gtk_text_mark_set_visible (priv->dnd_mark,
7432                                  priv->cursor_visible);
7433       
7434       gdk_drag_status (context, suggested_action, time);
7435     }
7436   else
7437     {
7438       gdk_drag_status (context, 0, time);
7439       gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7440     }
7441
7442   priv->dnd_device = gdk_drag_context_get_device (context);
7443
7444   if (!priv->scroll_timeout)
7445     priv->scroll_timeout =
7446       gdk_threads_add_timeout (100, drag_scan_timeout, text_view);
7447
7448   /* TRUE return means don't propagate the drag motion to parent
7449    * widgets that may also be drop sites.
7450    */
7451   return TRUE;
7452 }
7453
7454 static gboolean
7455 gtk_text_view_drag_drop (GtkWidget        *widget,
7456                          GdkDragContext   *context,
7457                          gint              x,
7458                          gint              y,
7459                          guint             time)
7460 {
7461   GtkTextView *text_view;
7462   GtkTextViewPrivate *priv;
7463   GtkTextIter drop_point;
7464   GdkAtom target = GDK_NONE;
7465
7466   text_view = GTK_TEXT_VIEW (widget);
7467   priv = text_view->priv;
7468
7469   if (priv->scroll_timeout != 0)
7470     g_source_remove (priv->scroll_timeout);
7471
7472   priv->scroll_timeout = 0;
7473
7474   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7475
7476   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7477                                     &drop_point,
7478                                     priv->dnd_mark);
7479
7480   if (gtk_text_iter_can_insert (&drop_point, priv->editable))
7481     target = gtk_drag_dest_find_target (widget, context, NULL);
7482
7483   if (target != GDK_NONE)
7484     gtk_drag_get_data (widget, context, target, time);
7485   else
7486     gtk_drag_finish (context, FALSE, FALSE, time);
7487
7488   return TRUE;
7489 }
7490
7491 static void
7492 insert_text_data (GtkTextView      *text_view,
7493                   GtkTextIter      *drop_point,
7494                   GtkSelectionData *selection_data)
7495 {
7496   guchar *str;
7497
7498   str = gtk_selection_data_get_text (selection_data);
7499
7500   if (str)
7501     {
7502       if (!gtk_text_buffer_insert_interactive (get_buffer (text_view),
7503                                                drop_point, (gchar *) str, -1,
7504                                                text_view->priv->editable))
7505         {
7506           gtk_widget_error_bell (GTK_WIDGET (text_view));
7507         }
7508
7509       g_free (str);
7510     }
7511 }
7512
7513 static void
7514 gtk_text_view_drag_data_received (GtkWidget        *widget,
7515                                   GdkDragContext   *context,
7516                                   gint              x,
7517                                   gint              y,
7518                                   GtkSelectionData *selection_data,
7519                                   guint             info,
7520                                   guint             time)
7521 {
7522   GtkTextIter drop_point;
7523   GtkTextView *text_view;
7524   GtkTextViewPrivate *priv;
7525   gboolean success = FALSE;
7526   GtkTextBuffer *buffer = NULL;
7527
7528   text_view = GTK_TEXT_VIEW (widget);
7529   priv = text_view->priv;
7530
7531   if (!priv->dnd_mark)
7532     goto done;
7533
7534   buffer = get_buffer (text_view);
7535
7536   gtk_text_buffer_get_iter_at_mark (buffer,
7537                                     &drop_point,
7538                                     priv->dnd_mark);
7539   
7540   if (!gtk_text_iter_can_insert (&drop_point, priv->editable))
7541     goto done;
7542
7543   success = TRUE;
7544
7545   gtk_text_buffer_begin_user_action (buffer);
7546
7547   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7548     {
7549       GtkTextBuffer *src_buffer = NULL;
7550       GtkTextIter start, end;
7551       gboolean copy_tags = TRUE;
7552
7553       if (gtk_selection_data_get_length (selection_data) != sizeof (src_buffer))
7554         return;
7555
7556       memcpy (&src_buffer, gtk_selection_data_get_data (selection_data), sizeof (src_buffer));
7557
7558       if (src_buffer == NULL)
7559         return;
7560
7561       g_return_if_fail (GTK_IS_TEXT_BUFFER (src_buffer));
7562
7563       if (gtk_text_buffer_get_tag_table (src_buffer) !=
7564           gtk_text_buffer_get_tag_table (buffer))
7565         {
7566           /*  try to find a suitable rich text target instead  */
7567           GdkAtom *atoms;
7568           gint     n_atoms;
7569           GList   *list;
7570           GdkAtom  target = GDK_NONE;
7571
7572           copy_tags = FALSE;
7573
7574           atoms = gtk_text_buffer_get_deserialize_formats (buffer, &n_atoms);
7575
7576           for (list = gdk_drag_context_list_targets (context); list; list = g_list_next (list))
7577             {
7578               gint i;
7579
7580               for (i = 0; i < n_atoms; i++)
7581                 if (GUINT_TO_POINTER (atoms[i]) == list->data)
7582                   {
7583                     target = atoms[i];
7584                     break;
7585                   }
7586             }
7587
7588           g_free (atoms);
7589
7590           if (target != GDK_NONE)
7591             {
7592               gtk_drag_get_data (widget, context, target, time);
7593               gtk_text_buffer_end_user_action (buffer);
7594               return;
7595             }
7596         }
7597
7598       if (gtk_text_buffer_get_selection_bounds (src_buffer,
7599                                                 &start,
7600                                                 &end))
7601         {
7602           if (copy_tags)
7603             gtk_text_buffer_insert_range_interactive (buffer,
7604                                                       &drop_point,
7605                                                       &start,
7606                                                       &end,
7607                                                       priv->editable);
7608           else
7609             {
7610               gchar *str;
7611
7612               str = gtk_text_iter_get_visible_text (&start, &end);
7613               gtk_text_buffer_insert_interactive (buffer,
7614                                                   &drop_point, str, -1,
7615                                                   priv->editable);
7616               g_free (str);
7617             }
7618         }
7619     }
7620   else if (gtk_selection_data_get_length (selection_data) > 0 &&
7621            info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
7622     {
7623       gboolean retval;
7624       GError *error = NULL;
7625
7626       retval = gtk_text_buffer_deserialize (buffer, buffer,
7627                                             gtk_selection_data_get_target (selection_data),
7628                                             &drop_point,
7629                                             (guint8 *) gtk_selection_data_get_data (selection_data),
7630                                             gtk_selection_data_get_length (selection_data),
7631                                             &error);
7632
7633       if (!retval)
7634         {
7635           g_warning ("error pasting: %s\n", error->message);
7636           g_clear_error (&error);
7637         }
7638     }
7639   else
7640     insert_text_data (text_view, &drop_point, selection_data);
7641
7642  done:
7643   gtk_drag_finish (context, success,
7644                    success && gdk_drag_context_get_selected_action (context) == GDK_ACTION_MOVE,
7645                    time);
7646
7647   if (success)
7648     {
7649       gtk_text_buffer_get_iter_at_mark (buffer,
7650                                         &drop_point,
7651                                         priv->dnd_mark);
7652       gtk_text_buffer_place_cursor (buffer, &drop_point);
7653
7654       gtk_text_buffer_end_user_action (buffer);
7655     }
7656 }
7657
7658 /**
7659  * gtk_text_view_get_hadjustment:
7660  * @text_view: a #GtkTextView
7661  *
7662  * Gets the horizontal-scrolling #GtkAdjustment.
7663  *
7664  * Returns: (transfer none): pointer to the horizontal #GtkAdjustment
7665  *
7666  * Since: 2.22
7667  *
7668  * Deprecated: 3.0: Use gtk_scrollable_get_hadjustment()
7669  **/
7670 GtkAdjustment*
7671 gtk_text_view_get_hadjustment (GtkTextView *text_view)
7672 {
7673   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7674
7675   return text_view->priv->hadjustment;
7676 }
7677
7678 static void
7679 gtk_text_view_set_hadjustment (GtkTextView   *text_view,
7680                                GtkAdjustment *adjustment)
7681 {
7682   GtkTextViewPrivate *priv = text_view->priv;
7683
7684   if (adjustment && priv->hadjustment == adjustment)
7685     return;
7686
7687   if (priv->hadjustment != NULL)
7688     {
7689       g_signal_handlers_disconnect_by_func (priv->hadjustment,
7690                                             gtk_text_view_value_changed,
7691                                             text_view);
7692       g_object_unref (priv->hadjustment);
7693     }
7694
7695   if (adjustment == NULL)
7696     adjustment = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7697
7698   g_signal_connect (adjustment, "value-changed",
7699                     G_CALLBACK (gtk_text_view_value_changed), text_view);
7700   priv->hadjustment = g_object_ref_sink (adjustment);
7701   gtk_text_view_set_hadjustment_values (text_view);
7702
7703   g_object_notify (G_OBJECT (text_view), "hadjustment");
7704 }
7705
7706 /**
7707  * gtk_text_view_get_vadjustment:
7708  * @text_view: a #GtkTextView
7709  *
7710  * Gets the vertical-scrolling #GtkAdjustment.
7711  *
7712  * Returns: (transfer none): pointer to the vertical #GtkAdjustment
7713  *
7714  * Since: 2.22
7715  *
7716  * Deprecated: 3.0: Use gtk_scrollable_get_vadjustment()
7717  **/
7718 GtkAdjustment*
7719 gtk_text_view_get_vadjustment (GtkTextView *text_view)
7720 {
7721   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7722
7723   return text_view->priv->vadjustment;
7724 }
7725
7726 static void
7727 gtk_text_view_set_vadjustment (GtkTextView   *text_view,
7728                                GtkAdjustment *adjustment)
7729 {
7730   GtkTextViewPrivate *priv = text_view->priv;
7731
7732   if (adjustment && priv->vadjustment == adjustment)
7733     return;
7734
7735   if (priv->vadjustment != NULL)
7736     {
7737       g_signal_handlers_disconnect_by_func (priv->vadjustment,
7738                                             gtk_text_view_value_changed,
7739                                             text_view);
7740       g_object_unref (priv->vadjustment);
7741     }
7742
7743   if (adjustment == NULL)
7744     adjustment = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7745
7746   g_signal_connect (adjustment, "value-changed",
7747                     G_CALLBACK (gtk_text_view_value_changed), text_view);
7748   priv->vadjustment = g_object_ref_sink (adjustment);
7749   gtk_text_view_set_vadjustment_values (text_view);
7750
7751   g_object_notify (G_OBJECT (text_view), "vadjustment");
7752 }
7753
7754 static void
7755 gtk_text_view_set_hadjustment_values (GtkTextView *text_view)
7756 {
7757   GtkTextViewPrivate *priv;
7758   gint screen_width;
7759   gdouble old_value;
7760   gdouble new_value;
7761   gdouble new_upper;
7762
7763   priv = text_view->priv;
7764
7765   screen_width = SCREEN_WIDTH (text_view);
7766   old_value = gtk_adjustment_get_value (priv->hadjustment);
7767   new_upper = MAX (screen_width, priv->width);
7768
7769   g_object_set (priv->hadjustment,
7770                 "lower", 0.0,
7771                 "upper", new_upper,
7772                 "page-size", (gdouble)screen_width,
7773                 "step-increment", screen_width * 0.1,
7774                 "page-increment", screen_width * 0.9,
7775                 NULL);
7776
7777   new_value = CLAMP (old_value, 0, new_upper - screen_width);
7778   if (new_value != old_value)
7779     gtk_adjustment_set_value (priv->hadjustment, new_value);
7780 }
7781
7782 static void
7783 gtk_text_view_set_vadjustment_values (GtkTextView *text_view)
7784 {
7785   GtkTextViewPrivate *priv;
7786   GtkTextIter first_para;
7787   gint screen_height;
7788   gint y;
7789   gdouble old_value;
7790   gdouble new_value;
7791   gdouble new_upper;
7792
7793   priv = text_view->priv;
7794
7795   screen_height = SCREEN_HEIGHT (text_view);
7796   old_value = gtk_adjustment_get_value (priv->vadjustment);
7797   new_upper = MAX (screen_height, priv->height);
7798
7799   g_object_set (priv->vadjustment,
7800                 "lower", 0.0,
7801                 "upper", new_upper,
7802                 "page-size", (gdouble)screen_height,
7803                 "step-increment", screen_height * 0.1,
7804                 "page-increment", screen_height * 0.9,
7805                 NULL);
7806
7807   /* Now adjust the value of the adjustment to keep the cursor at the
7808    * same place in the buffer */
7809   gtk_text_view_ensure_layout (text_view);
7810   gtk_text_view_get_first_para_iter (text_view, &first_para);
7811   gtk_text_layout_get_line_yrange (priv->layout, &first_para, &y, NULL);
7812
7813   y += priv->first_para_pixels;
7814
7815   new_value = CLAMP (y, 0, new_upper - screen_height);
7816   if (new_value != old_value)
7817     gtk_adjustment_set_value (priv->vadjustment, new_value);
7818  }
7819
7820
7821 /* FIXME this adjust_allocation is a big cut-and-paste from
7822  * GtkCList, needs to be some "official" way to do this
7823  * factored out.
7824  */
7825 typedef struct
7826 {
7827   GdkWindow *window;
7828   int dx;
7829   int dy;
7830 } ScrollData;
7831
7832 /* The window to which widget->window is relative */
7833 #define ALLOCATION_WINDOW(widget)               \
7834    (!gtk_widget_get_has_window (widget) ?                   \
7835     gtk_widget_get_window (widget) :                        \
7836     gdk_window_get_parent (gtk_widget_get_window (widget)))
7837
7838 static void
7839 adjust_allocation_recurse (GtkWidget *widget,
7840                            gpointer   data)
7841 {
7842   GtkAllocation allocation;
7843   ScrollData *scroll_data = data;
7844
7845   /* Need to really size allocate instead of just poking
7846    * into widget->allocation if the widget is not realized.
7847    * FIXME someone figure out why this was.
7848    */
7849   gtk_widget_get_allocation (widget, &allocation);
7850
7851   if (!gtk_widget_get_realized (widget))
7852     {
7853       if (gtk_widget_get_visible (widget))
7854         {
7855           GdkRectangle tmp_rectangle;
7856
7857           tmp_rectangle = allocation;
7858           tmp_rectangle.x += scroll_data->dx;
7859           tmp_rectangle.y += scroll_data->dy;
7860           
7861           gtk_widget_size_allocate (widget, &tmp_rectangle);
7862         }
7863     }
7864   else
7865     {
7866       if (ALLOCATION_WINDOW (widget) == scroll_data->window)
7867         {
7868           allocation.x += scroll_data->dx;
7869           allocation.y += scroll_data->dy;
7870           gtk_widget_set_allocation (widget, &allocation);
7871
7872           if (GTK_IS_CONTAINER (widget))
7873             gtk_container_forall (GTK_CONTAINER (widget),
7874                                   adjust_allocation_recurse,
7875                                   data);
7876         }
7877     }
7878 }
7879
7880 static void
7881 adjust_allocation (GtkWidget *widget,
7882                    int        dx,
7883                    int        dy)
7884 {
7885   ScrollData scroll_data;
7886
7887   if (gtk_widget_get_realized (widget))
7888     scroll_data.window = ALLOCATION_WINDOW (widget);
7889   else
7890     scroll_data.window = NULL;
7891     
7892   scroll_data.dx = dx;
7893   scroll_data.dy = dy;
7894   
7895   adjust_allocation_recurse (widget, &scroll_data);
7896 }
7897
7898 static void
7899 gtk_text_view_value_changed (GtkAdjustment *adjustment,
7900                              GtkTextView   *text_view)
7901 {
7902   GtkTextViewPrivate *priv;
7903   GtkTextIter iter;
7904   gint line_top;
7905   gint dx = 0;
7906   gint dy = 0;
7907
7908   priv = text_view->priv;
7909
7910   /* Note that we oddly call this function with adjustment == NULL
7911    * sometimes
7912    */
7913   
7914   priv->onscreen_validated = FALSE;
7915
7916   DV(g_print(">Scroll offset changed %s/%g, onscreen_validated = FALSE ("G_STRLOC")\n",
7917              adjustment == priv->hadjustment ? "hadjustment" : adjustment == priv->vadjustment ? "vadjustment" : "none",
7918              adjustment ? gtk_adjustment_get_value (adjustment) : 0.0));
7919   
7920   if (adjustment == priv->hadjustment)
7921     {
7922       dx = priv->xoffset - (gint)gtk_adjustment_get_value (adjustment);
7923       priv->xoffset = gtk_adjustment_get_value (adjustment);
7924
7925       /* If the change is due to a size change we need 
7926        * to invalidate the entire text window because there might be
7927        * right-aligned or centered text 
7928        */
7929       if (priv->width_changed)
7930         {
7931           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7932             gdk_window_invalidate_rect (priv->text_window->bin_window, NULL, FALSE);
7933           
7934           priv->width_changed = FALSE;
7935         }
7936     }
7937   else if (adjustment == priv->vadjustment)
7938     {
7939       dy = priv->yoffset - (gint)gtk_adjustment_get_value (adjustment);
7940       priv->yoffset = gtk_adjustment_get_value (adjustment);
7941
7942       if (priv->layout)
7943         {
7944           gtk_text_layout_get_line_at_y (priv->layout, &iter, gtk_adjustment_get_value (adjustment), &line_top);
7945
7946           gtk_text_buffer_move_mark (get_buffer (text_view), priv->first_para_mark, &iter);
7947
7948           priv->first_para_pixels = gtk_adjustment_get_value (adjustment) - line_top;
7949         }
7950     }
7951   
7952   if (dx != 0 || dy != 0)
7953     {
7954       GSList *tmp_list;
7955
7956       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7957         {
7958           if (dy != 0)
7959             {
7960               if (priv->left_window)
7961                 text_window_scroll (priv->left_window, 0, dy);
7962               if (priv->right_window)
7963                 text_window_scroll (priv->right_window, 0, dy);
7964             }
7965       
7966           if (dx != 0)
7967             {
7968               if (priv->top_window)
7969                 text_window_scroll (priv->top_window, dx, 0);
7970               if (priv->bottom_window)
7971                 text_window_scroll (priv->bottom_window, dx, 0);
7972             }
7973       
7974           /* It looks nicer to scroll the main area last, because
7975            * it takes a while, and making the side areas update
7976            * afterward emphasizes the slowness of scrolling the
7977            * main area.
7978            */
7979           text_window_scroll (priv->text_window, dx, dy);
7980         }
7981       
7982       /* Children are now "moved" in the text window, poke
7983        * into widget->allocation for each child
7984        */
7985       tmp_list = priv->children;
7986       while (tmp_list != NULL)
7987         {
7988           GtkTextViewChild *child = tmp_list->data;
7989           
7990           if (child->anchor)
7991             adjust_allocation (child->widget, dx, dy);
7992           
7993           tmp_list = g_slist_next (tmp_list);
7994         }
7995     }
7996
7997   /* This could result in invalidation, which would install the
7998    * first_validate_idle, which would validate onscreen;
7999    * but we're going to go ahead and validate here, so
8000    * first_validate_idle shouldn't have anything to do.
8001    */
8002   gtk_text_view_update_layout_width (text_view);
8003   
8004   /* We also update the IM spot location here, since the IM context
8005    * might do something that leads to validation.
8006    */
8007   gtk_text_view_update_im_spot_location (text_view);
8008
8009   /* note that validation of onscreen could invoke this function
8010    * recursively, by scrolling to maintain first_para, or in response
8011    * to updating the layout width, however there is no problem with
8012    * that, or shouldn't be.
8013    */
8014   gtk_text_view_validate_onscreen (text_view);
8015   
8016   /* If this got installed, get rid of it, it's just a waste of time. */
8017   if (priv->first_validate_idle != 0)
8018     {
8019       g_source_remove (priv->first_validate_idle);
8020       priv->first_validate_idle = 0;
8021     }
8022
8023   /* Finally we update the IM cursor location again, to ensure any
8024    * changes made by the validation are pushed through.
8025    */
8026   gtk_text_view_update_im_spot_location (text_view);
8027
8028   gtk_text_view_update_handles (text_view,
8029                                 _gtk_text_handle_get_mode (priv->text_handle));
8030
8031   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
8032 }
8033
8034 static void
8035 gtk_text_view_commit_handler (GtkIMContext  *context,
8036                               const gchar   *str,
8037                               GtkTextView   *text_view)
8038 {
8039   gtk_text_view_commit_text (text_view, str);
8040 }
8041
8042 static void
8043 gtk_text_view_commit_text (GtkTextView   *text_view,
8044                            const gchar   *str)
8045 {
8046   GtkTextViewPrivate *priv;
8047   gboolean had_selection;
8048
8049   priv = text_view->priv;
8050
8051   gtk_text_buffer_begin_user_action (get_buffer (text_view));
8052
8053   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8054                                                         NULL, NULL);
8055   
8056   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8057                                     priv->editable);
8058
8059   if (!strcmp (str, "\n"))
8060     {
8061       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
8062                                                          priv->editable))
8063         {
8064           gtk_widget_error_bell (GTK_WIDGET (text_view));
8065         }
8066     }
8067   else
8068     {
8069       if (!had_selection && priv->overwrite_mode)
8070         {
8071           GtkTextIter insert;
8072
8073           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8074                                             &insert,
8075                                             gtk_text_buffer_get_insert (get_buffer (text_view)));
8076           if (!gtk_text_iter_ends_line (&insert))
8077             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
8078         }
8079
8080       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
8081                                                          priv->editable))
8082         {
8083           gtk_widget_error_bell (GTK_WIDGET (text_view));
8084         }
8085     }
8086
8087   gtk_text_buffer_end_user_action (get_buffer (text_view));
8088
8089   gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
8090   DV(g_print (G_STRLOC": scrolling onscreen\n"));
8091   gtk_text_view_scroll_mark_onscreen (text_view,
8092                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
8093 }
8094
8095 static void
8096 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
8097                                        GtkTextView  *text_view)
8098 {
8099   GtkTextViewPrivate *priv;
8100   gchar *str;
8101   PangoAttrList *attrs;
8102   gint cursor_pos;
8103   GtkTextIter iter;
8104
8105   priv = text_view->priv;
8106
8107   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8108                                     gtk_text_buffer_get_insert (priv->buffer));
8109
8110   /* Keypress events are passed to input method even if cursor position is
8111    * not editable; so beep here if it's multi-key input sequence, input
8112    * method will be reset in key-press-event handler.
8113    */
8114   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
8115
8116   if (str && str[0] && !gtk_text_iter_can_insert (&iter, priv->editable))
8117     {
8118       gtk_widget_error_bell (GTK_WIDGET (text_view));
8119       goto out;
8120     }
8121
8122   g_signal_emit (text_view, signals[PREEDIT_CHANGED], 0, str);
8123
8124   if (priv->layout)
8125     gtk_text_layout_set_preedit_string (priv->layout, str, attrs, cursor_pos);
8126   if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
8127     gtk_text_view_scroll_mark_onscreen (text_view,
8128                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8129
8130 out:
8131   pango_attr_list_unref (attrs);
8132   g_free (str);
8133 }
8134
8135 static gboolean
8136 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
8137                                             GtkTextView   *text_view)
8138 {
8139   GtkTextIter start;
8140   GtkTextIter end;
8141   gint pos;
8142   gchar *text;
8143
8144   gtk_text_buffer_get_iter_at_mark (text_view->priv->buffer, &start,
8145                                     gtk_text_buffer_get_insert (text_view->priv->buffer));
8146   end = start;
8147
8148   pos = gtk_text_iter_get_line_index (&start);
8149   gtk_text_iter_set_line_offset (&start, 0);
8150   gtk_text_iter_forward_to_line_end (&end);
8151
8152   text = gtk_text_iter_get_slice (&start, &end);
8153   gtk_im_context_set_surrounding (context, text, -1, pos);
8154   g_free (text);
8155
8156   return TRUE;
8157 }
8158
8159 static gboolean
8160 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
8161                                           gint           offset,
8162                                           gint           n_chars,
8163                                           GtkTextView   *text_view)
8164 {
8165   GtkTextViewPrivate *priv;
8166   GtkTextIter start;
8167   GtkTextIter end;
8168
8169   priv = text_view->priv;
8170
8171   gtk_text_buffer_get_iter_at_mark (priv->buffer, &start,
8172                                     gtk_text_buffer_get_insert (priv->buffer));
8173   end = start;
8174
8175   gtk_text_iter_forward_chars (&start, offset);
8176   gtk_text_iter_forward_chars (&end, offset + n_chars);
8177
8178   gtk_text_buffer_delete_interactive (priv->buffer, &start, &end,
8179                                       priv->editable);
8180
8181   return TRUE;
8182 }
8183
8184 static void
8185 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
8186                                 const GtkTextIter *location,
8187                                 GtkTextMark       *mark,
8188                                 gpointer           data)
8189 {
8190   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8191   gboolean need_reset = FALSE;
8192
8193   if (mark == gtk_text_buffer_get_insert (buffer))
8194     {
8195       text_view->priv->virtual_cursor_x = -1;
8196       text_view->priv->virtual_cursor_y = -1;
8197       gtk_text_view_update_im_spot_location (text_view);
8198       need_reset = TRUE;
8199     }
8200   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
8201     {
8202       need_reset = TRUE;
8203     }
8204
8205   if (need_reset)
8206     {
8207       gtk_text_view_reset_im_context (text_view);
8208       gtk_text_view_update_handles (text_view,
8209                                     _gtk_text_handle_get_mode (text_view->priv->text_handle));
8210     }
8211 }
8212
8213 static void
8214 gtk_text_view_target_list_notify (GtkTextBuffer    *buffer,
8215                                   const GParamSpec *pspec,
8216                                   gpointer          data)
8217 {
8218   GtkWidget     *widget = GTK_WIDGET (data);
8219   GtkTargetList *view_list;
8220   GtkTargetList *buffer_list;
8221   GList         *list;
8222
8223   view_list = gtk_drag_dest_get_target_list (widget);
8224   buffer_list = gtk_text_buffer_get_paste_target_list (buffer);
8225
8226   if (view_list)
8227     gtk_target_list_ref (view_list);
8228   else
8229     view_list = gtk_target_list_new (NULL, 0);
8230
8231   list = view_list->list;
8232   while (list)
8233     {
8234       GtkTargetPair *pair = list->data;
8235
8236       list = g_list_next (list); /* get next element before removing */
8237
8238       if (pair->info >= GTK_TEXT_BUFFER_TARGET_INFO_TEXT &&
8239           pair->info <= GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
8240         {
8241           gtk_target_list_remove (view_list, pair->target);
8242         }
8243     }
8244
8245   for (list = buffer_list->list; list; list = g_list_next (list))
8246     {
8247       GtkTargetPair *pair = list->data;
8248
8249       gtk_target_list_add (view_list, pair->target, pair->flags, pair->info);
8250     }
8251
8252   gtk_drag_dest_set_target_list (widget, view_list);
8253   gtk_target_list_unref (view_list);
8254 }
8255
8256 static void
8257 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
8258                                       GtkTextIter *cursor,
8259                                       gint        *x,
8260                                       gint        *y)
8261 {
8262   GtkTextViewPrivate *priv;
8263   GtkTextIter insert;
8264   GdkRectangle pos;
8265
8266   priv = text_view->priv;
8267
8268   if (cursor)
8269     insert = *cursor;
8270   else
8271     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
8272                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
8273
8274   if ((x && priv->virtual_cursor_x == -1) ||
8275       (y && priv->virtual_cursor_y == -1))
8276     gtk_text_layout_get_cursor_locations (priv->layout, &insert, &pos, NULL);
8277
8278   if (x)
8279     {
8280       if (priv->virtual_cursor_x != -1)
8281         *x = priv->virtual_cursor_x;
8282       else
8283         *x = pos.x;
8284     }
8285
8286   if (y)
8287     {
8288       if (priv->virtual_cursor_x != -1)
8289         *y = priv->virtual_cursor_y;
8290       else
8291         *y = pos.y + pos.height / 2;
8292     }
8293 }
8294
8295 static void
8296 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
8297                                       gint         x,
8298                                       gint         y)
8299 {
8300   GdkRectangle pos;
8301
8302   if (!text_view->priv->layout)
8303     return;
8304
8305   if (x == -1 || y == -1)
8306     gtk_text_view_get_cursor_locations (text_view, NULL, &pos, NULL);
8307
8308   text_view->priv->virtual_cursor_x = (x == -1) ? pos.x : x;
8309   text_view->priv->virtual_cursor_y = (y == -1) ? pos.y + pos.height / 2 : y;
8310 }
8311
8312 /* Quick hack of a popup menu
8313  */
8314 static void
8315 activate_cb (GtkWidget   *menuitem,
8316              GtkTextView *text_view)
8317 {
8318   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
8319   g_signal_emit_by_name (text_view, signal);
8320 }
8321
8322 static void
8323 append_action_signal (GtkTextView  *text_view,
8324                       GtkWidget    *menu,
8325                       const gchar  *stock_id,
8326                       const gchar  *signal,
8327                       gboolean      sensitive)
8328 {
8329   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
8330
8331   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
8332   g_signal_connect (menuitem, "activate",
8333                     G_CALLBACK (activate_cb), text_view);
8334
8335   gtk_widget_set_sensitive (menuitem, sensitive);
8336   
8337   gtk_widget_show (menuitem);
8338   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
8339 }
8340
8341 static void
8342 gtk_text_view_select_all (GtkWidget *widget,
8343                           gboolean select)
8344 {
8345   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
8346   GtkTextBuffer *buffer;
8347   GtkTextIter start_iter, end_iter, insert;
8348
8349   buffer = text_view->priv->buffer;
8350   if (select) 
8351     {
8352       gtk_text_buffer_get_bounds (buffer, &start_iter, &end_iter);
8353       gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
8354     }
8355   else 
8356     {
8357       gtk_text_buffer_get_iter_at_mark (buffer, &insert,
8358                                         gtk_text_buffer_get_insert (buffer));
8359       gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &insert);
8360     }
8361 }
8362
8363 static void
8364 select_all_cb (GtkWidget   *menuitem,
8365                GtkTextView *text_view)
8366 {
8367   gtk_text_view_select_all (GTK_WIDGET (text_view), TRUE);
8368 }
8369
8370 static void
8371 delete_cb (GtkTextView *text_view)
8372 {
8373   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8374                                     text_view->priv->editable);
8375 }
8376
8377 static void
8378 popup_menu_detach (GtkWidget *attach_widget,
8379                    GtkMenu   *menu)
8380 {
8381   GTK_TEXT_VIEW (attach_widget)->priv->popup_menu = NULL;
8382 }
8383
8384 static void
8385 popup_position_func (GtkMenu   *menu,
8386                      gint      *x,
8387                      gint      *y,
8388                      gboolean  *push_in,
8389                      gpointer   user_data)
8390 {
8391   GtkAllocation allocation;
8392   GtkTextView *text_view;
8393   GtkWidget *widget;
8394   GdkRectangle cursor_rect;
8395   GdkRectangle onscreen_rect;
8396   gint root_x, root_y;
8397   GtkTextIter iter;
8398   GtkRequisition req;      
8399   GdkScreen *screen;
8400   gint monitor_num;
8401   GdkRectangle monitor;
8402       
8403   text_view = GTK_TEXT_VIEW (user_data);
8404   widget = GTK_WIDGET (text_view);
8405   
8406   g_return_if_fail (gtk_widget_get_realized (widget));
8407   
8408   screen = gtk_widget_get_screen (widget);
8409
8410   gdk_window_get_origin (gtk_widget_get_window (widget),
8411                          &root_x, &root_y);
8412
8413   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8414                                     &iter,
8415                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
8416
8417   gtk_text_view_get_iter_location (text_view,
8418                                    &iter,
8419                                    &cursor_rect);
8420
8421   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
8422
8423   gtk_widget_get_preferred_size (text_view->priv->popup_menu,
8424                                  &req, NULL);
8425
8426   gtk_widget_get_allocation (widget, &allocation);
8427
8428   /* can't use rectangle_intersect since cursor rect can have 0 width */
8429   if (cursor_rect.x >= onscreen_rect.x &&
8430       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
8431       cursor_rect.y >= onscreen_rect.y &&
8432       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
8433     {    
8434       gtk_text_view_buffer_to_window_coords (text_view,
8435                                              GTK_TEXT_WINDOW_WIDGET,
8436                                              cursor_rect.x, cursor_rect.y,
8437                                              &cursor_rect.x, &cursor_rect.y);
8438
8439       *x = root_x + cursor_rect.x + cursor_rect.width;
8440       *y = root_y + cursor_rect.y + cursor_rect.height;
8441     }
8442   else
8443     {
8444       /* Just center the menu, since cursor is offscreen. */
8445       *x = root_x + (allocation.width / 2 - req.width / 2);
8446       *y = root_y + (allocation.height / 2 - req.height / 2);
8447     }
8448
8449   /* Ensure sanity */
8450   *x = CLAMP (*x, root_x, (root_x + allocation.width));
8451   *y = CLAMP (*y, root_y, (root_y + allocation.height));
8452
8453   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
8454   gtk_menu_set_monitor (menu, monitor_num);
8455   gdk_screen_get_monitor_workarea (screen, monitor_num, &monitor);
8456
8457   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
8458   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
8459
8460   *push_in = FALSE;
8461 }
8462
8463 typedef struct
8464 {
8465   GtkTextView *text_view;
8466   gint button;
8467   guint time;
8468   GdkDevice *device;
8469 } PopupInfo;
8470
8471 static gboolean
8472 range_contains_editable_text (const GtkTextIter *start,
8473                               const GtkTextIter *end,
8474                               gboolean default_editability)
8475 {
8476   GtkTextIter iter = *start;
8477
8478   while (gtk_text_iter_compare (&iter, end) < 0)
8479     {
8480       if (gtk_text_iter_editable (&iter, default_editability))
8481         return TRUE;
8482       
8483       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
8484     }
8485
8486   return FALSE;
8487 }                             
8488
8489 static void
8490 unichar_chosen_func (const char *text,
8491                      gpointer    data)
8492 {
8493   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8494
8495   gtk_text_view_commit_text (text_view, text);
8496 }
8497
8498 static void
8499 popup_targets_received (GtkClipboard     *clipboard,
8500                         GtkSelectionData *data,
8501                         gpointer          user_data)
8502 {
8503   PopupInfo *info = user_data;
8504   GtkTextView *text_view;
8505   GtkTextViewPrivate *priv;
8506
8507   text_view = info->text_view;
8508   priv = text_view->priv;
8509
8510   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
8511     {
8512       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
8513        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
8514        */
8515       gboolean clipboard_contains_text;
8516       GtkWidget *menuitem;
8517       GtkWidget *submenu;
8518       gboolean have_selection;
8519       gboolean can_insert;
8520       GtkTextIter iter;
8521       GtkTextIter sel_start, sel_end;
8522       gboolean show_input_method_menu;
8523       gboolean show_unicode_menu;
8524       
8525       clipboard_contains_text = gtk_selection_data_targets_include_text (data);
8526
8527       if (priv->popup_menu)
8528         gtk_widget_destroy (priv->popup_menu);
8529
8530       priv->popup_menu = gtk_menu_new ();
8531       
8532       gtk_menu_attach_to_widget (GTK_MENU (priv->popup_menu),
8533                                  GTK_WIDGET (text_view),
8534                                  popup_menu_detach);
8535       
8536       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8537                                                              &sel_start, &sel_end);
8538       
8539       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8540                                         &iter,
8541                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8542       
8543       can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
8544       
8545       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_CUT, "cut-clipboard",
8546                             have_selection &&
8547                             range_contains_editable_text (&sel_start, &sel_end,
8548                                                           priv->editable));
8549       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_COPY, "copy-clipboard",
8550                             have_selection);
8551       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_PASTE, "paste-clipboard",
8552                             can_insert && clipboard_contains_text);
8553       
8554       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
8555       gtk_widget_set_sensitive (menuitem, 
8556                                 have_selection &&
8557                                 range_contains_editable_text (&sel_start, &sel_end,
8558                                                               priv->editable));
8559       g_signal_connect_swapped (menuitem, "activate",
8560                                 G_CALLBACK (delete_cb), text_view);
8561       gtk_widget_show (menuitem);
8562       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8563
8564       menuitem = gtk_separator_menu_item_new ();
8565       gtk_widget_show (menuitem);
8566       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8567
8568       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
8569       gtk_widget_set_sensitive (menuitem,
8570                                 gtk_text_buffer_get_char_count (priv->buffer) > 0);
8571       g_signal_connect (menuitem, "activate",
8572                         G_CALLBACK (select_all_cb), text_view);
8573       gtk_widget_show (menuitem);
8574       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8575
8576       g_object_get (gtk_widget_get_settings (GTK_WIDGET (text_view)),
8577                     "gtk-show-input-method-menu", &show_input_method_menu,
8578                     "gtk-show-unicode-menu", &show_unicode_menu,
8579                     NULL);
8580       
8581       if (show_input_method_menu || show_unicode_menu)
8582         {
8583           menuitem = gtk_separator_menu_item_new ();
8584           gtk_widget_show (menuitem);
8585           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8586         }
8587
8588       if (show_input_method_menu)
8589         {
8590           menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
8591           gtk_widget_show (menuitem);
8592           gtk_widget_set_sensitive (menuitem, can_insert);
8593
8594           submenu = gtk_menu_new ();
8595           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8596           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8597           
8598           gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (priv->im_context),
8599                                                 GTK_MENU_SHELL (submenu));
8600         }
8601
8602       if (show_unicode_menu)
8603         {
8604           menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
8605           gtk_widget_show (menuitem);
8606           gtk_widget_set_sensitive (menuitem, can_insert);
8607       
8608           submenu = gtk_menu_new ();
8609           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8610           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8611           
8612           _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
8613                                                         unichar_chosen_func,
8614                                                         text_view);
8615         }
8616           
8617       g_signal_emit (text_view,
8618                      signals[POPULATE_POPUP],
8619                      0,
8620                      priv->popup_menu);
8621       
8622       if (info->device)
8623         gtk_menu_popup_for_device (GTK_MENU (priv->popup_menu), 
8624       info->device, NULL, NULL, NULL, NULL, NULL,
8625                         info->button, info->time);
8626       else
8627         {
8628           gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL,
8629                           popup_position_func, text_view,
8630                           0, gtk_get_current_event_time ());
8631           gtk_menu_shell_select_first (GTK_MENU_SHELL (priv->popup_menu), FALSE);
8632         }
8633     }
8634
8635   g_object_unref (text_view);
8636   g_free (info);
8637 }
8638
8639 static void
8640 gtk_text_view_do_popup (GtkTextView    *text_view,
8641                         GdkEventButton *event)
8642 {
8643   PopupInfo *info = g_new (PopupInfo, 1);
8644
8645   /* In order to know what entries we should make sensitive, we
8646    * ask for the current targets of the clipboard, and when
8647    * we get them, then we actually pop up the menu.
8648    */
8649   info->text_view = g_object_ref (text_view);
8650   
8651   if (event)
8652     {
8653       info->button = event->button;
8654       info->time = event->time;
8655       info->device = event->device;
8656     }
8657   else
8658     {
8659       info->button = 0;
8660       info->time = gtk_get_current_event_time ();
8661       info->device = NULL;
8662     }
8663
8664   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
8665                                                             GDK_SELECTION_CLIPBOARD),
8666                                   gdk_atom_intern_static_string ("TARGETS"),
8667                                   popup_targets_received,
8668                                   info);
8669 }
8670
8671 static gboolean
8672 gtk_text_view_popup_menu (GtkWidget *widget)
8673 {
8674   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
8675   return TRUE;
8676 }
8677
8678 /* Child GdkWindows */
8679
8680
8681 static GtkTextWindow*
8682 text_window_new (GtkTextWindowType  type,
8683                  GtkWidget         *widget,
8684                  gint               width_request,
8685                  gint               height_request)
8686 {
8687   GtkTextWindow *win;
8688
8689   win = g_new (GtkTextWindow, 1);
8690
8691   win->type = type;
8692   win->widget = widget;
8693   win->window = NULL;
8694   win->bin_window = NULL;
8695   win->requisition.width = width_request;
8696   win->requisition.height = height_request;
8697   win->allocation.width = width_request;
8698   win->allocation.height = height_request;
8699   win->allocation.x = 0;
8700   win->allocation.y = 0;
8701
8702   return win;
8703 }
8704
8705 static void
8706 text_window_free (GtkTextWindow *win)
8707 {
8708   if (win->window)
8709     text_window_unrealize (win);
8710
8711   g_free (win);
8712 }
8713
8714 static void
8715 text_window_realize (GtkTextWindow *win,
8716                      GtkWidget     *widget)
8717 {
8718   GtkStyleContext *context;
8719   GtkStateFlags state;
8720   GdkWindow *window;
8721   GdkWindowAttr attributes;
8722   gint attributes_mask;
8723   GdkCursor *cursor;
8724   GdkRGBA color;
8725
8726   attributes.window_type = GDK_WINDOW_CHILD;
8727   attributes.x = win->allocation.x;
8728   attributes.y = win->allocation.y;
8729   attributes.width = win->allocation.width;
8730   attributes.height = win->allocation.height;
8731   attributes.wclass = GDK_INPUT_OUTPUT;
8732   attributes.visual = gtk_widget_get_visual (win->widget);
8733   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
8734
8735   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
8736
8737   window = gtk_widget_get_window (widget);
8738
8739   win->window = gdk_window_new (window,
8740                                 &attributes, attributes_mask);
8741
8742   gdk_window_show (win->window);
8743   gdk_window_set_user_data (win->window, win->widget);
8744   gdk_window_lower (win->window);
8745
8746   attributes.x = 0;
8747   attributes.y = 0;
8748   attributes.width = win->allocation.width;
8749   attributes.height = win->allocation.height;
8750   attributes.event_mask = (GDK_EXPOSURE_MASK            |
8751                            GDK_SCROLL_MASK              |
8752                            GDK_SMOOTH_SCROLL_MASK       |
8753                            GDK_KEY_PRESS_MASK           |
8754                            GDK_BUTTON_PRESS_MASK        |
8755                            GDK_BUTTON_RELEASE_MASK      |
8756                            GDK_POINTER_MOTION_MASK      |
8757                            GDK_POINTER_MOTION_HINT_MASK |
8758                            gtk_widget_get_events (win->widget));
8759
8760   win->bin_window = gdk_window_new (win->window,
8761                                     &attributes,
8762                                     attributes_mask);
8763
8764   gdk_window_show (win->bin_window);
8765   gdk_window_set_user_data (win->bin_window, win->widget);
8766
8767   context = gtk_widget_get_style_context (widget);
8768   state = gtk_widget_get_state_flags (widget);
8769
8770   if (win->type == GTK_TEXT_WINDOW_TEXT)
8771     {
8772       if (gtk_widget_is_sensitive (widget))
8773         {
8774           /* I-beam cursor */
8775           cursor = gdk_cursor_new_for_display (gdk_window_get_display (window),
8776                                                GDK_XTERM);
8777           gdk_window_set_cursor (win->bin_window, cursor);
8778           g_object_unref (cursor);
8779         } 
8780
8781       gtk_im_context_set_client_window (GTK_TEXT_VIEW (widget)->priv->im_context,
8782                                         win->window);
8783
8784       gtk_style_context_save (context);
8785       gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
8786
8787       gtk_style_context_get_background_color (context, state, &color);
8788       gdk_window_set_background_rgba (win->bin_window, &color);
8789
8790       gtk_style_context_restore (context);
8791     }
8792   else
8793     {
8794       gtk_style_context_get_background_color (context, state, &color);
8795       gdk_window_set_background_rgba (win->bin_window, &color);
8796     }
8797
8798   g_object_set_qdata (G_OBJECT (win->window),
8799                       g_quark_from_static_string ("gtk-text-view-text-window"),
8800                       win);
8801
8802   g_object_set_qdata (G_OBJECT (win->bin_window),
8803                       g_quark_from_static_string ("gtk-text-view-text-window"),
8804                       win);
8805 }
8806
8807 static void
8808 text_window_unrealize (GtkTextWindow *win)
8809 {
8810   if (win->type == GTK_TEXT_WINDOW_TEXT)
8811     {
8812       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->priv->im_context,
8813                                         NULL);
8814     }
8815
8816   gdk_window_set_user_data (win->window, NULL);
8817   gdk_window_set_user_data (win->bin_window, NULL);
8818   gdk_window_destroy (win->bin_window);
8819   gdk_window_destroy (win->window);
8820   win->window = NULL;
8821   win->bin_window = NULL;
8822 }
8823
8824 static void
8825 text_window_size_allocate (GtkTextWindow *win,
8826                            GdkRectangle  *rect)
8827 {
8828   win->allocation = *rect;
8829
8830   if (win->window)
8831     {
8832       gdk_window_move_resize (win->window,
8833                               rect->x, rect->y,
8834                               rect->width, rect->height);
8835
8836       gdk_window_resize (win->bin_window,
8837                          rect->width, rect->height);
8838     }
8839 }
8840
8841 static void
8842 text_window_scroll        (GtkTextWindow *win,
8843                            gint           dx,
8844                            gint           dy)
8845 {
8846   if (dx != 0 || dy != 0)
8847     {
8848       gdk_window_scroll (win->bin_window, dx, dy);
8849     }
8850 }
8851
8852 static void
8853 text_window_invalidate_rect (GtkTextWindow *win,
8854                              GdkRectangle  *rect)
8855 {
8856   GdkRectangle window_rect;
8857
8858   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
8859                                          win->type,
8860                                          rect->x,
8861                                          rect->y,
8862                                          &window_rect.x,
8863                                          &window_rect.y);
8864
8865   window_rect.width = rect->width;
8866   window_rect.height = rect->height;
8867   
8868   /* Adjust the rect as appropriate */
8869   
8870   switch (win->type)
8871     {
8872     case GTK_TEXT_WINDOW_TEXT:
8873       break;
8874
8875     case GTK_TEXT_WINDOW_LEFT:
8876     case GTK_TEXT_WINDOW_RIGHT:
8877       window_rect.x = 0;
8878       window_rect.width = win->allocation.width;
8879       break;
8880
8881     case GTK_TEXT_WINDOW_TOP:
8882     case GTK_TEXT_WINDOW_BOTTOM:
8883       window_rect.y = 0;
8884       window_rect.height = win->allocation.height;
8885       break;
8886
8887     default:
8888       g_warning ("%s: bug!", G_STRFUNC);
8889       return;
8890       break;
8891     }
8892           
8893   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
8894
8895 #if 0
8896   {
8897     cairo_t *cr = gdk_cairo_create (win->bin_window);
8898     gdk_cairo_rectangle (cr, &window_rect);
8899     cairo_set_source_rgb  (cr, 1.0, 0.0, 0.0);  /* red */
8900     cairo_fill (cr);
8901     cairo_destroy (cr);
8902   }
8903 #endif
8904 }
8905
8906 static void
8907 text_window_invalidate_cursors (GtkTextWindow *win)
8908 {
8909   GtkTextView *text_view;
8910   GtkTextViewPrivate *priv;
8911   GtkTextIter  iter;
8912   GdkRectangle strong;
8913   GdkRectangle weak;
8914   gboolean     draw_arrow;
8915   gfloat       cursor_aspect_ratio;
8916   gint         stem_width;
8917   gint         arrow_width;
8918
8919   text_view = GTK_TEXT_VIEW (win->widget);
8920   priv = text_view->priv;
8921
8922   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8923                                     gtk_text_buffer_get_insert (priv->buffer));
8924
8925   if (_gtk_text_layout_get_block_cursor (priv->layout, &strong))
8926     {
8927       text_window_invalidate_rect (win, &strong);
8928       return;
8929     }
8930
8931   gtk_text_layout_get_cursor_locations (priv->layout, &iter,
8932                                         &strong, &weak);
8933
8934   /* cursor width calculation as in gtkstylecontext.c:draw_insertion_cursor(),
8935    * ignoring the text direction be exposing both sides of the cursor
8936    */
8937
8938   draw_arrow = (strong.x != weak.x || strong.y != weak.y);
8939
8940   gtk_widget_style_get (win->widget,
8941                         "cursor-aspect-ratio", &cursor_aspect_ratio,
8942                         NULL);
8943   
8944   stem_width = strong.height * cursor_aspect_ratio + 1;
8945   arrow_width = stem_width + 1;
8946
8947   strong.width = stem_width;
8948
8949   /* round up to the next even number */
8950   if (stem_width & 1)
8951     stem_width++;
8952
8953   strong.x     -= stem_width / 2;
8954   strong.width += stem_width;
8955
8956   if (draw_arrow)
8957     {
8958       strong.x     -= arrow_width;
8959       strong.width += arrow_width * 2;
8960     }
8961
8962   text_window_invalidate_rect (win, &strong);
8963
8964   if (draw_arrow) /* == have weak */
8965     {
8966       stem_width = weak.height * cursor_aspect_ratio + 1;
8967       arrow_width = stem_width + 1;
8968
8969       weak.width = stem_width;
8970
8971       /* round up to the next even number */
8972       if (stem_width & 1)
8973         stem_width++;
8974
8975       weak.x     -= stem_width / 2;
8976       weak.width += stem_width;
8977
8978       weak.x     -= arrow_width;
8979       weak.width += arrow_width * 2;
8980
8981       text_window_invalidate_rect (win, &weak);
8982     }
8983 }
8984
8985 static gint
8986 text_window_get_width (GtkTextWindow *win)
8987 {
8988   return win->allocation.width;
8989 }
8990
8991 static gint
8992 text_window_get_height (GtkTextWindow *win)
8993 {
8994   return win->allocation.height;
8995 }
8996
8997 /* Windows */
8998
8999
9000 /**
9001  * gtk_text_view_get_window:
9002  * @text_view: a #GtkTextView
9003  * @win: window to get
9004  *
9005  * Retrieves the #GdkWindow corresponding to an area of the text view;
9006  * possible windows include the overall widget window, child windows
9007  * on the left, right, top, bottom, and the window that displays the
9008  * text buffer. Windows are %NULL and nonexistent if their width or
9009  * height is 0, and are nonexistent before the widget has been
9010  * realized.
9011  *
9012  * Return value: (transfer none): a #GdkWindow, or %NULL
9013  **/
9014 GdkWindow*
9015 gtk_text_view_get_window (GtkTextView *text_view,
9016                           GtkTextWindowType win)
9017 {
9018   GtkTextViewPrivate *priv = text_view->priv;
9019
9020   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
9021
9022   switch (win)
9023     {
9024     case GTK_TEXT_WINDOW_WIDGET:
9025       return gtk_widget_get_window (GTK_WIDGET (text_view));
9026       break;
9027
9028     case GTK_TEXT_WINDOW_TEXT:
9029       return priv->text_window->bin_window;
9030       break;
9031
9032     case GTK_TEXT_WINDOW_LEFT:
9033       if (priv->left_window)
9034         return priv->left_window->bin_window;
9035       else
9036         return NULL;
9037       break;
9038
9039     case GTK_TEXT_WINDOW_RIGHT:
9040       if (priv->right_window)
9041         return priv->right_window->bin_window;
9042       else
9043         return NULL;
9044       break;
9045
9046     case GTK_TEXT_WINDOW_TOP:
9047       if (priv->top_window)
9048         return priv->top_window->bin_window;
9049       else
9050         return NULL;
9051       break;
9052
9053     case GTK_TEXT_WINDOW_BOTTOM:
9054       if (priv->bottom_window)
9055         return priv->bottom_window->bin_window;
9056       else
9057         return NULL;
9058       break;
9059
9060     case GTK_TEXT_WINDOW_PRIVATE:
9061       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_STRFUNC);
9062       return NULL;
9063       break;
9064     }
9065
9066   g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9067   return NULL;
9068 }
9069
9070 /**
9071  * gtk_text_view_get_window_type:
9072  * @text_view: a #GtkTextView
9073  * @window: a window type
9074  *
9075  * Usually used to find out which window an event corresponds to.
9076  * If you connect to an event signal on @text_view, this function
9077  * should be called on <literal>event-&gt;window</literal> to
9078  * see which window it was.
9079  *
9080  * Return value: the window type.
9081  **/
9082 GtkTextWindowType
9083 gtk_text_view_get_window_type (GtkTextView *text_view,
9084                                GdkWindow   *window)
9085 {
9086   GtkTextWindow *win;
9087
9088   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9089   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
9090
9091   if (window == gtk_widget_get_window (GTK_WIDGET (text_view)))
9092     return GTK_TEXT_WINDOW_WIDGET;
9093
9094   win = g_object_get_qdata (G_OBJECT (window),
9095                             g_quark_try_string ("gtk-text-view-text-window"));
9096
9097   if (win)
9098     return win->type;
9099   else
9100     {
9101       return GTK_TEXT_WINDOW_PRIVATE;
9102     }
9103 }
9104
9105 static void
9106 buffer_to_widget (GtkTextView      *text_view,
9107                   gint              buffer_x,
9108                   gint              buffer_y,
9109                   gint             *window_x,
9110                   gint             *window_y)
9111 {
9112   GtkTextViewPrivate *priv = text_view->priv;
9113
9114   if (window_x)
9115     {
9116       *window_x = buffer_x - priv->xoffset;
9117       *window_x += priv->text_window->allocation.x;
9118     }
9119
9120   if (window_y)
9121     {
9122       *window_y = buffer_y - priv->yoffset;
9123       *window_y += priv->text_window->allocation.y;
9124     }
9125 }
9126
9127 static void
9128 widget_to_text_window (GtkTextWindow *win,
9129                        gint           widget_x,
9130                        gint           widget_y,
9131                        gint          *window_x,
9132                        gint          *window_y)
9133 {
9134   if (window_x)
9135     *window_x = widget_x - win->allocation.x;
9136
9137   if (window_y)
9138     *window_y = widget_y - win->allocation.y;
9139 }
9140
9141 static void
9142 buffer_to_text_window (GtkTextView   *text_view,
9143                        GtkTextWindow *win,
9144                        gint           buffer_x,
9145                        gint           buffer_y,
9146                        gint          *window_x,
9147                        gint          *window_y)
9148 {
9149   if (win == NULL)
9150     {
9151       g_warning ("Attempt to convert text buffer coordinates to coordinates "
9152                  "for a nonexistent or private child window of GtkTextView");
9153       return;
9154     }
9155
9156   buffer_to_widget (text_view,
9157                     buffer_x, buffer_y,
9158                     window_x, window_y);
9159
9160   widget_to_text_window (win,
9161                          window_x ? *window_x : 0,
9162                          window_y ? *window_y : 0,
9163                          window_x,
9164                          window_y);
9165 }
9166
9167 /**
9168  * gtk_text_view_buffer_to_window_coords:
9169  * @text_view: a #GtkTextView
9170  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
9171  * @buffer_x: buffer x coordinate
9172  * @buffer_y: buffer y coordinate
9173  * @window_x: (out) (allow-none): window x coordinate return location or %NULL
9174  * @window_y: (out) (allow-none): window y coordinate return location or %NULL
9175  *
9176  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
9177  * @win, and stores the result in (@window_x, @window_y). 
9178  *
9179  * Note that you can't convert coordinates for a nonexisting window (see 
9180  * gtk_text_view_set_border_window_size()).
9181  **/
9182 void
9183 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
9184                                        GtkTextWindowType win,
9185                                        gint              buffer_x,
9186                                        gint              buffer_y,
9187                                        gint             *window_x,
9188                                        gint             *window_y)
9189 {
9190   GtkTextViewPrivate *priv = text_view->priv;
9191
9192   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9193
9194   switch (win)
9195     {
9196     case GTK_TEXT_WINDOW_WIDGET:
9197       buffer_to_widget (text_view,
9198                         buffer_x, buffer_y,
9199                         window_x, window_y);
9200       break;
9201
9202     case GTK_TEXT_WINDOW_TEXT:
9203       if (window_x)
9204         *window_x = buffer_x - priv->xoffset;
9205       if (window_y)
9206         *window_y = buffer_y - priv->yoffset;
9207       break;
9208
9209     case GTK_TEXT_WINDOW_LEFT:
9210       buffer_to_text_window (text_view,
9211                              priv->left_window,
9212                              buffer_x, buffer_y,
9213                              window_x, window_y);
9214       break;
9215
9216     case GTK_TEXT_WINDOW_RIGHT:
9217       buffer_to_text_window (text_view,
9218                              priv->right_window,
9219                              buffer_x, buffer_y,
9220                              window_x, window_y);
9221       break;
9222
9223     case GTK_TEXT_WINDOW_TOP:
9224       buffer_to_text_window (text_view,
9225                              priv->top_window,
9226                              buffer_x, buffer_y,
9227                              window_x, window_y);
9228       break;
9229
9230     case GTK_TEXT_WINDOW_BOTTOM:
9231       buffer_to_text_window (text_view,
9232                              priv->bottom_window,
9233                              buffer_x, buffer_y,
9234                              window_x, window_y);
9235       break;
9236
9237     case GTK_TEXT_WINDOW_PRIVATE:
9238       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9239       break;
9240
9241     default:
9242       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9243       break;
9244     }
9245 }
9246
9247 static void
9248 widget_to_buffer (GtkTextView *text_view,
9249                   gint         widget_x,
9250                   gint         widget_y,
9251                   gint        *buffer_x,
9252                   gint        *buffer_y)
9253 {
9254   GtkTextViewPrivate *priv = text_view->priv;
9255
9256   if (buffer_x)
9257     {
9258       *buffer_x = widget_x + priv->xoffset;
9259       *buffer_x -= priv->text_window->allocation.x;
9260     }
9261
9262   if (buffer_y)
9263     {
9264       *buffer_y = widget_y + priv->yoffset;
9265       *buffer_y -= priv->text_window->allocation.y;
9266     }
9267 }
9268
9269 static void
9270 text_window_to_widget (GtkTextWindow *win,
9271                        gint           window_x,
9272                        gint           window_y,
9273                        gint          *widget_x,
9274                        gint          *widget_y)
9275 {
9276   if (widget_x)
9277     *widget_x = window_x + win->allocation.x;
9278
9279   if (widget_y)
9280     *widget_y = window_y + win->allocation.y;
9281 }
9282
9283 static void
9284 text_window_to_buffer (GtkTextView   *text_view,
9285                        GtkTextWindow *win,
9286                        gint           window_x,
9287                        gint           window_y,
9288                        gint          *buffer_x,
9289                        gint          *buffer_y)
9290 {
9291   if (win == NULL)
9292     {
9293       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
9294                  "coordinates for a nonexistent child window.");
9295       return;
9296     }
9297
9298   text_window_to_widget (win,
9299                          window_x,
9300                          window_y,
9301                          buffer_x,
9302                          buffer_y);
9303
9304   widget_to_buffer (text_view,
9305                     buffer_x ? *buffer_x : 0,
9306                     buffer_y ? *buffer_y : 0,
9307                     buffer_x,
9308                     buffer_y);
9309 }
9310
9311 /**
9312  * gtk_text_view_window_to_buffer_coords:
9313  * @text_view: a #GtkTextView
9314  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
9315  * @window_x: window x coordinate
9316  * @window_y: window y coordinate
9317  * @buffer_x: (out) (allow-none): buffer x coordinate return location or %NULL
9318  * @buffer_y: (out) (allow-none): buffer y coordinate return location or %NULL
9319  *
9320  * Converts coordinates on the window identified by @win to buffer
9321  * coordinates, storing the result in (@buffer_x,@buffer_y).
9322  *
9323  * Note that you can't convert coordinates for a nonexisting window (see 
9324  * gtk_text_view_set_border_window_size()).
9325  **/
9326 void
9327 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
9328                                        GtkTextWindowType win,
9329                                        gint              window_x,
9330                                        gint              window_y,
9331                                        gint             *buffer_x,
9332                                        gint             *buffer_y)
9333 {
9334   GtkTextViewPrivate *priv = text_view->priv;
9335
9336   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9337
9338   switch (win)
9339     {
9340     case GTK_TEXT_WINDOW_WIDGET:
9341       widget_to_buffer (text_view,
9342                         window_x, window_y,
9343                         buffer_x, buffer_y);
9344       break;
9345
9346     case GTK_TEXT_WINDOW_TEXT:
9347       if (buffer_x)
9348         *buffer_x = window_x + priv->xoffset;
9349       if (buffer_y)
9350         *buffer_y = window_y + priv->yoffset;
9351       break;
9352
9353     case GTK_TEXT_WINDOW_LEFT:
9354       text_window_to_buffer (text_view,
9355                              priv->left_window,
9356                              window_x, window_y,
9357                              buffer_x, buffer_y);
9358       break;
9359
9360     case GTK_TEXT_WINDOW_RIGHT:
9361       text_window_to_buffer (text_view,
9362                              priv->right_window,
9363                              window_x, window_y,
9364                              buffer_x, buffer_y);
9365       break;
9366
9367     case GTK_TEXT_WINDOW_TOP:
9368       text_window_to_buffer (text_view,
9369                              priv->top_window,
9370                              window_x, window_y,
9371                              buffer_x, buffer_y);
9372       break;
9373
9374     case GTK_TEXT_WINDOW_BOTTOM:
9375       text_window_to_buffer (text_view,
9376                              priv->bottom_window,
9377                              window_x, window_y,
9378                              buffer_x, buffer_y);
9379       break;
9380
9381     case GTK_TEXT_WINDOW_PRIVATE:
9382       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9383       break;
9384
9385     default:
9386       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9387       break;
9388     }
9389 }
9390
9391 static void
9392 set_window_width (GtkTextView      *text_view,
9393                   gint              width,
9394                   GtkTextWindowType type,
9395                   GtkTextWindow   **winp)
9396 {
9397   if (width == 0)
9398     {
9399       if (*winp)
9400         {
9401           text_window_free (*winp);
9402           *winp = NULL;
9403           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9404         }
9405     }
9406   else
9407     {
9408       if (*winp == NULL)
9409         {
9410           *winp = text_window_new (type,
9411                                    GTK_WIDGET (text_view),
9412                                    width, 0);
9413           /* if the widget is already realized we need to realize the child manually */
9414           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9415             text_window_realize (*winp, GTK_WIDGET (text_view));
9416         }
9417       else
9418         {
9419           if ((*winp)->requisition.width == width)
9420             return;
9421
9422           (*winp)->requisition.width = width;
9423         }
9424
9425       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9426     }
9427 }
9428
9429
9430 static void
9431 set_window_height (GtkTextView      *text_view,
9432                    gint              height,
9433                    GtkTextWindowType type,
9434                    GtkTextWindow   **winp)
9435 {
9436   if (height == 0)
9437     {
9438       if (*winp)
9439         {
9440           text_window_free (*winp);
9441           *winp = NULL;
9442           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9443         }
9444     }
9445   else
9446     {
9447       if (*winp == NULL)
9448         {
9449           *winp = text_window_new (type,
9450                                    GTK_WIDGET (text_view),
9451                                    0, height);
9452
9453           /* if the widget is already realized we need to realize the child manually */
9454           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9455             text_window_realize (*winp, GTK_WIDGET (text_view));
9456         }
9457       else
9458         {
9459           if ((*winp)->requisition.height == height)
9460             return;
9461
9462           (*winp)->requisition.height = height;
9463         }
9464
9465       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9466     }
9467 }
9468
9469 /**
9470  * gtk_text_view_set_border_window_size:
9471  * @text_view: a #GtkTextView
9472  * @type: window to affect
9473  * @size: width or height of the window
9474  *
9475  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
9476  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
9477  * Automatically destroys the corresponding window if the size is set
9478  * to 0, and creates the window if the size is set to non-zero.  This
9479  * function can only be used for the "border windows," it doesn't work
9480  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
9481  * #GTK_TEXT_WINDOW_PRIVATE.
9482  **/
9483 void
9484 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
9485                                       GtkTextWindowType type,
9486                                       gint              size)
9487 {
9488   GtkTextViewPrivate *priv = text_view->priv;
9489
9490   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9491   g_return_if_fail (size >= 0);
9492
9493   switch (type)
9494     {
9495     case GTK_TEXT_WINDOW_LEFT:
9496       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
9497                         &priv->left_window);
9498       break;
9499
9500     case GTK_TEXT_WINDOW_RIGHT:
9501       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
9502                         &priv->right_window);
9503       break;
9504
9505     case GTK_TEXT_WINDOW_TOP:
9506       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
9507                          &priv->top_window);
9508       break;
9509
9510     case GTK_TEXT_WINDOW_BOTTOM:
9511       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
9512                          &priv->bottom_window);
9513       break;
9514
9515     default:
9516       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
9517       break;
9518     }
9519 }
9520
9521 /**
9522  * gtk_text_view_get_border_window_size:
9523  * @text_view: a #GtkTextView
9524  * @type: window to return size from
9525  *
9526  * Gets the width of the specified border window. See
9527  * gtk_text_view_set_border_window_size().
9528  *
9529  * Return value: width of window
9530  **/
9531 gint
9532 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
9533                                       GtkTextWindowType  type)
9534 {
9535   GtkTextViewPrivate *priv = text_view->priv;
9536
9537   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9538   
9539   switch (type)
9540     {
9541     case GTK_TEXT_WINDOW_LEFT:
9542       if (priv->left_window)
9543         return priv->left_window->requisition.width;
9544       break;
9545       
9546     case GTK_TEXT_WINDOW_RIGHT:
9547       if (priv->right_window)
9548         return priv->right_window->requisition.width;
9549       break;
9550       
9551     case GTK_TEXT_WINDOW_TOP:
9552       if (priv->top_window)
9553         return priv->top_window->requisition.height;
9554       break;
9555
9556     case GTK_TEXT_WINDOW_BOTTOM:
9557       if (priv->bottom_window)
9558         return priv->bottom_window->requisition.height;
9559       break;
9560       
9561     default:
9562       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
9563       break;
9564     }
9565
9566   return 0;
9567 }
9568
9569 /*
9570  * Child widgets
9571  */
9572
9573 static GtkTextViewChild*
9574 text_view_child_new_anchored (GtkWidget          *child,
9575                               GtkTextChildAnchor *anchor,
9576                               GtkTextLayout      *layout)
9577 {
9578   GtkTextViewChild *vc;
9579
9580   vc = g_new (GtkTextViewChild, 1);
9581
9582   vc->type = GTK_TEXT_WINDOW_PRIVATE;
9583   vc->widget = child;
9584   vc->anchor = anchor;
9585
9586   vc->from_top_of_line = 0;
9587   vc->from_left_of_buffer = 0;
9588   
9589   g_object_ref (vc->widget);
9590   g_object_ref (vc->anchor);
9591
9592   g_object_set_data (G_OBJECT (child),
9593                      I_("gtk-text-view-child"),
9594                      vc);
9595
9596   gtk_text_child_anchor_register_child (anchor, child, layout);
9597   
9598   return vc;
9599 }
9600
9601 static GtkTextViewChild*
9602 text_view_child_new_window (GtkWidget          *child,
9603                             GtkTextWindowType   type,
9604                             gint                x,
9605                             gint                y)
9606 {
9607   GtkTextViewChild *vc;
9608
9609   vc = g_new (GtkTextViewChild, 1);
9610
9611   vc->widget = child;
9612   vc->anchor = NULL;
9613
9614   vc->from_top_of_line = 0;
9615   vc->from_left_of_buffer = 0;
9616  
9617   g_object_ref (vc->widget);
9618
9619   vc->type = type;
9620   vc->x = x;
9621   vc->y = y;
9622
9623   g_object_set_data (G_OBJECT (child),
9624                      I_("gtk-text-view-child"),
9625                      vc);
9626   
9627   return vc;
9628 }
9629
9630 static void
9631 text_view_child_free (GtkTextViewChild *child)
9632 {
9633   g_object_set_data (G_OBJECT (child->widget),
9634                      I_("gtk-text-view-child"), NULL);
9635
9636   if (child->anchor)
9637     {
9638       gtk_text_child_anchor_unregister_child (child->anchor,
9639                                               child->widget);
9640       g_object_unref (child->anchor);
9641     }
9642
9643   g_object_unref (child->widget);
9644
9645   g_free (child);
9646 }
9647
9648 static void
9649 text_view_child_set_parent_window (GtkTextView      *text_view,
9650                                    GtkTextViewChild *vc)
9651 {
9652   if (vc->anchor)
9653     gtk_widget_set_parent_window (vc->widget,
9654                                   text_view->priv->text_window->bin_window);
9655   else
9656     {
9657       GdkWindow *window;
9658       window = gtk_text_view_get_window (text_view,
9659                                          vc->type);
9660       gtk_widget_set_parent_window (vc->widget, window);
9661     }
9662 }
9663
9664 static void
9665 add_child (GtkTextView      *text_view,
9666            GtkTextViewChild *vc)
9667 {
9668   text_view->priv->children = g_slist_prepend (text_view->priv->children,
9669                                                vc);
9670
9671   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9672     text_view_child_set_parent_window (text_view, vc);
9673   
9674   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
9675 }
9676
9677 /**
9678  * gtk_text_view_add_child_at_anchor:
9679  * @text_view: a #GtkTextView
9680  * @child: a #GtkWidget
9681  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
9682  * 
9683  * Adds a child widget in the text buffer, at the given @anchor.
9684  **/
9685 void
9686 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
9687                                    GtkWidget            *child,
9688                                    GtkTextChildAnchor   *anchor)
9689 {
9690   GtkTextViewChild *vc;
9691
9692   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9693   g_return_if_fail (GTK_IS_WIDGET (child));
9694   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
9695   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9696
9697   gtk_text_view_ensure_layout (text_view);
9698
9699   vc = text_view_child_new_anchored (child, anchor,
9700                                      text_view->priv->layout);
9701
9702   add_child (text_view, vc);
9703
9704   g_assert (vc->widget == child);
9705   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9706 }
9707
9708 /**
9709  * gtk_text_view_add_child_in_window:
9710  * @text_view: a #GtkTextView
9711  * @child: a #GtkWidget
9712  * @which_window: which window the child should appear in
9713  * @xpos: X position of child in window coordinates
9714  * @ypos: Y position of child in window coordinates
9715  *
9716  * Adds a child at fixed coordinates in one of the text widget's
9717  * windows.
9718  *
9719  * The window must have nonzero size (see
9720  * gtk_text_view_set_border_window_size()). Note that the child
9721  * coordinates are given relative to the #GdkWindow in question, and
9722  * that these coordinates have no sane relationship to scrolling. When
9723  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
9724  * irrelevant, the child floats above all scrollable areas. But when
9725  * placing a child in one of the scrollable windows (border windows or
9726  * text window), you'll need to compute the child's correct position
9727  * in buffer coordinates any time scrolling occurs or buffer changes
9728  * occur, and then call gtk_text_view_move_child() to update the
9729  * child's position.
9730  */
9731 void
9732 gtk_text_view_add_child_in_window (GtkTextView       *text_view,
9733                                    GtkWidget         *child,
9734                                    GtkTextWindowType  which_window,
9735                                    gint               xpos,
9736                                    gint               ypos)
9737 {
9738   GtkTextViewChild *vc;
9739
9740   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9741   g_return_if_fail (GTK_IS_WIDGET (child));
9742   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9743
9744   vc = text_view_child_new_window (child, which_window,
9745                                    xpos, ypos);
9746
9747   add_child (text_view, vc);
9748
9749   g_assert (vc->widget == child);
9750   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9751 }
9752
9753 /**
9754  * gtk_text_view_move_child:
9755  * @text_view: a #GtkTextView
9756  * @child: child widget already added to the text view
9757  * @xpos: new X position in window coordinates
9758  * @ypos: new Y position in window coordinates
9759  *
9760  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
9761  **/
9762 void
9763 gtk_text_view_move_child (GtkTextView *text_view,
9764                           GtkWidget   *child,
9765                           gint         xpos,
9766                           gint         ypos)
9767 {
9768   GtkTextViewChild *vc;
9769
9770   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9771   g_return_if_fail (GTK_IS_WIDGET (child));
9772   g_return_if_fail (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9773
9774   vc = g_object_get_data (G_OBJECT (child),
9775                           "gtk-text-view-child");
9776
9777   g_assert (vc != NULL);
9778
9779   if (vc->x == xpos &&
9780       vc->y == ypos)
9781     return;
9782   
9783   vc->x = xpos;
9784   vc->y = ypos;
9785
9786   if (gtk_widget_get_visible (child) &&
9787       gtk_widget_get_visible (GTK_WIDGET (text_view)))
9788     gtk_widget_queue_resize (child);
9789 }
9790
9791
9792 /* Iterator operations */
9793
9794 /**
9795  * gtk_text_view_forward_display_line:
9796  * @text_view: a #GtkTextView
9797  * @iter: a #GtkTextIter
9798  * 
9799  * Moves the given @iter forward by one display (wrapped) line.
9800  * A display line is different from a paragraph. Paragraphs are
9801  * separated by newlines or other paragraph separator characters.
9802  * Display lines are created by line-wrapping a paragraph. If
9803  * wrapping is turned off, display lines and paragraphs will be the
9804  * same. Display lines are divided differently for each view, since
9805  * they depend on the view's width; paragraphs are the same in all
9806  * views, since they depend on the contents of the #GtkTextBuffer.
9807  * 
9808  * Return value: %TRUE if @iter was moved and is not on the end iterator
9809  **/
9810 gboolean
9811 gtk_text_view_forward_display_line (GtkTextView *text_view,
9812                                     GtkTextIter *iter)
9813 {
9814   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9815   g_return_val_if_fail (iter != NULL, FALSE);
9816
9817   gtk_text_view_ensure_layout (text_view);
9818
9819   return gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, iter);
9820 }
9821
9822 /**
9823  * gtk_text_view_backward_display_line:
9824  * @text_view: a #GtkTextView
9825  * @iter: a #GtkTextIter
9826  * 
9827  * Moves the given @iter backward by one display (wrapped) line.
9828  * A display line is different from a paragraph. Paragraphs are
9829  * separated by newlines or other paragraph separator characters.
9830  * Display lines are created by line-wrapping a paragraph. If
9831  * wrapping is turned off, display lines and paragraphs will be the
9832  * same. Display lines are divided differently for each view, since
9833  * they depend on the view's width; paragraphs are the same in all
9834  * views, since they depend on the contents of the #GtkTextBuffer.
9835  * 
9836  * Return value: %TRUE if @iter was moved and is not on the end iterator
9837  **/
9838 gboolean
9839 gtk_text_view_backward_display_line (GtkTextView *text_view,
9840                                      GtkTextIter *iter)
9841 {
9842   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9843   g_return_val_if_fail (iter != NULL, FALSE);
9844
9845   gtk_text_view_ensure_layout (text_view);
9846
9847   return gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, iter);
9848 }
9849
9850 /**
9851  * gtk_text_view_forward_display_line_end:
9852  * @text_view: a #GtkTextView
9853  * @iter: a #GtkTextIter
9854  * 
9855  * Moves the given @iter forward to the next display line end.
9856  * A display line is different from a paragraph. Paragraphs are
9857  * separated by newlines or other paragraph separator characters.
9858  * Display lines are created by line-wrapping a paragraph. If
9859  * wrapping is turned off, display lines and paragraphs will be the
9860  * same. Display lines are divided differently for each view, since
9861  * they depend on the view's width; paragraphs are the same in all
9862  * views, since they depend on the contents of the #GtkTextBuffer.
9863  * 
9864  * Return value: %TRUE if @iter was moved and is not on the end iterator
9865  **/
9866 gboolean
9867 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
9868                                         GtkTextIter *iter)
9869 {
9870   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9871   g_return_val_if_fail (iter != NULL, FALSE);
9872
9873   gtk_text_view_ensure_layout (text_view);
9874
9875   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, 1);
9876 }
9877
9878 /**
9879  * gtk_text_view_backward_display_line_start:
9880  * @text_view: a #GtkTextView
9881  * @iter: a #GtkTextIter
9882  * 
9883  * Moves the given @iter backward to the next display line start.
9884  * A display line is different from a paragraph. Paragraphs are
9885  * separated by newlines or other paragraph separator characters.
9886  * Display lines are created by line-wrapping a paragraph. If
9887  * wrapping is turned off, display lines and paragraphs will be the
9888  * same. Display lines are divided differently for each view, since
9889  * they depend on the view's width; paragraphs are the same in all
9890  * views, since they depend on the contents of the #GtkTextBuffer.
9891  * 
9892  * Return value: %TRUE if @iter was moved and is not on the end iterator
9893  **/
9894 gboolean
9895 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
9896                                            GtkTextIter *iter)
9897 {
9898   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9899   g_return_val_if_fail (iter != NULL, FALSE);
9900
9901   gtk_text_view_ensure_layout (text_view);
9902
9903   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, -1);
9904 }
9905
9906 /**
9907  * gtk_text_view_starts_display_line:
9908  * @text_view: a #GtkTextView
9909  * @iter: a #GtkTextIter
9910  * 
9911  * Determines whether @iter is at the start of a display line.
9912  * See gtk_text_view_forward_display_line() for an explanation of
9913  * display lines vs. paragraphs.
9914  * 
9915  * Return value: %TRUE if @iter begins a wrapped line
9916  **/
9917 gboolean
9918 gtk_text_view_starts_display_line (GtkTextView       *text_view,
9919                                    const GtkTextIter *iter)
9920 {
9921   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9922   g_return_val_if_fail (iter != NULL, FALSE);
9923
9924   gtk_text_view_ensure_layout (text_view);
9925
9926   return gtk_text_layout_iter_starts_line (text_view->priv->layout, iter);
9927 }
9928
9929 /**
9930  * gtk_text_view_move_visually:
9931  * @text_view: a #GtkTextView
9932  * @iter: a #GtkTextIter
9933  * @count: number of characters to move (negative moves left, 
9934  *    positive moves right)
9935  *
9936  * Move the iterator a given number of characters visually, treating
9937  * it as the strong cursor position. If @count is positive, then the
9938  * new strong cursor position will be @count positions to the right of
9939  * the old cursor position. If @count is negative then the new strong
9940  * cursor position will be @count positions to the left of the old
9941  * cursor position.
9942  *
9943  * In the presence of bi-directional text, the correspondence
9944  * between logical and visual order will depend on the direction
9945  * of the current run, and there may be jumps when the cursor
9946  * is moved off of the end of a run.
9947  * 
9948  * Return value: %TRUE if @iter moved and is not on the end iterator
9949  **/
9950 gboolean
9951 gtk_text_view_move_visually (GtkTextView *text_view,
9952                              GtkTextIter *iter,
9953                              gint         count)
9954 {
9955   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9956   g_return_val_if_fail (iter != NULL, FALSE);
9957
9958   gtk_text_view_ensure_layout (text_view);
9959
9960   return gtk_text_layout_move_iter_visually (text_view->priv->layout, iter, count);
9961 }
9962
9963 /**
9964  * gtk_text_view_set_input_purpose:
9965  * @text_view: a #GtkTextView
9966  * @purpose: the purpose
9967  *
9968  * Sets the #GtkTextView:input-purpose property which
9969  * can be used by on-screen keyboards and other input
9970  * methods to adjust their behaviour.
9971  *
9972  * Since: 3.6
9973  */
9974
9975 void
9976 gtk_text_view_set_input_purpose (GtkTextView     *text_view,
9977                                  GtkInputPurpose  purpose)
9978
9979 {
9980   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9981
9982   if (gtk_text_view_get_input_purpose (text_view) != purpose)
9983     {
9984       g_object_set (G_OBJECT (text_view->priv->im_context),
9985                     "input-purpose", purpose,
9986                     NULL);
9987
9988       g_object_notify (G_OBJECT (text_view), "input-purpose");
9989     }
9990 }
9991
9992 /**
9993  * gtk_text_view_get_input_purpose:
9994  * @text_view: a #GtkTextView
9995  *
9996  * Gets the value of the #GtkTextView:input-purpose property.
9997  *
9998  * Since: 3.6
9999  */
10000
10001 GtkInputPurpose
10002 gtk_text_view_get_input_purpose (GtkTextView *text_view)
10003 {
10004   GtkInputPurpose purpose;
10005
10006   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_INPUT_PURPOSE_FREE_FORM);
10007
10008   g_object_get (G_OBJECT (text_view->priv->im_context),
10009                 "input-purpose", &purpose,
10010                 NULL);
10011
10012   return purpose;
10013 }
10014
10015 /**
10016  * gtk_text_view_set_input_hints:
10017  * @text_view: a #GtkTextView
10018  * @hints: the hints
10019  *
10020  * Sets the #GtkTextView:input-hints property, which
10021  * allows input methods to fine-tune their behaviour.
10022  *
10023  * Since: 3.6
10024  */
10025
10026 void
10027 gtk_text_view_set_input_hints (GtkTextView   *text_view,
10028                                GtkInputHints  hints)
10029
10030 {
10031   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
10032
10033   if (gtk_text_view_get_input_hints (text_view) != hints)
10034     {
10035       g_object_set (G_OBJECT (text_view->priv->im_context),
10036                     "input-hints", hints,
10037                     NULL);
10038
10039       g_object_notify (G_OBJECT (text_view), "input-hints");
10040     }
10041 }
10042
10043 /**
10044  * gtk_text_view_get_input_hints:
10045  * @text_view: a #GtkTextView
10046  *
10047  * Gets the value of the #GtkTextView:input-hints property.
10048  *
10049  * Since: 3.6
10050  */
10051
10052 GtkInputHints
10053 gtk_text_view_get_input_hints (GtkTextView *text_view)
10054 {
10055   GtkInputHints hints;
10056
10057   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_INPUT_HINT_NONE);
10058
10059   g_object_get (G_OBJECT (text_view->priv->im_context),
10060                 "input-hints", &hints,
10061                 NULL);
10062
10063   return hints;
10064 }