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