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