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