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