]> Pileus Git - ~andy/gtk/blob - gtk/gtktextlayout.c
fba9de57802c3c07d30613930d53e9abf01ed58c
[~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                   GTK_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           g_slist_foreach (display->cursors, (GFunc)g_free, NULL);
831           g_slist_free (display->cursors);
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_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
941                                         &line_start, line, 0);
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_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
1261                                     iter, line, 0);
1262   
1263   if (!_gtk_text_btree_char_is_invisible (iter))
1264     return FALSE;
1265
1266   bytes = 0;
1267   seg = line->segments;
1268
1269   while (seg != NULL)
1270     {
1271       if (seg->byte_count > 0)
1272         bytes += seg->byte_count;
1273
1274       /* Note that these two tests can cause us to bail out
1275        * when we shouldn't, because a higher-priority tag
1276        * may override these settings. However the important
1277        * thing is to only invisible really-invisible lines, rather
1278        * than to invisible all really-invisible lines.
1279        */
1280
1281       else if (seg->type == &gtk_text_toggle_on_type)
1282         {
1283           invalidate_cached_style (layout);
1284
1285           /* Bail out if an elision-unsetting tag begins */
1286           if (seg->body.toggle.info->tag->invisible_set &&
1287               !seg->body.toggle.info->tag->values->invisible)
1288             break;
1289         }
1290       else if (seg->type == &gtk_text_toggle_off_type)
1291         {
1292           invalidate_cached_style (layout);
1293
1294           /* Bail out if an elision-setting tag ends */
1295           if (seg->body.toggle.info->tag->invisible_set &&
1296               seg->body.toggle.info->tag->values->invisible)
1297             break;
1298         }
1299
1300       seg = seg->next;
1301     }
1302
1303   if (seg != NULL)       /* didn't reach line end */
1304     return FALSE;
1305
1306   return TRUE;
1307 }
1308
1309 static void
1310 set_para_values (GtkTextLayout      *layout,
1311                  PangoDirection      base_dir,
1312                  GtkTextAttributes  *style,
1313                  GtkTextLineDisplay *display)
1314 {
1315   PangoAlignment pango_align = PANGO_ALIGN_LEFT;
1316   PangoWrapMode pango_wrap = PANGO_WRAP_WORD;
1317
1318   switch (base_dir)
1319     {
1320     /* If no base direction was found, then use the style direction */
1321     case PANGO_DIRECTION_NEUTRAL :
1322       display->direction = style->direction;
1323
1324       /* Override the base direction */
1325       if (display->direction == GTK_TEXT_DIR_RTL)
1326         base_dir = PANGO_DIRECTION_RTL;
1327       else
1328         base_dir = PANGO_DIRECTION_LTR;
1329       
1330       break;
1331     case PANGO_DIRECTION_RTL :
1332       display->direction = GTK_TEXT_DIR_RTL;
1333       break;
1334     default:
1335       display->direction = GTK_TEXT_DIR_LTR;
1336       break;
1337     }
1338   
1339   if (display->direction == GTK_TEXT_DIR_RTL)
1340     display->layout = pango_layout_new (layout->rtl_context);
1341   else
1342     display->layout = pango_layout_new (layout->ltr_context);
1343
1344   switch (style->justification)
1345     {
1346     case GTK_JUSTIFY_LEFT:
1347       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
1348       break;
1349     case GTK_JUSTIFY_RIGHT:
1350       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
1351       break;
1352     case GTK_JUSTIFY_CENTER:
1353       pango_align = PANGO_ALIGN_CENTER;
1354       break;
1355     case GTK_JUSTIFY_FILL:
1356       pango_align = (base_dir == PANGO_DIRECTION_LTR) ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
1357       pango_layout_set_justify (display->layout, TRUE);
1358       break;
1359     default:
1360       g_assert_not_reached ();
1361       break;
1362     }
1363
1364   pango_layout_set_alignment (display->layout, pango_align);
1365   pango_layout_set_spacing (display->layout,
1366                             style->pixels_inside_wrap * PANGO_SCALE);
1367
1368   if (style->tabs)
1369     pango_layout_set_tabs (display->layout, style->tabs);
1370
1371   display->top_margin = style->pixels_above_lines;
1372   display->height = style->pixels_above_lines + style->pixels_below_lines;
1373   display->bottom_margin = style->pixels_below_lines;
1374   display->left_margin = style->left_margin;
1375   display->right_margin = style->right_margin;
1376   
1377   display->x_offset = display->left_margin;
1378
1379   pango_layout_set_indent (display->layout,
1380                            style->indent * PANGO_SCALE);
1381
1382   switch (style->wrap_mode)
1383     {
1384     case GTK_WRAP_CHAR:
1385       pango_wrap = PANGO_WRAP_CHAR;
1386       break;
1387     case GTK_WRAP_WORD:
1388       pango_wrap = PANGO_WRAP_WORD;
1389       break;
1390
1391     case GTK_WRAP_WORD_CHAR:
1392       pango_wrap = PANGO_WRAP_WORD_CHAR;
1393       break;
1394
1395     case GTK_WRAP_NONE:
1396       break;
1397     }
1398
1399   if (style->wrap_mode != GTK_WRAP_NONE)
1400     {
1401       int layout_width = (layout->screen_width - display->left_margin - display->right_margin);
1402       pango_layout_set_width (display->layout, layout_width * PANGO_SCALE);
1403       pango_layout_set_wrap (display->layout, pango_wrap);
1404     }
1405
1406   display->total_width = MAX (layout->screen_width, layout->width) - display->left_margin - display->right_margin;
1407   
1408   if (style->pg_bg_color)
1409     display->pg_bg_color = gdk_color_copy (style->pg_bg_color);
1410   else
1411     display->pg_bg_color = NULL;  
1412 }
1413
1414 static PangoAttribute *
1415 gtk_text_attr_appearance_copy (const PangoAttribute *attr)
1416 {
1417   const GtkTextAttrAppearance *appearance_attr = (const GtkTextAttrAppearance *)attr;
1418
1419   return gtk_text_attr_appearance_new (&appearance_attr->appearance);
1420 }
1421
1422 static void
1423 gtk_text_attr_appearance_destroy (PangoAttribute *attr)
1424 {
1425   GtkTextAttrAppearance *appearance_attr = (GtkTextAttrAppearance *)attr;
1426
1427   g_slice_free (GtkTextAttrAppearance, appearance_attr);
1428 }
1429
1430 static gboolean
1431 gtk_text_attr_appearance_compare (const PangoAttribute *attr1,
1432                                   const PangoAttribute *attr2)
1433 {
1434   const GtkTextAppearance *appearance1 = &((const GtkTextAttrAppearance *)attr1)->appearance;
1435   const GtkTextAppearance *appearance2 = &((const GtkTextAttrAppearance *)attr2)->appearance;
1436
1437   return (gdk_color_equal (&appearance1->fg_color, &appearance2->fg_color) &&
1438           gdk_color_equal (&appearance1->bg_color, &appearance2->bg_color) &&
1439           appearance1->underline == appearance2->underline &&
1440           appearance1->strikethrough == appearance2->strikethrough &&
1441           appearance1->draw_bg == appearance2->draw_bg);
1442 }
1443
1444 /*
1445  * gtk_text_attr_appearance_new:
1446  * @desc:
1447  *
1448  * Create a new font description attribute. (This attribute
1449  * allows setting family, style, weight, variant, stretch,
1450  * and size simultaneously.)
1451  *
1452  * Return value:
1453  */
1454 static PangoAttribute *
1455 gtk_text_attr_appearance_new (const GtkTextAppearance *appearance)
1456 {
1457   static PangoAttrClass klass = {
1458     0,
1459     gtk_text_attr_appearance_copy,
1460     gtk_text_attr_appearance_destroy,
1461     gtk_text_attr_appearance_compare
1462   };
1463
1464   GtkTextAttrAppearance *result;
1465
1466   if (!klass.type)
1467     klass.type = gtk_text_attr_appearance_type =
1468       pango_attr_type_register ("GtkTextAttrAppearance");
1469
1470   result = g_slice_new (GtkTextAttrAppearance);
1471   result->attr.klass = &klass;
1472
1473   result->appearance = *appearance;
1474
1475   return (PangoAttribute *)result;
1476 }
1477
1478 static void
1479 add_generic_attrs (GtkTextLayout      *layout,
1480                    GtkTextAppearance  *appearance,
1481                    gint                byte_count,
1482                    PangoAttrList      *attrs,
1483                    gint                start,
1484                    gboolean            size_only,
1485                    gboolean            is_text)
1486 {
1487   PangoAttribute *attr;
1488
1489   if (appearance->underline != PANGO_UNDERLINE_NONE)
1490     {
1491       attr = pango_attr_underline_new (appearance->underline);
1492       
1493       attr->start_index = start;
1494       attr->end_index = start + byte_count;
1495       
1496       pango_attr_list_insert (attrs, attr);
1497     }
1498
1499   if (appearance->strikethrough)
1500     {
1501       attr = pango_attr_strikethrough_new (appearance->strikethrough);
1502       
1503       attr->start_index = start;
1504       attr->end_index = start + byte_count;
1505       
1506       pango_attr_list_insert (attrs, attr);
1507     }
1508
1509   if (appearance->rise != 0)
1510     {
1511       attr = pango_attr_rise_new (appearance->rise);
1512       
1513       attr->start_index = start;
1514       attr->end_index = start + byte_count;
1515       
1516       pango_attr_list_insert (attrs, attr);
1517     }
1518   
1519   if (!size_only)
1520     {
1521       attr = gtk_text_attr_appearance_new (appearance);
1522       
1523       attr->start_index = start;
1524       attr->end_index = start + byte_count;
1525
1526       ((GtkTextAttrAppearance *)attr)->appearance.is_text = is_text;
1527       
1528       pango_attr_list_insert (attrs, attr);
1529     }
1530 }
1531
1532 static void
1533 add_text_attrs (GtkTextLayout      *layout,
1534                 GtkTextAttributes  *style,
1535                 gint                byte_count,
1536                 PangoAttrList      *attrs,
1537                 gint                start,
1538                 gboolean            size_only)
1539 {
1540   PangoAttribute *attr;
1541
1542   attr = pango_attr_font_desc_new (style->font);
1543   attr->start_index = start;
1544   attr->end_index = start + byte_count;
1545
1546   pango_attr_list_insert (attrs, attr);
1547
1548   if (style->font_scale != 1.0)
1549     {
1550       attr = pango_attr_scale_new (style->font_scale);
1551
1552       attr->start_index = start;
1553       attr->end_index = start + byte_count;
1554       
1555       pango_attr_list_insert (attrs, attr);
1556     }
1557 }
1558
1559 static void
1560 add_pixbuf_attrs (GtkTextLayout      *layout,
1561                   GtkTextLineDisplay *display,
1562                   GtkTextAttributes  *style,
1563                   GtkTextLineSegment *seg,
1564                   PangoAttrList      *attrs,
1565                   gint                start)
1566 {
1567   PangoAttribute *attr;
1568   PangoRectangle logical_rect;
1569   GtkTextPixbuf *pixbuf = &seg->body.pixbuf;
1570   gint width, height;
1571
1572   width = gdk_pixbuf_get_width (pixbuf->pixbuf);
1573   height = gdk_pixbuf_get_height (pixbuf->pixbuf);
1574
1575   logical_rect.x = 0;
1576   logical_rect.y = -height * PANGO_SCALE;
1577   logical_rect.width = width * PANGO_SCALE;
1578   logical_rect.height = height * PANGO_SCALE;
1579
1580   attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
1581                                          pixbuf->pixbuf, NULL, NULL);
1582   attr->start_index = start;
1583   attr->end_index = start + seg->byte_count;
1584   pango_attr_list_insert (attrs, attr);
1585
1586   display->shaped_objects =
1587     g_slist_append (display->shaped_objects, pixbuf->pixbuf);
1588 }
1589
1590 static void
1591 add_child_attrs (GtkTextLayout      *layout,
1592                  GtkTextLineDisplay *display,
1593                  GtkTextAttributes  *style,
1594                  GtkTextLineSegment *seg,
1595                  PangoAttrList      *attrs,
1596                  gint                start)
1597 {
1598   PangoAttribute *attr;
1599   PangoRectangle logical_rect;
1600   gint width, height;
1601   GSList *tmp_list;
1602   GtkWidget *widget;
1603
1604   width = 1;
1605   height = 1;
1606   
1607   tmp_list = seg->body.child.widgets;
1608   while (tmp_list != NULL)
1609     {
1610       GtkWidget *child = tmp_list->data;
1611
1612       if (_gtk_anchored_child_get_layout (child) == layout)
1613         {
1614           /* Found it */
1615           GtkRequisition req;
1616
1617           gtk_widget_get_child_requisition (child, &req);
1618           
1619           width = req.width;
1620           height = req.height;
1621
1622           widget = child;
1623           
1624           break;
1625         }
1626       
1627       tmp_list = g_slist_next (tmp_list);
1628     }
1629
1630   if (tmp_list == NULL)
1631     {
1632       /* If tmp_list == NULL then there is no widget at this anchor in
1633        * this display; not an error. We make up an arbitrary size
1634        * to use, just so the programmer can see the blank spot.
1635        * We also put a NULL in the shaped objects list, to keep
1636        * the correspondence between the list and the shaped chars in
1637        * the layout. A bad hack, yes.
1638        */
1639
1640       width = 30;
1641       height = 20;
1642
1643       widget = NULL;
1644     }
1645
1646   display->shaped_objects = g_slist_append (display->shaped_objects, widget);
1647   
1648   logical_rect.x = 0;
1649   logical_rect.y = -height * PANGO_SCALE;
1650   logical_rect.width = width * PANGO_SCALE;
1651   logical_rect.height = height * PANGO_SCALE;
1652
1653   attr = pango_attr_shape_new_with_data (&logical_rect, &logical_rect,
1654                                          widget, NULL, NULL);
1655   attr->start_index = start;
1656   attr->end_index = start + seg->byte_count;
1657   pango_attr_list_insert (attrs, attr);
1658 }
1659
1660 /*
1661  * get_block_cursor:
1662  * @layout: a #GtkTextLayout
1663  * @display: a #GtkTextLineDisplay
1664  * @insert_iter: iter pointing to the cursor location
1665  * @insert_index: cursor offset in the @display's layout, it may
1666  * be different from @insert_iter's offset in case when preedit
1667  * string is present.
1668  * @pos: location to store cursor position
1669  * @cursor_at_line_end: whether cursor is at the end of line
1670  *
1671  * Checks whether layout should display block cursor at given position.
1672  * For this layout must be in overwrite mode and text at @insert_iter 
1673  * must be editable.
1674  */
1675 static gboolean
1676 get_block_cursor (GtkTextLayout      *layout,
1677                   GtkTextLineDisplay *display,
1678                   const GtkTextIter  *insert_iter,
1679                   gint                insert_index,
1680                   GdkRectangle       *pos,
1681                   gboolean           *cursor_at_line_end)
1682 {
1683   PangoRectangle pango_pos;
1684
1685   if (layout->overwrite_mode &&
1686       gtk_text_iter_editable (insert_iter, TRUE) &&
1687       _gtk_text_util_get_block_cursor_location (display->layout,
1688                                                 insert_index,
1689                                                 &pango_pos,
1690                                                 cursor_at_line_end))
1691     {
1692       if (pos)
1693         {
1694           pos->x = PANGO_PIXELS (pango_pos.x);
1695           pos->y = PANGO_PIXELS (pango_pos.y);
1696           pos->width = PANGO_PIXELS (pango_pos.width);
1697           pos->height = PANGO_PIXELS (pango_pos.height);
1698         }
1699
1700       return TRUE;
1701     }
1702   else
1703     return FALSE;
1704 }
1705
1706 static void
1707 add_cursor (GtkTextLayout      *layout,
1708             GtkTextLineDisplay *display,
1709             GtkTextLineSegment *seg,
1710             gint                start)
1711 {
1712   PangoRectangle strong_pos, weak_pos;
1713   GtkTextCursorDisplay *cursor = NULL; /* Quiet GCC */
1714   gboolean add_weak = FALSE;
1715   gboolean add_strong = FALSE;
1716   
1717   /* Hide insertion cursor when we have a selection or the layout
1718    * user has hidden the cursor.
1719    */
1720   if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
1721                                      seg->body.mark.obj) &&
1722       (!layout->cursor_visible ||
1723        gtk_text_buffer_get_selection_bounds (layout->buffer, NULL, NULL)))
1724     return;
1725
1726   if (layout->overwrite_mode &&
1727       _gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
1728                                       seg->body.mark.obj))
1729     {
1730       GtkTextIter iter;
1731       gboolean cursor_at_line_end;
1732
1733       _gtk_text_btree_get_iter_at_mark (_gtk_text_buffer_get_btree (layout->buffer),
1734                                         &iter, seg->body.mark.obj);
1735
1736       if (get_block_cursor (layout, display, &iter, start,
1737                             &display->block_cursor,
1738                             &cursor_at_line_end))
1739         {
1740           display->has_block_cursor = TRUE;
1741           display->cursor_at_line_end = cursor_at_line_end;
1742           return;
1743         }
1744     }
1745
1746   pango_layout_get_cursor_pos (display->layout, start, &strong_pos, &weak_pos);
1747
1748   if (layout->cursor_direction == GTK_TEXT_DIR_NONE)
1749     {
1750       add_strong = TRUE;
1751       add_weak = TRUE;
1752     }
1753   else if (display->direction == layout->cursor_direction)
1754     add_strong = TRUE;
1755   else
1756     add_weak = TRUE;
1757
1758   if (add_strong)
1759     {
1760       cursor = g_new (GtkTextCursorDisplay, 1);
1761
1762       cursor->x = PANGO_PIXELS (strong_pos.x);
1763       cursor->y = PANGO_PIXELS (strong_pos.y);
1764       cursor->height = PANGO_PIXELS (strong_pos.height);
1765       cursor->is_strong = TRUE;
1766       cursor->is_weak = (layout->cursor_direction == GTK_TEXT_DIR_NONE) ? FALSE : TRUE;
1767       display->cursors = g_slist_prepend (display->cursors, cursor);
1768     }
1769   
1770   if (add_weak)
1771     {
1772       if (weak_pos.x == strong_pos.x && add_strong)
1773         cursor->is_weak = TRUE;
1774       else
1775         {
1776           cursor = g_new (GtkTextCursorDisplay, 1);
1777           
1778           cursor->x = PANGO_PIXELS (weak_pos.x);
1779           cursor->y = PANGO_PIXELS (weak_pos.y);
1780           cursor->height = PANGO_PIXELS (weak_pos.height);
1781           cursor->is_strong = (layout->cursor_direction == GTK_TEXT_DIR_NONE) ? FALSE : TRUE;
1782           cursor->is_weak = TRUE;
1783           display->cursors = g_slist_prepend (display->cursors, cursor);
1784         }
1785     }
1786 }
1787
1788 static gboolean
1789 is_shape (PangoLayoutRun *run)
1790 {
1791   GSList *tmp_list = run->item->analysis.extra_attrs;
1792     
1793   while (tmp_list)
1794     {
1795       PangoAttribute *attr = tmp_list->data;
1796
1797       if (attr->klass->type == PANGO_ATTR_SHAPE)
1798         return TRUE;
1799
1800       tmp_list = tmp_list->next;
1801     }
1802
1803   return FALSE;
1804 }
1805
1806 static void
1807 allocate_child_widgets (GtkTextLayout      *text_layout,
1808                         GtkTextLineDisplay *display)
1809 {
1810   PangoLayout *layout = display->layout;
1811   PangoLayoutIter *run_iter;
1812
1813   run_iter = pango_layout_get_iter (layout);
1814   do
1815     {
1816       PangoLayoutRun *run = pango_layout_iter_get_run_readonly (run_iter);
1817
1818       if (run && is_shape (run))
1819         {
1820           gint byte_index;
1821           GtkTextIter text_iter;
1822           GtkTextChildAnchor *anchor = NULL;
1823           GList *widgets = NULL;
1824           GList *l;
1825
1826           /* The pango iterator iterates in visual order.
1827            * We use the byte index to find the child widget.
1828            */
1829           byte_index = pango_layout_iter_get_index (run_iter);
1830           line_display_index_to_iter (text_layout, display, &text_iter, byte_index, 0);
1831           anchor = gtk_text_iter_get_child_anchor (&text_iter);
1832           if (anchor)
1833             widgets = gtk_text_child_anchor_get_widgets (anchor);
1834
1835           for (l = widgets; l; l = l->next)
1836             {
1837               PangoRectangle extents;
1838               GtkWidget *child = l->data;
1839
1840               if (_gtk_anchored_child_get_layout (child) == text_layout)
1841                 {
1842
1843                   /* We emit "allocate_child" with the x,y of
1844                    * the widget with respect to the top of the line
1845                    * and the left side of the buffer
1846                    */
1847                   pango_layout_iter_get_run_extents (run_iter,
1848                                                      NULL,
1849                                                      &extents);
1850
1851                   g_signal_emit (text_layout,
1852                                  signals[ALLOCATE_CHILD],
1853                                  0,
1854                                  child,
1855                                  PANGO_PIXELS (extents.x) + display->x_offset,
1856                                  PANGO_PIXELS (extents.y) + display->top_margin);
1857                 }
1858             }
1859
1860           g_list_free (widgets);
1861         }
1862     }
1863   while (pango_layout_iter_next_run (run_iter));
1864
1865   pango_layout_iter_free (run_iter);
1866 }
1867
1868 static void
1869 convert_color (GdkColor       *result,
1870                PangoAttrColor *attr)
1871 {
1872   result->red = attr->color.red;
1873   result->blue = attr->color.blue;
1874   result->green = attr->color.green;
1875 }
1876
1877 /* This function is used to convert the preedit string attributes, which are
1878  * standard PangoAttributes, into the custom attributes used by the text
1879  * widget and insert them into a attr list with a given offset.
1880  */
1881 static void
1882 add_preedit_attrs (GtkTextLayout     *layout,
1883                    GtkTextAttributes *style,
1884                    PangoAttrList     *attrs,
1885                    gint               offset,
1886                    gboolean           size_only)
1887 {
1888   PangoAttrIterator *iter = pango_attr_list_get_iterator (layout->preedit_attrs);
1889
1890   do
1891     {
1892       GtkTextAppearance appearance = style->appearance;
1893       PangoFontDescription *font_desc = pango_font_description_copy_static (style->font);
1894       PangoAttribute *insert_attr;
1895       GSList *extra_attrs = NULL;
1896       GSList *tmp_list;
1897       PangoLanguage *language;
1898       gint start, end;
1899
1900       pango_attr_iterator_range (iter, &start, &end);
1901
1902       if (end == G_MAXINT)
1903         end = layout->preedit_len;
1904       
1905       if (end == start)
1906         continue;
1907
1908       pango_attr_iterator_get_font (iter, font_desc, &language, &extra_attrs);
1909       
1910       tmp_list = extra_attrs;
1911       while (tmp_list)
1912         {
1913           PangoAttribute *attr = tmp_list->data;
1914           
1915           switch (attr->klass->type)
1916             {
1917             case PANGO_ATTR_FOREGROUND:
1918               convert_color (&appearance.fg_color, (PangoAttrColor *)attr);
1919               break;
1920             case PANGO_ATTR_BACKGROUND:
1921               convert_color (&appearance.bg_color, (PangoAttrColor *)attr);
1922               appearance.draw_bg = TRUE;
1923               break;
1924             case PANGO_ATTR_UNDERLINE:
1925               appearance.underline = ((PangoAttrInt *)attr)->value;
1926               break;
1927             case PANGO_ATTR_STRIKETHROUGH:
1928               appearance.strikethrough = ((PangoAttrInt *)attr)->value;
1929               break;
1930             case PANGO_ATTR_RISE:
1931               appearance.rise = ((PangoAttrInt *)attr)->value;
1932               break;
1933             default:
1934               break;
1935             }
1936           
1937           pango_attribute_destroy (attr);
1938           tmp_list = tmp_list->next;
1939         }
1940       
1941       g_slist_free (extra_attrs);
1942       
1943       insert_attr = pango_attr_font_desc_new (font_desc);
1944       insert_attr->start_index = start + offset;
1945       insert_attr->end_index = end + offset;
1946       
1947       pango_attr_list_insert (attrs, insert_attr);
1948
1949       if (language)
1950         {
1951           insert_attr = pango_attr_language_new (language);
1952           insert_attr->start_index = start + offset;
1953           insert_attr->end_index = end + offset;
1954           
1955           pango_attr_list_insert (attrs, insert_attr);
1956         }
1957
1958       add_generic_attrs (layout, &appearance, end - start,
1959                          attrs, start + offset,
1960                          size_only, TRUE);
1961       
1962       pango_font_description_free (font_desc);
1963     }
1964   while (pango_attr_iterator_next (iter));
1965
1966   pango_attr_iterator_destroy (iter);
1967 }
1968
1969 /* Iterate over the line and fill in display->cursors.
1970  * It's a stripped copy of gtk_text_layout_get_line_display() */
1971 static void
1972 update_text_display_cursors (GtkTextLayout      *layout,
1973                              GtkTextLine        *line,
1974                              GtkTextLineDisplay *display)
1975 {
1976   GtkTextLineSegment *seg;
1977   GtkTextIter iter;
1978   gint layout_byte_offset, buffer_byte_offset;
1979   GSList *cursor_byte_offsets = NULL;
1980   GSList *cursor_segs = NULL;
1981   GSList *tmp_list1, *tmp_list2;
1982
1983   if (!display->cursors_invalid)
1984     return;
1985
1986   display->cursors_invalid = FALSE;
1987
1988   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
1989                                     &iter, line, 0);
1990
1991   /* Special-case optimization for completely
1992    * invisible lines; makes it faster to deal
1993    * with sequences of invisible lines.
1994    */
1995   if (totally_invisible_line (layout, line, &iter))
1996     return;
1997
1998   /* Iterate over segments */
1999   layout_byte_offset = 0; /* position in the layout text (includes preedit, does not include invisible text) */
2000   buffer_byte_offset = 0; /* position in the buffer line */
2001   seg = _gtk_text_iter_get_any_segment (&iter);
2002   while (seg != NULL)
2003     {
2004       /* Displayable segments */
2005       if (seg->type == &gtk_text_char_type ||
2006           seg->type == &gtk_text_pixbuf_type ||
2007           seg->type == &gtk_text_child_type)
2008         {
2009           _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
2010                                             &iter, line,
2011                                             buffer_byte_offset);
2012
2013           if (!_gtk_text_btree_char_is_invisible (&iter))
2014             layout_byte_offset += seg->byte_count;
2015
2016           buffer_byte_offset += seg->byte_count;
2017         }
2018
2019       /* Marks */
2020       else if (seg->type == &gtk_text_right_mark_type ||
2021                seg->type == &gtk_text_left_mark_type)
2022         {
2023           gint cursor_offset = 0;
2024
2025           /* At the insertion point, add the preedit string, if any */
2026
2027           if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2028                                               seg->body.mark.obj))
2029             {
2030               display->insert_index = layout_byte_offset;
2031
2032               if (layout->preedit_len > 0)
2033                 {
2034                   layout_byte_offset += layout->preedit_len;
2035                   /* DO NOT increment the buffer byte offset for preedit */
2036                   cursor_offset = layout->preedit_cursor - layout->preedit_len;
2037                 }
2038             }
2039
2040           /* Display visible marks */
2041
2042           if (seg->body.mark.visible)
2043             {
2044               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
2045                                                      GINT_TO_POINTER (layout_byte_offset + cursor_offset));
2046               cursor_segs = g_slist_prepend (cursor_segs, seg);
2047             }
2048         }
2049
2050       /* Toggles */
2051       else if (seg->type == &gtk_text_toggle_on_type ||
2052                seg->type == &gtk_text_toggle_off_type)
2053         {
2054         }
2055
2056       else
2057         g_error ("Unknown segment type: %s", seg->type->name);
2058
2059       seg = seg->next;
2060     }
2061
2062   tmp_list1 = cursor_byte_offsets;
2063   tmp_list2 = cursor_segs;
2064   while (tmp_list1)
2065     {
2066       add_cursor (layout, display, tmp_list2->data,
2067                   GPOINTER_TO_INT (tmp_list1->data));
2068       tmp_list1 = tmp_list1->next;
2069       tmp_list2 = tmp_list2->next;
2070     }
2071   g_slist_free (cursor_byte_offsets);
2072   g_slist_free (cursor_segs);
2073 }
2074
2075 /* Same as _gtk_text_btree_get_tags(), except it returns GPtrArray,
2076  * to be used in gtk_text_layout_get_line_display(). */
2077 static GPtrArray *
2078 get_tags_array_at_iter (GtkTextIter *iter)
2079 {
2080   GtkTextTag **tags;
2081   GPtrArray *array = NULL;
2082   gint n_tags;
2083
2084   tags = _gtk_text_btree_get_tags (iter, &n_tags);
2085
2086   if (n_tags > 0)
2087     {
2088       array = g_ptr_array_sized_new (n_tags);
2089       g_ptr_array_set_size (array, n_tags);
2090       memcpy (array->pdata, tags, n_tags * sizeof (GtkTextTag*));
2091     }
2092
2093   g_free (tags);
2094   return array;
2095 }
2096
2097 /* Add the tag to the array if it's not there already, and remove
2098  * it otherwise. It keeps the array sorted by tags priority. */
2099 static GPtrArray *
2100 tags_array_toggle_tag (GPtrArray  *array,
2101                        GtkTextTag *tag)
2102 {
2103   gint pos;
2104   GtkTextTag **tags;
2105
2106   if (array == NULL)
2107     array = g_ptr_array_new ();
2108
2109   tags = (GtkTextTag**) array->pdata;
2110
2111   for (pos = 0; pos < array->len && tags[pos]->priority < tag->priority; pos++) ;
2112
2113   if (pos < array->len && tags[pos] == tag)
2114     g_ptr_array_remove_index (array, pos);
2115   else
2116     {
2117       g_ptr_array_set_size (array, array->len + 1);
2118       if (pos < array->len - 1)
2119         memmove (array->pdata + pos + 1, array->pdata + pos,
2120                  (array->len - pos - 1) * sizeof (GtkTextTag*));
2121       array->pdata[pos] = tag;
2122     }
2123
2124   return array;
2125 }
2126
2127 GtkTextLineDisplay *
2128 gtk_text_layout_get_line_display (GtkTextLayout *layout,
2129                                   GtkTextLine   *line,
2130                                   gboolean       size_only)
2131 {
2132   GtkTextLayoutPrivate *priv = GTK_TEXT_LAYOUT_GET_PRIVATE (layout);
2133   GtkTextLineDisplay *display;
2134   GtkTextLineSegment *seg;
2135   GtkTextIter iter;
2136   GtkTextAttributes *style;
2137   gchar *text;
2138   PangoAttrList *attrs;
2139   gint text_allocated, layout_byte_offset, buffer_byte_offset;
2140   PangoRectangle extents;
2141   gboolean para_values_set = FALSE;
2142   GSList *cursor_byte_offsets = NULL;
2143   GSList *cursor_segs = NULL;
2144   GSList *tmp_list1, *tmp_list2;
2145   gboolean saw_widget = FALSE;
2146   PangoDirection base_dir;
2147   GPtrArray *tags;
2148   gboolean initial_toggle_segments;
2149   
2150   g_return_val_if_fail (line != NULL, NULL);
2151
2152   if (layout->one_display_cache)
2153     {
2154       if (line == layout->one_display_cache->line &&
2155           (size_only || !layout->one_display_cache->size_only))
2156         {
2157           if (!size_only)
2158             update_text_display_cursors (layout, line, layout->one_display_cache);
2159           return layout->one_display_cache;
2160         }
2161       else
2162         {
2163           GtkTextLineDisplay *tmp_display = layout->one_display_cache;
2164           layout->one_display_cache = NULL;
2165           gtk_text_layout_free_line_display (layout, tmp_display);
2166         }
2167     }
2168
2169   DV (g_print ("creating one line display cache (%s)\n", G_STRLOC));
2170
2171   display = g_new0 (GtkTextLineDisplay, 1);
2172
2173   display->size_only = size_only;
2174   display->line = line;
2175   display->insert_index = -1;
2176
2177   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
2178                                     &iter, line, 0);
2179
2180   /* Special-case optimization for completely
2181    * invisible lines; makes it faster to deal
2182    * with sequences of invisible lines.
2183    */
2184   if (totally_invisible_line (layout, line, &iter))
2185     {
2186       if (display->direction == GTK_TEXT_DIR_RTL)
2187         display->layout = pango_layout_new (layout->rtl_context);
2188       else
2189         display->layout = pango_layout_new (layout->ltr_context);
2190       
2191       return display;
2192     }
2193
2194   /* Find the bidi base direction */
2195   base_dir = line->dir_propagated_forward;
2196   if (base_dir == PANGO_DIRECTION_NEUTRAL)
2197     base_dir = line->dir_propagated_back;
2198
2199   if (line == priv->cursor_line &&
2200       line->dir_strong == PANGO_DIRECTION_NEUTRAL)
2201     {
2202       base_dir = (layout->keyboard_direction == GTK_TEXT_DIR_LTR) ?
2203          PANGO_DIRECTION_LTR : PANGO_DIRECTION_RTL;
2204     }
2205   
2206   /* Allocate space for flat text for buffer
2207    */
2208   text_allocated = _gtk_text_line_byte_count (line);
2209   text = g_malloc (text_allocated);
2210
2211   attrs = pango_attr_list_new ();
2212
2213   /* Iterate over segments, creating display chunks for them, and updating the tags array. */
2214   layout_byte_offset = 0; /* current length of layout text (includes preedit, does not include invisible text) */
2215   buffer_byte_offset = 0; /* position in the buffer line */
2216   seg = _gtk_text_iter_get_any_segment (&iter);
2217   tags = get_tags_array_at_iter (&iter);
2218   initial_toggle_segments = TRUE;
2219   while (seg != NULL)
2220     {
2221       /* Displayable segments */
2222       if (seg->type == &gtk_text_char_type ||
2223           seg->type == &gtk_text_pixbuf_type ||
2224           seg->type == &gtk_text_child_type)
2225         {
2226           style = get_style (layout, tags);
2227           initial_toggle_segments = FALSE;
2228
2229           /* We have to delay setting the paragraph values until we
2230            * hit the first pixbuf or text segment because toggles at
2231            * the beginning of the paragraph should affect the
2232            * paragraph-global values
2233            */
2234           if (!para_values_set)
2235             {
2236               set_para_values (layout, base_dir, style, display);
2237               para_values_set = TRUE;
2238             }
2239
2240           /* First see if the chunk is invisible, and ignore it if so. Tk
2241            * looked at tabs, wrap mode, etc. before doing this, but
2242            * that made no sense to me, so I am just skipping the
2243            * invisible chunks
2244            */
2245           if (!style->invisible)
2246             {
2247               if (seg->type == &gtk_text_char_type)
2248                 {
2249                   /* We don't want to split segments because of marks,
2250                    * so we scan forward for more segments only
2251                    * separated from us by marks. In theory, we should
2252                    * also merge segments with identical styles, even
2253                    * if there are toggles in-between
2254                    */
2255
2256                   gint bytes = 0;
2257                   GtkTextLineSegment *prev_seg = NULL;
2258   
2259                   while (seg)
2260                     {
2261                       if (seg->type == &gtk_text_char_type)
2262                         {
2263                           memcpy (text + layout_byte_offset, seg->body.chars, seg->byte_count);
2264                           layout_byte_offset += seg->byte_count;
2265                           buffer_byte_offset += seg->byte_count;
2266                           bytes += seg->byte_count;
2267                         }
2268                       else if (seg->type == &gtk_text_right_mark_type ||
2269                                seg->type == &gtk_text_left_mark_type)
2270                         {
2271                           /* If we have preedit string, break out of this loop - we'll almost
2272                            * certainly have different attributes on the preedit string
2273                            */
2274
2275                           if (layout->preedit_len > 0 &&
2276                               _gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2277                                                              seg->body.mark.obj))
2278                             break;
2279
2280                           if (seg->body.mark.visible)
2281                             {
2282                               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets, GINT_TO_POINTER (layout_byte_offset));
2283                               cursor_segs = g_slist_prepend (cursor_segs, seg);
2284                               if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2285                                                                   seg->body.mark.obj))
2286                                 display->insert_index = layout_byte_offset;
2287                             }
2288                         }
2289                       else
2290                         break;
2291
2292                       prev_seg = seg;
2293                       seg = seg->next;
2294                     }
2295
2296                   seg = prev_seg; /* Back up one */
2297                   add_generic_attrs (layout, &style->appearance,
2298                                      bytes,
2299                                      attrs, layout_byte_offset - bytes,
2300                                      size_only, TRUE);
2301                   add_text_attrs (layout, style, bytes, attrs,
2302                                   layout_byte_offset - bytes, size_only);
2303                 }
2304               else if (seg->type == &gtk_text_pixbuf_type)
2305                 {
2306                   add_generic_attrs (layout,
2307                                      &style->appearance,
2308                                      seg->byte_count,
2309                                      attrs, layout_byte_offset,
2310                                      size_only, FALSE);
2311                   add_pixbuf_attrs (layout, display, style,
2312                                     seg, attrs, layout_byte_offset);
2313                   memcpy (text + layout_byte_offset, gtk_text_unknown_char_utf8,
2314                           seg->byte_count);
2315                   layout_byte_offset += seg->byte_count;
2316                   buffer_byte_offset += seg->byte_count;
2317                 }
2318               else if (seg->type == &gtk_text_child_type)
2319                 {
2320                   saw_widget = TRUE;
2321                   
2322                   add_generic_attrs (layout, &style->appearance,
2323                                      seg->byte_count,
2324                                      attrs, layout_byte_offset,
2325                                      size_only, FALSE);
2326                   add_child_attrs (layout, display, style,
2327                                    seg, attrs, layout_byte_offset);
2328                   memcpy (text + layout_byte_offset, gtk_text_unknown_char_utf8,
2329                           seg->byte_count);
2330                   layout_byte_offset += seg->byte_count;
2331                   buffer_byte_offset += seg->byte_count;
2332                 }
2333               else
2334                 {
2335                   /* We don't know this segment type */
2336                   g_assert_not_reached ();
2337                 }
2338               
2339             } /* if (segment was visible) */
2340           else
2341             {
2342               /* Invisible segment */
2343               buffer_byte_offset += seg->byte_count;
2344             }
2345
2346           release_style (layout, style);
2347         }
2348
2349       /* Toggles */
2350       else if (seg->type == &gtk_text_toggle_on_type ||
2351                seg->type == &gtk_text_toggle_off_type)
2352         {
2353           /* Style may have changed, drop our
2354              current cached style */
2355           invalidate_cached_style (layout);
2356           /* Add the tag only after we have seen some non-toggle non-mark segment,
2357            * otherwise the tag is already accounted for by _gtk_text_btree_get_tags(). */
2358           if (!initial_toggle_segments)
2359             tags = tags_array_toggle_tag (tags, seg->body.toggle.info->tag);
2360         }
2361
2362       /* Marks */
2363       else if (seg->type == &gtk_text_right_mark_type ||
2364                seg->type == &gtk_text_left_mark_type)
2365         {
2366           gint cursor_offset = 0;
2367           
2368           /* At the insertion point, add the preedit string, if any */
2369           
2370           if (_gtk_text_btree_mark_is_insert (_gtk_text_buffer_get_btree (layout->buffer),
2371                                              seg->body.mark.obj))
2372             {
2373               display->insert_index = layout_byte_offset;
2374               
2375               if (layout->preedit_len > 0)
2376                 {
2377                   text_allocated += layout->preedit_len;
2378                   text = g_realloc (text, text_allocated);
2379
2380                   style = get_style (layout, tags);
2381                   add_preedit_attrs (layout, style, attrs, layout_byte_offset, size_only);
2382                   release_style (layout, style);
2383                   
2384                   memcpy (text + layout_byte_offset, layout->preedit_string, layout->preedit_len);
2385                   layout_byte_offset += layout->preedit_len;
2386                   /* DO NOT increment the buffer byte offset for preedit */
2387                   
2388                   cursor_offset = layout->preedit_cursor - layout->preedit_len;
2389                 }
2390             }
2391           
2392
2393           /* Display visible marks */
2394
2395           if (seg->body.mark.visible)
2396             {
2397               cursor_byte_offsets = g_slist_prepend (cursor_byte_offsets,
2398                                                      GINT_TO_POINTER (layout_byte_offset + cursor_offset));
2399               cursor_segs = g_slist_prepend (cursor_segs, seg);
2400             }
2401         }
2402
2403       else
2404         g_error ("Unknown segment type: %s", seg->type->name);
2405
2406       seg = seg->next;
2407     }
2408   
2409   if (!para_values_set)
2410     {
2411       style = get_style (layout, tags);
2412       set_para_values (layout, base_dir, style, display);
2413       release_style (layout, style);
2414     }
2415   
2416   /* Pango doesn't want the trailing paragraph delimiters */
2417
2418   {
2419     /* Only one character has type G_UNICODE_PARAGRAPH_SEPARATOR in
2420      * Unicode 3.0; update this if that changes.
2421      */
2422 #define PARAGRAPH_SEPARATOR 0x2029
2423     gunichar ch = 0;
2424
2425     if (layout_byte_offset > 0)
2426       {
2427         const char *prev = g_utf8_prev_char (text + layout_byte_offset);
2428         ch = g_utf8_get_char (prev);
2429         if (ch == PARAGRAPH_SEPARATOR || ch == '\r' || ch == '\n')
2430           layout_byte_offset = prev - text; /* chop off */
2431
2432         if (ch == '\n' && layout_byte_offset > 0)
2433           {
2434             /* Possibly chop a CR as well */
2435             prev = g_utf8_prev_char (text + layout_byte_offset);
2436             if (*prev == '\r')
2437               --layout_byte_offset;
2438           }
2439       }
2440   }
2441   
2442   pango_layout_set_text (display->layout, text, layout_byte_offset);
2443   pango_layout_set_attributes (display->layout, attrs);
2444
2445   tmp_list1 = cursor_byte_offsets;
2446   tmp_list2 = cursor_segs;
2447   while (tmp_list1)
2448     {
2449       add_cursor (layout, display, tmp_list2->data,
2450                   GPOINTER_TO_INT (tmp_list1->data));
2451       tmp_list1 = tmp_list1->next;
2452       tmp_list2 = tmp_list2->next;
2453     }
2454   g_slist_free (cursor_byte_offsets);
2455   g_slist_free (cursor_segs);
2456
2457   pango_layout_get_extents (display->layout, NULL, &extents);
2458
2459   display->width = PIXEL_BOUND (extents.width) + display->left_margin + display->right_margin;
2460   display->height += PANGO_PIXELS (extents.height);
2461
2462   /* If we aren't wrapping, we need to do the alignment of each
2463    * paragraph ourselves.
2464    */
2465   if (pango_layout_get_width (display->layout) < 0)
2466     {
2467       gint excess = display->total_width - display->width;
2468
2469       switch (pango_layout_get_alignment (display->layout))
2470         {
2471         case PANGO_ALIGN_LEFT:
2472           break;
2473         case PANGO_ALIGN_CENTER:
2474           display->x_offset += excess / 2;
2475           break;
2476         case PANGO_ALIGN_RIGHT:
2477           display->x_offset += excess;
2478           break;
2479         }
2480     }
2481   
2482   /* Free this if we aren't in a loop */
2483   if (layout->wrap_loop_count == 0)
2484     invalidate_cached_style (layout);
2485
2486   g_free (text);
2487   pango_attr_list_unref (attrs);
2488   if (tags != NULL)
2489     g_ptr_array_free (tags, TRUE);
2490
2491   layout->one_display_cache = display;
2492
2493   if (saw_widget)
2494     allocate_child_widgets (layout, display);
2495   
2496   return display;
2497 }
2498
2499 void
2500 gtk_text_layout_free_line_display (GtkTextLayout      *layout,
2501                                    GtkTextLineDisplay *display)
2502 {
2503   if (display != layout->one_display_cache)
2504     {
2505       if (display->layout)
2506         g_object_unref (display->layout);
2507
2508       if (display->cursors)
2509         {
2510           g_slist_foreach (display->cursors, (GFunc)g_free, NULL);
2511           g_slist_free (display->cursors);
2512         }
2513       g_slist_free (display->shaped_objects);
2514       
2515       if (display->pg_bg_color)
2516         gdk_color_free (display->pg_bg_color);
2517
2518       g_free (display);
2519     }
2520 }
2521
2522 /* Functions to convert iter <=> index for the line of a GtkTextLineDisplay
2523  * taking into account the preedit string and invisible text if necessary.
2524  */
2525 static gint
2526 line_display_iter_to_index (GtkTextLayout      *layout,
2527                             GtkTextLineDisplay *display,
2528                             const GtkTextIter  *iter)
2529 {
2530   gint index;
2531
2532   g_return_val_if_fail (_gtk_text_iter_get_text_line (iter) == display->line, 0);
2533
2534   index = gtk_text_iter_get_visible_line_index (iter);
2535   
2536   if (layout->preedit_len > 0 && display->insert_index >= 0)
2537     {
2538       if (index >= display->insert_index)
2539         index += layout->preedit_len;
2540     }
2541
2542   return index;
2543 }
2544
2545 static void
2546 line_display_index_to_iter (GtkTextLayout      *layout,
2547                             GtkTextLineDisplay *display,
2548                             GtkTextIter        *iter,
2549                             gint                index,
2550                             gint                trailing)
2551 {
2552   g_return_if_fail (!_gtk_text_line_is_last (display->line,
2553                                              _gtk_text_buffer_get_btree (layout->buffer)));
2554   
2555   if (layout->preedit_len > 0 && display->insert_index >= 0)
2556     {
2557       if (index >= display->insert_index + layout->preedit_len)
2558         index -= layout->preedit_len;
2559       else if (index > display->insert_index)
2560         {
2561           index = display->insert_index;
2562           trailing = 0;
2563         }
2564     }
2565
2566   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
2567                                     iter, display->line, 0);
2568
2569   gtk_text_iter_set_visible_line_index (iter, index);
2570   
2571   if (_gtk_text_iter_get_text_line (iter) != display->line)
2572     {
2573       /* Clamp to end of line - really this clamping should have been done
2574        * before here, maybe in Pango, this is a broken band-aid I think
2575        */
2576       _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
2577                                         iter, display->line, 0);
2578
2579       if (!gtk_text_iter_ends_line (iter))
2580         gtk_text_iter_forward_to_line_end (iter);
2581     }
2582   
2583   gtk_text_iter_forward_chars (iter, trailing);
2584 }
2585
2586 static void
2587 get_line_at_y (GtkTextLayout *layout,
2588                gint           y,
2589                GtkTextLine  **line,
2590                gint          *line_top)
2591 {
2592   if (y < 0)
2593     y = 0;
2594   if (y > layout->height)
2595     y = layout->height;
2596
2597   *line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
2598                                          layout, y, line_top);
2599   if (*line == NULL)
2600     {
2601       *line = _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
2602       
2603       if (line_top)
2604         *line_top =
2605           _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2606                                         *line, layout);
2607     }
2608 }
2609
2610 /**
2611  * gtk_text_layout_get_line_at_y:
2612  * @layout: a #GtkLayout
2613  * @target_iter: the iterator in which the result is stored
2614  * @y: the y positition
2615  * @line_top: location to store the y coordinate of the
2616  *            top of the line. (Can by %NULL)
2617  *
2618  * Get the iter at the beginning of the line which is displayed
2619  * at the given y.
2620  */
2621 void
2622 gtk_text_layout_get_line_at_y (GtkTextLayout *layout,
2623                                GtkTextIter   *target_iter,
2624                                gint           y,
2625                                gint          *line_top)
2626 {
2627   GtkTextLine *line;
2628
2629   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2630   g_return_if_fail (target_iter != NULL);
2631
2632   get_line_at_y (layout, y, &line, line_top);
2633   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
2634                                    target_iter, line, 0);
2635 }
2636
2637 void
2638 gtk_text_layout_get_iter_at_pixel (GtkTextLayout *layout,
2639                                    GtkTextIter   *target_iter,
2640                                    gint           x, 
2641                                    gint           y)
2642 {
2643   gint trailing;
2644
2645   gtk_text_layout_get_iter_at_position (layout, target_iter, &trailing, x, y);
2646
2647   gtk_text_iter_forward_chars (target_iter, trailing);  
2648 }
2649
2650 void gtk_text_layout_get_iter_at_position (GtkTextLayout     *layout,
2651                                            GtkTextIter       *target_iter,
2652                                            gint              *trailing,
2653                                            gint               x,
2654                                            gint               y)
2655 {
2656   GtkTextLine *line;
2657   gint byte_index;
2658   gint line_top;
2659   GtkTextLineDisplay *display;
2660
2661   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2662   g_return_if_fail (target_iter != NULL);
2663
2664   get_line_at_y (layout, y, &line, &line_top);
2665
2666   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2667
2668   x -= display->x_offset;
2669   y -= line_top + display->top_margin;
2670
2671   /* If we are below the layout, position the cursor at the last character
2672    * of the line.
2673    */
2674   if (y > display->height - display->top_margin - display->bottom_margin)
2675     {
2676       byte_index = _gtk_text_line_byte_count (line);
2677       if (trailing)
2678         *trailing = 0;
2679     }
2680   else
2681     {
2682        /* Ignore the "outside" return value from pango. Pango is doing
2683         * the right thing even if we are outside the layout in the
2684         * x-direction.
2685         */
2686       pango_layout_xy_to_index (display->layout, x * PANGO_SCALE, y * PANGO_SCALE,
2687                                 &byte_index, trailing);
2688     }
2689
2690   line_display_index_to_iter (layout, display, target_iter, byte_index, 0);
2691
2692   gtk_text_layout_free_line_display (layout, display);
2693 }
2694
2695
2696 /**
2697  * gtk_text_layout_get_cursor_locations:
2698  * @layout: a #GtkTextLayout
2699  * @iter: a #GtkTextIter
2700  * @strong_pos: (allow-none): location to store the strong cursor position (may be %NULL)
2701  * @weak_pos: (allow-none): location to store the weak cursor position (may be %NULL)
2702  *
2703  * Given an iterator within a text layout, determine the positions of the
2704  * strong and weak cursors if the insertion point is at that
2705  * iterator. The position of each cursor is stored as a zero-width
2706  * rectangle. The strong cursor location is the location where
2707  * characters of the directionality equal to the base direction of the
2708  * paragraph are inserted.  The weak cursor location is the location
2709  * where characters of the directionality opposite to the base
2710  * direction of the paragraph are inserted.
2711  **/
2712 void
2713 gtk_text_layout_get_cursor_locations (GtkTextLayout  *layout,
2714                                       GtkTextIter    *iter,
2715                                       GdkRectangle   *strong_pos,
2716                                       GdkRectangle   *weak_pos)
2717 {
2718   GtkTextLine *line;
2719   GtkTextLineDisplay *display;
2720   gint line_top;
2721   gint index;
2722   GtkTextIter insert_iter;
2723
2724   PangoRectangle pango_strong_pos;
2725   PangoRectangle pango_weak_pos;
2726
2727   g_return_if_fail (layout != NULL);
2728   g_return_if_fail (iter != NULL);
2729
2730   line = _gtk_text_iter_get_text_line (iter);
2731   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2732   index = line_display_iter_to_index (layout, display, iter);
2733   
2734   line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2735                                            line, layout);
2736   
2737   gtk_text_buffer_get_iter_at_mark (layout->buffer, &insert_iter,
2738                                     gtk_text_buffer_get_insert (layout->buffer));
2739
2740   if (gtk_text_iter_equal (iter, &insert_iter))
2741     index += layout->preedit_cursor - layout->preedit_len;
2742   
2743   pango_layout_get_cursor_pos (display->layout, index,
2744                                strong_pos ? &pango_strong_pos : NULL,
2745                                weak_pos ? &pango_weak_pos : NULL);
2746
2747   if (strong_pos)
2748     {
2749       strong_pos->x = display->x_offset + pango_strong_pos.x / PANGO_SCALE;
2750       strong_pos->y = line_top + display->top_margin + pango_strong_pos.y / PANGO_SCALE;
2751       strong_pos->width = 0;
2752       strong_pos->height = pango_strong_pos.height / PANGO_SCALE;
2753     }
2754
2755   if (weak_pos)
2756     {
2757       weak_pos->x = display->x_offset + pango_weak_pos.x / PANGO_SCALE;
2758       weak_pos->y = line_top + display->top_margin + pango_weak_pos.y / PANGO_SCALE;
2759       weak_pos->width = 0;
2760       weak_pos->height = pango_weak_pos.height / PANGO_SCALE;
2761     }
2762
2763   gtk_text_layout_free_line_display (layout, display);
2764 }
2765
2766 /**
2767  * _gtk_text_layout_get_block_cursor:
2768  * @layout: a #GtkTextLayout
2769  * @pos: a #GdkRectangle to store block cursor position
2770  *
2771  * If layout is to display a block cursor, calculates its position
2772  * and returns %TRUE. Otherwise it returns %FALSE. In case when
2773  * cursor is visible, it simply returns the position stored in
2774  * the line display, otherwise it has to compute the position
2775  * (see get_block_cursor()).
2776  **/
2777 gboolean
2778 _gtk_text_layout_get_block_cursor (GtkTextLayout *layout,
2779                                    GdkRectangle  *pos)
2780 {
2781   GtkTextLine *line;
2782   GtkTextLineDisplay *display;
2783   GtkTextIter iter;
2784   GdkRectangle rect;
2785   gboolean block = FALSE;
2786
2787   g_return_val_if_fail (layout != NULL, FALSE);
2788
2789   gtk_text_buffer_get_iter_at_mark (layout->buffer, &iter,
2790                                     gtk_text_buffer_get_insert (layout->buffer));
2791   line = _gtk_text_iter_get_text_line (&iter);
2792   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2793
2794   if (display->has_block_cursor)
2795     {
2796       block = TRUE;
2797       rect = display->block_cursor;
2798     }
2799   else
2800     {
2801       gint index = display->insert_index;
2802
2803       if (index < 0)
2804         index = gtk_text_iter_get_line_index (&iter);
2805
2806       if (get_block_cursor (layout, display, &iter, index, &rect, NULL))
2807         block = TRUE;
2808     }
2809
2810   if (block && pos)
2811     {
2812       gint line_top;
2813
2814       line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2815                                                 line, layout);
2816
2817       *pos = rect;
2818       pos->x += display->x_offset;
2819       pos->y += line_top + display->top_margin;
2820     }
2821
2822   gtk_text_layout_free_line_display (layout, display);
2823   return block;
2824 }
2825
2826 /**
2827  * gtk_text_layout_get_line_yrange:
2828  * @layout: a #GtkTextLayout
2829  * @iter:   a #GtkTextIter
2830  * @y:      location to store the top of the paragraph in pixels,
2831  *          or %NULL.
2832  * @height  location to store the height of the paragraph in pixels,
2833  *          or %NULL.
2834  *
2835  * Find the range of y coordinates for the paragraph containing
2836  * the given iter.
2837  **/
2838 void
2839 gtk_text_layout_get_line_yrange (GtkTextLayout     *layout,
2840                                  const GtkTextIter *iter,
2841                                  gint              *y,
2842                                  gint              *height)
2843 {
2844   GtkTextLine *line;
2845
2846   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2847   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2848
2849   line = _gtk_text_iter_get_text_line (iter);
2850
2851   if (y)
2852     *y = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2853                                        line, layout);
2854   if (height)
2855     {
2856       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
2857       if (line_data)
2858         *height = line_data->height;
2859       else
2860         *height = 0;
2861     }
2862 }
2863
2864 /**
2865  * _gtk_text_layout_get_line_xrange:
2866  * @layout: a #GtkTextLayout
2867  * @iter:   a #GtkTextIter
2868  * @x:      location to store the top of the paragraph in pixels,
2869  *          or %NULL.
2870  * @width  location to store the height of the paragraph in pixels,
2871  *          or %NULL.
2872  *
2873  * Find the range of X coordinates for the paragraph containing
2874  * the given iter. Private for 2.0 due to API freeze, could
2875  * be made public for 2.2.
2876  **/
2877 void
2878 _gtk_text_layout_get_line_xrange (GtkTextLayout     *layout,
2879                                   const GtkTextIter *iter,
2880                                   gint              *x,
2881                                   gint              *width)
2882 {
2883   GtkTextLine *line;
2884
2885   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2886   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2887
2888   line = _gtk_text_iter_get_text_line (iter);
2889
2890   if (x)
2891     *x = 0; /* FIXME This is wrong; should represent the first available cursor position */
2892   
2893   if (width)
2894     {
2895       GtkTextLineData *line_data = _gtk_text_line_get_data (line, layout);
2896       if (line_data)
2897         *width = line_data->width;
2898       else
2899         *width = 0;
2900     }
2901 }
2902
2903 void
2904 gtk_text_layout_get_iter_location (GtkTextLayout     *layout,
2905                                    const GtkTextIter *iter,
2906                                    GdkRectangle      *rect)
2907 {
2908   PangoRectangle pango_rect;
2909   GtkTextLine *line;
2910   GtkTextBTree *tree;
2911   GtkTextLineDisplay *display;
2912   gint byte_index;
2913   gint x_offset;
2914   
2915   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
2916   g_return_if_fail (_gtk_text_iter_get_btree (iter) == _gtk_text_buffer_get_btree (layout->buffer));
2917   g_return_if_fail (rect != NULL);
2918
2919   tree = _gtk_text_iter_get_btree (iter);
2920   line = _gtk_text_iter_get_text_line (iter);
2921
2922   display = gtk_text_layout_get_line_display (layout, line, FALSE);
2923
2924   rect->y = _gtk_text_btree_find_line_top (tree, line, layout);
2925
2926   x_offset = display->x_offset * PANGO_SCALE;
2927
2928   byte_index = gtk_text_iter_get_line_index (iter);
2929   
2930   pango_layout_index_to_pos (display->layout, byte_index, &pango_rect);
2931   
2932   rect->x = PANGO_PIXELS (x_offset + pango_rect.x);
2933   rect->y += PANGO_PIXELS (pango_rect.y) + display->top_margin;
2934   rect->width = PANGO_PIXELS (pango_rect.width);
2935   rect->height = PANGO_PIXELS (pango_rect.height);
2936
2937   gtk_text_layout_free_line_display (layout, display);
2938 }
2939
2940 /* FFIXX */
2941
2942 /* Find the iter for the logical beginning of the first display line whose
2943  * top y is >= y. If none exists, move the iter to the logical beginning
2944  * of the last line in the buffer.
2945  */
2946 static void
2947 find_display_line_below (GtkTextLayout *layout,
2948                          GtkTextIter   *iter,
2949                          gint           y)
2950 {
2951   GtkTextLine *line, *next;
2952   GtkTextLine *found_line = NULL;
2953   gint line_top;
2954   gint found_byte = 0;
2955
2956   line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer),
2957                                         layout, y, &line_top);
2958   if (!line)
2959     {
2960       line =
2961         _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
2962
2963       line_top =
2964         _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer),
2965                                       line, layout);
2966     }
2967
2968   while (line && !found_line)
2969     {
2970       GtkTextLineDisplay *display = gtk_text_layout_get_line_display (layout, line, FALSE);
2971       PangoLayoutIter *layout_iter;
2972
2973       layout_iter = pango_layout_get_iter (display->layout);
2974
2975       line_top += display->top_margin;
2976
2977       do
2978         {
2979           gint first_y, last_y;
2980           PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
2981
2982           found_byte = layout_line->start_index;
2983           
2984           if (line_top >= y)
2985             {
2986               found_line = line;
2987               break;
2988             }
2989
2990           pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
2991           line_top += (last_y - first_y) / PANGO_SCALE;
2992         }
2993       while (pango_layout_iter_next_line (layout_iter));
2994
2995       pango_layout_iter_free (layout_iter);
2996       
2997       line_top += display->bottom_margin;
2998       gtk_text_layout_free_line_display (layout, display);
2999
3000       next = _gtk_text_line_next_excluding_last (line);
3001       if (!next)
3002         found_line = line;
3003
3004       line = next;
3005     }
3006
3007   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3008                                    iter, found_line, found_byte);
3009 }
3010
3011 /* Find the iter for the logical beginning of the last display line whose
3012  * top y is >= y. If none exists, move the iter to the logical beginning
3013  * of the first line in the buffer.
3014  */
3015 static void
3016 find_display_line_above (GtkTextLayout *layout,
3017                          GtkTextIter   *iter,
3018                          gint           y)
3019 {
3020   GtkTextLine *line;
3021   GtkTextLine *found_line = NULL;
3022   gint line_top;
3023   gint found_byte = 0;
3024
3025   line = _gtk_text_btree_find_line_by_y (_gtk_text_buffer_get_btree (layout->buffer), layout, y, &line_top);
3026   if (!line)
3027     {
3028       line = _gtk_text_btree_get_end_iter_line (_gtk_text_buffer_get_btree (layout->buffer));
3029       
3030       line_top = _gtk_text_btree_find_line_top (_gtk_text_buffer_get_btree (layout->buffer), line, layout);
3031     }
3032
3033   while (line && !found_line)
3034     {
3035       GtkTextLineDisplay *display = gtk_text_layout_get_line_display (layout, line, FALSE);
3036       PangoRectangle logical_rect;
3037       PangoLayoutIter *layout_iter;
3038       gint tmp_top;
3039
3040       layout_iter = pango_layout_get_iter (display->layout);
3041       
3042       line_top -= display->top_margin + display->bottom_margin;
3043       pango_layout_iter_get_layout_extents (layout_iter, NULL, &logical_rect);
3044       line_top -= logical_rect.height / PANGO_SCALE;
3045
3046       tmp_top = line_top + display->top_margin;
3047
3048       do
3049         {
3050           gint first_y, last_y;
3051           PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
3052
3053           found_byte = layout_line->start_index;
3054
3055           pango_layout_iter_get_line_yrange (layout_iter, &first_y, &last_y);
3056           
3057           tmp_top -= (last_y - first_y) / PANGO_SCALE;
3058
3059           if (tmp_top < y)
3060             {
3061               found_line = line;
3062               pango_layout_iter_free (layout_iter);
3063               goto done;
3064             }
3065         }
3066       while (pango_layout_iter_next_line (layout_iter));
3067
3068       pango_layout_iter_free (layout_iter);
3069       
3070       gtk_text_layout_free_line_display (layout, display);
3071
3072       line = _gtk_text_line_previous (line);
3073     }
3074
3075  done:
3076   
3077   if (found_line)
3078     _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3079                                      iter, found_line, found_byte);
3080   else
3081     gtk_text_buffer_get_iter_at_offset (layout->buffer, iter, 0);
3082 }
3083
3084 /**
3085  * gtk_text_layout_clamp_iter_to_vrange:
3086  * @layout: a #GtkTextLayout
3087  * @iter:   a #GtkTextIter
3088  * @top:    the top of the range
3089  * @bottom: the bottom the range
3090  *
3091  * If the iterator is not fully in the range @top <= y < @bottom,
3092  * then, if possible, move it the minimum distance so that the
3093  * iterator in this range.
3094  *
3095  * Returns: %TRUE if the iterator was moved, otherwise %FALSE.
3096  **/
3097 gboolean
3098 gtk_text_layout_clamp_iter_to_vrange (GtkTextLayout *layout,
3099                                       GtkTextIter   *iter,
3100                                       gint           top,
3101                                       gint           bottom)
3102 {
3103   GdkRectangle iter_rect;
3104
3105   gtk_text_layout_get_iter_location (layout, iter, &iter_rect);
3106
3107   /* If the iter is at least partially above the range, put the iter
3108    * at the first fully visible line after the range.
3109    */
3110   if (iter_rect.y < top)
3111     {
3112       find_display_line_below (layout, iter, top);
3113
3114       return TRUE;
3115     }
3116   /* Otherwise, if the iter is at least partially below the screen, put the
3117    * iter on the last logical position of the last completely visible
3118    * line on screen
3119    */
3120   else if (iter_rect.y + iter_rect.height > bottom)
3121     {
3122       find_display_line_above (layout, iter, bottom);
3123
3124       return TRUE;
3125     }
3126   else
3127     return FALSE;
3128 }
3129
3130 /**
3131  * gtk_text_layout_move_iter_to_previous_line:
3132  * @layout: a #GtkLayout
3133  * @iter:   a #GtkTextIter
3134  *
3135  * Move the iterator to the beginning of the previous line. The lines
3136  * of a wrapped paragraph are treated as distinct for this operation.
3137  **/
3138 gboolean
3139 gtk_text_layout_move_iter_to_previous_line (GtkTextLayout *layout,
3140                                             GtkTextIter   *iter)
3141 {
3142   GtkTextLine *line;
3143   GtkTextLineDisplay *display;
3144   gint line_byte;
3145   GSList *tmp_list;
3146   PangoLayoutLine *layout_line;
3147   GtkTextIter orig;
3148   gboolean update_byte = FALSE;
3149   
3150   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3151   g_return_val_if_fail (iter != NULL, FALSE);
3152
3153   orig = *iter;
3154
3155
3156   line = _gtk_text_iter_get_text_line (iter);
3157   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3158   line_byte = line_display_iter_to_index (layout, display, iter);
3159
3160   /* If display->height == 0 then the line is invisible, so don't
3161    * move onto it.
3162    */
3163   while (display->height == 0)
3164     {
3165       GtkTextLine *prev_line;
3166
3167       prev_line = _gtk_text_line_previous (line);
3168
3169       if (prev_line == NULL)
3170         {
3171           line_display_index_to_iter (layout, display, iter, 0, 0);
3172           goto out;
3173         }
3174
3175       gtk_text_layout_free_line_display (layout, display);
3176
3177       line = prev_line;
3178       display = gtk_text_layout_get_line_display (layout, prev_line, FALSE);
3179       update_byte = TRUE;
3180     }
3181   
3182   tmp_list = pango_layout_get_lines_readonly (display->layout);
3183   layout_line = tmp_list->data;
3184
3185   if (update_byte)
3186     {
3187       line_byte = layout_line->start_index + layout_line->length;
3188     }
3189
3190   if (line_byte < layout_line->length || !tmp_list->next) /* first line of paragraph */
3191     {
3192       GtkTextLine *prev_line;
3193
3194       prev_line = _gtk_text_line_previous (line);
3195
3196       /* first line of the whole buffer, do not move the iter and return FALSE */
3197       if (prev_line == NULL)
3198         goto out;
3199
3200       while (prev_line)
3201         {
3202           gtk_text_layout_free_line_display (layout, display);
3203
3204           display = gtk_text_layout_get_line_display (layout, prev_line, FALSE);
3205
3206           if (display->height > 0)
3207             {
3208               tmp_list = g_slist_last (pango_layout_get_lines_readonly (display->layout));
3209               layout_line = tmp_list->data;
3210
3211               line_display_index_to_iter (layout, display, iter,
3212                                           layout_line->start_index + layout_line->length, 0);
3213               break;
3214             }
3215
3216           prev_line = _gtk_text_line_previous (prev_line);
3217         }
3218     }
3219   else
3220     {
3221       gint prev_offset = layout_line->start_index;
3222
3223       tmp_list = tmp_list->next;
3224       while (tmp_list)
3225         {
3226           layout_line = tmp_list->data;
3227
3228           if (line_byte < layout_line->start_index + layout_line->length ||
3229               !tmp_list->next)
3230             {
3231               line_display_index_to_iter (layout, display, iter, prev_offset, 0);
3232               break;
3233             }
3234
3235           prev_offset = layout_line->start_index;
3236           tmp_list = tmp_list->next;
3237         }
3238     }
3239
3240  out:
3241   
3242   gtk_text_layout_free_line_display (layout, display);
3243
3244   return
3245     !gtk_text_iter_equal (iter, &orig) &&
3246     !gtk_text_iter_is_end (iter);
3247 }
3248
3249 /**
3250  * gtk_text_layout_move_iter_to_next_line:
3251  * @layout: a #GtkLayout
3252  * @iter:   a #GtkTextIter
3253  *
3254  * Move the iterator to the beginning of the next line. The
3255  * lines of a wrapped paragraph are treated as distinct for
3256  * this operation.
3257  **/
3258 gboolean
3259 gtk_text_layout_move_iter_to_next_line (GtkTextLayout *layout,
3260                                         GtkTextIter   *iter)
3261 {
3262   GtkTextLine *line;
3263   GtkTextLineDisplay *display;
3264   gint line_byte;
3265   GtkTextIter orig;
3266   gboolean found = FALSE;
3267   gboolean found_after = FALSE;
3268   gboolean first = TRUE;
3269
3270   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3271   g_return_val_if_fail (iter != NULL, FALSE);
3272
3273   orig = *iter;
3274   
3275   line = _gtk_text_iter_get_text_line (iter);
3276
3277   while (line && !found_after)
3278     {
3279       GSList *tmp_list;
3280
3281       display = gtk_text_layout_get_line_display (layout, line, FALSE);
3282
3283       if (display->height == 0)
3284         goto next;
3285       
3286       if (first)
3287         {
3288           line_byte = line_display_iter_to_index (layout, display, iter);
3289           first = FALSE;
3290         }
3291       else
3292         line_byte = 0;
3293         
3294       tmp_list = pango_layout_get_lines_readonly (display->layout);
3295       while (tmp_list && !found_after)
3296         {
3297           PangoLayoutLine *layout_line = tmp_list->data;
3298
3299           if (found)
3300             {
3301               line_display_index_to_iter (layout, display, iter,
3302                                           layout_line->start_index, 0);
3303               found_after = TRUE;
3304             }
3305           else if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
3306             found = TRUE;
3307           
3308           tmp_list = tmp_list->next;
3309         }
3310
3311     next:
3312       
3313       gtk_text_layout_free_line_display (layout, display);
3314
3315       line = _gtk_text_line_next_excluding_last (line);
3316     }
3317
3318   if (!found_after)
3319     gtk_text_buffer_get_end_iter (layout->buffer, iter);
3320   
3321   return
3322     !gtk_text_iter_equal (iter, &orig) &&
3323     !gtk_text_iter_is_end (iter);
3324 }
3325
3326 /**
3327  * gtk_text_layout_move_iter_to_line_end:
3328  * @layout: a #GtkTextLayout
3329  * @direction: if negative, move to beginning of line, otherwise
3330                move to end of line.
3331  *
3332  * Move to the beginning or end of a display line.
3333  **/
3334 gboolean
3335 gtk_text_layout_move_iter_to_line_end (GtkTextLayout *layout,
3336                                        GtkTextIter   *iter,
3337                                        gint           direction)
3338 {
3339   GtkTextLine *line;
3340   GtkTextLineDisplay *display;
3341   gint line_byte;
3342   GSList *tmp_list;
3343   GtkTextIter orig;
3344   
3345   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3346   g_return_val_if_fail (iter != NULL, FALSE);
3347
3348   orig = *iter;
3349   
3350   line = _gtk_text_iter_get_text_line (iter);
3351   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3352   line_byte = line_display_iter_to_index (layout, display, iter);
3353
3354   tmp_list = pango_layout_get_lines_readonly (display->layout);
3355   while (tmp_list)
3356     {
3357       PangoLayoutLine *layout_line = tmp_list->data;
3358
3359       if (line_byte < layout_line->start_index + layout_line->length || !tmp_list->next)
3360         {
3361           line_display_index_to_iter (layout, display, iter,
3362                                       direction < 0 ? layout_line->start_index : layout_line->start_index + layout_line->length,
3363                                       0);
3364
3365           /* FIXME: As a bad hack, we move back one position when we
3366            * are inside a paragraph to avoid going to next line on a
3367            * forced break not at whitespace. Real fix is to keep track
3368            * of whether marks are at leading or trailing edge?  */
3369           if (direction > 0 && layout_line->length > 0 && 
3370               !gtk_text_iter_ends_line (iter) && 
3371               !_gtk_text_btree_char_is_invisible (iter))
3372             gtk_text_iter_backward_char (iter);
3373           break;
3374         }
3375       
3376       tmp_list = tmp_list->next;
3377     }
3378
3379   gtk_text_layout_free_line_display (layout, display);
3380
3381   return
3382     !gtk_text_iter_equal (iter, &orig) &&
3383     !gtk_text_iter_is_end (iter);
3384 }
3385
3386
3387 /**
3388  * gtk_text_layout_iter_starts_line:
3389  * @layout: a #GtkTextLayout
3390  * @iter: iterator to test
3391  *
3392  * Tests whether an iterator is at the start of a display line.
3393  **/
3394 gboolean
3395 gtk_text_layout_iter_starts_line (GtkTextLayout       *layout,
3396                                   const GtkTextIter   *iter)
3397 {
3398   GtkTextLine *line;
3399   GtkTextLineDisplay *display;
3400   gint line_byte;
3401   GSList *tmp_list;
3402   
3403   g_return_val_if_fail (GTK_IS_TEXT_LAYOUT (layout), FALSE);
3404   g_return_val_if_fail (iter != NULL, FALSE);
3405
3406   line = _gtk_text_iter_get_text_line (iter);
3407   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3408   line_byte = line_display_iter_to_index (layout, display, iter);
3409
3410   tmp_list = pango_layout_get_lines_readonly (display->layout);
3411   while (tmp_list)
3412     {
3413       PangoLayoutLine *layout_line = tmp_list->data;
3414
3415       if (line_byte < layout_line->start_index + layout_line->length ||
3416           !tmp_list->next)
3417         {
3418           /* We're located on this line or the para delimiters before
3419            * it
3420            */
3421           gtk_text_layout_free_line_display (layout, display);
3422           
3423           if (line_byte == layout_line->start_index)
3424             return TRUE;
3425           else
3426             return FALSE;
3427         }
3428       
3429       tmp_list = tmp_list->next;
3430     }
3431
3432   g_assert_not_reached ();
3433   return FALSE;
3434 }
3435
3436 void
3437 gtk_text_layout_get_iter_at_line (GtkTextLayout  *layout,
3438                                   GtkTextIter    *iter,
3439                                   GtkTextLine    *line,
3440                                   gint            byte_offset)
3441 {
3442   _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3443                                     iter, line, byte_offset);
3444 }
3445
3446
3447 /**
3448  * gtk_text_layout_move_iter_to_x:
3449  * @layout: a #GtkTextLayout
3450  * @iter:   a #GtkTextIter
3451  * @x:      X coordinate
3452  *
3453  * Keeping the iterator on the same line of the layout, move it to the
3454  * specified X coordinate. The lines of a wrapped paragraph are
3455  * treated as distinct for this operation.
3456  **/
3457 void
3458 gtk_text_layout_move_iter_to_x (GtkTextLayout *layout,
3459                                 GtkTextIter   *iter,
3460                                 gint           x)
3461 {
3462   GtkTextLine *line;
3463   GtkTextLineDisplay *display;
3464   gint line_byte;
3465   PangoLayoutIter *layout_iter;
3466   
3467   g_return_if_fail (GTK_IS_TEXT_LAYOUT (layout));
3468   g_return_if_fail (iter != NULL);
3469
3470   line = _gtk_text_iter_get_text_line (iter);
3471
3472   display = gtk_text_layout_get_line_display (layout, line, FALSE);
3473   line_byte = line_display_iter_to_index (layout, display, iter);
3474
3475   layout_iter = pango_layout_get_iter (display->layout);
3476
3477   do
3478     {
3479       PangoLayoutLine *layout_line = pango_layout_iter_get_line_readonly (layout_iter);
3480
3481       if (line_byte < layout_line->start_index + layout_line->length ||
3482           pango_layout_iter_at_last_line (layout_iter))
3483         {
3484           PangoRectangle logical_rect;
3485           gint byte_index, trailing;
3486           gint x_offset = display->x_offset * PANGO_SCALE;
3487
3488           pango_layout_iter_get_line_extents (layout_iter, NULL, &logical_rect);
3489
3490           pango_layout_line_x_to_index (layout_line,
3491                                         x * PANGO_SCALE - x_offset - logical_rect.x,
3492                                         &byte_index, &trailing);
3493
3494           line_display_index_to_iter (layout, display, iter, byte_index, trailing);
3495
3496           break;
3497         }
3498     }
3499   while (pango_layout_iter_next_line (layout_iter));
3500
3501   pango_layout_iter_free (layout_iter);
3502   
3503   gtk_text_layout_free_line_display (layout, display);
3504 }
3505
3506 /**
3507  * gtk_text_layout_move_iter_visually:
3508  * @layout:  a #GtkTextLayout
3509  * @iter:    a #GtkTextIter
3510  * @count:   number of characters to move (negative moves left, positive moves right)
3511  *
3512  * Move the iterator a given number of characters visually, treating
3513  * it as the strong cursor position. If @count is positive, then the
3514  * new strong cursor position will be @count positions to the right of
3515  * the old cursor position. If @count is negative then the new strong
3516  * cursor position will be @count positions to the left of the old
3517  * cursor position.
3518  *
3519  * In the presence of bidirection text, the correspondence
3520  * between logical and visual order will depend on the direction
3521  * of the current run, and there may be jumps when the cursor
3522  * is moved off of the end of a run.
3523  **/
3524
3525 gboolean
3526 gtk_text_layout_move_iter_visually (GtkTextLayout *layout,
3527                                     GtkTextIter   *iter,
3528                                     gint           count)
3529 {
3530   GtkTextLineDisplay *display = NULL;
3531   GtkTextIter orig;
3532   GtkTextIter lineiter;
3533   
3534   g_return_val_if_fail (layout != NULL, FALSE);
3535   g_return_val_if_fail (iter != NULL, FALSE);
3536
3537   orig = *iter;
3538   
3539   while (count != 0)
3540     {
3541       GtkTextLine *line = _gtk_text_iter_get_text_line (iter);
3542       gint line_byte;
3543       gint extra_back = 0;
3544       gboolean strong;
3545
3546       int byte_count = _gtk_text_line_byte_count (line);
3547
3548       int new_index;
3549       int new_trailing;
3550
3551       if (!display)
3552         display = gtk_text_layout_get_line_display (layout, line, FALSE);
3553
3554       if (layout->cursor_direction == GTK_TEXT_DIR_NONE)
3555         strong = TRUE;
3556       else
3557         strong = display->direction == layout->cursor_direction;
3558
3559       line_byte = line_display_iter_to_index (layout, display, iter);
3560
3561       if (count > 0)
3562         {
3563           pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, 1, &new_index, &new_trailing);
3564           count--;
3565         }
3566       else
3567         {
3568           pango_layout_move_cursor_visually (display->layout, strong, line_byte, 0, -1, &new_index, &new_trailing);
3569           count++;
3570         }
3571
3572       /* We need to handle the preedit string specially. Well, we don't really need to
3573        * handle it specially, since hopefully calling gtk_im_context_reset() will
3574        * remove the preedit string; but if we start off in front of the preedit
3575        * string (logically) and end up in or on the back edge of the preedit string,
3576        * we should move the iter one place farther.
3577        */
3578       if (layout->preedit_len > 0 && display->insert_index >= 0)
3579         {
3580           if (line_byte == display->insert_index + layout->preedit_len &&
3581               new_index < display->insert_index + layout->preedit_len)
3582             {
3583               line_byte = display->insert_index;
3584               extra_back = 1;
3585             }
3586         }
3587       
3588       if (new_index < 0 || (new_index == 0 && extra_back))
3589         {
3590           do
3591             {
3592               line = _gtk_text_line_previous (line);
3593
3594               if (!line)
3595                 goto done;
3596               
3597               _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3598                                                 &lineiter, line, 0);
3599             }
3600           while (totally_invisible_line (layout, line, &lineiter));
3601           
3602           gtk_text_layout_free_line_display (layout, display);
3603           display = gtk_text_layout_get_line_display (layout, line, FALSE);
3604           gtk_text_iter_forward_to_line_end (&lineiter);
3605           new_index = gtk_text_iter_get_visible_line_index (&lineiter);
3606         }
3607       else if (new_index > byte_count)
3608         {
3609           do
3610             {
3611               line = _gtk_text_line_next_excluding_last (line);
3612               if (!line)
3613                 goto done;
3614
3615               _gtk_text_btree_get_iter_at_line (_gtk_text_buffer_get_btree (layout->buffer),
3616                                                 &lineiter, line, 0);
3617             }
3618           while (totally_invisible_line (layout, line, &lineiter));
3619   
3620           gtk_text_layout_free_line_display (layout, display);
3621           display = gtk_text_layout_get_line_display (layout, line, FALSE);
3622           new_index = 0;
3623         }
3624       
3625        line_display_index_to_iter (layout, display, iter, new_index, new_trailing);
3626        if (extra_back)
3627          gtk_text_iter_backward_char (iter);
3628     }
3629
3630   gtk_text_layout_free_line_display (layout, display);
3631
3632  done:
3633   
3634   return
3635     !gtk_text_iter_equal (iter, &orig) &&
3636     !gtk_text_iter_is_end (iter);
3637 }
3638
3639 void
3640 gtk_text_layout_spew (GtkTextLayout *layout)
3641 {
3642 #if 0
3643   GtkTextDisplayLine *iter;
3644   guint wrapped = 0;
3645   guint paragraphs = 0;
3646   GtkTextLine *last_line = NULL;
3647
3648   iter = layout->line_list;
3649   while (iter != NULL)
3650     {
3651       if (iter->line != last_line)
3652         {
3653           printf ("%5u  paragraph (%p)\n", paragraphs, iter->line);
3654           ++paragraphs;
3655           last_line = iter->line;
3656         }
3657
3658       printf ("  %5u  y: %d len: %d start: %d bytes: %d\n",
3659               wrapped, iter->y, iter->length, iter->byte_offset,
3660               iter->byte_count);
3661
3662       ++wrapped;
3663       iter = iter->next;
3664     }
3665
3666   printf ("Layout %s recompute\n",
3667           layout->need_recompute ? "needs" : "doesn't need");
3668
3669   printf ("Layout pars: %u lines: %u size: %d x %d Screen width: %d\n",
3670           paragraphs, wrapped, layout->width,
3671           layout->height, layout->screen_width);
3672 #endif
3673 }
3674
3675 /* Catch all situations that move the insertion point.
3676  */
3677 static void
3678 gtk_text_layout_mark_set_handler (GtkTextBuffer     *buffer,
3679                                   const GtkTextIter *location,
3680                                   GtkTextMark       *mark,
3681                                   gpointer           data)
3682 {
3683   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3684
3685   if (mark == gtk_text_buffer_get_insert (buffer))
3686     gtk_text_layout_update_cursor_line (layout);
3687 }
3688
3689 static void
3690 gtk_text_layout_buffer_insert_text (GtkTextBuffer *textbuffer,
3691                                     GtkTextIter   *iter,
3692                                     gchar         *str,
3693                                     gint           len,
3694                                     gpointer       data)
3695 {
3696   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3697
3698   gtk_text_layout_update_cursor_line (layout);
3699 }
3700
3701 static void
3702 gtk_text_layout_buffer_delete_range (GtkTextBuffer *textbuffer,
3703                                      GtkTextIter   *start,
3704                                      GtkTextIter   *end,
3705                                      gpointer       data)
3706 {
3707   GtkTextLayout *layout = GTK_TEXT_LAYOUT (data);
3708
3709   gtk_text_layout_update_cursor_line (layout);
3710 }