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