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