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