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