]> Pileus Git - ~andy/gtk/blob - gtk/gtktextview.c
use gtk_text_layout_invalidate_cache instead of cut-and-paste
[~andy/gtk] / gtk / gtktextview.c
1 /* GTK - The GIMP Toolkit
2  * gtktextview.c Copyright (C) 2000 Red Hat, Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 #include <string.h>
28
29 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
30 #include "gtkbindings.h"
31 #include "gtkdnd.h"
32 #include "gtkimagemenuitem.h"
33 #include "gtkintl.h"
34 #include "gtkmain.h"
35 #include "gtkmarshalers.h"
36 #include "gtkmenu.h"
37 #include "gtkmenuitem.h"
38 #include "gtkseparatormenuitem.h"
39 #include "gtksettings.h"
40 #include "gtksignal.h"
41 #include "gtkstock.h"
42 #include "gtktextdisplay.h"
43 #include "gtktextview.h"
44 #include "gtkimmulticontext.h"
45 #include "gdk/gdkkeysyms.h"
46 #include "gtksizegroup.h"          /* FIXME http://bugzilla.gnome.org/show_bug.cgi?id=72258 */
47 #include "gtktextutil.h"
48 #include "gtkwindow.h"
49 #include <string.h>
50
51 /* How scrolling, validation, exposes, etc. work.
52  *
53  * The expose_event handler has the invariant that the onscreen lines
54  * have been validated.
55  *
56  * There are two ways that onscreen lines can become invalid. The first
57  * is to change which lines are onscreen. This happens when the value
58  * of a scroll adjustment changes. So the code path begins in
59  * gtk_text_view_value_changed() and goes like this:
60  *   - gdk_window_scroll() to reflect the new adjustment value
61  *   - validate the lines that were moved onscreen
62  *   - gdk_window_process_updates() to handle the exposes immediately
63  *
64  * The second way is that you get the "invalidated" signal from the layout,
65  * indicating that lines have become invalid. This code path begins in
66  * invalidated_handler() and goes like this:
67  *   - install high-priority idle which does the rest of the steps
68  *   - if a scroll is pending from scroll_to_mark(), do the scroll,
69  *     jumping to the gtk_text_view_value_changed() code path
70  *   - otherwise, validate the onscreen lines
71  *   - DO NOT process updates
72  *
73  * In both cases, validating the onscreen lines can trigger a scroll
74  * due to maintaining the first_para on the top of the screen.
75  * If validation triggers a scroll, we jump to the top of the code path
76  * for value_changed, and bail out of the current code path.
77  *
78  * Also, in size_allocate, if we invalidate some lines from changing
79  * the layout width, we need to go ahead and run the high-priority idle,
80  * because GTK sends exposes right after doing the size allocates without
81  * returning to the main loop. This is also why the high-priority idle
82  * is at a higher priority than resizing.
83  *
84  */
85
86 #if 0
87 #define DEBUG_VALIDATION_AND_SCROLLING
88 #endif
89
90 #ifdef DEBUG_VALIDATION_AND_SCROLLING
91 #define DV(x) (x)
92 #else
93 #define DV(x)
94 #endif
95
96 #define SCREEN_WIDTH(widget) text_window_get_width (GTK_TEXT_VIEW (widget)->text_window)
97 #define SCREEN_HEIGHT(widget) text_window_get_height (GTK_TEXT_VIEW (widget)->text_window)
98
99 struct _GtkTextPendingScroll
100 {
101   GtkTextMark   *mark;
102   gdouble        within_margin;
103   gboolean       use_align;
104   gdouble        xalign;
105   gdouble        yalign;
106 };
107   
108 enum
109 {
110   SET_SCROLL_ADJUSTMENTS,
111   POPULATE_POPUP,
112   MOVE_CURSOR,
113   PAGE_HORIZONTALLY,
114   SET_ANCHOR,
115   INSERT_AT_CURSOR,
116   DELETE_FROM_CURSOR,
117   CUT_CLIPBOARD,
118   COPY_CLIPBOARD,
119   PASTE_CLIPBOARD,
120   TOGGLE_OVERWRITE,
121   MOVE_FOCUS,
122   LAST_SIGNAL
123 };
124
125 enum
126 {
127   PROP_0,
128   PROP_PIXELS_ABOVE_LINES,
129   PROP_PIXELS_BELOW_LINES,
130   PROP_PIXELS_INSIDE_WRAP,
131   PROP_EDITABLE,
132   PROP_WRAP_MODE,
133   PROP_JUSTIFICATION,
134   PROP_LEFT_MARGIN,
135   PROP_RIGHT_MARGIN,
136   PROP_INDENT,
137   PROP_TABS,
138   PROP_CURSOR_VISIBLE,
139   LAST_PROP
140 };
141
142 static void gtk_text_view_init                 (GtkTextView      *text_view);
143 static void gtk_text_view_class_init           (GtkTextViewClass *klass);
144 static void gtk_text_view_destroy              (GtkObject        *object);
145 static void gtk_text_view_finalize             (GObject          *object);
146 static void gtk_text_view_set_property         (GObject         *object,
147                                                 guint            prop_id,
148                                                 const GValue    *value,
149                                                 GParamSpec      *pspec);
150 static void gtk_text_view_get_property         (GObject         *object,
151                                                 guint            prop_id,
152                                                 GValue          *value,
153                                                 GParamSpec      *pspec);
154 static void gtk_text_view_size_request         (GtkWidget        *widget,
155                                                 GtkRequisition   *requisition);
156 static void gtk_text_view_size_allocate        (GtkWidget        *widget,
157                                                 GtkAllocation    *allocation);
158 static void gtk_text_view_realize              (GtkWidget        *widget);
159 static void gtk_text_view_unrealize            (GtkWidget        *widget);
160 static void gtk_text_view_style_set            (GtkWidget        *widget,
161                                                 GtkStyle         *previous_style);
162 static void gtk_text_view_direction_changed    (GtkWidget        *widget,
163                                                 GtkTextDirection  previous_direction);
164 static gint gtk_text_view_event                (GtkWidget        *widget,
165                                                 GdkEvent         *event);
166 static gint gtk_text_view_key_press_event      (GtkWidget        *widget,
167                                                 GdkEventKey      *event);
168 static gint gtk_text_view_key_release_event    (GtkWidget        *widget,
169                                                 GdkEventKey      *event);
170 static gint gtk_text_view_button_press_event   (GtkWidget        *widget,
171                                                 GdkEventButton   *event);
172 static gint gtk_text_view_button_release_event (GtkWidget        *widget,
173                                                 GdkEventButton   *event);
174 static gint gtk_text_view_focus_in_event       (GtkWidget        *widget,
175                                                 GdkEventFocus    *event);
176 static gint gtk_text_view_focus_out_event      (GtkWidget        *widget,
177                                                 GdkEventFocus    *event);
178 static gint gtk_text_view_motion_event         (GtkWidget        *widget,
179                                                 GdkEventMotion   *event);
180 static gint gtk_text_view_expose_event         (GtkWidget        *widget,
181                                                 GdkEventExpose   *expose);
182 static void gtk_text_view_draw_focus           (GtkWidget        *widget);
183 static void gtk_text_view_grab_focus           (GtkWidget        *widget);
184 static gboolean gtk_text_view_focus            (GtkWidget        *widget,
185                                                 GtkDirectionType  direction);
186
187
188 /* Source side drag signals */
189 static void gtk_text_view_drag_begin       (GtkWidget        *widget,
190                                             GdkDragContext   *context);
191 static void gtk_text_view_drag_end         (GtkWidget        *widget,
192                                             GdkDragContext   *context);
193 static void gtk_text_view_drag_data_get    (GtkWidget        *widget,
194                                             GdkDragContext   *context,
195                                             GtkSelectionData *selection_data,
196                                             guint             info,
197                                             guint             time);
198 static void gtk_text_view_drag_data_delete (GtkWidget        *widget,
199                                             GdkDragContext   *context);
200
201 /* Target side drag signals */
202 static void     gtk_text_view_drag_leave         (GtkWidget        *widget,
203                                                   GdkDragContext   *context,
204                                                   guint             time);
205 static gboolean gtk_text_view_drag_motion        (GtkWidget        *widget,
206                                                   GdkDragContext   *context,
207                                                   gint              x,
208                                                   gint              y,
209                                                   guint             time);
210 static gboolean gtk_text_view_drag_drop          (GtkWidget        *widget,
211                                                   GdkDragContext   *context,
212                                                   gint              x,
213                                                   gint              y,
214                                                   guint             time);
215 static void     gtk_text_view_drag_data_received (GtkWidget        *widget,
216                                                   GdkDragContext   *context,
217                                                   gint              x,
218                                                   gint              y,
219                                                   GtkSelectionData *selection_data,
220                                                   guint             info,
221                                                   guint             time);
222
223 static void gtk_text_view_set_scroll_adjustments (GtkTextView   *text_view,
224                                                   GtkAdjustment *hadj,
225                                                   GtkAdjustment *vadj);
226 static gboolean gtk_text_view_popup_menu         (GtkWidget     *widget);
227
228 static void gtk_text_view_move_cursor       (GtkTextView           *text_view,
229                                              GtkMovementStep        step,
230                                              gint                   count,
231                                              gboolean               extend_selection);
232 static void gtk_text_view_page_horizontally (GtkTextView          *text_view,
233                                              gint                  count,
234                                              gboolean              extend_selection);
235 static void gtk_text_view_set_anchor       (GtkTextView           *text_view);
236 static void gtk_text_view_scroll_pages     (GtkTextView           *text_view,
237                                             gint                   count,
238                                             gboolean               extend_selection);
239 static void gtk_text_view_scroll_hpages    (GtkTextView           *text_view,
240                                             gint                   count,
241                                             gboolean               extend_selection);
242 static void gtk_text_view_insert_at_cursor (GtkTextView           *text_view,
243                                             const gchar           *str);
244 static void gtk_text_view_delete_from_cursor (GtkTextView           *text_view,
245                                               GtkDeleteType          type,
246                                               gint                   count);
247 static void gtk_text_view_cut_clipboard    (GtkTextView           *text_view);
248 static void gtk_text_view_copy_clipboard   (GtkTextView           *text_view);
249 static void gtk_text_view_paste_clipboard  (GtkTextView           *text_view);
250 static void gtk_text_view_toggle_overwrite (GtkTextView           *text_view);
251 static void gtk_text_view_move_focus       (GtkTextView           *text_view,
252                                             GtkDirectionType       direction_type);
253 static void gtk_text_view_unselect         (GtkTextView           *text_view);
254
255 static void     gtk_text_view_validate_onscreen     (GtkTextView        *text_view);
256 static void     gtk_text_view_get_first_para_iter   (GtkTextView        *text_view,
257                                                      GtkTextIter        *iter);
258 static void     gtk_text_view_update_layout_width       (GtkTextView        *text_view);
259 static void     gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
260                                                          GtkTextAttributes *values,
261                                                          GtkStyle           *style);
262 static void     gtk_text_view_ensure_layout          (GtkTextView        *text_view);
263 static void     gtk_text_view_destroy_layout         (GtkTextView        *text_view);
264 static void     gtk_text_view_check_keymap_direction (GtkTextView        *text_view);
265 static void     gtk_text_view_reset_im_context       (GtkTextView        *text_view);
266 static void     gtk_text_view_start_selection_drag   (GtkTextView        *text_view,
267                                                       const GtkTextIter  *iter,
268                                                       GdkEventButton     *event);
269 static gboolean gtk_text_view_end_selection_drag     (GtkTextView        *text_view,
270                                                       GdkEventButton     *event);
271 static void     gtk_text_view_start_selection_dnd    (GtkTextView        *text_view,
272                                                       const GtkTextIter  *iter,
273                                                       GdkEventMotion     *event);
274 static void     gtk_text_view_check_cursor_blink     (GtkTextView        *text_view);
275 static void     gtk_text_view_pend_cursor_blink      (GtkTextView        *text_view);
276 static void     gtk_text_view_stop_cursor_blink      (GtkTextView        *text_view);
277
278 static void     gtk_text_view_value_changed                (GtkAdjustment *adj,
279                                                             GtkTextView   *view);
280 static void     gtk_text_view_commit_handler               (GtkIMContext  *context,
281                                                             const gchar   *str,
282                                                             GtkTextView   *text_view);
283 static void     gtk_text_view_commit_text                  (GtkTextView   *text_view,
284                                                             const gchar   *text);
285 static void     gtk_text_view_preedit_changed_handler      (GtkIMContext  *context,
286                                                             GtkTextView   *text_view);
287 static gboolean gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
288                                                             GtkTextView   *text_view);
289 static gboolean gtk_text_view_delete_surrounding_handler   (GtkIMContext  *context,
290                                                             gint           offset,
291                                                             gint           n_chars,
292                                                             GtkTextView   *text_view);
293
294 static void gtk_text_view_mark_set_handler       (GtkTextBuffer     *buffer,
295                                                   const GtkTextIter *location,
296                                                   GtkTextMark       *mark,
297                                                   gpointer           data);
298 static void gtk_text_view_get_virtual_cursor_pos (GtkTextView       *text_view,
299                                                   gint              *x,
300                                                   gint              *y);
301 static void gtk_text_view_set_virtual_cursor_pos (GtkTextView       *text_view,
302                                                   gint               x,
303                                                   gint               y);
304
305 static GtkAdjustment* get_hadjustment            (GtkTextView       *text_view);
306 static GtkAdjustment* get_vadjustment            (GtkTextView       *text_view);
307
308 static void gtk_text_view_do_popup               (GtkTextView       *text_view,
309                                                   GdkEventButton    *event);
310
311 static void gtk_text_view_queue_scroll           (GtkTextView   *text_view,
312                                                   GtkTextMark   *mark,
313                                                   gdouble        within_margin,
314                                                   gboolean       use_align,
315                                                   gdouble        xalign,
316                                                   gdouble        yalign);
317
318 static gboolean gtk_text_view_flush_scroll         (GtkTextView *text_view);
319 static void     gtk_text_view_update_adjustments   (GtkTextView *text_view);
320 static void     gtk_text_view_invalidate           (GtkTextView *text_view);
321 static void     gtk_text_view_flush_first_validate (GtkTextView *text_view);
322
323 static void gtk_text_view_update_im_spot_location (GtkTextView *text_view);
324
325 /* Container methods */
326 static void gtk_text_view_add    (GtkContainer *container,
327                                   GtkWidget    *child);
328 static void gtk_text_view_remove (GtkContainer *container,
329                                   GtkWidget    *child);
330 static void gtk_text_view_forall (GtkContainer *container,
331                                   gboolean      include_internals,
332                                  GtkCallback   callback,
333                                   gpointer      callback_data);
334
335 /* FIXME probably need the focus methods. */
336
337 typedef struct _GtkTextViewChild GtkTextViewChild;
338
339 struct _GtkTextViewChild
340 {
341   GtkWidget *widget;
342
343   GtkTextChildAnchor *anchor;
344
345   gint from_top_of_line;
346   gint from_left_of_buffer;
347   
348   /* These are ignored if anchor != NULL */
349   GtkTextWindowType type;
350   gint x;
351   gint y;
352 };
353
354 static GtkTextViewChild* text_view_child_new_anchored      (GtkWidget          *child,
355                                                             GtkTextChildAnchor *anchor,
356                                                             GtkTextLayout      *layout);
357 static GtkTextViewChild* text_view_child_new_window        (GtkWidget          *child,
358                                                             GtkTextWindowType   type,
359                                                             gint                x,
360                                                             gint                y);
361 static void              text_view_child_free              (GtkTextViewChild   *child);
362 static void              text_view_child_set_parent_window (GtkTextView        *text_view,
363                                                             GtkTextViewChild   *child);
364
365 struct _GtkTextWindow
366 {
367   GtkTextWindowType type;
368   GtkWidget *widget;
369   GdkWindow *window;
370   GdkWindow *bin_window;
371   GtkRequisition requisition;
372   GdkRectangle allocation;
373 };
374
375 static GtkTextWindow *text_window_new             (GtkTextWindowType  type,
376                                                    GtkWidget         *widget,
377                                                    gint               width_request,
378                                                    gint               height_request);
379 static void           text_window_free            (GtkTextWindow     *win);
380 static void           text_window_realize         (GtkTextWindow     *win,
381                                                    GdkWindow         *parent);
382 static void           text_window_unrealize       (GtkTextWindow     *win);
383 static void           text_window_size_allocate   (GtkTextWindow     *win,
384                                                    GdkRectangle      *rect);
385 static void           text_window_scroll          (GtkTextWindow     *win,
386                                                    gint               dx,
387                                                    gint               dy);
388 static void           text_window_invalidate_rect (GtkTextWindow     *win,
389                                                    GdkRectangle      *rect);
390
391 static gint           text_window_get_width       (GtkTextWindow     *win);
392 static gint           text_window_get_height      (GtkTextWindow     *win);
393 static void           text_window_get_allocation  (GtkTextWindow     *win,
394                                                    GdkRectangle      *rect);
395
396
397 enum
398 {
399   TARGET_STRING,
400   TARGET_TEXT,
401   TARGET_COMPOUND_TEXT,
402   TARGET_UTF8_STRING,
403   TARGET_TEXT_BUFFER_CONTENTS
404 };
405
406 static GtkTargetEntry target_table[] = {
407   { "GTK_TEXT_BUFFER_CONTENTS", GTK_TARGET_SAME_APP,
408     TARGET_TEXT_BUFFER_CONTENTS },
409   { "UTF8_STRING", 0, TARGET_UTF8_STRING },
410   { "COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT },
411   { "TEXT", 0, TARGET_TEXT },
412   { "STRING",     0, TARGET_STRING }
413 };
414
415 static GtkContainerClass *parent_class = NULL;
416 static guint signals[LAST_SIGNAL] = { 0 };
417
418 GtkType
419 gtk_text_view_get_type (void)
420 {
421   static GtkType our_type = 0;
422
423   if (our_type == 0)
424     {
425       static const GtkTypeInfo our_info =
426       {
427         "GtkTextView",
428         sizeof (GtkTextView),
429         sizeof (GtkTextViewClass),
430         (GtkClassInitFunc) gtk_text_view_class_init,
431         (GtkObjectInitFunc) gtk_text_view_init,
432         /* reserved_1 */ NULL,
433         /* reserved_2 */ NULL,
434         (GtkClassInitFunc) NULL
435       };
436
437       our_type = gtk_type_unique (GTK_TYPE_CONTAINER, &our_info);
438     }
439
440   return our_type;
441 }
442
443 static void
444 add_move_binding (GtkBindingSet  *binding_set,
445                   guint           keyval,
446                   guint           modmask,
447                   GtkMovementStep step,
448                   gint            count)
449 {
450   g_return_if_fail ((modmask & GDK_SHIFT_MASK) == 0);
451
452   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
453                                 "move_cursor", 3,
454                                 GTK_TYPE_ENUM, step,
455                                 GTK_TYPE_INT, count,
456                                 GTK_TYPE_BOOL, FALSE);
457
458   /* Selection-extending version */
459   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
460                                 "move_cursor", 3,
461                                 GTK_TYPE_ENUM, step,
462                                 GTK_TYPE_INT, count,
463                                 GTK_TYPE_BOOL, TRUE);
464 }
465
466 static void
467 gtk_text_view_class_init (GtkTextViewClass *klass)
468 {
469   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
470   GtkObjectClass *object_class = GTK_OBJECT_CLASS (klass);
471   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
472   GtkContainerClass *container_class = GTK_CONTAINER_CLASS (klass);
473   GtkBindingSet *binding_set;
474
475   parent_class = gtk_type_class (GTK_TYPE_CONTAINER);
476
477   /* Default handlers and virtual methods
478    */
479   gobject_class->set_property = gtk_text_view_set_property;
480   gobject_class->get_property = gtk_text_view_get_property;
481
482   object_class->destroy = gtk_text_view_destroy;
483   gobject_class->finalize = gtk_text_view_finalize;
484
485   widget_class->realize = gtk_text_view_realize;
486   widget_class->unrealize = gtk_text_view_unrealize;
487   widget_class->style_set = gtk_text_view_style_set;
488   widget_class->direction_changed = gtk_text_view_direction_changed;
489   widget_class->size_request = gtk_text_view_size_request;
490   widget_class->size_allocate = gtk_text_view_size_allocate;
491   widget_class->event = gtk_text_view_event;
492   widget_class->key_press_event = gtk_text_view_key_press_event;
493   widget_class->key_release_event = gtk_text_view_key_release_event;
494   widget_class->button_press_event = gtk_text_view_button_press_event;
495   widget_class->button_release_event = gtk_text_view_button_release_event;
496   widget_class->focus_in_event = gtk_text_view_focus_in_event;
497   widget_class->focus_out_event = gtk_text_view_focus_out_event;
498   widget_class->motion_notify_event = gtk_text_view_motion_event;
499   widget_class->expose_event = gtk_text_view_expose_event;
500   widget_class->grab_focus = gtk_text_view_grab_focus;
501   widget_class->focus = gtk_text_view_focus;
502   
503   widget_class->drag_begin = gtk_text_view_drag_begin;
504   widget_class->drag_end = gtk_text_view_drag_end;
505   widget_class->drag_data_get = gtk_text_view_drag_data_get;
506   widget_class->drag_data_delete = gtk_text_view_drag_data_delete;
507
508   widget_class->drag_leave = gtk_text_view_drag_leave;
509   widget_class->drag_motion = gtk_text_view_drag_motion;
510   widget_class->drag_drop = gtk_text_view_drag_drop;
511   widget_class->drag_data_received = gtk_text_view_drag_data_received;
512
513   widget_class->popup_menu = gtk_text_view_popup_menu;
514   
515   container_class->add = gtk_text_view_add;
516   container_class->remove = gtk_text_view_remove;
517   container_class->forall = gtk_text_view_forall;
518
519   klass->move_cursor = gtk_text_view_move_cursor;
520   klass->page_horizontally = gtk_text_view_page_horizontally;
521   klass->set_anchor = gtk_text_view_set_anchor;
522   klass->insert_at_cursor = gtk_text_view_insert_at_cursor;
523   klass->delete_from_cursor = gtk_text_view_delete_from_cursor;
524   klass->cut_clipboard = gtk_text_view_cut_clipboard;
525   klass->copy_clipboard = gtk_text_view_copy_clipboard;
526   klass->paste_clipboard = gtk_text_view_paste_clipboard;
527   klass->toggle_overwrite = gtk_text_view_toggle_overwrite;
528   klass->move_focus = gtk_text_view_move_focus;
529   klass->set_scroll_adjustments = gtk_text_view_set_scroll_adjustments;
530
531   /*
532    * Properties
533    */
534  
535   g_object_class_install_property (gobject_class,
536                                    PROP_PIXELS_ABOVE_LINES,
537                                    g_param_spec_int ("pixels_above_lines",
538                                                      _("Pixels Above Lines"),
539                                                      _("Pixels of blank space above paragraphs"),
540                                                      0,
541                                                      G_MAXINT,
542                                                      0,
543                                                      G_PARAM_READWRITE));
544  
545   g_object_class_install_property (gobject_class,
546                                    PROP_PIXELS_BELOW_LINES,
547                                    g_param_spec_int ("pixels_below_lines",
548                                                      _("Pixels Below Lines"),
549                                                      _("Pixels of blank space below paragraphs"),
550                                                      0,
551                                                      G_MAXINT,
552                                                      0,
553                                                      G_PARAM_READWRITE));
554  
555   g_object_class_install_property (gobject_class,
556                                    PROP_PIXELS_INSIDE_WRAP,
557                                    g_param_spec_int ("pixels_inside_wrap",
558                                                      _("Pixels Inside Wrap"),
559                                                      _("Pixels of blank space between wrapped lines in a paragraph"),
560                                                      0,
561                                                      G_MAXINT,
562                                                      0,
563                                                      G_PARAM_READWRITE));
564
565   g_object_class_install_property (gobject_class,
566                                    PROP_EDITABLE,
567                                    g_param_spec_boolean ("editable",
568                                                          _("Editable"),
569                                                          _("Whether the text can be modified by the user"),
570                                                          TRUE,
571                                                          G_PARAM_READWRITE));
572
573   g_object_class_install_property (gobject_class,
574                                    PROP_WRAP_MODE,
575                                    g_param_spec_enum ("wrap_mode",
576                                                       _("Wrap Mode"),
577                                                       _("Whether to wrap lines never, at word boundaries, or at character boundaries"),
578                                                       GTK_TYPE_WRAP_MODE,
579                                                       GTK_WRAP_NONE,
580                                                       G_PARAM_READWRITE));
581  
582   g_object_class_install_property (gobject_class,
583                                    PROP_JUSTIFICATION,
584                                    g_param_spec_enum ("justification",
585                                                       _("Justification"),
586                                                       _("Left, right, or center justification"),
587                                                       GTK_TYPE_JUSTIFICATION,
588                                                       GTK_JUSTIFY_LEFT,
589                                                       G_PARAM_READWRITE));
590  
591   g_object_class_install_property (gobject_class,
592                                    PROP_LEFT_MARGIN,
593                                    g_param_spec_int ("left_margin",
594                                                      _("Left Margin"),
595                                                      _("Width of the left margin in pixels"),
596                                                      0,
597                                                      G_MAXINT,
598                                                      0,
599                                                      G_PARAM_READWRITE));
600
601   g_object_class_install_property (gobject_class,
602                                    PROP_RIGHT_MARGIN,
603                                    g_param_spec_int ("right_margin",
604                                                      _("Right Margin"),
605                                                      _("Width of the right margin in pixels"),
606                                                      0,
607                                                      G_MAXINT,
608                                                      0,
609                                                      G_PARAM_READWRITE));
610
611   g_object_class_install_property (gobject_class,
612                                    PROP_INDENT,
613                                    g_param_spec_int ("indent",
614                                                      _("Indent"),
615                                                      _("Amount to indent the paragraph, in pixels"),
616                                                      0,
617                                                      G_MAXINT,
618                                                      0,
619                                                      G_PARAM_READWRITE));
620
621   g_object_class_install_property (gobject_class,
622                                    PROP_TABS,
623                                    g_param_spec_boxed ("tabs",
624                                                        _("Tabs"),
625                                                        _("Custom tabs for this text"),
626                                                        PANGO_TYPE_TAB_ARRAY,
627                                                        G_PARAM_READWRITE));
628
629   g_object_class_install_property (gobject_class,
630                                    PROP_CURSOR_VISIBLE,
631                                    g_param_spec_boolean ("cursor_visible",
632                                                          _("Cursor Visible"),
633                                                          _("If the insertion cursor is shown"),
634                                                          TRUE,
635                                                          G_PARAM_READWRITE));
636
637   
638   /*
639    * Signals
640    */
641
642   signals[MOVE_CURSOR] =
643     gtk_signal_new ("move_cursor",
644                     GTK_RUN_LAST | GTK_RUN_ACTION,
645                     GTK_CLASS_TYPE (object_class),
646                     GTK_SIGNAL_OFFSET (GtkTextViewClass, move_cursor),
647                     _gtk_marshal_VOID__ENUM_INT_BOOLEAN,
648                     GTK_TYPE_NONE, 3, GTK_TYPE_MOVEMENT_STEP, GTK_TYPE_INT, GTK_TYPE_BOOL);
649
650   signals[PAGE_HORIZONTALLY] =
651     gtk_signal_new ("page_horizontally",
652                     GTK_RUN_LAST | GTK_RUN_ACTION,
653                     GTK_CLASS_TYPE (object_class),
654                     GTK_SIGNAL_OFFSET (GtkTextViewClass, page_horizontally),
655                     _gtk_marshal_VOID__INT_BOOLEAN,
656                     GTK_TYPE_NONE, 2, GTK_TYPE_INT, GTK_TYPE_BOOL);
657   
658   signals[SET_ANCHOR] =
659     gtk_signal_new ("set_anchor",
660                     GTK_RUN_LAST | GTK_RUN_ACTION,
661                     GTK_CLASS_TYPE (object_class),
662                     GTK_SIGNAL_OFFSET (GtkTextViewClass, set_anchor),
663                     _gtk_marshal_VOID__VOID,
664                     GTK_TYPE_NONE, 0);
665
666   signals[INSERT_AT_CURSOR] =
667     gtk_signal_new ("insert_at_cursor",
668                     GTK_RUN_LAST | GTK_RUN_ACTION,
669                     GTK_CLASS_TYPE (object_class),
670                     GTK_SIGNAL_OFFSET (GtkTextViewClass, insert_at_cursor),
671                     _gtk_marshal_VOID__STRING,
672                     GTK_TYPE_NONE, 1, GTK_TYPE_STRING);
673
674   signals[DELETE_FROM_CURSOR] =
675     gtk_signal_new ("delete_from_cursor",
676                     GTK_RUN_LAST | GTK_RUN_ACTION,
677                     GTK_CLASS_TYPE (object_class),
678                     GTK_SIGNAL_OFFSET (GtkTextViewClass, delete_from_cursor),
679                     _gtk_marshal_VOID__ENUM_INT,
680                     GTK_TYPE_NONE, 2, GTK_TYPE_DELETE_TYPE, GTK_TYPE_INT);
681
682   signals[CUT_CLIPBOARD] =
683     gtk_signal_new ("cut_clipboard",
684                     GTK_RUN_LAST | GTK_RUN_ACTION,
685                     GTK_CLASS_TYPE (object_class),
686                     GTK_SIGNAL_OFFSET (GtkTextViewClass, cut_clipboard),
687                     _gtk_marshal_VOID__VOID,
688                     GTK_TYPE_NONE, 0);
689
690   signals[COPY_CLIPBOARD] =
691     gtk_signal_new ("copy_clipboard",
692                     GTK_RUN_LAST | GTK_RUN_ACTION,
693                     GTK_CLASS_TYPE (object_class),
694                     GTK_SIGNAL_OFFSET (GtkTextViewClass, copy_clipboard),
695                     _gtk_marshal_VOID__VOID,
696                     GTK_TYPE_NONE, 0);
697
698   signals[PASTE_CLIPBOARD] =
699     gtk_signal_new ("paste_clipboard",
700                     GTK_RUN_LAST | GTK_RUN_ACTION,
701                     GTK_CLASS_TYPE (object_class),
702                     GTK_SIGNAL_OFFSET (GtkTextViewClass, paste_clipboard),
703                     _gtk_marshal_VOID__VOID,
704                     GTK_TYPE_NONE, 0);
705
706   signals[TOGGLE_OVERWRITE] =
707     gtk_signal_new ("toggle_overwrite",
708                     GTK_RUN_LAST | GTK_RUN_ACTION,
709                     GTK_CLASS_TYPE (object_class),
710                     GTK_SIGNAL_OFFSET (GtkTextViewClass, toggle_overwrite),
711                     _gtk_marshal_VOID__VOID,
712                     GTK_TYPE_NONE, 0);
713
714   signals[MOVE_FOCUS] =
715     gtk_signal_new ("move_focus",
716                     GTK_RUN_LAST | GTK_RUN_ACTION,
717                     GTK_CLASS_TYPE (object_class),
718                     GTK_SIGNAL_OFFSET (GtkTextViewClass, move_focus),
719                     _gtk_marshal_VOID__ENUM,
720                     GTK_TYPE_NONE, 1, GTK_TYPE_DIRECTION_TYPE);
721   
722   signals[SET_SCROLL_ADJUSTMENTS] =
723     gtk_signal_new ("set_scroll_adjustments",
724                     GTK_RUN_LAST,
725                     GTK_CLASS_TYPE (object_class),
726                     GTK_SIGNAL_OFFSET (GtkTextViewClass, set_scroll_adjustments),
727                     _gtk_marshal_VOID__OBJECT_OBJECT,
728                     GTK_TYPE_NONE, 2, GTK_TYPE_ADJUSTMENT, GTK_TYPE_ADJUSTMENT);
729   widget_class->set_scroll_adjustments_signal = signals[SET_SCROLL_ADJUSTMENTS];
730
731   signals[POPULATE_POPUP] =
732     gtk_signal_new ("populate_popup",
733                     GTK_RUN_LAST,
734                     GTK_CLASS_TYPE (object_class),
735                     GTK_SIGNAL_OFFSET (GtkTextViewClass, populate_popup),
736                     _gtk_marshal_VOID__OBJECT,
737                     GTK_TYPE_NONE, 1, GTK_TYPE_MENU);
738   
739   /*
740    * Key bindings
741    */
742
743   binding_set = gtk_binding_set_by_class (klass);
744   
745   /* Moving the insertion point */
746   add_move_binding (binding_set, GDK_Right, 0,
747                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
748
749   add_move_binding (binding_set, GDK_KP_Right, 0,
750                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
751   
752   add_move_binding (binding_set, GDK_Left, 0,
753                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
754
755   add_move_binding (binding_set, GDK_KP_Left, 0,
756                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
757   
758   add_move_binding (binding_set, GDK_Right, GDK_CONTROL_MASK,
759                     GTK_MOVEMENT_WORDS, 1);
760
761   add_move_binding (binding_set, GDK_KP_Right, GDK_CONTROL_MASK,
762                     GTK_MOVEMENT_WORDS, 1);
763   
764   add_move_binding (binding_set, GDK_Left, GDK_CONTROL_MASK,
765                     GTK_MOVEMENT_WORDS, -1);
766
767   add_move_binding (binding_set, GDK_KP_Left, GDK_CONTROL_MASK,
768                     GTK_MOVEMENT_WORDS, 1);
769   
770   add_move_binding (binding_set, GDK_Up, 0,
771                     GTK_MOVEMENT_DISPLAY_LINES, -1);
772
773   add_move_binding (binding_set, GDK_KP_Up, 0,
774                     GTK_MOVEMENT_DISPLAY_LINES, -1);
775   
776   add_move_binding (binding_set, GDK_Down, 0,
777                     GTK_MOVEMENT_DISPLAY_LINES, 1);
778
779   add_move_binding (binding_set, GDK_KP_Down, 0,
780                     GTK_MOVEMENT_DISPLAY_LINES, 1);
781   
782   add_move_binding (binding_set, GDK_Up, GDK_CONTROL_MASK,
783                     GTK_MOVEMENT_PARAGRAPHS, -1);
784
785   add_move_binding (binding_set, GDK_KP_Up, GDK_CONTROL_MASK,
786                     GTK_MOVEMENT_PARAGRAPHS, -1);
787   
788   add_move_binding (binding_set, GDK_Down, GDK_CONTROL_MASK,
789                     GTK_MOVEMENT_PARAGRAPHS, 1);
790
791   add_move_binding (binding_set, GDK_KP_Down, GDK_CONTROL_MASK,
792                     GTK_MOVEMENT_PARAGRAPHS, 1);
793   
794   add_move_binding (binding_set, GDK_Home, 0,
795                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
796
797   add_move_binding (binding_set, GDK_KP_Home, 0,
798                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
799   
800   add_move_binding (binding_set, GDK_End, 0,
801                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
802
803   add_move_binding (binding_set, GDK_KP_End, 0,
804                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
805   
806   add_move_binding (binding_set, GDK_Home, GDK_CONTROL_MASK,
807                     GTK_MOVEMENT_BUFFER_ENDS, -1);
808
809   add_move_binding (binding_set, GDK_KP_Home, GDK_CONTROL_MASK,
810                     GTK_MOVEMENT_BUFFER_ENDS, -1);
811   
812   add_move_binding (binding_set, GDK_End, GDK_CONTROL_MASK,
813                     GTK_MOVEMENT_BUFFER_ENDS, 1);
814
815   add_move_binding (binding_set, GDK_KP_End, GDK_CONTROL_MASK,
816                     GTK_MOVEMENT_BUFFER_ENDS, 1);
817   
818   add_move_binding (binding_set, GDK_Page_Up, 0,
819                     GTK_MOVEMENT_PAGES, -1);
820
821   add_move_binding (binding_set, GDK_KP_Page_Up, 0,
822                     GTK_MOVEMENT_PAGES, -1);
823   
824   add_move_binding (binding_set, GDK_Page_Down, 0,
825                     GTK_MOVEMENT_PAGES, 1);
826
827   add_move_binding (binding_set, GDK_KP_Page_Down, 0,
828                     GTK_MOVEMENT_PAGES, 1);
829
830   /* Select all
831    */
832   gtk_binding_entry_add_signal (binding_set, GDK_a, GDK_CONTROL_MASK,
833                                 "move_cursor", 3,
834                                 GTK_TYPE_MOVEMENT_STEP, GTK_MOVEMENT_BUFFER_ENDS,
835                                 GTK_TYPE_INT, -1,
836                                 GTK_TYPE_BOOL, FALSE);
837   gtk_binding_entry_add_signal (binding_set, GDK_a, GDK_CONTROL_MASK,
838                                 "move_cursor", 3,
839                                 GTK_TYPE_MOVEMENT_STEP, GTK_MOVEMENT_BUFFER_ENDS,
840                                 GTK_TYPE_INT, 1,
841                                 GTK_TYPE_BOOL, TRUE);
842
843   
844   gtk_binding_entry_add_signal (binding_set, GDK_Page_Up, GDK_CONTROL_MASK,
845                                 "page_horizontally", 2,
846                                 GTK_TYPE_INT, -1,
847                                 GTK_TYPE_BOOL, FALSE);
848
849   gtk_binding_entry_add_signal (binding_set, GDK_Page_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK,
850                                 "page_horizontally", 2,
851                                 GTK_TYPE_INT, -1,
852                                 GTK_TYPE_BOOL, TRUE);
853
854   gtk_binding_entry_add_signal (binding_set, GDK_KP_Page_Up, GDK_CONTROL_MASK,
855                                 "page_horizontally", 2,
856                                 GTK_TYPE_INT, -1,
857                                 GTK_TYPE_BOOL, FALSE);
858
859   gtk_binding_entry_add_signal (binding_set, GDK_KP_Page_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK,
860                                 "page_horizontally", 2,
861                                 GTK_TYPE_INT, -1,
862                                 GTK_TYPE_BOOL, TRUE);
863
864   gtk_binding_entry_add_signal (binding_set, GDK_Page_Down, GDK_CONTROL_MASK,
865                                 "page_horizontally", 2,
866                                 GTK_TYPE_INT, 1,
867                                 GTK_TYPE_BOOL, FALSE);
868
869   gtk_binding_entry_add_signal (binding_set, GDK_Page_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK,
870                                 "page_horizontally", 2,
871                                 GTK_TYPE_INT, 1,
872                                 GTK_TYPE_BOOL, TRUE);
873
874   gtk_binding_entry_add_signal (binding_set, GDK_KP_Page_Down, GDK_CONTROL_MASK,
875                                 "page_horizontally", 2,
876                                 GTK_TYPE_INT, 1,
877                                 GTK_TYPE_BOOL, FALSE);
878
879   gtk_binding_entry_add_signal (binding_set, GDK_KP_Page_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK,
880                                 "page_horizontally", 2,
881                                 GTK_TYPE_INT, 1,
882                                 GTK_TYPE_BOOL, TRUE);
883   
884   /* Deleting text */
885   gtk_binding_entry_add_signal (binding_set, GDK_Delete, 0,
886                                 "delete_from_cursor", 2,
887                                 GTK_TYPE_ENUM, GTK_DELETE_CHARS,
888                                 GTK_TYPE_INT, 1);
889
890   gtk_binding_entry_add_signal (binding_set, GDK_KP_Delete, 0,
891                                 "delete_from_cursor", 2,
892                                 GTK_TYPE_ENUM, GTK_DELETE_CHARS,
893                                 GTK_TYPE_INT, 1);
894   
895   gtk_binding_entry_add_signal (binding_set, GDK_BackSpace, 0,
896                                 "delete_from_cursor", 2,
897                                 GTK_TYPE_ENUM, GTK_DELETE_CHARS,
898                                 GTK_TYPE_INT, -1);
899
900   gtk_binding_entry_add_signal (binding_set, GDK_Delete, GDK_CONTROL_MASK,
901                                 "delete_from_cursor", 2,
902                                 GTK_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
903                                 GTK_TYPE_INT, 1);
904
905   gtk_binding_entry_add_signal (binding_set, GDK_KP_Delete, GDK_CONTROL_MASK,
906                                 "delete_from_cursor", 2,
907                                 GTK_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
908                                 GTK_TYPE_INT, 1);
909   
910   gtk_binding_entry_add_signal (binding_set, GDK_BackSpace, GDK_CONTROL_MASK,
911                                 "delete_from_cursor", 2,
912                                 GTK_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
913                                 GTK_TYPE_INT, -1);
914
915   /* Cut/copy/paste */
916
917   gtk_binding_entry_add_signal (binding_set, GDK_x, GDK_CONTROL_MASK,
918                                 "cut_clipboard", 0);
919
920   gtk_binding_entry_add_signal (binding_set, GDK_c, GDK_CONTROL_MASK,
921                                 "copy_clipboard", 0);
922
923   gtk_binding_entry_add_signal (binding_set, GDK_v, GDK_CONTROL_MASK,
924                                 "paste_clipboard", 0);
925
926   /* Overwrite */
927   gtk_binding_entry_add_signal (binding_set, GDK_Insert, 0,
928                                 "toggle_overwrite", 0);
929   gtk_binding_entry_add_signal (binding_set, GDK_KP_Insert, 0,
930                                 "toggle_overwrite", 0);
931
932   /* Control-tab focus motion */
933   gtk_binding_entry_add_signal (binding_set, GDK_Tab, GDK_CONTROL_MASK,
934                                 "move_focus", 1,
935                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
936   gtk_binding_entry_add_signal (binding_set, GDK_KP_Tab, GDK_CONTROL_MASK,
937                                 "move_focus", 1,
938                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_FORWARD);
939   
940   gtk_binding_entry_add_signal (binding_set, GDK_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
941                                 "move_focus", 1,
942                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
943   gtk_binding_entry_add_signal (binding_set, GDK_KP_Tab, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
944                                 "move_focus", 1,
945                                 GTK_TYPE_DIRECTION_TYPE, GTK_DIR_TAB_BACKWARD);
946 }
947
948 static void
949 gtk_text_view_init (GtkTextView *text_view)
950 {
951   GtkWidget *widget;
952
953   widget = GTK_WIDGET (text_view);
954
955   GTK_WIDGET_SET_FLAGS (widget, GTK_CAN_FOCUS);
956
957   /* Set up default style */
958   text_view->wrap_mode = GTK_WRAP_NONE;
959   text_view->pixels_above_lines = 0;
960   text_view->pixels_below_lines = 0;
961   text_view->pixels_inside_wrap = 0;
962   text_view->justify = GTK_JUSTIFY_LEFT;
963   text_view->left_margin = 0;
964   text_view->right_margin = 0;
965   text_view->indent = 0;
966   text_view->tabs = NULL;
967   text_view->editable = TRUE;
968
969   gtk_drag_dest_set (widget,
970                      0,
971                      target_table, G_N_ELEMENTS (target_table),
972                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
973
974   text_view->virtual_cursor_x = -1;
975   text_view->virtual_cursor_y = -1;
976
977   /* This object is completely private. No external entity can gain a reference
978    * to it; so we create it here and destroy it in finalize ().
979    */
980   text_view->im_context = gtk_im_multicontext_new ();
981
982   g_signal_connect (G_OBJECT (text_view->im_context), "commit",
983                     G_CALLBACK (gtk_text_view_commit_handler), text_view);
984   g_signal_connect (G_OBJECT (text_view->im_context), "preedit_changed",
985                     G_CALLBACK (gtk_text_view_preedit_changed_handler), text_view);
986   g_signal_connect (G_OBJECT (text_view->im_context), "retrieve_surrounding",
987                     G_CALLBACK (gtk_text_view_retrieve_surrounding_handler), text_view);
988   g_signal_connect (G_OBJECT (text_view->im_context), "delete_surrounding",
989                     G_CALLBACK (gtk_text_view_delete_surrounding_handler), text_view);
990
991   text_view->cursor_visible = TRUE;
992
993   text_view->text_window = text_window_new (GTK_TEXT_WINDOW_TEXT,
994                                             widget, 200, 200);
995
996   text_view->drag_start_x = -1;
997   text_view->drag_start_y = -1;
998
999   text_view->pending_place_cursor_button = 0;
1000
1001   /* We handle all our own redrawing */
1002   gtk_widget_set_redraw_on_allocate (widget, FALSE);
1003 }
1004
1005 /**
1006  * gtk_text_view_new:
1007  *
1008  * Creates a new #GtkTextView. If you don't call gtk_text_view_set_buffer()
1009  * before using the text view, an empty default buffer will be created
1010  * for you. Get the buffer with gtk_text_view_get_buffer(). If you want
1011  * to specify your own buffer, consider gtk_text_view_new_with_buffer().
1012  *
1013  * Return value: a new #GtkTextView
1014  **/
1015 GtkWidget*
1016 gtk_text_view_new (void)
1017 {
1018   return GTK_WIDGET (gtk_type_new (gtk_text_view_get_type ()));
1019 }
1020
1021 /**
1022  * gtk_text_view_new_with_buffer:
1023  * @buffer: a #GtkTextBuffer
1024  *
1025  * Creates a new #GtkTextView widget displaying the buffer
1026  * @buffer. One buffer can be shared among many widgets.
1027  * @buffer may be NULL to create a default buffer, in which case
1028  * this function is equivalent to gtk_text_view_new(). The
1029  * text view adds its own reference count to the buffer; it does not
1030  * take over an existing reference.
1031  *
1032  * Return value: a new #GtkTextView.
1033  **/
1034 GtkWidget*
1035 gtk_text_view_new_with_buffer (GtkTextBuffer *buffer)
1036 {
1037   GtkTextView *text_view;
1038
1039   text_view = (GtkTextView*)gtk_text_view_new ();
1040
1041   gtk_text_view_set_buffer (text_view, buffer);
1042
1043   return GTK_WIDGET (text_view);
1044 }
1045
1046 /**
1047  * gtk_text_view_set_buffer:
1048  * @text_view: a #GtkTextView
1049  * @buffer: a #GtkTextBuffer
1050  *
1051  * Sets @buffer as the buffer being displayed by @text_view. The previous
1052  * buffer displayed by the text view is unreferenced, and a reference is
1053  * added to @buffer. If you owned a reference to @buffer before passing it
1054  * to this function, you must remove that reference yourself; #GtkTextView
1055  * will not "adopt" it.
1056  *
1057  **/
1058 void
1059 gtk_text_view_set_buffer (GtkTextView   *text_view,
1060                           GtkTextBuffer *buffer)
1061 {
1062   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1063   g_return_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer));
1064
1065   if (text_view->buffer == buffer)
1066     return;
1067
1068   if (text_view->buffer != NULL)
1069     {
1070       /* Destroy all anchored children */
1071       GSList *tmp_list;
1072       GSList *copy;
1073
1074       copy = g_slist_copy (text_view->children);
1075       tmp_list = copy;
1076       while (tmp_list != NULL)
1077         {
1078           GtkTextViewChild *vc = tmp_list->data;
1079
1080           if (vc->anchor)
1081             {
1082               gtk_widget_destroy (vc->widget);
1083               /* vc may now be invalid! */
1084             }
1085
1086           tmp_list = g_slist_next (tmp_list);
1087         }
1088
1089       g_slist_free (copy);
1090
1091       g_signal_handlers_disconnect_by_func (G_OBJECT (text_view->buffer),
1092                                             (gpointer) gtk_text_view_mark_set_handler, text_view);
1093       g_object_unref (G_OBJECT (text_view->buffer));
1094       text_view->dnd_mark = NULL;
1095
1096       if (GTK_WIDGET_REALIZED (text_view))
1097         {
1098           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1099                                                               GDK_SELECTION_PRIMARY);
1100           gtk_text_buffer_remove_selection_clipboard (text_view->buffer, clipboard);
1101         }
1102     }
1103
1104   text_view->buffer = buffer;
1105
1106   if (buffer != NULL)
1107     {
1108       GtkTextIter start;
1109
1110       g_object_ref (G_OBJECT (buffer));
1111
1112       if (text_view->layout)
1113         gtk_text_layout_set_buffer (text_view->layout, buffer);
1114
1115       gtk_text_buffer_get_iter_at_offset (text_view->buffer, &start, 0);
1116
1117       text_view->dnd_mark = gtk_text_buffer_create_mark (text_view->buffer,
1118                                                          "gtk_drag_target",
1119                                                          &start, FALSE);
1120
1121       text_view->first_para_mark = gtk_text_buffer_create_mark (text_view->buffer,
1122                                                                 NULL,
1123                                                                 &start, TRUE);
1124
1125       text_view->first_para_pixels = 0;
1126
1127       g_signal_connect (G_OBJECT (text_view->buffer), "mark_set",
1128                         G_CALLBACK (gtk_text_view_mark_set_handler), text_view);
1129
1130       if (GTK_WIDGET_REALIZED (text_view))
1131         {
1132           GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
1133                                                               GDK_SELECTION_PRIMARY);
1134           gtk_text_buffer_add_selection_clipboard (text_view->buffer, clipboard);
1135         }
1136     }
1137   
1138   if (GTK_WIDGET_VISIBLE (text_view))
1139     gtk_widget_queue_draw (GTK_WIDGET (text_view));
1140
1141   DV(g_print ("Invalidating due to set_buffer\n"));
1142   gtk_text_view_invalidate (text_view);
1143 }
1144
1145 static GtkTextBuffer*
1146 get_buffer (GtkTextView *text_view)
1147 {
1148   if (text_view->buffer == NULL)
1149     {
1150       GtkTextBuffer *b;
1151       b = gtk_text_buffer_new (NULL);
1152       gtk_text_view_set_buffer (text_view, b);
1153       g_object_unref (G_OBJECT (b));
1154     }
1155
1156   return text_view->buffer;
1157 }
1158
1159 /**
1160  * gtk_text_view_get_buffer:
1161  * @text_view: a #GtkTextView
1162  *
1163  * Returns the #GtkTextBuffer being displayed by this text view.
1164  * The reference count on the buffer is not incremented; the caller
1165  * of this function won't own a new reference.
1166  *
1167  * Return value: a #GtkTextBuffer
1168  **/
1169 GtkTextBuffer*
1170 gtk_text_view_get_buffer (GtkTextView *text_view)
1171 {
1172   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
1173
1174   return get_buffer (text_view);
1175 }
1176
1177 /**
1178  * gtk_text_view_get_iter_at_location:
1179  * @text_view: a #GtkTextView
1180  * @iter: a #GtkTextIter
1181  * @x: x position, in buffer coordinates
1182  * @y: y position, in buffer coordinates
1183  *
1184  * Retrieves the iterator at buffer coordinates @x and @y. Buffer
1185  * coordinates are coordinates for the entire buffer, not just the
1186  * currently-displayed portion.  If you have coordinates from an
1187  * event, you have to convert those to buffer coordinates with
1188  * gtk_text_view_window_to_buffer_coords().
1189  *
1190  **/
1191 void
1192 gtk_text_view_get_iter_at_location (GtkTextView *text_view,
1193                                     GtkTextIter *iter,
1194                                     gint         x,
1195                                     gint         y)
1196 {
1197   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1198   g_return_if_fail (iter != NULL);
1199
1200   gtk_text_view_ensure_layout (text_view);
1201   
1202   gtk_text_layout_get_iter_at_pixel (text_view->layout,
1203                                      iter,
1204                                      x,
1205                                      y);
1206 }
1207
1208 /**
1209  * gtk_text_view_get_iter_location:
1210  * @text_view: a #GtkTextView
1211  * @iter: a #GtkTextIter
1212  * @location: bounds of the character at @iter
1213  *
1214  * Gets a rectangle which roughly contains the character at @iter.
1215  * The rectangle position is in buffer coordinates; use
1216  * gtk_text_view_buffer_to_window_coords() to convert these
1217  * coordinates to coordinates for one of the windows in the text view.
1218  *
1219  **/
1220 void
1221 gtk_text_view_get_iter_location (GtkTextView       *text_view,
1222                                  const GtkTextIter *iter,
1223                                  GdkRectangle      *location)
1224 {
1225   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1226   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1227
1228   gtk_text_view_ensure_layout (text_view);
1229   
1230   gtk_text_layout_get_iter_location (text_view->layout, iter, location);
1231 }
1232
1233 /**
1234  * gtk_text_view_get_line_yrange:
1235  * @text_view: a #GtkTextView
1236  * @iter: a #GtkTextIter
1237  * @y: return location for a y coordinate
1238  * @height: return location for a height
1239  *
1240  * Gets the y coordinate of the top of the line containing @iter,
1241  * and the height of the line. The coordinate is a buffer coordinate;
1242  * convert to window coordinates with gtk_text_view_buffer_to_window_coords().
1243  *
1244  **/
1245 void
1246 gtk_text_view_get_line_yrange (GtkTextView       *text_view,
1247                                const GtkTextIter *iter,
1248                                gint              *y,
1249                                gint              *height)
1250 {
1251   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1252   g_return_if_fail (gtk_text_iter_get_buffer (iter) == get_buffer (text_view));
1253
1254   gtk_text_view_ensure_layout (text_view);
1255   
1256   gtk_text_layout_get_line_yrange (text_view->layout,
1257                                    iter,
1258                                    y,
1259                                    height);
1260 }
1261
1262 /**
1263  * gtk_text_view_get_line_at_y:
1264  * @text_view: a #GtkTextView
1265  * @target_iter: a #GtkTextIter
1266  * @y: a y coordinate
1267  * @line_top: return location for top coordinate of the line
1268  *
1269  * Gets the #GtkTextIter at the start of the line containing
1270  * the coordinate @y. @y is in buffer coordinates, convert from
1271  * window coordinates with gtk_text_view_window_to_buffer_coords().
1272  * If non-%NULL, @line_top will be filled with the coordinate of the top
1273  * edge of the line.
1274  **/
1275 void
1276 gtk_text_view_get_line_at_y (GtkTextView *text_view,
1277                              GtkTextIter *target_iter,
1278                              gint         y,
1279                              gint        *line_top)
1280 {
1281   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1282
1283   gtk_text_view_ensure_layout (text_view);
1284   
1285   gtk_text_layout_get_line_at_y (text_view->layout,
1286                                  target_iter,
1287                                  y,
1288                                  line_top);
1289 }
1290
1291 static gboolean
1292 set_adjustment_clamped (GtkAdjustment *adj, gdouble val)
1293 {
1294   DV (g_print ("  Setting adj to raw value %g\n", val));
1295   
1296   /* We don't really want to clamp to upper; we want to clamp to
1297      upper - page_size which is the highest value the scrollbar
1298      will let us reach. */
1299   if (val > (adj->upper - adj->page_size))
1300     val = adj->upper - adj->page_size;
1301
1302   if (val < adj->lower)
1303     val = adj->lower;
1304
1305   if (val != adj->value)
1306     {
1307       DV (g_print ("  Setting adj to clamped value %g\n", val));
1308       gtk_adjustment_set_value (adj, val);
1309       return TRUE;
1310     }
1311   else
1312     return FALSE;
1313 }
1314
1315 /**
1316  * gtk_text_view_scroll_to_iter:
1317  * @text_view: a #GtkTextView
1318  * @iter: a #GtkTextIter
1319  * @within_margin: margin as a [0.0,0.5) fraction of screen size
1320  * @use_align: whether to use alignment arguments (if %FALSE, just get the mark onscreen)
1321  * @xalign: horizontal alignment of mark within visible area.
1322  * @yalign: vertical alignment of mark within visible area
1323  *
1324  * Scrolls @text_view so that @iter is on the screen in the position
1325  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
1326  * left or top, 1.0 indicates right or bottom, 0.5 means center. If @use_align
1327  * is %FALSE, the text scrolls the minimal distance to get the mark onscreen,
1328  * possibly not scrolling at all. The effective screen for purposes
1329  * of this function is reduced by a margin of size @within_margin.
1330  * NOTE: This function uses the currently-computed height of the
1331  * lines in the text buffer. Note that line heights are computed
1332  * in an idle handler; so this function may not have the desired effect
1333  * if it's called before the height computations. To avoid oddness,
1334  * consider using gtk_text_view_scroll_to_mark() which saves a point
1335  * to be scrolled to after line validation.
1336  *
1337  * Return value: %TRUE if scrolling occurred
1338  **/
1339 gboolean
1340 gtk_text_view_scroll_to_iter (GtkTextView   *text_view,
1341                               GtkTextIter   *iter,
1342                               gdouble        within_margin,
1343                               gboolean       use_align,
1344                               gdouble        xalign,
1345                               gdouble        yalign)
1346 {
1347   GdkRectangle rect;
1348   GdkRectangle screen;
1349   gint screen_bottom;
1350   gint screen_right;
1351   gint scroll_dest;
1352   GtkWidget *widget;
1353   gboolean retval = FALSE;
1354   gint scroll_inc;
1355   gint screen_xoffset, screen_yoffset;
1356   gint current_x_scroll, current_y_scroll;
1357
1358   /* FIXME why don't we do the validate-at-scroll-destination thing
1359    * from flush_scroll in this function? I think it wasn't done before
1360    * because changed_handler was screwed up, but I could be wrong.
1361    */
1362   
1363   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1364   g_return_val_if_fail (iter != NULL, FALSE);
1365   g_return_val_if_fail (within_margin >= 0.0 && within_margin < 0.5, FALSE);
1366   g_return_val_if_fail (xalign >= 0.0 && xalign <= 1.0, FALSE);
1367   g_return_val_if_fail (yalign >= 0.0 && yalign <= 1.0, FALSE);
1368   
1369   widget = GTK_WIDGET (text_view);
1370
1371   DV(g_print(G_STRLOC"\n"));
1372   
1373   gtk_text_layout_get_iter_location (text_view->layout,
1374                                      iter,
1375                                      &rect);
1376
1377   DV (g_print (" target rect %d,%d  %d x %d\n", rect.x, rect.y, rect.width, rect.height));
1378   
1379   current_x_scroll = text_view->xoffset;
1380   current_y_scroll = text_view->yoffset;
1381
1382   screen.x = current_x_scroll;
1383   screen.y = current_y_scroll;
1384   screen.width = SCREEN_WIDTH (widget);
1385   screen.height = SCREEN_HEIGHT (widget);
1386   
1387   screen_xoffset = screen.width * within_margin;
1388   screen_yoffset = screen.height * within_margin;
1389   
1390   screen.x += screen_xoffset;
1391   screen.y += screen_yoffset;
1392   screen.width -= screen_xoffset * 2;
1393   screen.height -= screen_yoffset * 2;
1394
1395   /* paranoia check */
1396   if (screen.width < 1)
1397     screen.width = 1;
1398   if (screen.height < 1)
1399     screen.height = 1;
1400   
1401   screen_right = screen.x + screen.width;
1402   screen_bottom = screen.y + screen.height;
1403   
1404   /* The alignment affects the point in the target character that we
1405    * choose to align. If we're doing right/bottom alignment, we align
1406    * the right/bottom edge of the character the mark is at; if we're
1407    * doing left/top we align the left/top edge of the character; if
1408    * we're doing center alignment we align the center of the
1409    * character.
1410    */
1411   
1412   /* Vertical scroll */
1413
1414   scroll_inc = 0;
1415   scroll_dest = current_y_scroll;
1416   
1417   if (use_align)
1418     {      
1419       scroll_dest = rect.y + (rect.height * yalign) - (screen.height * yalign);
1420       
1421       /* if scroll_dest < screen.y, we move a negative increment (up),
1422        * else a positive increment (down)
1423        */
1424       scroll_inc = scroll_dest - screen.y + screen_yoffset;
1425     }
1426   else
1427     {
1428       /* move minimum to get onscreen */
1429       if (rect.y < screen.y)
1430         {
1431           scroll_dest = rect.y;
1432           scroll_inc = scroll_dest - screen.y - screen_yoffset;
1433         }
1434       else if ((rect.y + rect.height) > screen_bottom)
1435         {
1436           scroll_dest = rect.y + rect.height;
1437           scroll_inc = scroll_dest - screen_bottom + screen_yoffset;
1438         }
1439     }  
1440   
1441   if (scroll_inc != 0)
1442     {
1443       retval = set_adjustment_clamped (get_vadjustment (text_view),
1444                                        current_y_scroll + scroll_inc);
1445
1446       DV (g_print (" vert increment %d\n", scroll_inc));
1447     }
1448
1449   /* Horizontal scroll */
1450   
1451   scroll_inc = 0;
1452   scroll_dest = current_x_scroll;
1453   
1454   if (use_align)
1455     {      
1456       scroll_dest = rect.x + (rect.width * xalign) - (screen.width * xalign);
1457
1458       /* if scroll_dest < screen.y, we move a negative increment (left),
1459        * else a positive increment (right)
1460        */
1461       scroll_inc = scroll_dest - screen.x + screen_xoffset;
1462     }
1463   else
1464     {
1465       /* move minimum to get onscreen */
1466       if (rect.x < screen.x)
1467         {
1468           scroll_dest = rect.x;
1469           scroll_inc = scroll_dest - screen.x - screen_xoffset;
1470         }
1471       else if ((rect.x + rect.width) > screen_right)
1472         {
1473           scroll_dest = rect.x + rect.width;
1474           scroll_inc = scroll_dest - screen_right + screen_xoffset;
1475         }
1476     }
1477   
1478   if (scroll_inc != 0)
1479     {
1480       retval = set_adjustment_clamped (get_hadjustment (text_view),
1481                                        current_x_scroll + scroll_inc);
1482
1483       DV (g_print (" horiz increment %d\n", scroll_inc));
1484     }
1485   
1486   if (retval)
1487     DV(g_print (">Actually scrolled ("G_STRLOC")\n"));
1488   else
1489     DV(g_print (">Didn't end up scrolling ("G_STRLOC")\n"));
1490   
1491   return retval;
1492 }
1493
1494 static void
1495 free_pending_scroll (GtkTextPendingScroll *scroll)
1496 {
1497   if (!gtk_text_mark_get_deleted (scroll->mark))
1498     gtk_text_buffer_delete_mark (gtk_text_mark_get_buffer (scroll->mark),
1499                                  scroll->mark);
1500   g_object_unref (G_OBJECT (scroll->mark));
1501   g_free (scroll);
1502 }
1503
1504 static void
1505 gtk_text_view_queue_scroll (GtkTextView   *text_view,
1506                             GtkTextMark   *mark,
1507                             gdouble        within_margin,
1508                             gboolean       use_align,
1509                             gdouble        xalign,
1510                             gdouble        yalign)
1511 {
1512   GtkTextIter iter;
1513   GtkTextPendingScroll *scroll;
1514
1515   DV(g_print(G_STRLOC"\n"));
1516   
1517   scroll = g_new (GtkTextPendingScroll, 1);
1518
1519   scroll->within_margin = within_margin;
1520   scroll->use_align = use_align;
1521   scroll->xalign = xalign;
1522   scroll->yalign = yalign;
1523   
1524   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
1525
1526   scroll->mark = gtk_text_buffer_create_mark (get_buffer (text_view),
1527                                               NULL,
1528                                               &iter,
1529                                               gtk_text_mark_get_left_gravity (mark));
1530
1531   g_object_ref (G_OBJECT (scroll->mark));
1532   
1533   if (text_view->pending_scroll)
1534     free_pending_scroll (text_view->pending_scroll);
1535
1536   text_view->pending_scroll = scroll;
1537 }
1538
1539 static gboolean
1540 gtk_text_view_flush_scroll (GtkTextView *text_view)
1541 {
1542   GtkTextIter iter;
1543   GtkTextPendingScroll *scroll;
1544   gboolean retval;
1545   GtkWidget *widget;
1546
1547   widget = GTK_WIDGET (text_view);
1548   
1549   DV(g_print(G_STRLOC"\n"));
1550   
1551   if (text_view->pending_scroll == NULL)
1552     {
1553       DV (g_print ("in flush scroll, no pending scroll\n"));
1554       return FALSE;
1555     }
1556
1557   scroll = text_view->pending_scroll;
1558
1559   /* avoid recursion */
1560   text_view->pending_scroll = NULL;
1561   
1562   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, scroll->mark);
1563
1564   /* Validate area around the scroll destination, so the adjustment
1565    * can meaningfully point into that area. We must validate
1566    * enough area to be sure that after we scroll, everything onscreen
1567    * is valid; otherwise, validation will maintain the first para
1568    * in one place, but may push the target iter off the bottom of
1569    * the screen.
1570    */
1571   DV(g_print (">Validating scroll destination ("G_STRLOC")\n"));
1572   gtk_text_layout_validate_yrange (text_view->layout, &iter,
1573                                    - (widget->allocation.height * 2),
1574                                    widget->allocation.height * 2);
1575   
1576   DV(g_print (">Done validating scroll destination ("G_STRLOC")\n"));
1577
1578   /* Ensure we have updated width/height */
1579   gtk_text_view_update_adjustments (text_view);
1580   
1581   retval = gtk_text_view_scroll_to_iter (text_view,
1582                                          &iter,
1583                                          scroll->within_margin,
1584                                          scroll->use_align,
1585                                          scroll->xalign,
1586                                          scroll->yalign);
1587   
1588   free_pending_scroll (scroll);
1589
1590   return retval;
1591 }
1592
1593 static void
1594 gtk_text_view_set_adjustment_upper (GtkAdjustment *adj, gdouble upper)
1595 {  
1596   if (upper != adj->upper)
1597     {
1598       gdouble min = MAX (0.0, upper - adj->page_size);
1599       gboolean value_changed = FALSE;
1600
1601       adj->upper = upper;
1602
1603       if (adj->value > min)
1604         {
1605           adj->value = min;
1606           value_changed = TRUE;
1607         }
1608
1609       gtk_signal_emit_by_name (GTK_OBJECT (adj), "changed");
1610       DV(g_print(">Changed adj upper to %g ("G_STRLOC")\n", upper));
1611       
1612       if (value_changed)
1613         {
1614           DV(g_print(">Changed adj value because upper decreased ("G_STRLOC")\n"));
1615           gtk_signal_emit_by_name (GTK_OBJECT (adj), "value_changed");
1616         }
1617     }
1618 }
1619
1620 static void
1621 gtk_text_view_update_adjustments (GtkTextView *text_view)
1622 {
1623   gint width = 0, height = 0;
1624
1625   DV(g_print(">Updating adjustments ("G_STRLOC")\n"));
1626
1627   if (text_view->layout)
1628     gtk_text_layout_get_size (text_view->layout, &width, &height);
1629
1630   if (text_view->width != width || text_view->height != height)
1631     {
1632       text_view->width = width;
1633       text_view->height = height;
1634
1635       gtk_text_view_set_adjustment_upper (get_hadjustment (text_view),
1636                                           MAX (SCREEN_WIDTH (text_view), width));
1637       gtk_text_view_set_adjustment_upper (get_vadjustment (text_view),
1638                                           MAX (SCREEN_HEIGHT (text_view), height));
1639       
1640       /* hadj/vadj exist since we called get_hadjustment/get_vadjustment above */
1641
1642       /* Set up the step sizes; we'll say that a page is
1643          our allocation minus one step, and a step is
1644          1/10 of our allocation. */
1645       text_view->hadjustment->step_increment =
1646         SCREEN_WIDTH (text_view) / 10.0;
1647       text_view->hadjustment->page_increment =
1648         SCREEN_WIDTH (text_view) * 0.9;
1649       
1650       text_view->vadjustment->step_increment =
1651         SCREEN_HEIGHT (text_view) / 10.0;
1652       text_view->vadjustment->page_increment =
1653         SCREEN_HEIGHT (text_view) * 0.9;
1654
1655       gtk_signal_emit_by_name (GTK_OBJECT (get_hadjustment (text_view)), "changed");
1656       gtk_signal_emit_by_name (GTK_OBJECT (get_hadjustment (text_view)), "changed");
1657     }
1658 }
1659
1660 static void
1661 gtk_text_view_update_layout_width (GtkTextView *text_view)
1662 {
1663   DV(g_print(">Updating layout width ("G_STRLOC")\n"));
1664   
1665   gtk_text_view_ensure_layout (text_view);
1666
1667   gtk_text_layout_set_screen_width (text_view->layout,
1668                                     SCREEN_WIDTH (text_view));
1669 }
1670
1671 static void
1672 gtk_text_view_update_im_spot_location (GtkTextView *text_view)
1673 {
1674   GdkRectangle area;
1675   gint cursor_x_pos, cursor_y_pos;
1676
1677   if (text_view->layout == NULL)
1678     return;
1679   
1680   gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, &cursor_y_pos);
1681
1682   area.x = cursor_x_pos;
1683   area.y = cursor_y_pos;
1684   area.width = area.height = 0;
1685
1686   gtk_im_context_set_cursor_location (text_view->im_context, &area);
1687 }
1688
1689 /**
1690  * gtk_text_view_scroll_to_mark:
1691  * @text_view: a #GtkTextView
1692  * @mark: a #GtkTextMark
1693  * @within_margin: margin as a [0.0,0.5) fraction of screen size
1694  * @use_align: whether to use alignment arguments (if %FALSE, just get the mark onscreen)
1695  * @xalign: horizontal alignment of mark within visible area.
1696  * @yalign: vertical alignment of mark within visible area
1697  *
1698  * Scrolls @text_view so that @mark is on the screen in the position
1699  * indicated by @xalign and @yalign. An alignment of 0.0 indicates
1700  * left or top, 1.0 indicates right or bottom, 0.5 means center. If @use_align
1701  * is %FALSE, the text scrolls the minimal distance to get the mark onscreen,
1702  * possibly not scrolling at all. The effective screen for purposes
1703  * of this function is reduced by a margin of size @within_margin.
1704  *
1705  **/
1706 void
1707 gtk_text_view_scroll_to_mark (GtkTextView *text_view,
1708                               GtkTextMark *mark,
1709                               gdouble      within_margin,
1710                               gboolean     use_align,
1711                               gdouble      xalign,
1712                               gdouble      yalign)
1713 {  
1714   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1715   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
1716   g_return_if_fail (within_margin >= 0.0 && within_margin < 0.5);
1717   g_return_if_fail (xalign >= 0.0 && xalign <= 1.0);
1718   g_return_if_fail (yalign >= 0.0 && yalign <= 1.0);
1719
1720   gtk_text_view_queue_scroll (text_view, mark,
1721                               within_margin,
1722                               use_align,
1723                               xalign,
1724                               yalign);
1725
1726   /* If no validation is pending, we need to go ahead and force an
1727    * immediate scroll.
1728    */
1729   if (text_view->layout &&
1730       gtk_text_layout_is_valid (text_view->layout))
1731     gtk_text_view_flush_scroll (text_view);
1732 }
1733
1734 /**
1735  * gtk_text_view_scroll_mark_onscreen:
1736  * @text_view: a #GtkTextView
1737  * @mark: a mark in the buffer for @text_view
1738  * 
1739  * Scrolls @text_view the minimum distance such that @mark is contained
1740  * within the visible area of the widget.
1741  * 
1742  **/
1743 void
1744 gtk_text_view_scroll_mark_onscreen (GtkTextView *text_view,
1745                                     GtkTextMark *mark)
1746 {
1747   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1748   g_return_if_fail (GTK_IS_TEXT_MARK (mark));
1749
1750   gtk_text_view_scroll_to_mark (text_view, mark, 0.0, FALSE, 0.0, 0.0);
1751 }
1752
1753 static gboolean
1754 clamp_iter_onscreen (GtkTextView *text_view, GtkTextIter *iter)
1755 {
1756   GdkRectangle visible_rect;
1757   gtk_text_view_get_visible_rect (text_view, &visible_rect);
1758
1759   return gtk_text_layout_clamp_iter_to_vrange (text_view->layout, iter,
1760                                                visible_rect.y,
1761                                                visible_rect.y + visible_rect.height);
1762 }
1763
1764 /**
1765  * gtk_text_view_move_mark_onscreen:
1766  * @text_view: a #GtkTextView
1767  * @mark: a #GtkTextMark
1768  *
1769  * Moves a mark within the buffer so that it's
1770  * located within the currently-visible text area.
1771  *
1772  * Return value: %TRUE if the mark moved (wasn't already onscreen)
1773  **/
1774 gboolean
1775 gtk_text_view_move_mark_onscreen (GtkTextView *text_view,
1776                                   GtkTextMark *mark)
1777 {
1778   GtkTextIter iter;
1779
1780   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1781   g_return_val_if_fail (mark != NULL, FALSE);
1782
1783   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, mark);
1784
1785   if (clamp_iter_onscreen (text_view, &iter))
1786     {
1787       gtk_text_buffer_move_mark (get_buffer (text_view), mark, &iter);
1788       return TRUE;
1789     }
1790   else
1791     return FALSE;
1792 }
1793
1794 /**
1795  * gtk_text_view_get_visible_rect:
1796  * @text_view: a #GtkTextView
1797  * @visible_rect: rectangle to fill
1798  *
1799  * Fills @visible_rect with the currently-visible
1800  * region of the buffer, in buffer coordinates. Convert to window coordinates
1801  * with gtk_text_view_buffer_to_window_coords().
1802  **/
1803 void
1804 gtk_text_view_get_visible_rect (GtkTextView  *text_view,
1805                                 GdkRectangle *visible_rect)
1806 {
1807   GtkWidget *widget;
1808
1809   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1810
1811   widget = GTK_WIDGET (text_view);
1812
1813   if (visible_rect)
1814     {
1815       visible_rect->x = text_view->xoffset;
1816       visible_rect->y = text_view->yoffset;
1817       visible_rect->width = SCREEN_WIDTH (widget);
1818       visible_rect->height = SCREEN_HEIGHT (widget);
1819
1820       DV(g_print(" visible rect: %d,%d %d x %d\n",
1821                  visible_rect->x,
1822                  visible_rect->y,
1823                  visible_rect->width,
1824                  visible_rect->height));
1825     }
1826 }
1827
1828 /**
1829  * gtk_text_view_set_wrap_mode:
1830  * @text_view: a #GtkTextView
1831  * @wrap_mode: a #GtkWrapMode
1832  *
1833  * Sets the line wrapping for the view.
1834  **/
1835 void
1836 gtk_text_view_set_wrap_mode (GtkTextView *text_view,
1837                              GtkWrapMode  wrap_mode)
1838 {
1839   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1840
1841   if (text_view->wrap_mode != wrap_mode)
1842     {
1843       text_view->wrap_mode = wrap_mode;
1844
1845       if (text_view->layout)
1846         {
1847           text_view->layout->default_style->wrap_mode = wrap_mode;
1848           gtk_text_layout_default_style_changed (text_view->layout);
1849         }
1850     }
1851
1852   g_object_notify (G_OBJECT (text_view), "wrap_mode");
1853 }
1854
1855 /**
1856  * gtk_text_view_get_wrap_mode:
1857  * @text_view: a #GtkTextView
1858  *
1859  * Gets the line wrapping for the view.
1860  *
1861  * Return value: the line wrap setting
1862  **/
1863 GtkWrapMode
1864 gtk_text_view_get_wrap_mode (GtkTextView *text_view)
1865 {
1866   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_WRAP_NONE);
1867
1868   return text_view->wrap_mode;
1869 }
1870
1871 /**
1872  * gtk_text_view_set_editable:
1873  * @text_view: a #GtkTextView
1874  * @setting: whether it's editable
1875  *
1876  * Sets the default editability of the #GtkTextView. You can override
1877  * this default setting with tags in the buffer, using the "editable"
1878  * attribute of tags.
1879  **/
1880 void
1881 gtk_text_view_set_editable (GtkTextView *text_view,
1882                             gboolean     setting)
1883 {
1884   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1885   setting = setting != FALSE;
1886
1887   if (text_view->editable != setting)
1888     {
1889       text_view->editable = setting;
1890
1891       if (text_view->layout)
1892         {
1893           text_view->layout->default_style->editable = text_view->editable;
1894           gtk_text_layout_default_style_changed (text_view->layout);
1895         }
1896
1897       g_object_notify (G_OBJECT (text_view), "editable");
1898     }
1899 }
1900
1901 /**
1902  * gtk_text_view_get_editable:
1903  * @text_view: a #GtkTextView
1904  *
1905  * Returns the default editability of the #GtkTextView. Tags in the
1906  * buffer may override this setting for some ranges of text.
1907  *
1908  * Return value: whether text is editable by default
1909  **/
1910 gboolean
1911 gtk_text_view_get_editable (GtkTextView *text_view)
1912 {
1913   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
1914
1915   return text_view->editable;
1916 }
1917
1918 /**
1919  * gtk_text_view_set_pixels_above_lines:
1920  * @text_view: a #GtkTextView
1921  * @pixels_above_lines: pixels above paragraphs
1922  * 
1923  * Sets the default number of blank pixels above paragraphs in @text_view.
1924  * Tags in the buffer for @text_view may override the defaults.
1925  * 
1926  **/
1927 void
1928 gtk_text_view_set_pixels_above_lines (GtkTextView *text_view,
1929                                       gint         pixels_above_lines)
1930 {
1931   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1932
1933   if (text_view->pixels_above_lines != pixels_above_lines)
1934     {
1935       text_view->pixels_above_lines = pixels_above_lines;
1936
1937       if (text_view->layout)
1938         {
1939           text_view->layout->default_style->pixels_above_lines = pixels_above_lines;
1940           gtk_text_layout_default_style_changed (text_view->layout);
1941         }
1942
1943       g_object_notify (G_OBJECT (text_view), "pixels_above_lines");
1944     }
1945 }
1946
1947 /**
1948  * gtk_text_view_get_pixels_above_lines:
1949  * @text_view: a #GtkTextView
1950  * 
1951  * Gets the default number of pixels to put above paragraphs.
1952  * 
1953  * Return value: default number of pixels above paragraphs
1954  **/
1955 gint
1956 gtk_text_view_get_pixels_above_lines (GtkTextView *text_view)
1957 {
1958   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
1959
1960   return text_view->pixels_above_lines;
1961 }
1962
1963 /**
1964  * gtk_text_view_set_pixels_below_lines:
1965  * @text_view: a #GtkTextView
1966  * @pixels_below_lines: pixels below paragraphs 
1967  *
1968  * Sets the default number of pixels of blank space
1969  * to put below paragraphs in @text_view. May be overridden
1970  * by tags applied to @text_view's buffer. 
1971  * 
1972  **/
1973 void
1974 gtk_text_view_set_pixels_below_lines (GtkTextView *text_view,
1975                                       gint         pixels_below_lines)
1976 {
1977   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
1978
1979   if (text_view->pixels_below_lines != pixels_below_lines)
1980     {
1981       text_view->pixels_below_lines = pixels_below_lines;
1982
1983       if (text_view->layout)
1984         {
1985           text_view->layout->default_style->pixels_below_lines = pixels_below_lines;
1986           gtk_text_layout_default_style_changed (text_view->layout);
1987         }
1988
1989       g_object_notify (G_OBJECT (text_view), "pixels_below_lines");
1990     }
1991 }
1992
1993 /**
1994  * gtk_text_view_get_pixels_below_lines:
1995  * @text_view: a #GtkTextView
1996  * 
1997  * Gets the value set by gtk_text_view_set_pixels_below_lines().
1998  * 
1999  * Return value: default number of blank pixels below paragraphs
2000  **/
2001 gint
2002 gtk_text_view_get_pixels_below_lines (GtkTextView *text_view)
2003 {
2004   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2005
2006   return text_view->pixels_below_lines;
2007 }
2008
2009 /**
2010  * gtk_text_view_set_pixels_inside_wrap:
2011  * @text_view: a #GtkTextView
2012  * @pixels_inside_wrap: default number of pixels between wrapped lines
2013  *
2014  * Sets the default number of pixels of blank space to leave between
2015  * display/wrapped lines within a paragraph. May be overridden by
2016  * tags in @text_view's buffer.
2017  * 
2018  **/
2019 void
2020 gtk_text_view_set_pixels_inside_wrap (GtkTextView *text_view,
2021                                       gint         pixels_inside_wrap)
2022 {
2023   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2024
2025   if (text_view->pixels_inside_wrap != pixels_inside_wrap)
2026     {
2027       text_view->pixels_inside_wrap = pixels_inside_wrap;
2028
2029       if (text_view->layout)
2030         {
2031           text_view->layout->default_style->pixels_inside_wrap = pixels_inside_wrap;
2032           gtk_text_layout_default_style_changed (text_view->layout);
2033         }
2034
2035       g_object_notify (G_OBJECT (text_view), "pixels_inside_wrap");
2036     }
2037 }
2038
2039 /**
2040  * gtk_text_view_get_pixels_inside_wrap:
2041  * @text_view: a #GtkTextView
2042  * 
2043  * Gets the value set by gtk_text_view_set_pixels_inside_wrap().
2044  * 
2045  * Return value: default number of pixels of blank space between wrapped lines
2046  **/
2047 gint
2048 gtk_text_view_get_pixels_inside_wrap (GtkTextView *text_view)
2049 {
2050   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2051
2052   return text_view->pixels_inside_wrap;
2053 }
2054
2055 /**
2056  * gtk_text_view_set_justification:
2057  * @text_view: a #GtkTextView
2058  * @justification: justification
2059  *
2060  * Sets the default justification of text in @text_view.
2061  * Tags in the view's buffer may override the default.
2062  * 
2063  **/
2064 void
2065 gtk_text_view_set_justification (GtkTextView     *text_view,
2066                                  GtkJustification justification)
2067 {
2068   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2069
2070   if (text_view->justify != justification)
2071     {
2072       text_view->justify = justification;
2073
2074       if (text_view->layout)
2075         {
2076           text_view->layout->default_style->justification = justification;
2077           gtk_text_layout_default_style_changed (text_view->layout);
2078         }
2079
2080       g_object_notify (G_OBJECT (text_view), "justification");
2081     }
2082 }
2083
2084 /**
2085  * gtk_text_view_get_justification:
2086  * @text_view: a #GtkTextView
2087  * 
2088  * Gets the default justification of paragraphs in @text_view.
2089  * Tags in the buffer may override the default.
2090  * 
2091  * Return value: default justification
2092  **/
2093 GtkJustification
2094 gtk_text_view_get_justification (GtkTextView *text_view)
2095 {
2096   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), GTK_JUSTIFY_LEFT);
2097
2098   return text_view->justify;
2099 }
2100
2101 /**
2102  * gtk_text_view_set_left_margin:
2103  * @text_view: a #GtkTextView
2104  * @left_margin: left margin in pixels
2105  * 
2106  * Sets the default left margin for text in @text_view.
2107  * Tags in the buffer may override the default.
2108  * 
2109  **/
2110 void
2111 gtk_text_view_set_left_margin (GtkTextView *text_view,
2112                                gint         left_margin)
2113 {
2114   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2115
2116   if (text_view->left_margin != left_margin)
2117     {
2118       text_view->left_margin = left_margin;
2119
2120       if (text_view->layout)
2121         {
2122           text_view->layout->default_style->left_margin = left_margin;
2123           gtk_text_layout_default_style_changed (text_view->layout);
2124         }
2125
2126       g_object_notify (G_OBJECT (text_view), "left_margin");
2127     }
2128 }
2129
2130 /**
2131  * gtk_text_view_get_left_margin:
2132  * @text_view: a #GtkTextView
2133  * 
2134  * Gets the default left margin size of paragraphs in the @text_view.
2135  * Tags in the buffer may override the default.
2136  * 
2137  * Return value: left margin in pixels
2138  **/
2139 gint
2140 gtk_text_view_get_left_margin (GtkTextView *text_view)
2141 {
2142   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2143
2144   return text_view->left_margin;
2145 }
2146
2147 /**
2148  * gtk_text_view_set_right_margin:
2149  * @text_view: a #GtkTextView
2150  * @right_margin: right margin in pixels
2151  *
2152  * Sets the default right margin for text in the text view.
2153  * Tags in the buffer may override the default.
2154  * 
2155  **/
2156 void
2157 gtk_text_view_set_right_margin (GtkTextView *text_view,
2158                                 gint         right_margin)
2159 {
2160   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2161
2162   if (text_view->right_margin != right_margin)
2163     {
2164       text_view->right_margin = right_margin;
2165
2166       if (text_view->layout)
2167         {
2168           text_view->layout->default_style->right_margin = right_margin;
2169           gtk_text_layout_default_style_changed (text_view->layout);
2170         }
2171
2172       g_object_notify (G_OBJECT (text_view), "right_margin");
2173     }
2174 }
2175
2176 /**
2177  * gtk_text_view_get_right_margin:
2178  * @text_view: a #GtkTextView
2179  * 
2180  * Gets the default right margin for text in @text_view. Tags
2181  * in the buffer may override the default.
2182  * 
2183  * Return value: right margin in pixels
2184  **/
2185 gint
2186 gtk_text_view_get_right_margin (GtkTextView *text_view)
2187 {
2188   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2189
2190   return text_view->right_margin;
2191 }
2192
2193 /**
2194  * gtk_text_view_set_indent:
2195  * @text_view: a #GtkTextView
2196  * @indent: indentation in pixels
2197  *
2198  * Sets the default indentation for paragraphs in @text_view.
2199  * Tags in the buffer may override the default.
2200  * 
2201  **/
2202 void
2203 gtk_text_view_set_indent (GtkTextView *text_view,
2204                           gint         indent)
2205 {
2206   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2207
2208   if (text_view->indent != indent)
2209     {
2210       text_view->indent = indent;
2211
2212       if (text_view->layout)
2213         {
2214           text_view->layout->default_style->indent = indent;
2215           gtk_text_layout_default_style_changed (text_view->layout);
2216         }
2217
2218       g_object_notify (G_OBJECT (text_view), "indent");
2219     }
2220 }
2221
2222 /**
2223  * gtk_text_view_get_indent:
2224  * @text_view: a #GtkTextView
2225  * 
2226  * Gets the default indentation of paragraphs in @text_view.
2227  * Tags in the view's buffer may override the default.
2228  * The indentation may be negative.
2229  * 
2230  * Return value: number of pixels of indentation
2231  **/
2232 gint
2233 gtk_text_view_get_indent (GtkTextView *text_view)
2234 {
2235   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
2236
2237   return text_view->indent;
2238 }
2239
2240 /**
2241  * gtk_text_view_set_tabs:
2242  * @text_view: a #GtkTextView
2243  * @tabs: tabs as a #PangoTabArray
2244  *
2245  * Sets the default tab stops for paragraphs in @text_view.
2246  * Tags in the buffer may override the default.
2247  * 
2248  **/
2249 void
2250 gtk_text_view_set_tabs (GtkTextView   *text_view,
2251                         PangoTabArray *tabs)
2252 {
2253   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2254
2255   if (text_view->tabs)
2256     pango_tab_array_free (text_view->tabs);
2257
2258   text_view->tabs = tabs ? pango_tab_array_copy (tabs) : NULL;
2259
2260   if (text_view->layout)
2261     {
2262       /* some unkosher futzing in internal struct details... */
2263       if (text_view->layout->default_style->tabs)
2264         pango_tab_array_free (text_view->layout->default_style->tabs);
2265
2266       text_view->layout->default_style->tabs =
2267         text_view->tabs ? pango_tab_array_copy (text_view->tabs) : NULL;
2268
2269       gtk_text_layout_default_style_changed (text_view->layout);
2270     }
2271
2272   g_object_notify (G_OBJECT (text_view), "tabs");
2273 }
2274
2275 /**
2276  * gtk_text_view_get_tabs:
2277  * @text_view: a #GtkTextView
2278  * 
2279  * Gets the default tabs for @text_view. Tags in the buffer may
2280  * override the defaults. The returned array will be %NULL if
2281  * "standard" (8-space) tabs are used. Free the return value
2282  * with pango_tab_array_free().
2283  * 
2284  * Return value: copy of default tab array, or %NULL if "standard" tabs are used; must be freed with pango_tab_array_free().
2285  **/
2286 PangoTabArray*
2287 gtk_text_view_get_tabs (GtkTextView *text_view)
2288 {
2289   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
2290
2291   return text_view->tabs ? pango_tab_array_copy (text_view->tabs) : NULL;
2292 }
2293
2294 /**
2295  * gtk_text_view_set_cursor_visible:
2296  * @text_view: a #GtkTextView
2297  * @setting: whether to show the insertion cursor
2298  *
2299  * Toggles whether the insertion point is displayed. A buffer with no editable
2300  * text probably shouldn't have a visible cursor, so you may want to turn
2301  * the cursor off.
2302  **/
2303 void
2304 gtk_text_view_set_cursor_visible    (GtkTextView   *text_view,
2305                                      gboolean       setting)
2306 {
2307   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
2308
2309   setting = (setting != FALSE);
2310
2311   if (text_view->cursor_visible != setting)
2312     {
2313       text_view->cursor_visible = setting;
2314
2315       if (GTK_WIDGET_HAS_FOCUS (text_view))
2316         {
2317           if (text_view->layout)
2318             {
2319               gtk_text_layout_set_cursor_visible (text_view->layout, setting);
2320               gtk_text_view_check_cursor_blink (text_view);
2321             }
2322         }
2323
2324       g_object_notify (G_OBJECT (text_view), "cursor_visible");
2325     }
2326 }
2327
2328 /**
2329  * gtk_text_view_get_cursor_visible:
2330  * @text_view: a #GtkTextView
2331  *
2332  * Find out whether the cursor is being displayed.
2333  *
2334  * Return value: whether the insertion mark is visible
2335  **/
2336 gboolean
2337 gtk_text_view_get_cursor_visible    (GtkTextView   *text_view)
2338 {
2339   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2340
2341   return text_view->cursor_visible;
2342 }
2343
2344
2345 /**
2346  * gtk_text_view_place_cursor_onscreen:
2347  * @text_view: a #GtkTextView
2348  *
2349  * Moves the cursor to the currently visible region of the
2350  * buffer, it it isn't there already.
2351  *
2352  * Return value: TRUE if the cursor had to be moved.
2353  **/
2354 gboolean
2355 gtk_text_view_place_cursor_onscreen (GtkTextView *text_view)
2356 {
2357   GtkTextIter insert;
2358
2359   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
2360
2361   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
2362                                     gtk_text_buffer_get_mark (get_buffer (text_view),
2363                                                               "insert"));
2364
2365   if (clamp_iter_onscreen (text_view, &insert))
2366     {
2367       gtk_text_buffer_place_cursor (get_buffer (text_view), &insert);
2368       return TRUE;
2369     }
2370   else
2371     return FALSE;
2372 }
2373
2374 static void
2375 gtk_text_view_remove_validate_idles (GtkTextView *text_view)
2376 {
2377   if (text_view->first_validate_idle != 0)
2378     {
2379       DV (g_print ("Removing first validate idle: %s\n", G_STRLOC));
2380       g_source_remove (text_view->first_validate_idle);
2381       text_view->first_validate_idle = 0;
2382     }
2383
2384   if (text_view->incremental_validate_idle != 0)
2385     {
2386       g_source_remove (text_view->incremental_validate_idle);
2387       text_view->incremental_validate_idle = 0;
2388     }
2389 }
2390
2391 static void
2392 gtk_text_view_destroy (GtkObject *object)
2393 {
2394   GtkTextView *text_view;
2395   GtkTextLayout *layout;
2396   
2397   text_view = GTK_TEXT_VIEW (object);
2398
2399   layout = text_view->layout;
2400   
2401   gtk_text_view_remove_validate_idles (text_view);
2402   gtk_text_view_set_buffer (text_view, NULL);
2403   gtk_text_view_destroy_layout (text_view);
2404
2405   (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
2406 }
2407
2408 static void
2409 gtk_text_view_finalize (GObject *object)
2410 {
2411   GtkTextView *text_view;
2412
2413   text_view = GTK_TEXT_VIEW (object);
2414
2415   g_return_if_fail (text_view->buffer == NULL);
2416
2417   gtk_text_view_destroy_layout (text_view);
2418   gtk_text_view_set_buffer (text_view, NULL);
2419   
2420   if (text_view->pending_scroll)
2421     {
2422       free_pending_scroll (text_view->pending_scroll);
2423       text_view->pending_scroll = NULL;
2424     }
2425
2426   if (text_view->tabs)
2427     pango_tab_array_free (text_view->tabs);
2428   
2429   if (text_view->hadjustment)
2430     g_object_unref (G_OBJECT (text_view->hadjustment));
2431   if (text_view->vadjustment)
2432     g_object_unref (G_OBJECT (text_view->vadjustment));
2433
2434   text_window_free (text_view->text_window);
2435
2436   if (text_view->left_window)
2437     text_window_free (text_view->left_window);
2438
2439   if (text_view->top_window)
2440     text_window_free (text_view->top_window);
2441
2442   if (text_view->right_window)
2443     text_window_free (text_view->right_window);
2444
2445   if (text_view->bottom_window)
2446     text_window_free (text_view->bottom_window);
2447
2448   g_object_unref (G_OBJECT (text_view->im_context));
2449   
2450   (* G_OBJECT_CLASS (parent_class)->finalize) (object);
2451 }
2452
2453 static void
2454 gtk_text_view_set_property (GObject         *object,
2455                             guint            prop_id,
2456                             const GValue    *value,
2457                             GParamSpec      *pspec)
2458 {
2459   GtkTextView *text_view;
2460
2461   text_view = GTK_TEXT_VIEW (object);
2462
2463   switch (prop_id)
2464     {
2465     case PROP_PIXELS_ABOVE_LINES:
2466       gtk_text_view_set_pixels_above_lines (text_view, g_value_get_int (value));
2467       break;
2468
2469     case PROP_PIXELS_BELOW_LINES:
2470       gtk_text_view_set_pixels_below_lines (text_view, g_value_get_int (value));
2471       break;
2472
2473     case PROP_PIXELS_INSIDE_WRAP:
2474       gtk_text_view_set_pixels_inside_wrap (text_view, g_value_get_int (value));
2475       break;
2476
2477     case PROP_EDITABLE:
2478       gtk_text_view_set_editable (text_view, g_value_get_boolean (value));
2479       break;
2480
2481     case PROP_WRAP_MODE:
2482       gtk_text_view_set_wrap_mode (text_view, g_value_get_enum (value));
2483       break;
2484       
2485     case PROP_JUSTIFICATION:
2486       gtk_text_view_set_justification (text_view, g_value_get_enum (value));
2487       break;
2488
2489     case PROP_LEFT_MARGIN:
2490       gtk_text_view_set_left_margin (text_view, g_value_get_int (value));
2491       break;
2492
2493     case PROP_RIGHT_MARGIN:
2494       gtk_text_view_set_right_margin (text_view, g_value_get_int (value));
2495       break;
2496
2497     case PROP_INDENT:
2498       gtk_text_view_set_indent (text_view, g_value_get_int (value));
2499       break;
2500
2501     case PROP_TABS:
2502       gtk_text_view_set_tabs (text_view, g_value_get_boxed (value));
2503       break;
2504
2505     case PROP_CURSOR_VISIBLE:
2506       gtk_text_view_set_cursor_visible (text_view, g_value_get_boolean (value));
2507       break;
2508
2509     default:
2510       g_assert_not_reached ();
2511       break;
2512     }
2513 }
2514
2515 static void
2516 gtk_text_view_get_property (GObject         *object,
2517                             guint            prop_id,
2518                             GValue          *value,
2519                             GParamSpec      *pspec)
2520 {
2521   GtkTextView *text_view;
2522
2523   text_view = GTK_TEXT_VIEW (object);
2524
2525   switch (prop_id)
2526     {
2527     case PROP_PIXELS_ABOVE_LINES:
2528       g_value_set_int (value, text_view->pixels_above_lines);
2529       break;
2530
2531     case PROP_PIXELS_BELOW_LINES:
2532       g_value_set_int (value, text_view->pixels_below_lines);
2533       break;
2534
2535     case PROP_PIXELS_INSIDE_WRAP:
2536       g_value_set_int (value, text_view->pixels_inside_wrap);
2537       break;
2538
2539     case PROP_EDITABLE:
2540       g_value_set_boolean (value, text_view->editable);
2541       break;
2542       
2543     case PROP_WRAP_MODE:
2544       g_value_set_enum (value, text_view->wrap_mode);
2545       break;
2546
2547     case PROP_JUSTIFICATION:
2548       g_value_set_enum (value, text_view->justify);
2549       break;
2550
2551     case PROP_LEFT_MARGIN:
2552       g_value_set_int (value, text_view->left_margin);
2553       break;
2554
2555     case PROP_RIGHT_MARGIN:
2556       g_value_set_int (value, text_view->right_margin);
2557       break;
2558
2559     case PROP_INDENT:
2560       g_value_set_int (value, text_view->indent);
2561       break;
2562
2563     case PROP_TABS:
2564       g_value_set_boxed (value, text_view->tabs);
2565       break;
2566
2567     case PROP_CURSOR_VISIBLE:
2568       g_value_set_boolean (value, text_view->cursor_visible);
2569       break;
2570
2571     default:
2572       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2573       break;
2574     }
2575 }
2576
2577 static void
2578 gtk_text_view_size_request (GtkWidget      *widget,
2579                             GtkRequisition *requisition)
2580 {
2581   GtkTextView *text_view;
2582   GSList *tmp_list;
2583   gint focus_edge_width;
2584   gint focus_width;
2585   gboolean interior_focus;
2586   
2587   text_view = GTK_TEXT_VIEW (widget);
2588
2589   gtk_widget_style_get (widget,
2590                         "interior_focus", &interior_focus,
2591                         "focus_line_width", &focus_width,
2592                         NULL);
2593
2594   if (interior_focus)
2595     focus_edge_width = 0;
2596   else
2597     focus_edge_width = focus_width;
2598
2599   if (text_view->layout)
2600     {
2601       text_view->text_window->requisition.width = text_view->layout->width;
2602       text_view->text_window->requisition.height = text_view->layout->height;
2603     }
2604   else
2605     {
2606       text_view->text_window->requisition.width = 0;
2607       text_view->text_window->requisition.height = 0;
2608     }
2609   
2610   requisition->width = text_view->text_window->requisition.width + focus_edge_width * 2;
2611   requisition->height = text_view->text_window->requisition.height + focus_edge_width * 2;
2612
2613   if (text_view->left_window)
2614     requisition->width += text_view->left_window->requisition.width;
2615
2616   if (text_view->right_window)
2617     requisition->width += text_view->right_window->requisition.width;
2618
2619   if (text_view->top_window)
2620     requisition->height += text_view->top_window->requisition.height;
2621
2622   if (text_view->bottom_window)
2623     requisition->height += text_view->bottom_window->requisition.height;
2624
2625   requisition->width += GTK_CONTAINER (text_view)->border_width * 2;
2626   requisition->height += GTK_CONTAINER (text_view)->border_width * 2;
2627   
2628   tmp_list = text_view->children;
2629   while (tmp_list != NULL)
2630     {
2631       GtkTextViewChild *child = tmp_list->data;
2632
2633       if (child->anchor)
2634         {
2635           GtkRequisition child_req;
2636           GtkRequisition old_req;
2637
2638           gtk_widget_get_child_requisition (child->widget, &old_req);
2639           
2640           gtk_widget_size_request (child->widget, &child_req);
2641
2642           gtk_widget_get_child_requisition (child->widget, &child_req);
2643
2644           /* Invalidate layout lines if required */
2645           if (text_view->layout &&
2646               (old_req.width != child_req.width ||
2647                old_req.height != child_req.height))
2648             gtk_text_child_anchor_queue_resize (child->anchor,
2649                                                 text_view->layout);
2650         }
2651       else
2652         {
2653           GtkRequisition child_req;
2654           
2655           gtk_widget_size_request (child->widget, &child_req);
2656         }
2657
2658       tmp_list = g_slist_next (tmp_list);
2659     }
2660 }
2661
2662 static void
2663 gtk_text_view_compute_child_allocation (GtkTextView      *text_view,
2664                                         GtkTextViewChild *vc,
2665                                         GtkAllocation    *allocation)
2666 {
2667   gint buffer_y;
2668   GtkTextIter iter;
2669   GtkRequisition req;
2670   
2671   gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
2672                                             &iter,
2673                                             vc->anchor);
2674
2675   gtk_text_layout_get_line_yrange (text_view->layout, &iter,
2676                                    &buffer_y, NULL);
2677
2678   buffer_y += vc->from_top_of_line;
2679
2680   allocation->x = vc->from_left_of_buffer - text_view->xoffset;
2681   allocation->y = buffer_y - text_view->yoffset;
2682
2683   gtk_widget_get_child_requisition (vc->widget, &req);
2684   allocation->width = req.width;
2685   allocation->height = req.height;
2686 }
2687
2688 static void
2689 gtk_text_view_update_child_allocation (GtkTextView      *text_view,
2690                                        GtkTextViewChild *vc)
2691 {
2692   GtkAllocation allocation;
2693
2694   gtk_text_view_compute_child_allocation (text_view, vc, &allocation);
2695   
2696   gtk_widget_size_allocate (vc->widget, &allocation);
2697
2698 #if 0
2699   g_print ("allocation for %p allocated to %d,%d yoffset = %d\n",
2700            vc->widget,
2701            vc->widget->allocation.x,
2702            vc->widget->allocation.y,
2703            text_view->yoffset);
2704 #endif
2705 }
2706
2707 static void
2708 gtk_text_view_child_allocated (GtkTextLayout *layout,
2709                                GtkWidget     *child,
2710                                gint           x,
2711                                gint           y,
2712                                gpointer       data)
2713 {
2714   GtkTextViewChild *vc = NULL;
2715   GtkTextView *text_view = data;
2716   
2717   /* x,y is the position of the child from the top of the line, and
2718    * from the left of the buffer. We have to translate that into text
2719    * window coordinates, then size_allocate the child.
2720    */
2721
2722   vc = g_object_get_data (G_OBJECT (child),
2723                           "gtk-text-view-child");
2724
2725   g_assert (vc != NULL);
2726
2727   DV (g_print ("child allocated at %d,%d\n", x, y));
2728   
2729   vc->from_left_of_buffer = x;
2730   vc->from_top_of_line = y;
2731
2732   gtk_text_view_update_child_allocation (text_view, vc);
2733 }
2734
2735 static void
2736 gtk_text_view_allocate_children (GtkTextView *text_view)
2737 {
2738   GSList *tmp_list;
2739
2740   DV(g_print(G_STRLOC"\n"));
2741   
2742   tmp_list = text_view->children;
2743   while (tmp_list != NULL)
2744     {
2745       GtkTextViewChild *child = tmp_list->data;
2746
2747       if (child->anchor)
2748         {
2749           /* We need to force-validate the regions containing
2750            * children.
2751            */
2752           GtkTextIter child_loc;
2753           gtk_text_buffer_get_iter_at_child_anchor (get_buffer (text_view),
2754                                                     &child_loc,
2755                                                     child->anchor);
2756
2757           gtk_text_layout_validate_yrange (text_view->layout,
2758                                            &child_loc,
2759                                            0, 1);
2760         }
2761       else
2762         {
2763           GtkAllocation allocation;          
2764           GtkRequisition child_req;
2765              
2766           g_assert (child != NULL);
2767           
2768           allocation.x = child->x;
2769           allocation.y = child->y;
2770
2771           gtk_widget_get_child_requisition (child->widget, &child_req);
2772           
2773           allocation.width = child_req.width;
2774           allocation.height = child_req.height;
2775           
2776           gtk_widget_size_allocate (child->widget, &allocation);          
2777         }
2778
2779       tmp_list = g_slist_next (tmp_list);
2780     }
2781 }
2782
2783 static void
2784 gtk_text_view_size_allocate (GtkWidget *widget,
2785                              GtkAllocation *allocation)
2786 {
2787   GtkTextView *text_view;
2788   GtkTextIter first_para;
2789   gint y;
2790   GtkAdjustment *vadj;
2791   gboolean yoffset_changed = FALSE;
2792   gint width, height;
2793   GdkRectangle text_rect;
2794   GdkRectangle left_rect;
2795   GdkRectangle right_rect;
2796   GdkRectangle top_rect;
2797   GdkRectangle bottom_rect;
2798   gint focus_edge_width;
2799   gint focus_width;
2800   gboolean interior_focus;
2801   gboolean size_changed;
2802   
2803   text_view = GTK_TEXT_VIEW (widget);
2804
2805   DV(g_print(G_STRLOC"\n"));
2806
2807   size_changed =
2808     widget->allocation.width != allocation->width ||
2809     widget->allocation.height != allocation->height;
2810   
2811   widget->allocation = *allocation;
2812
2813   if (GTK_WIDGET_REALIZED (widget))
2814     {
2815       gdk_window_move_resize (widget->window,
2816                               allocation->x, allocation->y,
2817                               allocation->width, allocation->height);
2818     }
2819
2820   /* distribute width/height among child windows. Ensure all
2821    * windows get at least a 1x1 allocation.
2822    */
2823
2824   gtk_widget_style_get (widget,
2825                         "interior_focus", &interior_focus,
2826                         "focus_line_width", &focus_width,
2827                         NULL);
2828
2829   if (interior_focus)
2830     focus_edge_width = 0;
2831   else
2832     focus_edge_width = focus_width;
2833   
2834   width = allocation->width - focus_edge_width * 2 - GTK_CONTAINER (text_view)->border_width * 2;
2835
2836   if (text_view->left_window)
2837     left_rect.width = text_view->left_window->requisition.width;
2838   else
2839     left_rect.width = 0;
2840
2841   width -= left_rect.width;
2842
2843   if (text_view->right_window)
2844     right_rect.width = text_view->right_window->requisition.width;
2845   else
2846     right_rect.width = 0;
2847
2848   width -= right_rect.width;
2849
2850   text_rect.width = MAX (1, width);
2851
2852   top_rect.width = text_rect.width;
2853   bottom_rect.width = text_rect.width;
2854
2855
2856   height = allocation->height - focus_edge_width * 2 - GTK_CONTAINER (text_view)->border_width * 2;
2857
2858   if (text_view->top_window)
2859     top_rect.height = text_view->top_window->requisition.height;
2860   else
2861     top_rect.height = 0;
2862
2863   height -= top_rect.height;
2864
2865   if (text_view->bottom_window)
2866     bottom_rect.height = text_view->bottom_window->requisition.height;
2867   else
2868     bottom_rect.height = 0;
2869
2870   height -= bottom_rect.height;
2871
2872   text_rect.height = MAX (1, height);
2873
2874   left_rect.height = text_rect.height;
2875   right_rect.height = text_rect.height;
2876
2877   /* Origins */
2878   left_rect.x = focus_edge_width + GTK_CONTAINER (text_view)->border_width;
2879   top_rect.y = focus_edge_width + GTK_CONTAINER (text_view)->border_width;
2880
2881   text_rect.x = left_rect.x + left_rect.width;
2882   text_rect.y = top_rect.y + top_rect.height;
2883
2884   left_rect.y = text_rect.y;
2885   right_rect.y = text_rect.y;
2886
2887   top_rect.x = text_rect.x;
2888   bottom_rect.x = text_rect.x;
2889
2890   right_rect.x = text_rect.x + text_rect.width;
2891   bottom_rect.y = text_rect.y + text_rect.height;
2892
2893   text_window_size_allocate (text_view->text_window,
2894                              &text_rect);
2895
2896   if (text_view->left_window)
2897     text_window_size_allocate (text_view->left_window,
2898                                &left_rect);
2899
2900   if (text_view->right_window)
2901     text_window_size_allocate (text_view->right_window,
2902                                &right_rect);
2903
2904   if (text_view->top_window)
2905     text_window_size_allocate (text_view->top_window,
2906                                &top_rect);
2907
2908   if (text_view->bottom_window)
2909     text_window_size_allocate (text_view->bottom_window,
2910                                &bottom_rect);
2911
2912   gtk_text_view_update_layout_width (text_view);
2913   
2914   /* Note that this will do some layout validation */
2915   gtk_text_view_allocate_children (text_view);
2916
2917   /* Now adjust the value of the adjustment to keep the cursor at the
2918    * same place in the buffer
2919    */
2920   gtk_text_view_get_first_para_iter (text_view, &first_para);
2921   gtk_text_layout_get_line_yrange (text_view->layout, &first_para, &y, NULL);
2922
2923   y += text_view->first_para_pixels;
2924
2925   /* Ensure h/v adj exist */
2926   get_hadjustment (text_view);
2927   get_vadjustment (text_view);
2928
2929   vadj = text_view->vadjustment;
2930   if (y > vadj->upper - vadj->page_size)
2931     y = MAX (0, vadj->upper - vadj->page_size);
2932
2933   if (y != text_view->yoffset)
2934     {
2935       vadj->value = y;
2936       yoffset_changed = TRUE;
2937     }
2938
2939   text_view->hadjustment->page_size = SCREEN_WIDTH (text_view);
2940   text_view->hadjustment->page_increment = SCREEN_WIDTH (text_view) * 0.9;
2941   text_view->hadjustment->step_increment = SCREEN_WIDTH (text_view) * 0.1;
2942   text_view->hadjustment->lower = 0;
2943   text_view->hadjustment->upper = MAX (SCREEN_WIDTH (text_view),
2944                                        text_view->width);
2945   gtk_signal_emit_by_name (GTK_OBJECT (text_view->hadjustment), "changed");
2946
2947   text_view->vadjustment->page_size = SCREEN_HEIGHT (text_view);
2948   text_view->vadjustment->page_increment = SCREEN_HEIGHT (text_view) * 0.9;
2949   text_view->vadjustment->step_increment = SCREEN_HEIGHT (text_view) * 0.1;
2950   text_view->vadjustment->lower = 0;
2951   text_view->vadjustment->upper = MAX (SCREEN_HEIGHT (text_view),
2952                                        text_view->height);
2953   gtk_signal_emit_by_name (GTK_OBJECT (text_view->vadjustment), "changed");
2954
2955   if (yoffset_changed)
2956     gtk_adjustment_value_changed (vadj);
2957
2958   /* The GTK resize loop processes all the pending exposes right
2959    * after doing the resize stuff, so the idle sizer won't have a
2960    * chance to run. So we do the work here. 
2961    */
2962   gtk_text_view_flush_first_validate (text_view);
2963
2964   /* widget->window doesn't get auto-redrawn as the layout is computed, so has to
2965    * be invalidated
2966    */
2967   if (size_changed && GTK_WIDGET_REALIZED (widget))
2968     gdk_window_invalidate_rect (widget->window, NULL, FALSE);
2969 }
2970
2971 static void
2972 gtk_text_view_get_first_para_iter (GtkTextView *text_view,
2973                                    GtkTextIter *iter)
2974 {
2975   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), iter,
2976                                     text_view->first_para_mark);
2977 }
2978
2979 static void
2980 gtk_text_view_validate_onscreen (GtkTextView *text_view)
2981 {
2982   GtkWidget *widget = GTK_WIDGET (text_view);
2983   
2984   DV(g_print(">Validating onscreen ("G_STRLOC")\n"));
2985   
2986   if (SCREEN_HEIGHT (widget) > 0)
2987     {
2988       GtkTextIter first_para;
2989
2990       /* Be sure we've validated the stuff onscreen; if we
2991        * scrolled, these calls won't have any effect, because
2992        * they were called in the recursive validate_onscreen
2993        */
2994       gtk_text_view_get_first_para_iter (text_view, &first_para);
2995
2996       gtk_text_layout_validate_yrange (text_view->layout,
2997                                        &first_para,
2998                                        0,
2999                                        text_view->first_para_pixels +
3000                                        SCREEN_HEIGHT (widget));
3001     }
3002
3003   text_view->onscreen_validated = TRUE;
3004
3005   DV(g_print(">Done validating onscreen, onscreen_validated = TRUE ("G_STRLOC")\n"));
3006   
3007   /* This can have the odd side effect of triggering a scroll, which should
3008    * flip "onscreen_validated" back to FALSE, but should also get us
3009    * back into this function to turn it on again.
3010    */
3011   gtk_text_view_update_adjustments (text_view);
3012
3013   g_assert (text_view->onscreen_validated);
3014 }
3015
3016 static void
3017 gtk_text_view_flush_first_validate (GtkTextView *text_view)
3018 {
3019   if (text_view->first_validate_idle == 0)
3020     return;
3021
3022   /* Do this first, which means that if an "invalidate"
3023    * occurs during any of this process, a new first_validate_callback
3024    * will be installed, and we'll start again.
3025    */
3026   DV (g_print ("removing first validate in %s\n", G_STRLOC));
3027   g_source_remove (text_view->first_validate_idle);
3028   text_view->first_validate_idle = 0;
3029   
3030   /* be sure we have up-to-date screen size set on the
3031    * layout.
3032    */
3033   gtk_text_view_update_layout_width (text_view);
3034
3035   /* Bail out if we invalidated stuff; scrolling right away will just
3036    * confuse the issue.
3037    */
3038   if (text_view->first_validate_idle != 0)
3039     {
3040       DV(g_print(">Width change forced requeue ("G_STRLOC")\n"));
3041     }
3042   else
3043     {
3044       /* scroll to any marks, if that's pending. This can
3045        * jump us to the validation codepath used for scrolling
3046        * onscreen, if so we bail out.
3047        */
3048       if (!gtk_text_view_flush_scroll (text_view))
3049         gtk_text_view_validate_onscreen (text_view);
3050       
3051       DV(g_print(">Leaving first validate idle ("G_STRLOC")\n"));
3052       
3053       g_assert (text_view->onscreen_validated);
3054     }
3055 }
3056
3057 static gboolean
3058 first_validate_callback (gpointer data)
3059 {
3060   GtkTextView *text_view = data;
3061
3062   GDK_THREADS_ENTER ();
3063   
3064   /* Note that some of this code is duplicated at the end of size_allocate,
3065    * keep in sync with that.
3066    */
3067   
3068   DV(g_print(G_STRLOC"\n"));
3069
3070   gtk_text_view_flush_first_validate (text_view);
3071   
3072   GDK_THREADS_LEAVE ();
3073   
3074   return FALSE;
3075 }
3076
3077 static gboolean
3078 incremental_validate_callback (gpointer data)
3079 {
3080   GtkTextView *text_view = data;
3081   gboolean result = TRUE;
3082
3083   GDK_THREADS_ENTER ();
3084   
3085   DV(g_print(G_STRLOC"\n"));
3086   
3087   gtk_text_layout_validate (text_view->layout, 2000);
3088
3089   gtk_text_view_update_adjustments (text_view);
3090   
3091   if (gtk_text_layout_is_valid (text_view->layout))
3092     {
3093       text_view->incremental_validate_idle = 0;
3094       result = FALSE;
3095     }
3096
3097   GDK_THREADS_LEAVE ();
3098
3099   return result;
3100 }
3101
3102 static void
3103 gtk_text_view_invalidate (GtkTextView *text_view)
3104 {  
3105   DV (g_print (">Invalidate, onscreen_validated = %d now FALSE ("G_STRLOC")\n",
3106                text_view->onscreen_validated));
3107
3108   text_view->onscreen_validated = FALSE;
3109
3110   /* We'll invalidate when the layout is created */
3111   if (text_view->layout == NULL)
3112     return;
3113   
3114   if (!text_view->first_validate_idle)
3115     {
3116       text_view->first_validate_idle = g_idle_add_full (GTK_PRIORITY_RESIZE - 2, first_validate_callback, text_view, NULL);
3117       DV (g_print (G_STRLOC": adding first validate idle %d\n",
3118                    text_view->first_validate_idle));
3119     }
3120       
3121   if (!text_view->incremental_validate_idle)
3122     {
3123       text_view->incremental_validate_idle = g_idle_add_full (GTK_TEXT_VIEW_PRIORITY_VALIDATE, incremental_validate_callback, text_view, NULL);
3124       DV (g_print (G_STRLOC": adding incremental validate idle %d\n",
3125                    text_view->incremental_validate_idle));
3126     }
3127 }
3128
3129 static void
3130 invalidated_handler (GtkTextLayout *layout,
3131                      gpointer       data)
3132 {
3133   GtkTextView *text_view;
3134
3135   text_view = GTK_TEXT_VIEW (data);
3136
3137   DV (g_print ("Invalidating due to layout invalidate signal\n"));
3138   gtk_text_view_invalidate (text_view);
3139 }
3140
3141 static void
3142 changed_handler (GtkTextLayout     *layout,
3143                  gint               start_y,
3144                  gint               old_height,
3145                  gint               new_height,
3146                  gpointer           data)
3147 {
3148   GtkTextView *text_view;
3149   GtkWidget *widget;
3150   GdkRectangle visible_rect;
3151   GdkRectangle redraw_rect;
3152   
3153   text_view = GTK_TEXT_VIEW (data);
3154   widget = GTK_WIDGET (data);
3155   
3156   DV(g_print(">Lines Validated ("G_STRLOC")\n"));
3157
3158   if (GTK_WIDGET_REALIZED (text_view))
3159     {      
3160       gtk_text_view_get_visible_rect (text_view, &visible_rect);
3161
3162       redraw_rect.x = visible_rect.x;
3163       redraw_rect.width = visible_rect.width;
3164       redraw_rect.y = start_y;
3165
3166       if (old_height == new_height)
3167         redraw_rect.height = old_height;
3168       else
3169         redraw_rect.height = MAX (0, visible_rect.y + visible_rect.height - start_y);
3170
3171       if (gdk_rectangle_intersect (&redraw_rect, &visible_rect, &redraw_rect))
3172         {
3173           /* text_window_invalidate_rect() takes buffer coordinates */
3174           text_window_invalidate_rect (text_view->text_window,
3175                                        &redraw_rect);
3176
3177           DV(g_print(" invalidated rect: %d,%d %d x %d\n",
3178                      redraw_rect.x,
3179                      redraw_rect.y,
3180                      redraw_rect.width,
3181                      redraw_rect.height));
3182           
3183           if (text_view->left_window)
3184             text_window_invalidate_rect (text_view->left_window,
3185                                          &redraw_rect);
3186           if (text_view->right_window)
3187             text_window_invalidate_rect (text_view->right_window,
3188                                          &redraw_rect);
3189           if (text_view->top_window)
3190             text_window_invalidate_rect (text_view->top_window,
3191                                          &redraw_rect);
3192           if (text_view->bottom_window)
3193             text_window_invalidate_rect (text_view->bottom_window,
3194                                          &redraw_rect);
3195
3196           gtk_text_view_update_im_spot_location (text_view);
3197         }
3198     }
3199   
3200   if (old_height != new_height)
3201     {
3202       gboolean yoffset_changed = FALSE;
3203       GSList *tmp_list;
3204       int new_first_para_top;
3205       int old_first_para_top;
3206       GtkTextIter first;
3207       
3208       /* If the bottom of the old area was above the top of the
3209        * screen, we need to scroll to keep the current top of the
3210        * screen in place.  Remember that first_para_pixels is the
3211        * position of the top of the screen in coordinates relative to
3212        * the first paragraph onscreen.
3213        *
3214        * In short we are adding the height delta of the portion of the
3215        * changed region above first_para_mark to text_view->yoffset.
3216        */
3217       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &first,
3218                                         text_view->first_para_mark);
3219
3220       gtk_text_layout_get_line_yrange (layout, &first, &new_first_para_top, NULL);
3221
3222       old_first_para_top = text_view->yoffset - text_view->first_para_pixels;
3223
3224       if (new_first_para_top != old_first_para_top)
3225         {
3226           text_view->yoffset += new_first_para_top - old_first_para_top;
3227           
3228           get_vadjustment (text_view)->value = text_view->yoffset;
3229           yoffset_changed = TRUE;
3230         }
3231
3232       if (yoffset_changed)
3233         {
3234           DV(g_print ("Changing scroll position (%s)\n", G_STRLOC));
3235           gtk_adjustment_value_changed (get_vadjustment (text_view));
3236         }
3237
3238       /* FIXME be smarter about which anchored widgets we update */
3239
3240       tmp_list = text_view->children;
3241       while (tmp_list != NULL)
3242         {
3243           GtkTextViewChild *child = tmp_list->data;
3244
3245           if (child->anchor)
3246             gtk_text_view_update_child_allocation (text_view, child);
3247
3248           tmp_list = g_slist_next (tmp_list);
3249         }
3250     }
3251
3252   {
3253     GtkRequisition old_req;
3254     GtkRequisition new_req;
3255
3256     old_req = widget->requisition;
3257
3258     /* Use this instead of gtk_widget_size_request wrapper
3259      * to avoid the optimization which just returns widget->requisition
3260      * if a resize hasn't been queued.
3261      */
3262     GTK_WIDGET_GET_CLASS (widget)->size_request (widget, &new_req);
3263
3264     if (old_req.width != new_req.width ||
3265         old_req.height != new_req.height)
3266       {
3267         /* FIXME http://bugzilla.gnome.org/show_bug.cgi?id=72258 */
3268         _gtk_size_group_queue_resize (widget);
3269       }
3270   }
3271 }
3272
3273 static void
3274 gtk_text_view_realize (GtkWidget *widget)
3275 {
3276   GtkTextView *text_view;
3277   GdkWindowAttr attributes;
3278   gint attributes_mask;
3279   GSList *tmp_list;
3280   
3281   text_view = GTK_TEXT_VIEW (widget);
3282   GTK_WIDGET_SET_FLAGS (text_view, GTK_REALIZED);
3283
3284   attributes.window_type = GDK_WINDOW_CHILD;
3285   attributes.x = widget->allocation.x;
3286   attributes.y = widget->allocation.y;
3287   attributes.width = widget->allocation.width;
3288   attributes.height = widget->allocation.height;
3289   attributes.wclass = GDK_INPUT_OUTPUT;
3290   attributes.visual = gtk_widget_get_visual (widget);
3291   attributes.colormap = gtk_widget_get_colormap (widget);
3292   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK | GDK_EXPOSURE_MASK;
3293
3294   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
3295
3296   widget->window = gdk_window_new (gtk_widget_get_parent_window (widget),
3297                                    &attributes, attributes_mask);
3298   gdk_window_set_user_data (widget->window, widget);
3299
3300   /* must come before text_window_realize calls */
3301   widget->style = gtk_style_attach (widget->style, widget->window);
3302
3303   gdk_window_set_background (widget->window,
3304                              &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3305
3306   text_window_realize (text_view->text_window, widget->window);
3307
3308   if (text_view->left_window)
3309     text_window_realize (text_view->left_window,
3310                          widget->window);
3311
3312   if (text_view->top_window)
3313     text_window_realize (text_view->top_window,
3314                          widget->window);
3315
3316   if (text_view->right_window)
3317     text_window_realize (text_view->right_window,
3318                          widget->window);
3319
3320   if (text_view->bottom_window)
3321     text_window_realize (text_view->bottom_window,
3322                          widget->window);
3323
3324   gtk_text_view_ensure_layout (text_view);
3325
3326   if (text_view->buffer)
3327     {
3328       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
3329                                                           GDK_SELECTION_PRIMARY);
3330       gtk_text_buffer_add_selection_clipboard (text_view->buffer, clipboard);
3331     }
3332
3333   tmp_list = text_view->children;
3334   while (tmp_list != NULL)
3335     {
3336       GtkTextViewChild *vc = tmp_list->data;
3337       
3338       text_view_child_set_parent_window (text_view, vc);
3339       
3340       tmp_list = tmp_list->next;
3341     }
3342 }
3343
3344 static void
3345 gtk_text_view_unrealize (GtkWidget *widget)
3346 {
3347   GtkTextView *text_view;
3348   
3349   text_view = GTK_TEXT_VIEW (widget);
3350
3351   if (text_view->buffer)
3352     {
3353       GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
3354                                                           GDK_SELECTION_PRIMARY);
3355       gtk_text_buffer_remove_selection_clipboard (text_view->buffer, clipboard);
3356     }
3357
3358   gtk_text_view_remove_validate_idles (text_view);
3359
3360   if (text_view->popup_menu)
3361     {
3362       gtk_widget_destroy (text_view->popup_menu);
3363       text_view->popup_menu = NULL;
3364     }
3365
3366   text_window_unrealize (text_view->text_window);
3367
3368   if (text_view->left_window)
3369     text_window_unrealize (text_view->left_window);
3370
3371   if (text_view->top_window)
3372     text_window_unrealize (text_view->top_window);
3373
3374   if (text_view->right_window)
3375     text_window_unrealize (text_view->right_window);
3376
3377   if (text_view->bottom_window)
3378     text_window_unrealize (text_view->bottom_window);
3379
3380   gtk_text_view_destroy_layout (text_view);
3381   
3382   (* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
3383 }
3384
3385 static void
3386 gtk_text_view_style_set (GtkWidget *widget,
3387                          GtkStyle  *previous_style)
3388 {
3389   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3390
3391   if (GTK_WIDGET_REALIZED (widget))
3392     {
3393       gdk_window_set_background (widget->window,
3394                                  &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3395
3396       gdk_window_set_background (text_view->text_window->bin_window,
3397                                  &widget->style->base[GTK_WIDGET_STATE (widget)]);
3398
3399       if (text_view->left_window)
3400         gdk_window_set_background (text_view->left_window->bin_window,
3401                                    &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3402       if (text_view->right_window)
3403         gdk_window_set_background (text_view->right_window->bin_window,
3404                                    &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3405
3406       if (text_view->top_window)
3407         gdk_window_set_background (text_view->top_window->bin_window,
3408                                    &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3409
3410       if (text_view->bottom_window)
3411         gdk_window_set_background (text_view->bottom_window->bin_window,
3412                                    &widget->style->bg[GTK_WIDGET_STATE (widget)]);
3413     }
3414
3415   if (text_view->layout && previous_style)
3416     {
3417       gtk_text_view_set_attributes_from_style (text_view,
3418                                                text_view->layout->default_style,
3419                                                widget->style);
3420       gtk_text_layout_default_style_changed (text_view->layout);
3421     }
3422 }
3423
3424 static void
3425 gtk_text_view_direction_changed (GtkWidget        *widget,
3426                                  GtkTextDirection  previous_direction)
3427 {
3428   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3429
3430   if (text_view->layout)
3431     {
3432       text_view->layout->default_style->direction = gtk_widget_get_direction (widget);
3433       gtk_text_layout_default_style_changed (text_view->layout);
3434     }
3435 }
3436
3437
3438 static void
3439 set_invisible_cursor (GdkWindow *window)
3440 {
3441   GdkBitmap *empty_bitmap;
3442   GdkCursor *cursor;
3443   GdkColor useless;
3444   char invisible_cursor_bits[] = { 0x0 };       
3445         
3446   useless.red = useless.green = useless.blue = 0;
3447   useless.pixel = 0;
3448   
3449   empty_bitmap = gdk_bitmap_create_from_data (window,
3450                                               invisible_cursor_bits,
3451                                               1, 1);
3452   
3453   cursor = gdk_cursor_new_from_pixmap (empty_bitmap,
3454                                        empty_bitmap,
3455                                        &useless,
3456                                        &useless, 0, 0);
3457   
3458   gdk_window_set_cursor (window, cursor);
3459   
3460   gdk_cursor_unref (cursor);
3461   
3462   g_object_unref (empty_bitmap);
3463 }
3464
3465 static void
3466 gtk_text_view_obscure_mouse_cursor (GtkTextView *text_view)
3467 {
3468   if (text_view->mouse_cursor_obscured)
3469     return;
3470
3471   set_invisible_cursor (text_view->text_window->bin_window);
3472   
3473   text_view->mouse_cursor_obscured = TRUE;  
3474 }
3475
3476 /*
3477  * Events
3478  */
3479
3480 static gboolean
3481 get_event_coordinates (GdkEvent *event, gint *x, gint *y)
3482 {
3483   if (event)
3484     switch (event->type)
3485       {
3486       case GDK_MOTION_NOTIFY:
3487         *x = event->motion.x;
3488         *y = event->motion.y;
3489         return TRUE;
3490         break;
3491
3492       case GDK_BUTTON_PRESS:
3493       case GDK_2BUTTON_PRESS:
3494       case GDK_3BUTTON_PRESS:
3495       case GDK_BUTTON_RELEASE:
3496         *x = event->button.x;
3497         *y = event->button.y;
3498         return TRUE;
3499         break;
3500
3501       case GDK_KEY_PRESS:
3502       case GDK_KEY_RELEASE:
3503       case GDK_ENTER_NOTIFY:
3504       case GDK_LEAVE_NOTIFY:
3505       case GDK_PROPERTY_NOTIFY:
3506       case GDK_SELECTION_CLEAR:
3507       case GDK_SELECTION_REQUEST:
3508       case GDK_SELECTION_NOTIFY:
3509       case GDK_PROXIMITY_IN:
3510       case GDK_PROXIMITY_OUT:
3511       case GDK_DRAG_ENTER:
3512       case GDK_DRAG_LEAVE:
3513       case GDK_DRAG_MOTION:
3514       case GDK_DRAG_STATUS:
3515       case GDK_DROP_START:
3516       case GDK_DROP_FINISHED:
3517       default:
3518         return FALSE;
3519         break;
3520       }
3521
3522   return FALSE;
3523 }
3524
3525 static gint
3526 emit_event_on_tags (GtkWidget   *widget,
3527                     GdkEvent    *event,
3528                     GtkTextIter *iter)
3529 {
3530   GSList *tags;
3531   GSList *tmp;
3532   gboolean retval = FALSE;
3533   GtkTextView *text_view;
3534
3535   text_view = GTK_TEXT_VIEW (widget);
3536
3537   tags = gtk_text_iter_get_tags (iter);
3538
3539   tmp = tags;
3540   while (tmp != NULL)
3541     {
3542       GtkTextTag *tag = tmp->data;
3543
3544       if (gtk_text_tag_event (tag, G_OBJECT (widget), event, iter))
3545         {
3546           retval = TRUE;
3547           break;
3548         }
3549
3550       tmp = g_slist_next (tmp);
3551     }
3552
3553   g_slist_free (tags);
3554
3555   return retval;
3556 }
3557
3558 static gint
3559 gtk_text_view_event (GtkWidget *widget, GdkEvent *event)
3560 {
3561   GtkTextView *text_view;
3562   gint x = 0, y = 0;
3563
3564   text_view = GTK_TEXT_VIEW (widget);
3565
3566   if (text_view->layout == NULL ||
3567       get_buffer (text_view) == NULL)
3568     return FALSE;
3569
3570   if (event->any.window != text_view->text_window->bin_window)
3571     return FALSE;
3572
3573   if (get_event_coordinates (event, &x, &y))
3574     {
3575       GtkTextIter iter;
3576
3577       x += text_view->xoffset;
3578       y += text_view->yoffset;
3579
3580       /* FIXME this is slow and we do it twice per event.
3581        * My favorite solution is to have GtkTextLayout cache
3582        * the last couple lookups.
3583        */
3584       gtk_text_layout_get_iter_at_pixel (text_view->layout,
3585                                          &iter,
3586                                          x, y);
3587
3588       return emit_event_on_tags (widget, event, &iter);
3589     }
3590   else if (event->type == GDK_KEY_PRESS ||
3591            event->type == GDK_KEY_RELEASE)
3592     {
3593       GtkTextMark *insert;
3594       GtkTextIter iter;
3595
3596       insert = gtk_text_buffer_get_mark (get_buffer (text_view),
3597                                          "insert");
3598
3599       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
3600
3601       return emit_event_on_tags (widget, event, &iter);
3602     }
3603   else
3604     return FALSE;
3605 }
3606
3607 static gint
3608 gtk_text_view_key_press_event (GtkWidget *widget, GdkEventKey *event)
3609 {
3610   gboolean retval = FALSE;
3611   gboolean obscure = FALSE;
3612   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3613   GtkTextMark *insert;
3614   GtkTextIter iter;
3615   gboolean can_insert;
3616   
3617   if (text_view->layout == NULL ||
3618       get_buffer (text_view) == NULL)
3619     return FALSE;
3620
3621   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
3622   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
3623   can_insert = gtk_text_iter_can_insert (&iter, text_view->editable);
3624   if (can_insert &&
3625       gtk_im_context_filter_keypress (text_view->im_context, event))
3626     {
3627       text_view->need_im_reset = TRUE;
3628       obscure = TRUE;
3629       retval = TRUE;
3630     }
3631   /* Binding set */
3632   else if (GTK_WIDGET_CLASS (parent_class)->key_press_event &&
3633            GTK_WIDGET_CLASS (parent_class)->key_press_event (widget, event))
3634     retval = TRUE;
3635   /* use overall editability not can_insert, more predictable for users */
3636   else if (text_view->editable &&
3637            (event->keyval == GDK_Return ||
3638             event->keyval == GDK_KP_Enter))
3639     {
3640       /* this won't actually insert the newline if the cursor isn't
3641        * editable
3642        */
3643       gtk_text_view_commit_text (text_view, "\n");
3644
3645       obscure = TRUE;
3646       retval = TRUE;
3647     }
3648   /* Pass through Tab as literal tab, unless Control is held down */
3649   else if ((event->keyval == GDK_Tab ||
3650             event->keyval == GDK_KP_Tab) &&
3651            !(event->state & GDK_CONTROL_MASK))
3652     {
3653       /* If the text widget isn't editable overall, move the focus
3654        * instead
3655        */
3656       if (text_view->editable)
3657         {
3658           gtk_text_view_commit_text (text_view, "\t");
3659           obscure = TRUE;
3660         }
3661       else
3662         gtk_text_view_move_focus (text_view,
3663                                   (event->state & GDK_SHIFT_MASK) ?
3664                                   GTK_DIR_TAB_BACKWARD: GTK_DIR_TAB_FORWARD);
3665
3666       retval = TRUE;
3667     }
3668   else
3669     retval = FALSE;
3670
3671   if (obscure)
3672     gtk_text_view_obscure_mouse_cursor (text_view);
3673   
3674   gtk_text_view_pend_cursor_blink (text_view);
3675
3676   return retval;
3677 }
3678
3679 static gint
3680 gtk_text_view_key_release_event (GtkWidget *widget, GdkEventKey *event)
3681 {
3682   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3683   GtkTextMark *insert;
3684   GtkTextIter iter;
3685
3686   if (text_view->layout == NULL || get_buffer (text_view) == NULL)
3687     return FALSE;
3688       
3689   insert = gtk_text_buffer_get_insert (get_buffer (text_view));
3690   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &iter, insert);
3691   if (gtk_text_iter_can_insert (&iter, text_view->editable) &&
3692       gtk_im_context_filter_keypress (text_view->im_context, event))
3693     {
3694       text_view->need_im_reset = TRUE;
3695       return TRUE;
3696     }
3697   else
3698     return GTK_WIDGET_CLASS (parent_class)->key_release_event (widget, event);
3699 }
3700
3701 static gint
3702 gtk_text_view_button_press_event (GtkWidget *widget, GdkEventButton *event)
3703 {
3704   GtkTextView *text_view;
3705
3706   text_view = GTK_TEXT_VIEW (widget);
3707
3708   text_view->disable_scroll_on_focus = TRUE;
3709   gtk_widget_grab_focus (widget);
3710   text_view->disable_scroll_on_focus = FALSE;
3711
3712   if (event->window != text_view->text_window->bin_window)
3713     {
3714       /* Remove selection if any. */
3715       gtk_text_view_unselect (text_view);
3716       return FALSE;
3717     }
3718
3719 #if 0
3720   /* debug hack */
3721   if (event->button == 3 && (event->state & GDK_CONTROL_MASK) != 0)
3722     _gtk_text_buffer_spew (GTK_TEXT_VIEW (widget)->buffer);
3723   else if (event->button == 3)
3724     gtk_text_layout_spew (GTK_TEXT_VIEW (widget)->layout);
3725 #endif
3726
3727   if (event->type == GDK_BUTTON_PRESS)
3728     {
3729       gtk_text_view_reset_im_context (text_view);
3730
3731       if (event->button == 1)
3732         {
3733           /* If we're in the selection, start a drag copy/move of the
3734            * selection; otherwise, start creating a new selection.
3735            */
3736           GtkTextIter iter;
3737           GtkTextIter start, end;
3738
3739           gtk_text_layout_get_iter_at_pixel (text_view->layout,
3740                                              &iter,
3741                                              event->x + text_view->xoffset,
3742                                              event->y + text_view->yoffset);
3743
3744           if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
3745                                                     &start, &end) &&
3746               gtk_text_iter_in_range (&iter, &start, &end))
3747             {
3748               text_view->drag_start_x = event->x;
3749               text_view->drag_start_y = event->y;
3750               text_view->pending_place_cursor_button = event->button;
3751             }
3752           else
3753             {
3754               gtk_text_view_start_selection_drag (text_view, &iter, event);
3755             }
3756
3757           return TRUE;
3758         }
3759       else if (event->button == 2)
3760         {
3761           GtkTextIter iter;
3762
3763           gtk_text_layout_get_iter_at_pixel (text_view->layout,
3764                                              &iter,
3765                                              event->x + text_view->xoffset,
3766                                              event->y + text_view->yoffset);
3767
3768           gtk_text_buffer_paste_clipboard (get_buffer (text_view),
3769                                            gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY),
3770                                            &iter,
3771                                            text_view->editable);
3772           return TRUE;
3773         }
3774       else if (event->button == 3)
3775         {
3776           gtk_text_view_do_popup (text_view, event);
3777         }
3778     }
3779   else if ((event->type == GDK_2BUTTON_PRESS ||
3780             event->type == GDK_3BUTTON_PRESS) &&
3781            event->button == 1)
3782     {
3783       GtkTextIter start, end;      
3784       
3785       /* End the selection drag, otherwise we'd clear the new
3786        * word/line selection on button release
3787        */
3788       gtk_text_view_end_selection_drag (text_view, event);
3789
3790       gtk_text_layout_get_iter_at_pixel (text_view->layout,
3791                                          &start,
3792                                          event->x + text_view->xoffset,
3793                                          event->y + text_view->yoffset); 
3794
3795       end = start;
3796       
3797       if (event->type == GDK_2BUTTON_PRESS)
3798         {
3799           if (gtk_text_iter_inside_word (&start))
3800             {
3801               if (!gtk_text_iter_starts_word (&start))
3802                 gtk_text_iter_backward_word_start (&start);
3803               
3804               if (!gtk_text_iter_ends_word (&end))
3805                 gtk_text_iter_forward_word_end (&end);
3806             }
3807         }
3808       else if (event->type == GDK_3BUTTON_PRESS)
3809         {
3810           if (gtk_text_view_starts_display_line (text_view, &start))
3811             {
3812               /* If on a display line boundary, we assume the user
3813                * clicked off the end of a line and we therefore select
3814                * the line before the boundary.
3815                */
3816               gtk_text_view_backward_display_line_start (text_view, &start);
3817             }
3818           else
3819             {
3820               /* start isn't on the start of a line, so we move it to the
3821                * start, and move end to the end unless it's already there.
3822                */
3823               gtk_text_view_backward_display_line_start (text_view, &start);
3824
3825               if (!gtk_text_view_starts_display_line (text_view, &end))
3826                 gtk_text_view_forward_display_line_end (text_view, &end);
3827             }
3828         }
3829
3830       if (event->state & GDK_SHIFT_MASK)
3831         {
3832           /* Take union of old and new selection */
3833           GtkTextIter old_start, old_end;
3834           
3835           gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
3836                                                 &old_start, &old_end);
3837
3838           gtk_text_iter_order (&start, &old_start);
3839           gtk_text_iter_order (&old_end, &end);
3840
3841           /* Now start is the first of the starts, and end is the
3842            * last of the ends
3843            */
3844         }
3845       
3846       gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
3847                                          "selection_bound",
3848                                          &start);
3849       gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
3850                                          "insert",
3851                                          &end);
3852
3853       text_view->just_selected_element = TRUE;
3854       
3855       return TRUE;
3856     }
3857   
3858   return FALSE;
3859 }
3860
3861 static gint
3862 gtk_text_view_button_release_event (GtkWidget *widget, GdkEventButton *event)
3863 {
3864   GtkTextView *text_view;
3865
3866   text_view = GTK_TEXT_VIEW (widget);
3867
3868   if (event->window != text_view->text_window->bin_window)
3869     return FALSE;
3870
3871   if (event->button == 1)
3872     {
3873       if (text_view->drag_start_x >= 0)
3874         {
3875           text_view->drag_start_x = -1;
3876           text_view->drag_start_y = -1;
3877         }
3878
3879       if (gtk_text_view_end_selection_drag (GTK_TEXT_VIEW (widget), event))
3880         return TRUE;
3881       else if (text_view->just_selected_element)
3882         {
3883           text_view->just_selected_element = FALSE;
3884           return FALSE;
3885         }
3886       else if (text_view->pending_place_cursor_button == event->button)
3887         {
3888           GtkTextIter iter;
3889
3890           /* Unselect everything; we clicked inside selection, but
3891            * didn't move by the drag threshold, so just clear selection
3892            * and place cursor.
3893            */
3894           gtk_text_layout_get_iter_at_pixel (text_view->layout,
3895                                              &iter,
3896                                              event->x + text_view->xoffset,
3897                                              event->y + text_view->yoffset);
3898
3899           gtk_text_buffer_place_cursor (get_buffer (text_view), &iter);
3900
3901           text_view->pending_place_cursor_button = 0;
3902           
3903           return FALSE;
3904         }
3905     }
3906
3907   return FALSE;
3908 }
3909
3910 static void
3911 keymap_direction_changed (GdkKeymap   *keymap,
3912                           GtkTextView *text_view)
3913 {
3914   gtk_text_view_check_keymap_direction (text_view);
3915 }
3916
3917 static gint
3918 gtk_text_view_focus_in_event (GtkWidget *widget, GdkEventFocus *event)
3919 {
3920   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3921
3922   gtk_widget_queue_draw (widget);
3923
3924   DV(g_print (G_STRLOC": focus_in_event\n"));
3925   
3926   if (text_view->cursor_visible && text_view->layout)
3927     {
3928       gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
3929       gtk_text_view_check_cursor_blink (text_view);
3930     }
3931
3932   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
3933                     "direction_changed",
3934                     G_CALLBACK (keymap_direction_changed), text_view);
3935   gtk_text_view_check_keymap_direction (text_view);
3936   
3937   text_view->need_im_reset = TRUE;
3938   gtk_im_context_focus_in (GTK_TEXT_VIEW (widget)->im_context);
3939
3940   return FALSE;
3941 }
3942
3943 static gint
3944 gtk_text_view_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
3945 {
3946   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3947
3948   gtk_widget_queue_draw (widget);
3949
3950   DV(g_print (G_STRLOC": focus_out_event\n"));
3951   
3952   if (text_view->cursor_visible && text_view->layout)
3953     {
3954       gtk_text_layout_set_cursor_visible (text_view->layout, FALSE);
3955       gtk_text_view_check_cursor_blink (text_view);
3956     }
3957
3958   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
3959                                         (gpointer) keymap_direction_changed,
3960                                         text_view);
3961
3962   text_view->need_im_reset = TRUE;
3963   gtk_im_context_focus_out (GTK_TEXT_VIEW (widget)->im_context);
3964
3965   return FALSE;
3966 }
3967
3968 static gint
3969 gtk_text_view_motion_event (GtkWidget *widget, GdkEventMotion *event)
3970 {
3971   GtkTextView *text_view = GTK_TEXT_VIEW (widget);
3972
3973   if (text_view->mouse_cursor_obscured)
3974     {
3975       GdkCursor *cursor;
3976       
3977       cursor = gdk_cursor_new_for_screen (gtk_widget_get_screen (widget),
3978                                           GDK_XTERM);
3979       gdk_window_set_cursor (text_view->text_window->bin_window, cursor);
3980       gdk_cursor_unref (cursor);
3981       text_view->mouse_cursor_obscured = FALSE;
3982     }
3983
3984   if (event->window == text_view->text_window->bin_window &&
3985       text_view->drag_start_x >= 0)
3986     {
3987       gint x, y;
3988
3989       gdk_window_get_pointer (text_view->text_window->bin_window,
3990                               &x, &y, NULL);
3991
3992       if (gtk_drag_check_threshold (widget,
3993                                     text_view->drag_start_x, 
3994                                     text_view->drag_start_y,
3995                                     x, y))
3996         {
3997           GtkTextIter iter;
3998           gint buffer_x, buffer_y;
3999
4000           gtk_text_view_window_to_buffer_coords (text_view,
4001                                                  GTK_TEXT_WINDOW_TEXT,
4002                                                  text_view->drag_start_x,
4003                                                  text_view->drag_start_y,
4004                                                  &buffer_x,
4005                                                  &buffer_y);
4006
4007           gtk_text_layout_get_iter_at_pixel (text_view->layout,
4008                                              &iter,
4009                                              buffer_x, buffer_y);
4010
4011           gtk_text_view_start_selection_dnd (text_view, &iter, event);
4012           return TRUE;
4013         }
4014     }
4015
4016   return FALSE;
4017 }
4018
4019 static void
4020 gtk_text_view_paint (GtkWidget      *widget,
4021                      GdkRectangle   *area,
4022                      GdkEventExpose *event)
4023 {
4024   GtkTextView *text_view;
4025   GList *child_exposes;
4026   GList *tmp_list;
4027   GdkRegion *updates;
4028   
4029   text_view = GTK_TEXT_VIEW (widget);
4030
4031   g_return_if_fail (text_view->layout != NULL);
4032   g_return_if_fail (text_view->xoffset >= 0);
4033   g_return_if_fail (text_view->yoffset >= 0);
4034
4035   while (text_view->first_validate_idle != 0)
4036     {
4037       DV (g_print (G_STRLOC": first_validate_idle: %d\n",
4038                    text_view->first_validate_idle));
4039       gtk_text_view_flush_first_validate (text_view);
4040     }
4041
4042   /* More regions could have become invalid in the above loop */
4043   updates = gdk_window_get_update_area (text_view->text_window->bin_window);
4044   if (updates)
4045     {
4046       GdkRectangle rect;
4047       
4048       gdk_region_get_clipbox (updates, &rect);
4049
4050       gdk_rectangle_union (area, &rect, area);
4051       
4052       gdk_region_destroy (updates);
4053     }
4054   
4055   if (!text_view->onscreen_validated)
4056     {
4057       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.");
4058       g_assert_not_reached ();
4059     }
4060   
4061 #if 0
4062   printf ("painting %d,%d  %d x %d\n",
4063           area->x, area->y,
4064           area->width, area->height);
4065 #endif
4066
4067   child_exposes = NULL;
4068   gtk_text_layout_draw (text_view->layout,
4069                         widget,
4070                         text_view->text_window->bin_window,
4071                         NULL,
4072                         text_view->xoffset,
4073                         text_view->yoffset,
4074                         area->x, area->y,
4075                         area->width, area->height,
4076                         &child_exposes);
4077
4078   tmp_list = child_exposes;
4079   while (tmp_list != NULL)
4080     {
4081       GtkWidget *child = tmp_list->data;
4082       
4083       gtk_container_propagate_expose (GTK_CONTAINER (text_view),
4084                                       child,
4085                                       event);
4086
4087       g_object_unref (G_OBJECT (child));
4088       
4089       tmp_list = tmp_list->next;
4090     }
4091
4092   g_list_free (child_exposes);
4093 }
4094
4095 static gint
4096 gtk_text_view_expose_event (GtkWidget *widget, GdkEventExpose *event)
4097 {
4098   GSList *tmp_list;
4099   
4100   if (event->window == gtk_text_view_get_window (GTK_TEXT_VIEW (widget),
4101                                                  GTK_TEXT_WINDOW_TEXT))
4102     {
4103       DV(g_print (">Exposed ("G_STRLOC")\n"));
4104       gtk_text_view_paint (widget, &event->area, event);
4105     }
4106
4107   if (event->window == widget->window)
4108     gtk_text_view_draw_focus (widget);
4109
4110   /* Propagate exposes to all children not in the buffer. */
4111   tmp_list = GTK_TEXT_VIEW (widget)->children;
4112   while (tmp_list != NULL)
4113     {
4114       GtkTextViewChild *vc = tmp_list->data;
4115
4116       /* propagate_expose checks that event->window matches
4117        * child->window
4118        */
4119       if (vc->type != GTK_TEXT_WINDOW_TEXT)
4120         gtk_container_propagate_expose (GTK_CONTAINER (widget),
4121                                         vc->widget,
4122                                         event);
4123       
4124       tmp_list = tmp_list->next;
4125     }
4126   
4127   return FALSE;
4128 }
4129
4130 static void
4131 gtk_text_view_draw_focus (GtkWidget *widget)
4132 {
4133   gboolean interior_focus;
4134
4135   /* We clear the focus if we are in interior focus mode. */
4136   gtk_widget_style_get (widget,
4137                         "interior_focus", &interior_focus,
4138                         NULL);
4139   
4140   if (GTK_WIDGET_DRAWABLE (widget))
4141     {
4142       if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
4143         {          
4144           gtk_paint_focus (widget->style, widget->window, GTK_WIDGET_STATE (widget), 
4145                            NULL, widget, "textview",
4146                            0, 0,
4147                            widget->allocation.width,
4148                            widget->allocation.height);
4149         }
4150       else
4151         {
4152           gdk_window_clear (widget->window);
4153         }
4154     }
4155 }
4156
4157 static void
4158 gtk_text_view_grab_focus (GtkWidget *widget)
4159 {
4160   GtkTextView *text_view;
4161
4162   text_view = GTK_TEXT_VIEW (widget);
4163   
4164   GTK_WIDGET_CLASS (parent_class)->grab_focus (widget);
4165
4166   if (!text_view->disable_scroll_on_focus)
4167     gtk_text_view_scroll_mark_onscreen (text_view,
4168                                         gtk_text_buffer_get_mark (get_buffer (text_view),
4169                                                                   "insert"));
4170 }
4171
4172 static gboolean
4173 gtk_text_view_focus (GtkWidget        *widget,
4174                      GtkDirectionType  direction)
4175 {
4176   GtkTextView *text_view;
4177   GtkContainer *container;
4178   
4179   text_view = GTK_TEXT_VIEW (widget);
4180   container = GTK_CONTAINER (widget);  
4181   
4182   return GTK_WIDGET_CLASS (parent_class)->focus (widget, direction);
4183 }
4184
4185 /*
4186  * Container
4187  */
4188
4189 static void
4190 gtk_text_view_add (GtkContainer *container,
4191                    GtkWidget    *child)
4192 {
4193   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
4194   g_return_if_fail (GTK_IS_WIDGET (child));
4195
4196   /* This is pretty random. */
4197   gtk_text_view_add_child_in_window (GTK_TEXT_VIEW (container),
4198                                      child,
4199                                      GTK_TEXT_WINDOW_WIDGET,
4200                                      0, 0);
4201 }
4202
4203 static void
4204 gtk_text_view_remove (GtkContainer *container,
4205                       GtkWidget    *child)
4206 {
4207   GSList *iter;
4208   GtkTextView *text_view;
4209   GtkTextViewChild *vc;
4210
4211   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
4212   g_return_if_fail (GTK_IS_WIDGET (child));
4213   g_return_if_fail (child->parent == (GtkWidget*) container);
4214
4215   text_view = GTK_TEXT_VIEW (container);
4216
4217   vc = NULL;
4218   iter = text_view->children;
4219
4220   while (iter != NULL)
4221     {
4222       vc = iter->data;
4223
4224       if (vc->widget == child)
4225         break;
4226
4227       iter = g_slist_next (iter);
4228     }
4229
4230   g_assert (iter != NULL); /* be sure we had the child in the list */
4231
4232   text_view->children = g_slist_remove (text_view->children, vc);
4233
4234   gtk_widget_unparent (vc->widget);
4235
4236   text_view_child_free (vc);
4237 }
4238
4239 static void
4240 gtk_text_view_forall (GtkContainer *container,
4241                       gboolean      include_internals,
4242                       GtkCallback   callback,
4243                       gpointer      callback_data)
4244 {
4245   GSList *iter;
4246   GtkTextView *text_view;
4247   GSList *copy;
4248
4249   g_return_if_fail (GTK_IS_TEXT_VIEW (container));
4250   g_return_if_fail (callback != NULL);
4251
4252   text_view = GTK_TEXT_VIEW (container);
4253
4254   copy = g_slist_copy (text_view->children);
4255   iter = copy;
4256
4257   while (iter != NULL)
4258     {
4259       GtkTextViewChild *vc = iter->data;
4260
4261       (* callback) (vc->widget, callback_data);
4262
4263       iter = g_slist_next (iter);
4264     }
4265
4266   g_slist_free (copy);
4267 }
4268
4269 #define CURSOR_ON_MULTIPLIER 0.66
4270 #define CURSOR_OFF_MULTIPLIER 0.34
4271 #define CURSOR_PEND_MULTIPLIER 1.0
4272
4273 static gboolean
4274 cursor_blinks (GtkTextView *text_view)
4275 {
4276   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
4277   gboolean blink;
4278
4279 #ifdef DEBUG_VALIDATION_AND_SCROLLING
4280   return FALSE;
4281 #endif
4282   if (gtk_debug_flags & GTK_DEBUG_UPDATES)
4283     return FALSE;
4284   
4285   g_object_get (G_OBJECT (settings), "gtk-cursor-blink", &blink, NULL);
4286   return blink;
4287 }
4288
4289 static gint
4290 get_cursor_time (GtkTextView *text_view)
4291 {
4292   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
4293   gint time;
4294
4295   g_object_get (G_OBJECT (settings), "gtk-cursor-blink-time", &time, NULL);
4296
4297   return time;
4298 }
4299
4300 /*
4301  * Blink!
4302  */
4303
4304 static gint
4305 blink_cb (gpointer data)
4306 {
4307   GtkTextView *text_view;
4308   gboolean visible;
4309
4310   GDK_THREADS_ENTER ();
4311
4312   text_view = GTK_TEXT_VIEW (data);
4313   
4314   g_assert (text_view->layout);
4315   g_assert (GTK_WIDGET_HAS_FOCUS (text_view));
4316   g_assert (text_view->cursor_visible);
4317
4318   visible = gtk_text_layout_get_cursor_visible (text_view->layout);
4319
4320   if (visible)
4321     text_view->blink_timeout = gtk_timeout_add (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER,
4322                                                 blink_cb,
4323                                                 text_view);
4324   else
4325     text_view->blink_timeout = gtk_timeout_add (get_cursor_time (text_view) * CURSOR_ON_MULTIPLIER,
4326                                                 blink_cb,
4327                                                 text_view);
4328   
4329   gtk_text_layout_set_cursor_visible (text_view->layout,
4330                                       !visible);
4331
4332   GDK_THREADS_LEAVE ();
4333
4334   /* Remove ourselves */
4335   return FALSE;
4336 }
4337
4338
4339 static void
4340 gtk_text_view_stop_cursor_blink (GtkTextView *text_view)
4341 {
4342   if (text_view->blink_timeout)  
4343     { 
4344       gtk_timeout_remove (text_view->blink_timeout);
4345       text_view->blink_timeout = 0;
4346     }
4347 }
4348
4349 static void
4350 gtk_text_view_check_cursor_blink (GtkTextView *text_view)
4351 {
4352   if (text_view->layout != NULL &&
4353       text_view->cursor_visible &&
4354       GTK_WIDGET_HAS_FOCUS (text_view))
4355     {
4356       if (cursor_blinks (text_view))
4357         {
4358           if (text_view->blink_timeout == 0)
4359             {
4360               gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4361               
4362               text_view->blink_timeout = gtk_timeout_add (get_cursor_time (text_view) * CURSOR_OFF_MULTIPLIER,
4363                                                           blink_cb,
4364                                                           text_view);
4365             }
4366         }
4367       else
4368         gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);   
4369     }
4370   else
4371     {
4372       gtk_text_view_stop_cursor_blink (text_view);
4373     }
4374 }
4375
4376 static void
4377 gtk_text_view_pend_cursor_blink(GtkTextView *text_view)
4378 {
4379   if (text_view->layout != NULL &&
4380       text_view->cursor_visible &&
4381       GTK_WIDGET_HAS_FOCUS (text_view) &&
4382       cursor_blinks (text_view))
4383     {
4384       if (text_view->blink_timeout != 0)
4385         {
4386           gtk_timeout_remove (text_view->blink_timeout);
4387           text_view->blink_timeout = 0;
4388         }
4389       
4390       gtk_text_layout_set_cursor_visible (text_view->layout, TRUE);
4391       
4392       text_view->blink_timeout = gtk_timeout_add (get_cursor_time (text_view) * CURSOR_PEND_MULTIPLIER,
4393                                                   blink_cb,
4394                                                   text_view);
4395     }
4396 }
4397
4398
4399 /*
4400  * Key binding handlers
4401  */
4402
4403 static void
4404 gtk_text_view_move_iter_by_lines (GtkTextView *text_view,
4405                                   GtkTextIter *newplace,
4406                                   gint         count)
4407 {
4408   while (count < 0)
4409     {
4410       gtk_text_layout_move_iter_to_previous_line (text_view->layout, newplace);
4411       count++;
4412     }
4413
4414   while (count > 0)
4415     {
4416       gtk_text_layout_move_iter_to_next_line (text_view->layout, newplace);
4417       count--;
4418     }
4419 }
4420
4421 static void
4422 move_cursor (GtkTextView       *text_view,
4423              const GtkTextIter *new_location,
4424              gboolean           extend_selection)
4425 {
4426   if (extend_selection)
4427     gtk_text_buffer_move_mark_by_name (get_buffer (text_view),
4428                                        "insert",
4429                                        new_location);
4430   else
4431     gtk_text_buffer_place_cursor (get_buffer (text_view),
4432                                   new_location);
4433 }
4434
4435 /* FIXME when we are unfrozen and can change GtkMovementStep,
4436  * fix this
4437  */
4438 #define PAGE_HORIZONTALLY_HACK_VALUE 57
4439
4440 static void
4441 gtk_text_view_move_cursor_internal (GtkTextView     *text_view,
4442                                     GtkMovementStep  step,
4443                                     gint             count,
4444                                     gboolean         extend_selection)
4445 {
4446   GtkTextIter insert;
4447   GtkTextIter newplace;
4448
4449   gint cursor_x_pos = 0;
4450
4451   gtk_text_view_reset_im_context (text_view);
4452
4453   if (step == GTK_MOVEMENT_PAGES)
4454     {
4455       gtk_text_view_scroll_pages (text_view, count, extend_selection);
4456       gtk_text_view_pend_cursor_blink (text_view);
4457       return;
4458     }
4459   else if (step == PAGE_HORIZONTALLY_HACK_VALUE)
4460     {
4461       gtk_text_view_scroll_hpages (text_view, count, extend_selection);
4462       gtk_text_view_pend_cursor_blink (text_view);
4463       return;
4464     }
4465
4466   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
4467                                     gtk_text_buffer_get_mark (get_buffer (text_view),
4468                                                               "insert"));
4469   newplace = insert;
4470
4471   if (step == GTK_MOVEMENT_DISPLAY_LINES)
4472     gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, NULL);
4473
4474   switch (step)
4475     {
4476     case GTK_MOVEMENT_LOGICAL_POSITIONS:
4477       gtk_text_iter_forward_cursor_positions (&newplace, count);
4478       break;
4479
4480     case GTK_MOVEMENT_VISUAL_POSITIONS:
4481       gtk_text_layout_move_iter_visually (text_view->layout,
4482                                           &newplace, count);
4483       break;
4484
4485     case GTK_MOVEMENT_WORDS:
4486       if (count < 0)
4487         gtk_text_iter_backward_word_starts (&newplace, -count);
4488       else if (count > 0)
4489         gtk_text_iter_forward_word_ends (&newplace, count);
4490       break;
4491
4492     case GTK_MOVEMENT_DISPLAY_LINES:
4493       gtk_text_view_move_iter_by_lines (text_view, &newplace, count);
4494       gtk_text_layout_move_iter_to_x (text_view->layout, &newplace, cursor_x_pos);
4495       break;
4496
4497     case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
4498       if (count > 1)
4499         gtk_text_view_move_iter_by_lines (text_view, &newplace, --count);
4500       else if (count < -1)
4501         gtk_text_view_move_iter_by_lines (text_view, &newplace, ++count);
4502
4503       if (count != 0)
4504         gtk_text_layout_move_iter_to_line_end (text_view->layout, &newplace, count);
4505       break;
4506
4507     case GTK_MOVEMENT_PARAGRAPHS:
4508       if (count > 0)
4509         {
4510           if (!gtk_text_iter_ends_line (&newplace))
4511             {
4512               gtk_text_iter_forward_to_line_end (&newplace);
4513               --count;
4514             }
4515         }
4516       else if (count < 0)
4517         {
4518           if (gtk_text_iter_get_line_offset (&newplace) > 0)
4519             {
4520               gtk_text_iter_set_line_offset (&newplace, 0);
4521               ++count;
4522             }
4523         }
4524
4525       if (count != 0)
4526         {
4527           gtk_text_iter_forward_lines (&newplace, count);
4528           gtk_text_iter_set_line_offset (&newplace, 0);
4529         }
4530       break;
4531
4532     case GTK_MOVEMENT_PARAGRAPH_ENDS:
4533       if (count > 0)
4534         {
4535           if (!gtk_text_iter_ends_line (&newplace))
4536             gtk_text_iter_forward_to_line_end (&newplace);
4537         }
4538       else if (count < 0)
4539         {
4540           gtk_text_iter_set_line_offset (&newplace, 0);
4541         }
4542       break;
4543
4544     case GTK_MOVEMENT_BUFFER_ENDS:
4545       if (count > 0)
4546         gtk_text_buffer_get_end_iter (get_buffer (text_view), &newplace);
4547       else if (count < 0)
4548         gtk_text_buffer_get_iter_at_offset (get_buffer (text_view), &newplace, 0);
4549       break;
4550       
4551     default:
4552       break;
4553     }
4554
4555   if (!gtk_text_iter_equal (&insert, &newplace))
4556     {
4557       move_cursor (text_view, &newplace, extend_selection);
4558
4559       DV(g_print (G_STRLOC": scrolling onscreen\n"));
4560       gtk_text_view_scroll_mark_onscreen (text_view,
4561                                           gtk_text_buffer_get_mark (get_buffer (text_view),
4562                                                                     "insert"));
4563
4564       if (step == GTK_MOVEMENT_DISPLAY_LINES)
4565         {
4566           gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, -1);
4567         }
4568     }
4569
4570   gtk_text_view_pend_cursor_blink (text_view);
4571 }
4572
4573 static void
4574 gtk_text_view_move_cursor (GtkTextView     *text_view,
4575                            GtkMovementStep  step,
4576                            gint             count,
4577                            gboolean         extend_selection)
4578 {
4579   gtk_text_view_move_cursor_internal (text_view, step, count, extend_selection);
4580 }
4581
4582 static void
4583 gtk_text_view_page_horizontally (GtkTextView     *text_view,
4584                                  gint             count,
4585                                  gboolean         extend_selection)
4586 {
4587   gtk_text_view_move_cursor_internal (text_view, PAGE_HORIZONTALLY_HACK_VALUE,
4588                                       count, extend_selection);
4589 }
4590
4591 static void
4592 gtk_text_view_set_anchor (GtkTextView *text_view)
4593 {
4594   GtkTextIter insert;
4595
4596   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
4597                                     gtk_text_buffer_get_mark (get_buffer (text_view),
4598                                                               "insert"));
4599
4600   gtk_text_buffer_create_mark (get_buffer (text_view), "anchor", &insert, TRUE);
4601 }
4602
4603 static void
4604 gtk_text_view_scroll_pages (GtkTextView *text_view,
4605                             gint         count,
4606                             gboolean     extend_selection)
4607 {
4608   gdouble newval;
4609   gdouble oldval;
4610   GtkAdjustment *adj;
4611   gint cursor_x_pos, cursor_y_pos;
4612   GtkTextIter new_insert;
4613   GtkTextIter anchor;
4614   gint y0, y1;
4615
4616   g_return_if_fail (text_view->vadjustment != NULL);
4617
4618   adj = text_view->vadjustment;
4619
4620   /* Validate the region that will be brought into view by the cursor motion
4621    */
4622   if (count < 0)
4623     {
4624       gtk_text_view_get_first_para_iter (text_view, &anchor);
4625       y0 = adj->page_size;
4626       y1 = adj->page_size + count * adj->page_increment;
4627     }
4628   else
4629     {
4630       gtk_text_view_get_first_para_iter (text_view, &anchor);
4631       y0 = count * adj->page_increment + adj->page_size;
4632       y1 = 0;
4633     }
4634
4635   gtk_text_layout_validate_yrange (text_view->layout, &anchor, y0, y1);
4636   /* FIXME do we need to update the adjustment ranges here? */
4637
4638   if (count < 0 && adj->value <= (adj->lower + 1e-12))
4639     {
4640       /* already at top, just be sure we are at offset 0 */
4641       gtk_text_buffer_get_start_iter (get_buffer (text_view), &new_insert);
4642       move_cursor (text_view, &new_insert, extend_selection);
4643     }
4644   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
4645     {
4646       /* already at bottom, just be sure we are at the end */
4647       gtk_text_buffer_get_end_iter (get_buffer (text_view), &new_insert);
4648       move_cursor (text_view, &new_insert, extend_selection);
4649     }
4650   else
4651     {
4652       gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, &cursor_y_pos);
4653
4654       newval = adj->value;
4655       oldval = adj->value;
4656   
4657       newval += count * adj->page_increment;
4658
4659       set_adjustment_clamped (adj, newval);
4660       cursor_y_pos += adj->value - oldval;
4661
4662       gtk_text_layout_get_iter_at_pixel (text_view->layout, &new_insert, cursor_x_pos, cursor_y_pos);
4663       clamp_iter_onscreen (text_view, &new_insert);
4664       move_cursor (text_view, &new_insert, extend_selection);
4665
4666       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
4667     }
4668   
4669   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
4670    * only guarantees 1 pixel onscreen.
4671    */
4672   DV(g_print (G_STRLOC": scrolling onscreen\n"));
4673   gtk_text_view_scroll_mark_onscreen (text_view,
4674                                       gtk_text_buffer_get_mark (get_buffer (text_view),
4675                                                                 "insert"));
4676 }
4677
4678 static void
4679 gtk_text_view_scroll_hpages (GtkTextView *text_view,
4680                              gint         count,
4681                              gboolean     extend_selection)
4682 {
4683   gdouble newval;
4684   gdouble oldval;
4685   GtkAdjustment *adj;
4686   gint cursor_x_pos, cursor_y_pos;
4687   GtkTextIter new_insert;
4688   gint y, height;
4689   
4690   g_return_if_fail (text_view->hadjustment != NULL);
4691
4692   adj = text_view->hadjustment;
4693
4694   /* Validate the line that we're moving within.
4695    */
4696   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
4697                                     &new_insert,
4698                                     gtk_text_buffer_get_mark (get_buffer (text_view), "insert"));
4699   gtk_text_layout_get_line_yrange (text_view->layout, &new_insert, &y, &height);
4700   gtk_text_layout_validate_yrange (text_view->layout, &new_insert, y, y + height);
4701   /* FIXME do we need to update the adjustment ranges here? */
4702   
4703   if (count < 0 && adj->value <= (adj->lower + 1e-12))
4704     {
4705       /* already at far left, just be sure we are at offset 0 */
4706       gtk_text_iter_set_line_offset (&new_insert, 0);
4707       move_cursor (text_view, &new_insert, extend_selection);
4708     }
4709   else if (count > 0 && adj->value >= (adj->upper - adj->page_size - 1e-12))
4710     {
4711       /* already at far right, just be sure we are at the end */
4712       gtk_text_iter_forward_to_line_end (&new_insert);
4713       move_cursor (text_view, &new_insert, extend_selection);
4714     }
4715   else
4716     {
4717       gtk_text_view_get_virtual_cursor_pos (text_view, &cursor_x_pos, &cursor_y_pos);
4718
4719       newval = adj->value;
4720       oldval = adj->value;
4721   
4722       newval += count * adj->page_increment;
4723
4724       set_adjustment_clamped (adj, newval);
4725       cursor_x_pos += adj->value - oldval;
4726
4727       gtk_text_layout_get_iter_at_pixel (text_view->layout, &new_insert, cursor_x_pos, cursor_y_pos);
4728       clamp_iter_onscreen (text_view, &new_insert);
4729       move_cursor (text_view, &new_insert, extend_selection);
4730
4731       gtk_text_view_set_virtual_cursor_pos (text_view, cursor_x_pos, cursor_y_pos);
4732     }
4733
4734   /*  FIXME for lines shorter than the overall widget width, this results in a
4735    *  "bounce" effect as we scroll to the right of the widget, then scroll
4736    *  back to get the end of the line onscreen.
4737    *      http://bugzilla.gnome.org/show_bug.cgi?id=68963
4738    */
4739   
4740   /* Adjust to have the cursor _entirely_ onscreen, move_mark_onscreen
4741    * only guarantees 1 pixel onscreen.
4742    */
4743   DV(g_print (G_STRLOC": scrolling onscreen\n"));
4744   gtk_text_view_scroll_mark_onscreen (text_view,
4745                                       gtk_text_buffer_get_mark (get_buffer (text_view),
4746                                                                 "insert"));
4747 }
4748
4749 static gboolean
4750 whitespace (gunichar ch, gpointer user_data)
4751 {
4752   return (ch == ' ' || ch == '\t');
4753 }
4754
4755 static gboolean
4756 not_whitespace (gunichar ch, gpointer user_data)
4757 {
4758   return !whitespace (ch, user_data);
4759 }
4760
4761 static gboolean
4762 find_whitepace_region (const GtkTextIter *center,
4763                        GtkTextIter *start, GtkTextIter *end)
4764 {
4765   *start = *center;
4766   *end = *center;
4767
4768   if (gtk_text_iter_backward_find_char (start, not_whitespace, NULL, NULL))
4769     gtk_text_iter_forward_char (start); /* we want the first whitespace... */
4770   if (whitespace (gtk_text_iter_get_char (end), NULL))
4771     gtk_text_iter_forward_find_char (end, not_whitespace, NULL, NULL);
4772
4773   return !gtk_text_iter_equal (start, end);
4774 }
4775
4776 static void
4777 gtk_text_view_insert_at_cursor (GtkTextView *text_view,
4778                                 const gchar *str)
4779 {
4780   gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
4781                                                 text_view->editable);
4782 }
4783
4784 static void
4785 gtk_text_view_delete_from_cursor (GtkTextView   *text_view,
4786                                   GtkDeleteType  type,
4787                                   gint           count)
4788 {
4789   GtkTextIter insert;
4790   GtkTextIter start;
4791   GtkTextIter end;
4792   gboolean leave_one = FALSE;
4793
4794   gtk_text_view_reset_im_context (text_view);
4795
4796   if (type == GTK_DELETE_CHARS)
4797     {
4798       /* Char delete deletes the selection, if one exists */
4799       if (gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
4800                                             text_view->editable))
4801         return;
4802     }
4803
4804   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
4805                                     &insert,
4806                                     gtk_text_buffer_get_mark (get_buffer (text_view),
4807                                                               "insert"));
4808
4809   start = insert;
4810   end = insert;
4811
4812   switch (type)
4813     {
4814     case GTK_DELETE_CHARS:
4815       gtk_text_iter_forward_cursor_positions (&end, count);
4816       break;
4817
4818     case GTK_DELETE_WORD_ENDS:
4819       if (count > 0)
4820         gtk_text_iter_forward_word_ends (&end, count);
4821       else if (count < 0)
4822         gtk_text_iter_backward_word_starts (&start, 0 - count);
4823       break;
4824
4825     case GTK_DELETE_WORDS:
4826       break;
4827
4828     case GTK_DELETE_DISPLAY_LINE_ENDS:
4829       break;
4830
4831     case GTK_DELETE_DISPLAY_LINES:
4832       break;
4833
4834     case GTK_DELETE_PARAGRAPH_ENDS:
4835       /* If we're already at a newline, we need to
4836        * simply delete that newline, instead of
4837        * moving to the next one.
4838        */
4839       if (gtk_text_iter_ends_line (&end))
4840         {
4841           gtk_text_iter_forward_line (&end);
4842           --count;
4843         }
4844
4845       while (count > 0)
4846         {
4847           if (!gtk_text_iter_forward_to_line_end (&end))
4848             break;
4849
4850           --count;
4851         }
4852
4853       /* FIXME figure out what a negative count means
4854          and support that */
4855       break;
4856
4857     case GTK_DELETE_PARAGRAPHS:
4858       if (count > 0)
4859         {
4860           gtk_text_iter_set_line_offset (&start, 0);
4861           gtk_text_iter_forward_to_line_end (&end);
4862
4863           /* Do the lines beyond the first. */
4864           while (count > 1)
4865             {
4866               gtk_text_iter_forward_to_line_end (&end);
4867
4868               --count;
4869             }
4870         }
4871
4872       /* FIXME negative count? */
4873
4874       break;
4875
4876     case GTK_DELETE_WHITESPACE:
4877       {
4878         find_whitepace_region (&insert, &start, &end);
4879       }
4880       break;
4881
4882     default:
4883       break;
4884     }
4885
4886   if (!gtk_text_iter_equal (&start, &end))
4887     {
4888       gtk_text_buffer_begin_user_action (get_buffer (text_view));
4889
4890       if (gtk_text_buffer_delete_interactive (get_buffer (text_view), &start, &end,
4891                                               text_view->editable))
4892         {
4893           if (leave_one)
4894             gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view),
4895                                                           " ", 1,
4896                                                           text_view->editable);
4897         }
4898
4899       gtk_text_buffer_end_user_action (get_buffer (text_view));
4900
4901       DV(g_print (G_STRLOC": scrolling onscreen\n"));
4902       gtk_text_view_scroll_mark_onscreen (text_view,
4903                                           gtk_text_buffer_get_mark (get_buffer (text_view), "insert"));
4904     }
4905 }
4906
4907 static void
4908 gtk_text_view_cut_clipboard (GtkTextView *text_view)
4909 {
4910   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4911                                                       GDK_SELECTION_CLIPBOARD);
4912   
4913   gtk_text_buffer_cut_clipboard (get_buffer (text_view),
4914                                  clipboard,
4915                                  text_view->editable);
4916   DV(g_print (G_STRLOC": scrolling onscreen\n"));
4917   gtk_text_view_scroll_mark_onscreen (text_view,
4918                                       gtk_text_buffer_get_mark (get_buffer (text_view),
4919                                                                 "insert"));
4920 }
4921
4922 static void
4923 gtk_text_view_copy_clipboard (GtkTextView *text_view)
4924 {
4925   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4926                                                       GDK_SELECTION_CLIPBOARD);
4927   
4928   gtk_text_buffer_copy_clipboard (get_buffer (text_view),
4929                                   clipboard);
4930   DV(g_print (G_STRLOC": scrolling onscreen\n"));
4931   gtk_text_view_scroll_mark_onscreen (text_view,
4932                                       gtk_text_buffer_get_mark (get_buffer (text_view),
4933                                                                 "insert"));
4934 }
4935
4936 static void
4937 gtk_text_view_paste_clipboard (GtkTextView *text_view)
4938 {
4939   GtkClipboard *clipboard = gtk_widget_get_clipboard (GTK_WIDGET (text_view),
4940                                                       GDK_SELECTION_CLIPBOARD);
4941   
4942   gtk_text_buffer_paste_clipboard (get_buffer (text_view),
4943                                    clipboard,
4944                                    NULL,
4945                                    text_view->editable);
4946   DV(g_print (G_STRLOC": scrolling onscreen\n"));
4947   gtk_text_view_scroll_mark_onscreen (text_view,
4948                                       gtk_text_buffer_get_mark (get_buffer (text_view),
4949                                                                 "insert"));
4950 }
4951
4952 static void
4953 gtk_text_view_toggle_overwrite (GtkTextView *text_view)
4954 {
4955   text_view->overwrite_mode = !text_view->overwrite_mode;
4956 }
4957
4958 static void
4959 gtk_text_view_move_focus (GtkTextView     *text_view,
4960                           GtkDirectionType direction_type)
4961 {
4962   GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (text_view));
4963
4964   if (!GTK_WIDGET_TOPLEVEL (toplevel))
4965     return;
4966
4967   /* Propagate to toplevel */
4968   g_signal_emit_by_name (G_OBJECT (toplevel), "move_focus", direction_type);
4969 }
4970
4971 /*
4972  * Selections
4973  */
4974
4975 static void
4976 gtk_text_view_unselect (GtkTextView *text_view)
4977 {
4978   GtkTextIter insert;
4979
4980   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
4981                                     &insert,
4982                                     gtk_text_buffer_get_mark (get_buffer (text_view),
4983                                                               "insert"));
4984
4985   gtk_text_buffer_move_mark (get_buffer (text_view),
4986                              gtk_text_buffer_get_mark (get_buffer (text_view),
4987                                                        "selection_bound"),
4988                              &insert);
4989 }
4990
4991 static void
4992 move_mark_to_pointer_and_scroll (GtkTextView *text_view,
4993                                  const gchar *mark_name)
4994 {
4995   gint x, y;
4996   GdkModifierType state;
4997   GtkTextIter newplace;
4998
4999   /*   DV(g_print (G_STRLOC": begin\n")); */
5000   
5001   gdk_window_get_pointer (text_view->text_window->bin_window,
5002                           &x, &y, &state);
5003
5004   /*   DV(g_print (G_STRLOC": get iter at pixel\n"); */
5005   gtk_text_layout_get_iter_at_pixel (text_view->layout,
5006                                      &newplace,
5007                                      x + text_view->xoffset,
5008                                      y + text_view->yoffset);
5009
5010   {
5011     GtkTextMark *mark =
5012       gtk_text_buffer_get_mark (get_buffer (text_view), mark_name);
5013
5014     /* This may invalidate the layout */
5015     DV(g_print (G_STRLOC": move mark\n"));
5016     gtk_text_buffer_move_mark (get_buffer (text_view),
5017                                mark,
5018                                &newplace);
5019
5020     DV(g_print (G_STRLOC": scrolling onscreen\n"));
5021     gtk_text_view_scroll_mark_onscreen (text_view, mark);
5022   }
5023
5024   DV (g_print ("first validate idle leaving %s is %d\n",
5025                G_STRLOC, text_view->first_validate_idle));
5026 }
5027
5028 static gint
5029 selection_scan_timeout (gpointer data)
5030 {
5031   GtkTextView *text_view;
5032
5033   GDK_THREADS_ENTER ();
5034   
5035   text_view = GTK_TEXT_VIEW (data);
5036
5037   DV(g_print (G_STRLOC": calling move_mark_to_pointer_and_scroll\n"));
5038   move_mark_to_pointer_and_scroll (text_view, "insert");
5039
5040   GDK_THREADS_LEAVE ();
5041   
5042   return TRUE; /* remain installed. */
5043 }
5044
5045 #define DND_SCROLL_MARGIN 0.20
5046
5047 static gint
5048 drag_scan_timeout (gpointer data)
5049 {
5050   GtkTextView *text_view;
5051   gint x, y;
5052   GdkModifierType state;
5053   GtkTextIter newplace;
5054
5055   GDK_THREADS_ENTER ();
5056   
5057   text_view = GTK_TEXT_VIEW (data);
5058
5059   gdk_window_get_pointer (text_view->text_window->bin_window,
5060                           &x, &y, &state);
5061   
5062   gtk_text_layout_get_iter_at_pixel (text_view->layout,
5063                                      &newplace,
5064                                      x + text_view->xoffset,
5065                                      y + text_view->yoffset);
5066   
5067   gtk_text_buffer_move_mark (get_buffer (text_view),
5068                              text_view->dnd_mark,
5069                              &newplace);
5070
5071   DV(g_print (G_STRLOC": scrolling onscreen\n"));
5072   gtk_text_view_scroll_to_mark (text_view,
5073                                 text_view->dnd_mark,
5074                                 DND_SCROLL_MARGIN, FALSE, 0.0, 0.0);
5075
5076   GDK_THREADS_LEAVE ();
5077   
5078   return TRUE;
5079 }
5080
5081 static gint
5082 selection_motion_event_handler (GtkTextView *text_view, GdkEventMotion *event, gpointer data)
5083 {
5084   DV(g_print (G_STRLOC": calling move_mark_to_pointer_and_scroll\n"));
5085   move_mark_to_pointer_and_scroll (text_view, "insert");
5086
5087   /* If we had to scroll offscreen, insert a timeout to do so
5088    * again. Note that in the timeout, even if the mouse doesn't
5089    * move, due to this scroll xoffset/yoffset will have changed
5090    * and we'll need to scroll again.
5091    */
5092   if (text_view->scroll_timeout != 0) /* reset on every motion event */
5093     gtk_timeout_remove (text_view->scroll_timeout);
5094   
5095   text_view->scroll_timeout =
5096     gtk_timeout_add (50, selection_scan_timeout, text_view);
5097
5098   return TRUE;
5099 }
5100
5101 static void
5102 gtk_text_view_start_selection_drag (GtkTextView       *text_view,
5103                                     const GtkTextIter *iter,
5104                                     GdkEventButton    *button)
5105 {
5106   GtkTextIter newplace;
5107   GtkTextBuffer *buffer;
5108   
5109   g_return_if_fail (text_view->selection_drag_handler == 0);
5110
5111   gtk_grab_add (GTK_WIDGET (text_view));
5112
5113   buffer = get_buffer (text_view);
5114   
5115   newplace = *iter;
5116
5117   if (button->state & GDK_SHIFT_MASK)
5118     {
5119       /* Extend selection */
5120       GtkTextIter start, end;
5121
5122       gtk_text_buffer_get_selection_bounds (buffer, &start, &end);
5123
5124       if (gtk_text_iter_compare (&newplace, &start) <= 0)
5125         {
5126           gtk_text_buffer_move_mark_by_name (buffer, "insert",
5127                                              &newplace);
5128
5129           gtk_text_buffer_move_mark_by_name (buffer, "selection_bound",
5130                                              &end);
5131         }
5132       else if (gtk_text_iter_compare (&newplace, &end) >= 0)
5133         {
5134           gtk_text_buffer_move_mark_by_name (buffer, "insert",
5135                                              &newplace);
5136
5137           gtk_text_buffer_move_mark_by_name (buffer, "selection_bound",
5138                                              &start);
5139         }
5140     }
5141   else
5142     {
5143       /* Replace selection */
5144       gtk_text_buffer_place_cursor (buffer, &newplace);
5145     }
5146
5147   text_view->selection_drag_handler = gtk_signal_connect (GTK_OBJECT (text_view),
5148                                                           "motion_notify_event",
5149                                                           GTK_SIGNAL_FUNC (selection_motion_event_handler),
5150                                                           NULL);
5151 }
5152
5153 /* returns whether we were really dragging */
5154 static gboolean
5155 gtk_text_view_end_selection_drag (GtkTextView *text_view, GdkEventButton *event)
5156 {
5157   if (text_view->selection_drag_handler == 0)
5158     return FALSE;
5159
5160   gtk_signal_disconnect (GTK_OBJECT (text_view), text_view->selection_drag_handler);
5161   text_view->selection_drag_handler = 0;
5162
5163   if (text_view->scroll_timeout != 0)
5164     {
5165       gtk_timeout_remove (text_view->scroll_timeout);
5166       text_view->scroll_timeout = 0;
5167     }
5168
5169   /* one last update to current position */
5170   DV(g_print (G_STRLOC": calling move_mark_to_pointer_and_scroll\n"));
5171   move_mark_to_pointer_and_scroll (text_view, "insert");
5172
5173   gtk_grab_remove (GTK_WIDGET (text_view));
5174
5175   return TRUE;
5176 }
5177
5178 /*
5179  * Layout utils
5180  */
5181
5182 static void
5183 gtk_text_view_set_attributes_from_style (GtkTextView        *text_view,
5184                                          GtkTextAttributes  *values,
5185                                          GtkStyle           *style)
5186 {
5187   values->appearance.bg_color = style->base[GTK_STATE_NORMAL];
5188   values->appearance.fg_color = style->text[GTK_STATE_NORMAL];
5189
5190   if (values->font)
5191     pango_font_description_free (values->font);
5192
5193   values->font = pango_font_description_copy (style->font_desc);
5194 }
5195
5196 static void
5197 gtk_text_view_check_keymap_direction (GtkTextView *text_view)
5198 {
5199   if (text_view->layout)
5200     {
5201       gboolean split_cursor;
5202       GtkTextDirection new_dir;
5203       GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (text_view));
5204   
5205       g_object_get (G_OBJECT (settings),
5206                     "gtk-split-cursor", &split_cursor,
5207                     NULL);
5208       if (split_cursor)
5209         {
5210           new_dir = GTK_TEXT_DIR_NONE;
5211         }
5212       else
5213         {
5214           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (text_view)));
5215           new_dir = (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_LTR) ?
5216             GTK_TEXT_DIR_LTR : GTK_TEXT_DIR_RTL;
5217         }
5218       
5219       if (text_view->layout->cursor_direction != new_dir)
5220         gtk_text_layout_set_cursor_direction (text_view->layout, new_dir);
5221     }
5222 }
5223
5224 static void
5225 gtk_text_view_ensure_layout (GtkTextView *text_view)
5226 {
5227   GtkWidget *widget;
5228
5229   widget = GTK_WIDGET (text_view);
5230
5231   if (text_view->layout == NULL)
5232     {
5233       GtkTextAttributes *style;
5234       PangoContext *ltr_context, *rtl_context;
5235       GSList *tmp_list;
5236
5237       DV(g_print(G_STRLOC"\n"));
5238       
5239       text_view->layout = gtk_text_layout_new ();
5240
5241       g_signal_connect (G_OBJECT (text_view->layout),
5242                         "invalidated",
5243                         G_CALLBACK (invalidated_handler),
5244                         text_view);
5245
5246       g_signal_connect (G_OBJECT (text_view->layout),
5247                         "changed",
5248                         G_CALLBACK (changed_handler),
5249                         text_view);
5250
5251       g_signal_connect (G_OBJECT (text_view->layout),
5252                         "allocate_child",
5253                         G_CALLBACK (gtk_text_view_child_allocated),
5254                         text_view);
5255       
5256       if (get_buffer (text_view))
5257         gtk_text_layout_set_buffer (text_view->layout, get_buffer (text_view));
5258
5259       if ((GTK_WIDGET_HAS_FOCUS (text_view) && text_view->cursor_visible))
5260         gtk_text_view_pend_cursor_blink (text_view);
5261       else
5262         gtk_text_layout_set_cursor_visible (text_view->layout, FALSE);
5263
5264       ltr_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
5265       pango_context_set_base_dir (ltr_context, PANGO_DIRECTION_LTR);
5266       rtl_context = gtk_widget_create_pango_context (GTK_WIDGET (text_view));
5267       pango_context_set_base_dir (rtl_context, PANGO_DIRECTION_RTL);
5268
5269       gtk_text_layout_set_contexts (text_view->layout, ltr_context, rtl_context);
5270
5271       g_object_unref (G_OBJECT (ltr_context));
5272       g_object_unref (G_OBJECT (rtl_context));
5273
5274       gtk_text_view_check_keymap_direction (text_view);
5275
5276       style = gtk_text_attributes_new ();
5277
5278       gtk_widget_ensure_style (widget);
5279       gtk_text_view_set_attributes_from_style (text_view,
5280                                                style, widget->style);
5281
5282       style->pixels_above_lines = text_view->pixels_above_lines;
5283       style->pixels_below_lines = text_view->pixels_below_lines;
5284       style->pixels_inside_wrap = text_view->pixels_inside_wrap;
5285       style->left_margin = text_view->left_margin;
5286       style->right_margin = text_view->right_margin;
5287       style->indent = text_view->indent;
5288       style->tabs = text_view->tabs ? pango_tab_array_copy (text_view->tabs) : NULL;
5289
5290       style->wrap_mode = text_view->wrap_mode;
5291       style->justification = text_view->justify;
5292       style->direction = gtk_widget_get_direction (GTK_WIDGET (text_view));
5293
5294       gtk_text_layout_set_default_style (text_view->layout, style);
5295
5296       gtk_text_attributes_unref (style);
5297
5298       /* Set layout for all anchored children */
5299
5300       tmp_list = text_view->children;
5301       while (tmp_list != NULL)
5302         {
5303           GtkTextViewChild *vc = tmp_list->data;
5304
5305           if (vc->anchor)
5306             {
5307               gtk_text_anchored_child_set_layout (vc->widget,
5308                                                   text_view->layout);
5309               /* vc may now be invalid! */
5310             }
5311
5312           tmp_list = g_slist_next (tmp_list);
5313         }
5314
5315       gtk_text_view_invalidate (text_view);
5316     }
5317 }
5318
5319 /**
5320  * gtk_text_view_get_default_attributes:
5321  * @text_view: a #GtkTextView
5322  * 
5323  * Obtains a copy of the default text attributes. These are the
5324  * attributes used for text unless a tag overrides them.
5325  * You'd typically pass the default attributes in to
5326  * gtk_text_iter_get_attributes() in order to get the
5327  * attributes in effect at a given text position.
5328  *
5329  * The return value is a copy owned by the caller of this function,
5330  * and should be freed.
5331  * 
5332  * Return value: a new #GtkTextAttributes
5333  **/
5334 GtkTextAttributes*
5335 gtk_text_view_get_default_attributes (GtkTextView *text_view)
5336 {
5337   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
5338   
5339   gtk_text_view_ensure_layout (text_view);
5340
5341   return gtk_text_attributes_copy (text_view->layout->default_style);
5342 }
5343
5344 static void
5345 gtk_text_view_destroy_layout (GtkTextView *text_view)
5346 {
5347   if (text_view->layout)
5348     {
5349       GSList *tmp_list;
5350
5351       gtk_text_view_remove_validate_idles (text_view);
5352
5353       g_signal_handlers_disconnect_by_func (G_OBJECT (text_view->layout),
5354                                             (gpointer) invalidated_handler,
5355                                             text_view);
5356       g_signal_handlers_disconnect_by_func (G_OBJECT (text_view->layout),
5357                                             (gpointer) changed_handler, 
5358                                             text_view);
5359       
5360       /* Remove layout from all anchored children */
5361       tmp_list = text_view->children;
5362       while (tmp_list != NULL)
5363         {
5364           GtkTextViewChild *vc = tmp_list->data;
5365
5366           if (vc->anchor)
5367             {
5368               gtk_text_anchored_child_set_layout (vc->widget, NULL);
5369               /* vc may now be invalid! */
5370             }
5371
5372           tmp_list = g_slist_next (tmp_list);
5373         }
5374       
5375       gtk_text_view_stop_cursor_blink (text_view);
5376       gtk_text_view_end_selection_drag (text_view, NULL);
5377
5378       g_object_unref (G_OBJECT (text_view->layout));
5379       text_view->layout = NULL;
5380     }
5381 }
5382
5383 static void
5384 gtk_text_view_reset_im_context (GtkTextView *text_view)
5385 {
5386   if (text_view->need_im_reset)
5387     {
5388       text_view->need_im_reset = FALSE;
5389       gtk_im_context_reset (text_view->im_context);
5390     }
5391 }
5392
5393 /*
5394  * DND feature
5395  */
5396
5397 static void
5398 gtk_text_view_start_selection_dnd (GtkTextView       *text_view,
5399                                    const GtkTextIter *iter,
5400                                    GdkEventMotion    *event)
5401 {
5402   GdkDragContext *context;
5403   GtkTargetList *target_list;
5404
5405   text_view->drag_start_x = -1;
5406   text_view->drag_start_y = -1;
5407   text_view->pending_place_cursor_button = 0;
5408   
5409   target_list = gtk_target_list_new (target_table,
5410                                      G_N_ELEMENTS (target_table));
5411
5412   context = gtk_drag_begin (GTK_WIDGET (text_view), target_list,
5413                             GDK_ACTION_COPY | GDK_ACTION_MOVE,
5414                             1, (GdkEvent*)event);
5415
5416   gtk_target_list_unref (target_list);
5417
5418   gtk_drag_set_icon_default (context);
5419 }
5420
5421 static void
5422 gtk_text_view_drag_begin (GtkWidget        *widget,
5423                           GdkDragContext   *context)
5424 {
5425   /* do nothing */
5426 }
5427
5428 static void
5429 gtk_text_view_drag_end (GtkWidget        *widget,
5430                         GdkDragContext   *context)
5431 {
5432   GtkTextView *text_view;
5433
5434   text_view = GTK_TEXT_VIEW (widget);
5435 }
5436
5437 static void
5438 gtk_text_view_drag_data_get (GtkWidget        *widget,
5439                              GdkDragContext   *context,
5440                              GtkSelectionData *selection_data,
5441                              guint             info,
5442                              guint             time)
5443 {
5444   GtkTextView *text_view;
5445
5446   text_view = GTK_TEXT_VIEW (widget);
5447
5448   if (selection_data->target == gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
5449     {
5450       GtkTextBuffer *buffer = gtk_text_view_get_buffer (text_view);
5451
5452       gtk_selection_data_set (selection_data,
5453                               gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE),
5454                               8, /* bytes */
5455                               (void*)&buffer,
5456                               sizeof (buffer));
5457     }
5458   else
5459     {
5460       gchar *str;
5461       GtkTextIter start;
5462       GtkTextIter end;
5463
5464       str = NULL;
5465
5466       if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
5467                                                 &start, &end))
5468         {
5469           /* Extract the selected text */
5470           str = gtk_text_iter_get_visible_text (&start, &end);
5471         }
5472
5473       if (str)
5474         {
5475           gtk_selection_data_set_text (selection_data, str, -1);
5476           g_free (str);
5477         }
5478     }
5479 }
5480
5481 static void
5482 gtk_text_view_drag_data_delete (GtkWidget        *widget,
5483                                 GdkDragContext   *context)
5484 {
5485   GtkTextView *text_view;
5486
5487   text_view = GTK_TEXT_VIEW (widget);
5488
5489   gtk_text_buffer_delete_selection (GTK_TEXT_VIEW (widget)->buffer,
5490                                     TRUE, GTK_TEXT_VIEW (widget)->editable);
5491 }
5492
5493 static void
5494 gtk_text_view_drag_leave (GtkWidget        *widget,
5495                           GdkDragContext   *context,
5496                           guint             time)
5497 {
5498   GtkTextView *text_view;
5499
5500   text_view = GTK_TEXT_VIEW (widget);
5501
5502   gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
5503   
5504   if (text_view->scroll_timeout != 0)
5505     gtk_timeout_remove (text_view->scroll_timeout);
5506
5507   text_view->scroll_timeout = 0;
5508 }
5509
5510 static gboolean
5511 gtk_text_view_drag_motion (GtkWidget        *widget,
5512                            GdkDragContext   *context,
5513                            gint              x,
5514                            gint              y,
5515                            guint             time)
5516 {
5517   GtkTextIter newplace;
5518   GtkTextView *text_view;
5519   GtkTextIter start;
5520   GtkTextIter end;
5521   GdkRectangle target_rect;
5522   gint bx, by;
5523   GdkDragAction suggested_action = 0;
5524   
5525   text_view = GTK_TEXT_VIEW (widget);
5526
5527   target_rect = text_view->text_window->allocation;
5528   
5529   if (x < target_rect.x ||
5530       y < target_rect.y ||
5531       x > (target_rect.x + target_rect.width) ||
5532       y > (target_rect.y + target_rect.height))
5533     return FALSE; /* outside the text window, allow parent widgets to handle event */
5534
5535   gtk_text_view_window_to_buffer_coords (text_view,
5536                                          GTK_TEXT_WINDOW_WIDGET,
5537                                          x, y,
5538                                          &bx, &by);
5539
5540   gtk_text_layout_get_iter_at_pixel (text_view->layout,
5541                                      &newplace,
5542                                      bx, by);  
5543
5544   if (gtk_drag_dest_find_target (widget, context,
5545                                  gtk_drag_dest_get_target_list (widget)) == GDK_NONE)
5546     {
5547       /* can't accept any of the offered targets */
5548     }                                 
5549   else if (gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
5550                                             &start, &end) &&
5551            gtk_text_iter_in_range (&newplace, &start, &end))
5552     {
5553       /* We're inside the selection. */
5554     }
5555   else
5556     {      
5557       if (gtk_text_iter_can_insert (&newplace, text_view->editable))
5558         {
5559           GtkWidget *source_widget;
5560           
5561           suggested_action = context->suggested_action;
5562           
5563           source_widget = gtk_drag_get_source_widget (context);
5564           
5565           if (source_widget == widget)
5566             {
5567               /* Default to MOVE, unless the user has
5568                * pressed ctrl or alt to affect available actions
5569                */
5570               if ((context->actions & GDK_ACTION_MOVE) != 0)
5571                 suggested_action = GDK_ACTION_MOVE;
5572             }
5573         }
5574       else
5575         {
5576           /* Can't drop here. */
5577         }
5578     }
5579
5580   if (suggested_action != 0)
5581     {
5582       gtk_text_mark_set_visible (text_view->dnd_mark,
5583                                  text_view->cursor_visible);
5584       
5585       gdk_drag_status (context, suggested_action, time);
5586     }
5587   else
5588     {
5589       gdk_drag_status (context, 0, time);
5590       gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
5591     }
5592       
5593   gtk_text_buffer_move_mark (get_buffer (text_view),
5594                              text_view->dnd_mark,
5595                              &newplace);
5596
5597   DV(g_print (G_STRLOC": scrolling to mark\n"));
5598   gtk_text_view_scroll_to_mark (text_view,
5599                                 text_view->dnd_mark,
5600                                 DND_SCROLL_MARGIN, FALSE, 0.0, 0.0);
5601   
5602   if (text_view->scroll_timeout != 0) /* reset on every motion event */
5603     gtk_timeout_remove (text_view->scroll_timeout);
5604       
5605   text_view->scroll_timeout =
5606     gtk_timeout_add (50, drag_scan_timeout, text_view);
5607
5608   /* TRUE return means don't propagate the drag motion to parent
5609    * widgets that may also be drop sites.
5610    */
5611   return TRUE;
5612 }
5613
5614 static gboolean
5615 gtk_text_view_drag_drop (GtkWidget        *widget,
5616                          GdkDragContext   *context,
5617                          gint              x,
5618                          gint              y,
5619                          guint             time)
5620 {
5621   GtkTextView *text_view;
5622   GtkTextIter drop_point;
5623   GdkAtom target = GDK_NONE;
5624   
5625   text_view = GTK_TEXT_VIEW (widget);
5626   
5627   if (text_view->scroll_timeout != 0)
5628     gtk_timeout_remove (text_view->scroll_timeout);
5629
5630   text_view->scroll_timeout = 0;
5631
5632   gtk_text_mark_set_visible (text_view->dnd_mark, FALSE);
5633
5634   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5635                                     &drop_point,
5636                                     text_view->dnd_mark);
5637
5638   if (gtk_text_iter_can_insert (&drop_point, text_view->editable))
5639     target = gtk_drag_dest_find_target (widget, context, NULL);
5640
5641   if (target != GDK_NONE)
5642     gtk_drag_get_data (widget, context, target, time);
5643   else
5644     gtk_drag_finish (context, FALSE, FALSE, time);
5645
5646   return TRUE;
5647 }
5648
5649 static void
5650 insert_text_data (GtkTextView      *text_view,
5651                   GtkTextIter      *drop_point,
5652                   GtkSelectionData *selection_data)
5653 {
5654   gchar *str;
5655
5656   str = gtk_selection_data_get_text (selection_data);
5657
5658   if (str)
5659     {
5660       gtk_text_buffer_insert_interactive (get_buffer (text_view),
5661                                           drop_point, str, -1,
5662                                           text_view->editable);
5663       g_free (str);
5664     }
5665 }
5666
5667 static void
5668 gtk_text_view_drag_data_received (GtkWidget        *widget,
5669                                   GdkDragContext   *context,
5670                                   gint              x,
5671                                   gint              y,
5672                                   GtkSelectionData *selection_data,
5673                                   guint             info,
5674                                   guint             time)
5675 {
5676   GtkTextIter drop_point;
5677   GtkTextView *text_view;
5678   gboolean success = FALSE;
5679
5680   text_view = GTK_TEXT_VIEW (widget);
5681
5682   if (!text_view->dnd_mark)
5683     goto done;
5684
5685   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
5686                                     &drop_point,
5687                                     text_view->dnd_mark);
5688   
5689   if (!gtk_text_iter_can_insert (&drop_point, text_view->editable))
5690     goto done;
5691
5692   if (selection_data->target == gdk_atom_intern ("GTK_TEXT_BUFFER_CONTENTS", FALSE))
5693     {
5694       GtkTextBuffer *src_buffer = NULL;
5695       GtkTextIter start, end;
5696       gboolean copy_tags = TRUE;
5697
5698       if (selection_data->length != sizeof (src_buffer))
5699         return;
5700
5701       memcpy (&src_buffer, selection_data->data, sizeof (src_buffer));
5702
5703       if (src_buffer == NULL)
5704         return;
5705
5706       g_return_if_fail (GTK_IS_TEXT_BUFFER (src_buffer));
5707
5708       if (gtk_text_buffer_get_tag_table (src_buffer) !=
5709           gtk_text_buffer_get_tag_table (get_buffer (text_view)))
5710         copy_tags = FALSE;
5711
5712       if (gtk_text_buffer_get_selection_bounds (src_buffer,
5713                                                 &start,
5714                                                 &end))
5715         {
5716           if (copy_tags)
5717             gtk_text_buffer_insert_range_interactive (get_buffer (text_view),
5718                                                       &drop_point,
5719                                                       &start,
5720                                                       &end,
5721                                                       text_view->editable);
5722           else
5723             {
5724               gchar *str;
5725
5726               str = gtk_text_iter_get_visible_text (&start, &end);
5727               gtk_text_buffer_insert_interactive (get_buffer (text_view),
5728                                                   &drop_point, str, -1,
5729                                                   text_view->editable);
5730               g_free (str);
5731             }
5732         }
5733     }
5734   else
5735     insert_text_data (text_view, &drop_point, selection_data);
5736
5737   success = TRUE;
5738
5739  done:
5740   gtk_drag_finish (context, success,
5741                    success && context->action == GDK_ACTION_MOVE,
5742                    time);
5743 }
5744
5745 static GtkAdjustment*
5746 get_hadjustment (GtkTextView *text_view)
5747 {
5748   if (text_view->hadjustment == NULL)
5749     gtk_text_view_set_scroll_adjustments (text_view,
5750                                           NULL, /* forces creation */
5751                                           text_view->vadjustment);
5752
5753   return text_view->hadjustment;
5754 }
5755
5756 static GtkAdjustment*
5757 get_vadjustment (GtkTextView *text_view)
5758 {
5759   if (text_view->vadjustment == NULL)
5760     gtk_text_view_set_scroll_adjustments (text_view,
5761                                           text_view->hadjustment,
5762                                           NULL); /* forces creation */
5763   return text_view->vadjustment;
5764 }
5765
5766
5767 static void
5768 gtk_text_view_set_scroll_adjustments (GtkTextView   *text_view,
5769                                       GtkAdjustment *hadj,
5770                                       GtkAdjustment *vadj)
5771 {
5772   gboolean need_adjust = FALSE;
5773
5774   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
5775
5776   if (hadj)
5777     g_return_if_fail (GTK_IS_ADJUSTMENT (hadj));
5778   else
5779     hadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
5780   if (vadj)
5781     g_return_if_fail (GTK_IS_ADJUSTMENT (vadj));
5782   else
5783     vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0));
5784
5785   if (text_view->hadjustment && (text_view->hadjustment != hadj))
5786     {
5787       gtk_signal_disconnect_by_data (GTK_OBJECT (text_view->hadjustment), text_view);
5788       g_object_unref (G_OBJECT (text_view->hadjustment));
5789     }
5790
5791   if (text_view->vadjustment && (text_view->vadjustment != vadj))
5792     {
5793       gtk_signal_disconnect_by_data (GTK_OBJECT (text_view->vadjustment), text_view);
5794       g_object_unref (G_OBJECT (text_view->vadjustment));
5795     }
5796
5797   if (text_view->hadjustment != hadj)
5798     {
5799       text_view->hadjustment = hadj;
5800       g_object_ref (G_OBJECT (text_view->hadjustment));
5801       gtk_object_sink (GTK_OBJECT (text_view->hadjustment));
5802       
5803       gtk_signal_connect (GTK_OBJECT (text_view->hadjustment), "value_changed",
5804                           (GtkSignalFunc) gtk_text_view_value_changed,
5805                           text_view);
5806       need_adjust = TRUE;
5807     }
5808
5809   if (text_view->vadjustment != vadj)
5810     {
5811       text_view->vadjustment = vadj;
5812       g_object_ref (G_OBJECT (text_view->vadjustment));
5813       gtk_object_sink (GTK_OBJECT (text_view->vadjustment));
5814       
5815       gtk_signal_connect (GTK_OBJECT (text_view->vadjustment), "value_changed",
5816                           (GtkSignalFunc) gtk_text_view_value_changed,
5817                           text_view);
5818       need_adjust = TRUE;
5819     }
5820
5821   if (need_adjust)
5822     gtk_text_view_value_changed (NULL, text_view);
5823 }
5824
5825 /* FIXME this adjust_allocation is a big cut-and-paste from
5826  * GtkCList, needs to be some "official" way to do this
5827  * factored out.
5828  */
5829 typedef struct
5830 {
5831   GdkWindow *window;
5832   int dx;
5833   int dy;
5834 } ScrollData;
5835
5836 /* The window to which widget->window is relative */
5837 #define ALLOCATION_WINDOW(widget)               \
5838    (GTK_WIDGET_NO_WINDOW (widget) ?             \
5839     (widget)->window :                          \
5840      gdk_window_get_parent ((widget)->window))
5841
5842 static void
5843 adjust_allocation_recurse (GtkWidget *widget,
5844                            gpointer   data)
5845 {
5846   ScrollData *scroll_data = data;
5847
5848   /* Need to really size allocate instead of just poking
5849    * into widget->allocation if the widget is not realized.
5850    * FIXME someone figure out why this was.
5851    */
5852   if (!GTK_WIDGET_REALIZED (widget))
5853     {
5854       if (GTK_WIDGET_VISIBLE (widget))
5855         {
5856           GdkRectangle tmp_rectangle = widget->allocation;
5857           tmp_rectangle.x += scroll_data->dx;
5858           tmp_rectangle.y += scroll_data->dy;
5859           
5860           gtk_widget_size_allocate (widget, &tmp_rectangle);
5861         }
5862     }
5863   else
5864     {
5865       if (ALLOCATION_WINDOW (widget) == scroll_data->window)
5866         {
5867           widget->allocation.x += scroll_data->dx;
5868           widget->allocation.y += scroll_data->dy;
5869           
5870           if (GTK_IS_CONTAINER (widget))
5871             gtk_container_forall (GTK_CONTAINER (widget),
5872                                   adjust_allocation_recurse,
5873                                   data);
5874         }
5875     }
5876 }
5877
5878 static void
5879 adjust_allocation (GtkWidget *widget,
5880                    int        dx,
5881                    int        dy)
5882 {
5883   ScrollData scroll_data;
5884
5885   if (GTK_WIDGET_REALIZED (widget))
5886     scroll_data.window = ALLOCATION_WINDOW (widget);
5887   else
5888     scroll_data.window = NULL;
5889     
5890   scroll_data.dx = dx;
5891   scroll_data.dy = dy;
5892   
5893   adjust_allocation_recurse (widget, &scroll_data);
5894 }
5895             
5896 static void
5897 gtk_text_view_value_changed (GtkAdjustment *adj,
5898                              GtkTextView   *text_view)
5899 {
5900   GtkTextIter iter;
5901   gint line_top;
5902   gint dx = 0;
5903   gint dy = 0;
5904   
5905   /* Note that we oddly call this function with adj == NULL
5906    * sometimes
5907    */
5908   
5909   text_view->onscreen_validated = FALSE;
5910
5911   DV(g_print(">Scroll offset changed %s/%g, onscreen_validated = FALSE ("G_STRLOC")\n",
5912              adj == text_view->hadjustment ? "hadj" : adj == text_view->vadjustment ? "vadj" : "none",
5913              adj ? adj->value : 0.0));
5914   
5915   if (adj == text_view->hadjustment)
5916     {
5917       dx = text_view->xoffset - (gint)adj->value;
5918       text_view->xoffset = adj->value;
5919     }
5920   else if (adj == text_view->vadjustment)
5921     {
5922       dy = text_view->yoffset - (gint)adj->value;
5923       text_view->yoffset = adj->value;
5924
5925       if (text_view->layout)
5926         {
5927           gtk_text_layout_get_line_at_y (text_view->layout, &iter, adj->value, &line_top);
5928
5929           gtk_text_buffer_move_mark (get_buffer (text_view), text_view->first_para_mark, &iter);
5930
5931           text_view->first_para_pixels = adj->value - line_top;
5932         }
5933     }
5934   
5935   if (dx != 0 || dy != 0)
5936     {
5937       GSList *tmp_list;
5938
5939       if (GTK_WIDGET_REALIZED (text_view))
5940         {
5941           if (dy != 0)
5942             {
5943               if (text_view->left_window)
5944                 text_window_scroll (text_view->left_window, 0, dy);
5945               if (text_view->right_window)
5946                 text_window_scroll (text_view->right_window, 0, dy);
5947             }
5948       
5949           if (dx != 0)
5950             {
5951               if (text_view->top_window)
5952                 text_window_scroll (text_view->top_window, dx, 0);
5953               if (text_view->bottom_window)
5954                 text_window_scroll (text_view->bottom_window, dx, 0);
5955             }
5956       
5957           /* It looks nicer to scroll the main area last, because
5958            * it takes a while, and making the side areas update
5959            * afterward emphasizes the slowness of scrolling the
5960            * main area.
5961            */
5962           text_window_scroll (text_view->text_window, dx, dy);
5963         }
5964       
5965       /* Children are now "moved" in the text window, poke
5966        * into widget->allocation for each child
5967        */
5968       tmp_list = text_view->children;
5969       while (tmp_list != NULL)
5970         {
5971           GtkTextViewChild *child = tmp_list->data;
5972           
5973           if (child->anchor)
5974             adjust_allocation (child->widget, dx, dy);
5975           
5976           tmp_list = g_slist_next (tmp_list);
5977         }
5978     }
5979
5980   /* This could result in invalidation, which would install the
5981    * first_validate_idle, which would validate onscreen;
5982    * but we're going to go ahead and validate here, so
5983    * first_validate_idle shouldn't have anything to do.
5984    */
5985   gtk_text_view_update_layout_width (text_view);
5986   
5987   /* note that validation of onscreen could invoke this function
5988    * recursively, by scrolling to maintain first_para, or in response
5989    * to updating the layout width, however there is no problem with
5990    * that, or shouldn't be.
5991    */
5992   gtk_text_view_validate_onscreen (text_view);
5993   
5994   /* process exposes */
5995   if (GTK_WIDGET_REALIZED (text_view))
5996     {
5997       DV (g_print ("Processing updates (%s)\n", G_STRLOC));
5998       
5999       if (text_view->left_window)
6000         gdk_window_process_updates (text_view->left_window->bin_window, TRUE);
6001
6002       if (text_view->right_window)
6003         gdk_window_process_updates (text_view->right_window->bin_window, TRUE);
6004
6005       if (text_view->top_window)
6006         gdk_window_process_updates (text_view->top_window->bin_window, TRUE);
6007       
6008       if (text_view->bottom_window)
6009         gdk_window_process_updates (text_view->bottom_window->bin_window, TRUE);
6010   
6011       gdk_window_process_updates (text_view->text_window->bin_window, TRUE);
6012     }
6013
6014   /* If this got installed, get rid of it, it's just a waste of time. */
6015   if (text_view->first_validate_idle != 0)
6016     {
6017       g_source_remove (text_view->first_validate_idle);
6018       text_view->first_validate_idle = 0;
6019     }
6020
6021   gtk_text_view_update_im_spot_location (text_view);
6022   
6023   DV(g_print(">End scroll offset changed handler ("G_STRLOC")\n"));
6024 }
6025
6026 static void
6027 gtk_text_view_commit_handler (GtkIMContext  *context,
6028                               const gchar   *str,
6029                               GtkTextView   *text_view)
6030 {
6031   gtk_text_view_commit_text (text_view, str);
6032 }
6033
6034 static void
6035 gtk_text_view_commit_text (GtkTextView   *text_view,
6036                            const gchar   *str)
6037 {
6038   gboolean had_selection;
6039   
6040   gtk_text_buffer_begin_user_action (get_buffer (text_view));
6041
6042   had_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
6043                                                         NULL, NULL);
6044   
6045   gtk_text_buffer_delete_selection (get_buffer (text_view), TRUE,
6046                                     text_view->editable);
6047
6048   if (!strcmp (str, "\n"))
6049     {
6050       gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), "\n", 1,
6051                                                     text_view->editable);
6052     }
6053   else
6054     {
6055       if (!had_selection && text_view->overwrite_mode)
6056         {
6057           GtkTextIter insert;
6058           
6059           gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6060                                             &insert,
6061                                             gtk_text_buffer_get_mark (get_buffer (text_view),
6062                                                                       "insert"));
6063           if (!gtk_text_iter_ends_line (&insert))
6064             gtk_text_view_delete_from_cursor (text_view, GTK_DELETE_CHARS, 1);
6065         }
6066       gtk_text_buffer_insert_interactive_at_cursor (get_buffer (text_view), str, -1,
6067                                                     text_view->editable);
6068     }
6069
6070   gtk_text_buffer_end_user_action (get_buffer (text_view));
6071
6072   DV(g_print (G_STRLOC": scrolling onscreen\n"));
6073   gtk_text_view_scroll_mark_onscreen (text_view,
6074                                       gtk_text_buffer_get_mark (get_buffer (text_view),
6075                                                                 "insert"));
6076 }
6077
6078 static void
6079 gtk_text_view_preedit_changed_handler (GtkIMContext *context,
6080                                        GtkTextView  *text_view)
6081 {
6082   gchar *str;
6083   PangoAttrList *attrs;
6084   gint cursor_pos;
6085
6086   gtk_im_context_get_preedit_string (context, &str, &attrs, &cursor_pos);
6087   gtk_text_layout_set_preedit_string (text_view->layout, str, attrs, cursor_pos);
6088
6089   pango_attr_list_unref (attrs);
6090   g_free (str);
6091 }
6092
6093 static gboolean
6094 gtk_text_view_retrieve_surrounding_handler (GtkIMContext  *context,
6095                                             GtkTextView   *text_view)
6096 {
6097   GtkTextIter start;
6098   GtkTextIter end;
6099   gint pos;
6100   gchar *text;
6101
6102   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &start,  
6103                                     gtk_text_buffer_get_insert (text_view->buffer));
6104   end = start;
6105
6106   pos = gtk_text_iter_get_line_index (&start);
6107   gtk_text_iter_set_line_offset (&start, 0);
6108   gtk_text_iter_forward_to_line_end (&end);
6109
6110   text = gtk_text_iter_get_slice (&start, &end);
6111   gtk_im_context_set_surrounding (context, text, -1, pos);
6112   g_free (text);
6113
6114   return TRUE;
6115 }
6116
6117 static gboolean
6118 gtk_text_view_delete_surrounding_handler (GtkIMContext  *context,
6119                                           gint           offset,
6120                                           gint           n_chars,
6121                                           GtkTextView   *text_view)
6122 {
6123   GtkTextIter start;
6124   GtkTextIter end;
6125
6126   gtk_text_buffer_get_iter_at_mark (text_view->buffer, &start,  
6127                                     gtk_text_buffer_get_insert (text_view->buffer));
6128   end = start;
6129
6130   gtk_text_iter_forward_chars (&start, offset);
6131   gtk_text_iter_forward_chars (&end, offset + n_chars);
6132
6133   gtk_text_buffer_delete (text_view->buffer, &start, &end);
6134
6135   return TRUE;
6136 }
6137
6138 static void
6139 gtk_text_view_mark_set_handler (GtkTextBuffer     *buffer,
6140                                 const GtkTextIter *location,
6141                                 GtkTextMark       *mark,
6142                                 gpointer           data)
6143 {
6144   GtkTextView *text_view = GTK_TEXT_VIEW (data);
6145   gboolean need_reset = FALSE;
6146
6147   if (mark == gtk_text_buffer_get_insert (buffer))
6148     {
6149       text_view->virtual_cursor_x = -1;
6150       text_view->virtual_cursor_y = -1;
6151       gtk_text_view_update_im_spot_location (text_view);
6152       need_reset = TRUE;
6153     }
6154   else if (mark == gtk_text_buffer_get_selection_bound (buffer))
6155     {
6156       need_reset = TRUE;
6157     }
6158
6159   if (need_reset)
6160     gtk_text_view_reset_im_context (text_view);
6161 }
6162
6163 static void
6164 gtk_text_view_get_virtual_cursor_pos (GtkTextView *text_view,
6165                                       gint        *x,
6166                                       gint        *y)
6167 {
6168   GdkRectangle strong_pos;
6169   GtkTextIter insert;
6170
6171   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6172                                     gtk_text_buffer_get_mark (get_buffer (text_view),
6173                                                               "insert"));
6174
6175   if ((x && text_view->virtual_cursor_x == -1) ||
6176       (y && text_view->virtual_cursor_y == -1))
6177     gtk_text_layout_get_cursor_locations (text_view->layout, &insert, &strong_pos, NULL);
6178
6179   if (x)
6180     {
6181       if (text_view->virtual_cursor_x != -1)
6182         *x = text_view->virtual_cursor_x;
6183       else
6184         *x = strong_pos.x;
6185     }
6186
6187   if (y)
6188     {
6189       if (text_view->virtual_cursor_x != -1)
6190         *y = text_view->virtual_cursor_y;
6191       else
6192         *y = strong_pos.y + strong_pos.height / 2;
6193     }
6194 }
6195
6196 static void
6197 gtk_text_view_set_virtual_cursor_pos (GtkTextView *text_view,
6198                                       gint         x,
6199                                       gint         y)
6200 {
6201   GdkRectangle strong_pos;
6202   GtkTextIter insert;
6203
6204   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view), &insert,
6205                                     gtk_text_buffer_get_mark (get_buffer (text_view),
6206                                                               "insert"));
6207
6208   if (x == -1 || y == -1)
6209     gtk_text_layout_get_cursor_locations (text_view->layout, &insert, &strong_pos, NULL);
6210
6211   text_view->virtual_cursor_x = (x == -1) ? strong_pos.x : x;
6212   text_view->virtual_cursor_y = (y == -1) ? strong_pos.y + strong_pos.height / 2 : y;
6213 }
6214
6215 /* Quick hack of a popup menu
6216  */
6217 static void
6218 activate_cb (GtkWidget   *menuitem,
6219              GtkTextView *text_view)
6220 {
6221   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
6222   gtk_signal_emit_by_name (GTK_OBJECT (text_view), signal);
6223 }
6224
6225 static void
6226 append_action_signal (GtkTextView  *text_view,
6227                       GtkWidget    *menu,
6228                       const gchar  *stock_id,
6229                       const gchar  *signal,
6230                       gboolean      sensitive)
6231 {
6232   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
6233
6234   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
6235   gtk_signal_connect (GTK_OBJECT (menuitem), "activate",
6236                       GTK_SIGNAL_FUNC (activate_cb), text_view);
6237
6238   gtk_widget_set_sensitive (menuitem, sensitive);
6239   
6240   gtk_widget_show (menuitem);
6241   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6242 }
6243
6244 static void
6245 popup_menu_detach (GtkWidget *attach_widget,
6246                    GtkMenu   *menu)
6247 {
6248   GTK_TEXT_VIEW (attach_widget)->popup_menu = NULL;
6249 }
6250
6251 static void
6252 popup_position_func (GtkMenu   *menu,
6253                      gint      *x,
6254                      gint      *y,
6255                      gboolean  *push_in,
6256                      gpointer   user_data)
6257 {
6258   GtkTextView *text_view;
6259   GtkWidget *widget;
6260   GdkRectangle cursor_rect;
6261   GdkRectangle onscreen_rect;
6262   gint root_x, root_y;
6263   GtkTextIter iter;
6264   GtkRequisition req;      
6265   GdkScreen *screen;
6266   
6267   text_view = GTK_TEXT_VIEW (user_data);
6268   widget = GTK_WIDGET (text_view);
6269   
6270   g_return_if_fail (GTK_WIDGET_REALIZED (text_view));
6271   
6272   screen = gtk_widget_get_screen (widget);
6273
6274   gdk_window_get_origin (widget->window, &root_x, &root_y);
6275
6276   gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6277                                     &iter,
6278                                     gtk_text_buffer_get_insert (get_buffer (text_view)));
6279
6280   gtk_text_view_get_iter_location (text_view,
6281                                    &iter,
6282                                    &cursor_rect);
6283
6284   gtk_text_view_get_visible_rect (text_view, &onscreen_rect);
6285   
6286   gtk_widget_size_request (text_view->popup_menu, &req);
6287
6288   /* can't use rectangle_intersect since cursor rect can have 0 width */
6289   if (cursor_rect.x >= onscreen_rect.x &&
6290       cursor_rect.x < onscreen_rect.x + onscreen_rect.width &&
6291       cursor_rect.y >= onscreen_rect.y &&
6292       cursor_rect.y < onscreen_rect.y + onscreen_rect.height)
6293     {    
6294       gtk_text_view_buffer_to_window_coords (text_view,
6295                                              GTK_TEXT_WINDOW_WIDGET,
6296                                              cursor_rect.x, cursor_rect.y,
6297                                              &cursor_rect.x, &cursor_rect.y);
6298
6299       *x = root_x + cursor_rect.x + cursor_rect.width;
6300       *y = root_y + cursor_rect.y + cursor_rect.height;
6301     }
6302   else
6303     {
6304       /* Just center the menu, since cursor is offscreen. */      
6305       *x = root_x + (widget->allocation.width / 2 - req.width / 2);
6306       *y = root_y + (widget->allocation.height / 2 - req.height / 2);      
6307     }
6308
6309   /* Ensure sanity */
6310   *x = CLAMP (*x, root_x, (root_x + widget->allocation.width));
6311   *y = CLAMP (*y, root_y, (root_y + widget->allocation.height));
6312
6313   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
6314   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
6315 }
6316
6317 typedef struct
6318 {
6319   GtkTextView *text_view;
6320   gint button;
6321   guint time;
6322 } PopupInfo;
6323
6324 static gboolean
6325 range_contains_editable_text (const GtkTextIter *start,
6326                               const GtkTextIter *end,
6327                               gboolean default_editability)
6328 {
6329   GtkTextIter iter = *start;
6330
6331   while (gtk_text_iter_compare (&iter, end) < 0)
6332     {
6333       if (gtk_text_iter_editable (&iter, default_editability))
6334         return TRUE;
6335       
6336       gtk_text_iter_forward_to_tag_toggle (&iter, NULL);
6337     }
6338
6339   return FALSE;
6340 }                             
6341
6342 static void
6343 unichar_chosen_func (const char *text,
6344                      gpointer    data)
6345 {
6346   GtkTextView *text_view = GTK_TEXT_VIEW (data);
6347
6348   gtk_text_view_commit_text (text_view, text);
6349 }
6350
6351 static void
6352 popup_targets_received (GtkClipboard     *clipboard,
6353                         GtkSelectionData *data,
6354                         gpointer          user_data)
6355 {
6356   PopupInfo *info = user_data;
6357   GtkTextView *text_view = info->text_view;
6358   
6359   if (GTK_WIDGET_REALIZED (text_view))
6360     {
6361       /* We implicitely rely here on the fact that if we are pasting ourself, we'll
6362        * have text targets as well as the private GTK_TEXT_BUFFER_CONTENTS target.
6363        */
6364       gboolean clipboard_contains_text = gtk_selection_data_targets_include_text (data);
6365       GtkWidget *menuitem;
6366       GtkWidget *submenu;
6367       gboolean have_selection;
6368       gboolean can_insert;
6369       GtkTextIter iter;
6370       GtkTextIter sel_start, sel_end;
6371       
6372       if (text_view->popup_menu)
6373         gtk_widget_destroy (text_view->popup_menu);
6374
6375       text_view->popup_menu = gtk_menu_new ();
6376       
6377       gtk_menu_attach_to_widget (GTK_MENU (text_view->popup_menu),
6378                                  GTK_WIDGET (text_view),
6379                                  popup_menu_detach);
6380       
6381       have_selection = gtk_text_buffer_get_selection_bounds (get_buffer (text_view),
6382                                                              &sel_start, &sel_end);
6383       
6384       gtk_text_buffer_get_iter_at_mark (get_buffer (text_view),
6385                                         &iter,
6386                                         gtk_text_buffer_get_insert (get_buffer (text_view)));
6387       
6388       can_insert = gtk_text_iter_can_insert (&iter, text_view->editable);
6389       
6390       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
6391                             have_selection &&
6392                             range_contains_editable_text (&sel_start, &sel_end,
6393                                                           text_view->editable));
6394       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
6395                             have_selection);
6396       append_action_signal (text_view, text_view->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
6397                             can_insert && clipboard_contains_text);
6398       
6399       menuitem = gtk_separator_menu_item_new ();
6400       gtk_widget_show (menuitem);
6401       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
6402       
6403       menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
6404       gtk_widget_show (menuitem);
6405       submenu = gtk_menu_new ();
6406       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
6407       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);
6408       
6409       gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (text_view->im_context),
6410                                             GTK_MENU_SHELL (submenu));
6411
6412       menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode control character"));
6413       gtk_widget_show (menuitem);
6414       gtk_widget_set_sensitive (menuitem, can_insert);
6415       
6416       submenu = gtk_menu_new ();
6417       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
6418       gtk_menu_shell_append (GTK_MENU_SHELL (text_view->popup_menu), menuitem);      
6419
6420       _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
6421                                                     unichar_chosen_func,
6422                                                     text_view);
6423       
6424       gtk_signal_emit (GTK_OBJECT (text_view),
6425                        signals[POPULATE_POPUP],
6426                        text_view->popup_menu);
6427       
6428       if (info->button)
6429         gtk_menu_popup (GTK_MENU (text_view->popup_menu), NULL, NULL,
6430                         NULL, NULL,
6431                         info->button, info->time);
6432       else
6433         {
6434           gtk_menu_popup (GTK_MENU (text_view->popup_menu), NULL, NULL,
6435                           popup_position_func, text_view,
6436                           0, gtk_get_current_event_time ());
6437           _gtk_menu_shell_select_first (GTK_MENU_SHELL (text_view->popup_menu));
6438         }
6439     }
6440
6441   g_object_unref (text_view);
6442   g_free (info);
6443 }
6444
6445 static void
6446 gtk_text_view_do_popup (GtkTextView    *text_view,
6447                         GdkEventButton *event)
6448 {
6449   PopupInfo *info = g_new (PopupInfo, 1);
6450
6451   /* should not need this, see http://bugzilla.gnome.org/show_bug.cgi?id=74620 */
6452   gtk_text_view_end_selection_drag (text_view, event);
6453   
6454   /* In order to know what entries we should make sensitive, we
6455    * ask for the current targets of the clipboard, and when
6456    * we get them, then we actually pop up the menu.
6457    */
6458   info->text_view = g_object_ref (text_view);
6459   
6460   if (event)
6461     {
6462       info->button = event->button;
6463       info->time = event->time;
6464     }
6465   else
6466     {
6467       info->button = 0;
6468       info->time = gtk_get_current_event_time ();
6469     }
6470
6471   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (text_view),
6472                                                             GDK_SELECTION_CLIPBOARD),
6473                                   gdk_atom_intern ("TARGETS", FALSE),
6474                                   popup_targets_received,
6475                                   info);
6476 }
6477
6478 static gboolean
6479 gtk_text_view_popup_menu (GtkWidget *widget)
6480 {
6481   gtk_text_view_do_popup (GTK_TEXT_VIEW (widget), NULL);  
6482   return TRUE;
6483 }
6484
6485 /* Child GdkWindows */
6486
6487
6488 static GtkTextWindow*
6489 text_window_new (GtkTextWindowType  type,
6490                  GtkWidget         *widget,
6491                  gint               width_request,
6492                  gint               height_request)
6493 {
6494   GtkTextWindow *win;
6495
6496   win = g_new (GtkTextWindow, 1);
6497
6498   win->type = type;
6499   win->widget = widget;
6500   win->window = NULL;
6501   win->bin_window = NULL;
6502   win->requisition.width = width_request;
6503   win->requisition.height = height_request;
6504   win->allocation.width = width_request;
6505   win->allocation.height = height_request;
6506   win->allocation.x = 0;
6507   win->allocation.y = 0;
6508
6509   return win;
6510 }
6511
6512 static void
6513 text_window_free (GtkTextWindow *win)
6514 {
6515   if (win->window)
6516     text_window_unrealize (win);
6517
6518   g_free (win);
6519 }
6520
6521 static void
6522 text_window_realize (GtkTextWindow *win,
6523                      GdkWindow     *parent)
6524 {
6525   GdkWindowAttr attributes;
6526   gint attributes_mask;
6527   GdkCursor *cursor;
6528
6529   attributes.window_type = GDK_WINDOW_CHILD;
6530   attributes.x = win->allocation.x;
6531   attributes.y = win->allocation.y;
6532   attributes.width = win->allocation.width;
6533   attributes.height = win->allocation.height;
6534   attributes.wclass = GDK_INPUT_OUTPUT;
6535   attributes.visual = gtk_widget_get_visual (win->widget);
6536   attributes.colormap = gtk_widget_get_colormap (win->widget);
6537   attributes.event_mask = GDK_VISIBILITY_NOTIFY_MASK;
6538
6539   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
6540
6541   win->window = gdk_window_new (parent,
6542                                 &attributes,
6543                                 attributes_mask);
6544
6545   gdk_window_show (win->window);
6546   gdk_window_set_user_data (win->window, win->widget);
6547
6548   attributes.x = 0;
6549   attributes.y = 0;
6550   attributes.width = win->allocation.width;
6551   attributes.height = win->allocation.height;
6552   attributes.event_mask = (GDK_EXPOSURE_MASK            |
6553                            GDK_SCROLL_MASK              |
6554                            GDK_KEY_PRESS_MASK           |
6555                            GDK_BUTTON_PRESS_MASK        |
6556                            GDK_BUTTON_RELEASE_MASK      |
6557                            GDK_POINTER_MOTION_MASK      |
6558                            GDK_POINTER_MOTION_HINT_MASK |
6559                            gtk_widget_get_events (win->widget));
6560
6561   win->bin_window = gdk_window_new (win->window,
6562                                     &attributes,
6563                                     attributes_mask);
6564
6565   gdk_window_show (win->bin_window);
6566   gdk_window_set_user_data (win->bin_window, win->widget);
6567
6568   if (win->type == GTK_TEXT_WINDOW_TEXT)
6569     {
6570       /* I-beam cursor */
6571       cursor = gdk_cursor_new_for_screen (gdk_drawable_get_screen (parent),
6572                                           GDK_XTERM);
6573       gdk_window_set_cursor (win->bin_window, cursor);
6574       gdk_cursor_unref (cursor);
6575
6576       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->im_context,
6577                                         win->window);
6578
6579
6580       gdk_window_set_background (win->bin_window,
6581                                  &win->widget->style->base[GTK_WIDGET_STATE (win->widget)]);
6582     }
6583   else
6584     {
6585       gdk_window_set_background (win->bin_window,
6586                                  &win->widget->style->bg[GTK_WIDGET_STATE (win->widget)]);
6587     }
6588
6589   g_object_set_qdata (G_OBJECT (win->window),
6590                       g_quark_from_static_string ("gtk-text-view-text-window"),
6591                       win);
6592
6593   g_object_set_qdata (G_OBJECT (win->bin_window),
6594                       g_quark_from_static_string ("gtk-text-view-text-window"),
6595                       win);
6596 }
6597
6598 static void
6599 text_window_unrealize (GtkTextWindow *win)
6600 {
6601   if (win->type == GTK_TEXT_WINDOW_TEXT)
6602     {
6603       gtk_im_context_set_client_window (GTK_TEXT_VIEW (win->widget)->im_context,
6604                                         NULL);
6605     }
6606
6607   gdk_window_set_user_data (win->window, NULL);
6608   gdk_window_set_user_data (win->bin_window, NULL);
6609   gdk_window_destroy (win->bin_window);
6610   gdk_window_destroy (win->window);
6611   win->window = NULL;
6612   win->bin_window = NULL;
6613 }
6614
6615 static void
6616 text_window_size_allocate (GtkTextWindow *win,
6617                            GdkRectangle  *rect)
6618 {
6619   win->allocation = *rect;
6620
6621   if (win->window)
6622     {
6623       gdk_window_move_resize (win->window,
6624                               rect->x, rect->y,
6625                               rect->width, rect->height);
6626
6627       gdk_window_resize (win->bin_window,
6628                          rect->width, rect->height);
6629     }
6630 }
6631
6632 static void
6633 text_window_scroll        (GtkTextWindow *win,
6634                            gint           dx,
6635                            gint           dy)
6636 {
6637   if (dx != 0 || dy != 0)
6638     {
6639       gdk_window_scroll (win->bin_window, dx, dy);
6640     }
6641 }
6642
6643 static void
6644 text_window_invalidate_rect (GtkTextWindow *win,
6645                              GdkRectangle  *rect)
6646 {
6647   GdkRectangle window_rect;
6648
6649   gtk_text_view_buffer_to_window_coords (GTK_TEXT_VIEW (win->widget),
6650                                          win->type,
6651                                          rect->x,
6652                                          rect->y,
6653                                          &window_rect.x,
6654                                          &window_rect.y);
6655
6656   window_rect.width = rect->width;
6657   window_rect.height = rect->height;
6658   
6659   /* Adjust the rect as appropriate */
6660   
6661   switch (win->type)
6662     {
6663     case GTK_TEXT_WINDOW_TEXT:
6664       break;
6665
6666     case GTK_TEXT_WINDOW_LEFT:
6667     case GTK_TEXT_WINDOW_RIGHT:
6668       window_rect.x = 0;
6669       window_rect.width = win->allocation.width;
6670       break;
6671
6672     case GTK_TEXT_WINDOW_TOP:
6673     case GTK_TEXT_WINDOW_BOTTOM:
6674       window_rect.y = 0;
6675       window_rect.height = win->allocation.height;
6676       break;
6677
6678     default:
6679       g_warning ("%s: bug!", G_STRLOC);
6680       return;
6681       break;
6682     }
6683           
6684   gdk_window_invalidate_rect (win->bin_window, &window_rect, FALSE);
6685
6686 #if 0
6687   {
6688     GdkColor color = { 0, 65535, 0, 0 };
6689     GdkGC *gc = gdk_gc_new (win->bin_window);
6690     gdk_gc_set_rgb_fg_color (gc, &color);
6691     gdk_draw_rectangle (win->bin_window,
6692                         gc, TRUE, window_rect.x, window_rect.y,
6693                         window_rect.width, window_rect.height);
6694     gdk_gc_unref (gc);
6695   }
6696 #endif
6697 }
6698
6699 static gint
6700 text_window_get_width (GtkTextWindow *win)
6701 {
6702   return win->allocation.width;
6703 }
6704
6705 static gint
6706 text_window_get_height (GtkTextWindow *win)
6707 {
6708   return win->allocation.height;
6709 }
6710
6711 static void
6712 text_window_get_allocation (GtkTextWindow *win,
6713                             GdkRectangle  *rect)
6714 {
6715   *rect = win->allocation;
6716 }
6717
6718 /* Windows */
6719
6720
6721 /**
6722  * gtk_text_view_get_window:
6723  * @text_view: a #GtkTextView
6724  * @win: window to get
6725  *
6726  * Retrieves the #GdkWindow corresponding to an area of the text view;
6727  * possible windows include the overall widget window, child windows
6728  * on the left, right, top, bottom, and the window that displays the
6729  * text buffer. Windows are %NULL and nonexistent if their width or
6730  * height is 0, and are nonexistent before the widget has been
6731  * realized.
6732  *
6733  * Return value: a #GdkWindow, or %NULL
6734  **/
6735 GdkWindow*
6736 gtk_text_view_get_window (GtkTextView *text_view,
6737                           GtkTextWindowType win)
6738 {
6739   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), NULL);
6740
6741   switch (win)
6742     {
6743     case GTK_TEXT_WINDOW_WIDGET:
6744       return GTK_WIDGET (text_view)->window;
6745       break;
6746
6747     case GTK_TEXT_WINDOW_TEXT:
6748       return text_view->text_window->bin_window;
6749       break;
6750
6751     case GTK_TEXT_WINDOW_LEFT:
6752       if (text_view->left_window)
6753         return text_view->left_window->bin_window;
6754       else
6755         return NULL;
6756       break;
6757
6758     case GTK_TEXT_WINDOW_RIGHT:
6759       if (text_view->right_window)
6760         return text_view->right_window->bin_window;
6761       else
6762         return NULL;
6763       break;
6764
6765     case GTK_TEXT_WINDOW_TOP:
6766       if (text_view->top_window)
6767         return text_view->top_window->bin_window;
6768       else
6769         return NULL;
6770       break;
6771
6772     case GTK_TEXT_WINDOW_BOTTOM:
6773       if (text_view->bottom_window)
6774         return text_view->bottom_window->bin_window;
6775       else
6776         return NULL;
6777       break;
6778
6779     case GTK_TEXT_WINDOW_PRIVATE:
6780       g_warning ("%s: You can't get GTK_TEXT_WINDOW_PRIVATE, it has \"PRIVATE\" in the name because it is private.", G_GNUC_FUNCTION);
6781       return NULL;
6782       break;
6783     }
6784
6785   g_warning ("%s: Unknown GtkTextWindowType", G_GNUC_FUNCTION);
6786   return NULL;
6787 }
6788
6789 /**
6790  * gtk_text_view_get_window_type:
6791  * @text_view: a #GtkTextView
6792  * @window: a window type
6793  *
6794  * Usually used to find out which window an event corresponds to.
6795  * If you connect to an event signal on @text_view, this function
6796  * should be called on <literal>event-&gt;window</literal> to
6797  * see which window it was.
6798  *
6799  * Return value: the window type.
6800  **/
6801 GtkTextWindowType
6802 gtk_text_view_get_window_type (GtkTextView *text_view,
6803                                GdkWindow   *window)
6804 {
6805   GtkTextWindow *win;
6806
6807   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
6808   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
6809
6810   if (window == GTK_WIDGET (text_view)->window)
6811     return GTK_TEXT_WINDOW_WIDGET;
6812
6813   win = g_object_get_qdata (G_OBJECT (window),
6814                             g_quark_try_string ("gtk-text-view-text-window"));
6815
6816   if (win)
6817     return win->type;
6818   else
6819     {
6820       return GTK_TEXT_WINDOW_PRIVATE;
6821     }
6822 }
6823
6824 static void
6825 buffer_to_widget (GtkTextView      *text_view,
6826                   gint              buffer_x,
6827                   gint              buffer_y,
6828                   gint             *window_x,
6829                   gint             *window_y)
6830 {  
6831   if (window_x)
6832     {
6833       *window_x = buffer_x - text_view->xoffset;
6834       *window_x += text_view->text_window->allocation.x;
6835     }
6836
6837   if (window_y)
6838     {
6839       *window_y = buffer_y - text_view->yoffset;
6840       *window_y += text_view->text_window->allocation.y;
6841     }
6842 }
6843
6844 static void
6845 widget_to_text_window (GtkTextWindow *win,
6846                        gint           widget_x,
6847                        gint           widget_y,
6848                        gint          *window_x,
6849                        gint          *window_y)
6850 {
6851   if (window_x)
6852     *window_x = widget_x - win->allocation.x;
6853
6854   if (window_y)
6855     *window_y = widget_y - win->allocation.y;
6856 }
6857
6858 static void
6859 buffer_to_text_window (GtkTextView   *text_view,
6860                        GtkTextWindow *win,
6861                        gint           buffer_x,
6862                        gint           buffer_y,
6863                        gint          *window_x,
6864                        gint          *window_y)
6865 {
6866   if (win == NULL)
6867     {
6868       g_warning ("Attempt to convert text buffer coordinates to coordinates "
6869                  "for a nonexistent or private child window of GtkTextView");
6870       return;
6871     }
6872
6873   buffer_to_widget (text_view,
6874                     buffer_x, buffer_y,
6875                     window_x, window_y);
6876
6877   widget_to_text_window (win,
6878                          window_x ? *window_x : 0,
6879                          window_y ? *window_y : 0,
6880                          window_x,
6881                          window_y);
6882 }
6883
6884 /**
6885  * gtk_text_view_buffer_to_window_coords:
6886  * @text_view: a #GtkTextView
6887  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
6888  * @buffer_x: buffer x coordinate
6889  * @buffer_y: buffer y coordinate
6890  * @window_x: window x coordinate return location
6891  * @window_y: window y coordinate return location
6892  *
6893  * Converts coordinate (@buffer_x, @buffer_y) to coordinates for the window
6894  * @win, and stores the result in (@window_x, @window_y). 
6895  *
6896  * Note that you can't convert coordinates for a nonexisting window (see 
6897  * gtk_text_view_set_border_window_size()).
6898  **/
6899 void
6900 gtk_text_view_buffer_to_window_coords (GtkTextView      *text_view,
6901                                        GtkTextWindowType win,
6902                                        gint              buffer_x,
6903                                        gint              buffer_y,
6904                                        gint             *window_x,
6905                                        gint             *window_y)
6906 {
6907   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
6908
6909   switch (win)
6910     {
6911     case GTK_TEXT_WINDOW_WIDGET:
6912       buffer_to_widget (text_view,
6913                         buffer_x, buffer_y,
6914                         window_x, window_y);
6915       break;
6916
6917     case GTK_TEXT_WINDOW_TEXT:
6918       if (window_x)
6919         *window_x = buffer_x - text_view->xoffset;
6920       if (window_y)
6921         *window_y = buffer_y - text_view->yoffset;
6922       break;
6923
6924     case GTK_TEXT_WINDOW_LEFT:
6925       buffer_to_text_window (text_view,
6926                              text_view->left_window,
6927                              buffer_x, buffer_y,
6928                              window_x, window_y);
6929       break;
6930
6931     case GTK_TEXT_WINDOW_RIGHT:
6932       buffer_to_text_window (text_view,
6933                              text_view->right_window,
6934                              buffer_x, buffer_y,
6935                              window_x, window_y);
6936       break;
6937
6938     case GTK_TEXT_WINDOW_TOP:
6939       buffer_to_text_window (text_view,
6940                              text_view->top_window,
6941                              buffer_x, buffer_y,
6942                              window_x, window_y);
6943       break;
6944
6945     case GTK_TEXT_WINDOW_BOTTOM:
6946       buffer_to_text_window (text_view,
6947                              text_view->bottom_window,
6948                              buffer_x, buffer_y,
6949                              window_x, window_y);
6950       break;
6951
6952     case GTK_TEXT_WINDOW_PRIVATE:
6953       g_warning ("%s: can't get coords for private windows", G_STRLOC);
6954       break;
6955
6956     default:
6957       g_warning ("%s: Unknown GtkTextWindowType", G_STRLOC);
6958       break;
6959     }
6960 }
6961
6962 static void
6963 widget_to_buffer (GtkTextView *text_view,
6964                   gint         widget_x,
6965                   gint         widget_y,
6966                   gint        *buffer_x,
6967                   gint        *buffer_y)
6968 {  
6969   if (buffer_x)
6970     {
6971       *buffer_x = widget_x + text_view->xoffset;
6972       *buffer_x -= text_view->text_window->allocation.x;
6973     }
6974
6975   if (buffer_y)
6976     {
6977       *buffer_y = widget_y + text_view->yoffset;
6978       *buffer_y -= text_view->text_window->allocation.y;
6979     }
6980 }
6981
6982 static void
6983 text_window_to_widget (GtkTextWindow *win,
6984                        gint           window_x,
6985                        gint           window_y,
6986                        gint          *widget_x,
6987                        gint          *widget_y)
6988 {
6989   if (widget_x)
6990     *widget_x = window_x + win->allocation.x;
6991
6992   if (widget_y)
6993     *widget_y = window_y + win->allocation.y;
6994 }
6995
6996 static void
6997 text_window_to_buffer (GtkTextView   *text_view,
6998                        GtkTextWindow *win,
6999                        gint           window_x,
7000                        gint           window_y,
7001                        gint          *buffer_x,
7002                        gint          *buffer_y)
7003 {
7004   if (win == NULL)
7005     {
7006       g_warning ("Attempt to convert GtkTextView buffer coordinates into "
7007                  "coordinates for a nonexistent child window.");
7008       return;
7009     }
7010
7011   text_window_to_widget (win,
7012                          window_x,
7013                          window_y,
7014                          buffer_x,
7015                          buffer_y);
7016
7017   widget_to_buffer (text_view,
7018                     buffer_x ? *buffer_x : 0,
7019                     buffer_y ? *buffer_y : 0,
7020                     buffer_x,
7021                     buffer_y);
7022 }
7023
7024 /**
7025  * gtk_text_view_window_to_buffer_coords:
7026  * @text_view: a #GtkTextView
7027  * @win: a #GtkTextWindowType except #GTK_TEXT_WINDOW_PRIVATE
7028  * @window_x: window x coordinate
7029  * @window_y: window y coordinate
7030  * @buffer_x: buffer x coordinate return location
7031  * @buffer_y: buffer y coordinate return location
7032  *
7033  * Converts coordinates on the window identified by @win to buffer
7034  * coordinates, storing the result in (@buffer_x,@buffer_y).
7035  *
7036  * Note that you can't convert coordinates for a nonexisting window (see 
7037  * gtk_text_view_set_border_window_size()).
7038  **/
7039 void
7040 gtk_text_view_window_to_buffer_coords (GtkTextView      *text_view,
7041                                        GtkTextWindowType win,
7042                                        gint              window_x,
7043                                        gint              window_y,
7044                                        gint             *buffer_x,
7045                                        gint             *buffer_y)
7046 {
7047   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7048
7049   switch (win)
7050     {
7051     case GTK_TEXT_WINDOW_WIDGET:
7052       widget_to_buffer (text_view,
7053                         window_x, window_y,
7054                         buffer_x, buffer_y);
7055       break;
7056
7057     case GTK_TEXT_WINDOW_TEXT:
7058       if (buffer_x)
7059         *buffer_x = window_x + text_view->xoffset;
7060       if (buffer_y)
7061         *buffer_y = window_y + text_view->yoffset;
7062       break;
7063
7064     case GTK_TEXT_WINDOW_LEFT:
7065       text_window_to_buffer (text_view,
7066                              text_view->left_window,
7067                              window_x, window_y,
7068                              buffer_x, buffer_y);
7069       break;
7070
7071     case GTK_TEXT_WINDOW_RIGHT:
7072       text_window_to_buffer (text_view,
7073                              text_view->right_window,
7074                              window_x, window_y,
7075                              buffer_x, buffer_y);
7076       break;
7077
7078     case GTK_TEXT_WINDOW_TOP:
7079       text_window_to_buffer (text_view,
7080                              text_view->top_window,
7081                              window_x, window_y,
7082                              buffer_x, buffer_y);
7083       break;
7084
7085     case GTK_TEXT_WINDOW_BOTTOM:
7086       text_window_to_buffer (text_view,
7087                              text_view->bottom_window,
7088                              window_x, window_y,
7089                              buffer_x, buffer_y);
7090       break;
7091
7092     case GTK_TEXT_WINDOW_PRIVATE:
7093       g_warning ("%s: can't get coords for private windows", G_STRLOC);
7094       break;
7095
7096     default:
7097       g_warning ("%s: Unknown GtkTextWindowType", G_STRLOC);
7098       break;
7099     }
7100 }
7101
7102 static void
7103 set_window_width (GtkTextView      *text_view,
7104                   gint              width,
7105                   GtkTextWindowType type,
7106                   GtkTextWindow   **winp)
7107 {
7108   if (width == 0)
7109     {
7110       if (*winp)
7111         {
7112           text_window_free (*winp);
7113           *winp = NULL;
7114           gtk_widget_queue_resize (GTK_WIDGET (text_view));
7115         }
7116     }
7117   else
7118     {
7119       if (*winp == NULL)
7120         {
7121           *winp = text_window_new (type,
7122                                    GTK_WIDGET (text_view),
7123                                    width, 0);
7124           /* if the widget is already realized we need to realize the child manually */
7125           if (GTK_WIDGET_REALIZED (text_view))
7126             text_window_realize (*winp, GTK_WIDGET (text_view)->window);
7127         }
7128       else
7129         {
7130           if ((*winp)->requisition.width == width)
7131             return;
7132
7133           (*winp)->requisition.width = width;
7134         }
7135
7136       gtk_widget_queue_resize (GTK_WIDGET (text_view));
7137     }
7138 }
7139
7140
7141 static void
7142 set_window_height (GtkTextView      *text_view,
7143                    gint              height,
7144                    GtkTextWindowType type,
7145                    GtkTextWindow   **winp)
7146 {
7147   if (height == 0)
7148     {
7149       if (*winp)
7150         {
7151           text_window_free (*winp);
7152           *winp = NULL;
7153           gtk_widget_queue_resize (GTK_WIDGET (text_view));
7154         }
7155     }
7156   else
7157     {
7158       if (*winp == NULL)
7159         {
7160           *winp = text_window_new (type,
7161                                    GTK_WIDGET (text_view),
7162                                    0, height);
7163
7164           /* if the widget is already realized we need to realize the child manually */
7165           if (GTK_WIDGET_REALIZED (text_view))
7166             text_window_realize (*winp, GTK_WIDGET (text_view)->window);
7167         }
7168       else
7169         {
7170           if ((*winp)->requisition.height == height)
7171             return;
7172
7173           (*winp)->requisition.height = height;
7174         }
7175
7176       gtk_widget_queue_resize (GTK_WIDGET (text_view));
7177     }
7178 }
7179
7180 /**
7181  * gtk_text_view_set_border_window_size:
7182  * @text_view: a #GtkTextView
7183  * @type: window to affect
7184  * @size: width or height of the window
7185  *
7186  * Sets the width of %GTK_TEXT_WINDOW_LEFT or %GTK_TEXT_WINDOW_RIGHT,
7187  * or the height of %GTK_TEXT_WINDOW_TOP or %GTK_TEXT_WINDOW_BOTTOM.
7188  * Automatically destroys the corresponding window if the size is set
7189  * to 0, and creates the window if the size is set to non-zero.  This
7190  * function can only be used for the "border windows," it doesn't work
7191  * with #GTK_TEXT_WINDOW_WIDGET, #GTK_TEXT_WINDOW_TEXT, or
7192  * #GTK_TEXT_WINDOW_PRIVATE.
7193  **/
7194 void
7195 gtk_text_view_set_border_window_size (GtkTextView      *text_view,
7196                                       GtkTextWindowType type,
7197                                       gint              size)
7198
7199 {
7200   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7201   g_return_if_fail (size >= 0);
7202
7203   switch (type)
7204     {
7205     case GTK_TEXT_WINDOW_LEFT:
7206       set_window_width (text_view, size, GTK_TEXT_WINDOW_LEFT,
7207                         &text_view->left_window);
7208       break;
7209
7210     case GTK_TEXT_WINDOW_RIGHT:
7211       set_window_width (text_view, size, GTK_TEXT_WINDOW_RIGHT,
7212                         &text_view->right_window);
7213       break;
7214
7215     case GTK_TEXT_WINDOW_TOP:
7216       set_window_height (text_view, size, GTK_TEXT_WINDOW_TOP,
7217                          &text_view->top_window);
7218       break;
7219
7220     case GTK_TEXT_WINDOW_BOTTOM:
7221       set_window_height (text_view, size, GTK_TEXT_WINDOW_BOTTOM,
7222                          &text_view->bottom_window);
7223       break;
7224
7225     default:
7226       g_warning ("Can only set size of left/right/top/bottom border windows with gtk_text_view_set_border_window_size()");
7227       break;
7228     }
7229 }
7230
7231 /**
7232  * gtk_text_view_get_border_window_size:
7233  * @text_view: a #GtkTextView
7234  * @type: window to return size from
7235  *
7236  * Gets the width of the specified border window. See
7237  * gtk_text_view_set_border_window_size().
7238  *
7239  * Return value: width of window
7240  **/
7241 gint
7242 gtk_text_view_get_border_window_size (GtkTextView       *text_view,
7243                                       GtkTextWindowType  type)
7244 {
7245   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), 0);
7246   
7247   switch (type)
7248     {
7249     case GTK_TEXT_WINDOW_LEFT:
7250       if (text_view->left_window)
7251         return text_view->left_window->requisition.width;
7252       
7253     case GTK_TEXT_WINDOW_RIGHT:
7254       if (text_view->right_window)
7255         return text_view->right_window->requisition.width;
7256       
7257     case GTK_TEXT_WINDOW_TOP:
7258       if (text_view->top_window)
7259         return text_view->top_window->requisition.height;
7260
7261     case GTK_TEXT_WINDOW_BOTTOM:
7262       if (text_view->bottom_window)
7263         return text_view->bottom_window->requisition.height;
7264       
7265     default:
7266       g_warning ("Can only get size of left/right/top/bottom border windows with gtk_text_view_get_border_window_size()");
7267       break;
7268     }
7269
7270   return 0;
7271 }
7272
7273 /*
7274  * Child widgets
7275  */
7276
7277 static GtkTextViewChild*
7278 text_view_child_new_anchored (GtkWidget          *child,
7279                               GtkTextChildAnchor *anchor,
7280                               GtkTextLayout      *layout)
7281 {
7282   GtkTextViewChild *vc;
7283
7284   vc = g_new (GtkTextViewChild, 1);
7285
7286   vc->widget = child;
7287   vc->anchor = anchor;
7288
7289   vc->from_top_of_line = 0;
7290   vc->from_left_of_buffer = 0;
7291   
7292   g_object_ref (G_OBJECT (vc->widget));
7293   g_object_ref (G_OBJECT (vc->anchor));
7294
7295   g_object_set_data (G_OBJECT (child),
7296                      "gtk-text-view-child",
7297                      vc);
7298
7299   gtk_text_child_anchor_register_child (anchor, child, layout);
7300   
7301   return vc;
7302 }
7303
7304 static GtkTextViewChild*
7305 text_view_child_new_window (GtkWidget          *child,
7306                             GtkTextWindowType   type,
7307                             gint                x,
7308                             gint                y)
7309 {
7310   GtkTextViewChild *vc;
7311
7312   vc = g_new (GtkTextViewChild, 1);
7313
7314   vc->widget = child;
7315   vc->anchor = NULL;
7316
7317   vc->from_top_of_line = 0;
7318   vc->from_left_of_buffer = 0;
7319   
7320   g_object_ref (G_OBJECT (vc->widget));
7321
7322   vc->type = type;
7323   vc->x = x;
7324   vc->y = y;
7325
7326   g_object_set_data (G_OBJECT (child),
7327                      "gtk-text-view-child",
7328                      vc);
7329   
7330   return vc;
7331 }
7332
7333 static void
7334 text_view_child_free (GtkTextViewChild *child)
7335 {
7336   g_object_set_data (G_OBJECT (child->widget),
7337                      "gtk-text-view-child", NULL);
7338
7339   if (child->anchor)
7340     {
7341       gtk_text_child_anchor_unregister_child (child->anchor,
7342                                               child->widget);
7343       g_object_unref (G_OBJECT (child->anchor));
7344     }
7345
7346   g_object_unref (G_OBJECT (child->widget));
7347
7348   g_free (child);
7349 }
7350
7351 static void
7352 text_view_child_set_parent_window (GtkTextView      *text_view,
7353                                    GtkTextViewChild *vc)
7354 {
7355   if (vc->anchor)
7356     gtk_widget_set_parent_window (vc->widget,
7357                                   text_view->text_window->bin_window);
7358   else
7359     {
7360       GdkWindow *window;
7361       window = gtk_text_view_get_window (text_view,
7362                                          vc->type);
7363       gtk_widget_set_parent_window (vc->widget, window);
7364     }
7365 }
7366
7367 static void
7368 add_child (GtkTextView      *text_view,
7369            GtkTextViewChild *vc)
7370 {
7371   text_view->children = g_slist_prepend (text_view->children,
7372                                          vc);
7373
7374   if (GTK_WIDGET_REALIZED (text_view))
7375     text_view_child_set_parent_window (text_view, vc);
7376   
7377   gtk_widget_set_parent (vc->widget, GTK_WIDGET (text_view));
7378 }
7379
7380 /**
7381  * gtk_text_view_add_child_at_anchor:
7382  * @text_view: a #GtkTextView
7383  * @child: a #GtkWidget
7384  * @anchor: a #GtkTextChildAnchor in the #GtkTextBuffer for @text_view
7385  * 
7386  * Adds a child widget in the text buffer, at the given @anchor.
7387  * 
7388  **/
7389 void
7390 gtk_text_view_add_child_at_anchor (GtkTextView          *text_view,
7391                                    GtkWidget            *child,
7392                                    GtkTextChildAnchor   *anchor)
7393 {
7394   GtkTextViewChild *vc;
7395
7396   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7397   g_return_if_fail (GTK_IS_WIDGET (child));
7398   g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
7399   g_return_if_fail (child->parent == NULL);
7400
7401   gtk_text_view_ensure_layout (text_view);
7402
7403   vc = text_view_child_new_anchored (child, anchor,
7404                                      text_view->layout);
7405
7406   add_child (text_view, vc);
7407
7408   g_assert (vc->widget == child);
7409   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
7410 }
7411
7412 /**
7413  * gtk_text_view_add_child_in_window:
7414  * @text_view: a #GtkTextView
7415  * @child: a #GtkWidget
7416  * @which_window: which window the child should appear in
7417  * @xpos: X position of child in window coordinates
7418  * @ypos: Y position of child in window coordinates
7419  *
7420  * Adds a child at fixed coordinates in one of the text widget's
7421  * windows.  The window must have nonzero size (see
7422  * gtk_text_view_set_border_window_size()).  Note that the child
7423  * coordinates are given relative to the #GdkWindow in question, and
7424  * that these coordinates have no sane relationship to scrolling. When
7425  * placing a child in #GTK_TEXT_WINDOW_WIDGET, scrolling is
7426  * irrelevant, the child floats above all scrollable areas. But when
7427  * placing a child in one of the scrollable windows (border windows or
7428  * text window), you'll need to compute the child's correct position
7429  * in buffer coordinates any time scrolling occurs or buffer changes
7430  * occur, and then call gtk_text_view_move_child() to update the
7431  * child's position. Unfortunately there's no good way to detect that
7432  * scrolling has occurred, using the current API; a possible hack
7433  * would be to update all child positions when the scroll adjustments
7434  * change or the text buffer changes. See bug 64518 on
7435  * bugzilla.gnome.org for status of fixing this issue.
7436  *
7437  **/
7438 void
7439 gtk_text_view_add_child_in_window (GtkTextView          *text_view,
7440                                    GtkWidget            *child,
7441                                    GtkTextWindowType     which_window,
7442                                    gint                  xpos,
7443                                    gint                  ypos)
7444 {
7445   GtkTextViewChild *vc;
7446
7447   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7448   g_return_if_fail (GTK_IS_WIDGET (child));
7449   g_return_if_fail (child->parent == NULL);
7450
7451   vc = text_view_child_new_window (child, which_window,
7452                                    xpos, ypos);
7453
7454   add_child (text_view, vc);
7455
7456   g_assert (vc->widget == child);
7457   g_assert (gtk_widget_get_parent (child) == GTK_WIDGET (text_view));
7458 }
7459
7460 /**
7461  * gtk_text_view_move_child:
7462  * @text_view: a #GtkTextView
7463  * @child: child widget already added to the text view
7464  * @xpos: new X position in window coordinates
7465  * @ypos: new Y position in window coordinates
7466  *
7467  * Updates the position of a child, as for gtk_text_view_add_child_in_window().
7468  * 
7469  **/
7470 void
7471 gtk_text_view_move_child          (GtkTextView          *text_view,
7472                                    GtkWidget            *child,
7473                                    gint                  xpos,
7474                                    gint                  ypos)
7475 {
7476   GtkTextViewChild *vc;
7477
7478   g_return_if_fail (GTK_IS_TEXT_VIEW (text_view));
7479   g_return_if_fail (GTK_IS_WIDGET (child));
7480   g_return_if_fail (child->parent == (GtkWidget*) text_view);
7481
7482   vc = g_object_get_data (G_OBJECT (child),
7483                           "gtk-text-view-child");
7484
7485   g_assert (vc != NULL);
7486
7487   if (vc->x == xpos &&
7488       vc->y == ypos)
7489     return;
7490   
7491   vc->x = xpos;
7492   vc->y = ypos;
7493
7494   if (GTK_WIDGET_VISIBLE (child) && GTK_WIDGET_VISIBLE (text_view))
7495     gtk_widget_queue_resize (child);
7496 }
7497
7498
7499 /* Iterator operations */
7500
7501 /**
7502  * gtk_text_view_forward_display_line:
7503  * @text_view: a #GtkTextView
7504  * @iter: a #GtkTextIter
7505  * 
7506  * Moves the given @iter forward by one display (wrapped) line.  A
7507  * display line is different from a paragraph. Paragraphs are
7508  * separated by newlines or other paragraph separator characters.
7509  * Display lines are created by line-wrapping a paragraph.  If
7510  * wrapping is turned off, display lines and paragraphs will be the
7511  * same. Display lines are divided differently for each view, since
7512  * they depend on the view's width; paragraphs are the same in all
7513  * views, since they depend on the contents of the #GtkTextBuffer.
7514  * 
7515  * Return value: %TRUE if @iter was moved and is not on the end iterator
7516  **/
7517 gboolean
7518 gtk_text_view_forward_display_line (GtkTextView *text_view,
7519                                     GtkTextIter *iter)
7520 {
7521   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7522   g_return_val_if_fail (iter != NULL, FALSE);
7523
7524   gtk_text_view_ensure_layout (text_view);
7525
7526   return gtk_text_layout_move_iter_to_next_line (text_view->layout, iter);
7527 }
7528
7529 /**
7530  * gtk_text_view_backward_display_line:
7531  * @text_view: a #GtkTextView
7532  * @iter: a #GtkTextIter
7533  * 
7534  * Moves the given @iter backward by one display (wrapped) line.  A
7535  * display line is different from a paragraph. Paragraphs are
7536  * separated by newlines or other paragraph separator characters.
7537  * Display lines are created by line-wrapping a paragraph.  If
7538  * wrapping is turned off, display lines and paragraphs will be the
7539  * same. Display lines are divided differently for each view, since
7540  * they depend on the view's width; paragraphs are the same in all
7541  * views, since they depend on the contents of the #GtkTextBuffer.
7542  * 
7543  * Return value: %TRUE if @iter was moved and is not on the end iterator
7544  **/
7545 gboolean
7546 gtk_text_view_backward_display_line (GtkTextView *text_view,
7547                                      GtkTextIter *iter)
7548 {
7549   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7550   g_return_val_if_fail (iter != NULL, FALSE);
7551
7552   gtk_text_view_ensure_layout (text_view);
7553
7554   return gtk_text_layout_move_iter_to_previous_line (text_view->layout, iter);
7555 }
7556
7557 /**
7558  * gtk_text_view_forward_display_line_end:
7559  * @text_view: a #GtkTextView
7560  * @iter: a #GtkTextIter
7561  * 
7562  * Moves the given @iter forward to the next display line end.  A
7563  * display line is different from a paragraph. Paragraphs are
7564  * separated by newlines or other paragraph separator characters.
7565  * Display lines are created by line-wrapping a paragraph.  If
7566  * wrapping is turned off, display lines and paragraphs will be the
7567  * same. Display lines are divided differently for each view, since
7568  * they depend on the view's width; paragraphs are the same in all
7569  * views, since they depend on the contents of the #GtkTextBuffer.
7570  * 
7571  * Return value: %TRUE if @iter was moved and is not on the end iterator
7572  **/
7573 gboolean
7574 gtk_text_view_forward_display_line_end (GtkTextView *text_view,
7575                                         GtkTextIter *iter)
7576 {
7577   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7578   g_return_val_if_fail (iter != NULL, FALSE);
7579
7580   gtk_text_view_ensure_layout (text_view);
7581
7582   return gtk_text_layout_move_iter_to_line_end (text_view->layout, iter, 1);
7583 }
7584
7585 /**
7586  * gtk_text_view_backward_display_line_start:
7587  * @text_view: a #GtkTextView
7588  * @iter: a #GtkTextIter
7589  * 
7590  * Moves the given @iter backward to the next display line start.  A
7591  * display line is different from a paragraph. Paragraphs are
7592  * separated by newlines or other paragraph separator characters.
7593  * Display lines are created by line-wrapping a paragraph.  If
7594  * wrapping is turned off, display lines and paragraphs will be the
7595  * same. Display lines are divided differently for each view, since
7596  * they depend on the view's width; paragraphs are the same in all
7597  * views, since they depend on the contents of the #GtkTextBuffer.
7598  * 
7599  * Return value: %TRUE if @iter was moved and is not on the end iterator
7600  **/
7601 gboolean
7602 gtk_text_view_backward_display_line_start (GtkTextView *text_view,
7603                                            GtkTextIter *iter)
7604 {
7605   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7606   g_return_val_if_fail (iter != NULL, FALSE);
7607
7608   gtk_text_view_ensure_layout (text_view);
7609
7610   return gtk_text_layout_move_iter_to_line_end (text_view->layout, iter, -1);
7611 }
7612
7613 /**
7614  * gtk_text_view_starts_display_line:
7615  * @text_view: a #GtkTextView
7616  * @iter: a #GtkTextIter
7617  * 
7618  * Determines whether @iter is at the start of a display line.
7619  * See gtk_text_view_forward_display_line() for an explanation of
7620  * display lines vs. paragraphs.
7621  * 
7622  * Return value: %TRUE if @iter begins a wrapped line
7623  **/
7624 gboolean
7625 gtk_text_view_starts_display_line (GtkTextView       *text_view,
7626                                    const GtkTextIter *iter)
7627 {
7628   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7629   g_return_val_if_fail (iter != NULL, FALSE);
7630
7631   gtk_text_view_ensure_layout (text_view);
7632
7633   return gtk_text_layout_iter_starts_line (text_view->layout, iter);
7634 }
7635
7636 /**
7637  * gtk_text_view_move_visually:
7638  * @text_view: a #GtkTextView
7639  * @iter: a #GtkTextIter
7640  * @count: number of lines to move
7641  * 
7642  * Moves @iter up or down by @count display (wrapped) lines.
7643  * See gtk_text_view_forward_display_line() for an explanation of
7644  * display lines vs. paragraphs.
7645  * 
7646  * Return value: %TRUE if @iter moved and is not on the end iterator
7647  **/
7648 gboolean
7649 gtk_text_view_move_visually (GtkTextView *text_view,
7650                              GtkTextIter *iter,
7651                              gint         count)
7652 {
7653   g_return_val_if_fail (GTK_IS_TEXT_VIEW (text_view), FALSE);
7654   g_return_val_if_fail (iter != NULL, FALSE);
7655
7656   gtk_text_view_ensure_layout (text_view);
7657
7658   return gtk_text_layout_move_iter_visually (text_view->layout, iter, count);
7659 }