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