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