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