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