]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
Make accessible implementations public
[~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   gdk_window_set_user_data (window, widget);
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   _gtk_text_handle_set_mode (priv->text_handle,
4759                              GTK_TEXT_HANDLE_MODE_NONE);
4760
4761   return retval;
4762 }
4763
4764 static gint
4765 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
4766 {
4767   GtkTextView *text_view;
4768   GtkTextViewPrivate *priv;
4769   GtkTextMark *insert;
4770   GtkTextIter iter;
4771
4772   text_view = GTK_TEXT_VIEW (widget);
4773   priv = text_view->priv;
4774
4775   if (priv->layout == NULL || get_buffer (text_view) == NULL)
4776     return FALSE;
4777       
4778   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
4779   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
4780   if (gtk_text_iter_can_insert (&iter, priv->editable) &&
4781       gtk_im_context_filter_keypress (priv->im_context, event))
4782     {
4783       priv->need_im_reset = TRUE;
4784       return TRUE;
4785     }
4786   else
4787     return GTK_WIDGET_CLASS (gtk_text_view_parent_class)->key_release_event (widget, event);
4788 }
4789
4790 static gint
4791 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
4792 {
4793   GtkTextView *text_view;
4794   GtkTextViewPrivate *priv;
4795   GdkDevice *device;
4796   gboolean is_touchscreen;
4797
4798   text_view = GTK_TEXT_VIEW (widget);
4799   priv = text_view->priv;
4800
4801   gtk_widget_grab_focus (widget);
4802
4803   if (event->window != priv->text_window->bin_window)
4804     {
4805       /* Remove selection if any. */
4806       gtk_text_view_unselect (text_view);
4807       return FALSE;
4808     }
4809
4810   gtk_text_view_reset_blink_time (text_view);
4811
4812 #if 0
4813   /* debug hack */
4814   if (event->button == GDK_BUTTON_SECONDARY && (event->state & GDK_CONTROL_MASK) != 0)
4815     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
4816   else if (event->button == GDK_BUTTON_SECONDARY)
4817     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
4818 #endif
4819
4820   device = gdk_event_get_source_device ((GdkEvent *) event);
4821   is_touchscreen = test_touchscreen ||
4822                    gdk_device_get_source (device) == GDK_SOURCE_TOUCHSCREEN;
4823
4824   if (event->type == GDK_BUTTON_PRESS)
4825     {
4826       gtk_text_view_reset_im_context (text_view);
4827
4828       if (gdk_event_triggers_context_menu ((GdkEvent *) event))
4829         {
4830           gtk_text_view_do_popup (text_view, event);
4831           return TRUE;
4832         }
4833       else if (event->button == GDK_BUTTON_PRIMARY)
4834         {
4835           /* If we're in the selection, start a drag copy/move of the
4836            * selection; otherwise, start creating a new selection.
4837            */
4838           GtkTextIter iter;
4839           GtkTextIter start, end;
4840
4841           gtk_text_layout_get_iter_at_pixel (priv->layout,
4842                                              &iter,
4843                                              event->x + priv->xoffset,
4844                                              event->y + priv->yoffset);
4845
4846           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
4847                                                     &start, &end) &&
4848               gtk_text_iter_in_range (&iter, &start, &end) &&
4849               !(event->state &
4850                 gtk_widget_get_modifier_mask (widget,
4851                                               GDK_MODIFIER_INTENT_EXTEND_SELECTION)))
4852             {
4853               priv->grab_device = event->device;
4854               priv->drag_start_x = event->x;
4855               priv->drag_start_y = event->y;
4856               priv->pending_place_cursor_button = event->button;
4857             }
4858           else
4859             {
4860               GtkTextHandleMode mode;
4861
4862               gtk_text_view_start_selection_drag (text_view, &iter, event);
4863
4864               if (gtk_widget_is_sensitive (widget) && is_touchscreen)
4865                 mode = GTK_TEXT_HANDLE_MODE_CURSOR;
4866               else
4867                 mode = GTK_TEXT_HANDLE_MODE_NONE;
4868
4869               gtk_text_view_update_handles (text_view, mode);
4870             }
4871
4872           return TRUE;
4873         }
4874       else if (event->button == GDK_BUTTON_MIDDLE &&
4875                get_middle_click_paste (text_view))
4876         {
4877           GtkTextIter iter;
4878
4879           /* We do not want to scroll back to the insert iter when we paste
4880              with the middle button */
4881           priv->scroll_after_paste = FALSE;
4882
4883           gtk_text_layout_get_iter_at_pixel (priv->layout,
4884                                              &iter,
4885                                              event->x + priv->xoffset,
4886                                              event->y + priv->yoffset);
4887
4888           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4889                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
4890                                            &iter,
4891                                            priv->editable);
4892           return TRUE;
4893         }
4894     }
4895   else if ((event->type == GDK_2BUTTON_PRESS ||
4896             event->type == GDK_3BUTTON_PRESS) &&
4897            event->button == GDK_BUTTON_PRIMARY)
4898     {
4899       GtkTextIter iter;
4900       GtkTextHandleMode mode;
4901
4902       gtk_text_view_end_selection_drag (text_view);
4903
4904       gtk_text_layout_get_iter_at_pixel (priv->layout,
4905                                          &iter,
4906                                          event->x + priv->xoffset,
4907                                          event->y + priv->yoffset);
4908
4909       gtk_text_view_start_selection_drag (text_view, &iter, event);
4910
4911       if (gtk_widget_is_sensitive (widget) && is_touchscreen)
4912         mode = GTK_TEXT_HANDLE_MODE_SELECTION;
4913       else
4914         mode = GTK_TEXT_HANDLE_MODE_NONE;
4915
4916       gtk_text_view_update_handles (text_view, mode);
4917       return TRUE;
4918     }
4919
4920   return FALSE;
4921 }
4922
4923 static gint
4924 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
4925 {
4926   GtkTextView *text_view;
4927   GtkTextViewPrivate *priv;
4928
4929   text_view = GTK_TEXT_VIEW (widget);
4930   priv = text_view->priv;
4931
4932   if (event->window != priv->text_window->bin_window)
4933     return FALSE;
4934
4935   if (event->button == GDK_BUTTON_PRIMARY)
4936     {
4937       if (priv->drag_start_x >= 0)
4938         {
4939           priv->drag_start_x = -1;
4940           priv->drag_start_y = -1;
4941         }
4942
4943       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget)))
4944         return TRUE;
4945       else if (priv->pending_place_cursor_button == event->button)
4946         {
4947           GtkTextHandleMode mode;
4948           GdkDevice *device;
4949           GtkTextIter iter;
4950
4951           /* Unselect everything; we clicked inside selection, but
4952            * didn't move by the drag threshold, so just clear selection
4953            * and place cursor.
4954            */
4955           gtk_text_layout_get_iter_at_pixel (priv->layout,
4956                                              &iter,
4957                                              event->x + priv->xoffset,
4958                                              event->y + priv->yoffset);
4959
4960           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
4961           gtk_text_view_check_cursor_blink (text_view);
4962
4963           device = gdk_event_get_source_device ((GdkEvent *) event);
4964
4965           if (gtk_widget_is_sensitive (widget) &&
4966               (test_touchscreen ||
4967                gdk_device_get_source (device) == GDK_SOURCE_TOUCHSCREEN))
4968             mode = GTK_TEXT_HANDLE_MODE_CURSOR;
4969           else
4970             mode = GTK_TEXT_HANDLE_MODE_NONE;
4971
4972           gtk_text_view_update_handles (text_view, mode);
4973           priv->pending_place_cursor_button = 0;
4974
4975           return FALSE;
4976         }
4977     }
4978
4979   return FALSE;
4980 }
4981
4982 static void
4983 keymap_direction_changed (GdkKeymap   *keymap,
4984                           GtkTextView *text_view)
4985 {
4986   gtk_text_view_check_keymap_direction (text_view);
4987 }
4988
4989 static gint
4990 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
4991 {
4992   GtkTextView *text_view;
4993   GtkTextViewPrivate *priv;
4994
4995   text_view = GTK_TEXT_VIEW (widget);
4996   priv = text_view->priv;
4997
4998   gtk_widget_queue_draw (widget);
4999
5000   DV(g_print (G_STRLOC": focus_in_event\n"));
5001
5002   gtk_text_view_reset_blink_time (text_view);
5003
5004   if (priv->cursor_visible && priv->layout)
5005     {
5006       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5007       gtk_text_view_check_cursor_blink (text_view);
5008     }
5009
5010   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
5011                     "direction-changed",
5012                     G_CALLBACK (keymap_direction_changed), text_view);
5013   gtk_text_view_check_keymap_direction (text_view);
5014
5015   if (priv->editable)
5016     {
5017       priv->need_im_reset = TRUE;
5018       gtk_im_context_focus_in (priv->im_context);
5019     }
5020
5021   return FALSE;
5022 }
5023
5024 static gint
5025 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
5026 {
5027   GtkTextView *text_view;
5028   GtkTextViewPrivate *priv;
5029
5030   text_view = GTK_TEXT_VIEW (widget);
5031   priv = text_view->priv;
5032
5033   gtk_text_view_end_selection_drag (text_view);
5034
5035   gtk_widget_queue_draw (widget);
5036
5037   DV(g_print (G_STRLOC": focus_out_event\n"));
5038   
5039   if (priv->cursor_visible && priv->layout)
5040     {
5041       gtk_text_view_check_cursor_blink (text_view);
5042       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
5043     }
5044
5045   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
5046                                         keymap_direction_changed,
5047                                         text_view);
5048   _gtk_text_handle_set_mode (priv->text_handle,
5049                              GTK_TEXT_HANDLE_MODE_NONE);
5050
5051   if (priv->editable)
5052     {
5053       priv->need_im_reset = TRUE;
5054       gtk_im_context_focus_out (priv->im_context);
5055     }
5056
5057   return FALSE;
5058 }
5059
5060 static gint
5061 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
5062 {
5063   GtkTextView *text_view;
5064   GtkTextViewPrivate *priv;
5065
5066   text_view = GTK_TEXT_VIEW (widget);
5067   priv = text_view->priv;
5068
5069   gtk_text_view_unobscure_mouse_cursor (text_view);
5070
5071   if (event->window == priv->text_window->bin_window &&
5072       priv->drag_start_x >= 0)
5073     {
5074       gint x = event->x;
5075       gint y = event->y;
5076
5077       gdk_event_request_motions (event);
5078
5079       if (gtk_drag_check_threshold (widget,
5080                                     priv->drag_start_x, 
5081                                     priv->drag_start_y,
5082                                     x, y))
5083         {
5084           GtkTextIter iter;
5085           gint buffer_x, buffer_y;
5086
5087           gtk_text_view_window_to_buffer_coords (text_view,
5088                                                  GTK_TEXT_WINDOW_TEXT,
5089                                                  priv->drag_start_x,
5090                                                  priv->drag_start_y,
5091                                                  &buffer_x,
5092                                                  &buffer_y);
5093
5094           gtk_text_layout_get_iter_at_pixel (priv->layout,
5095                                              &iter,
5096                                              buffer_x, buffer_y);
5097
5098           gtk_text_view_start_selection_dnd (text_view, &iter, event);
5099           return TRUE;
5100         }
5101     }
5102
5103   return FALSE;
5104 }
5105
5106 static void
5107 gtk_text_view_paint (GtkWidget      *widget,
5108                      cairo_t        *cr)
5109 {
5110   GtkTextView *text_view;
5111   GtkTextViewPrivate *priv;
5112   
5113   text_view = GTK_TEXT_VIEW (widget);
5114   priv = text_view->priv;
5115
5116   g_return_if_fail (priv->layout != NULL);
5117   g_return_if_fail (priv->xoffset >= 0);
5118   g_return_if_fail (priv->yoffset >= 0);
5119
5120   while (priv->first_validate_idle != 0)
5121     {
5122       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
5123                    priv->first_validate_idle));
5124       gtk_text_view_flush_first_validate (text_view);
5125     }
5126
5127   if (!priv->onscreen_validated)
5128     {
5129       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.");
5130       g_assert_not_reached ();
5131     }
5132   
5133 #if 0
5134   printf ("painting %d,%d  %d x %d\n",
5135           area->x, area->y,
5136           area->width, area->height);
5137 #endif
5138
5139   cairo_save (cr);
5140   cairo_translate (cr, -priv->xoffset, -priv->yoffset);
5141
5142   gtk_text_layout_draw (priv->layout,
5143                         widget,
5144                         cr,
5145                         NULL);
5146
5147   cairo_restore (cr);
5148 }
5149
5150 static gboolean
5151 gtk_text_view_draw (GtkWidget *widget,
5152                     cairo_t   *cr)
5153 {
5154   GSList *tmp_list;
5155   GdkWindow *window;
5156   
5157   if (gtk_cairo_should_draw_window (cr, gtk_widget_get_window (widget)))
5158     gtk_text_view_draw_focus (widget, cr);
5159
5160   window = gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
5161                                      GTK_TEXT_WINDOW_TEXT);
5162   if (gtk_cairo_should_draw_window (cr, window))
5163     {
5164       DV(g_print (">Exposed ("G_STRLOC")\n"));
5165       cairo_save (cr);
5166       gtk_cairo_transform_to_window (cr, widget, window);
5167       gtk_text_view_paint (widget, cr);
5168       cairo_restore (cr);
5169     }
5170
5171   /* Propagate exposes to all unanchored children. 
5172    * Anchored children are handled in gtk_text_view_paint(). 
5173    */
5174   tmp_list = GTK_TEXT_VIEW (widget)->priv->children;
5175   while (tmp_list != NULL)
5176     {
5177       GtkTextViewChild *vc = tmp_list->data;
5178
5179       /* propagate_draw checks that event->window matches
5180        * child->window
5181        */
5182       gtk_container_propagate_draw (GTK_CONTAINER (widget),
5183                                     vc->widget,
5184                                     cr);
5185       
5186       tmp_list = tmp_list->next;
5187     }
5188   
5189   return FALSE;
5190 }
5191
5192 static void
5193 gtk_text_view_draw_focus (GtkWidget *widget,
5194                           cairo_t   *cr)
5195 {
5196   gboolean interior_focus;
5197
5198   /* We clear the focus if we are in interior focus mode. */
5199   gtk_widget_style_get (widget,
5200                         "interior-focus", &interior_focus,
5201                         NULL);
5202   
5203   if (gtk_widget_has_visible_focus (widget) && !interior_focus)
5204     {
5205       GtkStyleContext *context;
5206
5207       context = gtk_widget_get_style_context (widget);
5208
5209       gtk_render_focus (context, cr, 0, 0,
5210                         gtk_widget_get_allocated_width (widget),
5211                         gtk_widget_get_allocated_height (widget));
5212     }
5213 }
5214
5215 static gboolean
5216 gtk_text_view_focus (GtkWidget        *widget,
5217                      GtkDirectionType  direction)
5218 {
5219   GtkContainer *container;
5220   gboolean result;
5221   
5222   container = GTK_CONTAINER (widget);  
5223
5224   if (!gtk_widget_is_focus (widget) &&
5225       gtk_container_get_focus_child (container) == NULL)
5226     {
5227       gtk_widget_grab_focus (widget);
5228       return TRUE;
5229     }
5230   else
5231     {
5232       /*
5233        * Unset CAN_FOCUS flag so that gtk_container_focus() allows
5234        * children to get the focus
5235        */
5236       gtk_widget_set_can_focus (widget, FALSE);
5237       result = GTK_WIDGET_CLASS (gtk_text_view_parent_class)->focus (widget, direction);
5238       gtk_widget_set_can_focus (widget, TRUE);
5239
5240       return result;
5241     }
5242 }
5243
5244 /*
5245  * Container
5246  */
5247
5248 static void
5249 gtk_text_view_add (GtkContainer *container,
5250                    GtkWidget    *child)
5251 {
5252   /* This is pretty random. */
5253   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
5254                                      child,
5255                                      GTK_TEXT_WINDOW_WIDGET,
5256                                      0, 0);
5257 }
5258
5259 static void
5260 gtk_text_view_remove (GtkContainer *container,
5261                       GtkWidget    *child)
5262 {
5263   GtkTextView *text_view;
5264   GtkTextViewPrivate *priv;
5265   GtkTextViewChild *vc;
5266   GSList *iter;
5267
5268   text_view = GTK_TEXT_VIEW (container);
5269   priv = text_view->priv;
5270
5271   vc = NULL;
5272   iter = priv->children;
5273
5274   while (iter != NULL)
5275     {
5276       vc = iter->data;
5277
5278       if (vc->widget == child)
5279         break;
5280
5281       iter = g_slist_next (iter);
5282     }
5283
5284   g_assert (iter != NULL); /* be sure we had the child in the list */
5285
5286   priv->children = g_slist_remove (priv->children, vc);
5287
5288   gtk_widget_unparent (vc->widget);
5289
5290   text_view_child_free (vc);
5291 }
5292
5293 static void
5294 gtk_text_view_forall (GtkContainer *container,
5295                       gboolean      include_internals,
5296                       GtkCallback   callback,
5297                       gpointer      callback_data)
5298 {
5299   GSList *iter;
5300   GtkTextView *text_view;
5301   GSList *copy;
5302
5303   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
5304   g_return_if_fail (callback != NULL);
5305
5306   text_view = GTK_TEXT_VIEW (container);
5307
5308   copy = g_slist_copy (text_view->priv->children);
5309   iter = copy;
5310
5311   while (iter != NULL)
5312     {
5313       GtkTextViewChild *vc = iter->data;
5314
5315       (* callback) (vc->widget, callback_data);
5316
5317       iter = g_slist_next (iter);
5318     }
5319
5320   g_slist_free (copy);
5321 }
5322
5323 #define CURSOR_ON_MULTIPLIER 2
5324 #define CURSOR_OFF_MULTIPLIER 1
5325 #define CURSOR_PEND_MULTIPLIER 3
5326 #define CURSOR_DIVIDER 3
5327
5328 static gboolean
5329 cursor_blinks (GtkTextView *text_view)
5330 {
5331   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5332   gboolean blink;
5333
5334 #ifdef DEBUG_VALIDATION_AND_SCROLLING
5335   return FALSE;
5336 #endif
5337   if (gtk_get_debug_flags () & GTK_DEBUG_UPDATES)
5338     return FALSE;
5339
5340   g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
5341
5342   if (!blink)
5343     return FALSE;
5344
5345   if (text_view->priv->editable)
5346     {
5347       GtkTextMark *insert;
5348       GtkTextIter iter;
5349       
5350       insert = gtk_text_buffer_get_insert (get_buffer (text_view));
5351       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
5352       
5353       if (gtk_text_iter_editable (&iter, text_view->priv->editable))
5354         return blink;
5355     }
5356
5357   return FALSE;
5358 }
5359
5360 static gboolean
5361 get_middle_click_paste (GtkTextView *text_view)
5362 {
5363   GtkSettings *settings;
5364   gboolean paste;
5365
5366   settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5367   g_object_get (settings, "gtk-enable-primary-paste", &paste, NULL);
5368
5369   return paste;
5370 }
5371
5372 static gint
5373 get_cursor_time (GtkTextView *text_view)
5374 {
5375   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5376   gint time;
5377
5378   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
5379
5380   return time;
5381 }
5382
5383 static gint
5384 get_cursor_blink_timeout (GtkTextView *text_view)
5385 {
5386   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5387   gint time;
5388
5389   g_object_get (settings, "gtk-cursor-blink-timeout", &time, NULL);
5390
5391   return time;
5392 }
5393
5394
5395 /*
5396  * Blink!
5397  */
5398
5399 static gint
5400 blink_cb (gpointer data)
5401 {
5402   GtkTextView *text_view;
5403   GtkTextViewPrivate *priv;
5404   gboolean visible;
5405   gint blink_timeout;
5406
5407   text_view = GTK_TEXT_VIEW (data);
5408   priv = text_view->priv;
5409
5410   if (!gtk_widget_has_focus (GTK_WIDGET (text_view)))
5411     {
5412       g_warning ("GtkTextView - did not receive focus-out-event. If you\n"
5413                  "connect a handler to this signal, it must return\n"
5414                  "FALSE so the text view gets the event as well");
5415
5416       gtk_text_view_check_cursor_blink (text_view);
5417
5418       return FALSE;
5419     }
5420
5421   g_assert (priv->layout);
5422   g_assert (priv->cursor_visible);
5423
5424   visible = gtk_text_layout_get_cursor_visible (priv->layout);
5425
5426   blink_timeout = get_cursor_blink_timeout (text_view);
5427   if (priv->blink_time > 1000 * blink_timeout &&
5428       blink_timeout < G_MAXINT/1000) 
5429     {
5430       /* we've blinked enough without the user doing anything, stop blinking */
5431       visible = 0;
5432       priv->blink_timeout = 0;
5433     } 
5434   else if (visible)
5435     priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5436                                                    blink_cb,
5437                                                    text_view);
5438   else 
5439     {
5440       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_ON_MULTIPLIER / CURSOR_DIVIDER,
5441                                                      blink_cb,
5442                                                      text_view);
5443       priv->blink_time += get_cursor_time (text_view);
5444     }
5445
5446   /* Block changed_handler while changing the layout's cursor visibility
5447    * because it would expose the whole paragraph. Instead, we expose
5448    * the cursor's area(s) manually below.
5449    */
5450   g_signal_handlers_block_by_func (priv->layout,
5451                                    changed_handler,
5452                                    text_view);
5453   gtk_text_layout_set_cursor_visible (priv->layout, !visible);
5454   g_signal_handlers_unblock_by_func (priv->layout,
5455                                      changed_handler,
5456                                      text_view);
5457
5458   text_window_invalidate_cursors (priv->text_window);
5459
5460   /* Remove ourselves */
5461   return FALSE;
5462 }
5463
5464
5465 static void
5466 gtk_text_view_stop_cursor_blink (GtkTextView *text_view)
5467 {
5468   if (text_view->priv->blink_timeout)
5469     { 
5470       g_source_remove (text_view->priv->blink_timeout);
5471       text_view->priv->blink_timeout = 0;
5472     }
5473 }
5474
5475 static void
5476 gtk_text_view_check_cursor_blink (GtkTextView *text_view)
5477 {
5478   GtkTextViewPrivate *priv = text_view->priv;
5479
5480   if (priv->layout != NULL &&
5481       priv->cursor_visible &&
5482       gtk_widget_has_focus (GTK_WIDGET (text_view)))
5483     {
5484       if (cursor_blinks (text_view))
5485         {
5486           if (priv->blink_timeout == 0)
5487             {
5488               gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5489               
5490               priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER / CURSOR_DIVIDER,
5491                                                              blink_cb,
5492                                                              text_view);
5493             }
5494         }
5495       else
5496         {
5497           gtk_text_view_stop_cursor_blink (text_view);
5498           gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5499         }
5500     }
5501   else
5502     {
5503       gtk_text_view_stop_cursor_blink (text_view);
5504       gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
5505     }
5506 }
5507
5508 static void
5509 gtk_text_view_pend_cursor_blink (GtkTextView *text_view)
5510 {
5511   GtkTextViewPrivate *priv = text_view->priv;
5512
5513   if (priv->layout != NULL &&
5514       priv->cursor_visible &&
5515       gtk_widget_has_focus (GTK_WIDGET (text_view)) &&
5516       cursor_blinks (text_view))
5517     {
5518       gtk_text_view_stop_cursor_blink (text_view);
5519       gtk_text_layout_set_cursor_visible (priv->layout, TRUE);
5520       
5521       priv->blink_timeout = gdk_threads_add_timeout (get_cursor_time (text_view) * CURSOR_PEND_MULTIPLIER / CURSOR_DIVIDER,
5522                                                      blink_cb,
5523                                                      text_view);
5524     }
5525 }
5526
5527 static void
5528 gtk_text_view_reset_blink_time (GtkTextView *text_view)
5529 {
5530   GtkTextViewPrivate *priv = text_view->priv;
5531
5532   priv->blink_time = 0;
5533 }
5534
5535
5536 /*
5537  * Key binding handlers
5538  */
5539
5540 static gboolean
5541 gtk_text_view_move_iter_by_lines (GtkTextView *text_view,
5542                                   GtkTextIter *newplace,
5543                                   gint         count)
5544 {
5545   gboolean ret = TRUE;
5546
5547   while (count < 0)
5548     {
5549       ret = gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, newplace);
5550       count++;
5551     }
5552
5553   while (count > 0)
5554     {
5555       ret = gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, newplace);
5556       count--;
5557     }
5558
5559   return ret;
5560 }
5561
5562 static void
5563 move_cursor (GtkTextView       *text_view,
5564              const GtkTextIter *new_location,
5565              gboolean           extend_selection)
5566 {
5567   if (extend_selection)
5568     gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
5569                                        "insert",
5570                                        new_location);
5571   else
5572       gtk_text_buffer_place_cursor (get_buffer (text_view),
5573                                     new_location);
5574   gtk_text_view_check_cursor_blink (text_view);
5575 }
5576
5577 static void
5578 gtk_text_view_move_cursor_internal (GtkTextView     *text_view,
5579                                     GtkMovementStep  step,
5580                                     gint             count,
5581                                     gboolean         extend_selection)
5582 {
5583   GtkTextViewPrivate *priv;
5584   GtkTextIter insert;
5585   GtkTextIter newplace;
5586   gboolean cancel_selection = FALSE;
5587   gint cursor_x_pos = 0;
5588   GtkDirectionType leave_direction = -1;
5589
5590   priv = text_view->priv;
5591
5592   if (!priv->cursor_visible) 
5593     {
5594       GtkScrollStep scroll_step;
5595       gdouble old_xpos, old_ypos;
5596
5597       switch (step) 
5598         {
5599         case GTK_MOVEMENT_VISUAL_POSITIONS:
5600           leave_direction = count > 0 ? GTK_DIR_RIGHT : GTK_DIR_LEFT;
5601           /* fall through */
5602         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5603         case GTK_MOVEMENT_WORDS:
5604           scroll_step = GTK_SCROLL_HORIZONTAL_STEPS;
5605           break;
5606         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5607           scroll_step = GTK_SCROLL_HORIZONTAL_ENDS;
5608           break;          
5609         case GTK_MOVEMENT_DISPLAY_LINES:
5610           leave_direction = count > 0 ? GTK_DIR_DOWN : GTK_DIR_UP;
5611           /* fall through */
5612         case GTK_MOVEMENT_PARAGRAPHS:
5613         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5614           scroll_step = GTK_SCROLL_STEPS;
5615           break;
5616         case GTK_MOVEMENT_PAGES:
5617           scroll_step = GTK_SCROLL_PAGES;
5618           break;
5619         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5620           scroll_step = GTK_SCROLL_HORIZONTAL_PAGES;
5621           break;
5622         case GTK_MOVEMENT_BUFFER_ENDS:
5623           scroll_step = GTK_SCROLL_ENDS;
5624           break;
5625         default:
5626           scroll_step = GTK_SCROLL_PAGES;
5627           break;
5628         }
5629
5630       old_xpos = priv->xoffset;
5631       old_ypos = priv->yoffset;
5632       gtk_text_view_move_viewport (text_view, scroll_step, count);
5633       if ((old_xpos == priv->xoffset && old_ypos == priv->yoffset) &&
5634           leave_direction != -1 &&
5635           !gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5636                                      leave_direction))
5637         {
5638           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5639         }
5640
5641       return;
5642     }
5643
5644   gtk_text_view_reset_im_context (text_view);
5645
5646   if (step == GTK_MOVEMENT_PAGES)
5647     {
5648       if (!gtk_text_view_scroll_pages (text_view, count, extend_selection))
5649         gtk_widget_error_bell (GTK_WIDGET (text_view));
5650
5651       gtk_text_view_check_cursor_blink (text_view);
5652       gtk_text_view_pend_cursor_blink (text_view);
5653       return;
5654     }
5655   else if (step == GTK_MOVEMENT_HORIZONTAL_PAGES)
5656     {
5657       if (!gtk_text_view_scroll_hpages (text_view, count, extend_selection))
5658         gtk_widget_error_bell (GTK_WIDGET (text_view));
5659
5660       gtk_text_view_check_cursor_blink (text_view);
5661       gtk_text_view_pend_cursor_blink (text_view);
5662       return;
5663     }
5664
5665   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5666                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5667
5668   if (! extend_selection)
5669     {
5670       GtkTextIter sel_bound;
5671
5672       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &sel_bound,
5673                                         gtk_text_buffer_get_selection_bound (get_buffer (text_view)));
5674
5675       /* if we move forward, assume the cursor is at the end of the selection;
5676        * if we move backward, assume the cursor is at the start
5677        */
5678       if (count > 0)
5679         gtk_text_iter_order (&sel_bound, &insert);
5680       else
5681         gtk_text_iter_order (&insert, &sel_bound);
5682
5683       /* if we actually have a selection, just move *to* the beginning/end
5684        * of the selection and not *from* there on LOGICAL_POSITIONS
5685        * and VISUAL_POSITIONS movement
5686        */
5687       if (! gtk_text_iter_equal (&sel_bound, &insert))
5688         cancel_selection = TRUE;
5689     }
5690
5691   newplace = insert;
5692
5693   if (step == GTK_MOVEMENT_DISPLAY_LINES)
5694     gtk_text_view_get_virtual_cursor_pos (text_view, &insert, &cursor_x_pos, NULL);
5695
5696   switch (step)
5697     {
5698     case GTK_MOVEMENT_LOGICAL_POSITIONS:
5699       if (! cancel_selection)
5700         gtk_text_iter_forward_visible_cursor_positions (&newplace, count);
5701       break;
5702
5703     case GTK_MOVEMENT_VISUAL_POSITIONS:
5704       if (! cancel_selection)
5705         gtk_text_layout_move_iter_visually (priv->layout,
5706                                             &newplace, count);
5707       break;
5708
5709     case GTK_MOVEMENT_WORDS:
5710       if (count < 0)
5711         gtk_text_iter_backward_visible_word_starts (&newplace, -count);
5712       else if (count > 0) 
5713         {
5714           if (!gtk_text_iter_forward_visible_word_ends (&newplace, count))
5715             gtk_text_iter_forward_to_line_end (&newplace);
5716         }
5717       break;
5718
5719     case GTK_MOVEMENT_DISPLAY_LINES:
5720       if (count < 0)
5721         {
5722           leave_direction = GTK_DIR_UP;
5723
5724           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5725             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5726           else
5727             gtk_text_iter_set_line_offset (&newplace, 0);
5728         }
5729       if (count > 0)
5730         {
5731           leave_direction = GTK_DIR_DOWN;
5732
5733           if (gtk_text_view_move_iter_by_lines (text_view, &newplace, count))
5734             gtk_text_layout_move_iter_to_x (priv->layout, &newplace, cursor_x_pos);
5735           else
5736             gtk_text_iter_forward_to_line_end (&newplace);
5737         }
5738       break;
5739
5740     case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5741       if (count > 1)
5742         gtk_text_view_move_iter_by_lines (text_view, &newplace, --count);
5743       else if (count < -1)
5744         gtk_text_view_move_iter_by_lines (text_view, &newplace, ++count);
5745
5746       if (count != 0)
5747         gtk_text_layout_move_iter_to_line_end (priv->layout, &newplace, count);
5748       break;
5749
5750     case GTK_MOVEMENT_PARAGRAPHS:
5751       if (count > 0)
5752         {
5753           if (!gtk_text_iter_ends_line (&newplace))
5754             {
5755               gtk_text_iter_forward_to_line_end (&newplace);
5756               --count;
5757             }
5758           gtk_text_iter_forward_visible_lines (&newplace, count);
5759           gtk_text_iter_forward_to_line_end (&newplace);
5760         }
5761       else if (count < 0)
5762         {
5763           if (gtk_text_iter_get_line_offset (&newplace) > 0)
5764             gtk_text_iter_set_line_offset (&newplace, 0);
5765           gtk_text_iter_forward_visible_lines (&newplace, count);
5766           gtk_text_iter_set_line_offset (&newplace, 0);
5767         }
5768       break;
5769
5770     case GTK_MOVEMENT_PARAGRAPH_ENDS:
5771       if (count > 0)
5772         {
5773           if (!gtk_text_iter_ends_line (&newplace))
5774             gtk_text_iter_forward_to_line_end (&newplace);
5775         }
5776       else if (count < 0)
5777         {
5778           gtk_text_iter_set_line_offset (&newplace, 0);
5779         }
5780       break;
5781
5782     case GTK_MOVEMENT_BUFFER_ENDS:
5783       if (count > 0)
5784         gtk_text_buffer_get_end_iter (get_buffer (text_view), &newplace);
5785       else if (count < 0)
5786         gtk_text_buffer_get_iter_at_offset (get_buffer (text_view), &newplace, 0);
5787      break;
5788       
5789     default:
5790       break;
5791     }
5792
5793   /* call move_cursor() even if the cursor hasn't moved, since it 
5794      cancels the selection
5795   */
5796   move_cursor (text_view, &newplace, extend_selection);
5797
5798   if (!gtk_text_iter_equal (&insert, &newplace))
5799     {
5800       DV(g_print (G_STRLOC": scrolling onscreen\n"));
5801       gtk_text_view_scroll_mark_onscreen (text_view,
5802                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
5803
5804       if (step == GTK_MOVEMENT_DISPLAY_LINES)
5805         gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, -1);
5806     }
5807   else if (leave_direction != -1)
5808     {
5809       if (!gtk_widget_keynav_failed (GTK_WIDGET (text_view),
5810                                      leave_direction))
5811         {
5812           g_signal_emit_by_name (text_view, "move-focus", leave_direction);
5813         }
5814     }
5815   else if (! cancel_selection)
5816     {
5817       gtk_widget_error_bell (GTK_WIDGET (text_view));
5818     }
5819
5820   gtk_text_view_check_cursor_blink (text_view);
5821   gtk_text_view_pend_cursor_blink (text_view);
5822 }
5823
5824 static void
5825 gtk_text_view_move_cursor (GtkTextView     *text_view,
5826                            GtkMovementStep  step,
5827                            gint             count,
5828                            gboolean         extend_selection)
5829 {
5830   gtk_text_view_move_cursor_internal (text_view, step, count, extend_selection);
5831 }
5832
5833 static void
5834 gtk_text_view_move_viewport (GtkTextView     *text_view,
5835                              GtkScrollStep    step,
5836                              gint             count)
5837 {
5838   GtkAdjustment *adjustment;
5839   gdouble increment;
5840   
5841   switch (step) 
5842     {
5843     case GTK_SCROLL_STEPS:
5844     case GTK_SCROLL_PAGES:
5845     case GTK_SCROLL_ENDS:
5846       adjustment = text_view->priv->vadjustment;
5847       break;
5848     case GTK_SCROLL_HORIZONTAL_STEPS:
5849     case GTK_SCROLL_HORIZONTAL_PAGES:
5850     case GTK_SCROLL_HORIZONTAL_ENDS:
5851       adjustment = text_view->priv->hadjustment;
5852       break;
5853     default:
5854       adjustment = text_view->priv->vadjustment;
5855       break;
5856     }
5857
5858   switch (step) 
5859     {
5860     case GTK_SCROLL_STEPS:
5861     case GTK_SCROLL_HORIZONTAL_STEPS:
5862       increment = gtk_adjustment_get_step_increment (adjustment);
5863       break;
5864     case GTK_SCROLL_PAGES:
5865     case GTK_SCROLL_HORIZONTAL_PAGES:
5866       increment = gtk_adjustment_get_page_increment (adjustment);
5867       break;
5868     case GTK_SCROLL_ENDS:
5869     case GTK_SCROLL_HORIZONTAL_ENDS:
5870       increment = gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_lower (adjustment);
5871       break;
5872     default:
5873       increment = 0.0;
5874       break;
5875     }
5876
5877   gtk_adjustment_set_value (adjustment, gtk_adjustment_get_value (adjustment) + count * increment);
5878 }
5879
5880 static void
5881 gtk_text_view_set_anchor (GtkTextView *text_view)
5882 {
5883   GtkTextIter insert;
5884
5885   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
5886                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
5887
5888   gtk_text_buffer_create_mark (get_buffer (text_view), "anchor", &insert, TRUE);
5889 }
5890
5891 static gboolean
5892 gtk_text_view_scroll_pages (GtkTextView *text_view,
5893                             gint         count,
5894                             gboolean     extend_selection)
5895 {
5896   GtkTextViewPrivate *priv;
5897   GtkAdjustment *adjustment;
5898   gint cursor_x_pos, cursor_y_pos;
5899   GtkTextMark *insert_mark;
5900   GtkTextIter old_insert;
5901   GtkTextIter new_insert;
5902   GtkTextIter anchor;
5903   gdouble newval;
5904   gdouble oldval;
5905   gint y0, y1;
5906
5907   priv = text_view->priv;
5908
5909   g_return_val_if_fail (priv->vadjustment != NULL, FALSE);
5910   
5911   adjustment = priv->vadjustment;
5912
5913   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
5914
5915   /* Make sure we start from the current cursor position, even
5916    * if it was offscreen, but don't queue more scrolls if we're
5917    * already behind.
5918    */
5919   if (priv->pending_scroll)
5920     cancel_pending_scroll (text_view);
5921   else
5922     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5923
5924   /* Validate the region that will be brought into view by the cursor motion
5925    */
5926   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5927                                     &old_insert, insert_mark);
5928
5929   if (count < 0)
5930     {
5931       gtk_text_view_get_first_para_iter (text_view, &anchor);
5932       y0 = gtk_adjustment_get_page_size (adjustment);
5933       y1 = gtk_adjustment_get_page_size (adjustment) + count * gtk_adjustment_get_page_increment (adjustment);
5934     }
5935   else
5936     {
5937       gtk_text_view_get_first_para_iter (text_view, &anchor);
5938       y0 = count * gtk_adjustment_get_page_increment (adjustment) + gtk_adjustment_get_page_size (adjustment);
5939       y1 = 0;
5940     }
5941
5942   gtk_text_layout_validate_yrange (priv->layout, &anchor, y0, y1);
5943   /* FIXME do we need to update the adjustment ranges here? */
5944
5945   new_insert = old_insert;
5946
5947   if (count < 0 && gtk_adjustment_get_value (adjustment) <= (gtk_adjustment_get_lower (adjustment) + 1e-12))
5948     {
5949       /* already at top, just be sure we are at offset 0 */
5950       gtk_text_buffer_get_start_iter (get_buffer (text_view), &new_insert);
5951       move_cursor (text_view, &new_insert, extend_selection);
5952     }
5953   else if (count > 0 && gtk_adjustment_get_value (adjustment) >= (gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment) - 1e-12))
5954     {
5955       /* already at bottom, just be sure we are at the end */
5956       gtk_text_buffer_get_end_iter (get_buffer (text_view), &new_insert);
5957       move_cursor (text_view, &new_insert, extend_selection);
5958     }
5959   else
5960     {
5961       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
5962
5963       oldval = gtk_adjustment_get_value (adjustment);
5964       newval = gtk_adjustment_get_value (adjustment);
5965
5966       newval += count * gtk_adjustment_get_page_increment (adjustment);
5967
5968       gtk_adjustment_set_value (adjustment, newval);
5969       cursor_y_pos += gtk_adjustment_get_value (adjustment) - oldval;
5970
5971       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
5972       clamp_iter_onscreen (text_view, &new_insert);
5973       move_cursor (text_view, &new_insert, extend_selection);
5974
5975       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
5976     }
5977   
5978   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
5979    * only guarantees 1 pixel onscreen.
5980    */
5981   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5982   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
5983
5984   return !gtk_text_iter_equal (&old_insert, &new_insert);
5985 }
5986
5987 static gboolean
5988 gtk_text_view_scroll_hpages (GtkTextView *text_view,
5989                              gint         count,
5990                              gboolean     extend_selection)
5991 {
5992   GtkTextViewPrivate *priv;
5993   GtkAdjustment *adjustment;
5994   gint cursor_x_pos, cursor_y_pos;
5995   GtkTextMark *insert_mark;
5996   GtkTextIter old_insert;
5997   GtkTextIter new_insert;
5998   gdouble newval;
5999   gdouble oldval;
6000   gint y, height;
6001
6002   priv = text_view->priv;
6003
6004   g_return_val_if_fail (priv->hadjustment != NULL, FALSE);
6005
6006   adjustment = priv->hadjustment;
6007
6008   insert_mark = gtk_text_buffer_get_insert (get_buffer (text_view));
6009
6010   /* Make sure we start from the current cursor position, even
6011    * if it was offscreen, but don't queue more scrolls if we're
6012    * already behind.
6013    */
6014   if (priv->pending_scroll)
6015     cancel_pending_scroll (text_view);
6016   else
6017     gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
6018
6019   /* Validate the line that we're moving within.
6020    */
6021   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6022                                     &old_insert, insert_mark);
6023
6024   gtk_text_layout_get_line_yrange (priv->layout, &old_insert, &y, &height);
6025   gtk_text_layout_validate_yrange (priv->layout, &old_insert, y, y + height);
6026   /* FIXME do we need to update the adjustment ranges here? */
6027
6028   new_insert = old_insert;
6029
6030   if (count < 0 && gtk_adjustment_get_value (adjustment) <= (gtk_adjustment_get_lower (adjustment) + 1e-12))
6031     {
6032       /* already at far left, just be sure we are at offset 0 */
6033       gtk_text_iter_set_line_offset (&new_insert, 0);
6034       move_cursor (text_view, &new_insert, extend_selection);
6035     }
6036   else if (count > 0 && gtk_adjustment_get_value (adjustment) >= (gtk_adjustment_get_upper (adjustment) - gtk_adjustment_get_page_size (adjustment) - 1e-12))
6037     {
6038       /* already at far right, just be sure we are at the end */
6039       if (!gtk_text_iter_ends_line (&new_insert))
6040           gtk_text_iter_forward_to_line_end (&new_insert);
6041       move_cursor (text_view, &new_insert, extend_selection);
6042     }
6043   else
6044     {
6045       gtk_text_view_get_virtual_cursor_pos (text_view, NULL, &cursor_x_pos, &cursor_y_pos);
6046
6047       oldval = gtk_adjustment_get_value (adjustment);
6048       newval = gtk_adjustment_get_value (adjustment);
6049
6050       newval += count * gtk_adjustment_get_page_increment (adjustment);
6051
6052       gtk_adjustment_set_value (adjustment, newval);
6053       cursor_x_pos += gtk_adjustment_get_value (adjustment) - oldval;
6054
6055       gtk_text_layout_get_iter_at_pixel (priv->layout, &new_insert, cursor_x_pos, cursor_y_pos);
6056       clamp_iter_onscreen (text_view, &new_insert);
6057       move_cursor (text_view, &new_insert, extend_selection);
6058
6059       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
6060     }
6061
6062   /*  FIXME for lines shorter than the overall widget width, this results in a
6063    *  "bounce" effect as we scroll to the right of the widget, then scroll
6064    *  back to get the end of the line onscreen.
6065    *      http://bugzilla.gnome.org/show_bug.cgi?id=68963
6066    */
6067   
6068   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
6069    * only guarantees 1 pixel onscreen.
6070    */
6071   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6072   gtk_text_view_scroll_mark_onscreen (text_view, insert_mark);
6073
6074   return !gtk_text_iter_equal (&old_insert, &new_insert);
6075 }
6076
6077 static gboolean
6078 whitespace (gunichar ch, gpointer user_data)
6079 {
6080   return (ch == ' ' || ch == '\t');
6081 }
6082
6083 static gboolean
6084 not_whitespace (gunichar ch, gpointer user_data)
6085 {
6086   return !whitespace (ch, user_data);
6087 }
6088
6089 static gboolean
6090 find_whitepace_region (const GtkTextIter *center,
6091                        GtkTextIter *start, GtkTextIter *end)
6092 {
6093   *start = *center;
6094   *end = *center;
6095
6096   if (gtk_text_iter_backward_find_char (start, not_whitespace, NULL, NULL))
6097     gtk_text_iter_forward_char (start); /* we want the first whitespace... */
6098   if (whitespace (gtk_text_iter_get_char (end), NULL))
6099     gtk_text_iter_forward_find_char (end, not_whitespace, NULL, NULL);
6100
6101   return !gtk_text_iter_equal (start, end);
6102 }
6103
6104 static void
6105 gtk_text_view_insert_at_cursor (GtkTextView *text_view,
6106                                 const gchar *str)
6107 {
6108   if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
6109                                                      text_view->priv->editable))
6110     {
6111       gtk_widget_error_bell (GTK_WIDGET (text_view));
6112     }
6113 }
6114
6115 static void
6116 gtk_text_view_delete_from_cursor (GtkTextView   *text_view,
6117                                   GtkDeleteType  type,
6118                                   gint           count)
6119 {
6120   GtkTextViewPrivate *priv;
6121   GtkTextIter insert;
6122   GtkTextIter start;
6123   GtkTextIter end;
6124   gboolean leave_one = FALSE;
6125
6126   priv = text_view->priv;
6127
6128   gtk_text_view_reset_im_context (text_view);
6129
6130   if (type == GTK_DELETE_CHARS)
6131     {
6132       /* Char delete deletes the selection, if one exists */
6133       if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
6134                                             priv->editable))
6135         return;
6136     }
6137
6138   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6139                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6140
6141   start = insert;
6142   end = insert;
6143
6144   switch (type)
6145     {
6146     case GTK_DELETE_CHARS:
6147       gtk_text_iter_forward_cursor_positions (&end, count);
6148       break;
6149
6150     case GTK_DELETE_WORD_ENDS:
6151       if (count > 0)
6152         gtk_text_iter_forward_word_ends (&end, count);
6153       else if (count < 0)
6154         gtk_text_iter_backward_word_starts (&start, 0 - count);
6155       break;
6156
6157     case GTK_DELETE_WORDS:
6158       break;
6159
6160     case GTK_DELETE_DISPLAY_LINE_ENDS:
6161       break;
6162
6163     case GTK_DELETE_DISPLAY_LINES:
6164       break;
6165
6166     case GTK_DELETE_PARAGRAPH_ENDS:
6167       if (count > 0)
6168         {
6169           /* If we're already at a newline, we need to
6170            * simply delete that newline, instead of
6171            * moving to the next one.
6172            */
6173           if (gtk_text_iter_ends_line (&end))
6174             {
6175               gtk_text_iter_forward_line (&end);
6176               --count;
6177             }
6178
6179           while (count > 0)
6180             {
6181               if (!gtk_text_iter_forward_to_line_end (&end))
6182                 break;
6183
6184               --count;
6185             }
6186         }
6187       else if (count < 0)
6188         {
6189           if (gtk_text_iter_starts_line (&start))
6190             {
6191               gtk_text_iter_backward_line (&start);
6192               if (!gtk_text_iter_ends_line (&end))
6193                 gtk_text_iter_forward_to_line_end (&start);
6194             }
6195           else
6196             {
6197               gtk_text_iter_set_line_offset (&start, 0);
6198             }
6199           ++count;
6200
6201           gtk_text_iter_backward_lines (&start, -count);
6202         }
6203       break;
6204
6205     case GTK_DELETE_PARAGRAPHS:
6206       if (count > 0)
6207         {
6208           gtk_text_iter_set_line_offset (&start, 0);
6209           gtk_text_iter_forward_to_line_end (&end);
6210
6211           /* Do the lines beyond the first. */
6212           while (count > 1)
6213             {
6214               gtk_text_iter_forward_to_line_end (&end);
6215
6216               --count;
6217             }
6218         }
6219
6220       /* FIXME negative count? */
6221
6222       break;
6223
6224     case GTK_DELETE_WHITESPACE:
6225       {
6226         find_whitepace_region (&insert, &start, &end);
6227       }
6228       break;
6229
6230     default:
6231       break;
6232     }
6233
6234   if (!gtk_text_iter_equal (&start, &end))
6235     {
6236       gtk_text_buffer_begin_user_action (get_buffer (text_view));
6237
6238       if (gtk_text_buffer_delete_interactive (get_buffer (text_view), &start, &end,
6239                                               priv->editable))
6240         {
6241           if (leave_one)
6242             gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view),
6243                                                           " ", 1,
6244                                                           priv->editable);
6245         }
6246       else
6247         {
6248           gtk_widget_error_bell (GTK_WIDGET (text_view));
6249         }
6250
6251       gtk_text_buffer_end_user_action (get_buffer (text_view));
6252       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
6253
6254       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6255       gtk_text_view_scroll_mark_onscreen (text_view,
6256                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
6257     }
6258   else
6259     {
6260       gtk_widget_error_bell (GTK_WIDGET (text_view));
6261     }
6262 }
6263
6264 static void
6265 gtk_text_view_backspace (GtkTextView *text_view)
6266 {
6267   GtkTextViewPrivate *priv;
6268   GtkTextIter insert;
6269
6270   priv = text_view->priv;
6271
6272   gtk_text_view_reset_im_context (text_view);
6273
6274   /* Backspace deletes the selection, if one exists */
6275   if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
6276                                         priv->editable))
6277     return;
6278
6279   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6280                                     &insert,
6281                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6282
6283   if (gtk_text_buffer_backspace (get_buffer (text_view), &insert,
6284                                  TRUE, priv->editable))
6285     {
6286       gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
6287       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6288       gtk_text_view_scroll_mark_onscreen (text_view,
6289                                           gtk_text_buffer_get_insert (get_buffer (text_view)));
6290     }
6291   else
6292     {
6293       gtk_widget_error_bell (GTK_WIDGET (text_view));
6294     }
6295 }
6296
6297 static void
6298 gtk_text_view_cut_clipboard (GtkTextView *text_view)
6299 {
6300   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6301                                                       GDK_SELECTION_CLIPBOARD);
6302   
6303   gtk_text_buffer_cut_clipboard (get_buffer (text_view),
6304                                  clipboard,
6305                                  text_view->priv->editable);
6306   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6307   gtk_text_view_scroll_mark_onscreen (text_view,
6308                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6309 }
6310
6311 static void
6312 gtk_text_view_copy_clipboard (GtkTextView *text_view)
6313 {
6314   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6315                                                       GDK_SELECTION_CLIPBOARD);
6316   
6317   gtk_text_buffer_copy_clipboard (get_buffer (text_view),
6318                                   clipboard);
6319
6320   /* on copy do not scroll, we are already onscreen */
6321 }
6322
6323 static void
6324 gtk_text_view_paste_clipboard (GtkTextView *text_view)
6325 {
6326   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6327                                                       GDK_SELECTION_CLIPBOARD);
6328   
6329   gtk_text_buffer_paste_clipboard (get_buffer (text_view),
6330                                    clipboard,
6331                                    NULL,
6332                                    text_view->priv->editable);
6333 }
6334
6335 static void
6336 gtk_text_view_paste_done_handler (GtkTextBuffer *buffer,
6337                                   GtkClipboard  *clipboard,
6338                                   gpointer       data)
6339 {
6340   GtkTextView *text_view = data;
6341   GtkTextViewPrivate *priv;
6342
6343   priv = text_view->priv;
6344
6345   if (priv->scroll_after_paste)
6346     {
6347       DV(g_print (G_STRLOC": scrolling onscreen\n"));
6348       gtk_text_view_scroll_mark_onscreen (text_view, gtk_text_buffer_get_insert (buffer));
6349     }
6350
6351   priv->scroll_after_paste = TRUE;
6352 }
6353
6354 static void
6355 gtk_text_view_buffer_changed_handler (GtkTextBuffer *buffer,
6356                                       gpointer       data)
6357 {
6358   GtkTextView *text_view = data;
6359   gtk_text_view_update_handles (text_view, GTK_TEXT_HANDLE_MODE_NONE);
6360 }
6361
6362 static void
6363 gtk_text_view_toggle_overwrite (GtkTextView *text_view)
6364 {
6365   GtkTextViewPrivate *priv = text_view->priv;
6366
6367   if (priv->text_window)
6368     text_window_invalidate_cursors (priv->text_window);
6369
6370   priv->overwrite_mode = !priv->overwrite_mode;
6371
6372   if (priv->layout)
6373     gtk_text_layout_set_overwrite_mode (priv->layout,
6374                                         priv->overwrite_mode && priv->editable);
6375
6376   if (priv->text_window)
6377     text_window_invalidate_cursors (priv->text_window);
6378
6379   gtk_text_view_pend_cursor_blink (text_view);
6380
6381   g_object_notify (G_OBJECT (text_view), "overwrite");
6382 }
6383
6384 /**
6385  * gtk_text_view_get_overwrite:
6386  * @text_view: a #GtkTextView
6387  *
6388  * Returns whether the #GtkTextView is in overwrite mode or not.
6389  *
6390  * Return value: whether @text_view is in overwrite mode or not.
6391  * 
6392  * Since: 2.4
6393  **/
6394 gboolean
6395 gtk_text_view_get_overwrite (GtkTextView *text_view)
6396 {
6397   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6398
6399   return text_view->priv->overwrite_mode;
6400 }
6401
6402 /**
6403  * gtk_text_view_set_overwrite:
6404  * @text_view: a #GtkTextView
6405  * @overwrite: %TRUE to turn on overwrite mode, %FALSE to turn it off
6406  *
6407  * Changes the #GtkTextView overwrite mode.
6408  *
6409  * Since: 2.4
6410  **/
6411 void
6412 gtk_text_view_set_overwrite (GtkTextView *text_view,
6413                              gboolean     overwrite)
6414 {
6415   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6416   overwrite = overwrite != FALSE;
6417
6418   if (text_view->priv->overwrite_mode != overwrite)
6419     gtk_text_view_toggle_overwrite (text_view);
6420 }
6421
6422 /**
6423  * gtk_text_view_set_accepts_tab:
6424  * @text_view: A #GtkTextView
6425  * @accepts_tab: %TRUE if pressing the Tab key should insert a tab 
6426  *    character, %FALSE, if pressing the Tab key should move the 
6427  *    keyboard focus.
6428  * 
6429  * Sets the behavior of the text widget when the Tab key is pressed. 
6430  * If @accepts_tab is %TRUE, a tab character is inserted. If @accepts_tab 
6431  * is %FALSE the keyboard focus is moved to the next widget in the focus 
6432  * chain.
6433  * 
6434  * Since: 2.4
6435  **/
6436 void
6437 gtk_text_view_set_accepts_tab (GtkTextView *text_view,
6438                                gboolean     accepts_tab)
6439 {
6440   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6441
6442   accepts_tab = accepts_tab != FALSE;
6443
6444   if (text_view->priv->accepts_tab != accepts_tab)
6445     {
6446       text_view->priv->accepts_tab = accepts_tab;
6447
6448       g_object_notify (G_OBJECT (text_view), "accepts-tab");
6449     }
6450 }
6451
6452 /**
6453  * gtk_text_view_get_accepts_tab:
6454  * @text_view: A #GtkTextView
6455  * 
6456  * Returns whether pressing the Tab key inserts a tab characters.
6457  * gtk_text_view_set_accepts_tab().
6458  * 
6459  * Return value: %TRUE if pressing the Tab key inserts a tab character, 
6460  *   %FALSE if pressing the Tab key moves the keyboard focus.
6461  * 
6462  * Since: 2.4
6463  **/
6464 gboolean
6465 gtk_text_view_get_accepts_tab (GtkTextView *text_view)
6466 {
6467   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
6468
6469   return text_view->priv->accepts_tab;
6470 }
6471
6472 /*
6473  * Selections
6474  */
6475
6476 static void
6477 gtk_text_view_unselect (GtkTextView *text_view)
6478 {
6479   GtkTextIter insert;
6480
6481   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6482                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6483
6484   gtk_text_buffer_move_mark (get_buffer (text_view),
6485                              gtk_text_buffer_get_selection_bound (get_buffer (text_view)),
6486                              &insert);
6487 }
6488
6489 static void
6490 get_iter_at_pointer (GtkTextView *text_view,
6491                      GdkDevice   *device,
6492                      GtkTextIter *iter,
6493                      gint        *x,
6494                      gint        *y)
6495 {
6496   GtkTextViewPrivate *priv;
6497   gint xcoord, ycoord;
6498   GdkModifierType state;
6499
6500   priv = text_view->priv;
6501
6502   gdk_window_get_device_position (priv->text_window->bin_window,
6503                                   device, &xcoord, &ycoord, &state);
6504
6505   gtk_text_layout_get_iter_at_pixel (priv->layout,
6506                                      iter,
6507                                      xcoord + priv->xoffset,
6508                                      ycoord + priv->yoffset);
6509   if (x)
6510     *x = xcoord;
6511
6512   if (y)
6513     *y = ycoord;
6514 }
6515
6516 static void
6517 move_mark_to_pointer_and_scroll (GtkTextView    *text_view,
6518                                  const gchar    *mark_name,
6519                                  GdkDevice      *device,
6520                                  GdkInputSource  source)
6521 {
6522   GtkTextIter newplace;
6523   GtkTextBuffer *buffer;
6524   GtkTextMark *mark;
6525
6526   buffer = get_buffer (text_view);
6527   get_iter_at_pointer (text_view, device, &newplace, NULL, NULL);
6528
6529   mark = gtk_text_buffer_get_mark (buffer, mark_name);
6530
6531   /* This may invalidate the layout */
6532   DV(g_print (G_STRLOC": move mark\n"));
6533
6534   gtk_text_buffer_move_mark (buffer, mark, &newplace);
6535
6536   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6537   gtk_text_view_scroll_mark_onscreen (text_view, mark);
6538
6539   DV (g_print ("first validate idle leaving %s is %d\n",
6540                G_STRLOC, text_view->priv->first_validate_idle));
6541 }
6542
6543 static gboolean
6544 selection_scan_timeout (gpointer data)
6545 {
6546   GtkTextView *text_view;
6547
6548   text_view = GTK_TEXT_VIEW (data);
6549
6550   gtk_text_view_scroll_mark_onscreen (text_view, 
6551                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
6552
6553   return TRUE; /* remain installed. */
6554 }
6555
6556 #define UPPER_OFFSET_ANCHOR 0.8
6557 #define LOWER_OFFSET_ANCHOR 0.2
6558
6559 static gboolean
6560 check_scroll (gdouble offset, GtkAdjustment *adjustment)
6561 {
6562   if ((offset > UPPER_OFFSET_ANCHOR &&
6563        gtk_adjustment_get_value (adjustment) + gtk_adjustment_get_page_size (adjustment) < gtk_adjustment_get_upper (adjustment)) ||
6564       (offset < LOWER_OFFSET_ANCHOR &&
6565        gtk_adjustment_get_value (adjustment) > gtk_adjustment_get_lower (adjustment)))
6566     return TRUE;
6567
6568   return FALSE;
6569 }
6570
6571 static gint
6572 drag_scan_timeout (gpointer data)
6573 {
6574   GtkTextView *text_view;
6575   GtkTextViewPrivate *priv;
6576   GtkTextIter newplace;
6577   gint x, y;
6578   gdouble pointer_xoffset, pointer_yoffset;
6579
6580   text_view = GTK_TEXT_VIEW (data);
6581   priv = text_view->priv;
6582
6583   get_iter_at_pointer (text_view, priv->dnd_device, &newplace, &x, &y);
6584
6585   gtk_text_buffer_move_mark (get_buffer (text_view),
6586                              priv->dnd_mark,
6587                              &newplace);
6588
6589   pointer_xoffset = (gdouble) x / gdk_window_get_width (priv->text_window->bin_window);
6590   pointer_yoffset = (gdouble) y / gdk_window_get_height (priv->text_window->bin_window);
6591
6592   if (check_scroll (pointer_xoffset, priv->hadjustment) ||
6593       check_scroll (pointer_yoffset, priv->vadjustment))
6594     {
6595       /* do not make offsets surpass lower nor upper anchors, this makes
6596        * scrolling speed relative to the distance of the pointer to the
6597        * anchors when it moves beyond them.
6598        */
6599       pointer_xoffset = CLAMP (pointer_xoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6600       pointer_yoffset = CLAMP (pointer_yoffset, LOWER_OFFSET_ANCHOR, UPPER_OFFSET_ANCHOR);
6601
6602       gtk_text_view_scroll_to_mark (text_view,
6603                                     priv->dnd_mark,
6604                                     0., TRUE, pointer_xoffset, pointer_yoffset);
6605     }
6606
6607   return TRUE;
6608 }
6609
6610 typedef enum 
6611 {
6612   SELECT_CHARACTERS,
6613   SELECT_WORDS,
6614   SELECT_LINES
6615 } SelectionGranularity;
6616
6617 /*
6618  * Move @start and @end to the boundaries of the selection unit (indicated by 
6619  * @granularity) which contained @start initially.
6620  * If the selction unit is SELECT_WORDS and @start is not contained in a word
6621  * the selection is extended to all the white spaces between the end of the 
6622  * word preceding @start and the start of the one following.
6623  */
6624 static void
6625 extend_selection (GtkTextView *text_view, 
6626                   SelectionGranularity granularity, 
6627                   GtkTextIter *start, 
6628                   GtkTextIter *end)
6629 {
6630   *end = *start;
6631
6632   if (granularity == SELECT_WORDS) 
6633     {
6634       if (gtk_text_iter_inside_word (start))
6635         {
6636           if (!gtk_text_iter_starts_word (start))
6637             gtk_text_iter_backward_visible_word_start (start);
6638           
6639           if (!gtk_text_iter_ends_word (end))
6640             {
6641               if (!gtk_text_iter_forward_visible_word_end (end))
6642                 gtk_text_iter_forward_to_end (end);
6643             }
6644         }
6645       else
6646         {
6647           GtkTextIter tmp;
6648
6649           tmp = *start;
6650           if (gtk_text_iter_backward_visible_word_start (&tmp))
6651             gtk_text_iter_forward_visible_word_end (&tmp);
6652
6653           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (start))
6654             *start = tmp;
6655           else
6656             gtk_text_iter_set_line_offset (start, 0);
6657
6658           tmp = *end;
6659           if (!gtk_text_iter_forward_visible_word_end (&tmp))
6660             gtk_text_iter_forward_to_end (&tmp);
6661
6662           if (gtk_text_iter_ends_word (&tmp))
6663             gtk_text_iter_backward_visible_word_start (&tmp);
6664
6665           if (gtk_text_iter_get_line (&tmp) == gtk_text_iter_get_line (end))
6666             *end = tmp;
6667           else
6668             gtk_text_iter_forward_to_line_end (end);
6669         }
6670     }
6671   else if (granularity == SELECT_LINES) 
6672     {
6673       if (gtk_text_view_starts_display_line (text_view, start))
6674         {
6675           /* If on a display line boundary, we assume the user
6676            * clicked off the end of a line and we therefore select
6677            * the line before the boundary.
6678            */
6679           gtk_text_view_backward_display_line_start (text_view, start);
6680         }
6681       else
6682         {
6683           /* start isn't on the start of a line, so we move it to the
6684            * start, and move end to the end unless it's already there.
6685            */
6686           gtk_text_view_backward_display_line_start (text_view, start);
6687           
6688           if (!gtk_text_view_starts_display_line (text_view, end))
6689             gtk_text_view_forward_display_line_end (text_view, end);
6690         }
6691     }
6692 }
6693  
6694
6695 typedef struct
6696 {
6697   SelectionGranularity granularity;
6698   GtkTextMark *orig_start;
6699   GtkTextMark *orig_end;
6700 } SelectionData;
6701
6702 static void
6703 selection_data_free (SelectionData *data)
6704 {
6705   if (data->orig_start != NULL)
6706     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_start),
6707                                  data->orig_start);
6708   if (data->orig_end != NULL)
6709     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (data->orig_end),
6710                                  data->orig_end);
6711   g_free (data);
6712 }
6713
6714 static gint
6715 selection_motion_event_handler (GtkTextView    *text_view, 
6716                                 GdkEventMotion *event, 
6717                                 SelectionData  *data)
6718 {
6719   GtkTextViewPrivate *priv;
6720   GdkInputSource input_source;
6721   GdkDevice *device;
6722
6723   priv = text_view->priv;
6724   gdk_event_request_motions (event);
6725
6726   device = gdk_event_get_source_device ((GdkEvent *) event);
6727   input_source = gdk_device_get_source (device);
6728
6729   if (priv->grab_device != event->device)
6730     return FALSE;
6731
6732   if (data->granularity == SELECT_CHARACTERS) 
6733     {
6734       move_mark_to_pointer_and_scroll (text_view, "insert",
6735                                        event->device, input_source);
6736     }
6737   else 
6738     {
6739       GtkTextIter cursor, start, end;
6740       GtkTextIter orig_start, orig_end;
6741       GtkTextBuffer *buffer;
6742       
6743       buffer = get_buffer (text_view);
6744
6745       gtk_text_buffer_get_iter_at_mark (buffer, &orig_start, data->orig_start);
6746       gtk_text_buffer_get_iter_at_mark (buffer, &orig_end, data->orig_end);
6747
6748       get_iter_at_pointer (text_view, event->device, &cursor, NULL, NULL);
6749       
6750       start = cursor;
6751       extend_selection (text_view, data->granularity, &start, &end);
6752
6753       /* either the selection extends to the front, or end (or not) */
6754       if (gtk_text_iter_compare (&cursor, &orig_start) < 0)
6755         gtk_text_buffer_select_range (buffer, &start, &orig_end);
6756       else
6757         gtk_text_buffer_select_range (buffer, &end, &orig_start);
6758
6759       gtk_text_view_scroll_mark_onscreen (text_view,
6760                                           gtk_text_buffer_get_insert (buffer));
6761     }
6762
6763   /* If we had to scroll offscreen, insert a timeout to do so
6764    * again. Note that in the timeout, even if the mouse doesn't
6765    * move, due to this scroll xoffset/yoffset will have changed
6766    * and we'll need to scroll again.
6767    */
6768   if (text_view->priv->scroll_timeout != 0) /* reset on every motion event */
6769     g_source_remove (text_view->priv->scroll_timeout);
6770   
6771   text_view->priv->scroll_timeout =
6772     gdk_threads_add_timeout (50, selection_scan_timeout, text_view);
6773
6774   if (test_touchscreen || input_source == GDK_SOURCE_TOUCHSCREEN)
6775     gtk_text_view_update_handles (text_view, GTK_TEXT_HANDLE_MODE_SELECTION);
6776
6777   return TRUE;
6778 }
6779
6780 static void
6781 gtk_text_view_start_selection_drag (GtkTextView       *text_view,
6782                                     const GtkTextIter *iter,
6783                                     GdkEventButton    *button)
6784 {
6785   GtkTextViewPrivate *priv;
6786   GtkTextIter cursor, ins, bound;
6787   GtkTextIter orig_start, orig_end;
6788   GtkTextBuffer *buffer;
6789   SelectionData *data;
6790
6791   if (text_view->priv->selection_drag_handler != 0)
6792     return;
6793
6794   priv = text_view->priv;
6795   data = g_new0 (SelectionData, 1);
6796
6797   if (button->type == GDK_2BUTTON_PRESS)
6798     data->granularity = SELECT_WORDS;
6799   else if (button->type == GDK_3BUTTON_PRESS)
6800     data->granularity = SELECT_LINES;
6801   else 
6802     data->granularity = SELECT_CHARACTERS;
6803
6804   priv->grab_device = button->device;
6805   gtk_device_grab_add (GTK_WIDGET (text_view),
6806                        priv->grab_device,
6807                        TRUE);
6808
6809   buffer = get_buffer (text_view);
6810   
6811   cursor = *iter;
6812   ins = cursor;
6813   
6814   extend_selection (text_view, data->granularity, &ins, &bound);
6815   orig_start = ins;
6816   orig_end = bound;
6817
6818   if (button->state &
6819       gtk_widget_get_modifier_mask (GTK_WIDGET (text_view),
6820                                     GDK_MODIFIER_INTENT_EXTEND_SELECTION))
6821     {
6822       /* Extend selection */
6823       GtkTextIter old_ins, old_bound;
6824       GtkTextIter old_start, old_end;
6825
6826       gtk_text_buffer_get_iter_at_mark (buffer, &old_ins, gtk_text_buffer_get_insert (buffer));
6827       gtk_text_buffer_get_iter_at_mark (buffer, &old_bound, gtk_text_buffer_get_selection_bound (buffer));
6828       old_start = old_ins;
6829       old_end = old_bound;
6830       gtk_text_iter_order (&old_start, &old_end);
6831       
6832       /* move the front cursor, if the mouse is in front of the selection. Should the
6833        * cursor however be inside the selection (this happens on tripple click) then we
6834        * move the side which was last moved (current insert mark) */
6835       if (gtk_text_iter_compare (&cursor, &old_start) <= 0 ||
6836           (gtk_text_iter_compare (&cursor, &old_end) < 0 && 
6837            gtk_text_iter_compare (&old_ins, &old_bound) <= 0))
6838         {
6839           bound = old_end;
6840           orig_start = old_end;
6841           orig_end = old_end;
6842         }
6843       else
6844         {
6845           ins = bound;
6846           bound = old_start;
6847           orig_end = bound;
6848           orig_start = bound;
6849         }
6850     }
6851
6852   gtk_text_buffer_select_range (buffer, &ins, &bound);
6853
6854   gtk_text_iter_order (&orig_start, &orig_end);
6855   data->orig_start = gtk_text_buffer_create_mark (buffer, NULL,
6856                                                   &orig_start, TRUE);
6857   data->orig_end = gtk_text_buffer_create_mark (buffer, NULL,
6858                                                 &orig_end, TRUE);
6859   gtk_text_view_check_cursor_blink (text_view);
6860
6861   text_view->priv->selection_drag_handler = g_signal_connect_data (text_view,
6862                                                                    "motion-notify-event",
6863                                                                    G_CALLBACK (selection_motion_event_handler),
6864                                                                    data,
6865                                                                    (GClosureNotify) selection_data_free, 0);
6866 }
6867
6868 /* returns whether we were really dragging */
6869 static gboolean
6870 gtk_text_view_end_selection_drag (GtkTextView *text_view)
6871 {
6872   GtkTextViewPrivate *priv;
6873
6874   priv = text_view->priv;
6875
6876   if (!priv->grab_device)
6877     return FALSE;
6878
6879   if (priv->selection_drag_handler == 0)
6880     return FALSE;
6881
6882   g_signal_handler_disconnect (text_view, priv->selection_drag_handler);
6883   priv->selection_drag_handler = 0;
6884
6885   if (priv->scroll_timeout != 0)
6886     {
6887       g_source_remove (priv->scroll_timeout);
6888       priv->scroll_timeout = 0;
6889     }
6890
6891   gtk_device_grab_remove (GTK_WIDGET (text_view),
6892                           priv->grab_device);
6893   priv->grab_device = NULL;
6894
6895   return TRUE;
6896 }
6897
6898 /*
6899  * Layout utils
6900  */
6901
6902 static void
6903 gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
6904                                          GtkTextAttributes  *values)
6905 {
6906   GtkStyleContext *context;
6907   GdkRGBA bg_color, fg_color;
6908   GtkStateFlags state;
6909
6910   context = gtk_widget_get_style_context (GTK_WIDGET (text_view));
6911   state = gtk_widget_get_state_flags (GTK_WIDGET (text_view));
6912
6913   gtk_style_context_save (context);
6914   gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
6915
6916   gtk_style_context_get_background_color (context, state, &bg_color);
6917   gtk_style_context_get_color (context, state, &fg_color);
6918
6919   values->appearance.bg_color.red = CLAMP (bg_color.red * 65535. + 0.5, 0, 65535);
6920   values->appearance.bg_color.green = CLAMP (bg_color.green * 65535. + 0.5, 0, 65535);
6921   values->appearance.bg_color.blue = CLAMP (bg_color.blue * 65535. + 0.5, 0, 65535);
6922
6923   values->appearance.fg_color.red = CLAMP (fg_color.red * 65535. + 0.5, 0, 65535);
6924   values->appearance.fg_color.green = CLAMP (fg_color.green * 65535. + 0.5, 0, 65535);
6925   values->appearance.fg_color.blue = CLAMP (fg_color.blue * 65535. + 0.5, 0, 65535);
6926
6927   if (values->font)
6928     pango_font_description_free (values->font);
6929
6930   gtk_style_context_get (context, state, "font", &values->font, NULL);
6931
6932   gtk_style_context_restore (context);
6933 }
6934
6935 static void
6936 gtk_text_view_check_keymap_direction (GtkTextView *text_view)
6937 {
6938   GtkTextViewPrivate *priv = text_view->priv;
6939
6940   if (priv->layout)
6941     {
6942       GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
6943       GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)));
6944       GtkTextDirection new_cursor_dir;
6945       GtkTextDirection new_keyboard_dir;
6946       gboolean split_cursor;
6947
6948       g_object_get (settings,
6949                     "gtk-split-cursor", &split_cursor,
6950                     NULL);
6951       
6952       if (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_RTL)
6953         new_keyboard_dir = GTK_TEXT_DIR_RTL;
6954       else
6955         new_keyboard_dir  = GTK_TEXT_DIR_LTR;
6956   
6957       if (split_cursor)
6958         new_cursor_dir = GTK_TEXT_DIR_NONE;
6959       else
6960         new_cursor_dir = new_keyboard_dir;
6961       
6962       gtk_text_layout_set_cursor_direction (priv->layout, new_cursor_dir);
6963       gtk_text_layout_set_keyboard_direction (priv->layout, new_keyboard_dir);
6964     }
6965 }
6966
6967 static void
6968 gtk_text_view_ensure_layout (GtkTextView *text_view)
6969 {
6970   GtkWidget *widget;
6971   GtkTextViewPrivate *priv;
6972
6973   widget = GTK_WIDGET (text_view);
6974   priv = text_view->priv;
6975
6976   if (priv->layout == NULL)
6977     {
6978       GtkTextAttributes *style;
6979       PangoContext *ltr_context, *rtl_context;
6980       GSList *tmp_list;
6981
6982       DV(g_print(G_STRLOC"\n"));
6983       
6984       priv->layout = gtk_text_layout_new ();
6985
6986       g_signal_connect (priv->layout,
6987                         "invalidated",
6988                         G_CALLBACK (invalidated_handler),
6989                         text_view);
6990
6991       g_signal_connect (priv->layout,
6992                         "changed",
6993                         G_CALLBACK (changed_handler),
6994                         text_view);
6995
6996       g_signal_connect (priv->layout,
6997                         "allocate-child",
6998                         G_CALLBACK (gtk_text_view_child_allocated),
6999                         text_view);
7000       
7001       if (get_buffer (text_view))
7002         gtk_text_layout_set_buffer (priv->layout, get_buffer (text_view));
7003
7004       if ((gtk_widget_has_focus (widget) && priv->cursor_visible))
7005         gtk_text_view_pend_cursor_blink (text_view);
7006       else
7007         gtk_text_layout_set_cursor_visible (priv->layout, FALSE);
7008
7009       gtk_text_layout_set_overwrite_mode (priv->layout,
7010                                           priv->overwrite_mode && priv->editable);
7011
7012       ltr_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
7013       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
7014       rtl_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
7015       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
7016
7017       gtk_text_layout_set_contexts (priv->layout, ltr_context, rtl_context);
7018
7019       g_object_unref (ltr_context);
7020       g_object_unref (rtl_context);
7021
7022       gtk_text_view_check_keymap_direction (text_view);
7023
7024       style = gtk_text_attributes_new ();
7025
7026       gtk_text_view_set_attributes_from_style (text_view, style);
7027
7028       style->pixels_above_lines = priv->pixels_above_lines;
7029       style->pixels_below_lines = priv->pixels_below_lines;
7030       style->pixels_inside_wrap = priv->pixels_inside_wrap;
7031       style->left_margin = priv->left_margin;
7032       style->right_margin = priv->right_margin;
7033       style->indent = priv->indent;
7034       style->tabs = priv->tabs ? pango_tab_array_copy (priv->tabs) : NULL;
7035
7036       style->wrap_mode = priv->wrap_mode;
7037       style->justification = priv->justify;
7038       style->direction = gtk_widget_get_direction (GTK_WIDGET (text_view));
7039
7040       gtk_text_layout_set_default_style (priv->layout, style);
7041
7042       gtk_text_attributes_unref (style);
7043
7044       /* Set layout for all anchored children */
7045
7046       tmp_list = priv->children;
7047       while (tmp_list != NULL)
7048         {
7049           GtkTextViewChild *vc = tmp_list->data;
7050
7051           if (vc->anchor)
7052             {
7053               gtk_text_anchored_child_set_layout (vc->widget,
7054                                                   priv->layout);
7055               /* vc may now be invalid! */
7056             }
7057
7058           tmp_list = g_slist_next (tmp_list);
7059         }
7060     }
7061 }
7062
7063 /**
7064  * gtk_text_view_get_default_attributes:
7065  * @text_view: a #GtkTextView
7066  * 
7067  * Obtains a copy of the default text attributes. These are the
7068  * attributes used for text unless a tag overrides them.
7069  * You'd typically pass the default attributes in to
7070  * gtk_text_iter_get_attributes() in order to get the
7071  * attributes in effect at a given text position.
7072  *
7073  * The return value is a copy owned by the caller of this function,
7074  * and should be freed.
7075  * 
7076  * Return value: a new #GtkTextAttributes
7077  **/
7078 GtkTextAttributes*
7079 gtk_text_view_get_default_attributes (GtkTextView *text_view)
7080 {
7081   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7082   
7083   gtk_text_view_ensure_layout (text_view);
7084
7085   return gtk_text_attributes_copy (text_view->priv->layout->default_style);
7086 }
7087
7088 static void
7089 gtk_text_view_destroy_layout (GtkTextView *text_view)
7090 {
7091   GtkTextViewPrivate *priv = text_view->priv;
7092
7093   if (priv->layout)
7094     {
7095       GSList *tmp_list;
7096
7097       gtk_text_view_remove_validate_idles (text_view);
7098
7099       g_signal_handlers_disconnect_by_func (priv->layout,
7100                                             invalidated_handler,
7101                                             text_view);
7102       g_signal_handlers_disconnect_by_func (priv->layout,
7103                                             changed_handler,
7104                                             text_view);
7105
7106       /* Remove layout from all anchored children */
7107       tmp_list = priv->children;
7108       while (tmp_list != NULL)
7109         {
7110           GtkTextViewChild *vc = tmp_list->data;
7111
7112           if (vc->anchor)
7113             {
7114               gtk_text_anchored_child_set_layout (vc->widget, NULL);
7115               /* vc may now be invalid! */
7116             }
7117
7118           tmp_list = g_slist_next (tmp_list);
7119         }
7120
7121       gtk_text_view_stop_cursor_blink (text_view);
7122       gtk_text_view_end_selection_drag (text_view);
7123
7124       g_object_unref (priv->layout);
7125       priv->layout = NULL;
7126     }
7127 }
7128
7129 /**
7130  * gtk_text_view_reset_im_context:
7131  * @text_view: a #GtkTextView
7132  *
7133  * Reset the input method context of the text view if needed.
7134  *
7135  * This can be necessary in the case where modifying the buffer
7136  * would confuse on-going input method behavior.
7137  *
7138  * Since: 2.22
7139  */
7140 void
7141 gtk_text_view_reset_im_context (GtkTextView *text_view)
7142 {
7143   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7144
7145   if (text_view->priv->need_im_reset)
7146     {
7147       text_view->priv->need_im_reset = FALSE;
7148       gtk_im_context_reset (text_view->priv->im_context);
7149     }
7150 }
7151
7152 /**
7153  * gtk_text_view_im_context_filter_keypress:
7154  * @text_view: a #GtkTextView
7155  * @event: the key event
7156  *
7157  * Allow the #GtkTextView input method to internally handle key press
7158  * and release events. If this function returns %TRUE, then no further
7159  * processing should be done for this key event. See
7160  * gtk_im_context_filter_keypress().
7161  *
7162  * Note that you are expected to call this function from your handler
7163  * when overriding key event handling. This is needed in the case when
7164  * you need to insert your own key handling between the input method
7165  * and the default key event handling of the #GtkTextView.
7166  *
7167  * |[
7168  * static gboolean
7169  * gtk_foo_bar_key_press_event (GtkWidget   *widget,
7170  *                              GdkEventKey *event)
7171  * {
7172  *   if ((key->keyval == GDK_KEY_Return || key->keyval == GDK_KEY_KP_Enter))
7173  *     {
7174  *       if (gtk_text_view_im_context_filter_keypress (GTK_TEXT_VIEW (view), event))
7175  *         return TRUE;
7176  *     }
7177  *
7178  *     /&ast; Do some stuff &ast;/
7179  *
7180  *   return GTK_WIDGET_CLASS (gtk_foo_bar_parent_class)->key_press_event (widget, event);
7181  * }
7182  * ]|
7183  *
7184  * Return value: %TRUE if the input method handled the key event.
7185  *
7186  * Since: 2.22
7187  */
7188 gboolean
7189 gtk_text_view_im_context_filter_keypress (GtkTextView  *text_view,
7190                                           GdkEventKey  *event)
7191 {
7192   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7193
7194   return gtk_im_context_filter_keypress (text_view->priv->im_context, event);
7195 }
7196
7197 /*
7198  * DND feature
7199  */
7200
7201 static void
7202 drag_begin_cb (GtkWidget      *widget,
7203                GdkDragContext *context,
7204                gpointer        data)
7205 {
7206   GtkTextView     *text_view = GTK_TEXT_VIEW (widget);
7207   GtkTextBuffer   *buffer = gtk_text_view_get_buffer (text_view);
7208   GtkTextIter      start;
7209   GtkTextIter      end;
7210   cairo_surface_t *surface = NULL;
7211
7212   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
7213
7214   if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7215     surface = _gtk_text_util_create_rich_drag_icon (widget, buffer, &start, &end);
7216
7217   if (surface)
7218     {
7219       gtk_drag_set_icon_surface (context, surface);
7220       cairo_surface_destroy (surface);
7221     }
7222   else
7223     {
7224       gtk_drag_set_icon_default (context);
7225     }
7226 }
7227
7228 static void
7229 gtk_text_view_start_selection_dnd (GtkTextView       *text_view,
7230                                    const GtkTextIter *iter,
7231                                    GdkEventMotion    *event)
7232 {
7233   GtkTargetList *target_list;
7234
7235   text_view->priv->drag_start_x = -1;
7236   text_view->priv->drag_start_y = -1;
7237   text_view->priv->pending_place_cursor_button = 0;
7238
7239   target_list = gtk_text_buffer_get_copy_target_list (get_buffer (text_view));
7240
7241   g_signal_connect (text_view, "drag-begin",
7242                     G_CALLBACK (drag_begin_cb), NULL);
7243   gtk_drag_begin (GTK_WIDGET (text_view), target_list,
7244                   GDK_ACTION_COPY | GDK_ACTION_MOVE,
7245                   1, (GdkEvent*)event);
7246 }
7247
7248 static void
7249 gtk_text_view_drag_begin (GtkWidget        *widget,
7250                           GdkDragContext   *context)
7251 {
7252   /* do nothing */
7253 }
7254
7255 static void
7256 gtk_text_view_drag_end (GtkWidget        *widget,
7257                         GdkDragContext   *context)
7258 {
7259 }
7260
7261 static void
7262 gtk_text_view_drag_data_get (GtkWidget        *widget,
7263                              GdkDragContext   *context,
7264                              GtkSelectionData *selection_data,
7265                              guint             info,
7266                              guint             time)
7267 {
7268   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
7269   GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
7270
7271   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7272     {
7273       gtk_selection_data_set (selection_data,
7274                               gdk_atom_intern_static_string ("GTK_TEXT_BUFFER_CONTENTS"),
7275                               8, /* bytes */
7276                               (void*)&buffer,
7277                               sizeof (buffer));
7278     }
7279   else if (info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
7280     {
7281       GtkTextIter start;
7282       GtkTextIter end;
7283       guint8 *str = NULL;
7284       gsize len;
7285
7286       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7287         {
7288           /* Extract the selected text */
7289           str = gtk_text_buffer_serialize (buffer, buffer,
7290                                            gtk_selection_data_get_target (selection_data),
7291                                            &start, &end,
7292                                            &len);
7293         }
7294
7295       if (str)
7296         {
7297           gtk_selection_data_set (selection_data,
7298                                   gtk_selection_data_get_target (selection_data),
7299                                   8, /* bytes */
7300                                   (guchar *) str, len);
7301           g_free (str);
7302         }
7303     }
7304   else
7305     {
7306       GtkTextIter start;
7307       GtkTextIter end;
7308       gchar *str = NULL;
7309
7310       if (gtk_text_buffer_get_selection_bounds (buffer, &start, &end))
7311         {
7312           /* Extract the selected text */
7313           str = gtk_text_iter_get_visible_text (&start, &end);
7314         }
7315
7316       if (str)
7317         {
7318           gtk_selection_data_set_text (selection_data, str, -1);
7319           g_free (str);
7320         }
7321     }
7322 }
7323
7324 static void
7325 gtk_text_view_drag_data_delete (GtkWidget        *widget,
7326                                 GdkDragContext   *context)
7327 {
7328   gtk_text_buffer_delete_selection (GTK_TEXT_VIEW (widget)->priv->buffer,
7329                                     TRUE, GTK_TEXT_VIEW (widget)->priv->editable);
7330 }
7331
7332 static void
7333 gtk_text_view_drag_leave (GtkWidget        *widget,
7334                           GdkDragContext   *context,
7335                           guint             time)
7336 {
7337   GtkTextView *text_view;
7338   GtkTextViewPrivate *priv;
7339
7340   text_view = GTK_TEXT_VIEW (widget);
7341   priv = text_view->priv;
7342
7343   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7344
7345   if (priv->dnd_device)
7346     priv->dnd_device = NULL;
7347
7348   if (priv->scroll_timeout != 0)
7349     g_source_remove (priv->scroll_timeout);
7350
7351   priv->scroll_timeout = 0;
7352 }
7353
7354 static gboolean
7355 gtk_text_view_drag_motion (GtkWidget        *widget,
7356                            GdkDragContext   *context,
7357                            gint              x,
7358                            gint              y,
7359                            guint             time)
7360 {
7361   GtkTextIter newplace;
7362   GtkTextView *text_view;
7363   GtkTextViewPrivate *priv;
7364   GtkTextIter start;
7365   GtkTextIter end;
7366   GdkRectangle target_rect;
7367   gint bx, by;
7368   GdkAtom target;
7369   GdkDragAction suggested_action = 0;
7370   
7371   text_view = GTK_TEXT_VIEW (widget);
7372   priv = text_view->priv;
7373
7374   target_rect = priv->text_window->allocation;
7375   
7376   if (x < target_rect.x ||
7377       y < target_rect.y ||
7378       x > (target_rect.x + target_rect.width) ||
7379       y > (target_rect.y + target_rect.height))
7380     return FALSE; /* outside the text window, allow parent widgets to handle event */
7381
7382   gtk_text_view_window_to_buffer_coords (text_view,
7383                                          GTK_TEXT_WINDOW_WIDGET,
7384                                          x, y,
7385                                          &bx, &by);
7386
7387   gtk_text_layout_get_iter_at_pixel (priv->layout,
7388                                      &newplace,
7389                                      bx, by);  
7390
7391   target = gtk_drag_dest_find_target (widget, context,
7392                                       gtk_drag_dest_get_target_list (widget));
7393
7394   if (target == GDK_NONE)
7395     {
7396       /* can't accept any of the offered targets */
7397     }                                 
7398   else if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
7399                                                  &start, &end) &&
7400            gtk_text_iter_compare (&newplace, &start) >= 0 &&
7401            gtk_text_iter_compare (&newplace, &end) <= 0)
7402     {
7403       /* We're inside the selection. */
7404     }
7405   else
7406     {      
7407       if (gtk_text_iter_can_insert (&newplace, priv->editable))
7408         {
7409           GtkWidget *source_widget;
7410           
7411           suggested_action = gdk_drag_context_get_suggested_action (context);
7412           
7413           source_widget = gtk_drag_get_source_widget (context);
7414           
7415           if (source_widget == widget)
7416             {
7417               /* Default to MOVE, unless the user has
7418                * pressed ctrl or alt to affect available actions
7419                */
7420               if ((gdk_drag_context_get_actions (context) & GDK_ACTION_MOVE) != 0)
7421                 suggested_action = GDK_ACTION_MOVE;
7422             }
7423         }
7424       else
7425         {
7426           /* Can't drop here. */
7427         }
7428     }
7429
7430   if (suggested_action != 0)
7431     {
7432       gtk_text_mark_set_visible (priv->dnd_mark,
7433                                  priv->cursor_visible);
7434       
7435       gdk_drag_status (context, suggested_action, time);
7436     }
7437   else
7438     {
7439       gdk_drag_status (context, 0, time);
7440       gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7441     }
7442
7443   priv->dnd_device = gdk_drag_context_get_device (context);
7444
7445   if (!priv->scroll_timeout)
7446     priv->scroll_timeout =
7447       gdk_threads_add_timeout (100, drag_scan_timeout, text_view);
7448
7449   /* TRUE return means don't propagate the drag motion to parent
7450    * widgets that may also be drop sites.
7451    */
7452   return TRUE;
7453 }
7454
7455 static gboolean
7456 gtk_text_view_drag_drop (GtkWidget        *widget,
7457                          GdkDragContext   *context,
7458                          gint              x,
7459                          gint              y,
7460                          guint             time)
7461 {
7462   GtkTextView *text_view;
7463   GtkTextViewPrivate *priv;
7464   GtkTextIter drop_point;
7465   GdkAtom target = GDK_NONE;
7466
7467   text_view = GTK_TEXT_VIEW (widget);
7468   priv = text_view->priv;
7469
7470   if (priv->scroll_timeout != 0)
7471     g_source_remove (priv->scroll_timeout);
7472
7473   priv->scroll_timeout = 0;
7474
7475   gtk_text_mark_set_visible (priv->dnd_mark, FALSE);
7476
7477   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
7478                                     &drop_point,
7479                                     priv->dnd_mark);
7480
7481   if (gtk_text_iter_can_insert (&drop_point, priv->editable))
7482     target = gtk_drag_dest_find_target (widget, context, NULL);
7483
7484   if (target != GDK_NONE)
7485     gtk_drag_get_data (widget, context, target, time);
7486   else
7487     gtk_drag_finish (context, FALSE, FALSE, time);
7488
7489   return TRUE;
7490 }
7491
7492 static void
7493 insert_text_data (GtkTextView      *text_view,
7494                   GtkTextIter      *drop_point,
7495                   GtkSelectionData *selection_data)
7496 {
7497   guchar *str;
7498
7499   str = gtk_selection_data_get_text (selection_data);
7500
7501   if (str)
7502     {
7503       if (!gtk_text_buffer_insert_interactive (get_buffer (text_view),
7504                                                drop_point, (gchar *) str, -1,
7505                                                text_view->priv->editable))
7506         {
7507           gtk_widget_error_bell (GTK_WIDGET (text_view));
7508         }
7509
7510       g_free (str);
7511     }
7512 }
7513
7514 static void
7515 gtk_text_view_drag_data_received (GtkWidget        *widget,
7516                                   GdkDragContext   *context,
7517                                   gint              x,
7518                                   gint              y,
7519                                   GtkSelectionData *selection_data,
7520                                   guint             info,
7521                                   guint             time)
7522 {
7523   GtkTextIter drop_point;
7524   GtkTextView *text_view;
7525   GtkTextViewPrivate *priv;
7526   gboolean success = FALSE;
7527   GtkTextBuffer *buffer = NULL;
7528
7529   text_view = GTK_TEXT_VIEW (widget);
7530   priv = text_view->priv;
7531
7532   if (!priv->dnd_mark)
7533     goto done;
7534
7535   buffer = get_buffer (text_view);
7536
7537   gtk_text_buffer_get_iter_at_mark (buffer,
7538                                     &drop_point,
7539                                     priv->dnd_mark);
7540   
7541   if (!gtk_text_iter_can_insert (&drop_point, priv->editable))
7542     goto done;
7543
7544   success = TRUE;
7545
7546   gtk_text_buffer_begin_user_action (buffer);
7547
7548   if (info == GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
7549     {
7550       GtkTextBuffer *src_buffer = NULL;
7551       GtkTextIter start, end;
7552       gboolean copy_tags = TRUE;
7553
7554       if (gtk_selection_data_get_length (selection_data) != sizeof (src_buffer))
7555         return;
7556
7557       memcpy (&src_buffer, gtk_selection_data_get_data (selection_data), sizeof (src_buffer));
7558
7559       if (src_buffer == NULL)
7560         return;
7561
7562       g_return_if_fail (GTK_IS_TEXT_BUFFER (src_buffer));
7563
7564       if (gtk_text_buffer_get_tag_table (src_buffer) !=
7565           gtk_text_buffer_get_tag_table (buffer))
7566         {
7567           /*  try to find a suitable rich text target instead  */
7568           GdkAtom *atoms;
7569           gint     n_atoms;
7570           GList   *list;
7571           GdkAtom  target = GDK_NONE;
7572
7573           copy_tags = FALSE;
7574
7575           atoms = gtk_text_buffer_get_deserialize_formats (buffer, &n_atoms);
7576
7577           for (list = gdk_drag_context_list_targets (context); list; list = g_list_next (list))
7578             {
7579               gint i;
7580
7581               for (i = 0; i < n_atoms; i++)
7582                 if (GUINT_TO_POINTER (atoms[i]) == list->data)
7583                   {
7584                     target = atoms[i];
7585                     break;
7586                   }
7587             }
7588
7589           g_free (atoms);
7590
7591           if (target != GDK_NONE)
7592             {
7593               gtk_drag_get_data (widget, context, target, time);
7594               gtk_text_buffer_end_user_action (buffer);
7595               return;
7596             }
7597         }
7598
7599       if (gtk_text_buffer_get_selection_bounds (src_buffer,
7600                                                 &start,
7601                                                 &end))
7602         {
7603           if (copy_tags)
7604             gtk_text_buffer_insert_range_interactive (buffer,
7605                                                       &drop_point,
7606                                                       &start,
7607                                                       &end,
7608                                                       priv->editable);
7609           else
7610             {
7611               gchar *str;
7612
7613               str = gtk_text_iter_get_visible_text (&start, &end);
7614               gtk_text_buffer_insert_interactive (buffer,
7615                                                   &drop_point, str, -1,
7616                                                   priv->editable);
7617               g_free (str);
7618             }
7619         }
7620     }
7621   else if (gtk_selection_data_get_length (selection_data) > 0 &&
7622            info == GTK_TEXT_BUFFER_TARGET_INFO_RICH_TEXT)
7623     {
7624       gboolean retval;
7625       GError *error = NULL;
7626
7627       retval = gtk_text_buffer_deserialize (buffer, buffer,
7628                                             gtk_selection_data_get_target (selection_data),
7629                                             &drop_point,
7630                                             (guint8 *) gtk_selection_data_get_data (selection_data),
7631                                             gtk_selection_data_get_length (selection_data),
7632                                             &error);
7633
7634       if (!retval)
7635         {
7636           g_warning ("error pasting: %s\n", error->message);
7637           g_clear_error (&error);
7638         }
7639     }
7640   else
7641     insert_text_data (text_view, &drop_point, selection_data);
7642
7643  done:
7644   gtk_drag_finish (context, success,
7645                    success && gdk_drag_context_get_selected_action (context) == GDK_ACTION_MOVE,
7646                    time);
7647
7648   if (success)
7649     {
7650       gtk_text_buffer_get_iter_at_mark (buffer,
7651                                         &drop_point,
7652                                         priv->dnd_mark);
7653       gtk_text_buffer_place_cursor (buffer, &drop_point);
7654
7655       gtk_text_buffer_end_user_action (buffer);
7656     }
7657 }
7658
7659 /**
7660  * gtk_text_view_get_hadjustment:
7661  * @text_view: a #GtkTextView
7662  *
7663  * Gets the horizontal-scrolling #GtkAdjustment.
7664  *
7665  * Returns: (transfer none): pointer to the horizontal #GtkAdjustment
7666  *
7667  * Since: 2.22
7668  *
7669  * Deprecated: 3.0: Use gtk_scrollable_get_hadjustment()
7670  **/
7671 GtkAdjustment*
7672 gtk_text_view_get_hadjustment (GtkTextView *text_view)
7673 {
7674   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7675
7676   return text_view->priv->hadjustment;
7677 }
7678
7679 static void
7680 gtk_text_view_set_hadjustment (GtkTextView   *text_view,
7681                                GtkAdjustment *adjustment)
7682 {
7683   GtkTextViewPrivate *priv = text_view->priv;
7684
7685   if (adjustment && priv->hadjustment == adjustment)
7686     return;
7687
7688   if (priv->hadjustment != NULL)
7689     {
7690       g_signal_handlers_disconnect_by_func (priv->hadjustment,
7691                                             gtk_text_view_value_changed,
7692                                             text_view);
7693       g_object_unref (priv->hadjustment);
7694     }
7695
7696   if (adjustment == NULL)
7697     adjustment = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7698
7699   g_signal_connect (adjustment, "value-changed",
7700                     G_CALLBACK (gtk_text_view_value_changed), text_view);
7701   priv->hadjustment = g_object_ref_sink (adjustment);
7702   gtk_text_view_set_hadjustment_values (text_view);
7703
7704   g_object_notify (G_OBJECT (text_view), "hadjustment");
7705 }
7706
7707 /**
7708  * gtk_text_view_get_vadjustment:
7709  * @text_view: a #GtkTextView
7710  *
7711  * Gets the vertical-scrolling #GtkAdjustment.
7712  *
7713  * Returns: (transfer none): pointer to the vertical #GtkAdjustment
7714  *
7715  * Since: 2.22
7716  *
7717  * Deprecated: 3.0: Use gtk_scrollable_get_vadjustment()
7718  **/
7719 GtkAdjustment*
7720 gtk_text_view_get_vadjustment (GtkTextView *text_view)
7721 {
7722   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
7723
7724   return text_view->priv->vadjustment;
7725 }
7726
7727 static void
7728 gtk_text_view_set_vadjustment (GtkTextView   *text_view,
7729                                GtkAdjustment *adjustment)
7730 {
7731   GtkTextViewPrivate *priv = text_view->priv;
7732
7733   if (adjustment && priv->vadjustment == adjustment)
7734     return;
7735
7736   if (priv->vadjustment != NULL)
7737     {
7738       g_signal_handlers_disconnect_by_func (priv->vadjustment,
7739                                             gtk_text_view_value_changed,
7740                                             text_view);
7741       g_object_unref (priv->vadjustment);
7742     }
7743
7744   if (adjustment == NULL)
7745     adjustment = gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7746
7747   g_signal_connect (adjustment, "value-changed",
7748                     G_CALLBACK (gtk_text_view_value_changed), text_view);
7749   priv->vadjustment = g_object_ref_sink (adjustment);
7750   gtk_text_view_set_vadjustment_values (text_view);
7751
7752   g_object_notify (G_OBJECT (text_view), "vadjustment");
7753 }
7754
7755 static void
7756 gtk_text_view_set_hadjustment_values (GtkTextView *text_view)
7757 {
7758   GtkTextViewPrivate *priv;
7759   gint screen_width;
7760   gdouble old_value;
7761   gdouble new_value;
7762   gdouble new_upper;
7763
7764   priv = text_view->priv;
7765
7766   screen_width = SCREEN_WIDTH (text_view);
7767   old_value = gtk_adjustment_get_value (priv->hadjustment);
7768   new_upper = MAX (screen_width, priv->width);
7769
7770   g_object_set (priv->hadjustment,
7771                 "lower", 0.0,
7772                 "upper", new_upper,
7773                 "page-size", (gdouble)screen_width,
7774                 "step-increment", screen_width * 0.1,
7775                 "page-increment", screen_width * 0.9,
7776                 NULL);
7777
7778   new_value = CLAMP (old_value, 0, new_upper - screen_width);
7779   if (new_value != old_value)
7780     gtk_adjustment_set_value (priv->hadjustment, new_value);
7781 }
7782
7783 static void
7784 gtk_text_view_set_vadjustment_values (GtkTextView *text_view)
7785 {
7786   GtkTextViewPrivate *priv;
7787   GtkTextIter first_para;
7788   gint screen_height;
7789   gint y;
7790   gdouble old_value;
7791   gdouble new_value;
7792   gdouble new_upper;
7793
7794   priv = text_view->priv;
7795
7796   screen_height = SCREEN_HEIGHT (text_view);
7797   old_value = gtk_adjustment_get_value (priv->vadjustment);
7798   new_upper = MAX (screen_height, priv->height);
7799
7800   g_object_set (priv->vadjustment,
7801                 "lower", 0.0,
7802                 "upper", new_upper,
7803                 "page-size", (gdouble)screen_height,
7804                 "step-increment", screen_height * 0.1,
7805                 "page-increment", screen_height * 0.9,
7806                 NULL);
7807
7808   /* Now adjust the value of the adjustment to keep the cursor at the
7809    * same place in the buffer */
7810   gtk_text_view_ensure_layout (text_view);
7811   gtk_text_view_get_first_para_iter (text_view, &first_para);
7812   gtk_text_layout_get_line_yrange (priv->layout, &first_para, &y, NULL);
7813
7814   y += priv->first_para_pixels;
7815
7816   new_value = CLAMP (y, 0, new_upper - screen_height);
7817   if (new_value != old_value)
7818     gtk_adjustment_set_value (priv->vadjustment, new_value);
7819  }
7820
7821
7822 /* FIXME this adjust_allocation is a big cut-and-paste from
7823  * GtkCList, needs to be some "official" way to do this
7824  * factored out.
7825  */
7826 typedef struct
7827 {
7828   GdkWindow *window;
7829   int dx;
7830   int dy;
7831 } ScrollData;
7832
7833 /* The window to which widget->window is relative */
7834 #define ALLOCATION_WINDOW(widget)               \
7835    (!gtk_widget_get_has_window (widget) ?                   \
7836     gtk_widget_get_window (widget) :                        \
7837     gdk_window_get_parent (gtk_widget_get_window (widget)))
7838
7839 static void
7840 adjust_allocation_recurse (GtkWidget *widget,
7841                            gpointer   data)
7842 {
7843   GtkAllocation allocation;
7844   ScrollData *scroll_data = data;
7845
7846   /* Need to really size allocate instead of just poking
7847    * into widget->allocation if the widget is not realized.
7848    * FIXME someone figure out why this was.
7849    */
7850   gtk_widget_get_allocation (widget, &allocation);
7851
7852   if (!gtk_widget_get_realized (widget))
7853     {
7854       if (gtk_widget_get_visible (widget))
7855         {
7856           GdkRectangle tmp_rectangle;
7857
7858           tmp_rectangle = allocation;
7859           tmp_rectangle.x += scroll_data->dx;
7860           tmp_rectangle.y += scroll_data->dy;
7861           
7862           gtk_widget_size_allocate (widget, &tmp_rectangle);
7863         }
7864     }
7865   else
7866     {
7867       if (ALLOCATION_WINDOW (widget) == scroll_data->window)
7868         {
7869           allocation.x += scroll_data->dx;
7870           allocation.y += scroll_data->dy;
7871           gtk_widget_set_allocation (widget, &allocation);
7872
7873           if (GTK_IS_CONTAINER (widget))
7874             gtk_container_forall (GTK_CONTAINER (widget),
7875                                   adjust_allocation_recurse,
7876                                   data);
7877         }
7878     }
7879 }
7880
7881 static void
7882 adjust_allocation (GtkWidget *widget,
7883                    int        dx,
7884                    int        dy)
7885 {
7886   ScrollData scroll_data;
7887
7888   if (gtk_widget_get_realized (widget))
7889     scroll_data.window = ALLOCATION_WINDOW (widget);
7890   else
7891     scroll_data.window = NULL;
7892     
7893   scroll_data.dx = dx;
7894   scroll_data.dy = dy;
7895   
7896   adjust_allocation_recurse (widget, &scroll_data);
7897 }
7898
7899 static void
7900 gtk_text_view_value_changed (GtkAdjustment *adjustment,
7901                              GtkTextView   *text_view)
7902 {
7903   GtkTextViewPrivate *priv;
7904   GtkTextIter iter;
7905   gint line_top;
7906   gint dx = 0;
7907   gint dy = 0;
7908
7909   priv = text_view->priv;
7910
7911   /* Note that we oddly call this function with adjustment == NULL
7912    * sometimes
7913    */
7914   
7915   priv->onscreen_validated = FALSE;
7916
7917   DV(g_print(">Scroll offset changed %s/%g, onscreen_validated = FALSE ("G_STRLOC")\n",
7918              adjustment == priv->hadjustment ? "hadjustment" : adjustment == priv->vadjustment ? "vadjustment" : "none",
7919              adjustment ? gtk_adjustment_get_value (adjustment) : 0.0));
7920   
7921   if (adjustment == priv->hadjustment)
7922     {
7923       dx = priv->xoffset - (gint)gtk_adjustment_get_value (adjustment);
7924       priv->xoffset = gtk_adjustment_get_value (adjustment);
7925
7926       /* If the change is due to a size change we need 
7927        * to invalidate the entire text window because there might be
7928        * right-aligned or centered text 
7929        */
7930       if (priv->width_changed)
7931         {
7932           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7933             gdk_window_invalidate_rect (priv->text_window->bin_window, NULL, FALSE);
7934           
7935           priv->width_changed = FALSE;
7936         }
7937     }
7938   else if (adjustment == priv->vadjustment)
7939     {
7940       dy = priv->yoffset - (gint)gtk_adjustment_get_value (adjustment);
7941       priv->yoffset = gtk_adjustment_get_value (adjustment);
7942
7943       if (priv->layout)
7944         {
7945           gtk_text_layout_get_line_at_y (priv->layout, &iter, gtk_adjustment_get_value (adjustment), &line_top);
7946
7947           gtk_text_buffer_move_mark (get_buffer (text_view), priv->first_para_mark, &iter);
7948
7949           priv->first_para_pixels = gtk_adjustment_get_value (adjustment) - line_top;
7950         }
7951     }
7952   
7953   if (dx != 0 || dy != 0)
7954     {
7955       GSList *tmp_list;
7956
7957       if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
7958         {
7959           if (dy != 0)
7960             {
7961               if (priv->left_window)
7962                 text_window_scroll (priv->left_window, 0, dy);
7963               if (priv->right_window)
7964                 text_window_scroll (priv->right_window, 0, dy);
7965             }
7966       
7967           if (dx != 0)
7968             {
7969               if (priv->top_window)
7970                 text_window_scroll (priv->top_window, dx, 0);
7971               if (priv->bottom_window)
7972                 text_window_scroll (priv->bottom_window, dx, 0);
7973             }
7974       
7975           /* It looks nicer to scroll the main area last, because
7976            * it takes a while, and making the side areas update
7977            * afterward emphasizes the slowness of scrolling the
7978            * main area.
7979            */
7980           text_window_scroll (priv->text_window, dx, dy);
7981         }
7982       
7983       /* Children are now "moved" in the text window, poke
7984        * into widget->allocation for each child
7985        */
7986       tmp_list = priv->children;
7987       while (tmp_list != NULL)
7988         {
7989           GtkTextViewChild *child = tmp_list->data;
7990           
7991           if (child->anchor)
7992             adjust_allocation (child->widget, dx, dy);
7993           
7994           tmp_list = g_slist_next (tmp_list);
7995         }
7996     }
7997
7998   /* This could result in invalidation, which would install the
7999    * first_validate_idle, which would validate onscreen;
8000    * but we're going to go ahead and validate here, so
8001    * first_validate_idle shouldn't have anything to do.
8002    */
8003   gtk_text_view_update_layout_width (text_view);
8004   
8005   /* We also update the IM spot location here, since the IM context
8006    * might do something that leads to validation.
8007    */
8008   gtk_text_view_update_im_spot_location (text_view);
8009
8010   /* note that validation of onscreen could invoke this function
8011    * recursively, by scrolling to maintain first_para, or in response
8012    * to updating the layout width, however there is no problem with
8013    * that, or shouldn't be.
8014    */
8015   gtk_text_view_validate_onscreen (text_view);
8016   
8017   /* If this got installed, get rid of it, it's just a waste of time. */
8018   if (priv->first_validate_idle != 0)
8019     {
8020       g_source_remove (priv->first_validate_idle);
8021       priv->first_validate_idle = 0;
8022     }
8023
8024   /* Finally we update the IM cursor location again, to ensure any
8025    * changes made by the validation are pushed through.
8026    */
8027   gtk_text_view_update_im_spot_location (text_view);
8028
8029   gtk_text_view_update_handles (text_view,
8030                                 _gtk_text_handle_get_mode (priv->text_handle));
8031
8032   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
8033 }
8034
8035 static void
8036 gtk_text_view_commit_handler (GtkIMContext  *context,
8037                               const gchar   *str,
8038                               GtkTextView   *text_view)
8039 {
8040   gtk_text_view_commit_text (text_view, str);
8041 }
8042
8043 static void
8044 gtk_text_view_commit_text (GtkTextView   *text_view,
8045                            const gchar   *str)
8046 {
8047   GtkTextViewPrivate *priv;
8048   gboolean had_selection;
8049
8050   priv = text_view->priv;
8051
8052   gtk_text_buffer_begin_user_action (get_buffer (text_view));
8053
8054   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8055                                                         NULL, NULL);
8056   
8057   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8058                                     priv->editable);
8059
8060   if (!strcmp (str, "\n"))
8061     {
8062       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
8063                                                          priv->editable))
8064         {
8065           gtk_widget_error_bell (GTK_WIDGET (text_view));
8066         }
8067     }
8068   else
8069     {
8070       if (!had_selection && priv->overwrite_mode)
8071         {
8072           GtkTextIter insert;
8073
8074           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8075                                             &insert,
8076                                             gtk_text_buffer_get_insert (get_buffer (text_view)));
8077           if (!gtk_text_iter_ends_line (&insert))
8078             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
8079         }
8080
8081       if (!gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
8082                                                          priv->editable))
8083         {
8084           gtk_widget_error_bell (GTK_WIDGET (text_view));
8085         }
8086     }
8087
8088   gtk_text_buffer_end_user_action (get_buffer (text_view));
8089
8090   gtk_text_view_set_virtual_cursor_pos (text_view, -1, -1);
8091   DV(g_print (G_STRLOC": scrolling onscreen\n"));
8092   gtk_text_view_scroll_mark_onscreen (text_view,
8093                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
8094 }
8095
8096 static void
8097 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
8098                                        GtkTextView  *text_view)
8099 {
8100   GtkTextViewPrivate *priv;
8101   gchar *str;
8102   PangoAttrList *attrs;
8103   gint cursor_pos;
8104   GtkTextIter iter;
8105
8106   priv = text_view->priv;
8107
8108   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8109                                     gtk_text_buffer_get_insert (priv->buffer));
8110
8111   /* Keypress events are passed to input method even if cursor position is
8112    * not editable; so beep here if it's multi-key input sequence, input
8113    * method will be reset in key-press-event handler.
8114    */
8115   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
8116
8117   if (str && str[0] && !gtk_text_iter_can_insert (&iter, priv->editable))
8118     {
8119       gtk_widget_error_bell (GTK_WIDGET (text_view));
8120       goto out;
8121     }
8122
8123   g_signal_emit (text_view, signals[PREEDIT_CHANGED], 0, str);
8124
8125   if (priv->layout)
8126     gtk_text_layout_set_preedit_string (priv->layout, str, attrs, cursor_pos);
8127   if (gtk_widget_has_focus (GTK_WIDGET (text_view)))
8128     gtk_text_view_scroll_mark_onscreen (text_view,
8129                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8130
8131 out:
8132   pango_attr_list_unref (attrs);
8133   g_free (str);
8134 }
8135
8136 static gboolean
8137 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
8138                                             GtkTextView   *text_view)
8139 {
8140   GtkTextIter start;
8141   GtkTextIter end;
8142   gint pos;
8143   gchar *text;
8144
8145   gtk_text_buffer_get_iter_at_mark (text_view->priv->buffer, &start,
8146                                     gtk_text_buffer_get_insert (text_view->priv->buffer));
8147   end = start;
8148
8149   pos = gtk_text_iter_get_line_index (&start);
8150   gtk_text_iter_set_line_offset (&start, 0);
8151   gtk_text_iter_forward_to_line_end (&end);
8152
8153   text = gtk_text_iter_get_slice (&start, &end);
8154   gtk_im_context_set_surrounding (context, text, -1, pos);
8155   g_free (text);
8156
8157   return TRUE;
8158 }
8159
8160 static gboolean
8161 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
8162                                           gint           offset,
8163                                           gint           n_chars,
8164                                           GtkTextView   *text_view)
8165 {
8166   GtkTextViewPrivate *priv;
8167   GtkTextIter start;
8168   GtkTextIter end;
8169
8170   priv = text_view->priv;
8171
8172   gtk_text_buffer_get_iter_at_mark (priv->buffer, &start,
8173                                     gtk_text_buffer_get_insert (priv->buffer));
8174   end = start;
8175
8176   gtk_text_iter_forward_chars (&start, offset);
8177   gtk_text_iter_forward_chars (&end, offset + n_chars);
8178
8179   gtk_text_buffer_delete_interactive (priv->buffer, &start, &end,
8180                                       priv->editable);
8181
8182   return TRUE;
8183 }
8184
8185 static void
8186 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
8187                                 const GtkTextIter *location,
8188                                 GtkTextMark       *mark,
8189                                 gpointer           data)
8190 {
8191   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8192   gboolean need_reset = FALSE;
8193
8194   if (mark == gtk_text_buffer_get_insert (buffer))
8195     {
8196       text_view->priv->virtual_cursor_x = -1;
8197       text_view->priv->virtual_cursor_y = -1;
8198       gtk_text_view_update_im_spot_location (text_view);
8199       need_reset = TRUE;
8200     }
8201   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
8202     {
8203       need_reset = TRUE;
8204     }
8205
8206   if (need_reset)
8207     {
8208       gtk_text_view_reset_im_context (text_view);
8209       gtk_text_view_update_handles (text_view,
8210                                     _gtk_text_handle_get_mode (text_view->priv->text_handle));
8211     }
8212 }
8213
8214 static void
8215 gtk_text_view_target_list_notify (GtkTextBuffer    *buffer,
8216                                   const GParamSpec *pspec,
8217                                   gpointer          data)
8218 {
8219   GtkWidget     *widget = GTK_WIDGET (data);
8220   GtkTargetList *view_list;
8221   GtkTargetList *buffer_list;
8222   GList         *list;
8223
8224   view_list = gtk_drag_dest_get_target_list (widget);
8225   buffer_list = gtk_text_buffer_get_paste_target_list (buffer);
8226
8227   if (view_list)
8228     gtk_target_list_ref (view_list);
8229   else
8230     view_list = gtk_target_list_new (NULL, 0);
8231
8232   list = view_list->list;
8233   while (list)
8234     {
8235       GtkTargetPair *pair = list->data;
8236
8237       list = g_list_next (list); /* get next element before removing */
8238
8239       if (pair->info >= GTK_TEXT_BUFFER_TARGET_INFO_TEXT &&
8240           pair->info <= GTK_TEXT_BUFFER_TARGET_INFO_BUFFER_CONTENTS)
8241         {
8242           gtk_target_list_remove (view_list, pair->target);
8243         }
8244     }
8245
8246   for (list = buffer_list->list; list; list = g_list_next (list))
8247     {
8248       GtkTargetPair *pair = list->data;
8249
8250       gtk_target_list_add (view_list, pair->target, pair->flags, pair->info);
8251     }
8252
8253   gtk_drag_dest_set_target_list (widget, view_list);
8254   gtk_target_list_unref (view_list);
8255 }
8256
8257 static void
8258 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
8259                                       GtkTextIter *cursor,
8260                                       gint        *x,
8261                                       gint        *y)
8262 {
8263   GtkTextViewPrivate *priv;
8264   GtkTextIter insert;
8265   GdkRectangle pos;
8266
8267   priv = text_view->priv;
8268
8269   if (cursor)
8270     insert = *cursor;
8271   else
8272     gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
8273                                       gtk_text_buffer_get_insert (get_buffer (text_view)));
8274
8275   if ((x && priv->virtual_cursor_x == -1) ||
8276       (y && priv->virtual_cursor_y == -1))
8277     gtk_text_layout_get_cursor_locations (priv->layout, &insert, &pos, NULL);
8278
8279   if (x)
8280     {
8281       if (priv->virtual_cursor_x != -1)
8282         *x = priv->virtual_cursor_x;
8283       else
8284         *x = pos.x;
8285     }
8286
8287   if (y)
8288     {
8289       if (priv->virtual_cursor_x != -1)
8290         *y = priv->virtual_cursor_y;
8291       else
8292         *y = pos.y + pos.height / 2;
8293     }
8294 }
8295
8296 static void
8297 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
8298                                       gint         x,
8299                                       gint         y)
8300 {
8301   GdkRectangle pos;
8302
8303   if (!text_view->priv->layout)
8304     return;
8305
8306   if (x == -1 || y == -1)
8307     gtk_text_view_get_cursor_locations (text_view, NULL, &pos, NULL);
8308
8309   text_view->priv->virtual_cursor_x = (x == -1) ? pos.x : x;
8310   text_view->priv->virtual_cursor_y = (y == -1) ? pos.y + pos.height / 2 : y;
8311 }
8312
8313 /* Quick hack of a popup menu
8314  */
8315 static void
8316 activate_cb (GtkWidget   *menuitem,
8317              GtkTextView *text_view)
8318 {
8319   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
8320   g_signal_emit_by_name (text_view, signal);
8321 }
8322
8323 static void
8324 append_action_signal (GtkTextView  *text_view,
8325                       GtkWidget    *menu,
8326                       const gchar  *stock_id,
8327                       const gchar  *signal,
8328                       gboolean      sensitive)
8329 {
8330   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
8331
8332   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
8333   g_signal_connect (menuitem, "activate",
8334                     G_CALLBACK (activate_cb), text_view);
8335
8336   gtk_widget_set_sensitive (menuitem, sensitive);
8337   
8338   gtk_widget_show (menuitem);
8339   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
8340 }
8341
8342 static void
8343 gtk_text_view_select_all (GtkWidget *widget,
8344                           gboolean select)
8345 {
8346   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
8347   GtkTextBuffer *buffer;
8348   GtkTextIter start_iter, end_iter, insert;
8349
8350   buffer = text_view->priv->buffer;
8351   if (select) 
8352     {
8353       gtk_text_buffer_get_bounds (buffer, &start_iter, &end_iter);
8354       gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
8355     }
8356   else 
8357     {
8358       gtk_text_buffer_get_iter_at_mark (buffer, &insert,
8359                                         gtk_text_buffer_get_insert (buffer));
8360       gtk_text_buffer_move_mark_by_name (buffer, "selection_bound", &insert);
8361     }
8362 }
8363
8364 static void
8365 select_all_cb (GtkWidget   *menuitem,
8366                GtkTextView *text_view)
8367 {
8368   gtk_text_view_select_all (GTK_WIDGET (text_view), TRUE);
8369 }
8370
8371 static void
8372 delete_cb (GtkTextView *text_view)
8373 {
8374   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
8375                                     text_view->priv->editable);
8376 }
8377
8378 static void
8379 popup_menu_detach (GtkWidget *attach_widget,
8380                    GtkMenu   *menu)
8381 {
8382   GTK_TEXT_VIEW (attach_widget)->priv->popup_menu = NULL;
8383 }
8384
8385 static void
8386 popup_position_func (GtkMenu   *menu,
8387                      gint      *x,
8388                      gint      *y,
8389                      gboolean  *push_in,
8390                      gpointer   user_data)
8391 {
8392   GtkAllocation allocation;
8393   GtkTextView *text_view;
8394   GtkWidget *widget;
8395   GdkRectangle cursor_rect;
8396   GdkRectangle onscreen_rect;
8397   gint root_x, root_y;
8398   GtkTextIter iter;
8399   GtkRequisition req;      
8400   GdkScreen *screen;
8401   gint monitor_num;
8402   GdkRectangle monitor;
8403       
8404   text_view = GTK_TEXT_VIEW (user_data);
8405   widget = GTK_WIDGET (text_view);
8406   
8407   g_return_if_fail (gtk_widget_get_realized (widget));
8408   
8409   screen = gtk_widget_get_screen (widget);
8410
8411   gdk_window_get_origin (gtk_widget_get_window (widget),
8412                          &root_x, &root_y);
8413
8414   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8415                                     &iter,
8416                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
8417
8418   gtk_text_view_get_iter_location (text_view,
8419                                    &iter,
8420                                    &cursor_rect);
8421
8422   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
8423
8424   gtk_widget_get_preferred_size (text_view->priv->popup_menu,
8425                                  &req, NULL);
8426
8427   gtk_widget_get_allocation (widget, &allocation);
8428
8429   /* can't use rectangle_intersect since cursor rect can have 0 width */
8430   if (cursor_rect.x >= onscreen_rect.x &&
8431       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
8432       cursor_rect.y >= onscreen_rect.y &&
8433       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
8434     {    
8435       gtk_text_view_buffer_to_window_coords (text_view,
8436                                              GTK_TEXT_WINDOW_WIDGET,
8437                                              cursor_rect.x, cursor_rect.y,
8438                                              &cursor_rect.x, &cursor_rect.y);
8439
8440       *x = root_x + cursor_rect.x + cursor_rect.width;
8441       *y = root_y + cursor_rect.y + cursor_rect.height;
8442     }
8443   else
8444     {
8445       /* Just center the menu, since cursor is offscreen. */
8446       *x = root_x + (allocation.width / 2 - req.width / 2);
8447       *y = root_y + (allocation.height / 2 - req.height / 2);
8448     }
8449
8450   /* Ensure sanity */
8451   *x = CLAMP (*x, root_x, (root_x + allocation.width));
8452   *y = CLAMP (*y, root_y, (root_y + allocation.height));
8453
8454   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
8455   gtk_menu_set_monitor (menu, monitor_num);
8456   gdk_screen_get_monitor_workarea (screen, monitor_num, &monitor);
8457
8458   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
8459   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
8460
8461   *push_in = FALSE;
8462 }
8463
8464 typedef struct
8465 {
8466   GtkTextView *text_view;
8467   gint button;
8468   guint time;
8469   GdkDevice *device;
8470 } PopupInfo;
8471
8472 static gboolean
8473 range_contains_editable_text (const GtkTextIter *start,
8474                               const GtkTextIter *end,
8475                               gboolean default_editability)
8476 {
8477   GtkTextIter iter = *start;
8478
8479   while (gtk_text_iter_compare (&iter, end) < 0)
8480     {
8481       if (gtk_text_iter_editable (&iter, default_editability))
8482         return TRUE;
8483       
8484       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
8485     }
8486
8487   return FALSE;
8488 }                             
8489
8490 static void
8491 unichar_chosen_func (const char *text,
8492                      gpointer    data)
8493 {
8494   GtkTextView *text_view = GTK_TEXT_VIEW (data);
8495
8496   gtk_text_view_commit_text (text_view, text);
8497 }
8498
8499 static void
8500 popup_targets_received (GtkClipboard     *clipboard,
8501                         GtkSelectionData *data,
8502                         gpointer          user_data)
8503 {
8504   PopupInfo *info = user_data;
8505   GtkTextView *text_view;
8506   GtkTextViewPrivate *priv;
8507
8508   text_view = info->text_view;
8509   priv = text_view->priv;
8510
8511   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
8512     {
8513       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
8514        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
8515        */
8516       gboolean clipboard_contains_text;
8517       GtkWidget *menuitem;
8518       GtkWidget *submenu;
8519       gboolean have_selection;
8520       gboolean can_insert;
8521       GtkTextIter iter;
8522       GtkTextIter sel_start, sel_end;
8523       gboolean show_input_method_menu;
8524       gboolean show_unicode_menu;
8525       
8526       clipboard_contains_text = gtk_selection_data_targets_include_text (data);
8527
8528       if (priv->popup_menu)
8529         gtk_widget_destroy (priv->popup_menu);
8530
8531       priv->popup_menu = gtk_menu_new ();
8532       
8533       gtk_menu_attach_to_widget (GTK_MENU (priv->popup_menu),
8534                                  GTK_WIDGET (text_view),
8535                                  popup_menu_detach);
8536       
8537       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
8538                                                              &sel_start, &sel_end);
8539       
8540       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
8541                                         &iter,
8542                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
8543       
8544       can_insert = gtk_text_iter_can_insert (&iter, priv->editable);
8545       
8546       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_CUT, "cut-clipboard",
8547                             have_selection &&
8548                             range_contains_editable_text (&sel_start, &sel_end,
8549                                                           priv->editable));
8550       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_COPY, "copy-clipboard",
8551                             have_selection);
8552       append_action_signal (text_view, priv->popup_menu, GTK_STOCK_PASTE, "paste-clipboard",
8553                             can_insert && clipboard_contains_text);
8554       
8555       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
8556       gtk_widget_set_sensitive (menuitem, 
8557                                 have_selection &&
8558                                 range_contains_editable_text (&sel_start, &sel_end,
8559                                                               priv->editable));
8560       g_signal_connect_swapped (menuitem, "activate",
8561                                 G_CALLBACK (delete_cb), text_view);
8562       gtk_widget_show (menuitem);
8563       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8564
8565       menuitem = gtk_separator_menu_item_new ();
8566       gtk_widget_show (menuitem);
8567       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8568
8569       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
8570       gtk_widget_set_sensitive (menuitem,
8571                                 gtk_text_buffer_get_char_count (priv->buffer) > 0);
8572       g_signal_connect (menuitem, "activate",
8573                         G_CALLBACK (select_all_cb), text_view);
8574       gtk_widget_show (menuitem);
8575       gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8576
8577       g_object_get (gtk_widget_get_settings (GTK_WIDGET (text_view)),
8578                     "gtk-show-input-method-menu", &show_input_method_menu,
8579                     "gtk-show-unicode-menu", &show_unicode_menu,
8580                     NULL);
8581       
8582       if (show_input_method_menu || show_unicode_menu)
8583         {
8584           menuitem = gtk_separator_menu_item_new ();
8585           gtk_widget_show (menuitem);
8586           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8587         }
8588
8589       if (show_input_method_menu)
8590         {
8591           menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
8592           gtk_widget_show (menuitem);
8593           gtk_widget_set_sensitive (menuitem, can_insert);
8594
8595           submenu = gtk_menu_new ();
8596           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8597           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8598           
8599           gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (priv->im_context),
8600                                                 GTK_MENU_SHELL (submenu));
8601         }
8602
8603       if (show_unicode_menu)
8604         {
8605           menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
8606           gtk_widget_show (menuitem);
8607           gtk_widget_set_sensitive (menuitem, can_insert);
8608       
8609           submenu = gtk_menu_new ();
8610           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
8611           gtk_menu_shell_append (GTK_MENU_SHELL (priv->popup_menu), menuitem);
8612           
8613           _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
8614                                                         unichar_chosen_func,
8615                                                         text_view);
8616         }
8617           
8618       g_signal_emit (text_view,
8619                      signals[POPULATE_POPUP],
8620                      0,
8621                      priv->popup_menu);
8622       
8623       if (info->device)
8624         gtk_menu_popup_for_device (GTK_MENU (priv->popup_menu), 
8625       info->device, NULL, NULL, NULL, NULL, NULL,
8626                         info->button, info->time);
8627       else
8628         {
8629           gtk_menu_popup (GTK_MENU (priv->popup_menu), NULL, NULL,
8630                           popup_position_func, text_view,
8631                           0, gtk_get_current_event_time ());
8632           gtk_menu_shell_select_first (GTK_MENU_SHELL (priv->popup_menu), FALSE);
8633         }
8634     }
8635
8636   g_object_unref (text_view);
8637   g_free (info);
8638 }
8639
8640 static void
8641 gtk_text_view_do_popup (GtkTextView    *text_view,
8642                         GdkEventButton *event)
8643 {
8644   PopupInfo *info = g_new (PopupInfo, 1);
8645
8646   /* In order to know what entries we should make sensitive, we
8647    * ask for the current targets of the clipboard, and when
8648    * we get them, then we actually pop up the menu.
8649    */
8650   info->text_view = g_object_ref (text_view);
8651   
8652   if (event)
8653     {
8654       info->button = event->button;
8655       info->time = event->time;
8656       info->device = event->device;
8657     }
8658   else
8659     {
8660       info->button = 0;
8661       info->time = gtk_get_current_event_time ();
8662       info->device = NULL;
8663     }
8664
8665   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
8666                                                             GDK_SELECTION_CLIPBOARD),
8667                                   gdk_atom_intern_static_string ("TARGETS"),
8668                                   popup_targets_received,
8669                                   info);
8670 }
8671
8672 static gboolean
8673 gtk_text_view_popup_menu (GtkWidget *widget)
8674 {
8675   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
8676   return TRUE;
8677 }
8678
8679 /* Child GdkWindows */
8680
8681
8682 static GtkTextWindow*
8683 text_window_new (GtkTextWindowType  type,
8684                  GtkWidget         *widget,
8685                  gint               width_request,
8686                  gint               height_request)
8687 {
8688   GtkTextWindow *win;
8689
8690   win = g_new (GtkTextWindow, 1);
8691
8692   win->type = type;
8693   win->widget = widget;
8694   win->window = NULL;
8695   win->bin_window = NULL;
8696   win->requisition.width = width_request;
8697   win->requisition.height = height_request;
8698   win->allocation.width = width_request;
8699   win->allocation.height = height_request;
8700   win->allocation.x = 0;
8701   win->allocation.y = 0;
8702
8703   return win;
8704 }
8705
8706 static void
8707 text_window_free (GtkTextWindow *win)
8708 {
8709   if (win->window)
8710     text_window_unrealize (win);
8711
8712   g_free (win);
8713 }
8714
8715 static void
8716 text_window_realize (GtkTextWindow *win,
8717                      GtkWidget     *widget)
8718 {
8719   GtkStyleContext *context;
8720   GtkStateFlags state;
8721   GdkWindow *window;
8722   GdkWindowAttr attributes;
8723   gint attributes_mask;
8724   GdkCursor *cursor;
8725   GdkRGBA color;
8726
8727   attributes.window_type = GDK_WINDOW_CHILD;
8728   attributes.x = win->allocation.x;
8729   attributes.y = win->allocation.y;
8730   attributes.width = win->allocation.width;
8731   attributes.height = win->allocation.height;
8732   attributes.wclass = GDK_INPUT_OUTPUT;
8733   attributes.visual = gtk_widget_get_visual (win->widget);
8734   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
8735
8736   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
8737
8738   window = gtk_widget_get_window (widget);
8739
8740   win->window = gdk_window_new (window,
8741                                 &attributes, attributes_mask);
8742
8743   gdk_window_show (win->window);
8744   gdk_window_set_user_data (win->window, win->widget);
8745   gdk_window_lower (win->window);
8746
8747   attributes.x = 0;
8748   attributes.y = 0;
8749   attributes.width = win->allocation.width;
8750   attributes.height = win->allocation.height;
8751   attributes.event_mask = (GDK_EXPOSURE_MASK            |
8752                            GDK_SCROLL_MASK              |
8753                            GDK_SMOOTH_SCROLL_MASK       |
8754                            GDK_KEY_PRESS_MASK           |
8755                            GDK_BUTTON_PRESS_MASK        |
8756                            GDK_BUTTON_RELEASE_MASK      |
8757                            GDK_POINTER_MOTION_MASK      |
8758                            GDK_POINTER_MOTION_HINT_MASK |
8759                            gtk_widget_get_events (win->widget));
8760
8761   win->bin_window = gdk_window_new (win->window,
8762                                     &attributes,
8763                                     attributes_mask);
8764
8765   gdk_window_show (win->bin_window);
8766   gdk_window_set_user_data (win->bin_window, win->widget);
8767
8768   context = gtk_widget_get_style_context (widget);
8769   state = gtk_widget_get_state_flags (widget);
8770
8771   if (win->type == GTK_TEXT_WINDOW_TEXT)
8772     {
8773       if (gtk_widget_is_sensitive (widget))
8774         {
8775           /* I-beam cursor */
8776           cursor = gdk_cursor_new_for_display (gdk_window_get_display (window),
8777                                                GDK_XTERM);
8778           gdk_window_set_cursor (win->bin_window, cursor);
8779           g_object_unref (cursor);
8780         } 
8781
8782       gtk_im_context_set_client_window (GTK_TEXT_VIEW (widget)->priv->im_context,
8783                                         win->window);
8784
8785       gtk_style_context_save (context);
8786       gtk_style_context_add_class (context, GTK_STYLE_CLASS_VIEW);
8787
8788       gtk_style_context_get_background_color (context, state, &color);
8789       gdk_window_set_background_rgba (win->bin_window, &color);
8790
8791       gtk_style_context_restore (context);
8792     }
8793   else
8794     {
8795       gtk_style_context_get_background_color (context, state, &color);
8796       gdk_window_set_background_rgba (win->bin_window, &color);
8797     }
8798
8799   g_object_set_qdata (G_OBJECT (win->window),
8800                       g_quark_from_static_string ("gtk-text-view-text-window"),
8801                       win);
8802
8803   g_object_set_qdata (G_OBJECT (win->bin_window),
8804                       g_quark_from_static_string ("gtk-text-view-text-window"),
8805                       win);
8806 }
8807
8808 static void
8809 text_window_unrealize (GtkTextWindow *win)
8810 {
8811   if (win->type == GTK_TEXT_WINDOW_TEXT)
8812     {
8813       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->priv->im_context,
8814                                         NULL);
8815     }
8816
8817   gdk_window_set_user_data (win->window, NULL);
8818   gdk_window_set_user_data (win->bin_window, NULL);
8819   gdk_window_destroy (win->bin_window);
8820   gdk_window_destroy (win->window);
8821   win->window = NULL;
8822   win->bin_window = NULL;
8823 }
8824
8825 static void
8826 text_window_size_allocate (GtkTextWindow *win,
8827                            GdkRectangle  *rect)
8828 {
8829   win->allocation = *rect;
8830
8831   if (win->window)
8832     {
8833       gdk_window_move_resize (win->window,
8834                               rect->x, rect->y,
8835                               rect->width, rect->height);
8836
8837       gdk_window_resize (win->bin_window,
8838                          rect->width, rect->height);
8839     }
8840 }
8841
8842 static void
8843 text_window_scroll        (GtkTextWindow *win,
8844                            gint           dx,
8845                            gint           dy)
8846 {
8847   if (dx != 0 || dy != 0)
8848     {
8849       gdk_window_scroll (win->bin_window, dx, dy);
8850     }
8851 }
8852
8853 static void
8854 text_window_invalidate_rect (GtkTextWindow *win,
8855                              GdkRectangle  *rect)
8856 {
8857   GdkRectangle window_rect;
8858
8859   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
8860                                          win->type,
8861                                          rect->x,
8862                                          rect->y,
8863                                          &window_rect.x,
8864                                          &window_rect.y);
8865
8866   window_rect.width = rect->width;
8867   window_rect.height = rect->height;
8868   
8869   /* Adjust the rect as appropriate */
8870   
8871   switch (win->type)
8872     {
8873     case GTK_TEXT_WINDOW_TEXT:
8874       break;
8875
8876     case GTK_TEXT_WINDOW_LEFT:
8877     case GTK_TEXT_WINDOW_RIGHT:
8878       window_rect.x = 0;
8879       window_rect.width = win->allocation.width;
8880       break;
8881
8882     case GTK_TEXT_WINDOW_TOP:
8883     case GTK_TEXT_WINDOW_BOTTOM:
8884       window_rect.y = 0;
8885       window_rect.height = win->allocation.height;
8886       break;
8887
8888     default:
8889       g_warning ("%s: bug!", G_STRFUNC);
8890       return;
8891       break;
8892     }
8893           
8894   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
8895
8896 #if 0
8897   {
8898     cairo_t *cr = gdk_cairo_create (win->bin_window);
8899     gdk_cairo_rectangle (cr, &window_rect);
8900     cairo_set_source_rgb  (cr, 1.0, 0.0, 0.0);  /* red */
8901     cairo_fill (cr);
8902     cairo_destroy (cr);
8903   }
8904 #endif
8905 }
8906
8907 static void
8908 text_window_invalidate_cursors (GtkTextWindow *win)
8909 {
8910   GtkTextView *text_view;
8911   GtkTextViewPrivate *priv;
8912   GtkTextIter  iter;
8913   GdkRectangle strong;
8914   GdkRectangle weak;
8915   gboolean     draw_arrow;
8916   gfloat       cursor_aspect_ratio;
8917   gint         stem_width;
8918   gint         arrow_width;
8919
8920   text_view = GTK_TEXT_VIEW (win->widget);
8921   priv = text_view->priv;
8922
8923   gtk_text_buffer_get_iter_at_mark (priv->buffer, &iter,
8924                                     gtk_text_buffer_get_insert (priv->buffer));
8925
8926   if (_gtk_text_layout_get_block_cursor (priv->layout, &strong))
8927     {
8928       text_window_invalidate_rect (win, &strong);
8929       return;
8930     }
8931
8932   gtk_text_layout_get_cursor_locations (priv->layout, &iter,
8933                                         &strong, &weak);
8934
8935   /* cursor width calculation as in gtkstylecontext.c:draw_insertion_cursor(),
8936    * ignoring the text direction be exposing both sides of the cursor
8937    */
8938
8939   draw_arrow = (strong.x != weak.x || strong.y != weak.y);
8940
8941   gtk_widget_style_get (win->widget,
8942                         "cursor-aspect-ratio", &cursor_aspect_ratio,
8943                         NULL);
8944   
8945   stem_width = strong.height * cursor_aspect_ratio + 1;
8946   arrow_width = stem_width + 1;
8947
8948   strong.width = stem_width;
8949
8950   /* round up to the next even number */
8951   if (stem_width & 1)
8952     stem_width++;
8953
8954   strong.x     -= stem_width / 2;
8955   strong.width += stem_width;
8956
8957   if (draw_arrow)
8958     {
8959       strong.x     -= arrow_width;
8960       strong.width += arrow_width * 2;
8961     }
8962
8963   text_window_invalidate_rect (win, &strong);
8964
8965   if (draw_arrow) /* == have weak */
8966     {
8967       stem_width = weak.height * cursor_aspect_ratio + 1;
8968       arrow_width = stem_width + 1;
8969
8970       weak.width = stem_width;
8971
8972       /* round up to the next even number */
8973       if (stem_width & 1)
8974         stem_width++;
8975
8976       weak.x     -= stem_width / 2;
8977       weak.width += stem_width;
8978
8979       weak.x     -= arrow_width;
8980       weak.width += arrow_width * 2;
8981
8982       text_window_invalidate_rect (win, &weak);
8983     }
8984 }
8985
8986 static gint
8987 text_window_get_width (GtkTextWindow *win)
8988 {
8989   return win->allocation.width;
8990 }
8991
8992 static gint
8993 text_window_get_height (GtkTextWindow *win)
8994 {
8995   return win->allocation.height;
8996 }
8997
8998 /* Windows */
8999
9000
9001 /**
9002  * gtk_text_view_get_window:
9003  * @text_view: a #GtkTextView
9004  * @win: window to get
9005  *
9006  * Retrieves the #GdkWindow corresponding to an area of the text view;
9007  * possible windows include the overall widget window, child windows
9008  * on the left, right, top, bottom, and the window that displays the
9009  * text buffer. Windows are %NULL and nonexistent if their width or
9010  * height is 0, and are nonexistent before the widget has been
9011  * realized.
9012  *
9013  * Return value: (transfer none): a #GdkWindow, or %NULL
9014  **/
9015 GdkWindow*
9016 gtk_text_view_get_window (GtkTextView *text_view,
9017                           GtkTextWindowType win)
9018 {
9019   GtkTextViewPrivate *priv = text_view->priv;
9020
9021   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
9022
9023   switch (win)
9024     {
9025     case GTK_TEXT_WINDOW_WIDGET:
9026       return gtk_widget_get_window (GTK_WIDGET (text_view));
9027       break;
9028
9029     case GTK_TEXT_WINDOW_TEXT:
9030       return priv->text_window->bin_window;
9031       break;
9032
9033     case GTK_TEXT_WINDOW_LEFT:
9034       if (priv->left_window)
9035         return priv->left_window->bin_window;
9036       else
9037         return NULL;
9038       break;
9039
9040     case GTK_TEXT_WINDOW_RIGHT:
9041       if (priv->right_window)
9042         return priv->right_window->bin_window;
9043       else
9044         return NULL;
9045       break;
9046
9047     case GTK_TEXT_WINDOW_TOP:
9048       if (priv->top_window)
9049         return priv->top_window->bin_window;
9050       else
9051         return NULL;
9052       break;
9053
9054     case GTK_TEXT_WINDOW_BOTTOM:
9055       if (priv->bottom_window)
9056         return priv->bottom_window->bin_window;
9057       else
9058         return NULL;
9059       break;
9060
9061     case GTK_TEXT_WINDOW_PRIVATE:
9062       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_STRFUNC);
9063       return NULL;
9064       break;
9065     }
9066
9067   g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9068   return NULL;
9069 }
9070
9071 /**
9072  * gtk_text_view_get_window_type:
9073  * @text_view: a #GtkTextView
9074  * @window: a window type
9075  *
9076  * Usually used to find out which window an event corresponds to.
9077  * If you connect to an event signal on @text_view, this function
9078  * should be called on <literal>event-&gt;window</literal> to
9079  * see which window it was.
9080  *
9081  * Return value: the window type.
9082  **/
9083 GtkTextWindowType
9084 gtk_text_view_get_window_type (GtkTextView *text_view,
9085                                GdkWindow   *window)
9086 {
9087   GtkTextWindow *win;
9088
9089   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9090   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
9091
9092   if (window == gtk_widget_get_window (GTK_WIDGET (text_view)))
9093     return GTK_TEXT_WINDOW_WIDGET;
9094
9095   win = g_object_get_qdata (G_OBJECT (window),
9096                             g_quark_try_string ("gtk-text-view-text-window"));
9097
9098   if (win)
9099     return win->type;
9100   else
9101     {
9102       return GTK_TEXT_WINDOW_PRIVATE;
9103     }
9104 }
9105
9106 static void
9107 buffer_to_widget (GtkTextView      *text_view,
9108                   gint              buffer_x,
9109                   gint              buffer_y,
9110                   gint             *window_x,
9111                   gint             *window_y)
9112 {
9113   GtkTextViewPrivate *priv = text_view->priv;
9114
9115   if (window_x)
9116     {
9117       *window_x = buffer_x - priv->xoffset;
9118       *window_x += priv->text_window->allocation.x;
9119     }
9120
9121   if (window_y)
9122     {
9123       *window_y = buffer_y - priv->yoffset;
9124       *window_y += priv->text_window->allocation.y;
9125     }
9126 }
9127
9128 static void
9129 widget_to_text_window (GtkTextWindow *win,
9130                        gint           widget_x,
9131                        gint           widget_y,
9132                        gint          *window_x,
9133                        gint          *window_y)
9134 {
9135   if (window_x)
9136     *window_x = widget_x - win->allocation.x;
9137
9138   if (window_y)
9139     *window_y = widget_y - win->allocation.y;
9140 }
9141
9142 static void
9143 buffer_to_text_window (GtkTextView   *text_view,
9144                        GtkTextWindow *win,
9145                        gint           buffer_x,
9146                        gint           buffer_y,
9147                        gint          *window_x,
9148                        gint          *window_y)
9149 {
9150   if (win == NULL)
9151     {
9152       g_warning ("Attempt to convert text buffer coordinates to coordinates "
9153                  "for a nonexistent or private child window of GtkTextView");
9154       return;
9155     }
9156
9157   buffer_to_widget (text_view,
9158                     buffer_x, buffer_y,
9159                     window_x, window_y);
9160
9161   widget_to_text_window (win,
9162                          window_x ? *window_x : 0,
9163                          window_y ? *window_y : 0,
9164                          window_x,
9165                          window_y);
9166 }
9167
9168 /**
9169  * gtk_text_view_buffer_to_window_coords:
9170  * @text_view: a #GtkTextView
9171  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
9172  * @buffer_x: buffer x coordinate
9173  * @buffer_y: buffer y coordinate
9174  * @window_x: (out) (allow-none): window x coordinate return location or %NULL
9175  * @window_y: (out) (allow-none): window y coordinate return location or %NULL
9176  *
9177  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
9178  * @win, and stores the result in (@window_x, @window_y). 
9179  *
9180  * Note that you can't convert coordinates for a nonexisting window (see 
9181  * gtk_text_view_set_border_window_size()).
9182  **/
9183 void
9184 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
9185                                        GtkTextWindowType win,
9186                                        gint              buffer_x,
9187                                        gint              buffer_y,
9188                                        gint             *window_x,
9189                                        gint             *window_y)
9190 {
9191   GtkTextViewPrivate *priv = text_view->priv;
9192
9193   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9194
9195   switch (win)
9196     {
9197     case GTK_TEXT_WINDOW_WIDGET:
9198       buffer_to_widget (text_view,
9199                         buffer_x, buffer_y,
9200                         window_x, window_y);
9201       break;
9202
9203     case GTK_TEXT_WINDOW_TEXT:
9204       if (window_x)
9205         *window_x = buffer_x - priv->xoffset;
9206       if (window_y)
9207         *window_y = buffer_y - priv->yoffset;
9208       break;
9209
9210     case GTK_TEXT_WINDOW_LEFT:
9211       buffer_to_text_window (text_view,
9212                              priv->left_window,
9213                              buffer_x, buffer_y,
9214                              window_x, window_y);
9215       break;
9216
9217     case GTK_TEXT_WINDOW_RIGHT:
9218       buffer_to_text_window (text_view,
9219                              priv->right_window,
9220                              buffer_x, buffer_y,
9221                              window_x, window_y);
9222       break;
9223
9224     case GTK_TEXT_WINDOW_TOP:
9225       buffer_to_text_window (text_view,
9226                              priv->top_window,
9227                              buffer_x, buffer_y,
9228                              window_x, window_y);
9229       break;
9230
9231     case GTK_TEXT_WINDOW_BOTTOM:
9232       buffer_to_text_window (text_view,
9233                              priv->bottom_window,
9234                              buffer_x, buffer_y,
9235                              window_x, window_y);
9236       break;
9237
9238     case GTK_TEXT_WINDOW_PRIVATE:
9239       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9240       break;
9241
9242     default:
9243       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9244       break;
9245     }
9246 }
9247
9248 static void
9249 widget_to_buffer (GtkTextView *text_view,
9250                   gint         widget_x,
9251                   gint         widget_y,
9252                   gint        *buffer_x,
9253                   gint        *buffer_y)
9254 {
9255   GtkTextViewPrivate *priv = text_view->priv;
9256
9257   if (buffer_x)
9258     {
9259       *buffer_x = widget_x + priv->xoffset;
9260       *buffer_x -= priv->text_window->allocation.x;
9261     }
9262
9263   if (buffer_y)
9264     {
9265       *buffer_y = widget_y + priv->yoffset;
9266       *buffer_y -= priv->text_window->allocation.y;
9267     }
9268 }
9269
9270 static void
9271 text_window_to_widget (GtkTextWindow *win,
9272                        gint           window_x,
9273                        gint           window_y,
9274                        gint          *widget_x,
9275                        gint          *widget_y)
9276 {
9277   if (widget_x)
9278     *widget_x = window_x + win->allocation.x;
9279
9280   if (widget_y)
9281     *widget_y = window_y + win->allocation.y;
9282 }
9283
9284 static void
9285 text_window_to_buffer (GtkTextView   *text_view,
9286                        GtkTextWindow *win,
9287                        gint           window_x,
9288                        gint           window_y,
9289                        gint          *buffer_x,
9290                        gint          *buffer_y)
9291 {
9292   if (win == NULL)
9293     {
9294       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
9295                  "coordinates for a nonexistent child window.");
9296       return;
9297     }
9298
9299   text_window_to_widget (win,
9300                          window_x,
9301                          window_y,
9302                          buffer_x,
9303                          buffer_y);
9304
9305   widget_to_buffer (text_view,
9306                     buffer_x ? *buffer_x : 0,
9307                     buffer_y ? *buffer_y : 0,
9308                     buffer_x,
9309                     buffer_y);
9310 }
9311
9312 /**
9313  * gtk_text_view_window_to_buffer_coords:
9314  * @text_view: a #GtkTextView
9315  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
9316  * @window_x: window x coordinate
9317  * @window_y: window y coordinate
9318  * @buffer_x: (out) (allow-none): buffer x coordinate return location or %NULL
9319  * @buffer_y: (out) (allow-none): buffer y coordinate return location or %NULL
9320  *
9321  * Converts coordinates on the window identified by @win to buffer
9322  * coordinates, storing the result in (@buffer_x,@buffer_y).
9323  *
9324  * Note that you can't convert coordinates for a nonexisting window (see 
9325  * gtk_text_view_set_border_window_size()).
9326  **/
9327 void
9328 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
9329                                        GtkTextWindowType win,
9330                                        gint              window_x,
9331                                        gint              window_y,
9332                                        gint             *buffer_x,
9333                                        gint             *buffer_y)
9334 {
9335   GtkTextViewPrivate *priv = text_view->priv;
9336
9337   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9338
9339   switch (win)
9340     {
9341     case GTK_TEXT_WINDOW_WIDGET:
9342       widget_to_buffer (text_view,
9343                         window_x, window_y,
9344                         buffer_x, buffer_y);
9345       break;
9346
9347     case GTK_TEXT_WINDOW_TEXT:
9348       if (buffer_x)
9349         *buffer_x = window_x + priv->xoffset;
9350       if (buffer_y)
9351         *buffer_y = window_y + priv->yoffset;
9352       break;
9353
9354     case GTK_TEXT_WINDOW_LEFT:
9355       text_window_to_buffer (text_view,
9356                              priv->left_window,
9357                              window_x, window_y,
9358                              buffer_x, buffer_y);
9359       break;
9360
9361     case GTK_TEXT_WINDOW_RIGHT:
9362       text_window_to_buffer (text_view,
9363                              priv->right_window,
9364                              window_x, window_y,
9365                              buffer_x, buffer_y);
9366       break;
9367
9368     case GTK_TEXT_WINDOW_TOP:
9369       text_window_to_buffer (text_view,
9370                              priv->top_window,
9371                              window_x, window_y,
9372                              buffer_x, buffer_y);
9373       break;
9374
9375     case GTK_TEXT_WINDOW_BOTTOM:
9376       text_window_to_buffer (text_view,
9377                              priv->bottom_window,
9378                              window_x, window_y,
9379                              buffer_x, buffer_y);
9380       break;
9381
9382     case GTK_TEXT_WINDOW_PRIVATE:
9383       g_warning ("%s: can't get coords for private windows", G_STRFUNC);
9384       break;
9385
9386     default:
9387       g_warning ("%s: Unknown GtkTextWindowType", G_STRFUNC);
9388       break;
9389     }
9390 }
9391
9392 static void
9393 set_window_width (GtkTextView      *text_view,
9394                   gint              width,
9395                   GtkTextWindowType type,
9396                   GtkTextWindow   **winp)
9397 {
9398   if (width == 0)
9399     {
9400       if (*winp)
9401         {
9402           text_window_free (*winp);
9403           *winp = NULL;
9404           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9405         }
9406     }
9407   else
9408     {
9409       if (*winp == NULL)
9410         {
9411           *winp = text_window_new (type,
9412                                    GTK_WIDGET (text_view),
9413                                    width, 0);
9414           /* if the widget is already realized we need to realize the child manually */
9415           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9416             text_window_realize (*winp, GTK_WIDGET (text_view));
9417         }
9418       else
9419         {
9420           if ((*winp)->requisition.width == width)
9421             return;
9422
9423           (*winp)->requisition.width = width;
9424         }
9425
9426       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9427     }
9428 }
9429
9430
9431 static void
9432 set_window_height (GtkTextView      *text_view,
9433                    gint              height,
9434                    GtkTextWindowType type,
9435                    GtkTextWindow   **winp)
9436 {
9437   if (height == 0)
9438     {
9439       if (*winp)
9440         {
9441           text_window_free (*winp);
9442           *winp = NULL;
9443           gtk_widget_queue_resize (GTK_WIDGET (text_view));
9444         }
9445     }
9446   else
9447     {
9448       if (*winp == NULL)
9449         {
9450           *winp = text_window_new (type,
9451                                    GTK_WIDGET (text_view),
9452                                    0, height);
9453
9454           /* if the widget is already realized we need to realize the child manually */
9455           if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9456             text_window_realize (*winp, GTK_WIDGET (text_view));
9457         }
9458       else
9459         {
9460           if ((*winp)->requisition.height == height)
9461             return;
9462
9463           (*winp)->requisition.height = height;
9464         }
9465
9466       gtk_widget_queue_resize (GTK_WIDGET (text_view));
9467     }
9468 }
9469
9470 /**
9471  * gtk_text_view_set_border_window_size:
9472  * @text_view: a #GtkTextView
9473  * @type: window to affect
9474  * @size: width or height of the window
9475  *
9476  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
9477  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
9478  * Automatically destroys the corresponding window if the size is set
9479  * to 0, and creates the window if the size is set to non-zero.  This
9480  * function can only be used for the "border windows," it doesn't work
9481  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
9482  * #GTK_TEXT_WINDOW_PRIVATE.
9483  **/
9484 void
9485 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
9486                                       GtkTextWindowType type,
9487                                       gint              size)
9488 {
9489   GtkTextViewPrivate *priv = text_view->priv;
9490
9491   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9492   g_return_if_fail (size >= 0);
9493
9494   switch (type)
9495     {
9496     case GTK_TEXT_WINDOW_LEFT:
9497       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
9498                         &priv->left_window);
9499       break;
9500
9501     case GTK_TEXT_WINDOW_RIGHT:
9502       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
9503                         &priv->right_window);
9504       break;
9505
9506     case GTK_TEXT_WINDOW_TOP:
9507       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
9508                          &priv->top_window);
9509       break;
9510
9511     case GTK_TEXT_WINDOW_BOTTOM:
9512       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
9513                          &priv->bottom_window);
9514       break;
9515
9516     default:
9517       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
9518       break;
9519     }
9520 }
9521
9522 /**
9523  * gtk_text_view_get_border_window_size:
9524  * @text_view: a #GtkTextView
9525  * @type: window to return size from
9526  *
9527  * Gets the width of the specified border window. See
9528  * gtk_text_view_set_border_window_size().
9529  *
9530  * Return value: width of window
9531  **/
9532 gint
9533 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
9534                                       GtkTextWindowType  type)
9535 {
9536   GtkTextViewPrivate *priv = text_view->priv;
9537
9538   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
9539   
9540   switch (type)
9541     {
9542     case GTK_TEXT_WINDOW_LEFT:
9543       if (priv->left_window)
9544         return priv->left_window->requisition.width;
9545       break;
9546       
9547     case GTK_TEXT_WINDOW_RIGHT:
9548       if (priv->right_window)
9549         return priv->right_window->requisition.width;
9550       break;
9551       
9552     case GTK_TEXT_WINDOW_TOP:
9553       if (priv->top_window)
9554         return priv->top_window->requisition.height;
9555       break;
9556
9557     case GTK_TEXT_WINDOW_BOTTOM:
9558       if (priv->bottom_window)
9559         return priv->bottom_window->requisition.height;
9560       break;
9561       
9562     default:
9563       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
9564       break;
9565     }
9566
9567   return 0;
9568 }
9569
9570 /*
9571  * Child widgets
9572  */
9573
9574 static GtkTextViewChild*
9575 text_view_child_new_anchored (GtkWidget          *child,
9576                               GtkTextChildAnchor *anchor,
9577                               GtkTextLayout      *layout)
9578 {
9579   GtkTextViewChild *vc;
9580
9581   vc = g_new (GtkTextViewChild, 1);
9582
9583   vc->type = GTK_TEXT_WINDOW_PRIVATE;
9584   vc->widget = child;
9585   vc->anchor = anchor;
9586
9587   vc->from_top_of_line = 0;
9588   vc->from_left_of_buffer = 0;
9589   
9590   g_object_ref (vc->widget);
9591   g_object_ref (vc->anchor);
9592
9593   g_object_set_data (G_OBJECT (child),
9594                      I_("gtk-text-view-child"),
9595                      vc);
9596
9597   gtk_text_child_anchor_register_child (anchor, child, layout);
9598   
9599   return vc;
9600 }
9601
9602 static GtkTextViewChild*
9603 text_view_child_new_window (GtkWidget          *child,
9604                             GtkTextWindowType   type,
9605                             gint                x,
9606                             gint                y)
9607 {
9608   GtkTextViewChild *vc;
9609
9610   vc = g_new (GtkTextViewChild, 1);
9611
9612   vc->widget = child;
9613   vc->anchor = NULL;
9614
9615   vc->from_top_of_line = 0;
9616   vc->from_left_of_buffer = 0;
9617  
9618   g_object_ref (vc->widget);
9619
9620   vc->type = type;
9621   vc->x = x;
9622   vc->y = y;
9623
9624   g_object_set_data (G_OBJECT (child),
9625                      I_("gtk-text-view-child"),
9626                      vc);
9627   
9628   return vc;
9629 }
9630
9631 static void
9632 text_view_child_free (GtkTextViewChild *child)
9633 {
9634   g_object_set_data (G_OBJECT (child->widget),
9635                      I_("gtk-text-view-child"), NULL);
9636
9637   if (child->anchor)
9638     {
9639       gtk_text_child_anchor_unregister_child (child->anchor,
9640                                               child->widget);
9641       g_object_unref (child->anchor);
9642     }
9643
9644   g_object_unref (child->widget);
9645
9646   g_free (child);
9647 }
9648
9649 static void
9650 text_view_child_set_parent_window (GtkTextView      *text_view,
9651                                    GtkTextViewChild *vc)
9652 {
9653   if (vc->anchor)
9654     gtk_widget_set_parent_window (vc->widget,
9655                                   text_view->priv->text_window->bin_window);
9656   else
9657     {
9658       GdkWindow *window;
9659       window = gtk_text_view_get_window (text_view,
9660                                          vc->type);
9661       gtk_widget_set_parent_window (vc->widget, window);
9662     }
9663 }
9664
9665 static void
9666 add_child (GtkTextView      *text_view,
9667            GtkTextViewChild *vc)
9668 {
9669   text_view->priv->children = g_slist_prepend (text_view->priv->children,
9670                                                vc);
9671
9672   if (gtk_widget_get_realized (GTK_WIDGET (text_view)))
9673     text_view_child_set_parent_window (text_view, vc);
9674   
9675   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
9676 }
9677
9678 /**
9679  * gtk_text_view_add_child_at_anchor:
9680  * @text_view: a #GtkTextView
9681  * @child: a #GtkWidget
9682  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
9683  * 
9684  * Adds a child widget in the text buffer, at the given @anchor.
9685  **/
9686 void
9687 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
9688                                    GtkWidget            *child,
9689                                    GtkTextChildAnchor   *anchor)
9690 {
9691   GtkTextViewChild *vc;
9692
9693   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9694   g_return_if_fail (GTK_IS_WIDGET (child));
9695   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
9696   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9697
9698   gtk_text_view_ensure_layout (text_view);
9699
9700   vc = text_view_child_new_anchored (child, anchor,
9701                                      text_view->priv->layout);
9702
9703   add_child (text_view, vc);
9704
9705   g_assert (vc->widget == child);
9706   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9707 }
9708
9709 /**
9710  * gtk_text_view_add_child_in_window:
9711  * @text_view: a #GtkTextView
9712  * @child: a #GtkWidget
9713  * @which_window: which window the child should appear in
9714  * @xpos: X position of child in window coordinates
9715  * @ypos: Y position of child in window coordinates
9716  *
9717  * Adds a child at fixed coordinates in one of the text widget's
9718  * windows.
9719  *
9720  * The window must have nonzero size (see
9721  * gtk_text_view_set_border_window_size()). Note that the child
9722  * coordinates are given relative to the #GdkWindow in question, and
9723  * that these coordinates have no sane relationship to scrolling. When
9724  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
9725  * irrelevant, the child floats above all scrollable areas. But when
9726  * placing a child in one of the scrollable windows (border windows or
9727  * text window), you'll need to compute the child's correct position
9728  * in buffer coordinates any time scrolling occurs or buffer changes
9729  * occur, and then call gtk_text_view_move_child() to update the
9730  * child's position.
9731  */
9732 void
9733 gtk_text_view_add_child_in_window (GtkTextView       *text_view,
9734                                    GtkWidget         *child,
9735                                    GtkTextWindowType  which_window,
9736                                    gint               xpos,
9737                                    gint               ypos)
9738 {
9739   GtkTextViewChild *vc;
9740
9741   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9742   g_return_if_fail (GTK_IS_WIDGET (child));
9743   g_return_if_fail (gtk_widget_get_parent (child) == NULL);
9744
9745   vc = text_view_child_new_window (child, which_window,
9746                                    xpos, ypos);
9747
9748   add_child (text_view, vc);
9749
9750   g_assert (vc->widget == child);
9751   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9752 }
9753
9754 /**
9755  * gtk_text_view_move_child:
9756  * @text_view: a #GtkTextView
9757  * @child: child widget already added to the text view
9758  * @xpos: new X position in window coordinates
9759  * @ypos: new Y position in window coordinates
9760  *
9761  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
9762  **/
9763 void
9764 gtk_text_view_move_child (GtkTextView *text_view,
9765                           GtkWidget   *child,
9766                           gint         xpos,
9767                           gint         ypos)
9768 {
9769   GtkTextViewChild *vc;
9770
9771   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9772   g_return_if_fail (GTK_IS_WIDGET (child));
9773   g_return_if_fail (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
9774
9775   vc = g_object_get_data (G_OBJECT (child),
9776                           "gtk-text-view-child");
9777
9778   g_assert (vc != NULL);
9779
9780   if (vc->x == xpos &&
9781       vc->y == ypos)
9782     return;
9783   
9784   vc->x = xpos;
9785   vc->y = ypos;
9786
9787   if (gtk_widget_get_visible (child) &&
9788       gtk_widget_get_visible (GTK_WIDGET (text_view)))
9789     gtk_widget_queue_resize (child);
9790 }
9791
9792
9793 /* Iterator operations */
9794
9795 /**
9796  * gtk_text_view_forward_display_line:
9797  * @text_view: a #GtkTextView
9798  * @iter: a #GtkTextIter
9799  * 
9800  * Moves the given @iter forward by one display (wrapped) line.
9801  * A display line is different from a paragraph. Paragraphs are
9802  * separated by newlines or other paragraph separator characters.
9803  * Display lines are created by line-wrapping a paragraph. If
9804  * wrapping is turned off, display lines and paragraphs will be the
9805  * same. Display lines are divided differently for each view, since
9806  * they depend on the view's width; paragraphs are the same in all
9807  * views, since they depend on the contents of the #GtkTextBuffer.
9808  * 
9809  * Return value: %TRUE if @iter was moved and is not on the end iterator
9810  **/
9811 gboolean
9812 gtk_text_view_forward_display_line (GtkTextView *text_view,
9813                                     GtkTextIter *iter)
9814 {
9815   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9816   g_return_val_if_fail (iter != NULL, FALSE);
9817
9818   gtk_text_view_ensure_layout (text_view);
9819
9820   return gtk_text_layout_move_iter_to_next_line (text_view->priv->layout, iter);
9821 }
9822
9823 /**
9824  * gtk_text_view_backward_display_line:
9825  * @text_view: a #GtkTextView
9826  * @iter: a #GtkTextIter
9827  * 
9828  * Moves the given @iter backward by one display (wrapped) line.
9829  * A display line is different from a paragraph. Paragraphs are
9830  * separated by newlines or other paragraph separator characters.
9831  * Display lines are created by line-wrapping a paragraph. If
9832  * wrapping is turned off, display lines and paragraphs will be the
9833  * same. Display lines are divided differently for each view, since
9834  * they depend on the view's width; paragraphs are the same in all
9835  * views, since they depend on the contents of the #GtkTextBuffer.
9836  * 
9837  * Return value: %TRUE if @iter was moved and is not on the end iterator
9838  **/
9839 gboolean
9840 gtk_text_view_backward_display_line (GtkTextView *text_view,
9841                                      GtkTextIter *iter)
9842 {
9843   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9844   g_return_val_if_fail (iter != NULL, FALSE);
9845
9846   gtk_text_view_ensure_layout (text_view);
9847
9848   return gtk_text_layout_move_iter_to_previous_line (text_view->priv->layout, iter);
9849 }
9850
9851 /**
9852  * gtk_text_view_forward_display_line_end:
9853  * @text_view: a #GtkTextView
9854  * @iter: a #GtkTextIter
9855  * 
9856  * Moves the given @iter forward to the next display line end.
9857  * A display line is different from a paragraph. Paragraphs are
9858  * separated by newlines or other paragraph separator characters.
9859  * Display lines are created by line-wrapping a paragraph. If
9860  * wrapping is turned off, display lines and paragraphs will be the
9861  * same. Display lines are divided differently for each view, since
9862  * they depend on the view's width; paragraphs are the same in all
9863  * views, since they depend on the contents of the #GtkTextBuffer.
9864  * 
9865  * Return value: %TRUE if @iter was moved and is not on the end iterator
9866  **/
9867 gboolean
9868 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
9869                                         GtkTextIter *iter)
9870 {
9871   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9872   g_return_val_if_fail (iter != NULL, FALSE);
9873
9874   gtk_text_view_ensure_layout (text_view);
9875
9876   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, 1);
9877 }
9878
9879 /**
9880  * gtk_text_view_backward_display_line_start:
9881  * @text_view: a #GtkTextView
9882  * @iter: a #GtkTextIter
9883  * 
9884  * Moves the given @iter backward to the next display line start.
9885  * A display line is different from a paragraph. Paragraphs are
9886  * separated by newlines or other paragraph separator characters.
9887  * Display lines are created by line-wrapping a paragraph. If
9888  * wrapping is turned off, display lines and paragraphs will be the
9889  * same. Display lines are divided differently for each view, since
9890  * they depend on the view's width; paragraphs are the same in all
9891  * views, since they depend on the contents of the #GtkTextBuffer.
9892  * 
9893  * Return value: %TRUE if @iter was moved and is not on the end iterator
9894  **/
9895 gboolean
9896 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
9897                                            GtkTextIter *iter)
9898 {
9899   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9900   g_return_val_if_fail (iter != NULL, FALSE);
9901
9902   gtk_text_view_ensure_layout (text_view);
9903
9904   return gtk_text_layout_move_iter_to_line_end (text_view->priv->layout, iter, -1);
9905 }
9906
9907 /**
9908  * gtk_text_view_starts_display_line:
9909  * @text_view: a #GtkTextView
9910  * @iter: a #GtkTextIter
9911  * 
9912  * Determines whether @iter is at the start of a display line.
9913  * See gtk_text_view_forward_display_line() for an explanation of
9914  * display lines vs. paragraphs.
9915  * 
9916  * Return value: %TRUE if @iter begins a wrapped line
9917  **/
9918 gboolean
9919 gtk_text_view_starts_display_line (GtkTextView       *text_view,
9920                                    const GtkTextIter *iter)
9921 {
9922   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9923   g_return_val_if_fail (iter != NULL, FALSE);
9924
9925   gtk_text_view_ensure_layout (text_view);
9926
9927   return gtk_text_layout_iter_starts_line (text_view->priv->layout, iter);
9928 }
9929
9930 /**
9931  * gtk_text_view_move_visually:
9932  * @text_view: a #GtkTextView
9933  * @iter: a #GtkTextIter
9934  * @count: number of characters to move (negative moves left, 
9935  *    positive moves right)
9936  *
9937  * Move the iterator a given number of characters visually, treating
9938  * it as the strong cursor position. If @count is positive, then the
9939  * new strong cursor position will be @count positions to the right of
9940  * the old cursor position. If @count is negative then the new strong
9941  * cursor position will be @count positions to the left of the old
9942  * cursor position.
9943  *
9944  * In the presence of bi-directional text, the correspondence
9945  * between logical and visual order will depend on the direction
9946  * of the current run, and there may be jumps when the cursor
9947  * is moved off of the end of a run.
9948  * 
9949  * Return value: %TRUE if @iter moved and is not on the end iterator
9950  **/
9951 gboolean
9952 gtk_text_view_move_visually (GtkTextView *text_view,
9953                              GtkTextIter *iter,
9954                              gint         count)
9955 {
9956   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
9957   g_return_val_if_fail (iter != NULL, FALSE);
9958
9959   gtk_text_view_ensure_layout (text_view);
9960
9961   return gtk_text_layout_move_iter_visually (text_view->priv->layout, iter, count);
9962 }
9963
9964 /**
9965  * gtk_text_view_set_input_purpose:
9966  * @text_view: a #GtkTextView
9967  * @purpose: the purpose
9968  *
9969  * Sets the #GtkTextView:input-purpose property which
9970  * can be used by on-screen keyboards and other input
9971  * methods to adjust their behaviour.
9972  *
9973  * Since: 3.6
9974  */
9975
9976 void
9977 gtk_text_view_set_input_purpose (GtkTextView     *text_view,
9978                                  GtkInputPurpose  purpose)
9979
9980 {
9981   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
9982
9983   if (gtk_text_view_get_input_purpose (text_view) != purpose)
9984     {
9985       g_object_set (G_OBJECT (text_view->priv->im_context),
9986                     "input-purpose", purpose,
9987                     NULL);
9988
9989       g_object_notify (G_OBJECT (text_view), "input-purpose");
9990     }
9991 }
9992
9993 /**
9994  * gtk_text_view_get_input_purpose:
9995  * @text_view: a #GtkTextView
9996  *
9997  * Gets the value of the #GtkTextView:input-purpose property.
9998  *
9999  * Since: 3.6
10000  */
10001
10002 GtkInputPurpose
10003 gtk_text_view_get_input_purpose (GtkTextView *text_view)
10004 {
10005   GtkInputPurpose purpose;
10006
10007   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_INPUT_PURPOSE_FREE_FORM);
10008
10009   g_object_get (G_OBJECT (text_view->priv->im_context),
10010                 "input-purpose", &purpose,
10011                 NULL);
10012
10013   return purpose;
10014 }
10015
10016 /**
10017  * gtk_text_view_set_input_hints:
10018  * @text_view: a #GtkTextView
10019  * @hints: the hints
10020  *
10021  * Sets the #GtkTextView:input-hints property, which
10022  * allows input methods to fine-tune their behaviour.
10023  *
10024  * Since: 3.6
10025  */
10026
10027 void
10028 gtk_text_view_set_input_hints (GtkTextView   *text_view,
10029                                GtkInputHints  hints)
10030
10031 {
10032   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
10033
10034   if (gtk_text_view_get_input_hints (text_view) != hints)
10035     {
10036       g_object_set (G_OBJECT (text_view->priv->im_context),
10037                     "input-hints", hints,
10038                     NULL);
10039
10040       g_object_notify (G_OBJECT (text_view), "input-hints");
10041     }
10042 }
10043
10044 /**
10045  * gtk_text_view_get_input_hints:
10046  * @text_view: a #GtkTextView
10047  *
10048  * Gets the value of the #GtkTextView:input-hints property.
10049  *
10050  * Since: 3.6
10051  */
10052
10053 GtkInputHints
10054 gtk_text_view_get_input_hints (GtkTextView *text_view)
10055 {
10056   GtkInputHints hints;
10057
10058   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_INPUT_HINT_NONE);
10059
10060   g_object_get (G_OBJECT (text_view->priv->im_context),
10061                 "input-hints", &hints,
10062                 NULL);
10063
10064   return hints;
10065 }