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