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