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