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