]> Pileus Git - ~andy/gtk/blob - gtk/gtktextlayout.c
widget: Remove underscore prefix from static function
[~andy/gtk] / gtk / gtktextlayout.c
1 /* GTK - The GIMP Toolkit
2  * gtktextlayout.c - calculate the layout of the text
3  *
4  * Copyright (c) 1992-1994 The Regents of the University of California.
5  * Copyright (c) 1994-1997 Sun Microsystems, Inc.
6  * Copyright (c) 2000 Red Hat, Inc.
7  * Tk->Gtk port by Havoc Pennington
8  * Pango support by Owen Taylor
9  *
10  * This file can be used under your choice of two licenses, the LGPL
11  * and the original Tk license.
12  *
13  * LGPL:
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library. If not, see <http://www.gnu.org/licenses/>.Free
27  *
28  * Original Tk license:
29  *
30  * This software is copyrighted by the Regents of the University of
31  * California, Sun Microsystems, Inc., and other parties.  The
32  * following terms apply to all files associated with the software
33  * unless explicitly disclaimed in individual files.
34  *
35  * The authors hereby grant permission to use, copy, modify,
36  * distribute, and license this software and its documentation for any
37  * purpose, provided that existing copyright notices are retained in
38  * all copies and that this notice is included verbatim in any
39  * distributions. No written agreement, license, or royalty fee is
40  * required for any of the authorized uses.  Modifications to this
41  * software may be copyrighted by their authors and need not follow
42  * the licensing terms described here, provided that the new terms are
43  * clearly indicated on the first page of each file where they apply.
44  *
45  * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY
46  * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
47  * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION,
48  * OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED
49  * OF THE POSSIBILITY OF SUCH DAMAGE.
50  *
51  * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
52  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
53  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
54  * NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS,
55  * AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
56  * MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
57  *
58  * GOVERNMENT USE: If you are acquiring this software on behalf of the
59  * U.S. government, the Government shall have only "Restricted Rights"
60  * in the software and related documentation as defined in the Federal
61  * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
62  * are acquiring the software on behalf of the Department of Defense,
63  * the software shall be classified as "Commercial Computer Software"
64  * and the Government shall have only "Restricted Rights" as defined
65  * in Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the
66  * foregoing, the authors grant the U.S. Government and others acting
67  * in its behalf permission to use and distribute the software in
68  * accordance with the terms specified in this license.
69  *
70  */
71 /*
72  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
73  * file for a list of people on the GTK+ Team.  See the ChangeLog
74  * files for a list of changes.  These files are distributed with
75  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
76  */
77
78 #define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
79 #include "config.h"
80 #include "gtkmarshalers.h"
81 #include "gtktextlayout.h"
82 #include "gtktextbtree.h"
83 #include "gtktextiterprivate.h"
84 #include "gtktextutil.h"
85 #include "gtkintl.h"
86
87 #include <stdlib.h>
88 #include <string.h>
89
90 #define GTK_TEXT_LAYOUT_GET_PRIVATE(o)  (G_TYPE_INSTANCE_GET_PRIVATE ((o), GTK_TYPE_TEXT_LAYOUT, GtkTextLayoutPrivate))
91
92 typedef struct _GtkTextLayoutPrivate GtkTextLayoutPrivate;
93
94 struct _GtkTextLayoutPrivate
95 {
96   /* Cache the line that the cursor is positioned on, as the keyboard
97      direction only influences the direction of the cursor line.
98   */
99   GtkTextLine *cursor_line;
100 };
101
102 static GtkTextLineData *gtk_text_layout_real_wrap (GtkTextLayout *layout,
103                                                    GtkTextLine *line,
104                                                    /* may be NULL */
105                                                    GtkTextLineData *line_data);
106
107 static void gtk_text_layout_invalidated     (GtkTextLayout     *layout);
108
109 static void gtk_text_layout_real_invalidate        (GtkTextLayout     *layout,
110                                                     const GtkTextIter *start,
111                                                     const GtkTextIter *end);
112 static void gtk_text_layout_real_invalidate_cursors(GtkTextLayout     *layout,
113                                                     const GtkTextIter *start,
114                                                     const GtkTextIter *end);
115 static void gtk_text_layout_invalidate_cache       (GtkTextLayout     *layout,
116                                                     GtkTextLine       *line,
117                                                     gboolean           cursors_only);
118 static void gtk_text_layout_invalidate_cursor_line (GtkTextLayout     *layout,
119                                                     gboolean           cursors_only);
120 static void gtk_text_layout_real_free_line_data    (GtkTextLayout     *layout,
121                                                     GtkTextLine       *line,
122                                                     GtkTextLineData   *line_data);
123 static void gtk_text_layout_emit_changed           (GtkTextLayout     *layout,
124                                                     gint               y,
125                                                     gint               old_height,
126                                                     gint               new_height);
127
128 static void gtk_text_layout_invalidate_all (GtkTextLayout *layout);
129
130 static PangoAttribute *gtk_text_attr_appearance_new (const GtkTextAppearance *appearance);
131
132 static void gtk_text_layout_mark_set_handler    (GtkTextBuffer     *buffer,
133                                                  const GtkTextIter *location,
134                                                  GtkTextMark       *mark,
135                                                  gpointer           data);
136 static void gtk_text_layout_buffer_insert_text  (GtkTextBuffer     *textbuffer,
137                                                  GtkTextIter       *iter,
138                                                  gchar             *str,
139                                                  gint               len,
140                                                  gpointer           data);
141 static void gtk_text_layout_buffer_delete_range (GtkTextBuffer     *textbuffer,
142                                                  GtkTextIter       *start,
143                                                  GtkTextIter       *end,
144                                                  gpointer           data);
145
146 static void gtk_text_layout_update_cursor_line (GtkTextLayout *layout);
147
148 static void line_display_index_to_iter (GtkTextLayout      *layout,
149                                         GtkTextLineDisplay *display,
150                                         GtkTextIter        *iter,
151                                         gint                index,
152                                         gint                trailing);
153
154 static gint line_display_iter_to_index (GtkTextLayout      *layout,
155                                         GtkTextLineDisplay *display,
156                                         const GtkTextIter  *iter);
157
158 enum {
159   INVALIDATED,
160   CHANGED,
161   ALLOCATE_CHILD,
162   LAST_SIGNAL
163 };
164
165 enum {
166   ARG_0,
167   LAST_ARG
168 };
169
170 #define PIXEL_BOUND(d) (((d) + PANGO_SCALE - 1) / PANGO_SCALE)
171
172 static guint signals[LAST_SIGNAL] = { 0 };
173
174 PangoAttrType gtk_text_attr_appearance_type = 0;
175
176 G_DEFINE_TYPE (GtkTextLayout, gtk_text_layout, G_TYPE_OBJECT)
177
178 static void
179 gtk_text_layout_dispose (GObject *object)
180 {
181   GtkTextLayout *layout;
182
183   layout = GTK_TEXT_LAYOUT (object);
184
185   gtk_text_layout_set_buffer (layout, NULL);
186
187   if (layout->default_style != NULL)
188     {
189       gtk_text_attributes_unref (layout->default_style);
190       layout->default_style = NULL;
191     }
192
193   g_clear_object (&layout->ltr_context);
194   g_clear_object (&layout->rtl_context);
195
196   if (layout->one_display_cache)
197     {
198       GtkTextLineDisplay *tmp_display = layout->one_display_cache;
199       layout->one_display_cache = NULL;
200       gtk_text_layout_free_line_display (layout, tmp_display);
201     }
202
203   if (layout->preedit_attrs != NULL)
204     {
205       pango_attr_list_unref (layout->preedit_attrs);
206       layout->preedit_attrs = NULL;
207     }
208
209   G_OBJECT_CLASS (gtk_text_layout_parent_class)->dispose (object);
210 }
211
212 static void
213 gtk_text_layout_finalize (GObject *object)
214 {
215   GtkTextLayout *layout;
216
217   layout = GTK_TEXT_LAYOUT (object);
218
219   g_free (layout->preedit_string);
220
221   G_OBJECT_CLASS (gtk_text_layout_parent_class)->finalize (object);
222 }
223
224 static void
225 gtk_text_layout_class_init (GtkTextLayoutClass *klass)
226 {
227   GObjectClass *object_class = G_OBJECT_CLASS (klass);
228
229   object_class->dispose = gtk_text_layout_dispose;
230   object_class->finalize = gtk_text_layout_finalize;
231
232   klass->wrap = gtk_text_layout_real_wrap;
233   klass->invalidate = gtk_text_layout_real_invalidate;
234   klass->invalidate_cursors = gtk_text_layout_real_invalidate_cursors;
235   klass->free_line_data = gtk_text_layout_real_free_line_data;
236
237   signals[INVALIDATED] =
238     g_signal_new (I_("invalidated"),
239                   G_OBJECT_CLASS_TYPE (object_class),
240                   G_SIGNAL_RUN_LAST,
241                   G_STRUCT_OFFSET (GtkTextLayoutClass, invalidated),
242                   NULL, NULL,
243                   _gtk_marshal_VOID__VOID,
244                   G_TYPE_NONE,
245                   0);
246
247   signals[CHANGED] =
248     g_signal_new (I_("changed"),
249                   G_OBJECT_CLASS_TYPE (object_class),
250                   G_SIGNAL_RUN_LAST,
251                   G_STRUCT_OFFSET (GtkTextLayoutClass, changed),
252                   NULL, NULL,
253                   _gtk_marshal_VOID__INT_INT_INT,
254                   G_TYPE_NONE,
255                   3,
256                   G_TYPE_INT,
257                   G_TYPE_INT,
258                   G_TYPE_INT);
259   g_signal_set_va_marshaller (signals[CHANGED], G_TYPE_FROM_CLASS (klass),
260                               _gtk_marshal_VOID__INT_INT_INTv);
261
262   signals[ALLOCATE_CHILD] =
263     g_signal_new (I_("allocate-child"),
264                   G_OBJECT_CLASS_TYPE (object_class),
265                   G_SIGNAL_RUN_LAST,
266                   G_STRUCT_OFFSET (GtkTextLayoutClass, allocate_child),
267                   NULL, NULL,
268                   _gtk_marshal_VOID__OBJECT_INT_INT,
269                   G_TYPE_NONE,
270                   3,
271                   G_TYPE_OBJECT,
272                   G_TYPE_INT,
273                   G_TYPE_INT);
274   
275   g_type_class_add_private (object_class, sizeof (GtkTextLayoutPrivate));
276 }
277
278 static void
279 gtk_text_layout_init (GtkTextLayout *text_layout)
280 {
281   text_layout->cursor_visible = TRUE;
282 }
283
284 GtkTextLayout*
285 gtk_text_layout_new (void)
286 {
287   return g_object_new (GTK_TYPE_TEXT_LAYOUT, NULL);
288 }
289
290 static void
291 free_style_cache (GtkTextLayout *text_layout)
292 {
293   if (text_layout->one_style_cache)
294     {
295       gtk_text_attributes_unref (text_layout->one_style_cache);
296       text_layout->one_style_cache = NULL;
297     }
298 }
299
300 /**
301  * gtk_text_layout_set_buffer:
302  * @buffer: (allow-none):
303  */
304 void
305 gtk_text_layout_set_buffer (GtkTextLayout *layout,
306                             GtkTextBuffer *buffer)
307 {
308   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
309   g_return_if_fail (buffer == NULL || GTK_IS_TEXT_BUFFER (buffer));
310
311   if (layout->buffer == buffer)
312     return;
313
314   free_style_cache (layout);
315
316   if (layout->buffer)
317     {
318       _gtk_text_btree_remove_view (_gtk_text_buffer_get_btree (layout->buffer),
319                                   layout);
320
321       g_signal_handlers_disconnect_by_func (layout->buffer, 
322                                             G_CALLBACK (gtk_text_layout_mark_set_handler), 
323                                             layout);
324       g_signal_handlers_disconnect_by_func (layout->buffer, 
325                                             G_CALLBACK (gtk_text_layout_buffer_insert_text), 
326                                             layout);
327       g_signal_handlers_disconnect_by_func (layout->buffer, 
328                                             G_CALLBACK (gtk_text_layout_buffer_delete_range), 
329                                             layout);
330
331       g_object_unref (layout->buffer);
332       layout->buffer = NULL;
333     }
334
335   if (buffer)
336     {
337       layout->buffer = buffer;
338
339       g_object_ref (buffer);
340
341       _gtk_text_btree_add_view (_gtk_text_buffer_get_btree (buffer), layout);
342
343       /* Bind to all signals that move the insert mark. */
344       g_signal_connect_after (layout->buffer, "mark-set",
345                               G_CALLBACK (gtk_text_layout_mark_set_handler), layout);
346       g_signal_connect_after (layout->buffer, "insert-text",
347                               G_CALLBACK (gtk_text_layout_buffer_insert_text), layout);
348       g_signal_connect_after (layout->buffer, "delete-range",
349                               G_CALLBACK (gtk_text_layout_buffer_delete_range), layout);
350
351       gtk_text_layout_update_cursor_line (layout);
352     }
353 }
354
355 void
356 gtk_text_layout_default_style_changed (GtkTextLayout *layout)
357 {
358   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
359
360   DV (g_print ("invalidating all due to default style change (%s)\n", G_STRLOC));
361   gtk_text_layout_invalidate_all (layout);
362 }
363
364 void
365 gtk_text_layout_set_default_style (GtkTextLayout *layout,
366                                    GtkTextAttributes *values)
367 {
368   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
369   g_return_if_fail (values != NULL);
370
371   if (values == layout->default_style)
372     return;
373
374   gtk_text_attributes_ref (values);
375
376   if (layout->default_style)
377     gtk_text_attributes_unref (layout->default_style);
378
379   layout->default_style = values;
380
381   gtk_text_layout_default_style_changed (layout);
382 }
383
384 void
385 gtk_text_layout_set_contexts (GtkTextLayout *layout,
386                               PangoContext  *ltr_context,
387                               PangoContext  *rtl_context)
388 {
389   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
390
391   if (layout->ltr_context != ltr_context)
392     {
393       if (layout->ltr_context)
394         g_object_unref (layout->ltr_context);
395
396       layout->ltr_context = ltr_context;
397       g_object_ref (layout->ltr_context);
398     }
399
400   if (layout->rtl_context != rtl_context)
401     {
402       if (layout->rtl_context)
403         g_object_unref (layout->rtl_context);
404
405       layout->rtl_context = rtl_context;
406       g_object_ref (layout->rtl_context);
407     }
408
409   DV (g_print ("invalidating all due to new pango contexts (%s)\n", G_STRLOC));
410   gtk_text_layout_invalidate_all (layout);
411 }
412
413 /**
414  * gtk_text_layout_set_overwrite_mode:
415  * @layout: a #GtkTextLayout
416  * @overwrite: overwrite mode
417  *
418  * Sets overwrite mode
419  */
420 void
421 gtk_text_layout_set_overwrite_mode (GtkTextLayout *layout,
422                                     gboolean       overwrite)
423 {
424   overwrite = overwrite != 0;
425   if (overwrite != layout->overwrite_mode)
426     {
427       layout->overwrite_mode = overwrite;
428       gtk_text_layout_invalidate_cursor_line (layout, TRUE);
429     }
430 }
431
432 /**
433  * gtk_text_layout_set_cursor_direction:
434  * @direction: the new direction(s) for which to draw cursors.
435  *             %GTK_TEXT_DIR_NONE means draw cursors for both
436  *             left-to-right insertion and right-to-left insertion.
437  *             (The two cursors will be visually distinguished.)
438  * 
439  * Sets which text directions (left-to-right and/or right-to-left) for
440  * which cursors will be drawn for the insertion point. The visual
441  * point at which new text is inserted depends on whether the new
442  * text is right-to-left or left-to-right, so it may be desired to
443  * make the drawn position of the cursor depend on the keyboard state.
444  */
445 void
446 gtk_text_layout_set_cursor_direction (GtkTextLayout   *layout,
447                                       GtkTextDirection direction)
448 {
449   if (direction != layout->cursor_direction)
450     {
451       layout->cursor_direction = direction;
452       gtk_text_layout_invalidate_cursor_line (layout, TRUE);
453     }
454 }
455
456 /**
457  * gtk_text_layout_set_keyboard_direction:
458  * @keyboard_dir: the current direction of the keyboard.
459  *
460  * Sets the keyboard direction; this is used as for the bidirectional
461  * base direction for the line with the cursor if the line contains
462  * only neutral characters.
463  */
464 void
465 gtk_text_layout_set_keyboard_direction (GtkTextLayout   *layout,
466                                         GtkTextDirection keyboard_dir)
467 {
468   if (keyboard_dir != layout->keyboard_direction)
469     {
470       layout->keyboard_direction = keyboard_dir;
471       gtk_text_layout_invalidate_cursor_line (layout, TRUE);
472     }
473 }
474
475 /**
476  * gtk_text_layout_get_buffer:
477  * @layout: a #GtkTextLayout
478  *
479  * Gets the text buffer used by the layout. See
480  * gtk_text_layout_set_buffer().
481  *
482  * Return value: the text buffer used by the layout.
483  */
484 GtkTextBuffer *
485 gtk_text_layout_get_buffer (GtkTextLayout *layout)
486 {
487   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), NULL);
488
489   return layout->buffer;
490 }
491
492 void
493 gtk_text_layout_set_screen_width (GtkTextLayout *layout, gint width)
494 {
495   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
496   g_return_if_fail (width >= 0);
497   g_return_if_fail (layout->wrap_loop_count == 0);
498
499   if (layout->screen_width == width)
500     return;
501
502   layout->screen_width = width;
503
504   DV (g_print ("invalidating all due to new screen width (%s)\n", G_STRLOC));
505   gtk_text_layout_invalidate_all (layout);
506 }
507
508 /**
509  * gtk_text_layout_set_cursor_visible:
510  * @layout: a #GtkTextLayout
511  * @cursor_visible: If %FALSE, then the insertion cursor will not
512  *   be shown, even if the text is editable.
513  *
514  * Sets whether the insertion cursor should be shown. Generally,
515  * widgets using #GtkTextLayout will hide the cursor when the
516  * widget does not have the input focus.
517  */
518 void
519 gtk_text_layout_set_cursor_visible (GtkTextLayout *layout,
520                                     gboolean       cursor_visible)
521 {
522   cursor_visible = (cursor_visible != FALSE);
523
524   if (layout->cursor_visible != cursor_visible)
525     {
526       GtkTextIter iter;
527       gint y, height;
528
529       layout->cursor_visible = cursor_visible;
530
531       /* Now queue a redraw on the paragraph containing the cursor
532        */
533       gtk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
534                                         gtk_text_buffer_get_insert (layout->buffer));
535
536       gtk_text_layout_get_line_yrange (layout, &iter, &y, &height);
537       gtk_text_layout_emit_changed (layout, y, height, height);
538
539       gtk_text_layout_invalidate_cache (layout, _gtk_text_iter_get_text_line (&iter), TRUE);
540     }
541 }
542
543 /**
544  * gtk_text_layout_get_cursor_visible:
545  * @layout: a #GtkTextLayout
546  *
547  * Returns whether the insertion cursor will be shown.
548  *
549  * Return value: if %FALSE, the insertion cursor will not be
550  *     shown, even if the text is editable.
551  */
552 gboolean
553 gtk_text_layout_get_cursor_visible (GtkTextLayout *layout)
554 {
555   return layout->cursor_visible;
556 }
557
558 /**
559  * gtk_text_layout_set_preedit_string:
560  * @layout: a #PangoLayout
561  * @preedit_string: a string to display at the insertion point
562  * @preedit_attrs: a #PangoAttrList of attributes that apply to @preedit_string
563  * @cursor_pos: position of cursor within preedit string in chars
564  * 
565  * Set the preedit string and attributes. The preedit string is a
566  * string showing text that is currently being edited and not
567  * yet committed into the buffer.
568  */
569 void
570 gtk_text_layout_set_preedit_string (GtkTextLayout *layout,
571                                     const gchar   *preedit_string,
572                                     PangoAttrList *preedit_attrs,
573                                     gint           cursor_pos)
574 {
575   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
576   g_return_if_fail (preedit_attrs != NULL || preedit_string == NULL);
577
578   g_free (layout->preedit_string);
579
580   if (layout->preedit_attrs)
581     pango_attr_list_unref (layout->preedit_attrs);
582
583   if (preedit_string)
584     {
585       layout->preedit_string = g_strdup (preedit_string);
586       layout->preedit_len = strlen (layout->preedit_string);
587       pango_attr_list_ref (preedit_attrs);
588       layout->preedit_attrs = preedit_attrs;
589
590       cursor_pos = CLAMP (cursor_pos, 0, g_utf8_strlen (layout->preedit_string, -1));
591       layout->preedit_cursor = g_utf8_offset_to_pointer (layout->preedit_string, cursor_pos) - layout->preedit_string;
592     }
593   else
594     {
595       layout->preedit_string = NULL;
596       layout->preedit_len = 0;
597       layout->preedit_attrs = NULL;
598       layout->preedit_cursor = 0;
599     }
600
601   gtk_text_layout_invalidate_cursor_line (layout, FALSE);
602 }
603
604 void
605 gtk_text_layout_get_size (GtkTextLayout *layout,
606                           gint *width,
607                           gint *height)
608 {
609   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
610
611   if (width)
612     *width = layout->width;
613
614   if (height)
615     *height = layout->height;
616 }
617
618 static void
619 gtk_text_layout_invalidated (GtkTextLayout *layout)
620 {
621   g_signal_emit (layout, signals[INVALIDATED], 0);
622 }
623
624 static void
625 gtk_text_layout_emit_changed (GtkTextLayout *layout,
626                               gint           y,
627                               gint           old_height,
628                               gint           new_height)
629 {
630   g_signal_emit (layout, signals[CHANGED], 0, y, old_height, new_height);
631 }
632
633 static void
634 text_layout_changed (GtkTextLayout *layout,
635                      gint           y,
636                      gint           old_height,
637                      gint           new_height,
638                      gboolean       cursors_only)
639 {
640   /* Check if the range intersects our cached line display,
641    * and invalidate the cached line if so.
642    */
643   if (layout->one_display_cache)
644     {
645       GtkTextLine *line = layout->one_display_cache->line;
646       gint cache_y = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
647                                                     line, layout);
648       gint cache_height = layout->one_display_cache->height;
649
650       if (cache_y + cache_height > y && cache_y < y + old_height)
651         gtk_text_layout_invalidate_cache (layout, line, cursors_only);
652     }
653
654   gtk_text_layout_emit_changed (layout, y, old_height, new_height);
655 }
656
657 void
658 gtk_text_layout_changed (GtkTextLayout *layout,
659                          gint           y,
660                          gint           old_height,
661                          gint           new_height)
662 {
663   text_layout_changed (layout, y, old_height, new_height, FALSE);
664 }
665
666 void
667 gtk_text_layout_cursors_changed (GtkTextLayout *layout,
668                                  gint           y,
669                                  gint           old_height,
670                                  gint           new_height)
671 {
672   text_layout_changed (layout, y, old_height, new_height, TRUE);
673 }
674
675 void
676 gtk_text_layout_free_line_data (GtkTextLayout     *layout,
677                                 GtkTextLine       *line,
678                                 GtkTextLineData   *line_data)
679 {
680   GTK_TEXT_LAYOUT_GET_CLASS (layout)->free_line_data (layout, line, line_data);
681 }
682
683 void
684 gtk_text_layout_invalidate (GtkTextLayout *layout,
685                             const GtkTextIter *start_index,
686                             const GtkTextIter *end_index)
687 {
688   GTK_TEXT_LAYOUT_GET_CLASS (layout)->invalidate (layout, start_index, end_index);
689 }
690
691 void
692 gtk_text_layout_invalidate_cursors (GtkTextLayout *layout,
693                                     const GtkTextIter *start_index,
694                                     const GtkTextIter *end_index)
695 {
696   GTK_TEXT_LAYOUT_GET_CLASS (layout)->invalidate_cursors (layout, start_index, end_index);
697 }
698
699 GtkTextLineData*
700 gtk_text_layout_wrap (GtkTextLayout *layout,
701                       GtkTextLine  *line,
702                       /* may be NULL */
703                       GtkTextLineData *line_data)
704 {
705   return GTK_TEXT_LAYOUT_GET_CLASS (layout)->wrap (layout, line, line_data);
706 }
707
708
709 /**
710  * gtk_text_layout_get_lines:
711  *
712  * Return value: (element-type GtkTextLine) (transfer container):
713  */
714 GSList*
715 gtk_text_layout_get_lines (GtkTextLayout *layout,
716                            /* [top_y, bottom_y) */
717                            gint top_y,
718                            gint bottom_y,
719                            gint *first_line_y)
720 {
721   GtkTextLine *first_btree_line;
722   GtkTextLine *last_btree_line;
723   GtkTextLine *line;
724   GSList *retval;
725
726   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), NULL);
727   g_return_val_if_fail (bottom_y > top_y, NULL);
728
729   retval = NULL;
730
731   first_btree_line =
732     _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
733                                    layout, top_y, first_line_y);
734   if (first_btree_line == NULL)
735     {
736       /* off the bottom */
737       return NULL;
738     }
739
740   /* -1 since bottom_y is one past */
741   last_btree_line =
742     _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
743                                     layout, bottom_y - 1, NULL);
744
745   if (!last_btree_line)
746     last_btree_line =
747       _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
748
749   g_assert (last_btree_line != NULL);
750
751   line = first_btree_line;
752   while (TRUE)
753     {
754       retval = g_slist_prepend (retval, line);
755
756       if (line == last_btree_line)
757         break;
758
759       line = _gtk_text_line_next_excluding_last (line);
760     }
761
762   retval = g_slist_reverse (retval);
763
764   return retval;
765 }
766
767 static void
768 invalidate_cached_style (GtkTextLayout *layout)
769 {
770   free_style_cache (layout);
771 }
772
773 /* These should be called around a loop which wraps a CONTIGUOUS bunch
774  * of display lines. If the lines aren't contiguous you can't call
775  * these.
776  */
777 void
778 gtk_text_layout_wrap_loop_start (GtkTextLayout *layout)
779 {
780   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
781   g_return_if_fail (layout->one_style_cache == NULL);
782
783   layout->wrap_loop_count += 1;
784 }
785
786 void
787 gtk_text_layout_wrap_loop_end (GtkTextLayout *layout)
788 {
789   g_return_if_fail (layout->wrap_loop_count > 0);
790
791   layout->wrap_loop_count -= 1;
792
793   if (layout->wrap_loop_count == 0)
794     {
795       /* We cache a some stuff if we're iterating over some lines wrapping
796        * them. This cleans it up.
797        */
798       /* Nuke our cached style */
799       invalidate_cached_style (layout);
800       g_assert (layout->one_style_cache == NULL);
801     }
802 }
803
804 static void
805 gtk_text_layout_invalidate_all (GtkTextLayout *layout)
806 {
807   GtkTextIter start;
808   GtkTextIter end;
809
810   if (layout->buffer == NULL)
811     return;
812
813   gtk_text_buffer_get_bounds (layout->buffer, &start, &end);
814
815   gtk_text_layout_invalidate (layout, &start, &end);
816 }
817
818 static void
819 gtk_text_layout_invalidate_cache (GtkTextLayout *layout,
820                                   GtkTextLine   *line,
821                                   gboolean       cursors_only)
822 {
823   if (layout->one_display_cache && line == layout->one_display_cache->line)
824     {
825       GtkTextLineDisplay *display = layout->one_display_cache;
826
827       if (cursors_only)
828         {
829           if (display->cursors)
830             g_array_free (display->cursors, TRUE);
831           display->cursors = NULL;
832           display->cursors_invalid = TRUE;
833           display->has_block_cursor = FALSE;
834         }
835       else
836         {
837           layout->one_display_cache = NULL;
838           gtk_text_layout_free_line_display (layout, display);
839         }
840     }
841 }
842
843 /* Now invalidate the paragraph containing the cursor
844  */
845 static void
846 gtk_text_layout_invalidate_cursor_line (GtkTextLayout *layout,
847                                         gboolean cursors_only)
848 {
849   GtkTextLayoutPrivate *priv = GTK_TEXT_LAYOUT_GET_PRIVATE (layout);
850   GtkTextLineData *line_data;
851
852   if (priv->cursor_line == NULL)
853     return;
854
855   line_data = _gtk_text_line_get_data (priv->cursor_line, layout);
856   if (line_data)
857     {
858       if (cursors_only)
859           gtk_text_layout_invalidate_cache (layout, priv->cursor_line, TRUE);
860       else
861         {
862           gtk_text_layout_invalidate_cache (layout, priv->cursor_line, FALSE);
863           _gtk_text_line_invalidate_wrap (priv->cursor_line, line_data);
864         }
865
866       gtk_text_layout_invalidated (layout);
867     }
868 }
869
870 static void
871 gtk_text_layout_update_cursor_line(GtkTextLayout *layout)
872 {
873   GtkTextLayoutPrivate *priv = GTK_TEXT_LAYOUT_GET_PRIVATE (layout);
874   GtkTextIter iter;
875
876   gtk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
877                                     gtk_text_buffer_get_insert (layout->buffer));
878
879   priv->cursor_line = _gtk_text_iter_get_text_line (&iter);
880 }
881
882 static void
883 gtk_text_layout_real_invalidate (GtkTextLayout *layout,
884                                  const GtkTextIter *start,
885                                  const GtkTextIter *end)
886 {
887   GtkTextLine *line;
888   GtkTextLine *last_line;
889
890   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
891   g_return_if_fail (layout->wrap_loop_count == 0);
892
893   /* Because we may be invalidating a mark, it's entirely possible
894    * that gtk_text_iter_equal (start, end) in which case we
895    * should still invalidate the line they are both on. i.e.
896    * we always invalidate the line with "start" even
897    * if there's an empty range.
898    */
899   
900 #if 0
901   gtk_text_view_index_spew (start_index, "invalidate start");
902   gtk_text_view_index_spew (end_index, "invalidate end");
903 #endif
904
905   last_line = _gtk_text_iter_get_text_line (end);
906   line = _gtk_text_iter_get_text_line (start);
907
908   while (TRUE)
909     {
910       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
911
912       gtk_text_layout_invalidate_cache (layout, line, FALSE);
913       
914       if (line_data)
915         _gtk_text_line_invalidate_wrap (line, line_data);
916
917       if (line == last_line)
918         break;
919
920       line = _gtk_text_line_next_excluding_last (line);
921     }
922
923   gtk_text_layout_invalidated (layout);
924 }
925
926 static void
927 gtk_text_layout_real_invalidate_cursors (GtkTextLayout     *layout,
928                                          const GtkTextIter *start,
929                                          const GtkTextIter *end)
930 {
931   /* Check if the range intersects our cached line display,
932    * and invalidate the cached line if so.
933    */
934   if (layout->one_display_cache)
935     {
936       GtkTextIter line_start, line_end;
937       GtkTextLine *line = layout->one_display_cache->line;
938
939       gtk_text_layout_get_iter_at_line (layout, &line_start, line, 0);
940
941       line_end = line_start;
942       if (!gtk_text_iter_ends_line (&line_end))
943         gtk_text_iter_forward_to_line_end (&line_end);
944
945       if (gtk_text_iter_compare (start, end) > 0)
946         {
947           const GtkTextIter *tmp = start;
948           start = end;
949           end = tmp;
950         }
951
952       if (gtk_text_iter_compare (&line_start, end) <= 0 &&
953           gtk_text_iter_compare (start, &line_end) <= 0)
954         {
955           gtk_text_layout_invalidate_cache (layout, line, TRUE);
956         }
957     }
958
959   gtk_text_layout_invalidated (layout);
960 }
961
962 static void
963 gtk_text_layout_real_free_line_data (GtkTextLayout     *layout,
964                                      GtkTextLine       *line,
965                                      GtkTextLineData   *line_data)
966 {
967   gtk_text_layout_invalidate_cache (layout, line, FALSE);
968
969   g_free (line_data);
970 }
971
972 /**
973  * gtk_text_layout_is_valid:
974  * @layout: a #GtkTextLayout
975  *
976  * Check if there are any invalid regions in a #GtkTextLayout's buffer
977  *
978  * Return value: %TRUE if any invalid regions were found
979  */
980 gboolean
981 gtk_text_layout_is_valid (GtkTextLayout *layout)
982 {
983   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
984
985   return _gtk_text_btree_is_valid (_gtk_text_buffer_get_btree (layout->buffer),
986                                   layout);
987 }
988
989 static void
990 update_layout_size (GtkTextLayout *layout)
991 {
992   _gtk_text_btree_get_view_size (_gtk_text_buffer_get_btree (layout->buffer),
993                                 layout,
994                                 &layout->width, &layout->height);
995 }
996
997 /**
998  * gtk_text_layout_validate_yrange:
999  * @layout: a #GtkTextLayout
1000  * @anchor: iter pointing into a line that will be used as the
1001  *          coordinate origin
1002  * @y0_: offset from the top of the line pointed to by @anchor at
1003  *       which to begin validation. (The offset here is in pixels
1004  *       after validation.)
1005  * @y1_: offset from the top of the line pointed to by @anchor at
1006  *       which to end validation. (The offset here is in pixels
1007  *       after validation.)
1008  *
1009  * Ensure that a region of a #GtkTextLayout is valid. The ::changed
1010  * signal will be emitted if any lines are validated.
1011  */
1012 void
1013 gtk_text_layout_validate_yrange (GtkTextLayout *layout,
1014                                  GtkTextIter   *anchor,
1015                                  gint           y0,
1016                                  gint           y1)
1017 {
1018   GtkTextLine *line;
1019   GtkTextLine *first_line = NULL;
1020   GtkTextLine *last_line = NULL;
1021   gint seen;
1022   gint delta_height = 0;
1023   gint first_line_y = 0;        /* Quiet GCC */
1024   gint last_line_y = 0;         /* Quiet GCC */
1025
1026   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
1027
1028   if (y0 > 0)
1029     y0 = 0;
1030   if (y1 < 0)
1031     y1 = 0;
1032   
1033   /* Validate backwards from the anchor line to y0
1034    */
1035   line = _gtk_text_iter_get_text_line (anchor);
1036   line = _gtk_text_line_previous (line);
1037   seen = 0;
1038   while (line && seen < -y0)
1039     {
1040       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
1041       if (!line_data || !line_data->valid)
1042         {
1043           gint old_height, new_height;
1044           
1045           old_height = line_data ? line_data->height : 0;
1046
1047           _gtk_text_btree_validate_line (_gtk_text_buffer_get_btree (layout->buffer),
1048                                          line, layout);
1049           line_data = _gtk_text_line_get_data (line, layout);
1050
1051           new_height = line_data ? line_data->height : 0;
1052
1053           delta_height += new_height - old_height;
1054           
1055           first_line = line;
1056           first_line_y = -seen - new_height;
1057           if (!last_line)
1058             {
1059               last_line = line;
1060               last_line_y = -seen;
1061             }
1062         }
1063
1064       seen += line_data ? line_data->height : 0;
1065       line = _gtk_text_line_previous (line);
1066     }
1067
1068   /* Validate forwards to y1 */
1069   line = _gtk_text_iter_get_text_line (anchor);
1070   seen = 0;
1071   while (line && seen < y1)
1072     {
1073       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
1074       if (!line_data || !line_data->valid)
1075         {
1076           gint old_height, new_height;
1077           
1078           old_height = line_data ? line_data->height : 0;
1079
1080           _gtk_text_btree_validate_line (_gtk_text_buffer_get_btree (layout->buffer),
1081                                          line, layout);
1082           line_data = _gtk_text_line_get_data (line, layout);
1083           new_height = line_data ? line_data->height : 0;
1084
1085           delta_height += new_height - old_height;
1086           
1087           if (!first_line)
1088             {
1089               first_line = line;
1090               first_line_y = seen;
1091             }
1092           last_line = line;
1093           last_line_y = seen + new_height;
1094         }
1095
1096       seen += line_data ? line_data->height : 0;
1097       line = _gtk_text_line_next_excluding_last (line);
1098     }
1099
1100   /* If we found and validated any invalid lines, update size and
1101    * emit the changed signal
1102    */
1103   if (first_line)
1104     {
1105       gint line_top;
1106
1107       update_layout_size (layout);
1108
1109       line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
1110                                                 first_line, layout);
1111
1112       gtk_text_layout_emit_changed (layout,
1113                                     line_top,
1114                                     last_line_y - first_line_y - delta_height,
1115                                     last_line_y - first_line_y);
1116     }
1117 }
1118
1119 /**
1120  * gtk_text_layout_validate:
1121  * @tree: a #GtkTextLayout
1122  * @max_pixels: the maximum number of pixels to validate. (No more
1123  *              than one paragraph beyond this limit will be validated)
1124  *
1125  * Validate regions of a #GtkTextLayout. The ::changed signal will
1126  * be emitted for each region validated.
1127  **/
1128 void
1129 gtk_text_layout_validate (GtkTextLayout *layout,
1130                           gint           max_pixels)
1131 {
1132   gint y, old_height, new_height;
1133
1134   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
1135
1136   while (max_pixels > 0 &&
1137          _gtk_text_btree_validate (_gtk_text_buffer_get_btree (layout->buffer),
1138                                    layout,  max_pixels,
1139                                    &y, &old_height, &new_height))
1140     {
1141       max_pixels -= new_height;
1142
1143       update_layout_size (layout);
1144       gtk_text_layout_emit_changed (layout, y, old_height, new_height);
1145     }
1146 }
1147
1148 static GtkTextLineData*
1149 gtk_text_layout_real_wrap (GtkTextLayout   *layout,
1150                            GtkTextLine     *line,
1151                            /* may be NULL */
1152                            GtkTextLineData *line_data)
1153 {
1154   GtkTextLineDisplay *display;
1155
1156   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), NULL);
1157   g_return_val_if_fail (line != NULL, NULL);
1158   
1159   if (line_data == NULL)
1160     {
1161       line_data = _gtk_text_line_data_new (layout, line);
1162       _gtk_text_line_add_data (line, line_data);
1163     }
1164
1165   display = gtk_text_layout_get_line_display (layout, line, TRUE);
1166   line_data->width = display->width;
1167   line_data->height = display->height;
1168   line_data->valid = TRUE;
1169   gtk_text_layout_free_line_display (layout, display);
1170
1171   return line_data;
1172 }
1173
1174 /*
1175  * Layout utility functions
1176  */
1177
1178 /* If you get the style with get_style () you need to call
1179    release_style () to free it. */
1180 static GtkTextAttributes*
1181 get_style (GtkTextLayout *layout,
1182            GPtrArray     *tags)
1183 {
1184   GtkTextAttributes *style;
1185
1186   /* If we have the one-style cache, then it means
1187      that we haven't seen a toggle since we filled in the
1188      one-style cache.
1189   */
1190   if (layout->one_style_cache != NULL)
1191     {
1192       gtk_text_attributes_ref (layout->one_style_cache);
1193       return layout->one_style_cache;
1194     }
1195
1196   g_assert (layout->one_style_cache == NULL);
1197
1198   /* No tags, use default style */
1199   if (tags == NULL || tags->len == 0)
1200     {
1201       /* One ref for the return value, one ref for the
1202          layout->one_style_cache reference */
1203       gtk_text_attributes_ref (layout->default_style);
1204       gtk_text_attributes_ref (layout->default_style);
1205       layout->one_style_cache = layout->default_style;
1206
1207       return layout->default_style;
1208     }
1209
1210   style = gtk_text_attributes_new ();
1211
1212   gtk_text_attributes_copy_values (layout->default_style,
1213                                    style);
1214
1215   _gtk_text_attributes_fill_from_tags (style,
1216                                        (GtkTextTag**) tags->pdata,
1217                                        tags->len);
1218
1219   g_assert (style->refcount == 1);
1220
1221   /* Leave this style as the last one seen */
1222   g_assert (layout->one_style_cache == NULL);
1223   gtk_text_attributes_ref (style); /* ref held by layout->one_style_cache */
1224   layout->one_style_cache = style;
1225
1226   /* Returning yet another refcount */
1227   return style;
1228 }
1229
1230 static void
1231 release_style (GtkTextLayout *layout,
1232                GtkTextAttributes *style)
1233 {
1234   g_return_if_fail (style != NULL);
1235   g_return_if_fail (style->refcount > 0);
1236
1237   gtk_text_attributes_unref (style);
1238 }
1239
1240 /*
1241  * Lines
1242  */
1243
1244 /* This function tries to optimize the case where a line
1245    is completely invisible */
1246 static gboolean
1247 totally_invisible_line (GtkTextLayout *layout,
1248                         GtkTextLine   *line,
1249                         GtkTextIter   *iter)
1250 {
1251   GtkTextLineSegment *seg;
1252   int bytes = 0;
1253
1254   /* Check if the first char is visible, if so we are partially visible.  
1255    * Note that we have to check this since we don't know the current 
1256    * invisible/noninvisible toggle state; this function can use the whole btree 
1257    * to get it right.
1258    */
1259   gtk_text_layout_get_iter_at_line (layout, iter, line, 0);
1260   if (!_gtk_text_btree_char_is_invisible (iter))
1261     return FALSE;
1262
1263   bytes = 0;
1264   seg = line->segments;
1265
1266   while (seg != NULL)
1267     {
1268       if (seg->byte_count > 0)
1269         bytes += seg->byte_count;
1270
1271       /* Note that these two tests can cause us to bail out
1272        * when we shouldn't, because a higher-priority tag
1273        * may override these settings. However the important
1274        * thing is to only invisible really-invisible lines, rather
1275        * than to invisible all really-invisible lines.
1276        */
1277
1278       else if (seg->type == &gtk_text_toggle_on_type)
1279         {
1280           invalidate_cached_style (layout);
1281
1282           /* Bail out if an elision-unsetting tag begins */
1283           if (seg->body.toggle.info->tag->priv->invisible_set &&
1284               !seg->body.toggle.info->tag->priv->values->invisible)
1285             break;
1286         }
1287       else if (seg->type == &gtk_text_toggle_off_type)
1288         {
1289           invalidate_cached_style (layout);
1290
1291           /* Bail out if an elision-setting tag ends */
1292           if (seg->body.toggle.info->tag->priv->invisible_set &&
1293               seg->body.toggle.info->tag->priv->values->invisible)
1294             break;
1295         }
1296
1297       seg = seg->next;
1298     }
1299
1300   if (seg != NULL)       /* didn't reach line end */
1301     return FALSE;
1302
1303   return TRUE;
1304 }
1305
1306 static void
1307 set_para_values (GtkTextLayout      *layout,
1308                  PangoDirection      base_dir,
1309                  GtkTextAttributes  *style,
1310                  GtkTextLineDisplay *display)
1311 {
1312   PangoAlignment pango_align = PANGO_ALIGN_LEFT;
1313   PangoWrapMode pango_wrap = PANGO_WRAP_WORD;
1314
1315   switch (base_dir)
1316     {
1317     /* If no base direction was found, then use the style direction */
1318     case PANGO_DIRECTION_NEUTRAL :
1319       display->direction = style->direction;
1320
1321       /* Override the base direction */
1322       if (display->direction == GTK_TEXT_DIR_RTL)
1323         base_dir = PANGO_DIRECTION_RTL;
1324       else
1325         base_dir = PANGO_DIRECTION_LTR;
1326       
1327       break;
1328     case PANGO_DIRECTION_RTL :
1329       display->direction = GTK_TEXT_DIR_RTL;
1330       break;
1331     default:
1332       display->direction = GTK_TEXT_DIR_LTR;
1333       break;
1334     }
1335   
1336   if (display->direction == GTK_TEXT_DIR_RTL)
1337     display->layout = pango_layout_new (layout->rtl_context);
1338   else
1339     display->layout = pango_layout_new (layout->ltr_context);
1340
1341   switch (style->justification)
1342     {
1343     case GTK_JUSTIFY_LEFT:
1344       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
1345       break;
1346     case GTK_JUSTIFY_RIGHT:
1347       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
1348       break;
1349     case GTK_JUSTIFY_CENTER:
1350       pango_align = PANGO_ALIGN_CENTER;
1351       break;
1352     case GTK_JUSTIFY_FILL:
1353       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
1354       pango_layout_set_justify (display->layout, TRUE);
1355       break;
1356     default:
1357       g_assert_not_reached ();
1358       break;
1359     }
1360
1361   pango_layout_set_alignment (display->layout, pango_align);
1362   pango_layout_set_spacing (display->layout,
1363                             style->pixels_inside_wrap * PANGO_SCALE);
1364
1365   if (style->tabs)
1366     pango_layout_set_tabs (display->layout, style->tabs);
1367
1368   display->top_margin = style->pixels_above_lines;
1369   display->height = style->pixels_above_lines + style->pixels_below_lines;
1370   display->bottom_margin = style->pixels_below_lines;
1371   display->left_margin = style->left_margin;
1372   display->right_margin = style->right_margin;
1373   
1374   display->x_offset = display->left_margin;
1375
1376   pango_layout_set_indent (display->layout,
1377                            style->indent * PANGO_SCALE);
1378
1379   switch (style->wrap_mode)
1380     {
1381     case GTK_WRAP_CHAR:
1382       pango_wrap = PANGO_WRAP_CHAR;
1383       break;
1384     case GTK_WRAP_WORD:
1385       pango_wrap = PANGO_WRAP_WORD;
1386       break;
1387
1388     case GTK_WRAP_WORD_CHAR:
1389       pango_wrap = PANGO_WRAP_WORD_CHAR;
1390       break;
1391
1392     case GTK_WRAP_NONE:
1393       break;
1394     }
1395
1396   if (style->wrap_mode != GTK_WRAP_NONE)
1397     {
1398       int layout_width = (layout->screen_width - display->left_margin - display->right_margin);
1399       pango_layout_set_width (display->layout, layout_width * PANGO_SCALE);
1400       pango_layout_set_wrap (display->layout, pango_wrap);
1401     }
1402
1403   display->total_width = MAX (layout->screen_width, layout->width) - display->left_margin - display->right_margin;
1404   
1405   if (style->pg_bg_color)
1406     display->pg_bg_color = gdk_color_copy (style->pg_bg_color);
1407   else
1408     display->pg_bg_color = NULL;
1409
1410   if (style->pg_bg_rgba)
1411     display->pg_bg_rgba = gdk_rgba_copy (style->pg_bg_rgba);
1412   else
1413     display->pg_bg_rgba = NULL;
1414 }
1415
1416 static PangoAttribute *
1417 gtk_text_attr_appearance_copy (const PangoAttribute *attr)
1418 {
1419   const GtkTextAttrAppearance *appearance_attr = (const GtkTextAttrAppearance *)attr;
1420
1421   return gtk_text_attr_appearance_new (&appearance_attr->appearance);
1422 }
1423
1424 static void
1425 gtk_text_attr_appearance_destroy (PangoAttribute *attr)
1426 {
1427   GtkTextAttrAppearance *appearance_attr = (GtkTextAttrAppearance *)attr;
1428
1429   if (appearance_attr->appearance.rgba[0])
1430     gdk_rgba_free (appearance_attr->appearance.rgba[0]);
1431
1432   if (appearance_attr->appearance.rgba[1])
1433     gdk_rgba_free (appearance_attr->appearance.rgba[1]);
1434
1435   g_slice_free (GtkTextAttrAppearance, appearance_attr);
1436 }
1437
1438 static gboolean 
1439 rgba_equal (const GdkRGBA *rgba1, const GdkRGBA *rgba2)
1440 {
1441   if (rgba1 && rgba2)
1442     return gdk_rgba_equal (rgba1, rgba2);
1443   
1444   if (rgba1 || rgba2)
1445     return FALSE;
1446
1447   return TRUE;
1448 }
1449
1450 static gboolean
1451 gtk_text_attr_appearance_compare (const PangoAttribute *attr1,
1452                                   const PangoAttribute *attr2)
1453 {
1454   const GtkTextAppearance *appearance1 = &((const GtkTextAttrAppearance *)attr1)->appearance;
1455   const GtkTextAppearance *appearance2 = &((const GtkTextAttrAppearance *)attr2)->appearance;
1456
1457   return (rgba_equal (appearance1->rgba[0], appearance2->rgba[0]) &&
1458           rgba_equal (appearance1->rgba[1], appearance2->rgba[1]) &&
1459           appearance1->underline == appearance2->underline &&
1460           appearance1->strikethrough == appearance2->strikethrough &&
1461           appearance1->draw_bg == appearance2->draw_bg);
1462 }
1463
1464 /*
1465  * gtk_text_attr_appearance_new:
1466  * @desc:
1467  *
1468  * Create a new font description attribute. (This attribute
1469  * allows setting family, style, weight, variant, stretch,
1470  * and size simultaneously.)
1471  *
1472  * Return value:
1473  */
1474 static PangoAttribute *
1475 gtk_text_attr_appearance_new (const GtkTextAppearance *appearance)
1476 {
1477   static PangoAttrClass klass = {
1478     0,
1479     gtk_text_attr_appearance_copy,
1480     gtk_text_attr_appearance_destroy,
1481     gtk_text_attr_appearance_compare
1482   };
1483
1484   GtkTextAttrAppearance *result;
1485
1486   if (!klass.type)
1487     klass.type = gtk_text_attr_appearance_type =
1488       pango_attr_type_register ("GtkTextAttrAppearance");
1489
1490   result = g_slice_new (GtkTextAttrAppearance);
1491   result->attr.klass = &klass;
1492
1493   result->appearance = *appearance;
1494
1495   if (appearance->rgba[0])
1496     result->appearance.rgba[0] = gdk_rgba_copy (appearance->rgba[0]);
1497
1498   if (appearance->rgba[1])
1499     result->appearance.rgba[1] = gdk_rgba_copy (appearance->rgba[1]);
1500
1501   return (PangoAttribute *)result;
1502 }
1503
1504 static void
1505 add_generic_attrs (GtkTextLayout      *layout,
1506                    GtkTextAppearance  *appearance,
1507                    gint                byte_count,
1508                    PangoAttrList      *attrs,
1509                    gint                start,
1510                    gboolean            size_only,
1511                    gboolean            is_text)
1512 {
1513   PangoAttribute *attr;
1514
1515   if (appearance->underline != PANGO_UNDERLINE_NONE)
1516     {
1517       attr = pango_attr_underline_new (appearance->underline);
1518       
1519       attr->start_index = start;
1520       attr->end_index = start + byte_count;
1521       
1522       pango_attr_list_insert (attrs, attr);
1523     }
1524
1525   if (appearance->strikethrough)
1526     {
1527       attr = pango_attr_strikethrough_new (appearance->strikethrough);
1528       
1529       attr->start_index = start;
1530       attr->end_index = start + byte_count;
1531       
1532       pango_attr_list_insert (attrs, attr);
1533     }
1534
1535   if (appearance->rise != 0)
1536     {
1537       attr = pango_attr_rise_new (appearance->rise);
1538       
1539       attr->start_index = start;
1540       attr->end_index = start + byte_count;
1541       
1542       pango_attr_list_insert (attrs, attr);
1543     }
1544   
1545   if (!size_only)
1546     {
1547       attr = gtk_text_attr_appearance_new (appearance);
1548       
1549       attr->start_index = start;
1550       attr->end_index = start + byte_count;
1551
1552       ((GtkTextAttrAppearance *)attr)->appearance.is_text = is_text;
1553       
1554       pango_attr_list_insert (attrs, attr);
1555     }
1556 }
1557
1558 static void
1559 add_text_attrs (GtkTextLayout      *layout,
1560                 GtkTextAttributes  *style,
1561                 gint                byte_count,
1562                 PangoAttrList      *attrs,
1563                 gint                start,
1564                 gboolean            size_only)
1565 {
1566   PangoAttribute *attr;
1567
1568   attr = pango_attr_font_desc_new (style->font);
1569   attr->start_index = start;
1570   attr->end_index = start + byte_count;
1571
1572   pango_attr_list_insert (attrs, attr);
1573
1574   if (style->font_scale != 1.0)
1575     {
1576       attr = pango_attr_scale_new (style->font_scale);
1577
1578       attr->start_index = start;
1579       attr->end_index = start + byte_count;
1580       
1581       pango_attr_list_insert (attrs, attr);
1582     }
1583 }
1584
1585 static void
1586 add_pixbuf_attrs (GtkTextLayout      *layout,
1587                   GtkTextLineDisplay *display,
1588                   GtkTextAttributes  *style,
1589                   GtkTextLineSegment *seg,
1590                   PangoAttrList      *attrs,
1591                   gint                start)
1592 {
1593   PangoAttribute *attr;
1594   PangoRectangle logical_rect;
1595   GtkTextPixbuf *pixbuf = &seg->body.pixbuf;
1596   gint width, height;
1597
1598   width = gdk_pixbuf_get_width (pixbuf->pixbuf);
1599   height = gdk_pixbuf_get_height (pixbuf->pixbuf);
1600
1601   logical_rect.x = 0;
1602   logical_rect.y = -height * PANGO_SCALE;
1603   logical_rect.width = width * PANGO_SCALE;
1604   logical_rect.height = height * PANGO_SCALE;
1605
1606   attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
1607                                          pixbuf->pixbuf, NULL, NULL);
1608   attr->start_index = start;
1609   attr->end_index = start + seg->byte_count;
1610   pango_attr_list_insert (attrs, attr);
1611 }
1612
1613 static void
1614 add_child_attrs (GtkTextLayout      *layout,
1615                  GtkTextLineDisplay *display,
1616                  GtkTextAttributes  *style,
1617                  GtkTextLineSegment *seg,
1618                  PangoAttrList      *attrs,
1619                  gint                start)
1620 {
1621   PangoAttribute *attr;
1622   PangoRectangle logical_rect;
1623   gint width, height;
1624   GSList *tmp_list;
1625   GtkWidget *widget;
1626
1627   width = 1;
1628   height = 1;
1629   
1630   tmp_list = seg->body.child.widgets;
1631   while (tmp_list != NULL)
1632     {
1633       GtkWidget *child = tmp_list->data;
1634
1635       if (_gtk_anchored_child_get_layout (child) == layout)
1636         {
1637           /* Found it */
1638           GtkRequisition req;
1639
1640           gtk_widget_get_preferred_size (child, &req, NULL);
1641
1642           width = req.width;
1643           height = req.height;
1644
1645           widget = child;
1646           
1647           break;
1648         }
1649       
1650       tmp_list = g_slist_next (tmp_list);
1651     }
1652
1653   if (tmp_list == NULL)
1654     {
1655       /* If tmp_list == NULL then there is no widget at this anchor in
1656        * this display; not an error. We make up an arbitrary size
1657        * to use, just so the programmer can see the blank spot.
1658        * We also put a NULL in the shaped objects list, to keep
1659        * the correspondence between the list and the shaped chars in
1660        * the layout. A bad hack, yes.
1661        */
1662
1663       width = 30;
1664       height = 20;
1665
1666       widget = NULL;
1667     }
1668
1669   logical_rect.x = 0;
1670   logical_rect.y = -height * PANGO_SCALE;
1671   logical_rect.width = width * PANGO_SCALE;
1672   logical_rect.height = height * PANGO_SCALE;
1673
1674   attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
1675                                          widget, NULL, NULL);
1676   attr->start_index = start;
1677   attr->end_index = start + seg->byte_count;
1678   pango_attr_list_insert (attrs, attr);
1679 }
1680
1681 /*
1682  * get_block_cursor:
1683  * @layout: a #GtkTextLayout
1684  * @display: a #GtkTextLineDisplay
1685  * @insert_iter: iter pointing to the cursor location
1686  * @insert_index: cursor offset in the @display's layout, it may
1687  * be different from @insert_iter's offset in case when preedit
1688  * string is present.
1689  * @pos: location to store cursor position
1690  * @cursor_at_line_end: whether cursor is at the end of line
1691  *
1692  * Checks whether layout should display block cursor at given position.
1693  * For this layout must be in overwrite mode and text at @insert_iter 
1694  * must be editable.
1695  */
1696 static gboolean
1697 get_block_cursor (GtkTextLayout      *layout,
1698                   GtkTextLineDisplay *display,
1699                   const GtkTextIter  *insert_iter,
1700                   gint                insert_index,
1701                   GdkRectangle       *pos,
1702                   gboolean           *cursor_at_line_end)
1703 {
1704   PangoRectangle pango_pos;
1705
1706   if (layout->overwrite_mode &&
1707       gtk_text_iter_editable (insert_iter, TRUE) &&
1708       _gtk_text_util_get_block_cursor_location (display->layout,
1709                                                 insert_index,
1710                                                 &pango_pos,
1711                                                 cursor_at_line_end))
1712     {
1713       if (pos)
1714         {
1715           pos->x = PANGO_PIXELS (pango_pos.x);
1716           pos->y = PANGO_PIXELS (pango_pos.y);
1717           pos->width = PANGO_PIXELS (pango_pos.width);
1718           pos->height = PANGO_PIXELS (pango_pos.height);
1719         }
1720
1721       return TRUE;
1722     }
1723   else
1724     return FALSE;
1725 }
1726
1727 static void
1728 add_cursor (GtkTextLayout      *layout,
1729             GtkTextLineDisplay *display,
1730             GtkTextLineSegment *seg,
1731             gint                start)
1732 {
1733   /* Hide insertion cursor when we have a selection or the layout
1734    * user has hidden the cursor.
1735    */
1736   if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
1737                                      seg->body.mark.obj) &&
1738       (!layout->cursor_visible ||
1739        gtk_text_buffer_get_selection_bounds (layout->buffer, NULL, NULL)))
1740     return;
1741
1742   if (layout->overwrite_mode &&
1743       _gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
1744                                       seg->body.mark.obj))
1745     {
1746       GtkTextIter iter;
1747       gboolean cursor_at_line_end;
1748
1749       _gtk_text_btree_get_iter_at_mark (_gtk_text_buffer_get_btree (layout->buffer),
1750                                         &iter, seg->body.mark.obj);
1751
1752       if (get_block_cursor (layout, display, &iter, start,
1753                             &display->block_cursor,
1754                             &cursor_at_line_end))
1755         {
1756           display->has_block_cursor = TRUE;
1757           display->cursor_at_line_end = cursor_at_line_end;
1758           return;
1759         }
1760     }
1761
1762   if (!display->cursors)
1763     display->cursors = g_array_new (FALSE, FALSE, sizeof(int));
1764
1765   display->cursors = g_array_append_val (display->cursors, start);
1766 }
1767
1768 static gboolean
1769 is_shape (PangoLayoutRun *run)
1770 {
1771   GSList *tmp_list = run->item->analysis.extra_attrs;
1772     
1773   while (tmp_list)
1774     {
1775       PangoAttribute *attr = tmp_list->data;
1776
1777       if (attr->klass->type == PANGO_ATTR_SHAPE)
1778         return TRUE;
1779
1780       tmp_list = tmp_list->next;
1781     }
1782
1783   return FALSE;
1784 }
1785
1786 static void
1787 allocate_child_widgets (GtkTextLayout      *text_layout,
1788                         GtkTextLineDisplay *display)
1789 {
1790   PangoLayout *layout = display->layout;
1791   PangoLayoutIter *run_iter;
1792
1793   run_iter = pango_layout_get_iter (layout);
1794   do
1795     {
1796       PangoLayoutRun *run = pango_layout_iter_get_run_readonly (run_iter);
1797
1798       if (run && is_shape (run))
1799         {
1800           gint byte_index;
1801           GtkTextIter text_iter;
1802           GtkTextChildAnchor *anchor = NULL;
1803           GList *widgets = NULL;
1804           GList *l;
1805
1806           /* The pango iterator iterates in visual order.
1807            * We use the byte index to find the child widget.
1808            */
1809           byte_index = pango_layout_iter_get_index (run_iter);
1810           line_display_index_to_iter (text_layout, display, &text_iter, byte_index, 0);
1811           anchor = gtk_text_iter_get_child_anchor (&text_iter);
1812           if (anchor)
1813             widgets = gtk_text_child_anchor_get_widgets (anchor);
1814
1815           for (l = widgets; l; l = l->next)
1816             {
1817               PangoRectangle extents;
1818               GtkWidget *child = l->data;
1819
1820               if (_gtk_anchored_child_get_layout (child) == text_layout)
1821                 {
1822
1823                   /* We emit "allocate_child" with the x,y of
1824                    * the widget with respect to the top of the line
1825                    * and the left side of the buffer
1826                    */
1827                   pango_layout_iter_get_run_extents (run_iter,
1828                                                      NULL,
1829                                                      &extents);
1830
1831                   g_signal_emit (text_layout,
1832                                  signals[ALLOCATE_CHILD],
1833                                  0,
1834                                  child,
1835                                  PANGO_PIXELS (extents.x) + display->x_offset,
1836                                  PANGO_PIXELS (extents.y) + display->top_margin);
1837                 }
1838             }
1839
1840           g_list_free (widgets);
1841         }
1842     }
1843   while (pango_layout_iter_next_run (run_iter));
1844
1845   pango_layout_iter_free (run_iter);
1846 }
1847
1848 static void
1849 convert_color (GdkColor       *result,
1850                PangoAttrColor *attr)
1851 {
1852   result->red = attr->color.red;
1853   result->blue = attr->color.blue;
1854   result->green = attr->color.green;
1855 }
1856
1857 /* This function is used to convert the preedit string attributes, which are
1858  * standard PangoAttributes, into the custom attributes used by the text
1859  * widget and insert them into a attr list with a given offset.
1860  */
1861 static void
1862 add_preedit_attrs (GtkTextLayout     *layout,
1863                    GtkTextAttributes *style,
1864                    PangoAttrList     *attrs,
1865                    gint               offset,
1866                    gboolean           size_only)
1867 {
1868   PangoAttrIterator *iter = pango_attr_list_get_iterator (layout->preedit_attrs);
1869
1870   do
1871     {
1872       GtkTextAppearance appearance = style->appearance;
1873       PangoFontDescription *font_desc = pango_font_description_copy_static (style->font);
1874       PangoAttribute *insert_attr;
1875       GSList *extra_attrs = NULL;
1876       GSList *tmp_list;
1877       PangoLanguage *language;
1878       gint start, end;
1879
1880       pango_attr_iterator_range (iter, &start, &end);
1881
1882       if (end == G_MAXINT)
1883         end = layout->preedit_len;
1884       
1885       if (end == start)
1886         continue;
1887
1888       pango_attr_iterator_get_font (iter, font_desc, &language, &extra_attrs);
1889       
1890       tmp_list = extra_attrs;
1891       while (tmp_list)
1892         {
1893           PangoAttribute *attr = tmp_list->data;
1894           
1895           switch (attr->klass->type)
1896             {
1897             case PANGO_ATTR_FOREGROUND:
1898               convert_color (&appearance.fg_color, (PangoAttrColor *)attr);
1899               break;
1900             case PANGO_ATTR_BACKGROUND:
1901               convert_color (&appearance.bg_color, (PangoAttrColor *)attr);
1902               appearance.draw_bg = TRUE;
1903               break;
1904             case PANGO_ATTR_UNDERLINE:
1905               appearance.underline = ((PangoAttrInt *)attr)->value;
1906               break;
1907             case PANGO_ATTR_STRIKETHROUGH:
1908               appearance.strikethrough = ((PangoAttrInt *)attr)->value;
1909               break;
1910             case PANGO_ATTR_RISE:
1911               appearance.rise = ((PangoAttrInt *)attr)->value;
1912               break;
1913             default:
1914               break;
1915             }
1916           
1917           pango_attribute_destroy (attr);
1918           tmp_list = tmp_list->next;
1919         }
1920       
1921       g_slist_free (extra_attrs);
1922       
1923       insert_attr = pango_attr_font_desc_new (font_desc);
1924       insert_attr->start_index = start + offset;
1925       insert_attr->end_index = end + offset;
1926       
1927       pango_attr_list_insert (attrs, insert_attr);
1928
1929       if (language)
1930         {
1931           insert_attr = pango_attr_language_new (language);
1932           insert_attr->start_index = start + offset;
1933           insert_attr->end_index = end + offset;
1934           
1935           pango_attr_list_insert (attrs, insert_attr);
1936         }
1937
1938       add_generic_attrs (layout, &appearance, end - start,
1939                          attrs, start + offset,
1940                          size_only, TRUE);
1941       
1942       pango_font_description_free (font_desc);
1943     }
1944   while (pango_attr_iterator_next (iter));
1945
1946   pango_attr_iterator_destroy (iter);
1947 }
1948
1949 /* Iterate over the line and fill in display->cursors.
1950  * It's a stripped copy of gtk_text_layout_get_line_display() */
1951 static void
1952 update_text_display_cursors (GtkTextLayout      *layout,
1953                              GtkTextLine        *line,
1954                              GtkTextLineDisplay *display)
1955 {
1956   GtkTextLineSegment *seg;
1957   GtkTextIter iter;
1958   gint layout_byte_offset, buffer_byte_offset;
1959   GSList *cursor_byte_offsets = NULL;
1960   GSList *cursor_segs = NULL;
1961   GSList *tmp_list1, *tmp_list2;
1962
1963   if (!display->cursors_invalid)
1964     return;
1965
1966   display->cursors_invalid = FALSE;
1967
1968   /* Special-case optimization for completely
1969    * invisible lines; makes it faster to deal
1970    * with sequences of invisible lines.
1971    */
1972   if (totally_invisible_line (layout, line, &iter))
1973     return;
1974
1975   /* Iterate over segments */
1976   layout_byte_offset = 0; /* position in the layout text (includes preedit, does not include invisible text) */
1977   buffer_byte_offset = 0; /* position in the buffer line */
1978   seg = _gtk_text_iter_get_any_segment (&iter);
1979   while (seg != NULL)
1980     {
1981       /* Displayable segments */
1982       if (seg->type == &gtk_text_char_type ||
1983           seg->type == &gtk_text_pixbuf_type ||
1984           seg->type == &gtk_text_child_type)
1985         {
1986           gtk_text_layout_get_iter_at_line (layout, &iter, line,
1987                                             buffer_byte_offset);
1988
1989           if (!_gtk_text_btree_char_is_invisible (&iter))
1990             layout_byte_offset += seg->byte_count;
1991
1992           buffer_byte_offset += seg->byte_count;
1993         }
1994
1995       /* Marks */
1996       else if (seg->type == &gtk_text_right_mark_type ||
1997                seg->type == &gtk_text_left_mark_type)
1998         {
1999           gint cursor_offset = 0;
2000
2001           /* At the insertion point, add the preedit string, if any */
2002
2003           if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2004                                               seg->body.mark.obj))
2005             {
2006               display->insert_index = layout_byte_offset;
2007
2008               if (layout->preedit_len > 0)
2009                 {
2010                   layout_byte_offset += layout->preedit_len;
2011                   /* DO NOT increment the buffer byte offset for preedit */
2012                   cursor_offset = layout->preedit_cursor - layout->preedit_len;
2013                 }
2014             }
2015
2016           /* Display visible marks */
2017
2018           if (seg->body.mark.visible)
2019             {
2020               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
2021                                                      GINT_TO_POINTER (layout_byte_offset + cursor_offset));
2022               cursor_segs = g_slist_prepend (cursor_segs, seg);
2023             }
2024         }
2025
2026       /* Toggles */
2027       else if (seg->type == &gtk_text_toggle_on_type ||
2028                seg->type == &gtk_text_toggle_off_type)
2029         {
2030         }
2031
2032       else
2033         g_error ("Unknown segment type: %s", seg->type->name);
2034
2035       seg = seg->next;
2036     }
2037
2038   tmp_list1 = cursor_byte_offsets;
2039   tmp_list2 = cursor_segs;
2040   while (tmp_list1)
2041     {
2042       add_cursor (layout, display, tmp_list2->data,
2043                   GPOINTER_TO_INT (tmp_list1->data));
2044       tmp_list1 = tmp_list1->next;
2045       tmp_list2 = tmp_list2->next;
2046     }
2047   g_slist_free (cursor_byte_offsets);
2048   g_slist_free (cursor_segs);
2049 }
2050
2051 /* Same as _gtk_text_btree_get_tags(), except it returns GPtrArray,
2052  * to be used in gtk_text_layout_get_line_display(). */
2053 static GPtrArray *
2054 get_tags_array_at_iter (GtkTextIter *iter)
2055 {
2056   GtkTextTag **tags;
2057   GPtrArray *array = NULL;
2058   gint n_tags;
2059
2060   tags = _gtk_text_btree_get_tags (iter, &n_tags);
2061
2062   if (n_tags > 0)
2063     {
2064       array = g_ptr_array_sized_new (n_tags);
2065       g_ptr_array_set_size (array, n_tags);
2066       memcpy (array->pdata, tags, n_tags * sizeof (GtkTextTag*));
2067     }
2068
2069   g_free (tags);
2070   return array;
2071 }
2072
2073 /* Add the tag to the array if it's not there already, and remove
2074  * it otherwise. It keeps the array sorted by tags priority. */
2075 static GPtrArray *
2076 tags_array_toggle_tag (GPtrArray  *array,
2077                        GtkTextTag *tag)
2078 {
2079   gint pos;
2080   GtkTextTag **tags;
2081
2082   if (array == NULL)
2083     array = g_ptr_array_new ();
2084
2085   tags = (GtkTextTag**) array->pdata;
2086
2087   for (pos = 0; pos < array->len && tags[pos]->priv->priority < tag->priv->priority; pos++) ;
2088
2089   if (pos < array->len && tags[pos] == tag)
2090     g_ptr_array_remove_index (array, pos);
2091   else
2092     {
2093       g_ptr_array_set_size (array, array->len + 1);
2094       if (pos < array->len - 1)
2095         memmove (array->pdata + pos + 1, array->pdata + pos,
2096                  (array->len - pos - 1) * sizeof (GtkTextTag*));
2097       array->pdata[pos] = tag;
2098     }
2099
2100   return array;
2101 }
2102
2103 GtkTextLineDisplay *
2104 gtk_text_layout_get_line_display (GtkTextLayout *layout,
2105                                   GtkTextLine   *line,
2106                                   gboolean       size_only)
2107 {
2108   GtkTextLayoutPrivate *priv = GTK_TEXT_LAYOUT_GET_PRIVATE (layout);
2109   GtkTextLineDisplay *display;
2110   GtkTextLineSegment *seg;
2111   GtkTextIter iter;
2112   GtkTextAttributes *style;
2113   gchar *text;
2114   PangoAttrList *attrs;
2115   gint text_allocated, layout_byte_offset, buffer_byte_offset;
2116   PangoRectangle extents;
2117   gboolean para_values_set = FALSE;
2118   GSList *cursor_byte_offsets = NULL;
2119   GSList *cursor_segs = NULL;
2120   GSList *tmp_list1, *tmp_list2;
2121   gboolean saw_widget = FALSE;
2122   PangoDirection base_dir;
2123   GPtrArray *tags;
2124   gboolean initial_toggle_segments;
2125   
2126   g_return_val_if_fail (line != NULL, NULL);
2127
2128   if (layout->one_display_cache)
2129     {
2130       if (line == layout->one_display_cache->line &&
2131           (size_only || !layout->one_display_cache->size_only))
2132         {
2133           if (!size_only)
2134             update_text_display_cursors (layout, line, layout->one_display_cache);
2135           return layout->one_display_cache;
2136         }
2137       else
2138         {
2139           GtkTextLineDisplay *tmp_display = layout->one_display_cache;
2140           layout->one_display_cache = NULL;
2141           gtk_text_layout_free_line_display (layout, tmp_display);
2142         }
2143     }
2144
2145   DV (g_print ("creating one line display cache (%s)\n", G_STRLOC));
2146
2147   display = g_slice_new0 (GtkTextLineDisplay);
2148
2149   display->size_only = size_only;
2150   display->line = line;
2151   display->insert_index = -1;
2152
2153   /* Special-case optimization for completely
2154    * invisible lines; makes it faster to deal
2155    * with sequences of invisible lines.
2156    */
2157   if (totally_invisible_line (layout, line, &iter))
2158     {
2159       if (display->direction == GTK_TEXT_DIR_RTL)
2160         display->layout = pango_layout_new (layout->rtl_context);
2161       else
2162         display->layout = pango_layout_new (layout->ltr_context);
2163       
2164       return display;
2165     }
2166
2167   /* Find the bidi base direction */
2168   base_dir = line->dir_propagated_forward;
2169   if (base_dir == PANGO_DIRECTION_NEUTRAL)
2170     base_dir = line->dir_propagated_back;
2171
2172   if (line == priv->cursor_line &&
2173       line->dir_strong == PANGO_DIRECTION_NEUTRAL)
2174     {
2175       base_dir = (layout->keyboard_direction == GTK_TEXT_DIR_LTR) ?
2176          PANGO_DIRECTION_LTR : PANGO_DIRECTION_RTL;
2177     }
2178   
2179   /* Allocate space for flat text for buffer
2180    */
2181   text_allocated = _gtk_text_line_byte_count (line);
2182   text = g_malloc (text_allocated);
2183
2184   attrs = pango_attr_list_new ();
2185
2186   /* Iterate over segments, creating display chunks for them, and updating the tags array. */
2187   layout_byte_offset = 0; /* current length of layout text (includes preedit, does not include invisible text) */
2188   buffer_byte_offset = 0; /* position in the buffer line */
2189   seg = _gtk_text_iter_get_any_segment (&iter);
2190   tags = get_tags_array_at_iter (&iter);
2191   initial_toggle_segments = TRUE;
2192   while (seg != NULL)
2193     {
2194       /* Displayable segments */
2195       if (seg->type == &gtk_text_char_type ||
2196           seg->type == &gtk_text_pixbuf_type ||
2197           seg->type == &gtk_text_child_type)
2198         {
2199           style = get_style (layout, tags);
2200           initial_toggle_segments = FALSE;
2201
2202           /* We have to delay setting the paragraph values until we
2203            * hit the first pixbuf or text segment because toggles at
2204            * the beginning of the paragraph should affect the
2205            * paragraph-global values
2206            */
2207           if (!para_values_set)
2208             {
2209               set_para_values (layout, base_dir, style, display);
2210               para_values_set = TRUE;
2211             }
2212
2213           /* First see if the chunk is invisible, and ignore it if so. Tk
2214            * looked at tabs, wrap mode, etc. before doing this, but
2215            * that made no sense to me, so I am just skipping the
2216            * invisible chunks
2217            */
2218           if (!style->invisible)
2219             {
2220               if (seg->type == &gtk_text_char_type)
2221                 {
2222                   /* We don't want to split segments because of marks,
2223                    * so we scan forward for more segments only
2224                    * separated from us by marks. In theory, we should
2225                    * also merge segments with identical styles, even
2226                    * if there are toggles in-between
2227                    */
2228
2229                   gint bytes = 0;
2230                   GtkTextLineSegment *prev_seg = NULL;
2231   
2232                   while (seg)
2233                     {
2234                       if (seg->type == &gtk_text_char_type)
2235                         {
2236                           memcpy (text + layout_byte_offset, seg->body.chars, seg->byte_count);
2237                           layout_byte_offset += seg->byte_count;
2238                           buffer_byte_offset += seg->byte_count;
2239                           bytes += seg->byte_count;
2240                         }
2241                       else if (seg->type == &gtk_text_right_mark_type ||
2242                                seg->type == &gtk_text_left_mark_type)
2243                         {
2244                           /* If we have preedit string, break out of this loop - we'll almost
2245                            * certainly have different attributes on the preedit string
2246                            */
2247
2248                           if (layout->preedit_len > 0 &&
2249                               _gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2250                                                              seg->body.mark.obj))
2251                             break;
2252
2253                           if (seg->body.mark.visible)
2254                             {
2255                               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets, GINT_TO_POINTER (layout_byte_offset));
2256                               cursor_segs = g_slist_prepend (cursor_segs, seg);
2257                               if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2258                                                                   seg->body.mark.obj))
2259                                 display->insert_index = layout_byte_offset;
2260                             }
2261                         }
2262                       else
2263                         break;
2264
2265                       prev_seg = seg;
2266                       seg = seg->next;
2267                     }
2268
2269                   seg = prev_seg; /* Back up one */
2270                   add_generic_attrs (layout, &style->appearance,
2271                                      bytes,
2272                                      attrs, layout_byte_offset - bytes,
2273                                      size_only, TRUE);
2274                   add_text_attrs (layout, style, bytes, attrs,
2275                                   layout_byte_offset - bytes, size_only);
2276                 }
2277               else if (seg->type == &gtk_text_pixbuf_type)
2278                 {
2279                   add_generic_attrs (layout,
2280                                      &style->appearance,
2281                                      seg->byte_count,
2282                                      attrs, layout_byte_offset,
2283                                      size_only, FALSE);
2284                   add_pixbuf_attrs (layout, display, style,
2285                                     seg, attrs, layout_byte_offset);
2286                   memcpy (text + layout_byte_offset, _gtk_text_unknown_char_utf8,
2287                           seg->byte_count);
2288                   layout_byte_offset += seg->byte_count;
2289                   buffer_byte_offset += seg->byte_count;
2290                 }
2291               else if (seg->type == &gtk_text_child_type)
2292                 {
2293                   saw_widget = TRUE;
2294                   
2295                   add_generic_attrs (layout, &style->appearance,
2296                                      seg->byte_count,
2297                                      attrs, layout_byte_offset,
2298                                      size_only, FALSE);
2299                   add_child_attrs (layout, display, style,
2300                                    seg, attrs, layout_byte_offset);
2301                   memcpy (text + layout_byte_offset, _gtk_text_unknown_char_utf8,
2302                           seg->byte_count);
2303                   layout_byte_offset += seg->byte_count;
2304                   buffer_byte_offset += seg->byte_count;
2305                 }
2306               else
2307                 {
2308                   /* We don't know this segment type */
2309                   g_assert_not_reached ();
2310                 }
2311               
2312             } /* if (segment was visible) */
2313           else
2314             {
2315               /* Invisible segment */
2316               buffer_byte_offset += seg->byte_count;
2317             }
2318
2319           release_style (layout, style);
2320         }
2321
2322       /* Toggles */
2323       else if (seg->type == &gtk_text_toggle_on_type ||
2324                seg->type == &gtk_text_toggle_off_type)
2325         {
2326           /* Style may have changed, drop our
2327              current cached style */
2328           invalidate_cached_style (layout);
2329           /* Add the tag only after we have seen some non-toggle non-mark segment,
2330            * otherwise the tag is already accounted for by _gtk_text_btree_get_tags(). */
2331           if (!initial_toggle_segments)
2332             tags = tags_array_toggle_tag (tags, seg->body.toggle.info->tag);
2333         }
2334
2335       /* Marks */
2336       else if (seg->type == &gtk_text_right_mark_type ||
2337                seg->type == &gtk_text_left_mark_type)
2338         {
2339           gint cursor_offset = 0;
2340           
2341           /* At the insertion point, add the preedit string, if any */
2342           
2343           if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2344                                              seg->body.mark.obj))
2345             {
2346               display->insert_index = layout_byte_offset;
2347               
2348               if (layout->preedit_len > 0)
2349                 {
2350                   text_allocated += layout->preedit_len;
2351                   text = g_realloc (text, text_allocated);
2352
2353                   style = get_style (layout, tags);
2354                   add_preedit_attrs (layout, style, attrs, layout_byte_offset, size_only);
2355                   release_style (layout, style);
2356                   
2357                   memcpy (text + layout_byte_offset, layout->preedit_string, layout->preedit_len);
2358                   layout_byte_offset += layout->preedit_len;
2359                   /* DO NOT increment the buffer byte offset for preedit */
2360                   
2361                   cursor_offset = layout->preedit_cursor - layout->preedit_len;
2362                 }
2363             }
2364           
2365
2366           /* Display visible marks */
2367
2368           if (seg->body.mark.visible)
2369             {
2370               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
2371                                                      GINT_TO_POINTER (layout_byte_offset + cursor_offset));
2372               cursor_segs = g_slist_prepend (cursor_segs, seg);
2373             }
2374         }
2375
2376       else
2377         g_error ("Unknown segment type: %s", seg->type->name);
2378
2379       seg = seg->next;
2380     }
2381   
2382   if (!para_values_set)
2383     {
2384       style = get_style (layout, tags);
2385       set_para_values (layout, base_dir, style, display);
2386       release_style (layout, style);
2387     }
2388   
2389   /* Pango doesn't want the trailing paragraph delimiters */
2390
2391   {
2392     /* Only one character has type G_UNICODE_PARAGRAPH_SEPARATOR in
2393      * Unicode 3.0; update this if that changes.
2394      */
2395 #define PARAGRAPH_SEPARATOR 0x2029
2396     gunichar ch = 0;
2397
2398     if (layout_byte_offset > 0)
2399       {
2400         const char *prev = g_utf8_prev_char (text + layout_byte_offset);
2401         ch = g_utf8_get_char (prev);
2402         if (ch == PARAGRAPH_SEPARATOR || ch == '\r' || ch == '\n')
2403           layout_byte_offset = prev - text; /* chop off */
2404
2405         if (ch == '\n' && layout_byte_offset > 0)
2406           {
2407             /* Possibly chop a CR as well */
2408             prev = g_utf8_prev_char (text + layout_byte_offset);
2409             if (*prev == '\r')
2410               --layout_byte_offset;
2411           }
2412       }
2413   }
2414   
2415   pango_layout_set_text (display->layout, text, layout_byte_offset);
2416   pango_layout_set_attributes (display->layout, attrs);
2417
2418   tmp_list1 = cursor_byte_offsets;
2419   tmp_list2 = cursor_segs;
2420   while (tmp_list1)
2421     {
2422       add_cursor (layout, display, tmp_list2->data,
2423                   GPOINTER_TO_INT (tmp_list1->data));
2424       tmp_list1 = tmp_list1->next;
2425       tmp_list2 = tmp_list2->next;
2426     }
2427   g_slist_free (cursor_byte_offsets);
2428   g_slist_free (cursor_segs);
2429
2430   pango_layout_get_extents (display->layout, NULL, &extents);
2431
2432   display->width = PIXEL_BOUND (extents.width) + display->left_margin + display->right_margin;
2433   display->height += PANGO_PIXELS (extents.height);
2434
2435   /* If we aren't wrapping, we need to do the alignment of each
2436    * paragraph ourselves.
2437    */
2438   if (pango_layout_get_width (display->layout) < 0)
2439     {
2440       gint excess = display->total_width - display->width;
2441
2442       switch (pango_layout_get_alignment (display->layout))
2443         {
2444         case PANGO_ALIGN_LEFT:
2445           break;
2446         case PANGO_ALIGN_CENTER:
2447           display->x_offset += excess / 2;
2448           break;
2449         case PANGO_ALIGN_RIGHT:
2450           display->x_offset += excess;
2451           break;
2452         }
2453     }
2454   
2455   /* Free this if we aren't in a loop */
2456   if (layout->wrap_loop_count == 0)
2457     invalidate_cached_style (layout);
2458
2459   g_free (text);
2460   pango_attr_list_unref (attrs);
2461   if (tags != NULL)
2462     g_ptr_array_free (tags, TRUE);
2463
2464   layout->one_display_cache = display;
2465
2466   if (saw_widget)
2467     allocate_child_widgets (layout, display);
2468   
2469   return display;
2470 }
2471
2472 void
2473 gtk_text_layout_free_line_display (GtkTextLayout      *layout,
2474                                    GtkTextLineDisplay *display)
2475 {
2476   if (display != layout->one_display_cache)
2477     {
2478       if (display->layout)
2479         g_object_unref (display->layout);
2480
2481       if (display->cursors)
2482         g_array_free (display->cursors, TRUE);
2483
2484       if (display->pg_bg_color)
2485         gdk_color_free (display->pg_bg_color);
2486
2487       if (display->pg_bg_rgba)
2488         gdk_rgba_free (display->pg_bg_rgba);
2489
2490       g_slice_free (GtkTextLineDisplay, display);
2491     }
2492 }
2493
2494 /* Functions to convert iter <=> index for the line of a GtkTextLineDisplay
2495  * taking into account the preedit string and invisible text if necessary.
2496  */
2497 static gint
2498 line_display_iter_to_index (GtkTextLayout      *layout,
2499                             GtkTextLineDisplay *display,
2500                             const GtkTextIter  *iter)
2501 {
2502   gint index;
2503
2504   g_return_val_if_fail (_gtk_text_iter_get_text_line (iter) == display->line, 0);
2505
2506   index = gtk_text_iter_get_visible_line_index (iter);
2507   
2508   if (layout->preedit_len > 0 && display->insert_index >= 0)
2509     {
2510       if (index >= display->insert_index)
2511         index += layout->preedit_len;
2512     }
2513
2514   return index;
2515 }
2516
2517 static void
2518 line_display_index_to_iter (GtkTextLayout      *layout,
2519                             GtkTextLineDisplay *display,
2520                             GtkTextIter        *iter,
2521                             gint                index,
2522                             gint                trailing)
2523 {
2524   g_return_if_fail (!_gtk_text_line_is_last (display->line,
2525                                              _gtk_text_buffer_get_btree (layout->buffer)));
2526   
2527   if (layout->preedit_len > 0 && display->insert_index >= 0)
2528     {
2529       if (index >= display->insert_index + layout->preedit_len)
2530         index -= layout->preedit_len;
2531       else if (index > display->insert_index)
2532         {
2533           index = display->insert_index;
2534           trailing = 0;
2535         }
2536     }
2537
2538   gtk_text_layout_get_iter_at_line (layout, iter, display->line, 0);
2539
2540   gtk_text_iter_set_visible_line_index (iter, index);
2541   
2542   if (_gtk_text_iter_get_text_line (iter) != display->line)
2543     {
2544       /* Clamp to end of line - really this clamping should have been done
2545        * before here, maybe in Pango, this is a broken band-aid I think
2546        */
2547       gtk_text_layout_get_iter_at_line (layout, iter, display->line, 0);
2548       if (!gtk_text_iter_ends_line (iter))
2549         gtk_text_iter_forward_to_line_end (iter);
2550     }
2551   
2552   gtk_text_iter_forward_chars (iter, trailing);
2553 }
2554
2555 static void
2556 get_line_at_y (GtkTextLayout *layout,
2557                gint           y,
2558                GtkTextLine  **line,
2559                gint          *line_top)
2560 {
2561   if (y < 0)
2562     y = 0;
2563   if (y > layout->height)
2564     y = layout->height;
2565
2566   *line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
2567                                          layout, y, line_top);
2568   if (*line == NULL)
2569     {
2570       *line = _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
2571       
2572       if (line_top)
2573         *line_top =
2574           _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2575                                         *line, layout);
2576     }
2577 }
2578
2579 /**
2580  * gtk_text_layout_get_line_at_y:
2581  * @layout: a #GtkLayout
2582  * @target_iter: the iterator in which the result is stored
2583  * @y: the y positition
2584  * @line_top: location to store the y coordinate of the
2585  *            top of the line. (Can by %NULL)
2586  *
2587  * Get the iter at the beginning of the line which is displayed
2588  * at the given y.
2589  */
2590 void
2591 gtk_text_layout_get_line_at_y (GtkTextLayout *layout,
2592                                GtkTextIter   *target_iter,
2593                                gint           y,
2594                                gint          *line_top)
2595 {
2596   GtkTextLine *line;
2597
2598   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2599   g_return_if_fail (target_iter != NULL);
2600
2601   get_line_at_y (layout, y, &line, line_top);
2602   gtk_text_layout_get_iter_at_line (layout, target_iter, line, 0);
2603 }
2604
2605 void
2606 gtk_text_layout_get_iter_at_pixel (GtkTextLayout *layout,
2607                                    GtkTextIter   *target_iter,
2608                                    gint           x, 
2609                                    gint           y)
2610 {
2611   gint trailing;
2612
2613   gtk_text_layout_get_iter_at_position (layout, target_iter, &trailing, x, y);
2614
2615   gtk_text_iter_forward_chars (target_iter, trailing);  
2616 }
2617
2618 void gtk_text_layout_get_iter_at_position (GtkTextLayout     *layout,
2619                                            GtkTextIter       *target_iter,
2620                                            gint              *trailing,
2621                                            gint               x,
2622                                            gint               y)
2623 {
2624   GtkTextLine *line;
2625   gint byte_index;
2626   gint line_top;
2627   GtkTextLineDisplay *display;
2628
2629   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2630   g_return_if_fail (target_iter != NULL);
2631
2632   get_line_at_y (layout, y, &line, &line_top);
2633
2634   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2635
2636   x -= display->x_offset;
2637   y -= line_top + display->top_margin;
2638
2639   /* If we are below the layout, position the cursor at the last character
2640    * of the line.
2641    */
2642   if (y > display->height - display->top_margin - display->bottom_margin)
2643     {
2644       byte_index = _gtk_text_line_byte_count (line);
2645       if (trailing)
2646         *trailing = 0;
2647     }
2648   else
2649     {
2650        /* Ignore the "outside" return value from pango. Pango is doing
2651         * the right thing even if we are outside the layout in the
2652         * x-direction.
2653         */
2654       pango_layout_xy_to_index (display->layout, x * PANGO_SCALE, y * PANGO_SCALE,
2655                                 &byte_index, trailing);
2656     }
2657
2658   line_display_index_to_iter (layout, display, target_iter, byte_index, 0);
2659
2660   gtk_text_layout_free_line_display (layout, display);
2661 }
2662
2663
2664 /**
2665  * gtk_text_layout_get_cursor_locations:
2666  * @layout: a #GtkTextLayout
2667  * @iter: a #GtkTextIter
2668  * @strong_pos: (allow-none): location to store the strong cursor position (may be %NULL)
2669  * @weak_pos: (allow-none): location to store the weak cursor position (may be %NULL)
2670  *
2671  * Given an iterator within a text layout, determine the positions of the
2672  * strong and weak cursors if the insertion point is at that
2673  * iterator. The position of each cursor is stored as a zero-width
2674  * rectangle. The strong cursor location is the location where
2675  * characters of the directionality equal to the base direction of the
2676  * paragraph are inserted.  The weak cursor location is the location
2677  * where characters of the directionality opposite to the base
2678  * direction of the paragraph are inserted.
2679  **/
2680 void
2681 gtk_text_layout_get_cursor_locations (GtkTextLayout  *layout,
2682                                       GtkTextIter    *iter,
2683                                       GdkRectangle   *strong_pos,
2684                                       GdkRectangle   *weak_pos)
2685 {
2686   GtkTextLine *line;
2687   GtkTextLineDisplay *display;
2688   gint line_top;
2689   gint index;
2690   GtkTextIter insert_iter;
2691
2692   PangoRectangle pango_strong_pos;
2693   PangoRectangle pango_weak_pos;
2694
2695   g_return_if_fail (layout != NULL);
2696   g_return_if_fail (iter != NULL);
2697
2698   line = _gtk_text_iter_get_text_line (iter);
2699   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2700   index = line_display_iter_to_index (layout, display, iter);
2701   
2702   line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2703                                            line, layout);
2704   
2705   gtk_text_buffer_get_iter_at_mark (layout->buffer, &insert_iter,
2706                                     gtk_text_buffer_get_insert (layout->buffer));
2707
2708   if (gtk_text_iter_equal (iter, &insert_iter))
2709     index += layout->preedit_cursor - layout->preedit_len;
2710   
2711   pango_layout_get_cursor_pos (display->layout, index,
2712                                strong_pos ? &pango_strong_pos : NULL,
2713                                weak_pos ? &pango_weak_pos : NULL);
2714
2715   if (strong_pos)
2716     {
2717       strong_pos->x = display->x_offset + pango_strong_pos.x / PANGO_SCALE;
2718       strong_pos->y = line_top + display->top_margin + pango_strong_pos.y / PANGO_SCALE;
2719       strong_pos->width = 0;
2720       strong_pos->height = pango_strong_pos.height / PANGO_SCALE;
2721     }
2722
2723   if (weak_pos)
2724     {
2725       weak_pos->x = display->x_offset + pango_weak_pos.x / PANGO_SCALE;
2726       weak_pos->y = line_top + display->top_margin + pango_weak_pos.y / PANGO_SCALE;
2727       weak_pos->width = 0;
2728       weak_pos->height = pango_weak_pos.height / PANGO_SCALE;
2729     }
2730
2731   gtk_text_layout_free_line_display (layout, display);
2732 }
2733
2734 /**
2735  * _gtk_text_layout_get_block_cursor:
2736  * @layout: a #GtkTextLayout
2737  * @pos: a #GdkRectangle to store block cursor position
2738  *
2739  * If layout is to display a block cursor, calculates its position
2740  * and returns %TRUE. Otherwise it returns %FALSE. In case when
2741  * cursor is visible, it simply returns the position stored in
2742  * the line display, otherwise it has to compute the position
2743  * (see get_block_cursor()).
2744  **/
2745 gboolean
2746 _gtk_text_layout_get_block_cursor (GtkTextLayout *layout,
2747                                    GdkRectangle  *pos)
2748 {
2749   GtkTextLine *line;
2750   GtkTextLineDisplay *display;
2751   GtkTextIter iter;
2752   GdkRectangle rect;
2753   gboolean block = FALSE;
2754
2755   g_return_val_if_fail (layout != NULL, FALSE);
2756
2757   gtk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
2758                                     gtk_text_buffer_get_insert (layout->buffer));
2759   line = _gtk_text_iter_get_text_line (&iter);
2760   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2761
2762   if (display->has_block_cursor)
2763     {
2764       block = TRUE;
2765       rect = display->block_cursor;
2766     }
2767   else
2768     {
2769       gint index = display->insert_index;
2770
2771       if (index < 0)
2772         index = gtk_text_iter_get_line_index (&iter);
2773
2774       if (get_block_cursor (layout, display, &iter, index, &rect, NULL))
2775         block = TRUE;
2776     }
2777
2778   if (block && pos)
2779     {
2780       gint line_top;
2781
2782       line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2783                                                 line, layout);
2784
2785       *pos = rect;
2786       pos->x += display->x_offset;
2787       pos->y += line_top + display->top_margin;
2788     }
2789
2790   gtk_text_layout_free_line_display (layout, display);
2791   return block;
2792 }
2793
2794 /**
2795  * gtk_text_layout_get_line_yrange:
2796  * @layout: a #GtkTextLayout
2797  * @iter:   a #GtkTextIter
2798  * @y:      location to store the top of the paragraph in pixels,
2799  *          or %NULL.
2800  * @height  location to store the height of the paragraph in pixels,
2801  *          or %NULL.
2802  *
2803  * Find the range of y coordinates for the paragraph containing
2804  * the given iter.
2805  **/
2806 void
2807 gtk_text_layout_get_line_yrange (GtkTextLayout     *layout,
2808                                  const GtkTextIter *iter,
2809                                  gint              *y,
2810                                  gint              *height)
2811 {
2812   GtkTextLine *line;
2813
2814   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2815   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2816
2817   line = _gtk_text_iter_get_text_line (iter);
2818
2819   if (y)
2820     *y = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2821                                        line, layout);
2822   if (height)
2823     {
2824       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
2825       if (line_data)
2826         *height = line_data->height;
2827       else
2828         *height = 0;
2829     }
2830 }
2831
2832 /**
2833  * _gtk_text_layout_get_line_xrange:
2834  * @layout: a #GtkTextLayout
2835  * @iter:   a #GtkTextIter
2836  * @x:      location to store the top of the paragraph in pixels,
2837  *          or %NULL.
2838  * @width  location to store the height of the paragraph in pixels,
2839  *          or %NULL.
2840  *
2841  * Find the range of X coordinates for the paragraph containing
2842  * the given iter. Private for 2.0 due to API freeze, could
2843  * be made public for 2.2.
2844  **/
2845 void
2846 _gtk_text_layout_get_line_xrange (GtkTextLayout     *layout,
2847                                   const GtkTextIter *iter,
2848                                   gint              *x,
2849                                   gint              *width)
2850 {
2851   GtkTextLine *line;
2852
2853   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2854   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2855
2856   line = _gtk_text_iter_get_text_line (iter);
2857
2858   if (x)
2859     *x = 0; /* FIXME This is wrong; should represent the first available cursor position */
2860   
2861   if (width)
2862     {
2863       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
2864       if (line_data)
2865         *width = line_data->width;
2866       else
2867         *width = 0;
2868     }
2869 }
2870
2871 void
2872 gtk_text_layout_get_iter_location (GtkTextLayout     *layout,
2873                                    const GtkTextIter *iter,
2874                                    GdkRectangle      *rect)
2875 {
2876   PangoRectangle pango_rect;
2877   GtkTextLine *line;
2878   GtkTextBTree *tree;
2879   GtkTextLineDisplay *display;
2880   gint byte_index;
2881   gint x_offset;
2882   
2883   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2884   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2885   g_return_if_fail (rect != NULL);
2886
2887   tree = _gtk_text_iter_get_btree (iter);
2888   line = _gtk_text_iter_get_text_line (iter);
2889
2890   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2891
2892   rect->y = _gtk_text_btree_find_line_top (tree, line, layout);
2893
2894   x_offset = display->x_offset * PANGO_SCALE;
2895
2896   byte_index = gtk_text_iter_get_line_index (iter);
2897   
2898   pango_layout_index_to_pos (display->layout, byte_index, &pango_rect);
2899   
2900   rect->x = PANGO_PIXELS (x_offset + pango_rect.x);
2901   rect->y += PANGO_PIXELS (pango_rect.y) + display->top_margin;
2902   rect->width = PANGO_PIXELS (pango_rect.width);
2903   rect->height = PANGO_PIXELS (pango_rect.height);
2904
2905   gtk_text_layout_free_line_display (layout, display);
2906 }
2907
2908 /* FFIXX */
2909
2910 /* Find the iter for the logical beginning of the first display line whose
2911  * top y is >= y. If none exists, move the iter to the logical beginning
2912  * of the last line in the buffer.
2913  */
2914 static void
2915 find_display_line_below (GtkTextLayout *layout,
2916                          GtkTextIter   *iter,
2917                          gint           y)
2918 {
2919   GtkTextLine *line, *next;
2920   GtkTextLine *found_line = NULL;
2921   gint line_top;
2922   gint found_byte = 0;
2923
2924   line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
2925                                         layout, y, &line_top);
2926   if (!line)
2927     {
2928       line =
2929         _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
2930
2931       line_top =
2932         _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2933                                       line, layout);
2934     }
2935
2936   while (line && !found_line)
2937     {
2938       GtkTextLineDisplay *display = gtk_text_layout_get_line_display (layout, line, FALSE);
2939       PangoLayoutIter *layout_iter;
2940
2941       layout_iter = pango_layout_get_iter (display->layout);
2942
2943       line_top += display->top_margin;
2944
2945       do
2946         {
2947           gint first_y, last_y;
2948           PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
2949
2950           found_byte = layout_line->start_index;
2951           
2952           if (line_top >= y)
2953             {
2954               found_line = line;
2955               break;
2956             }
2957
2958           pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
2959           line_top += (last_y - first_y) / PANGO_SCALE;
2960         }
2961       while (pango_layout_iter_next_line (layout_iter));
2962
2963       pango_layout_iter_free (layout_iter);
2964       
2965       line_top += display->bottom_margin;
2966       gtk_text_layout_free_line_display (layout, display);
2967
2968       next = _gtk_text_line_next_excluding_last (line);
2969       if (!next)
2970         found_line = line;
2971
2972       line = next;
2973     }
2974
2975   gtk_text_layout_get_iter_at_line (layout, iter, found_line, found_byte);
2976 }
2977
2978 /* Find the iter for the logical beginning of the last display line whose
2979  * top y is >= y. If none exists, move the iter to the logical beginning
2980  * of the first line in the buffer.
2981  */
2982 static void
2983 find_display_line_above (GtkTextLayout *layout,
2984                          GtkTextIter   *iter,
2985                          gint           y)
2986 {
2987   GtkTextLine *line;
2988   GtkTextLine *found_line = NULL;
2989   gint line_top;
2990   gint found_byte = 0;
2991
2992   line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer), layout, y, &line_top);
2993   if (!line)
2994     {
2995       line = _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
2996       
2997       line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer), line, layout);
2998     }
2999
3000   while (line && !found_line)
3001     {
3002       GtkTextLineDisplay *display = gtk_text_layout_get_line_display (layout, line, FALSE);
3003       PangoRectangle logical_rect;
3004       PangoLayoutIter *layout_iter;
3005       gint tmp_top;
3006
3007       layout_iter = pango_layout_get_iter (display->layout);
3008       
3009       line_top -= display->top_margin + display->bottom_margin;
3010       pango_layout_iter_get_layout_extents (layout_iter, NULL, &logical_rect);
3011       line_top -= logical_rect.height / PANGO_SCALE;
3012
3013       tmp_top = line_top + display->top_margin;
3014
3015       do
3016         {
3017           gint first_y, last_y;
3018           PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
3019
3020           found_byte = layout_line->start_index;
3021
3022           pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
3023           
3024           tmp_top -= (last_y - first_y) / PANGO_SCALE;
3025
3026           if (tmp_top < y)
3027             {
3028               found_line = line;
3029               pango_layout_iter_free (layout_iter);
3030               goto done;
3031             }
3032         }
3033       while (pango_layout_iter_next_line (layout_iter));
3034
3035       pango_layout_iter_free (layout_iter);
3036       
3037       gtk_text_layout_free_line_display (layout, display);
3038
3039       line = _gtk_text_line_previous (line);
3040     }
3041
3042  done:
3043
3044   if (found_line)
3045     gtk_text_layout_get_iter_at_line (layout, iter, found_line, found_byte);
3046   else
3047     gtk_text_buffer_get_iter_at_offset (layout->buffer, iter, 0);
3048 }
3049
3050 /**
3051  * gtk_text_layout_clamp_iter_to_vrange:
3052  * @layout: a #GtkTextLayout
3053  * @iter:   a #GtkTextIter
3054  * @top:    the top of the range
3055  * @bottom: the bottom the range
3056  *
3057  * If the iterator is not fully in the range @top <= y < @bottom,
3058  * then, if possible, move it the minimum distance so that the
3059  * iterator in this range.
3060  *
3061  * Returns: %TRUE if the iterator was moved, otherwise %FALSE.
3062  **/
3063 gboolean
3064 gtk_text_layout_clamp_iter_to_vrange (GtkTextLayout *layout,
3065                                       GtkTextIter   *iter,
3066                                       gint           top,
3067                                       gint           bottom)
3068 {
3069   GdkRectangle iter_rect;
3070
3071   gtk_text_layout_get_iter_location (layout, iter, &iter_rect);
3072
3073   /* If the iter is at least partially above the range, put the iter
3074    * at the first fully visible line after the range.
3075    */
3076   if (iter_rect.y < top)
3077     {
3078       find_display_line_below (layout, iter, top);
3079
3080       return TRUE;
3081     }
3082   /* Otherwise, if the iter is at least partially below the screen, put the
3083    * iter on the last logical position of the last completely visible
3084    * line on screen
3085    */
3086   else if (iter_rect.y + iter_rect.height > bottom)
3087     {
3088       find_display_line_above (layout, iter, bottom);
3089
3090       return TRUE;
3091     }
3092   else
3093     return FALSE;
3094 }
3095
3096 /**
3097  * gtk_text_layout_move_iter_to_previous_line:
3098  * @layout: a #GtkLayout
3099  * @iter:   a #GtkTextIter
3100  *
3101  * Move the iterator to the beginning of the previous line. The lines
3102  * of a wrapped paragraph are treated as distinct for this operation.
3103  **/
3104 gboolean
3105 gtk_text_layout_move_iter_to_previous_line (GtkTextLayout *layout,
3106                                             GtkTextIter   *iter)
3107 {
3108   GtkTextLine *line;
3109   GtkTextLineDisplay *display;
3110   gint line_byte;
3111   GSList *tmp_list;
3112   PangoLayoutLine *layout_line;
3113   GtkTextIter orig;
3114   gboolean update_byte = FALSE;
3115   
3116   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3117   g_return_val_if_fail (iter != NULL, FALSE);
3118
3119   orig = *iter;
3120
3121
3122   line = _gtk_text_iter_get_text_line (iter);
3123   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3124   line_byte = line_display_iter_to_index (layout, display, iter);
3125
3126   /* If display->height == 0 then the line is invisible, so don't
3127    * move onto it.
3128    */
3129   while (display->height == 0)
3130     {
3131       GtkTextLine *prev_line;
3132
3133       prev_line = _gtk_text_line_previous (line);
3134
3135       if (prev_line == NULL)
3136         {
3137           line_display_index_to_iter (layout, display, iter, 0, 0);
3138           goto out;
3139         }
3140
3141       gtk_text_layout_free_line_display (layout, display);
3142
3143       line = prev_line;
3144       display = gtk_text_layout_get_line_display (layout, prev_line, FALSE);
3145       update_byte = TRUE;
3146     }
3147   
3148   tmp_list = pango_layout_get_lines_readonly (display->layout);
3149   layout_line = tmp_list->data;
3150
3151   if (update_byte)
3152     {
3153       line_byte = layout_line->start_index + layout_line->length;
3154     }
3155
3156   if (line_byte < layout_line->length || !tmp_list->next) /* first line of paragraph */
3157     {
3158       GtkTextLine *prev_line;
3159
3160       prev_line = _gtk_text_line_previous (line);
3161
3162       /* first line of the whole buffer, do not move the iter and return FALSE */
3163       if (prev_line == NULL)
3164         goto out;
3165
3166       while (prev_line)
3167         {
3168           gtk_text_layout_free_line_display (layout, display);
3169
3170           display = gtk_text_layout_get_line_display (layout, prev_line, FALSE);
3171
3172           if (display->height > 0)
3173             {
3174               tmp_list = g_slist_last (pango_layout_get_lines_readonly (display->layout));
3175               layout_line = tmp_list->data;
3176
3177               line_display_index_to_iter (layout, display, iter,
3178                                           layout_line->start_index + layout_line->length, 0);
3179               break;
3180             }
3181
3182           prev_line = _gtk_text_line_previous (prev_line);
3183         }
3184     }
3185   else
3186     {
3187       gint prev_offset = layout_line->start_index;
3188
3189       tmp_list = tmp_list->next;
3190       while (tmp_list)
3191         {
3192           layout_line = tmp_list->data;
3193
3194           if (line_byte < layout_line->start_index + layout_line->length ||
3195               !tmp_list->next)
3196             {
3197               line_display_index_to_iter (layout, display, iter, prev_offset, 0);
3198               break;
3199             }
3200
3201           prev_offset = layout_line->start_index;
3202           tmp_list = tmp_list->next;
3203         }
3204     }
3205
3206  out:
3207   
3208   gtk_text_layout_free_line_display (layout, display);
3209
3210   return
3211     !gtk_text_iter_equal (iter, &orig) &&
3212     !gtk_text_iter_is_end (iter);
3213 }
3214
3215 /**
3216  * gtk_text_layout_move_iter_to_next_line:
3217  * @layout: a #GtkLayout
3218  * @iter:   a #GtkTextIter
3219  *
3220  * Move the iterator to the beginning of the next line. The
3221  * lines of a wrapped paragraph are treated as distinct for
3222  * this operation.
3223  **/
3224 gboolean
3225 gtk_text_layout_move_iter_to_next_line (GtkTextLayout *layout,
3226                                         GtkTextIter   *iter)
3227 {
3228   GtkTextLine *line;
3229   GtkTextLineDisplay *display;
3230   gint line_byte;
3231   GtkTextIter orig;
3232   gboolean found = FALSE;
3233   gboolean found_after = FALSE;
3234   gboolean first = TRUE;
3235
3236   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3237   g_return_val_if_fail (iter != NULL, FALSE);
3238
3239   orig = *iter;
3240   
3241   line = _gtk_text_iter_get_text_line (iter);
3242
3243   while (line && !found_after)
3244     {
3245       GSList *tmp_list;
3246
3247       display = gtk_text_layout_get_line_display (layout, line, FALSE);
3248
3249       if (display->height == 0)
3250         goto next;
3251       
3252       if (first)
3253         {
3254           line_byte = line_display_iter_to_index (layout, display, iter);
3255           first = FALSE;
3256         }
3257       else
3258         line_byte = 0;
3259         
3260       tmp_list = pango_layout_get_lines_readonly (display->layout);
3261       while (tmp_list && !found_after)
3262         {
3263           PangoLayoutLine *layout_line = tmp_list->data;
3264
3265           if (found)
3266             {
3267               line_display_index_to_iter (layout, display, iter,
3268                                           layout_line->start_index, 0);
3269               found_after = TRUE;
3270             }
3271           else if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
3272             found = TRUE;
3273           
3274           tmp_list = tmp_list->next;
3275         }
3276
3277     next:
3278       
3279       gtk_text_layout_free_line_display (layout, display);
3280
3281       line = _gtk_text_line_next_excluding_last (line);
3282     }
3283
3284   if (!found_after)
3285     gtk_text_buffer_get_end_iter (layout->buffer, iter);
3286   
3287   return
3288     !gtk_text_iter_equal (iter, &orig) &&
3289     !gtk_text_iter_is_end (iter);
3290 }
3291
3292 /**
3293  * gtk_text_layout_move_iter_to_line_end:
3294  * @layout: a #GtkTextLayout
3295  * @direction: if negative, move to beginning of line, otherwise
3296                move to end of line.
3297  *
3298  * Move to the beginning or end of a display line.
3299  **/
3300 gboolean
3301 gtk_text_layout_move_iter_to_line_end (GtkTextLayout *layout,
3302                                        GtkTextIter   *iter,
3303                                        gint           direction)
3304 {
3305   GtkTextLine *line;
3306   GtkTextLineDisplay *display;
3307   gint line_byte;
3308   GSList *tmp_list;
3309   GtkTextIter orig;
3310   
3311   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3312   g_return_val_if_fail (iter != NULL, FALSE);
3313
3314   orig = *iter;
3315   
3316   line = _gtk_text_iter_get_text_line (iter);
3317   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3318   line_byte = line_display_iter_to_index (layout, display, iter);
3319
3320   tmp_list = pango_layout_get_lines_readonly (display->layout);
3321   while (tmp_list)
3322     {
3323       PangoLayoutLine *layout_line = tmp_list->data;
3324
3325       if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
3326         {
3327           line_display_index_to_iter (layout, display, iter,
3328                                       direction < 0 ? layout_line->start_index : layout_line->start_index + layout_line->length,
3329                                       0);
3330
3331           /* FIXME: As a bad hack, we move back one position when we
3332            * are inside a paragraph to avoid going to next line on a
3333            * forced break not at whitespace. Real fix is to keep track
3334            * of whether marks are at leading or trailing edge?  */
3335           if (direction > 0 && layout_line->length > 0 && 
3336               !gtk_text_iter_ends_line (iter) && 
3337               !_gtk_text_btree_char_is_invisible (iter))
3338             gtk_text_iter_backward_char (iter);
3339           break;
3340         }
3341       
3342       tmp_list = tmp_list->next;
3343     }
3344
3345   gtk_text_layout_free_line_display (layout, display);
3346
3347   return
3348     !gtk_text_iter_equal (iter, &orig) &&
3349     !gtk_text_iter_is_end (iter);
3350 }
3351
3352
3353 /**
3354  * gtk_text_layout_iter_starts_line:
3355  * @layout: a #GtkTextLayout
3356  * @iter: iterator to test
3357  *
3358  * Tests whether an iterator is at the start of a display line.
3359  **/
3360 gboolean
3361 gtk_text_layout_iter_starts_line (GtkTextLayout       *layout,
3362                                   const GtkTextIter   *iter)
3363 {
3364   GtkTextLine *line;
3365   GtkTextLineDisplay *display;
3366   gint line_byte;
3367   GSList *tmp_list;
3368   
3369   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3370   g_return_val_if_fail (iter != NULL, FALSE);
3371
3372   line = _gtk_text_iter_get_text_line (iter);
3373   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3374   line_byte = line_display_iter_to_index (layout, display, iter);
3375
3376   tmp_list = pango_layout_get_lines_readonly (display->layout);
3377   while (tmp_list)
3378     {
3379       PangoLayoutLine *layout_line = tmp_list->data;
3380
3381       if (line_byte < layout_line->start_index + layout_line->length ||
3382           !tmp_list->next)
3383         {
3384           /* We're located on this line or the para delimiters before
3385            * it
3386            */
3387           gtk_text_layout_free_line_display (layout, display);
3388           
3389           if (line_byte == layout_line->start_index)
3390             return TRUE;
3391           else
3392             return FALSE;
3393         }
3394       
3395       tmp_list = tmp_list->next;
3396     }
3397
3398   g_assert_not_reached ();
3399   return FALSE;
3400 }
3401
3402 void
3403 gtk_text_layout_get_iter_at_line (GtkTextLayout  *layout,
3404                                   GtkTextIter    *iter,
3405                                   GtkTextLine    *line,
3406                                   gint            byte_offset)
3407 {
3408   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3409                                     iter, line, byte_offset);
3410 }
3411
3412 /**
3413  * gtk_text_layout_move_iter_to_x:
3414  * @layout: a #GtkTextLayout
3415  * @iter:   a #GtkTextIter
3416  * @x:      X coordinate
3417  *
3418  * Keeping the iterator on the same line of the layout, move it to the
3419  * specified X coordinate. The lines of a wrapped paragraph are
3420  * treated as distinct for this operation.
3421  **/
3422 void
3423 gtk_text_layout_move_iter_to_x (GtkTextLayout *layout,
3424                                 GtkTextIter   *iter,
3425                                 gint           x)
3426 {
3427   GtkTextLine *line;
3428   GtkTextLineDisplay *display;
3429   gint line_byte;
3430   PangoLayoutIter *layout_iter;
3431   
3432   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
3433   g_return_if_fail (iter != NULL);
3434
3435   line = _gtk_text_iter_get_text_line (iter);
3436
3437   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3438   line_byte = line_display_iter_to_index (layout, display, iter);
3439
3440   layout_iter = pango_layout_get_iter (display->layout);
3441
3442   do
3443     {
3444       PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
3445
3446       if (line_byte < layout_line->start_index + layout_line->length ||
3447           pango_layout_iter_at_last_line (layout_iter))
3448         {
3449           PangoRectangle logical_rect;
3450           gint byte_index, trailing;
3451           gint x_offset = display->x_offset * PANGO_SCALE;
3452
3453           pango_layout_iter_get_line_extents (layout_iter, NULL, &logical_rect);
3454
3455           pango_layout_line_x_to_index (layout_line,
3456                                         x * PANGO_SCALE - x_offset - logical_rect.x,
3457                                         &byte_index, &trailing);
3458
3459           line_display_index_to_iter (layout, display, iter, byte_index, trailing);
3460
3461           break;
3462         }
3463     }
3464   while (pango_layout_iter_next_line (layout_iter));
3465
3466   pango_layout_iter_free (layout_iter);
3467   
3468   gtk_text_layout_free_line_display (layout, display);
3469 }
3470
3471 /**
3472  * gtk_text_layout_move_iter_visually:
3473  * @layout:  a #GtkTextLayout
3474  * @iter:    a #GtkTextIter
3475  * @count:   number of characters to move (negative moves left, positive moves right)
3476  *
3477  * Move the iterator a given number of characters visually, treating
3478  * it as the strong cursor position. If @count is positive, then the
3479  * new strong cursor position will be @count positions to the right of
3480  * the old cursor position. If @count is negative then the new strong
3481  * cursor position will be @count positions to the left of the old
3482  * cursor position.
3483  *
3484  * In the presence of bidirection text, the correspondence
3485  * between logical and visual order will depend on the direction
3486  * of the current run, and there may be jumps when the cursor
3487  * is moved off of the end of a run.
3488  **/
3489
3490 gboolean
3491 gtk_text_layout_move_iter_visually (GtkTextLayout *layout,
3492                                     GtkTextIter   *iter,
3493                                     gint           count)
3494 {
3495   GtkTextLineDisplay *display = NULL;
3496   GtkTextIter orig;
3497   GtkTextIter lineiter;
3498   
3499   g_return_val_if_fail (layout != NULL, FALSE);
3500   g_return_val_if_fail (iter != NULL, FALSE);
3501
3502   orig = *iter;
3503   
3504   while (count != 0)
3505     {
3506       GtkTextLine *line = _gtk_text_iter_get_text_line (iter);
3507       gint line_byte;
3508       gint extra_back = 0;
3509       gboolean strong;
3510
3511       int byte_count = _gtk_text_line_byte_count (line);
3512
3513       int new_index;
3514       int new_trailing;
3515
3516       if (!display)
3517         display = gtk_text_layout_get_line_display (layout, line, FALSE);
3518
3519       if (layout->cursor_direction == GTK_TEXT_DIR_NONE)
3520         strong = TRUE;
3521       else
3522         strong = display->direction == layout->cursor_direction;
3523
3524       line_byte = line_display_iter_to_index (layout, display, iter);
3525
3526       if (count > 0)
3527         {
3528           pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, 1, &new_index, &new_trailing);
3529           count--;
3530         }
3531       else
3532         {
3533           pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, -1, &new_index, &new_trailing);
3534           count++;
3535         }
3536
3537       /* We need to handle the preedit string specially. Well, we don't really need to
3538        * handle it specially, since hopefully calling gtk_im_context_reset() will
3539        * remove the preedit string; but if we start off in front of the preedit
3540        * string (logically) and end up in or on the back edge of the preedit string,
3541        * we should move the iter one place farther.
3542        */
3543       if (layout->preedit_len > 0 && display->insert_index >= 0)
3544         {
3545           if (line_byte == display->insert_index + layout->preedit_len &&
3546               new_index < display->insert_index + layout->preedit_len)
3547             {
3548               line_byte = display->insert_index;
3549               extra_back = 1;
3550             }
3551         }
3552       
3553       if (new_index < 0 || (new_index == 0 && extra_back))
3554         {
3555           do
3556             {
3557               line = _gtk_text_line_previous (line);
3558               if (!line)
3559                 goto done;
3560             }
3561           while (totally_invisible_line (layout, line, &lineiter));
3562           
3563           gtk_text_layout_free_line_display (layout, display);
3564           display = gtk_text_layout_get_line_display (layout, line, FALSE);
3565           gtk_text_iter_forward_to_line_end (&lineiter);
3566           new_index = gtk_text_iter_get_visible_line_index (&lineiter);
3567         }
3568       else if (new_index > byte_count)
3569         {
3570           do
3571             {
3572               line = _gtk_text_line_next_excluding_last (line);
3573               if (!line)
3574                 goto done;
3575             }
3576           while (totally_invisible_line (layout, line, &lineiter));
3577
3578           gtk_text_layout_free_line_display (layout, display);
3579           display = gtk_text_layout_get_line_display (layout, line, FALSE);
3580           new_index = 0;
3581         }
3582       
3583        line_display_index_to_iter (layout, display, iter, new_index, new_trailing);
3584        if (extra_back)
3585          gtk_text_iter_backward_char (iter);
3586     }
3587
3588   gtk_text_layout_free_line_display (layout, display);
3589
3590  done:
3591   
3592   return
3593     !gtk_text_iter_equal (iter, &orig) &&
3594     !gtk_text_iter_is_end (iter);
3595 }
3596
3597 void
3598 gtk_text_layout_spew (GtkTextLayout *layout)
3599 {
3600 #if 0
3601   GtkTextDisplayLine *iter;
3602   guint wrapped = 0;
3603   guint paragraphs = 0;
3604   GtkTextLine *last_line = NULL;
3605
3606   iter = layout->line_list;
3607   while (iter != NULL)
3608     {
3609       if (iter->line != last_line)
3610         {
3611           printf ("%5u  paragraph (%p)\n", paragraphs, iter->line);
3612           ++paragraphs;
3613           last_line = iter->line;
3614         }
3615
3616       printf ("  %5u  y: %d len: %d start: %d bytes: %d\n",
3617               wrapped, iter->y, iter->length, iter->byte_offset,
3618               iter->byte_count);
3619
3620       ++wrapped;
3621       iter = iter->next;
3622     }
3623
3624   printf ("Layout %s recompute\n",
3625           layout->need_recompute ? "needs" : "doesn't need");
3626
3627   printf ("Layout pars: %u lines: %u size: %d x %d Screen width: %d\n",
3628           paragraphs, wrapped, layout->width,
3629           layout->height, layout->screen_width);
3630 #endif
3631 }
3632
3633 /* Catch all situations that move the insertion point.
3634  */
3635 static void
3636 gtk_text_layout_mark_set_handler (GtkTextBuffer     *buffer,
3637                                   const GtkTextIter *location,
3638                                   GtkTextMark       *mark,
3639                                   gpointer           data)
3640 {
3641   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3642
3643   if (mark == gtk_text_buffer_get_insert (buffer))
3644     gtk_text_layout_update_cursor_line (layout);
3645 }
3646
3647 static void
3648 gtk_text_layout_buffer_insert_text (GtkTextBuffer *textbuffer,
3649                                     GtkTextIter   *iter,
3650                                     gchar         *str,
3651                                     gint           len,
3652                                     gpointer       data)
3653 {
3654   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3655
3656   gtk_text_layout_update_cursor_line (layout);
3657 }
3658
3659 static void
3660 gtk_text_layout_buffer_delete_range (GtkTextBuffer *textbuffer,
3661                                      GtkTextIter   *start,
3662                                      GtkTextIter   *end,
3663                                      gpointer       data)
3664 {
3665   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3666
3667   gtk_text_layout_update_cursor_line (layout);
3668 }