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