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