]> Pileus Git - ~andy/gtk/blob - gtk/gtklabel.c
label: Stop setting state flags on the style context for drawing
[~andy/gtk] / gtk / gtklabel.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free
16  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 /*
20  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
21  * file for a list of people on the GTK+ Team.  See the ChangeLog
22  * files for a list of changes.  These files are distributed with
23  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
24  */
25
26 #include "config.h"
27
28 #include <math.h>
29 #include <string.h>
30
31 #include "gtklabel.h"
32 #include "gtkaccellabel.h"
33 #include "gtkdnd.h"
34 #include "gtkmarshalers.h"
35 #include "gtkpango.h"
36 #include "gtkwindow.h"
37 #include "gtkclipboard.h"
38 #include "gtkimagemenuitem.h"
39 #include "gtkintl.h"
40 #include "gtkseparatormenuitem.h"
41 #include "gtktextutil.h"
42 #include "gtkmain.h"
43 #include "gtkmenuitem.h"
44 #include "gtkmenushellprivate.h"
45 #include "gtknotebook.h"
46 #include "gtkstock.h"
47 #include "gtkbindings.h"
48 #include "gtkbuildable.h"
49 #include "gtkimage.h"
50 #include "gtkshow.h"
51 #include "gtktooltip.h"
52 #include "gtkprivate.h"
53 #include "gtktypebuiltins.h"
54 #include "gtkmain.h"
55
56 #include "a11y/gtklabelaccessible.h"
57
58 /* this is in case rint() is not provided by the compiler, 
59  * such as in the case of C89 compilers, like MSVC
60  */
61 #include "fallback-c89.c"
62
63 /**
64  * SECTION:gtklabel
65  * @Short_description: A widget that displays a small to medium amount of text
66  * @Title: GtkLabel
67  *
68  * The #GtkLabel widget displays a small amount of text. As the name
69  * implies, most labels are used to label another widget such as a
70  * #GtkButton, a #GtkMenuItem, or a #GtkOptionMenu.
71  *
72  * <refsect2 id="GtkLabel-BUILDER-UI">
73  * <title>GtkLabel as GtkBuildable</title>
74  * <para>
75  * The GtkLabel implementation of the GtkBuildable interface supports a
76  * custom &lt;attributes&gt; element, which supports any number of &lt;attribute&gt;
77  * elements. the &lt;attribute&gt; element has attributes named name, value,
78  * start and end and allows you to specify #PangoAttribute values for this label.
79  *
80  * <example>
81  * <title>A UI definition fragment specifying Pango attributes</title>
82  * <programlisting><![CDATA[
83  * <object class="GtkLabel">
84  *   <attributes>
85  *     <attribute name="weight" value="PANGO_WEIGHT_BOLD"/>
86  *     <attribute name="background" value="red" start="5" end="10"/>"
87  *   </attributes>
88  * </object>
89  * ]]></programlisting>
90  * </example>
91  * The start and end attributes specify the range of characters to which the
92  * Pango attribute applies. If start and end are not specified, the attribute is
93  * applied to the whole text. Note that specifying ranges does not make much
94  * sense with translatable attributes. Use markup embedded in the translatable
95  * content instead.
96  * </para>
97  * </refsect2>
98  * <refsect2>
99  * <title>Mnemonics</title>
100  * <para>
101  * Labels may contain <firstterm>mnemonics</firstterm>. Mnemonics are
102  * underlined characters in the label, used for keyboard navigation.
103  * Mnemonics are created by providing a string with an underscore before
104  * the mnemonic character, such as <literal>"_File"</literal>, to the
105  * functions gtk_label_new_with_mnemonic() or
106  * gtk_label_set_text_with_mnemonic().
107  *
108  * Mnemonics automatically activate any activatable widget the label is
109  * inside, such as a #GtkButton; if the label is not inside the
110  * mnemonic's target widget, you have to tell the label about the target
111  * using gtk_label_set_mnemonic_widget(). Here's a simple example where
112  * the label is inside a button:
113  *
114  * <informalexample>
115  * <programlisting>
116  *   // Pressing Alt+H will activate this button
117  *   button = gtk_button_new (<!-- -->);
118  *   label = gtk_label_new_with_mnemonic ("_Hello");
119  *   gtk_container_add (GTK_CONTAINER (button), label);
120  * </programlisting>
121  * </informalexample>
122  *
123  * There's a convenience function to create buttons with a mnemonic label
124  * already inside:
125  *
126  * <informalexample>
127  * <programlisting>
128  *   // Pressing Alt+H will activate this button
129  *   button = gtk_button_new_with_mnemonic ("_Hello");
130  * </programlisting>
131  * </informalexample>
132  *
133  * To create a mnemonic for a widget alongside the label, such as a
134  * #GtkEntry, you have to point the label at the entry with
135  * gtk_label_set_mnemonic_widget():
136  *
137  * <informalexample>
138  * <programlisting>
139  *   // Pressing Alt+H will focus the entry
140  *   entry = gtk_entry_new (<!-- -->);
141  *   label = gtk_label_new_with_mnemonic ("_Hello");
142  *   gtk_label_set_mnemonic_widget (GTK_LABEL (label), entry);
143  * </programlisting>
144  * </informalexample>
145  * </para>
146  * </refsect2>
147  * <refsect2>
148  * <title>Markup (styled text)</title>
149  * <para>
150  * To make it easy to format text in a label (changing colors, fonts,
151  * etc.), label text can be provided in a simple <link
152  * linkend="PangoMarkupFormat">markup format</link>.
153  * Here's how to create a label with a small font:
154  *
155  * <informalexample>
156  * <programlisting>
157  *   label = gtk_label_new (NULL);
158  *   gtk_label_set_markup (GTK_LABEL (label), "<small>Small text</small>");
159  * </programlisting>
160  * </informalexample>
161  *
162  * (See <link
163  * linkend="PangoMarkupFormat">complete documentation</link> of available
164  * tags in the Pango manual.)
165  *
166  * The markup passed to gtk_label_set_markup() must be valid; for example,
167  * literal &lt;, &gt; and &amp; characters must be escaped as \&lt;,
168  * \gt;, and \&amp;. If you pass text obtained from the user, file,
169  * or a network to gtk_label_set_markup(), you'll want to escape it with
170  * g_markup_escape_text() or g_markup_printf_escaped().
171  *
172  * Markup strings are just a convenient way to set the #PangoAttrList on
173  * a label; gtk_label_set_attributes() may be a simpler way to set
174  * attributes in some cases. Be careful though; #PangoAttrList tends to
175  * cause internationalization problems, unless you're applying attributes
176  * to the entire string (i.e. unless you set the range of each attribute
177  * to [0, %G_MAXINT)). The reason is that specifying the start_index and
178  * end_index for a #PangoAttribute requires knowledge of the exact string
179  * being displayed, so translations will cause problems.
180  * </para>
181  * </refsect2>
182  * <refsect2>
183  * <title>Selectable labels</title>
184  * Labels can be made selectable with gtk_label_set_selectable().
185  * Selectable labels allow the user to copy the label contents to
186  * the clipboard. Only labels that contain useful-to-copy information
187  * &mdash; such as error messages &mdash; should be made selectable.
188  * </refsect2>
189  * <refsect2 id="label-text-layout">
190  * <title>Text layout</title>
191  * <para>
192  * A label can contain any number of paragraphs, but will have
193  * performance problems if it contains more than a small number.
194  * Paragraphs are separated by newlines or other paragraph separators
195  * understood by Pango.
196  *
197  * Labels can automatically wrap text if you call
198  * gtk_label_set_line_wrap().
199  *
200  * gtk_label_set_justify() sets how the lines in a label align
201  * with one another. If you want to set how the label as a whole
202  * aligns in its available space, see gtk_misc_set_alignment().
203  *
204  * The #GtkLabel:width-chars and #GtkLabel:max-width-chars properties
205  * can be used to control the size allocation of ellipsized or wrapped
206  * labels. For ellipsizing labels, if either is specified (and less
207  * than the actual text size), it is used as the minimum width, and the actual
208  * text size is used as the natural width of the label. For wrapping labels,
209  * width-chars is used as the minimum width, if specified, and max-width-chars
210  * is used as the natural width. Even if max-width-chars specified, wrapping
211  * labels will be rewrapped to use all of the available width.
212  *
213  * <note><para>
214  * Note that the interpretation of #GtkLabel:width-chars and
215  * #GtkLabel:max-width-chars has changed a bit with the introduction of
216  * <link linkend="geometry-management">width-for-height geometry management.</link>
217  * </para></note>
218  * </para>
219  * </refsect2>
220  * <refsect2>
221  * <title>Links</title>
222  * <para>
223  * Since 2.18, GTK+ supports markup for clickable hyperlinks in addition
224  * to regular Pango markup. The markup for links is borrowed from HTML, using the
225  * <tag>a</tag> with href and title attributes. GTK+ renders links similar to the
226  * way they appear in web browsers, with colored, underlined text. The title
227  * attribute is displayed as a tooltip on the link. An example looks like this:
228  *
229  * <informalexample><programlisting>
230  * gtk_label_set_markup (label, "Go to the <a href="http://www.gtk.org" title="&lt;i&gt;Our&lt;/i&gt; website">GTK+ website</a> for more...");
231  * </programlisting></informalexample>
232  *
233  * It is possible to implement custom handling for links and their tooltips with
234  * the #GtkLabel::activate-link signal and the gtk_label_get_current_uri() function.
235  * </para>
236  * </refsect2>
237  */
238
239 struct _GtkLabelPrivate
240 {
241   GtkLabelSelectionInfo *select_info;
242   GtkWidget *mnemonic_widget;
243   GtkWindow *mnemonic_window;
244
245   PangoAttrList *attrs;
246   PangoAttrList *effective_attrs;
247   PangoLayout   *layout;
248
249   gchar   *label;
250   gchar   *text;
251
252   gdouble  angle;
253
254   guint    mnemonics_visible  : 1;
255   guint    jtype              : 2;
256   guint    wrap               : 1;
257   guint    use_underline      : 1;
258   guint    use_markup         : 1;
259   guint    ellipsize          : 3;
260   guint    single_line_mode   : 1;
261   guint    have_transform     : 1;
262   guint    in_click           : 1;
263   guint    wrap_mode          : 3;
264   guint    pattern_set        : 1;
265   guint    track_links        : 1;
266
267   guint    mnemonic_keyval;
268
269   gint     width_chars;
270   gint     max_width_chars;
271 };
272
273 /* Notes about the handling of links:
274  *
275  * Links share the GtkLabelSelectionInfo struct with selectable labels.
276  * There are some new fields for links. The links field contains the list
277  * of GtkLabelLink structs that describe the links which are embedded in
278  * the label. The active_link field points to the link under the mouse
279  * pointer. For keyboard navigation, the 'focus' link is determined by
280  * finding the link which contains the selection_anchor position.
281  * The link_clicked field is used with button press and release events
282  * to ensure that pressing inside a link and releasing outside of it
283  * does not activate the link.
284  *
285  * Links are rendered with the link-color/visited-link-color colors
286  * that are determined by the style and with an underline. When the mouse
287  * pointer is over a link, the pointer is changed to indicate the link,
288  * and the background behind the link is rendered with the base[PRELIGHT]
289  * color. While a button is pressed over a link, the background is rendered
290  * with the base[ACTIVE] color.
291  *
292  * Labels with links accept keyboard focus, and it is possible to move
293  * the focus between the embedded links using Tab/Shift-Tab. The focus
294  * is indicated by a focus rectangle that is drawn around the link text.
295  * Pressing Enter activates the focussed link, and there is a suitable
296  * context menu for links that can be opened with the Menu key. Pressing
297  * Control-C copies the link URI to the clipboard.
298  *
299  * In selectable labels with links, link functionality is only available
300  * when the selection is empty.
301  */
302 typedef struct
303 {
304   gchar *uri;
305   gchar *title;     /* the title attribute, used as tooltip */
306   gboolean visited; /* get set when the link is activated; this flag
307                      * gets preserved over later set_markup() calls
308                      */
309   gint start;       /* position of the link in the PangoLayout */
310   gint end;
311 } GtkLabelLink;
312
313 struct _GtkLabelSelectionInfo
314 {
315   GdkWindow *window;
316   gint selection_anchor;
317   gint selection_end;
318   GtkWidget *popup_menu;
319
320   GList *links;
321   GtkLabelLink *active_link;
322
323   gint drag_start_x;
324   gint drag_start_y;
325
326   guint in_drag      : 1;
327   guint select_words : 1;
328   guint selectable   : 1;
329   guint link_clicked : 1;
330 };
331
332 enum {
333   MOVE_CURSOR,
334   COPY_CLIPBOARD,
335   POPULATE_POPUP,
336   ACTIVATE_LINK,
337   ACTIVATE_CURRENT_LINK,
338   LAST_SIGNAL
339 };
340
341 enum {
342   PROP_0,
343   PROP_LABEL,
344   PROP_ATTRIBUTES,
345   PROP_USE_MARKUP,
346   PROP_USE_UNDERLINE,
347   PROP_JUSTIFY,
348   PROP_PATTERN,
349   PROP_WRAP,
350   PROP_WRAP_MODE,
351   PROP_SELECTABLE,
352   PROP_MNEMONIC_KEYVAL,
353   PROP_MNEMONIC_WIDGET,
354   PROP_CURSOR_POSITION,
355   PROP_SELECTION_BOUND,
356   PROP_ELLIPSIZE,
357   PROP_WIDTH_CHARS,
358   PROP_SINGLE_LINE_MODE,
359   PROP_ANGLE,
360   PROP_MAX_WIDTH_CHARS,
361   PROP_TRACK_VISITED_LINKS
362 };
363
364 /* When rotating ellipsizable text we want the natural size to request 
365  * more to ensure the label wont ever ellipsize in an allocation of full natural size.
366  * */
367 #define ROTATION_ELLIPSIZE_PADDING 2
368
369 static guint signals[LAST_SIGNAL] = { 0 };
370
371 static const GdkColor default_link_color = { 0, 0, 0, 0xeeee };
372 static const GdkColor default_visited_link_color = { 0, 0x5555, 0x1a1a, 0x8b8b };
373
374 static void gtk_label_set_property      (GObject          *object,
375                                          guint             prop_id,
376                                          const GValue     *value,
377                                          GParamSpec       *pspec);
378 static void gtk_label_get_property      (GObject          *object,
379                                          guint             prop_id,
380                                          GValue           *value,
381                                          GParamSpec       *pspec);
382 static void gtk_label_finalize          (GObject          *object);
383 static void gtk_label_destroy           (GtkWidget        *widget);
384 static void gtk_label_size_allocate     (GtkWidget        *widget,
385                                          GtkAllocation    *allocation);
386 static void gtk_label_state_flags_changed   (GtkWidget        *widget,
387                                              GtkStateFlags     prev_state);
388 static void gtk_label_style_updated     (GtkWidget        *widget);
389 static void gtk_label_direction_changed (GtkWidget        *widget,
390                                          GtkTextDirection  previous_dir);
391 static gint gtk_label_draw              (GtkWidget        *widget,
392                                          cairo_t          *cr);
393 static gboolean gtk_label_focus         (GtkWidget         *widget,
394                                          GtkDirectionType   direction);
395
396 static void gtk_label_realize           (GtkWidget        *widget);
397 static void gtk_label_unrealize         (GtkWidget        *widget);
398 static void gtk_label_map               (GtkWidget        *widget);
399 static void gtk_label_unmap             (GtkWidget        *widget);
400
401 static gboolean gtk_label_button_press      (GtkWidget        *widget,
402                                              GdkEventButton   *event);
403 static gboolean gtk_label_button_release    (GtkWidget        *widget,
404                                              GdkEventButton   *event);
405 static gboolean gtk_label_motion            (GtkWidget        *widget,
406                                              GdkEventMotion   *event);
407 static gboolean gtk_label_leave_notify      (GtkWidget        *widget,
408                                              GdkEventCrossing *event);
409
410 static void     gtk_label_grab_focus        (GtkWidget        *widget);
411
412 static gboolean gtk_label_query_tooltip     (GtkWidget        *widget,
413                                              gint              x,
414                                              gint              y,
415                                              gboolean          keyboard_tip,
416                                              GtkTooltip       *tooltip);
417
418 static void gtk_label_set_text_internal          (GtkLabel      *label,
419                                                   gchar         *str);
420 static void gtk_label_set_label_internal         (GtkLabel      *label,
421                                                   gchar         *str);
422 static void gtk_label_set_use_markup_internal    (GtkLabel      *label,
423                                                   gboolean       val);
424 static void gtk_label_set_use_underline_internal (GtkLabel      *label,
425                                                   gboolean       val);
426 static void gtk_label_set_attributes_internal    (GtkLabel      *label,
427                                                   PangoAttrList *attrs);
428 static void gtk_label_set_uline_text_internal    (GtkLabel      *label,
429                                                   const gchar   *str);
430 static void gtk_label_set_pattern_internal       (GtkLabel      *label,
431                                                   const gchar   *pattern,
432                                                   gboolean       is_mnemonic);
433 static void gtk_label_set_markup_internal        (GtkLabel      *label,
434                                                   const gchar   *str,
435                                                   gboolean       with_uline);
436 static void gtk_label_recalculate                (GtkLabel      *label);
437 static void gtk_label_hierarchy_changed          (GtkWidget     *widget,
438                                                   GtkWidget     *old_toplevel);
439 static void gtk_label_screen_changed             (GtkWidget     *widget,
440                                                   GdkScreen     *old_screen);
441 static gboolean gtk_label_popup_menu             (GtkWidget     *widget);
442
443 static void gtk_label_create_window       (GtkLabel *label);
444 static void gtk_label_destroy_window      (GtkLabel *label);
445 static void gtk_label_ensure_select_info  (GtkLabel *label);
446 static void gtk_label_clear_select_info   (GtkLabel *label);
447 static void gtk_label_update_cursor       (GtkLabel *label);
448 static void gtk_label_clear_layout        (GtkLabel *label);
449 static void gtk_label_ensure_layout       (GtkLabel *label);
450 static void gtk_label_select_region_index (GtkLabel *label,
451                                            gint      anchor_index,
452                                            gint      end_index);
453
454
455 static gboolean gtk_label_mnemonic_activate (GtkWidget         *widget,
456                                              gboolean           group_cycling);
457 static void     gtk_label_setup_mnemonic    (GtkLabel          *label,
458                                              guint              last_key);
459 static void     gtk_label_drag_data_get     (GtkWidget         *widget,
460                                              GdkDragContext    *context,
461                                              GtkSelectionData  *selection_data,
462                                              guint              info,
463                                              guint              time);
464
465 static void     gtk_label_buildable_interface_init     (GtkBuildableIface *iface);
466 static gboolean gtk_label_buildable_custom_tag_start   (GtkBuildable     *buildable,
467                                                         GtkBuilder       *builder,
468                                                         GObject          *child,
469                                                         const gchar      *tagname,
470                                                         GMarkupParser    *parser,
471                                                         gpointer         *data);
472
473 static void     gtk_label_buildable_custom_finished    (GtkBuildable     *buildable,
474                                                         GtkBuilder       *builder,
475                                                         GObject          *child,
476                                                         const gchar      *tagname,
477                                                         gpointer          user_data);
478
479
480 static void connect_mnemonics_visible_notify    (GtkLabel   *label);
481 static gboolean      separate_uline_pattern     (const gchar  *str,
482                                                  guint        *accel_key,
483                                                  gchar       **new_str,
484                                                  gchar       **pattern);
485
486
487 /* For selectable labels: */
488 static void gtk_label_move_cursor        (GtkLabel        *label,
489                                           GtkMovementStep  step,
490                                           gint             count,
491                                           gboolean         extend_selection);
492 static void gtk_label_copy_clipboard     (GtkLabel        *label);
493 static void gtk_label_select_all         (GtkLabel        *label);
494 static void gtk_label_do_popup           (GtkLabel        *label,
495                                           GdkEventButton  *event);
496 static gint gtk_label_move_forward_word  (GtkLabel        *label,
497                                           gint             start);
498 static gint gtk_label_move_backward_word (GtkLabel        *label,
499                                           gint             start);
500
501 /* For links: */
502 static void          gtk_label_rescan_links     (GtkLabel  *label);
503 static void          gtk_label_clear_links      (GtkLabel  *label);
504 static gboolean      gtk_label_activate_link    (GtkLabel    *label,
505                                                  const gchar *uri);
506 static void          gtk_label_activate_current_link (GtkLabel *label);
507 static GtkLabelLink *gtk_label_get_current_link (GtkLabel  *label);
508 static void          gtk_label_get_link_colors  (GtkWidget  *widget,
509                                                  GdkColor  **link_color,
510                                                  GdkColor  **visited_link_color);
511 static void          emit_activate_link         (GtkLabel     *label,
512                                                  GtkLabelLink *link);
513
514 static GtkSizeRequestMode gtk_label_get_request_mode                (GtkWidget           *widget);
515 static void               gtk_label_get_preferred_width             (GtkWidget           *widget,
516                                                                      gint                *minimum_size,
517                                                                      gint                *natural_size);
518 static void               gtk_label_get_preferred_height            (GtkWidget           *widget,
519                                                                      gint                *minimum_size,
520                                                                      gint                *natural_size);
521 static void               gtk_label_get_preferred_width_for_height  (GtkWidget           *widget,
522                                                                      gint                 height,
523                                                                      gint                *minimum_width,
524                                                                      gint                *natural_width);
525 static void               gtk_label_get_preferred_height_for_width  (GtkWidget           *widget,
526                                                                      gint                 width,
527                                                                      gint                *minimum_height,
528                                                                      gint                *natural_height);
529
530 static GtkBuildableIface *buildable_parent_iface = NULL;
531
532 G_DEFINE_TYPE_WITH_CODE (GtkLabel, gtk_label, GTK_TYPE_MISC,
533                          G_IMPLEMENT_INTERFACE (GTK_TYPE_BUILDABLE,
534                                                 gtk_label_buildable_interface_init))
535
536 static void
537 add_move_binding (GtkBindingSet  *binding_set,
538                   guint           keyval,
539                   guint           modmask,
540                   GtkMovementStep step,
541                   gint            count)
542 {
543   g_return_if_fail ((modmask & GDK_SHIFT_MASK) == 0);
544   
545   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
546                                 "move-cursor", 3,
547                                 G_TYPE_ENUM, step,
548                                 G_TYPE_INT, count,
549                                 G_TYPE_BOOLEAN, FALSE);
550
551   /* Selection-extending version */
552   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
553                                 "move-cursor", 3,
554                                 G_TYPE_ENUM, step,
555                                 G_TYPE_INT, count,
556                                 G_TYPE_BOOLEAN, TRUE);
557 }
558
559 static void
560 gtk_label_class_init (GtkLabelClass *class)
561 {
562   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
563   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
564   GtkBindingSet *binding_set;
565
566   gobject_class->set_property = gtk_label_set_property;
567   gobject_class->get_property = gtk_label_get_property;
568   gobject_class->finalize = gtk_label_finalize;
569
570   widget_class->destroy = gtk_label_destroy;
571   widget_class->size_allocate = gtk_label_size_allocate;
572   widget_class->state_flags_changed = gtk_label_state_flags_changed;
573   widget_class->style_updated = gtk_label_style_updated;
574   widget_class->query_tooltip = gtk_label_query_tooltip;
575   widget_class->direction_changed = gtk_label_direction_changed;
576   widget_class->draw = gtk_label_draw;
577   widget_class->realize = gtk_label_realize;
578   widget_class->unrealize = gtk_label_unrealize;
579   widget_class->map = gtk_label_map;
580   widget_class->unmap = gtk_label_unmap;
581   widget_class->button_press_event = gtk_label_button_press;
582   widget_class->button_release_event = gtk_label_button_release;
583   widget_class->motion_notify_event = gtk_label_motion;
584   widget_class->leave_notify_event = gtk_label_leave_notify;
585   widget_class->hierarchy_changed = gtk_label_hierarchy_changed;
586   widget_class->screen_changed = gtk_label_screen_changed;
587   widget_class->mnemonic_activate = gtk_label_mnemonic_activate;
588   widget_class->drag_data_get = gtk_label_drag_data_get;
589   widget_class->grab_focus = gtk_label_grab_focus;
590   widget_class->popup_menu = gtk_label_popup_menu;
591   widget_class->focus = gtk_label_focus;
592   widget_class->get_request_mode = gtk_label_get_request_mode;
593   widget_class->get_preferred_width = gtk_label_get_preferred_width;
594   widget_class->get_preferred_height = gtk_label_get_preferred_height;
595   widget_class->get_preferred_width_for_height = gtk_label_get_preferred_width_for_height;
596   widget_class->get_preferred_height_for_width = gtk_label_get_preferred_height_for_width;
597
598   class->move_cursor = gtk_label_move_cursor;
599   class->copy_clipboard = gtk_label_copy_clipboard;
600   class->activate_link = gtk_label_activate_link;
601
602   /**
603    * GtkLabel::move-cursor:
604    * @entry: the object which received the signal
605    * @step: the granularity of the move, as a #GtkMovementStep
606    * @count: the number of @step units to move
607    * @extend_selection: %TRUE if the move should extend the selection
608    *
609    * The ::move-cursor signal is a
610    * <link linkend="keybinding-signals">keybinding signal</link>
611    * which gets emitted when the user initiates a cursor movement.
612    * If the cursor is not visible in @entry, this signal causes
613    * the viewport to be moved instead.
614    *
615    * Applications should not connect to it, but may emit it with
616    * g_signal_emit_by_name() if they need to control the cursor
617    * programmatically.
618    *
619    * The default bindings for this signal come in two variants,
620    * the variant with the Shift modifier extends the selection,
621    * the variant without the Shift modifer does not.
622    * There are too many key combinations to list them all here.
623    * <itemizedlist>
624    * <listitem>Arrow keys move by individual characters/lines</listitem>
625    * <listitem>Ctrl-arrow key combinations move by words/paragraphs</listitem>
626    * <listitem>Home/End keys move to the ends of the buffer</listitem>
627    * </itemizedlist>
628    */
629   signals[MOVE_CURSOR] = 
630     g_signal_new (I_("move-cursor"),
631                   G_OBJECT_CLASS_TYPE (gobject_class),
632                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
633                   G_STRUCT_OFFSET (GtkLabelClass, move_cursor),
634                   NULL, NULL,
635                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN,
636                   G_TYPE_NONE, 3,
637                   GTK_TYPE_MOVEMENT_STEP,
638                   G_TYPE_INT,
639                   G_TYPE_BOOLEAN);
640
641    /**
642    * GtkLabel::copy-clipboard:
643    * @label: the object which received the signal
644    *
645    * The ::copy-clipboard signal is a
646    * <link linkend="keybinding-signals">keybinding signal</link>
647    * which gets emitted to copy the selection to the clipboard.
648    *
649    * The default binding for this signal is Ctrl-c.
650    */ 
651   signals[COPY_CLIPBOARD] =
652     g_signal_new (I_("copy-clipboard"),
653                   G_OBJECT_CLASS_TYPE (gobject_class),
654                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
655                   G_STRUCT_OFFSET (GtkLabelClass, copy_clipboard),
656                   NULL, NULL,
657                   _gtk_marshal_VOID__VOID,
658                   G_TYPE_NONE, 0);
659   
660   /**
661    * GtkLabel::populate-popup:
662    * @label: The label on which the signal is emitted
663    * @menu: the menu that is being populated
664    *
665    * The ::populate-popup signal gets emitted before showing the
666    * context menu of the label. Note that only selectable labels
667    * have context menus.
668    *
669    * If you need to add items to the context menu, connect
670    * to this signal and append your menuitems to the @menu.
671    */
672   signals[POPULATE_POPUP] =
673     g_signal_new (I_("populate-popup"),
674                   G_OBJECT_CLASS_TYPE (gobject_class),
675                   G_SIGNAL_RUN_LAST,
676                   G_STRUCT_OFFSET (GtkLabelClass, populate_popup),
677                   NULL, NULL,
678                   _gtk_marshal_VOID__OBJECT,
679                   G_TYPE_NONE, 1,
680                   GTK_TYPE_MENU);
681
682     /**
683      * GtkLabel::activate-current-link:
684      * @label: The label on which the signal was emitted
685      *
686      * A <link linkend="keybinding-signals">keybinding signal</link>
687      * which gets emitted when the user activates a link in the label.
688      *
689      * Applications may also emit the signal with g_signal_emit_by_name()
690      * if they need to control activation of URIs programmatically.
691      *
692      * The default bindings for this signal are all forms of the Enter key.
693      *
694      * Since: 2.18
695      */
696     signals[ACTIVATE_CURRENT_LINK] =
697       g_signal_new_class_handler ("activate-current-link",
698                                   G_TYPE_FROM_CLASS (gobject_class),
699                                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
700                                   G_CALLBACK (gtk_label_activate_current_link),
701                                   NULL, NULL,
702                                   _gtk_marshal_VOID__VOID,
703                                   G_TYPE_NONE, 0);
704
705     /**
706      * GtkLabel::activate-link:
707      * @label: The label on which the signal was emitted
708      * @uri: the URI that is activated
709      *
710      * The signal which gets emitted to activate a URI.
711      * Applications may connect to it to override the default behaviour,
712      * which is to call gtk_show_uri().
713      *
714      * Returns: %TRUE if the link has been activated
715      *
716      * Since: 2.18
717      */
718     signals[ACTIVATE_LINK] =
719       g_signal_new ("activate-link",
720                     G_TYPE_FROM_CLASS (gobject_class),
721                     G_SIGNAL_RUN_LAST,
722                     G_STRUCT_OFFSET (GtkLabelClass, activate_link),
723                     _gtk_boolean_handled_accumulator, NULL,
724                     _gtk_marshal_BOOLEAN__STRING,
725                     G_TYPE_BOOLEAN, 1, G_TYPE_STRING);
726
727   g_object_class_install_property (gobject_class,
728                                    PROP_LABEL,
729                                    g_param_spec_string ("label",
730                                                         P_("Label"),
731                                                         P_("The text of the label"),
732                                                         "",
733                                                         GTK_PARAM_READWRITE));
734   g_object_class_install_property (gobject_class,
735                                    PROP_ATTRIBUTES,
736                                    g_param_spec_boxed ("attributes",
737                                                        P_("Attributes"),
738                                                        P_("A list of style attributes to apply to the text of the label"),
739                                                        PANGO_TYPE_ATTR_LIST,
740                                                        GTK_PARAM_READWRITE));
741   g_object_class_install_property (gobject_class,
742                                    PROP_USE_MARKUP,
743                                    g_param_spec_boolean ("use-markup",
744                                                          P_("Use markup"),
745                                                          P_("The text of the label includes XML markup. See pango_parse_markup()"),
746                                                         FALSE,
747                                                         GTK_PARAM_READWRITE));
748   g_object_class_install_property (gobject_class,
749                                    PROP_USE_UNDERLINE,
750                                    g_param_spec_boolean ("use-underline",
751                                                          P_("Use underline"),
752                                                          P_("If set, an underline in the text indicates the next character should be used for the mnemonic accelerator key"),
753                                                         FALSE,
754                                                         GTK_PARAM_READWRITE));
755
756   g_object_class_install_property (gobject_class,
757                                    PROP_JUSTIFY,
758                                    g_param_spec_enum ("justify",
759                                                       P_("Justification"),
760                                                       P_("The alignment of the lines in the text of the label relative to each other. This does NOT affect the alignment of the label within its allocation. See GtkMisc::xalign for that"),
761                                                       GTK_TYPE_JUSTIFICATION,
762                                                       GTK_JUSTIFY_LEFT,
763                                                       GTK_PARAM_READWRITE));
764
765   g_object_class_install_property (gobject_class,
766                                    PROP_PATTERN,
767                                    g_param_spec_string ("pattern",
768                                                         P_("Pattern"),
769                                                         P_("A string with _ characters in positions correspond to characters in the text to underline"),
770                                                         NULL,
771                                                         GTK_PARAM_WRITABLE));
772
773   g_object_class_install_property (gobject_class,
774                                    PROP_WRAP,
775                                    g_param_spec_boolean ("wrap",
776                                                         P_("Line wrap"),
777                                                         P_("If set, wrap lines if the text becomes too wide"),
778                                                         FALSE,
779                                                         GTK_PARAM_READWRITE));
780   /**
781    * GtkLabel:wrap-mode:
782    *
783    * If line wrapping is on (see the #GtkLabel:wrap property) this controls 
784    * how the line wrapping is done. The default is %PANGO_WRAP_WORD, which 
785    * means wrap on word boundaries.
786    *
787    * Since: 2.10
788    */
789   g_object_class_install_property (gobject_class,
790                                    PROP_WRAP_MODE,
791                                    g_param_spec_enum ("wrap-mode",
792                                                       P_("Line wrap mode"),
793                                                       P_("If wrap is set, controls how linewrapping is done"),
794                                                       PANGO_TYPE_WRAP_MODE,
795                                                       PANGO_WRAP_WORD,
796                                                       GTK_PARAM_READWRITE));
797   g_object_class_install_property (gobject_class,
798                                    PROP_SELECTABLE,
799                                    g_param_spec_boolean ("selectable",
800                                                         P_("Selectable"),
801                                                         P_("Whether the label text can be selected with the mouse"),
802                                                         FALSE,
803                                                         GTK_PARAM_READWRITE));
804   g_object_class_install_property (gobject_class,
805                                    PROP_MNEMONIC_KEYVAL,
806                                    g_param_spec_uint ("mnemonic-keyval",
807                                                       P_("Mnemonic key"),
808                                                       P_("The mnemonic accelerator key for this label"),
809                                                       0,
810                                                       G_MAXUINT,
811                                                       GDK_KEY_VoidSymbol,
812                                                       GTK_PARAM_READABLE));
813   g_object_class_install_property (gobject_class,
814                                    PROP_MNEMONIC_WIDGET,
815                                    g_param_spec_object ("mnemonic-widget",
816                                                         P_("Mnemonic widget"),
817                                                         P_("The widget to be activated when the label's mnemonic "
818                                                           "key is pressed"),
819                                                         GTK_TYPE_WIDGET,
820                                                         GTK_PARAM_READWRITE));
821
822   g_object_class_install_property (gobject_class,
823                                    PROP_CURSOR_POSITION,
824                                    g_param_spec_int ("cursor-position",
825                                                      P_("Cursor Position"),
826                                                      P_("The current position of the insertion cursor in chars"),
827                                                      0,
828                                                      G_MAXINT,
829                                                      0,
830                                                      GTK_PARAM_READABLE));
831   
832   g_object_class_install_property (gobject_class,
833                                    PROP_SELECTION_BOUND,
834                                    g_param_spec_int ("selection-bound",
835                                                      P_("Selection Bound"),
836                                                      P_("The position of the opposite end of the selection from the cursor in chars"),
837                                                      0,
838                                                      G_MAXINT,
839                                                      0,
840                                                      GTK_PARAM_READABLE));
841   
842   /**
843    * GtkLabel:ellipsize:
844    *
845    * The preferred place to ellipsize the string, if the label does 
846    * not have enough room to display the entire string, specified as a 
847    * #PangoEllisizeMode. 
848    *
849    * Note that setting this property to a value other than 
850    * %PANGO_ELLIPSIZE_NONE has the side-effect that the label requests 
851    * only enough space to display the ellipsis "...". In particular, this 
852    * means that ellipsizing labels do not work well in notebook tabs, unless 
853    * the tab's #GtkNotebook:tab-expand property is set to %TRUE. Other ways
854    * to set a label's width are gtk_widget_set_size_request() and
855    * gtk_label_set_width_chars().
856    *
857    * Since: 2.6
858    */
859   g_object_class_install_property (gobject_class,
860                                    PROP_ELLIPSIZE,
861                                    g_param_spec_enum ("ellipsize",
862                                                       P_("Ellipsize"),
863                                                       P_("The preferred place to ellipsize the string, if the label does not have enough room to display the entire string"),
864                                                       PANGO_TYPE_ELLIPSIZE_MODE,
865                                                       PANGO_ELLIPSIZE_NONE,
866                                                       GTK_PARAM_READWRITE));
867
868   /**
869    * GtkLabel:width-chars:
870    *
871    * The desired width of the label, in characters. If this property is set to
872    * -1, the width will be calculated automatically.
873    *
874    * See the section on <link linkend="label-text-layout">text layout</link>
875    * for details of how #GtkLabel:width-chars and #GtkLabel:max-width-chars
876    * determine the width of ellipsized and wrapped labels.
877    *
878    * Since: 2.6
879    **/
880   g_object_class_install_property (gobject_class,
881                                    PROP_WIDTH_CHARS,
882                                    g_param_spec_int ("width-chars",
883                                                      P_("Width In Characters"),
884                                                      P_("The desired width of the label, in characters"),
885                                                      -1,
886                                                      G_MAXINT,
887                                                      -1,
888                                                      GTK_PARAM_READWRITE));
889   
890   /**
891    * GtkLabel:single-line-mode:
892    * 
893    * Whether the label is in single line mode. In single line mode,
894    * the height of the label does not depend on the actual text, it
895    * is always set to ascent + descent of the font. This can be an
896    * advantage in situations where resizing the label because of text 
897    * changes would be distracting, e.g. in a statusbar.
898    *
899    * Since: 2.6
900    **/
901   g_object_class_install_property (gobject_class,
902                                    PROP_SINGLE_LINE_MODE,
903                                    g_param_spec_boolean ("single-line-mode",
904                                                         P_("Single Line Mode"),
905                                                         P_("Whether the label is in single line mode"),
906                                                         FALSE,
907                                                         GTK_PARAM_READWRITE));
908
909   /**
910    * GtkLabel:angle:
911    * 
912    * The angle that the baseline of the label makes with the horizontal,
913    * in degrees, measured counterclockwise. An angle of 90 reads from
914    * from bottom to top, an angle of 270, from top to bottom. Ignored
915    * if the label is selectable, wrapped, or ellipsized.
916    *
917    * Since: 2.6
918    **/
919   g_object_class_install_property (gobject_class,
920                                    PROP_ANGLE,
921                                    g_param_spec_double ("angle",
922                                                         P_("Angle"),
923                                                         P_("Angle at which the label is rotated"),
924                                                         0.0,
925                                                         360.0,
926                                                         0.0, 
927                                                         GTK_PARAM_READWRITE));
928   
929   /**
930    * GtkLabel:max-width-chars:
931    * 
932    * The desired maximum width of the label, in characters. If this property 
933    * is set to -1, the width will be calculated automatically.
934    *
935    * See the section on <link linkend="label-text-layout">text layout</link>
936    * for details of how #GtkLabel:width-chars and #GtkLabel:max-width-chars
937    * determine the width of ellipsized and wrapped labels.
938    *
939    * Since: 2.6
940    **/
941   g_object_class_install_property (gobject_class,
942                                    PROP_MAX_WIDTH_CHARS,
943                                    g_param_spec_int ("max-width-chars",
944                                                      P_("Maximum Width In Characters"),
945                                                      P_("The desired maximum width of the label, in characters"),
946                                                      -1,
947                                                      G_MAXINT,
948                                                      -1,
949                                                      GTK_PARAM_READWRITE));
950
951   /**
952    * GtkLabel:track-visited-links:
953    *
954    * Set this property to %TRUE to make the label track which links
955    * have been clicked. It will then apply the ::visited-link-color
956    * color, instead of ::link-color.
957    *
958    * Since: 2.18
959    */
960   g_object_class_install_property (gobject_class,
961                                    PROP_TRACK_VISITED_LINKS,
962                                    g_param_spec_boolean ("track-visited-links",
963                                                          P_("Track visited links"),
964                                                          P_("Whether visited links should be tracked"),
965                                                          TRUE,
966                                                          GTK_PARAM_READWRITE));
967   /*
968    * Key bindings
969    */
970
971   binding_set = gtk_binding_set_by_class (class);
972
973   /* Moving the insertion point */
974   add_move_binding (binding_set, GDK_KEY_Right, 0,
975                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
976   
977   add_move_binding (binding_set, GDK_KEY_Left, 0,
978                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
979
980   add_move_binding (binding_set, GDK_KEY_KP_Right, 0,
981                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
982   
983   add_move_binding (binding_set, GDK_KEY_KP_Left, 0,
984                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
985   
986   add_move_binding (binding_set, GDK_KEY_f, GDK_CONTROL_MASK,
987                     GTK_MOVEMENT_LOGICAL_POSITIONS, 1);
988   
989   add_move_binding (binding_set, GDK_KEY_b, GDK_CONTROL_MASK,
990                     GTK_MOVEMENT_LOGICAL_POSITIONS, -1);
991   
992   add_move_binding (binding_set, GDK_KEY_Right, GDK_CONTROL_MASK,
993                     GTK_MOVEMENT_WORDS, 1);
994
995   add_move_binding (binding_set, GDK_KEY_Left, GDK_CONTROL_MASK,
996                     GTK_MOVEMENT_WORDS, -1);
997
998   add_move_binding (binding_set, GDK_KEY_KP_Right, GDK_CONTROL_MASK,
999                     GTK_MOVEMENT_WORDS, 1);
1000
1001   add_move_binding (binding_set, GDK_KEY_KP_Left, GDK_CONTROL_MASK,
1002                     GTK_MOVEMENT_WORDS, -1);
1003
1004   /* select all */
1005   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_CONTROL_MASK,
1006                                 "move-cursor", 3,
1007                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1008                                 G_TYPE_INT, -1,
1009                                 G_TYPE_BOOLEAN, FALSE);
1010
1011   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_CONTROL_MASK,
1012                                 "move-cursor", 3,
1013                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1014                                 G_TYPE_INT, 1,
1015                                 G_TYPE_BOOLEAN, TRUE);
1016
1017   gtk_binding_entry_add_signal (binding_set, GDK_KEY_slash, GDK_CONTROL_MASK,
1018                                 "move-cursor", 3,
1019                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1020                                 G_TYPE_INT, -1,
1021                                 G_TYPE_BOOLEAN, FALSE);
1022
1023   gtk_binding_entry_add_signal (binding_set, GDK_KEY_slash, GDK_CONTROL_MASK,
1024                                 "move-cursor", 3,
1025                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1026                                 G_TYPE_INT, 1,
1027                                 G_TYPE_BOOLEAN, TRUE);
1028
1029   /* unselect all */
1030   gtk_binding_entry_add_signal (binding_set, GDK_KEY_a, GDK_SHIFT_MASK | GDK_CONTROL_MASK,
1031                                 "move-cursor", 3,
1032                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1033                                 G_TYPE_INT, 0,
1034                                 G_TYPE_BOOLEAN, FALSE);
1035
1036   gtk_binding_entry_add_signal (binding_set, GDK_KEY_backslash, GDK_CONTROL_MASK,
1037                                 "move-cursor", 3,
1038                                 G_TYPE_ENUM, GTK_MOVEMENT_PARAGRAPH_ENDS,
1039                                 G_TYPE_INT, 0,
1040                                 G_TYPE_BOOLEAN, FALSE);
1041
1042   add_move_binding (binding_set, GDK_KEY_f, GDK_MOD1_MASK,
1043                     GTK_MOVEMENT_WORDS, 1);
1044
1045   add_move_binding (binding_set, GDK_KEY_b, GDK_MOD1_MASK,
1046                     GTK_MOVEMENT_WORDS, -1);
1047
1048   add_move_binding (binding_set, GDK_KEY_Home, 0,
1049                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1050
1051   add_move_binding (binding_set, GDK_KEY_End, 0,
1052                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1053
1054   add_move_binding (binding_set, GDK_KEY_KP_Home, 0,
1055                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
1056
1057   add_move_binding (binding_set, GDK_KEY_KP_End, 0,
1058                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
1059   
1060   add_move_binding (binding_set, GDK_KEY_Home, GDK_CONTROL_MASK,
1061                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1062
1063   add_move_binding (binding_set, GDK_KEY_End, GDK_CONTROL_MASK,
1064                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1065
1066   add_move_binding (binding_set, GDK_KEY_KP_Home, GDK_CONTROL_MASK,
1067                     GTK_MOVEMENT_BUFFER_ENDS, -1);
1068
1069   add_move_binding (binding_set, GDK_KEY_KP_End, GDK_CONTROL_MASK,
1070                     GTK_MOVEMENT_BUFFER_ENDS, 1);
1071
1072   /* copy */
1073   gtk_binding_entry_add_signal (binding_set, GDK_KEY_c, GDK_CONTROL_MASK,
1074                                 "copy-clipboard", 0);
1075
1076   gtk_binding_entry_add_signal (binding_set, GDK_KEY_Return, 0,
1077                                 "activate-current-link", 0);
1078   gtk_binding_entry_add_signal (binding_set, GDK_KEY_ISO_Enter, 0,
1079                                 "activate-current-link", 0);
1080   gtk_binding_entry_add_signal (binding_set, GDK_KEY_KP_Enter, 0,
1081                                 "activate-current-link", 0);
1082
1083   g_type_class_add_private (class, sizeof (GtkLabelPrivate));
1084
1085   gtk_widget_class_set_accessible_type (widget_class, GTK_TYPE_LABEL_ACCESSIBLE);
1086 }
1087
1088 static void 
1089 gtk_label_set_property (GObject      *object,
1090                         guint         prop_id,
1091                         const GValue *value,
1092                         GParamSpec   *pspec)
1093 {
1094   GtkLabel *label = GTK_LABEL (object);
1095
1096   switch (prop_id)
1097     {
1098     case PROP_LABEL:
1099       gtk_label_set_label (label, g_value_get_string (value));
1100       break;
1101     case PROP_ATTRIBUTES:
1102       gtk_label_set_attributes (label, g_value_get_boxed (value));
1103       break;
1104     case PROP_USE_MARKUP:
1105       gtk_label_set_use_markup (label, g_value_get_boolean (value));
1106       break;
1107     case PROP_USE_UNDERLINE:
1108       gtk_label_set_use_underline (label, g_value_get_boolean (value));
1109       break;
1110     case PROP_JUSTIFY:
1111       gtk_label_set_justify (label, g_value_get_enum (value));
1112       break;
1113     case PROP_PATTERN:
1114       gtk_label_set_pattern (label, g_value_get_string (value));
1115       break;
1116     case PROP_WRAP:
1117       gtk_label_set_line_wrap (label, g_value_get_boolean (value));
1118       break;      
1119     case PROP_WRAP_MODE:
1120       gtk_label_set_line_wrap_mode (label, g_value_get_enum (value));
1121       break;      
1122     case PROP_SELECTABLE:
1123       gtk_label_set_selectable (label, g_value_get_boolean (value));
1124       break;      
1125     case PROP_MNEMONIC_WIDGET:
1126       gtk_label_set_mnemonic_widget (label, (GtkWidget*) g_value_get_object (value));
1127       break;
1128     case PROP_ELLIPSIZE:
1129       gtk_label_set_ellipsize (label, g_value_get_enum (value));
1130       break;
1131     case PROP_WIDTH_CHARS:
1132       gtk_label_set_width_chars (label, g_value_get_int (value));
1133       break;
1134     case PROP_SINGLE_LINE_MODE:
1135       gtk_label_set_single_line_mode (label, g_value_get_boolean (value));
1136       break;      
1137     case PROP_ANGLE:
1138       gtk_label_set_angle (label, g_value_get_double (value));
1139       break;
1140     case PROP_MAX_WIDTH_CHARS:
1141       gtk_label_set_max_width_chars (label, g_value_get_int (value));
1142       break;
1143     case PROP_TRACK_VISITED_LINKS:
1144       gtk_label_set_track_visited_links (label, g_value_get_boolean (value));
1145       break;
1146     default:
1147       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1148       break;
1149     }
1150 }
1151
1152 static void 
1153 gtk_label_get_property (GObject     *object,
1154                         guint        prop_id,
1155                         GValue      *value,
1156                         GParamSpec  *pspec)
1157 {
1158   GtkLabel *label = GTK_LABEL (object);
1159   GtkLabelPrivate *priv = label->priv;
1160
1161   switch (prop_id)
1162     {
1163     case PROP_LABEL:
1164       g_value_set_string (value, priv->label);
1165       break;
1166     case PROP_ATTRIBUTES:
1167       g_value_set_boxed (value, priv->attrs);
1168       break;
1169     case PROP_USE_MARKUP:
1170       g_value_set_boolean (value, priv->use_markup);
1171       break;
1172     case PROP_USE_UNDERLINE:
1173       g_value_set_boolean (value, priv->use_underline);
1174       break;
1175     case PROP_JUSTIFY:
1176       g_value_set_enum (value, priv->jtype);
1177       break;
1178     case PROP_WRAP:
1179       g_value_set_boolean (value, priv->wrap);
1180       break;
1181     case PROP_WRAP_MODE:
1182       g_value_set_enum (value, priv->wrap_mode);
1183       break;
1184     case PROP_SELECTABLE:
1185       g_value_set_boolean (value, gtk_label_get_selectable (label));
1186       break;
1187     case PROP_MNEMONIC_KEYVAL:
1188       g_value_set_uint (value, priv->mnemonic_keyval);
1189       break;
1190     case PROP_MNEMONIC_WIDGET:
1191       g_value_set_object (value, (GObject*) priv->mnemonic_widget);
1192       break;
1193     case PROP_CURSOR_POSITION:
1194       g_value_set_int (value, _gtk_label_get_cursor_position (label));
1195       break;
1196     case PROP_SELECTION_BOUND:
1197       g_value_set_int (value, _gtk_label_get_selection_bound (label));
1198       break;
1199     case PROP_ELLIPSIZE:
1200       g_value_set_enum (value, priv->ellipsize);
1201       break;
1202     case PROP_WIDTH_CHARS:
1203       g_value_set_int (value, gtk_label_get_width_chars (label));
1204       break;
1205     case PROP_SINGLE_LINE_MODE:
1206       g_value_set_boolean (value, gtk_label_get_single_line_mode (label));
1207       break;
1208     case PROP_ANGLE:
1209       g_value_set_double (value, gtk_label_get_angle (label));
1210       break;
1211     case PROP_MAX_WIDTH_CHARS:
1212       g_value_set_int (value, gtk_label_get_max_width_chars (label));
1213       break;
1214     case PROP_TRACK_VISITED_LINKS:
1215       g_value_set_boolean (value, gtk_label_get_track_visited_links (label));
1216       break;
1217     default:
1218       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1219       break;
1220     }
1221 }
1222
1223 static void
1224 gtk_label_init (GtkLabel *label)
1225 {
1226   GtkLabelPrivate *priv;
1227
1228   label->priv = G_TYPE_INSTANCE_GET_PRIVATE (label,
1229                                              GTK_TYPE_LABEL,
1230                                              GtkLabelPrivate);
1231   priv = label->priv;
1232
1233   gtk_widget_set_has_window (GTK_WIDGET (label), FALSE);
1234
1235   priv->width_chars = -1;
1236   priv->max_width_chars = -1;
1237   priv->label = NULL;
1238
1239   priv->jtype = GTK_JUSTIFY_LEFT;
1240   priv->wrap = FALSE;
1241   priv->wrap_mode = PANGO_WRAP_WORD;
1242   priv->ellipsize = PANGO_ELLIPSIZE_NONE;
1243
1244   priv->use_underline = FALSE;
1245   priv->use_markup = FALSE;
1246   priv->pattern_set = FALSE;
1247   priv->track_links = TRUE;
1248
1249   priv->mnemonic_keyval = GDK_KEY_VoidSymbol;
1250   priv->layout = NULL;
1251   priv->text = NULL;
1252   priv->attrs = NULL;
1253
1254   priv->mnemonic_widget = NULL;
1255   priv->mnemonic_window = NULL;
1256
1257   priv->mnemonics_visible = TRUE;
1258
1259   gtk_label_set_text (label, "");
1260 }
1261
1262
1263 static void
1264 gtk_label_buildable_interface_init (GtkBuildableIface *iface)
1265 {
1266   buildable_parent_iface = g_type_interface_peek_parent (iface);
1267
1268   iface->custom_tag_start = gtk_label_buildable_custom_tag_start;
1269   iface->custom_finished = gtk_label_buildable_custom_finished;
1270 }
1271
1272 typedef struct {
1273   GtkBuilder    *builder;
1274   GObject       *object;
1275   PangoAttrList *attrs;
1276 } PangoParserData;
1277
1278 static PangoAttribute *
1279 attribute_from_text (GtkBuilder   *builder,
1280                      const gchar  *name, 
1281                      const gchar  *value,
1282                      GError      **error)
1283 {
1284   PangoAttribute *attribute = NULL;
1285   PangoAttrType   type;
1286   PangoLanguage  *language;
1287   PangoFontDescription *font_desc;
1288   GdkColor       *color;
1289   GValue          val = G_VALUE_INIT;
1290
1291   if (!gtk_builder_value_from_string_type (builder, PANGO_TYPE_ATTR_TYPE, name, &val, error))
1292     return NULL;
1293
1294   type = g_value_get_enum (&val);
1295   g_value_unset (&val);
1296
1297   switch (type)
1298     {
1299       /* PangoAttrLanguage */
1300     case PANGO_ATTR_LANGUAGE:
1301       if ((language = pango_language_from_string (value)))
1302         {
1303           attribute = pango_attr_language_new (language);
1304           g_value_init (&val, G_TYPE_INT);
1305         }
1306       break;
1307       /* PangoAttrInt */
1308     case PANGO_ATTR_STYLE:
1309       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_STYLE, value, &val, error))
1310         attribute = pango_attr_style_new (g_value_get_enum (&val));
1311       break;
1312     case PANGO_ATTR_WEIGHT:
1313       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_WEIGHT, value, &val, error))
1314         attribute = pango_attr_weight_new (g_value_get_enum (&val));
1315       break;
1316     case PANGO_ATTR_VARIANT:
1317       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_VARIANT, value, &val, error))
1318         attribute = pango_attr_variant_new (g_value_get_enum (&val));
1319       break;
1320     case PANGO_ATTR_STRETCH:
1321       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_STRETCH, value, &val, error))
1322         attribute = pango_attr_stretch_new (g_value_get_enum (&val));
1323       break;
1324     case PANGO_ATTR_UNDERLINE:
1325       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_UNDERLINE, value, &val, NULL))
1326         attribute = pango_attr_underline_new (g_value_get_enum (&val));
1327       else
1328         {
1329           /* XXX: allow boolean for backwards compat, so ignore error */
1330           /* Deprecate this somehow */
1331           g_value_unset (&val);
1332           if (gtk_builder_value_from_string_type (builder, G_TYPE_BOOLEAN, value, &val, error))
1333             attribute = pango_attr_underline_new (g_value_get_boolean (&val));
1334         }
1335       break;
1336     case PANGO_ATTR_STRIKETHROUGH:      
1337       if (gtk_builder_value_from_string_type (builder, G_TYPE_BOOLEAN, value, &val, error))
1338         attribute = pango_attr_strikethrough_new (g_value_get_boolean (&val));
1339       break;
1340     case PANGO_ATTR_GRAVITY:
1341       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_GRAVITY, value, &val, error))
1342         attribute = pango_attr_gravity_new (g_value_get_enum (&val));
1343       break;
1344     case PANGO_ATTR_GRAVITY_HINT:
1345       if (gtk_builder_value_from_string_type (builder, PANGO_TYPE_GRAVITY_HINT, 
1346                                               value, &val, error))
1347         attribute = pango_attr_gravity_hint_new (g_value_get_enum (&val));
1348       break;
1349       /* PangoAttrString */       
1350     case PANGO_ATTR_FAMILY:
1351       attribute = pango_attr_family_new (value);
1352       g_value_init (&val, G_TYPE_INT);
1353       break;
1354
1355       /* PangoAttrSize */         
1356     case PANGO_ATTR_SIZE:
1357       if (gtk_builder_value_from_string_type (builder, G_TYPE_INT, 
1358                                               value, &val, error))
1359         attribute = pango_attr_size_new (g_value_get_int (&val));
1360       break;
1361     case PANGO_ATTR_ABSOLUTE_SIZE:
1362       if (gtk_builder_value_from_string_type (builder, G_TYPE_INT, 
1363                                               value, &val, error))
1364         attribute = pango_attr_size_new_absolute (g_value_get_int (&val));
1365       break;
1366     
1367       /* PangoAttrFontDesc */
1368     case PANGO_ATTR_FONT_DESC:
1369       if ((font_desc = pango_font_description_from_string (value)))
1370         {
1371           attribute = pango_attr_font_desc_new (font_desc);
1372           pango_font_description_free (font_desc);
1373           g_value_init (&val, G_TYPE_INT);
1374         }
1375       break;
1376
1377       /* PangoAttrColor */
1378     case PANGO_ATTR_FOREGROUND:
1379       if (gtk_builder_value_from_string_type (builder, GDK_TYPE_COLOR, 
1380                                               value, &val, error))
1381         {
1382           color = g_value_get_boxed (&val);
1383           attribute = pango_attr_foreground_new (color->red, color->green, color->blue);
1384         }
1385       break;
1386     case PANGO_ATTR_BACKGROUND: 
1387       if (gtk_builder_value_from_string_type (builder, GDK_TYPE_COLOR, 
1388                                               value, &val, error))
1389         {
1390           color = g_value_get_boxed (&val);
1391           attribute = pango_attr_background_new (color->red, color->green, color->blue);
1392         }
1393       break;
1394     case PANGO_ATTR_UNDERLINE_COLOR:
1395       if (gtk_builder_value_from_string_type (builder, GDK_TYPE_COLOR, 
1396                                               value, &val, error))
1397         {
1398           color = g_value_get_boxed (&val);
1399           attribute = pango_attr_underline_color_new (color->red, color->green, color->blue);
1400         }
1401       break;
1402     case PANGO_ATTR_STRIKETHROUGH_COLOR:
1403       if (gtk_builder_value_from_string_type (builder, GDK_TYPE_COLOR, 
1404                                               value, &val, error))
1405         {
1406           color = g_value_get_boxed (&val);
1407           attribute = pango_attr_strikethrough_color_new (color->red, color->green, color->blue);
1408         }
1409       break;
1410       
1411       /* PangoAttrShape */
1412     case PANGO_ATTR_SHAPE:
1413       /* Unsupported for now */
1414       break;
1415       /* PangoAttrFloat */
1416     case PANGO_ATTR_SCALE:
1417       if (gtk_builder_value_from_string_type (builder, G_TYPE_DOUBLE, 
1418                                               value, &val, error))
1419         attribute = pango_attr_scale_new (g_value_get_double (&val));
1420       break;
1421
1422     case PANGO_ATTR_INVALID:
1423     case PANGO_ATTR_LETTER_SPACING:
1424     case PANGO_ATTR_RISE:
1425     case PANGO_ATTR_FALLBACK:
1426     default:
1427       break;
1428     }
1429
1430   g_value_unset (&val);
1431
1432   return attribute;
1433 }
1434
1435
1436 static void
1437 pango_start_element (GMarkupParseContext *context,
1438                      const gchar         *element_name,
1439                      const gchar        **names,
1440                      const gchar        **values,
1441                      gpointer             user_data,
1442                      GError             **error)
1443 {
1444   PangoParserData *data = (PangoParserData*)user_data;
1445   GValue val = G_VALUE_INIT;
1446   guint i;
1447   gint line_number, char_number;
1448
1449   if (strcmp (element_name, "attribute") == 0)
1450     {
1451       PangoAttribute *attr = NULL;
1452       const gchar *name = NULL;
1453       const gchar *value = NULL;
1454       const gchar *start = NULL;
1455       const gchar *end = NULL;
1456       guint start_val = 0;
1457       guint end_val   = G_MAXUINT;
1458
1459       for (i = 0; names[i]; i++)
1460         {
1461           if (strcmp (names[i], "name") == 0)
1462             name = values[i];
1463           else if (strcmp (names[i], "value") == 0)
1464             value = values[i];
1465           else if (strcmp (names[i], "start") == 0)
1466             start = values[i];
1467           else if (strcmp (names[i], "end") == 0)
1468             end = values[i];
1469           else
1470             {
1471               g_markup_parse_context_get_position (context,
1472                                                    &line_number,
1473                                                    &char_number);
1474               g_set_error (error,
1475                            GTK_BUILDER_ERROR,
1476                            GTK_BUILDER_ERROR_INVALID_ATTRIBUTE,
1477                            "%s:%d:%d '%s' is not a valid attribute of <%s>",
1478                            "<input>",
1479                            line_number, char_number, names[i], "attribute");
1480               return;
1481             }
1482         }
1483
1484       if (!name || !value)
1485         {
1486           g_markup_parse_context_get_position (context,
1487                                                &line_number,
1488                                                &char_number);
1489           g_set_error (error,
1490                        GTK_BUILDER_ERROR,
1491                        GTK_BUILDER_ERROR_MISSING_ATTRIBUTE,
1492                        "%s:%d:%d <%s> requires attribute \"%s\"",
1493                        "<input>",
1494                        line_number, char_number, "attribute",
1495                        name ? "value" : "name");
1496           return;
1497         }
1498
1499       if (start)
1500         {
1501           if (!gtk_builder_value_from_string_type (data->builder, G_TYPE_UINT, 
1502                                                    start, &val, error))
1503             return;
1504           start_val = g_value_get_uint (&val);
1505           g_value_unset (&val);
1506         }
1507
1508       if (end)
1509         {
1510           if (!gtk_builder_value_from_string_type (data->builder, G_TYPE_UINT, 
1511                                                    end, &val, error))
1512             return;
1513           end_val = g_value_get_uint (&val);
1514           g_value_unset (&val);
1515         }
1516
1517       attr = attribute_from_text (data->builder, name, value, error);
1518
1519       if (attr)
1520         {
1521           attr->start_index = start_val;
1522           attr->end_index   = end_val;
1523
1524           if (!data->attrs)
1525             data->attrs = pango_attr_list_new ();
1526
1527           pango_attr_list_insert (data->attrs, attr);
1528         }
1529     }
1530   else if (strcmp (element_name, "attributes") == 0)
1531     ;
1532   else
1533     g_warning ("Unsupported tag for GtkLabel: %s\n", element_name);
1534 }
1535
1536 static const GMarkupParser pango_parser =
1537   {
1538     pango_start_element,
1539   };
1540
1541 static gboolean
1542 gtk_label_buildable_custom_tag_start (GtkBuildable     *buildable,
1543                                       GtkBuilder       *builder,
1544                                       GObject          *child,
1545                                       const gchar      *tagname,
1546                                       GMarkupParser    *parser,
1547                                       gpointer         *data)
1548 {
1549   if (buildable_parent_iface->custom_tag_start (buildable, builder, child, 
1550                                                 tagname, parser, data))
1551     return TRUE;
1552
1553   if (strcmp (tagname, "attributes") == 0)
1554     {
1555       PangoParserData *parser_data;
1556
1557       parser_data = g_slice_new0 (PangoParserData);
1558       parser_data->builder = g_object_ref (builder);
1559       parser_data->object = g_object_ref (buildable);
1560       *parser = pango_parser;
1561       *data = parser_data;
1562       return TRUE;
1563     }
1564   return FALSE;
1565 }
1566
1567 static void
1568 gtk_label_buildable_custom_finished (GtkBuildable *buildable,
1569                                      GtkBuilder   *builder,
1570                                      GObject      *child,
1571                                      const gchar  *tagname,
1572                                      gpointer      user_data)
1573 {
1574   PangoParserData *data;
1575
1576   buildable_parent_iface->custom_finished (buildable, builder, child, 
1577                                            tagname, user_data);
1578
1579   if (strcmp (tagname, "attributes") == 0)
1580     {
1581       data = (PangoParserData*)user_data;
1582
1583       if (data->attrs)
1584         {
1585           gtk_label_set_attributes (GTK_LABEL (buildable), data->attrs);
1586           pango_attr_list_unref (data->attrs);
1587         }
1588
1589       g_object_unref (data->object);
1590       g_object_unref (data->builder);
1591       g_slice_free (PangoParserData, data);
1592     }
1593 }
1594
1595
1596 /**
1597  * gtk_label_new:
1598  * @str: The text of the label
1599  *
1600  * Creates a new label with the given text inside it. You can
1601  * pass %NULL to get an empty label widget.
1602  *
1603  * Return value: the new #GtkLabel
1604  **/
1605 GtkWidget*
1606 gtk_label_new (const gchar *str)
1607 {
1608   GtkLabel *label;
1609   
1610   label = g_object_new (GTK_TYPE_LABEL, NULL);
1611
1612   if (str && *str)
1613     gtk_label_set_text (label, str);
1614   
1615   return GTK_WIDGET (label);
1616 }
1617
1618 /**
1619  * gtk_label_new_with_mnemonic:
1620  * @str: The text of the label, with an underscore in front of the
1621  *       mnemonic character
1622  *
1623  * Creates a new #GtkLabel, containing the text in @str.
1624  *
1625  * If characters in @str are preceded by an underscore, they are
1626  * underlined. If you need a literal underscore character in a label, use
1627  * '__' (two underscores). The first underlined character represents a 
1628  * keyboard accelerator called a mnemonic. The mnemonic key can be used 
1629  * to activate another widget, chosen automatically, or explicitly using
1630  * gtk_label_set_mnemonic_widget().
1631  * 
1632  * If gtk_label_set_mnemonic_widget() is not called, then the first 
1633  * activatable ancestor of the #GtkLabel will be chosen as the mnemonic 
1634  * widget. For instance, if the label is inside a button or menu item, 
1635  * the button or menu item will automatically become the mnemonic widget 
1636  * and be activated by the mnemonic.
1637  *
1638  * Return value: the new #GtkLabel
1639  **/
1640 GtkWidget*
1641 gtk_label_new_with_mnemonic (const gchar *str)
1642 {
1643   GtkLabel *label;
1644   
1645   label = g_object_new (GTK_TYPE_LABEL, NULL);
1646
1647   if (str && *str)
1648     gtk_label_set_text_with_mnemonic (label, str);
1649   
1650   return GTK_WIDGET (label);
1651 }
1652
1653 static gboolean
1654 gtk_label_mnemonic_activate (GtkWidget *widget,
1655                              gboolean   group_cycling)
1656 {
1657   GtkLabel *label = GTK_LABEL (widget);
1658   GtkLabelPrivate *priv = label->priv;
1659   GtkWidget *parent;
1660
1661   if (priv->mnemonic_widget)
1662     return gtk_widget_mnemonic_activate (priv->mnemonic_widget, group_cycling);
1663
1664   /* Try to find the widget to activate by traversing the
1665    * widget's ancestry.
1666    */
1667   parent = gtk_widget_get_parent (widget);
1668
1669   if (GTK_IS_NOTEBOOK (parent))
1670     return FALSE;
1671   
1672   while (parent)
1673     {
1674       if (gtk_widget_get_can_focus (parent) ||
1675           (!group_cycling && GTK_WIDGET_GET_CLASS (parent)->activate_signal) ||
1676           GTK_IS_NOTEBOOK (gtk_widget_get_parent (parent)) ||
1677           GTK_IS_MENU_ITEM (parent))
1678         return gtk_widget_mnemonic_activate (parent, group_cycling);
1679       parent = gtk_widget_get_parent (parent);
1680     }
1681
1682   /* barf if there was nothing to activate */
1683   g_warning ("Couldn't find a target for a mnemonic activation.");
1684   gtk_widget_error_bell (widget);
1685
1686   return FALSE;
1687 }
1688
1689 static void
1690 gtk_label_setup_mnemonic (GtkLabel *label,
1691                           guint     last_key)
1692 {
1693   GtkLabelPrivate *priv = label->priv;
1694   GtkWidget *widget = GTK_WIDGET (label);
1695   GtkWidget *toplevel;
1696   GtkWidget *mnemonic_menu;
1697   
1698   mnemonic_menu = g_object_get_data (G_OBJECT (label), "gtk-mnemonic-menu");
1699   
1700   if (last_key != GDK_KEY_VoidSymbol)
1701     {
1702       if (priv->mnemonic_window)
1703         {
1704           gtk_window_remove_mnemonic  (priv->mnemonic_window,
1705                                        last_key,
1706                                        widget);
1707           priv->mnemonic_window = NULL;
1708         }
1709       if (mnemonic_menu)
1710         {
1711           _gtk_menu_shell_remove_mnemonic (GTK_MENU_SHELL (mnemonic_menu),
1712                                            last_key,
1713                                            widget);
1714           mnemonic_menu = NULL;
1715         }
1716     }
1717   
1718   if (priv->mnemonic_keyval == GDK_KEY_VoidSymbol)
1719       goto done;
1720
1721   connect_mnemonics_visible_notify (GTK_LABEL (widget));
1722
1723   toplevel = gtk_widget_get_toplevel (widget);
1724   if (gtk_widget_is_toplevel (toplevel))
1725     {
1726       GtkWidget *menu_shell;
1727       
1728       menu_shell = gtk_widget_get_ancestor (widget,
1729                                             GTK_TYPE_MENU_SHELL);
1730
1731       if (menu_shell)
1732         {
1733           _gtk_menu_shell_add_mnemonic (GTK_MENU_SHELL (menu_shell),
1734                                         priv->mnemonic_keyval,
1735                                         widget);
1736           mnemonic_menu = menu_shell;
1737         }
1738       
1739       if (!GTK_IS_MENU (menu_shell))
1740         {
1741           gtk_window_add_mnemonic (GTK_WINDOW (toplevel),
1742                                    priv->mnemonic_keyval,
1743                                    widget);
1744           priv->mnemonic_window = GTK_WINDOW (toplevel);
1745         }
1746     }
1747   
1748  done:
1749   g_object_set_data (G_OBJECT (label), I_("gtk-mnemonic-menu"), mnemonic_menu);
1750 }
1751
1752 static void
1753 gtk_label_hierarchy_changed (GtkWidget *widget,
1754                              GtkWidget *old_toplevel)
1755 {
1756   GtkLabel *label = GTK_LABEL (widget);
1757   GtkLabelPrivate *priv = label->priv;
1758
1759   gtk_label_setup_mnemonic (label, priv->mnemonic_keyval);
1760 }
1761
1762 static void
1763 label_shortcut_setting_apply (GtkLabel *label)
1764 {
1765   gtk_label_recalculate (label);
1766   if (GTK_IS_ACCEL_LABEL (label))
1767     gtk_accel_label_refetch (GTK_ACCEL_LABEL (label));
1768 }
1769
1770 static void
1771 label_shortcut_setting_traverse_container (GtkWidget *widget,
1772                                            gpointer   data)
1773 {
1774   if (GTK_IS_LABEL (widget))
1775     label_shortcut_setting_apply (GTK_LABEL (widget));
1776   else if (GTK_IS_CONTAINER (widget))
1777     gtk_container_forall (GTK_CONTAINER (widget),
1778                           label_shortcut_setting_traverse_container, data);
1779 }
1780
1781 static void
1782 label_shortcut_setting_changed (GtkSettings *settings)
1783 {
1784   GList *list, *l;
1785
1786   list = gtk_window_list_toplevels ();
1787
1788   for (l = list; l ; l = l->next)
1789     {
1790       GtkWidget *widget = l->data;
1791
1792       if (gtk_widget_get_settings (widget) == settings)
1793         gtk_container_forall (GTK_CONTAINER (widget),
1794                               label_shortcut_setting_traverse_container, NULL);
1795     }
1796
1797   g_list_free (list);
1798 }
1799
1800 static void
1801 mnemonics_visible_apply (GtkWidget *widget,
1802                          gboolean   mnemonics_visible)
1803 {
1804   GtkLabel *label = GTK_LABEL (widget);
1805   GtkLabelPrivate *priv = label->priv;
1806
1807   mnemonics_visible = mnemonics_visible != FALSE;
1808
1809   if (priv->mnemonics_visible != mnemonics_visible)
1810     {
1811       priv->mnemonics_visible = mnemonics_visible;
1812
1813       gtk_label_recalculate (label);
1814     }
1815 }
1816
1817 static void
1818 label_mnemonics_visible_traverse_container (GtkWidget *widget,
1819                                             gpointer   data)
1820 {
1821   gboolean mnemonics_visible = GPOINTER_TO_INT (data);
1822
1823   _gtk_label_mnemonics_visible_apply_recursively (widget, mnemonics_visible);
1824 }
1825
1826 void
1827 _gtk_label_mnemonics_visible_apply_recursively (GtkWidget *widget,
1828                                                 gboolean   mnemonics_visible)
1829 {
1830   if (GTK_IS_LABEL (widget))
1831     mnemonics_visible_apply (widget, mnemonics_visible);
1832   else if (GTK_IS_CONTAINER (widget))
1833     gtk_container_forall (GTK_CONTAINER (widget),
1834                           label_mnemonics_visible_traverse_container,
1835                           GINT_TO_POINTER (mnemonics_visible));
1836 }
1837
1838 static void
1839 label_mnemonics_visible_changed (GtkWindow  *window,
1840                                  GParamSpec *pspec,
1841                                  gpointer    data)
1842 {
1843   gboolean mnemonics_visible;
1844
1845   g_object_get (window, "mnemonics-visible", &mnemonics_visible, NULL);
1846
1847   gtk_container_forall (GTK_CONTAINER (window),
1848                         label_mnemonics_visible_traverse_container,
1849                         GINT_TO_POINTER (mnemonics_visible));
1850 }
1851
1852 static void
1853 gtk_label_screen_changed (GtkWidget *widget,
1854                           GdkScreen *old_screen)
1855 {
1856   GtkSettings *settings;
1857   gboolean shortcuts_connected;
1858
1859   if (!gtk_widget_has_screen (widget))
1860     return;
1861
1862   settings = gtk_widget_get_settings (widget);
1863
1864   shortcuts_connected =
1865     GPOINTER_TO_INT (g_object_get_data (G_OBJECT (settings),
1866                                         "gtk-label-shortcuts-connected"));
1867
1868   if (! shortcuts_connected)
1869     {
1870       g_signal_connect (settings, "notify::gtk-enable-mnemonics",
1871                         G_CALLBACK (label_shortcut_setting_changed),
1872                         NULL);
1873       g_signal_connect (settings, "notify::gtk-enable-accels",
1874                         G_CALLBACK (label_shortcut_setting_changed),
1875                         NULL);
1876
1877       g_object_set_data (G_OBJECT (settings), "gtk-label-shortcuts-connected",
1878                          GINT_TO_POINTER (TRUE));
1879     }
1880
1881   label_shortcut_setting_apply (GTK_LABEL (widget));
1882 }
1883
1884
1885 static void
1886 label_mnemonic_widget_weak_notify (gpointer      data,
1887                                    GObject      *where_the_object_was)
1888 {
1889   GtkLabel *label = data;
1890   GtkLabelPrivate *priv = label->priv;
1891
1892   priv->mnemonic_widget = NULL;
1893   g_object_notify (G_OBJECT (label), "mnemonic-widget");
1894 }
1895
1896 /**
1897  * gtk_label_set_mnemonic_widget:
1898  * @label: a #GtkLabel
1899  * @widget: (allow-none): the target #GtkWidget
1900  *
1901  * If the label has been set so that it has an mnemonic key (using
1902  * i.e. gtk_label_set_markup_with_mnemonic(),
1903  * gtk_label_set_text_with_mnemonic(), gtk_label_new_with_mnemonic()
1904  * or the "use_underline" property) the label can be associated with a
1905  * widget that is the target of the mnemonic. When the label is inside
1906  * a widget (like a #GtkButton or a #GtkNotebook tab) it is
1907  * automatically associated with the correct widget, but sometimes
1908  * (i.e. when the target is a #GtkEntry next to the label) you need to
1909  * set it explicitly using this function.
1910  *
1911  * The target widget will be accelerated by emitting the 
1912  * GtkWidget::mnemonic-activate signal on it. The default handler for 
1913  * this signal will activate the widget if there are no mnemonic collisions 
1914  * and toggle focus between the colliding widgets otherwise.
1915  **/
1916 void
1917 gtk_label_set_mnemonic_widget (GtkLabel  *label,
1918                                GtkWidget *widget)
1919 {
1920   GtkLabelPrivate *priv;
1921
1922   g_return_if_fail (GTK_IS_LABEL (label));
1923
1924   priv = label->priv;
1925
1926   if (widget)
1927     g_return_if_fail (GTK_IS_WIDGET (widget));
1928
1929   if (priv->mnemonic_widget)
1930     {
1931       gtk_widget_remove_mnemonic_label (priv->mnemonic_widget, GTK_WIDGET (label));
1932       g_object_weak_unref (G_OBJECT (priv->mnemonic_widget),
1933                            label_mnemonic_widget_weak_notify,
1934                            label);
1935     }
1936   priv->mnemonic_widget = widget;
1937   if (priv->mnemonic_widget)
1938     {
1939       g_object_weak_ref (G_OBJECT (priv->mnemonic_widget),
1940                          label_mnemonic_widget_weak_notify,
1941                          label);
1942       gtk_widget_add_mnemonic_label (priv->mnemonic_widget, GTK_WIDGET (label));
1943     }
1944   
1945   g_object_notify (G_OBJECT (label), "mnemonic-widget");
1946 }
1947
1948 /**
1949  * gtk_label_get_mnemonic_widget:
1950  * @label: a #GtkLabel
1951  *
1952  * Retrieves the target of the mnemonic (keyboard shortcut) of this
1953  * label. See gtk_label_set_mnemonic_widget().
1954  *
1955  * Return value: (transfer none): the target of the label's mnemonic,
1956  *     or %NULL if none has been set and the default algorithm will be used.
1957  **/
1958 GtkWidget *
1959 gtk_label_get_mnemonic_widget (GtkLabel *label)
1960 {
1961   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
1962
1963   return label->priv->mnemonic_widget;
1964 }
1965
1966 /**
1967  * gtk_label_get_mnemonic_keyval:
1968  * @label: a #GtkLabel
1969  *
1970  * If the label has been set so that it has an mnemonic key this function
1971  * returns the keyval used for the mnemonic accelerator. If there is no
1972  * mnemonic set up it returns #GDK_VoidSymbol.
1973  *
1974  * Returns: GDK keyval usable for accelerators, or #GDK_VoidSymbol
1975  **/
1976 guint
1977 gtk_label_get_mnemonic_keyval (GtkLabel *label)
1978 {
1979   g_return_val_if_fail (GTK_IS_LABEL (label), GDK_KEY_VoidSymbol);
1980
1981   return label->priv->mnemonic_keyval;
1982 }
1983
1984 static void
1985 gtk_label_set_text_internal (GtkLabel *label,
1986                              gchar    *str)
1987 {
1988   GtkLabelPrivate *priv = label->priv;
1989
1990   g_free (priv->text);
1991
1992   priv->text = str;
1993
1994   gtk_label_select_region_index (label, 0, 0);
1995 }
1996
1997 static void
1998 gtk_label_set_label_internal (GtkLabel *label,
1999                               gchar    *str)
2000 {
2001   GtkLabelPrivate *priv = label->priv;
2002
2003   g_free (priv->label);
2004
2005   priv->label = str;
2006
2007   g_object_notify (G_OBJECT (label), "label");
2008 }
2009
2010 static void
2011 gtk_label_set_use_markup_internal (GtkLabel *label,
2012                                    gboolean  val)
2013 {
2014   GtkLabelPrivate *priv = label->priv;
2015
2016   val = val != FALSE;
2017   if (priv->use_markup != val)
2018     {
2019       priv->use_markup = val;
2020
2021       g_object_notify (G_OBJECT (label), "use-markup");
2022     }
2023 }
2024
2025 static void
2026 gtk_label_set_use_underline_internal (GtkLabel *label,
2027                                       gboolean val)
2028 {
2029   GtkLabelPrivate *priv = label->priv;
2030
2031   val = val != FALSE;
2032   if (priv->use_underline != val)
2033     {
2034       priv->use_underline = val;
2035
2036       g_object_notify (G_OBJECT (label), "use-underline");
2037     }
2038 }
2039
2040 static void
2041 gtk_label_compose_effective_attrs (GtkLabel *label)
2042 {
2043   GtkLabelPrivate      *priv = label->priv;
2044   PangoAttrIterator *iter;
2045   PangoAttribute    *attr;
2046   GSList            *iter_attrs, *l;
2047
2048   if (priv->attrs)
2049     {
2050       if (priv->effective_attrs)
2051         {
2052           if ((iter = pango_attr_list_get_iterator (priv->attrs)))
2053             {
2054               do
2055                 {
2056                   iter_attrs = pango_attr_iterator_get_attrs (iter);
2057                   for (l = iter_attrs; l; l = l->next)
2058                     {
2059                       attr = l->data;
2060                       pango_attr_list_insert (priv->effective_attrs, attr);
2061                     }
2062                   g_slist_free (iter_attrs);
2063                 }
2064               while (pango_attr_iterator_next (iter));
2065               pango_attr_iterator_destroy (iter);
2066             }
2067         }
2068       else
2069         priv->effective_attrs =
2070           pango_attr_list_ref (priv->attrs);
2071     }
2072 }
2073
2074 static void
2075 gtk_label_set_attributes_internal (GtkLabel      *label,
2076                                    PangoAttrList *attrs)
2077 {
2078   GtkLabelPrivate *priv = label->priv;
2079
2080   if (attrs)
2081     pango_attr_list_ref (attrs);
2082
2083   if (priv->attrs)
2084     pango_attr_list_unref (priv->attrs);
2085   priv->attrs = attrs;
2086
2087   g_object_notify (G_OBJECT (label), "attributes");
2088 }
2089
2090
2091 /* Calculates text, attrs and mnemonic_keyval from
2092  * label, use_underline and use_markup
2093  */
2094 static void
2095 gtk_label_recalculate (GtkLabel *label)
2096 {
2097   GtkLabelPrivate *priv = label->priv;
2098   guint keyval = priv->mnemonic_keyval;
2099
2100   if (priv->use_markup)
2101     gtk_label_set_markup_internal (label, priv->label, priv->use_underline);
2102   else if (priv->use_underline)
2103     gtk_label_set_uline_text_internal (label, priv->label);
2104   else
2105     {
2106       if (!priv->pattern_set)
2107         {
2108           if (priv->effective_attrs)
2109             pango_attr_list_unref (priv->effective_attrs);
2110           priv->effective_attrs = NULL;
2111         }
2112       gtk_label_set_text_internal (label, g_strdup (priv->label));
2113     }
2114
2115   gtk_label_compose_effective_attrs (label);
2116
2117   if (!priv->use_underline)
2118     priv->mnemonic_keyval = GDK_KEY_VoidSymbol;
2119
2120   if (keyval != priv->mnemonic_keyval)
2121     {
2122       gtk_label_setup_mnemonic (label, keyval);
2123       g_object_notify (G_OBJECT (label), "mnemonic-keyval");
2124     }
2125
2126   gtk_label_clear_layout (label);
2127   gtk_label_clear_select_info (label);
2128   gtk_widget_queue_resize (GTK_WIDGET (label));
2129 }
2130
2131 /**
2132  * gtk_label_set_text:
2133  * @label: a #GtkLabel
2134  * @str: The text you want to set
2135  *
2136  * Sets the text within the #GtkLabel widget. It overwrites any text that
2137  * was there before.  
2138  *
2139  * This will also clear any previously set mnemonic accelerators.
2140  **/
2141 void
2142 gtk_label_set_text (GtkLabel    *label,
2143                     const gchar *str)
2144 {
2145   g_return_if_fail (GTK_IS_LABEL (label));
2146   
2147   g_object_freeze_notify (G_OBJECT (label));
2148
2149   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2150   gtk_label_set_use_markup_internal (label, FALSE);
2151   gtk_label_set_use_underline_internal (label, FALSE);
2152   
2153   gtk_label_recalculate (label);
2154
2155   g_object_thaw_notify (G_OBJECT (label));
2156 }
2157
2158 /**
2159  * gtk_label_set_attributes:
2160  * @label: a #GtkLabel
2161  * @attrs: a #PangoAttrList
2162  * 
2163  * Sets a #PangoAttrList; the attributes in the list are applied to the
2164  * label text. 
2165  *
2166  * <note><para>The attributes set with this function will be applied
2167  * and merged with any other attributes previously effected by way
2168  * of the #GtkLabel:use-underline or #GtkLabel:use-markup properties.
2169  * While it is not recommended to mix markup strings with manually set
2170  * attributes, if you must; know that the attributes will be applied
2171  * to the label after the markup string is parsed.</para></note>
2172  **/
2173 void
2174 gtk_label_set_attributes (GtkLabel         *label,
2175                           PangoAttrList    *attrs)
2176 {
2177   g_return_if_fail (GTK_IS_LABEL (label));
2178
2179   gtk_label_set_attributes_internal (label, attrs);
2180
2181   gtk_label_recalculate (label);
2182
2183   gtk_label_clear_layout (label);
2184   gtk_widget_queue_resize (GTK_WIDGET (label));
2185 }
2186
2187 /**
2188  * gtk_label_get_attributes:
2189  * @label: a #GtkLabel
2190  *
2191  * Gets the attribute list that was set on the label using
2192  * gtk_label_set_attributes(), if any. This function does
2193  * not reflect attributes that come from the labels markup
2194  * (see gtk_label_set_markup()). If you want to get the
2195  * effective attributes for the label, use
2196  * pango_layout_get_attribute (gtk_label_get_layout (label)).
2197  *
2198  * Return value: (transfer none): the attribute list, or %NULL
2199  *     if none was set.
2200  **/
2201 PangoAttrList *
2202 gtk_label_get_attributes (GtkLabel *label)
2203 {
2204   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
2205
2206   return label->priv->attrs;
2207 }
2208
2209 /**
2210  * gtk_label_set_label:
2211  * @label: a #GtkLabel
2212  * @str: the new text to set for the label
2213  *
2214  * Sets the text of the label. The label is interpreted as
2215  * including embedded underlines and/or Pango markup depending
2216  * on the values of the #GtkLabel:use-underline" and
2217  * #GtkLabel:use-markup properties.
2218  **/
2219 void
2220 gtk_label_set_label (GtkLabel    *label,
2221                      const gchar *str)
2222 {
2223   g_return_if_fail (GTK_IS_LABEL (label));
2224
2225   g_object_freeze_notify (G_OBJECT (label));
2226
2227   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2228   gtk_label_recalculate (label);
2229
2230   g_object_thaw_notify (G_OBJECT (label));
2231 }
2232
2233 /**
2234  * gtk_label_get_label:
2235  * @label: a #GtkLabel
2236  *
2237  * Fetches the text from a label widget including any embedded
2238  * underlines indicating mnemonics and Pango markup. (See
2239  * gtk_label_get_text()).
2240  *
2241  * Return value: the text of the label widget. This string is
2242  *   owned by the widget and must not be modified or freed.
2243  **/
2244 const gchar *
2245 gtk_label_get_label (GtkLabel *label)
2246 {
2247   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
2248
2249   return label->priv->label;
2250 }
2251
2252 typedef struct
2253 {
2254   GtkLabel *label;
2255   GList *links;
2256   GString *new_str;
2257   GdkColor *link_color;
2258   GdkColor *visited_link_color;
2259 } UriParserData;
2260
2261 static void
2262 start_element_handler (GMarkupParseContext  *context,
2263                        const gchar          *element_name,
2264                        const gchar         **attribute_names,
2265                        const gchar         **attribute_values,
2266                        gpointer              user_data,
2267                        GError              **error)
2268 {
2269   GtkLabelPrivate *priv;
2270   UriParserData *pdata = user_data;
2271
2272   if (strcmp (element_name, "a") == 0)
2273     {
2274       GtkLabelLink *link;
2275       const gchar *uri = NULL;
2276       const gchar *title = NULL;
2277       gboolean visited = FALSE;
2278       gint line_number;
2279       gint char_number;
2280       gint i;
2281       GdkColor *color = NULL;
2282
2283       g_markup_parse_context_get_position (context, &line_number, &char_number);
2284
2285       for (i = 0; attribute_names[i] != NULL; i++)
2286         {
2287           const gchar *attr = attribute_names[i];
2288
2289           if (strcmp (attr, "href") == 0)
2290             uri = attribute_values[i];
2291           else if (strcmp (attr, "title") == 0)
2292             title = attribute_values[i];
2293           else
2294             {
2295               g_set_error (error,
2296                            G_MARKUP_ERROR,
2297                            G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
2298                            "Attribute '%s' is not allowed on the <a> tag "
2299                            "on line %d char %d",
2300                             attr, line_number, char_number);
2301               return;
2302             }
2303         }
2304
2305       if (uri == NULL)
2306         {
2307           g_set_error (error,
2308                        G_MARKUP_ERROR,
2309                        G_MARKUP_ERROR_INVALID_CONTENT,
2310                        "Attribute 'href' was missing on the <a> tag "
2311                        "on line %d char %d",
2312                        line_number, char_number);
2313           return;
2314         }
2315
2316       visited = FALSE;
2317       priv = pdata->label->priv;
2318       if (priv->track_links && priv->select_info)
2319         {
2320           GList *l;
2321           for (l = priv->select_info->links; l; l = l->next)
2322             {
2323               link = l->data;
2324               if (strcmp (uri, link->uri) == 0)
2325                 {
2326                   visited = link->visited;
2327                   break;
2328                 }
2329             }
2330         }
2331
2332       if (visited)
2333         color = pdata->visited_link_color;
2334       else
2335         color = pdata->link_color;
2336
2337       g_string_append_printf (pdata->new_str,
2338                               "<span color=\"#%04x%04x%04x\" underline=\"single\">",
2339                               color->red,
2340                               color->green,
2341                               color->blue);
2342
2343       link = g_new0 (GtkLabelLink, 1);
2344       link->uri = g_strdup (uri);
2345       link->title = g_strdup (title);
2346       link->visited = visited;
2347       pdata->links = g_list_append (pdata->links, link);
2348     }
2349   else
2350     {
2351       gint i;
2352
2353       g_string_append_c (pdata->new_str, '<');
2354       g_string_append (pdata->new_str, element_name);
2355
2356       for (i = 0; attribute_names[i] != NULL; i++)
2357         {
2358           const gchar *attr  = attribute_names[i];
2359           const gchar *value = attribute_values[i];
2360           gchar *newvalue;
2361
2362           newvalue = g_markup_escape_text (value, -1);
2363
2364           g_string_append_c (pdata->new_str, ' ');
2365           g_string_append (pdata->new_str, attr);
2366           g_string_append (pdata->new_str, "=\"");
2367           g_string_append (pdata->new_str, newvalue);
2368           g_string_append_c (pdata->new_str, '\"');
2369
2370           g_free (newvalue);
2371         }
2372       g_string_append_c (pdata->new_str, '>');
2373     }
2374 }
2375
2376 static void
2377 end_element_handler (GMarkupParseContext  *context,
2378                      const gchar          *element_name,
2379                      gpointer              user_data,
2380                      GError              **error)
2381 {
2382   UriParserData *pdata = user_data;
2383
2384   if (!strcmp (element_name, "a"))
2385     g_string_append (pdata->new_str, "</span>");
2386   else
2387     {
2388       g_string_append (pdata->new_str, "</");
2389       g_string_append (pdata->new_str, element_name);
2390       g_string_append_c (pdata->new_str, '>');
2391     }
2392 }
2393
2394 static void
2395 text_handler (GMarkupParseContext  *context,
2396               const gchar          *text,
2397               gsize                 text_len,
2398               gpointer              user_data,
2399               GError              **error)
2400 {
2401   UriParserData *pdata = user_data;
2402   gchar *newtext;
2403
2404   newtext = g_markup_escape_text (text, text_len);
2405   g_string_append (pdata->new_str, newtext);
2406   g_free (newtext);
2407 }
2408
2409 static const GMarkupParser markup_parser =
2410 {
2411   start_element_handler,
2412   end_element_handler,
2413   text_handler,
2414   NULL,
2415   NULL
2416 };
2417
2418 static gboolean
2419 xml_isspace (gchar c)
2420 {
2421   return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
2422 }
2423
2424 static void
2425 link_free (GtkLabelLink *link)
2426 {
2427   g_free (link->uri);
2428   g_free (link->title);
2429   g_free (link);
2430 }
2431
2432 static void
2433 gtk_label_get_link_colors (GtkWidget  *widget,
2434                            GdkColor  **link_color,
2435                            GdkColor  **visited_link_color)
2436 {
2437   GtkStyleContext *context;
2438
2439   context = gtk_widget_get_style_context (widget);
2440   gtk_style_context_get_style (context,
2441                                "link-color", link_color,
2442                                "visited-link-color", visited_link_color,
2443                                 NULL);
2444   if (!*link_color)
2445     *link_color = gdk_color_copy (&default_link_color);
2446   if (!*visited_link_color)
2447     *visited_link_color = gdk_color_copy (&default_visited_link_color);
2448 }
2449
2450 static gboolean
2451 parse_uri_markup (GtkLabel     *label,
2452                   const gchar  *str,
2453                   gchar       **new_str,
2454                   GList       **links,
2455                   GError      **error)
2456 {
2457   GMarkupParseContext *context = NULL;
2458   const gchar *p, *end;
2459   gboolean needs_root = TRUE;
2460   gsize length;
2461   UriParserData pdata;
2462
2463   length = strlen (str);
2464   p = str;
2465   end = str + length;
2466
2467   pdata.label = label;
2468   pdata.links = NULL;
2469   pdata.new_str = g_string_sized_new (length);
2470
2471   gtk_label_get_link_colors (GTK_WIDGET (label), &pdata.link_color, &pdata.visited_link_color);
2472
2473   while (p != end && xml_isspace (*p))
2474     p++;
2475
2476   if (end - p >= 8 && strncmp (p, "<markup>", 8) == 0)
2477     needs_root = FALSE;
2478
2479   context = g_markup_parse_context_new (&markup_parser, 0, &pdata, NULL);
2480
2481   if (needs_root)
2482     {
2483       if (!g_markup_parse_context_parse (context, "<markup>", -1, error))
2484         goto failed;
2485     }
2486
2487   if (!g_markup_parse_context_parse (context, str, length, error))
2488     goto failed;
2489
2490   if (needs_root)
2491     {
2492       if (!g_markup_parse_context_parse (context, "</markup>", -1, error))
2493         goto failed;
2494     }
2495
2496   if (!g_markup_parse_context_end_parse (context, error))
2497     goto failed;
2498
2499   g_markup_parse_context_free (context);
2500
2501   *new_str = g_string_free (pdata.new_str, FALSE);
2502   *links = pdata.links;
2503
2504   gdk_color_free (pdata.link_color);
2505   gdk_color_free (pdata.visited_link_color);
2506
2507   return TRUE;
2508
2509 failed:
2510   g_markup_parse_context_free (context);
2511   g_string_free (pdata.new_str, TRUE);
2512   g_list_foreach (pdata.links, (GFunc)link_free, NULL);
2513   g_list_free (pdata.links);
2514   gdk_color_free (pdata.link_color);
2515   gdk_color_free (pdata.visited_link_color);
2516
2517   return FALSE;
2518 }
2519
2520 static void
2521 gtk_label_ensure_has_tooltip (GtkLabel *label)
2522 {
2523   GtkLabelPrivate *priv = label->priv;
2524   GList *l;
2525   gboolean has_tooltip = FALSE;
2526
2527   for (l = priv->select_info->links; l; l = l->next)
2528     {
2529       GtkLabelLink *link = l->data;
2530       if (link->title)
2531         {
2532           has_tooltip = TRUE;
2533           break;
2534         }
2535     }
2536
2537   gtk_widget_set_has_tooltip (GTK_WIDGET (label), has_tooltip);
2538 }
2539
2540 static void
2541 gtk_label_set_markup_internal (GtkLabel    *label,
2542                                const gchar *str,
2543                                gboolean     with_uline)
2544 {
2545   GtkLabelPrivate *priv = label->priv;
2546   gchar *text = NULL;
2547   GError *error = NULL;
2548   PangoAttrList *attrs = NULL;
2549   gunichar accel_char = 0;
2550   gchar *new_str;
2551   GList *links = NULL;
2552
2553   if (!parse_uri_markup (label, str, &new_str, &links, &error))
2554     {
2555       g_warning ("Failed to set text from markup due to error parsing markup: %s",
2556                  error->message);
2557       g_error_free (error);
2558       return;
2559     }
2560
2561   gtk_label_clear_links (label);
2562   if (links)
2563     {
2564       gtk_label_ensure_select_info (label);
2565       priv->select_info->links = links;
2566       gtk_label_ensure_has_tooltip (label);
2567     }
2568
2569   if (with_uline)
2570     {
2571       gboolean enable_mnemonics;
2572       gboolean auto_mnemonics;
2573
2574       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
2575                     "gtk-enable-mnemonics", &enable_mnemonics,
2576                     "gtk-auto-mnemonics", &auto_mnemonics,
2577                     NULL);
2578
2579       if (!(enable_mnemonics && priv->mnemonics_visible &&
2580             (!auto_mnemonics ||
2581              (gtk_widget_is_sensitive (GTK_WIDGET (label)) &&
2582               (!priv->mnemonic_widget ||
2583                gtk_widget_is_sensitive (priv->mnemonic_widget))))))
2584         {
2585           gchar *tmp;
2586           gchar *pattern;
2587           guint key;
2588
2589           if (separate_uline_pattern (new_str, &key, &tmp, &pattern))
2590             {
2591               g_free (new_str);
2592               new_str = tmp;
2593               g_free (pattern);
2594             }
2595         }
2596     }
2597
2598   if (!pango_parse_markup (new_str,
2599                            -1,
2600                            with_uline ? '_' : 0,
2601                            &attrs,
2602                            &text,
2603                            with_uline ? &accel_char : NULL,
2604                            &error))
2605     {
2606       g_warning ("Failed to set text from markup due to error parsing markup: %s",
2607                  error->message);
2608       g_free (new_str);
2609       g_error_free (error);
2610       return;
2611     }
2612
2613   g_free (new_str);
2614
2615   if (text)
2616     gtk_label_set_text_internal (label, text);
2617
2618   if (attrs)
2619     {
2620       if (priv->effective_attrs)
2621         pango_attr_list_unref (priv->effective_attrs);
2622       priv->effective_attrs = attrs;
2623     }
2624
2625   if (accel_char != 0)
2626     priv->mnemonic_keyval = gdk_keyval_to_lower (gdk_unicode_to_keyval (accel_char));
2627   else
2628     priv->mnemonic_keyval = GDK_KEY_VoidSymbol;
2629 }
2630
2631 /**
2632  * gtk_label_set_markup:
2633  * @label: a #GtkLabel
2634  * @str: a markup string (see <link linkend="PangoMarkupFormat">Pango markup format</link>)
2635  * 
2636  * Parses @str which is marked up with the <link
2637  * linkend="PangoMarkupFormat">Pango text markup language</link>, setting the
2638  * label's text and attribute list based on the parse results. If the @str is
2639  * external data, you may need to escape it with g_markup_escape_text() or
2640  * g_markup_printf_escaped()<!-- -->:
2641  * |[
2642  * char *markup;
2643  *
2644  * markup = g_markup_printf_escaped ("&lt;span style=\"italic\"&gt;&percnt;s&lt;/span&gt;", str);
2645  * gtk_label_set_markup (GTK_LABEL (label), markup);
2646  * g_free (markup);
2647  * ]|
2648  **/
2649 void
2650 gtk_label_set_markup (GtkLabel    *label,
2651                       const gchar *str)
2652 {
2653   g_return_if_fail (GTK_IS_LABEL (label));
2654
2655   g_object_freeze_notify (G_OBJECT (label));
2656
2657   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2658   gtk_label_set_use_markup_internal (label, TRUE);
2659   gtk_label_set_use_underline_internal (label, FALSE);
2660
2661   gtk_label_recalculate (label);
2662
2663   g_object_thaw_notify (G_OBJECT (label));
2664 }
2665
2666 /**
2667  * gtk_label_set_markup_with_mnemonic:
2668  * @label: a #GtkLabel
2669  * @str: a markup string (see
2670  *     <link linkend="PangoMarkupFormat">Pango markup format</link>)
2671  *
2672  * Parses @str which is marked up with the
2673  * <link linkend="PangoMarkupFormat">Pango text markup language</link>,
2674  * setting the label's text and attribute list based on the parse results.
2675  * If characters in @str are preceded by an underscore, they are underlined
2676  * indicating that they represent a keyboard accelerator called a mnemonic.
2677  *
2678  * The mnemonic key can be used to activate another widget, chosen
2679  * automatically, or explicitly using gtk_label_set_mnemonic_widget().
2680  */
2681 void
2682 gtk_label_set_markup_with_mnemonic (GtkLabel    *label,
2683                                     const gchar *str)
2684 {
2685   g_return_if_fail (GTK_IS_LABEL (label));
2686
2687   g_object_freeze_notify (G_OBJECT (label));
2688
2689   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2690   gtk_label_set_use_markup_internal (label, TRUE);
2691   gtk_label_set_use_underline_internal (label, TRUE);
2692
2693   gtk_label_recalculate (label);
2694
2695   g_object_thaw_notify (G_OBJECT (label));
2696 }
2697
2698 /**
2699  * gtk_label_get_text:
2700  * @label: a #GtkLabel
2701  * 
2702  * Fetches the text from a label widget, as displayed on the
2703  * screen. This does not include any embedded underlines
2704  * indicating mnemonics or Pango markup. (See gtk_label_get_label())
2705  * 
2706  * Return value: the text in the label widget. This is the internal
2707  *   string used by the label, and must not be modified.
2708  **/
2709 const gchar *
2710 gtk_label_get_text (GtkLabel *label)
2711 {
2712   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
2713
2714   return label->priv->text;
2715 }
2716
2717 static PangoAttrList *
2718 gtk_label_pattern_to_attrs (GtkLabel      *label,
2719                             const gchar   *pattern)
2720 {
2721   GtkLabelPrivate *priv = label->priv;
2722   const char *start;
2723   const char *p = priv->text;
2724   const char *q = pattern;
2725   PangoAttrList *attrs;
2726
2727   attrs = pango_attr_list_new ();
2728
2729   while (1)
2730     {
2731       while (*p && *q && *q != '_')
2732         {
2733           p = g_utf8_next_char (p);
2734           q++;
2735         }
2736       start = p;
2737       while (*p && *q && *q == '_')
2738         {
2739           p = g_utf8_next_char (p);
2740           q++;
2741         }
2742       
2743       if (p > start)
2744         {
2745           PangoAttribute *attr = pango_attr_underline_new (PANGO_UNDERLINE_LOW);
2746           attr->start_index = start - priv->text;
2747           attr->end_index = p - priv->text;
2748           
2749           pango_attr_list_insert (attrs, attr);
2750         }
2751       else
2752         break;
2753     }
2754
2755   return attrs;
2756 }
2757
2758 static void
2759 gtk_label_set_pattern_internal (GtkLabel    *label,
2760                                 const gchar *pattern,
2761                                 gboolean     is_mnemonic)
2762 {
2763   GtkLabelPrivate *priv = label->priv;
2764   PangoAttrList *attrs;
2765   gboolean enable_mnemonics;
2766   gboolean auto_mnemonics;
2767
2768   if (priv->pattern_set)
2769     return;
2770
2771   if (is_mnemonic)
2772     {
2773       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
2774                     "gtk-enable-mnemonics", &enable_mnemonics,
2775                     "gtk-auto-mnemonics", &auto_mnemonics,
2776                     NULL);
2777
2778       if (enable_mnemonics && priv->mnemonics_visible && pattern &&
2779           (!auto_mnemonics ||
2780            (gtk_widget_is_sensitive (GTK_WIDGET (label)) &&
2781             (!priv->mnemonic_widget ||
2782              gtk_widget_is_sensitive (priv->mnemonic_widget)))))
2783         attrs = gtk_label_pattern_to_attrs (label, pattern);
2784       else
2785         attrs = NULL;
2786     }
2787   else
2788     attrs = gtk_label_pattern_to_attrs (label, pattern);
2789
2790   if (priv->effective_attrs)
2791     pango_attr_list_unref (priv->effective_attrs);
2792   priv->effective_attrs = attrs;
2793 }
2794
2795 /**
2796  * gtk_label_set_pattern:
2797  * @label: The #GtkLabel you want to set the pattern to.
2798  * @pattern: The pattern as described above.
2799  *
2800  * The pattern of underlines you want under the existing text within the
2801  * #GtkLabel widget.  For example if the current text of the label says
2802  * "FooBarBaz" passing a pattern of "___   ___" will underline
2803  * "Foo" and "Baz" but not "Bar".
2804  */
2805 void
2806 gtk_label_set_pattern (GtkLabel    *label,
2807                        const gchar *pattern)
2808 {
2809   GtkLabelPrivate *priv;
2810
2811   g_return_if_fail (GTK_IS_LABEL (label));
2812
2813   priv = label->priv;
2814
2815   priv->pattern_set = FALSE;
2816
2817   if (pattern)
2818     {
2819       gtk_label_set_pattern_internal (label, pattern, FALSE);
2820       priv->pattern_set = TRUE;
2821     }
2822   else
2823     gtk_label_recalculate (label);
2824
2825   gtk_label_clear_layout (label);
2826   gtk_widget_queue_resize (GTK_WIDGET (label));
2827 }
2828
2829
2830 /**
2831  * gtk_label_set_justify:
2832  * @label: a #GtkLabel
2833  * @jtype: a #GtkJustification
2834  *
2835  * Sets the alignment of the lines in the text of the label relative to
2836  * each other. %GTK_JUSTIFY_LEFT is the default value when the
2837  * widget is first created with gtk_label_new(). If you instead want
2838  * to set the alignment of the label as a whole, use
2839  * gtk_misc_set_alignment() instead. gtk_label_set_justify() has no
2840  * effect on labels containing only a single line.
2841  **/
2842 void
2843 gtk_label_set_justify (GtkLabel        *label,
2844                        GtkJustification jtype)
2845 {
2846   GtkLabelPrivate *priv;
2847
2848   g_return_if_fail (GTK_IS_LABEL (label));
2849   g_return_if_fail (jtype >= GTK_JUSTIFY_LEFT && jtype <= GTK_JUSTIFY_FILL);
2850
2851   priv = label->priv;
2852
2853   if ((GtkJustification) priv->jtype != jtype)
2854     {
2855       priv->jtype = jtype;
2856
2857       /* No real need to be this drastic, but easier than duplicating the code */
2858       gtk_label_clear_layout (label);
2859       
2860       g_object_notify (G_OBJECT (label), "justify");
2861       gtk_widget_queue_resize (GTK_WIDGET (label));
2862     }
2863 }
2864
2865 /**
2866  * gtk_label_get_justify:
2867  * @label: a #GtkLabel
2868  *
2869  * Returns the justification of the label. See gtk_label_set_justify().
2870  *
2871  * Return value: #GtkJustification
2872  **/
2873 GtkJustification
2874 gtk_label_get_justify (GtkLabel *label)
2875 {
2876   g_return_val_if_fail (GTK_IS_LABEL (label), 0);
2877
2878   return label->priv->jtype;
2879 }
2880
2881 /**
2882  * gtk_label_set_ellipsize:
2883  * @label: a #GtkLabel
2884  * @mode: a #PangoEllipsizeMode
2885  *
2886  * Sets the mode used to ellipsize (add an ellipsis: "...") to the text 
2887  * if there is not enough space to render the entire string.
2888  *
2889  * Since: 2.6
2890  **/
2891 void
2892 gtk_label_set_ellipsize (GtkLabel          *label,
2893                          PangoEllipsizeMode mode)
2894 {
2895   GtkLabelPrivate *priv;
2896
2897   g_return_if_fail (GTK_IS_LABEL (label));
2898   g_return_if_fail (mode >= PANGO_ELLIPSIZE_NONE && mode <= PANGO_ELLIPSIZE_END);
2899
2900   priv = label->priv;
2901
2902   if ((PangoEllipsizeMode) priv->ellipsize != mode)
2903     {
2904       priv->ellipsize = mode;
2905
2906       /* No real need to be this drastic, but easier than duplicating the code */
2907       gtk_label_clear_layout (label);
2908       
2909       g_object_notify (G_OBJECT (label), "ellipsize");
2910       gtk_widget_queue_resize (GTK_WIDGET (label));
2911     }
2912 }
2913
2914 /**
2915  * gtk_label_get_ellipsize:
2916  * @label: a #GtkLabel
2917  *
2918  * Returns the ellipsizing position of the label. See gtk_label_set_ellipsize().
2919  *
2920  * Return value: #PangoEllipsizeMode
2921  *
2922  * Since: 2.6
2923  **/
2924 PangoEllipsizeMode
2925 gtk_label_get_ellipsize (GtkLabel *label)
2926 {
2927   g_return_val_if_fail (GTK_IS_LABEL (label), PANGO_ELLIPSIZE_NONE);
2928
2929   return label->priv->ellipsize;
2930 }
2931
2932 /**
2933  * gtk_label_set_width_chars:
2934  * @label: a #GtkLabel
2935  * @n_chars: the new desired width, in characters.
2936  * 
2937  * Sets the desired width in characters of @label to @n_chars.
2938  * 
2939  * Since: 2.6
2940  **/
2941 void
2942 gtk_label_set_width_chars (GtkLabel *label,
2943                            gint      n_chars)
2944 {
2945   GtkLabelPrivate *priv;
2946
2947   g_return_if_fail (GTK_IS_LABEL (label));
2948
2949   priv = label->priv;
2950
2951   if (priv->width_chars != n_chars)
2952     {
2953       priv->width_chars = n_chars;
2954       g_object_notify (G_OBJECT (label), "width-chars");
2955       gtk_widget_queue_resize (GTK_WIDGET (label));
2956     }
2957 }
2958
2959 /**
2960  * gtk_label_get_width_chars:
2961  * @label: a #GtkLabel
2962  * 
2963  * Retrieves the desired width of @label, in characters. See
2964  * gtk_label_set_width_chars().
2965  * 
2966  * Return value: the width of the label in characters.
2967  * 
2968  * Since: 2.6
2969  **/
2970 gint
2971 gtk_label_get_width_chars (GtkLabel *label)
2972 {
2973   g_return_val_if_fail (GTK_IS_LABEL (label), -1);
2974
2975   return label->priv->width_chars;
2976 }
2977
2978 /**
2979  * gtk_label_set_max_width_chars:
2980  * @label: a #GtkLabel
2981  * @n_chars: the new desired maximum width, in characters.
2982  * 
2983  * Sets the desired maximum width in characters of @label to @n_chars.
2984  * 
2985  * Since: 2.6
2986  **/
2987 void
2988 gtk_label_set_max_width_chars (GtkLabel *label,
2989                                gint      n_chars)
2990 {
2991   GtkLabelPrivate *priv;
2992
2993   g_return_if_fail (GTK_IS_LABEL (label));
2994
2995   priv = label->priv;
2996
2997   if (priv->max_width_chars != n_chars)
2998     {
2999       priv->max_width_chars = n_chars;
3000
3001       g_object_notify (G_OBJECT (label), "max-width-chars");
3002       gtk_widget_queue_resize (GTK_WIDGET (label));
3003     }
3004 }
3005
3006 /**
3007  * gtk_label_get_max_width_chars:
3008  * @label: a #GtkLabel
3009  * 
3010  * Retrieves the desired maximum width of @label, in characters. See
3011  * gtk_label_set_width_chars().
3012  * 
3013  * Return value: the maximum width of the label in characters.
3014  * 
3015  * Since: 2.6
3016  **/
3017 gint
3018 gtk_label_get_max_width_chars (GtkLabel *label)
3019 {
3020   g_return_val_if_fail (GTK_IS_LABEL (label), -1);
3021
3022   return label->priv->max_width_chars;
3023 }
3024
3025 /**
3026  * gtk_label_set_line_wrap:
3027  * @label: a #GtkLabel
3028  * @wrap: the setting
3029  *
3030  * Toggles line wrapping within the #GtkLabel widget. %TRUE makes it break
3031  * lines if text exceeds the widget's size. %FALSE lets the text get cut off
3032  * by the edge of the widget if it exceeds the widget size.
3033  *
3034  * Note that setting line wrapping to %TRUE does not make the label
3035  * wrap at its parent container's width, because GTK+ widgets
3036  * conceptually can't make their requisition depend on the parent
3037  * container's size. For a label that wraps at a specific position,
3038  * set the label's width using gtk_widget_set_size_request().
3039  **/
3040 void
3041 gtk_label_set_line_wrap (GtkLabel *label,
3042                          gboolean  wrap)
3043 {
3044   GtkLabelPrivate *priv;
3045
3046   g_return_if_fail (GTK_IS_LABEL (label));
3047
3048   priv = label->priv;
3049
3050   wrap = wrap != FALSE;
3051
3052   if (priv->wrap != wrap)
3053     {
3054       priv->wrap = wrap;
3055
3056       gtk_label_clear_layout (label);
3057       gtk_widget_queue_resize (GTK_WIDGET (label));
3058       g_object_notify (G_OBJECT (label), "wrap");
3059     }
3060 }
3061
3062 /**
3063  * gtk_label_get_line_wrap:
3064  * @label: a #GtkLabel
3065  *
3066  * Returns whether lines in the label are automatically wrapped. 
3067  * See gtk_label_set_line_wrap().
3068  *
3069  * Return value: %TRUE if the lines of the label are automatically wrapped.
3070  */
3071 gboolean
3072 gtk_label_get_line_wrap (GtkLabel *label)
3073 {
3074   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3075
3076   return label->priv->wrap;
3077 }
3078
3079 /**
3080  * gtk_label_set_line_wrap_mode:
3081  * @label: a #GtkLabel
3082  * @wrap_mode: the line wrapping mode
3083  *
3084  * If line wrapping is on (see gtk_label_set_line_wrap()) this controls how
3085  * the line wrapping is done. The default is %PANGO_WRAP_WORD which means
3086  * wrap on word boundaries.
3087  *
3088  * Since: 2.10
3089  **/
3090 void
3091 gtk_label_set_line_wrap_mode (GtkLabel *label,
3092                               PangoWrapMode wrap_mode)
3093 {
3094   GtkLabelPrivate *priv;
3095
3096   g_return_if_fail (GTK_IS_LABEL (label));
3097
3098   priv = label->priv;
3099
3100   if (priv->wrap_mode != wrap_mode)
3101     {
3102       priv->wrap_mode = wrap_mode;
3103       g_object_notify (G_OBJECT (label), "wrap-mode");
3104       
3105       gtk_widget_queue_resize (GTK_WIDGET (label));
3106     }
3107 }
3108
3109 /**
3110  * gtk_label_get_line_wrap_mode:
3111  * @label: a #GtkLabel
3112  *
3113  * Returns line wrap mode used by the label. See gtk_label_set_line_wrap_mode().
3114  *
3115  * Return value: %TRUE if the lines of the label are automatically wrapped.
3116  *
3117  * Since: 2.10
3118  */
3119 PangoWrapMode
3120 gtk_label_get_line_wrap_mode (GtkLabel *label)
3121 {
3122   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3123
3124   return label->priv->wrap_mode;
3125 }
3126
3127 static void
3128 gtk_label_destroy (GtkWidget *widget)
3129 {
3130   GtkLabel *label = GTK_LABEL (widget);
3131
3132   gtk_label_set_mnemonic_widget (label, NULL);
3133
3134   GTK_WIDGET_CLASS (gtk_label_parent_class)->destroy (widget);
3135 }
3136
3137 static void
3138 gtk_label_finalize (GObject *object)
3139 {
3140   GtkLabel *label = GTK_LABEL (object);
3141   GtkLabelPrivate *priv = label->priv;
3142
3143   g_free (priv->label);
3144   g_free (priv->text);
3145
3146   if (priv->layout)
3147     g_object_unref (priv->layout);
3148
3149   if (priv->attrs)
3150     pango_attr_list_unref (priv->attrs);
3151
3152   if (priv->effective_attrs)
3153     pango_attr_list_unref (priv->effective_attrs);
3154
3155   gtk_label_clear_links (label);
3156   g_free (priv->select_info);
3157
3158   G_OBJECT_CLASS (gtk_label_parent_class)->finalize (object);
3159 }
3160
3161 static void
3162 gtk_label_clear_layout (GtkLabel *label)
3163 {
3164   GtkLabelPrivate *priv = label->priv;
3165
3166   if (priv->layout)
3167     {
3168       g_object_unref (priv->layout);
3169       priv->layout = NULL;
3170
3171       //gtk_label_clear_links (label);
3172     }
3173 }
3174
3175 static PangoFontMetrics *
3176 get_font_metrics (PangoContext *context, GtkWidget *widget)
3177 {
3178   GtkStyleContext *style_context;
3179   const PangoFontDescription *font;
3180   PangoFontMetrics *retval;
3181
3182   style_context = gtk_widget_get_style_context (widget);
3183   font = gtk_style_context_get_font (style_context, GTK_STATE_FLAG_NORMAL);
3184
3185   retval = pango_context_get_metrics (context,
3186                                       font,
3187                                       pango_context_get_language (context));
3188
3189   return retval;
3190 }
3191
3192 /**
3193  * gtk_label_get_measuring_layout:
3194  * @label: the label
3195  * @existing_layout: %NULL or an existing layout already in use.
3196  * @width: the width to measure with in pango units, or -1 for infinite
3197  * @height: the height to measure with in pango units, or -1 for infinite
3198  *
3199  * Gets a layout that can be used for measuring sizes. The returned
3200  * layout will be identical to the label's layout except for the
3201  * layout's width, which will be set to @width. Do not modify the returned
3202  * layout.
3203  *
3204  * Returns: a new reference to a pango layout
3205  **/
3206 static PangoLayout *
3207 gtk_label_get_measuring_layout (GtkLabel *   label,
3208                                 PangoLayout *existing_layout,
3209                                 int          width,
3210                                 int          height)
3211 {
3212   GtkLabelPrivate *priv = label->priv;
3213   PangoRectangle rect;
3214   PangoLayout *copy;
3215
3216   if (existing_layout != NULL)
3217     {
3218       if (existing_layout != priv->layout)
3219         {
3220           pango_layout_set_width (existing_layout, width);
3221           pango_layout_set_height (existing_layout, height);
3222           return existing_layout;
3223         }
3224
3225       g_object_unref (existing_layout);
3226     }
3227
3228   gtk_label_ensure_layout (label);
3229
3230   if (pango_layout_get_width (priv->layout) == width &&
3231       pango_layout_get_height (priv->layout) == height)
3232     {
3233       g_object_ref (priv->layout);
3234       return priv->layout;
3235     }
3236
3237   /* We can use the label's own layout if we're not allocated a size yet,
3238    * because we don't need it to be properly setup at that point.
3239    * This way we can make use of caching upon the label's creation.
3240    */
3241   if (gtk_widget_get_allocated_width (GTK_WIDGET (label)) <= 1)
3242     {
3243       g_object_ref (priv->layout);
3244       pango_layout_set_width (priv->layout, width);
3245       pango_layout_set_height (priv->layout, height);
3246       return priv->layout;
3247     }
3248
3249   /* oftentimes we want to measure a width that is far wider than the current width,
3250    * even though the layout would not change if we made it wider. In that case, we
3251    * can just return the current layout, because for measuring purposes, it will be
3252    * identical.
3253    */
3254   pango_layout_get_extents (priv->layout, NULL, &rect);
3255   if ((width == -1 || rect.width <= width) &&
3256       (height == -1 || rect.height <= height) &&
3257       !pango_layout_is_wrapped (priv->layout) &&
3258       !pango_layout_is_ellipsized (priv->layout))
3259     {
3260       g_object_ref (priv->layout);
3261       return priv->layout;
3262     }
3263
3264   copy = pango_layout_copy (priv->layout);
3265   pango_layout_set_width (copy, width);
3266   pango_layout_set_height (copy, height);
3267   return copy;
3268 }
3269
3270 static void
3271 gtk_label_update_layout_width (GtkLabel *label)
3272 {
3273   GtkLabelPrivate *priv = label->priv;
3274   GtkWidget *widget = GTK_WIDGET (label);
3275
3276   g_assert (priv->layout);
3277
3278   if (priv->ellipsize || priv->wrap)
3279     {
3280       PangoRectangle logical;
3281       gint xpad, ypad;
3282       gint width, height;
3283
3284       gtk_misc_get_padding (GTK_MISC (label), &xpad, &ypad);
3285
3286       width = gtk_widget_get_allocated_width (GTK_WIDGET (label)) - xpad * 2;
3287       height = gtk_widget_get_allocated_height (GTK_WIDGET (label)) - ypad * 2;
3288
3289       if (priv->have_transform)
3290         {
3291           PangoContext *context = gtk_widget_get_pango_context (widget);
3292           const PangoMatrix *matrix = pango_context_get_matrix (context);
3293           const gdouble dx = matrix->xx; /* cos (M_PI * angle / 180) */
3294           const gdouble dy = matrix->xy; /* sin (M_PI * angle / 180) */
3295
3296           pango_layout_set_width (priv->layout, -1);
3297           pango_layout_set_height (priv->layout, -1);
3298           pango_layout_get_pixel_extents (priv->layout, NULL, &logical);
3299
3300           if (fabs (dy) < 0.01)
3301             {
3302               if (logical.width > width)
3303                 pango_layout_set_width (priv->layout, width * PANGO_SCALE);
3304             }
3305           else if (fabs (dx) < 0.01)
3306             {
3307               if (logical.width > height)
3308                 pango_layout_set_width (priv->layout, height * PANGO_SCALE);
3309             }
3310           else
3311             {
3312               gdouble x0, y0, x1, y1, length;
3313               gboolean vertical;
3314               gint cy;
3315
3316               x0 = width / 2;
3317               y0 = dx ? x0 * dy / dx : G_MAXDOUBLE;
3318               vertical = fabs (y0) > height / 2;
3319
3320               if (vertical)
3321                 {
3322                   y0 = height/2;
3323                   x0 = dy ? y0 * dx / dy : G_MAXDOUBLE;
3324                 }
3325
3326               length = 2 * sqrt (x0 * x0 + y0 * y0);
3327               pango_layout_set_width (priv->layout, rint (length * PANGO_SCALE));
3328               pango_layout_get_pixel_size (priv->layout, NULL, &cy);
3329
3330               x1 = +dy * cy/2;
3331               y1 = -dx * cy/2;
3332
3333               if (vertical)
3334                 {
3335                   y0 = height/2 + y1 - y0;
3336                   x0 = -y0 * dx/dy;
3337                 }
3338               else
3339                 {
3340                   x0 = width/2 + x1 - x0;
3341                   y0 = -x0 * dy/dx;
3342                 }
3343
3344               length = length - sqrt (x0 * x0 + y0 * y0) * 2;
3345               pango_layout_set_width (priv->layout, rint (length * PANGO_SCALE));
3346             }
3347         }
3348       else
3349         {
3350           pango_layout_set_width (priv->layout, width * PANGO_SCALE);
3351           pango_layout_set_height (priv->layout, priv->ellipsize ? height * PANGO_SCALE : -1);
3352         }
3353     }
3354   else
3355     {
3356       pango_layout_set_width (priv->layout, -1);
3357       pango_layout_set_height (priv->layout, -1);
3358     }
3359 }
3360
3361 static void
3362 gtk_label_ensure_layout (GtkLabel *label)
3363 {
3364   GtkLabelPrivate *priv = label->priv;
3365   GtkWidget *widget;
3366   gboolean rtl;
3367
3368   widget = GTK_WIDGET (label);
3369
3370   rtl = gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL;
3371
3372   if (!priv->layout)
3373     {
3374       PangoAlignment align = PANGO_ALIGN_LEFT; /* Quiet gcc */
3375       gdouble angle = gtk_label_get_angle (label);
3376
3377       if (angle != 0.0 && !priv->select_info)
3378         {
3379           PangoMatrix matrix = PANGO_MATRIX_INIT;
3380
3381           /* We rotate the standard singleton PangoContext for the widget,
3382            * depending on the fact that it's meant pretty much exclusively
3383            * for our use.
3384            */
3385           pango_matrix_rotate (&matrix, angle);
3386
3387           pango_context_set_matrix (gtk_widget_get_pango_context (widget), &matrix);
3388
3389           priv->have_transform = TRUE;
3390         }
3391       else
3392         {
3393           if (priv->have_transform)
3394             pango_context_set_matrix (gtk_widget_get_pango_context (widget), NULL);
3395
3396           priv->have_transform = FALSE;
3397         }
3398
3399       priv->layout = gtk_widget_create_pango_layout (widget, priv->text);
3400
3401       if (priv->effective_attrs)
3402         pango_layout_set_attributes (priv->layout, priv->effective_attrs);
3403
3404       gtk_label_rescan_links (label);
3405
3406       switch (priv->jtype)
3407         {
3408         case GTK_JUSTIFY_LEFT:
3409           align = rtl ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
3410           break;
3411         case GTK_JUSTIFY_RIGHT:
3412           align = rtl ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
3413           break;
3414         case GTK_JUSTIFY_CENTER:
3415           align = PANGO_ALIGN_CENTER;
3416           break;
3417         case GTK_JUSTIFY_FILL:
3418           align = rtl ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
3419           pango_layout_set_justify (priv->layout, TRUE);
3420           break;
3421         default:
3422           g_assert_not_reached();
3423         }
3424
3425       pango_layout_set_alignment (priv->layout, align);
3426       pango_layout_set_ellipsize (priv->layout, priv->ellipsize);
3427       pango_layout_set_wrap (priv->layout, priv->wrap_mode);
3428       pango_layout_set_single_paragraph_mode (priv->layout, priv->single_line_mode);
3429
3430       gtk_label_update_layout_width (label);
3431     }
3432 }
3433
3434 static gint
3435 get_single_line_height (GtkWidget   *widget,
3436                         PangoLayout *layout)
3437 {
3438   PangoContext *context;
3439   PangoFontMetrics *metrics;
3440   gint ascent, descent;
3441
3442   context = pango_layout_get_context (layout);
3443   metrics = get_font_metrics (context, widget);
3444   ascent = pango_font_metrics_get_ascent (metrics);
3445   descent = pango_font_metrics_get_descent (metrics);
3446   pango_font_metrics_unref (metrics);
3447
3448   return ascent + descent;
3449 }
3450
3451 static GtkSizeRequestMode
3452 gtk_label_get_request_mode (GtkWidget *widget)
3453 {
3454   GtkLabel *label = GTK_LABEL (widget);
3455   gdouble   angle = gtk_label_get_angle (label);
3456
3457   if (label->priv->wrap)
3458     return (angle == 90 || angle == 270) ?
3459       GTK_SIZE_REQUEST_WIDTH_FOR_HEIGHT : 
3460       GTK_SIZE_REQUEST_HEIGHT_FOR_WIDTH;
3461
3462     return GTK_SIZE_REQUEST_CONSTANT_SIZE;
3463 }
3464
3465 static void
3466 get_size_for_allocation (GtkLabel        *label,
3467                          GtkOrientation   orientation,
3468                          gint             allocation,
3469                          gint            *minimum_size,
3470                          gint            *natural_size)
3471 {
3472   GtkLabelPrivate *priv = label->priv;
3473   PangoLayout *layout;
3474   gint text_height;
3475
3476   layout = gtk_label_get_measuring_layout (label, NULL, allocation * PANGO_SCALE, -1);
3477
3478   pango_layout_get_pixel_size (layout, NULL, &text_height);
3479
3480   if (minimum_size)
3481     *minimum_size = text_height;
3482
3483   if (natural_size)
3484     {
3485       if (priv->ellipsize && priv->wrap)
3486         {
3487           layout = gtk_label_get_measuring_layout (label, layout, allocation * PANGO_SCALE, G_MAXINT);
3488           pango_layout_get_pixel_size (layout, NULL, &text_height);
3489         }
3490
3491       *natural_size = text_height;
3492     }
3493
3494   g_object_unref (layout);
3495 }
3496
3497 static gint
3498 get_char_pixels (GtkWidget   *label,
3499                  PangoLayout *layout)
3500 {
3501   PangoContext *context;
3502   PangoFontMetrics *metrics;
3503   gint char_width, digit_width;
3504
3505   context = pango_layout_get_context (layout);
3506   metrics = get_font_metrics (context, GTK_WIDGET (label));
3507   char_width = pango_font_metrics_get_approximate_char_width (metrics);
3508   digit_width = pango_font_metrics_get_approximate_digit_width (metrics);
3509   pango_font_metrics_unref (metrics);
3510
3511   return MAX (char_width, digit_width);;
3512 }
3513
3514 static void
3515 gtk_label_get_preferred_layout_size (GtkLabel *label,
3516                                      PangoRectangle *required,
3517                                      PangoRectangle *natural)
3518 {
3519   GtkLabelPrivate *priv = label->priv;
3520   PangoLayout *layout;
3521
3522   /* "width-chars" Hard-coded minimum width:
3523    *    - minimum size should be MAX (width-chars, strlen ("..."));
3524    *    - natural size should be MAX (width-chars, strlen (priv->text));
3525    *
3526    * "max-width-chars" User specified maximum size requisition
3527    *    - minimum size should be MAX (width-chars, 0)
3528    *    - natural size should be MIN (max-width-chars, strlen (priv->text))
3529    *
3530    *    For ellipsizing labels; if max-width-chars is specified: either it is used as 
3531    *    a minimum size or the label text as a minimum size (natural size still overflows).
3532    *
3533    *    For wrapping labels; A reasonable minimum size is useful to naturally layout
3534    *    interfaces automatically. In this case if no "width-chars" is specified, the minimum
3535    *    width will default to the wrap guess that gtk_label_ensure_layout() does.
3536    */
3537
3538   /* Start off with the pixel extents of an as-wide-as-possible layout */
3539   layout = gtk_label_get_measuring_layout (label, NULL, -1, -1);
3540
3541   pango_layout_get_extents (layout, NULL, natural);
3542   natural->x = natural->y = 0;
3543
3544   if (priv->wrap)
3545     natural->height = get_single_line_height (GTK_WIDGET (label), layout);
3546
3547   if (priv->ellipsize || priv->wrap)
3548     {
3549       /* a layout with width 0 will be as small as humanly possible */
3550       layout = gtk_label_get_measuring_layout (label, layout, 0, -1);
3551
3552       pango_layout_get_extents (layout, NULL, required);
3553
3554       /* can happen when Pango decides to ellipsize text */
3555       if (required->width > natural->width)
3556         required->width = natural->width;
3557
3558       required->x = required->y = 0;
3559       required->height = natural->height;
3560     }
3561   else
3562     {
3563       *required = *natural;
3564     }
3565
3566   if (priv->width_chars > -1 || priv->max_width_chars > -1)
3567     {
3568       gint char_pixels;
3569
3570       char_pixels = get_char_pixels (GTK_WIDGET (label), layout);
3571       
3572       if (priv->width_chars > -1)
3573         required->width = MAX (required->width, char_pixels * priv->width_chars);
3574
3575       if (priv->max_width_chars > -1)
3576         natural->width = MIN (natural->width, priv->max_width_chars * char_pixels);
3577       natural->width = MAX (natural->width, required->width);
3578     }
3579
3580   g_object_unref (layout);
3581 }
3582
3583 static void
3584 gtk_label_get_preferred_size (GtkWidget      *widget,
3585                               GtkOrientation  orientation,
3586                               gint           *minimum_size,
3587                               gint           *natural_size)
3588 {
3589   GtkLabel      *label = GTK_LABEL (widget);
3590   GtkLabelPrivate  *priv = label->priv;
3591   PangoRectangle required_rect;
3592   PangoRectangle natural_rect;
3593   gint           xpad, ypad;
3594
3595   gtk_label_get_preferred_layout_size (label, &required_rect, &natural_rect);
3596
3597   /* Now that we have minimum and natural sizes in pango extents, apply a possible transform */
3598   if (priv->have_transform)
3599     {
3600       PangoLayout *copy;
3601       PangoContext *context;
3602       const PangoMatrix *matrix;
3603
3604       copy = pango_layout_copy (priv->layout);
3605       context = pango_layout_get_context (copy);
3606       matrix = pango_context_get_matrix (context);
3607
3608       pango_layout_set_width (copy, -1);
3609       pango_layout_set_ellipsize (copy, PANGO_ELLIPSIZE_NONE);
3610
3611       pango_layout_get_extents (copy, NULL, &natural_rect);
3612       g_object_unref (copy);
3613
3614       pango_matrix_transform_rectangle (matrix, &required_rect);
3615       pango_matrix_transform_rectangle (matrix, &natural_rect);
3616
3617       /* Bump the natural size in case of ellipsize to ensure pango has
3618        * enough space in the angles (note, we could alternatively set the
3619        * layout to not ellipsize when we know we have been allocated our
3620        * full natural size, or it may be that pango needs a fix here).
3621        */
3622       if (priv->ellipsize && priv->angle != 0 && priv->angle != 90 && 
3623           priv->angle != 180 && priv->angle != 270 && priv->angle != 360)
3624         {
3625           /* For some reason we only need this at about 110 degrees, and only
3626            * when gaining in height
3627            */
3628           natural_rect.height += ROTATION_ELLIPSIZE_PADDING * 2 * PANGO_SCALE;
3629           natural_rect.width  += ROTATION_ELLIPSIZE_PADDING * 2 * PANGO_SCALE;
3630         }
3631     }
3632
3633   required_rect.width  = PANGO_PIXELS_CEIL (required_rect.width);
3634   required_rect.height = PANGO_PIXELS_CEIL (required_rect.height);
3635
3636   natural_rect.width  = PANGO_PIXELS_CEIL (natural_rect.width);
3637   natural_rect.height = PANGO_PIXELS_CEIL (natural_rect.height);
3638
3639   gtk_misc_get_padding (GTK_MISC (label), &xpad, &ypad);
3640
3641   if (orientation == GTK_ORIENTATION_HORIZONTAL)
3642     {
3643       /* Note, we cant use get_size_for_allocation() when rotating
3644        * ellipsized labels.
3645        */
3646       if (!(priv->ellipsize && priv->have_transform) &&
3647           (priv->angle == 90 || priv->angle == 270))
3648         {
3649           /* Doing a h4w request on a rotated label here, return the
3650            * required width for the minimum height.
3651            */
3652           get_size_for_allocation (label,
3653                                    GTK_ORIENTATION_VERTICAL,
3654                                    required_rect.height,
3655                                    minimum_size, natural_size);
3656
3657         }
3658       else
3659         {
3660           /* Normal desired width */
3661           *minimum_size = required_rect.width;
3662           *natural_size = natural_rect.width;
3663         }
3664
3665       *minimum_size += xpad * 2;
3666       *natural_size += xpad * 2;
3667     }
3668   else /* GTK_ORIENTATION_VERTICAL */
3669     {
3670       /* Note, we cant use get_size_for_allocation() when rotating
3671        * ellipsized labels.
3672        */
3673       if (!(priv->ellipsize && priv->have_transform) &&
3674           (priv->angle == 0 || priv->angle == 180 || priv->angle == 360))
3675         {
3676           /* Doing a w4h request on a label here, return the required
3677            * height for the minimum width.
3678            */
3679           get_size_for_allocation (label,
3680                                    GTK_ORIENTATION_HORIZONTAL,
3681                                    required_rect.width,
3682                                    minimum_size, natural_size);
3683         }
3684       else
3685         {
3686           /* A vertically rotated label does w4h, so return the base
3687            * desired height (text length)
3688            */
3689           *minimum_size = required_rect.height;
3690           *natural_size = natural_rect.height;
3691         }
3692
3693       *minimum_size += ypad * 2;
3694       *natural_size += ypad * 2;
3695     }
3696 }
3697
3698
3699 static void
3700 gtk_label_get_preferred_width (GtkWidget *widget,
3701                                gint      *minimum_size,
3702                                gint      *natural_size)
3703 {
3704   gtk_label_get_preferred_size (widget, GTK_ORIENTATION_HORIZONTAL, minimum_size, natural_size);
3705 }
3706
3707 static void
3708 gtk_label_get_preferred_height (GtkWidget *widget,
3709                                 gint      *minimum_size,
3710                                 gint      *natural_size)
3711 {
3712   gtk_label_get_preferred_size (widget, GTK_ORIENTATION_VERTICAL, minimum_size, natural_size);
3713 }
3714
3715 static void
3716 gtk_label_get_preferred_width_for_height (GtkWidget *widget,
3717                                           gint       height,
3718                                           gint      *minimum_width,
3719                                           gint      *natural_width)
3720 {
3721   GtkLabel *label = GTK_LABEL (widget);
3722   GtkLabelPrivate *priv = label->priv;
3723
3724   if (priv->wrap && (priv->angle == 90 || priv->angle == 270))
3725     {
3726       gint xpad, ypad;
3727
3728       gtk_misc_get_padding (GTK_MISC (label), &xpad, &ypad);
3729
3730       if (priv->wrap)
3731         gtk_label_clear_layout (label);
3732
3733       get_size_for_allocation (label, GTK_ORIENTATION_VERTICAL,
3734                                MAX (1, height - (ypad * 2)),
3735                                minimum_width, natural_width);
3736
3737       if (minimum_width)
3738         *minimum_width += xpad * 2;
3739
3740       if (natural_width)
3741         *natural_width += xpad * 2;
3742     }
3743   else
3744     GTK_WIDGET_GET_CLASS (widget)->get_preferred_width (widget, minimum_width, natural_width);
3745 }
3746
3747 static void
3748 gtk_label_get_preferred_height_for_width (GtkWidget *widget,
3749                                           gint       width,
3750                                           gint      *minimum_height,
3751                                           gint      *natural_height)
3752 {
3753   GtkLabel *label = GTK_LABEL (widget);
3754   GtkLabelPrivate *priv = label->priv;
3755
3756   if (priv->wrap && (priv->angle == 0 || priv->angle == 180 || priv->angle == 360))
3757     {
3758       gint xpad, ypad;
3759
3760       gtk_misc_get_padding (GTK_MISC (label), &xpad, &ypad);
3761
3762       if (priv->wrap)
3763         gtk_label_clear_layout (label);
3764
3765       get_size_for_allocation (label, GTK_ORIENTATION_HORIZONTAL,
3766                                MAX (1, width - xpad * 2),
3767                                minimum_height, natural_height);
3768
3769       if (minimum_height)
3770         *minimum_height += ypad * 2;
3771
3772       if (natural_height)
3773         *natural_height += ypad * 2;
3774     }
3775   else
3776     GTK_WIDGET_GET_CLASS (widget)->get_preferred_height (widget, minimum_height, natural_height);
3777 }
3778
3779 static void
3780 gtk_label_size_allocate (GtkWidget     *widget,
3781                          GtkAllocation *allocation)
3782 {
3783   GtkLabel *label = GTK_LABEL (widget);
3784   GtkLabelPrivate *priv = label->priv;
3785
3786   GTK_WIDGET_CLASS (gtk_label_parent_class)->size_allocate (widget, allocation);
3787
3788   if (priv->layout)
3789     gtk_label_update_layout_width (label);
3790
3791   if (priv->select_info && priv->select_info->window)
3792     {
3793       gdk_window_move_resize (priv->select_info->window,
3794                               allocation->x,
3795                               allocation->y,
3796                               allocation->width,
3797                               allocation->height);
3798     }
3799 }
3800
3801 static void
3802 gtk_label_update_cursor (GtkLabel *label)
3803 {
3804   GtkLabelPrivate *priv = label->priv;
3805   GtkWidget *widget;
3806
3807   if (!priv->select_info)
3808     return;
3809
3810   widget = GTK_WIDGET (label);
3811
3812   if (gtk_widget_get_realized (widget))
3813     {
3814       GdkDisplay *display;
3815       GdkCursor *cursor;
3816
3817       if (gtk_widget_is_sensitive (widget))
3818         {
3819           display = gtk_widget_get_display (widget);
3820
3821           if (priv->select_info->active_link)
3822             cursor = gdk_cursor_new_for_display (display, GDK_HAND2);
3823           else if (priv->select_info->selectable)
3824             cursor = gdk_cursor_new_for_display (display, GDK_XTERM);
3825           else
3826             cursor = NULL;
3827         }
3828       else
3829         cursor = NULL;
3830
3831       gdk_window_set_cursor (priv->select_info->window, cursor);
3832
3833       if (cursor)
3834         g_object_unref (cursor);
3835     }
3836 }
3837
3838 static void
3839 gtk_label_state_flags_changed (GtkWidget     *widget,
3840                                GtkStateFlags  prev_state)
3841 {
3842   GtkLabel *label = GTK_LABEL (widget);
3843   GtkLabelPrivate *priv = label->priv;
3844
3845   if (priv->select_info)
3846     {
3847       if (!gtk_widget_is_sensitive (widget))
3848         gtk_label_select_region (label, 0, 0);
3849
3850       gtk_label_update_cursor (label);
3851     }
3852
3853   /* We have to clear the layout, fonts etc. may have changed */
3854   gtk_label_clear_layout (label);
3855
3856   if (GTK_WIDGET_CLASS (gtk_label_parent_class)->state_flags_changed)
3857     GTK_WIDGET_CLASS (gtk_label_parent_class)->state_flags_changed (widget, prev_state);
3858 }
3859
3860 static void
3861 gtk_label_style_updated (GtkWidget *widget)
3862 {
3863   GtkLabel *label = GTK_LABEL (widget);
3864
3865   GTK_WIDGET_CLASS (gtk_label_parent_class)->style_updated (widget);
3866
3867   /* We have to clear the layout, fonts etc. may have changed */
3868   gtk_label_clear_layout (label);
3869 }
3870
3871 static void 
3872 gtk_label_direction_changed (GtkWidget        *widget,
3873                              GtkTextDirection previous_dir)
3874 {
3875   GtkLabel *label = GTK_LABEL (widget);
3876   GtkLabelPrivate *priv = label->priv;
3877
3878   if (priv->layout)
3879     pango_layout_context_changed (priv->layout);
3880
3881   GTK_WIDGET_CLASS (gtk_label_parent_class)->direction_changed (widget, previous_dir);
3882 }
3883
3884 static void
3885 get_layout_location (GtkLabel  *label,
3886                      gint      *xp,
3887                      gint      *yp)
3888 {
3889   GtkAllocation allocation;
3890   GtkMisc *misc;
3891   GtkWidget *widget;
3892   GtkLabelPrivate *priv;
3893   gint req_width, x, y;
3894   gint req_height;
3895   gint xpad, ypad;
3896   gfloat xalign, yalign;
3897   PangoRectangle logical;
3898
3899   misc   = GTK_MISC (label);
3900   widget = GTK_WIDGET (label);
3901   priv   = label->priv;
3902
3903   gtk_misc_get_alignment (misc, &xalign, &yalign);
3904   gtk_misc_get_padding (misc, &xpad, &ypad);
3905
3906   if (gtk_widget_get_direction (widget) != GTK_TEXT_DIR_LTR)
3907     xalign = 1.0 - xalign;
3908
3909   pango_layout_get_extents (priv->layout, NULL, &logical);
3910
3911   if (priv->have_transform)
3912     {
3913       PangoContext *context = gtk_widget_get_pango_context (widget);
3914       const PangoMatrix *matrix = pango_context_get_matrix (context);
3915       pango_matrix_transform_rectangle (matrix, &logical);
3916     }
3917
3918   pango_extents_to_pixels (&logical, NULL);
3919
3920   req_width  = logical.width;
3921   req_height = logical.height;
3922
3923   req_width  += 2 * xpad;
3924   req_height += 2 * ypad;
3925
3926   gtk_widget_get_allocation (widget, &allocation);
3927
3928   x = floor (allocation.x + xpad + xalign * (allocation.width - req_width) - logical.x);
3929
3930
3931   /* bgo#315462 - For single-line labels, *do* align the requisition with
3932    * respect to the allocation, even if we are under-allocated.  For multi-line
3933    * labels, always show the top of the text when they are under-allocated.  The
3934    * rationale is this:
3935    *
3936    * - Single-line labels appear in GtkButtons, and it is very easy to get them
3937    *   to be smaller than their requisition.  The button may clip the label, but
3938    *   the label will still be able to show most of itself and the focus
3939    *   rectangle.  Also, it is fairly easy to read a single line of clipped text.
3940    *
3941    * - Multi-line labels should not be clipped to showing "something in the
3942    *   middle".  You want to read the first line, at least, to get some context.
3943    */
3944   if (pango_layout_get_line_count (priv->layout) == 1)
3945     y = floor (allocation.y + ypad + (allocation.height - req_height) * yalign) - logical.y;
3946   else
3947     y = floor (allocation.y + ypad + MAX ((allocation.height - req_height) * yalign, 0)) - logical.y;
3948
3949   if (xp)
3950     *xp = x;
3951
3952   if (yp)
3953     *yp = y;
3954 }
3955
3956 static PangoDirection
3957 get_cursor_direction (GtkLabel *label)
3958 {
3959   GtkLabelPrivate *priv = label->priv;
3960   GSList *l;
3961
3962   g_assert (priv->select_info);
3963
3964   gtk_label_ensure_layout (label);
3965
3966   for (l = pango_layout_get_lines_readonly (priv->layout); l; l = l->next)
3967     {
3968       PangoLayoutLine *line = l->data;
3969
3970       /* If priv->select_info->selection_end is at the very end of
3971        * the line, we don't know if the cursor is on this line or
3972        * the next without looking ahead at the next line. (End
3973        * of paragraph is different from line break.) But it's
3974        * definitely in this paragraph, which is good enough
3975        * to figure out the resolved direction.
3976        */
3977        if (line->start_index + line->length >= priv->select_info->selection_end)
3978         return line->resolved_dir;
3979     }
3980
3981   return PANGO_DIRECTION_LTR;
3982 }
3983
3984 static GtkLabelLink *
3985 gtk_label_get_focus_link (GtkLabel *label)
3986 {
3987   GtkLabelPrivate *priv = label->priv;
3988   GtkLabelSelectionInfo *info = priv->select_info;
3989   GList *l;
3990
3991   if (!info)
3992     return NULL;
3993
3994   if (info->selection_anchor != info->selection_end)
3995     return NULL;
3996
3997   for (l = info->links; l; l = l->next)
3998     {
3999       GtkLabelLink *link = l->data;
4000       if (link->start <= info->selection_anchor &&
4001           info->selection_anchor <= link->end)
4002         return link;
4003     }
4004
4005   return NULL;
4006 }
4007
4008 static gint
4009 gtk_label_draw (GtkWidget *widget,
4010                 cairo_t   *cr)
4011 {
4012   GtkLabel *label = GTK_LABEL (widget);
4013   GtkLabelPrivate *priv = label->priv;
4014   GtkLabelSelectionInfo *info = priv->select_info;
4015   GtkAllocation allocation;
4016   GtkStyleContext *context;
4017   GtkStateFlags state;
4018   gint x, y;
4019
4020   gtk_label_ensure_layout (label);
4021
4022   if (priv->text && (*priv->text != '\0'))
4023     {
4024       get_layout_location (label, &x, &y);
4025
4026       context = gtk_widget_get_style_context (widget);
4027       gtk_widget_get_allocation (widget, &allocation);
4028
4029       cairo_translate (cr, -allocation.x, -allocation.y);
4030
4031       gtk_render_layout (context, cr,
4032                          x, y,
4033                          priv->layout);
4034
4035       state = gtk_widget_get_state_flags (widget);
4036
4037       if (info &&
4038           (info->selection_anchor != info->selection_end))
4039         {
4040           gint range[2];
4041           cairo_region_t *clip;
4042           GdkRGBA bg_color, fg_color;
4043
4044           range[0] = info->selection_anchor;
4045           range[1] = info->selection_end;
4046
4047           if (range[0] > range[1])
4048             {
4049               gint tmp = range[0];
4050               range[0] = range[1];
4051               range[1] = tmp;
4052             }
4053
4054           clip = gdk_pango_layout_get_clip_region (priv->layout,
4055                                                    x, y,
4056                                                    range,
4057                                                    1);
4058
4059          /* FIXME should use gtk_paint, but it can't use a clip region */
4060           cairo_save (cr);
4061
4062           gdk_cairo_region (cr, clip);
4063           cairo_clip (cr);
4064
4065           state = GTK_STATE_FLAG_SELECTED;
4066
4067           if (gtk_widget_has_focus (widget))
4068             state |= GTK_STATE_FLAG_FOCUSED;
4069
4070           gtk_style_context_get_color (context, state, &fg_color);
4071           gtk_style_context_get_background_color (context, state, &bg_color);
4072
4073           gdk_cairo_set_source_rgba (cr, &bg_color);
4074           cairo_paint (cr);
4075
4076           gdk_cairo_set_source_rgba (cr, &fg_color);
4077           cairo_move_to (cr, x, y);
4078           _gtk_pango_fill_layout (cr, priv->layout);
4079
4080           cairo_restore (cr);
4081           cairo_region_destroy (clip);
4082         }
4083       else if (info)
4084         {
4085           GtkLabelLink *focus_link;
4086           GtkLabelLink *active_link;
4087           gint range[2];
4088           cairo_region_t *clip;
4089           GdkRectangle rect;
4090           GdkColor *text_color;
4091           GdkColor *link_color;
4092           GdkColor *visited_link_color;
4093
4094           if (info->selectable &&
4095               gtk_widget_has_focus (widget) &&
4096               gtk_widget_is_drawable (widget))
4097             {
4098               PangoDirection cursor_direction;
4099
4100               cursor_direction = get_cursor_direction (label);
4101               gtk_render_insertion_cursor (context, cr,
4102                                            x, y,
4103                                            priv->layout, priv->select_info->selection_end,
4104                                            cursor_direction);
4105             }
4106
4107           focus_link = gtk_label_get_focus_link (label);
4108           active_link = info->active_link;
4109
4110           if (active_link)
4111             {
4112               GdkRGBA bg_color;
4113
4114               range[0] = active_link->start;
4115               range[1] = active_link->end;
4116
4117               cairo_save (cr);
4118
4119               clip = gdk_pango_layout_get_clip_region (priv->layout,
4120                                                        x, y,
4121                                                        range,
4122                                                        1);
4123               gdk_cairo_region (cr, clip);
4124               cairo_clip (cr);
4125               cairo_region_destroy (clip);
4126
4127               gtk_label_get_link_colors (widget, &link_color, &visited_link_color);
4128               if (active_link->visited)
4129                 text_color = visited_link_color;
4130               else
4131                 text_color = link_color;
4132
4133               if (info->link_clicked)
4134                 state = GTK_STATE_FLAG_ACTIVE;
4135               else
4136                 state = GTK_STATE_FLAG_PRELIGHT;
4137
4138               gtk_style_context_get_background_color (context, state, &bg_color);
4139
4140               gdk_cairo_set_source_rgba (cr, &bg_color);
4141               cairo_paint (cr);
4142
4143               gdk_cairo_set_source_color (cr, text_color);
4144               cairo_move_to (cr, x, y);
4145               _gtk_pango_fill_layout (cr, priv->layout);
4146
4147               gdk_color_free (link_color);
4148               gdk_color_free (visited_link_color);
4149
4150               cairo_restore (cr);
4151             }
4152
4153           if (focus_link && gtk_widget_has_visible_focus (widget))
4154             {
4155               range[0] = focus_link->start;
4156               range[1] = focus_link->end;
4157
4158               clip = gdk_pango_layout_get_clip_region (priv->layout,
4159                                                        x, y,
4160                                                        range,
4161                                                        1);
4162               cairo_region_get_extents (clip, &rect);
4163
4164               gtk_render_focus (context, cr,
4165                                 rect.x, rect.y,
4166                                 rect.width, rect.height);
4167
4168               cairo_region_destroy (clip);
4169             }
4170         }
4171     }
4172
4173   return FALSE;
4174 }
4175
4176 static gboolean
4177 separate_uline_pattern (const gchar  *str,
4178                         guint        *accel_key,
4179                         gchar       **new_str,
4180                         gchar       **pattern)
4181 {
4182   gboolean underscore;
4183   const gchar *src;
4184   gchar *dest;
4185   gchar *pattern_dest;
4186
4187   *accel_key = GDK_KEY_VoidSymbol;
4188   *new_str = g_new (gchar, strlen (str) + 1);
4189   *pattern = g_new (gchar, g_utf8_strlen (str, -1) + 1);
4190
4191   underscore = FALSE;
4192
4193   src = str;
4194   dest = *new_str;
4195   pattern_dest = *pattern;
4196
4197   while (*src)
4198     {
4199       gunichar c;
4200       const gchar *next_src;
4201
4202       c = g_utf8_get_char (src);
4203       if (c == (gunichar)-1)
4204         {
4205           g_warning ("Invalid input string");
4206           g_free (*new_str);
4207           g_free (*pattern);
4208
4209           return FALSE;
4210         }
4211       next_src = g_utf8_next_char (src);
4212
4213       if (underscore)
4214         {
4215           if (c == '_')
4216             *pattern_dest++ = ' ';
4217           else
4218             {
4219               *pattern_dest++ = '_';
4220               if (*accel_key == GDK_KEY_VoidSymbol)
4221                 *accel_key = gdk_keyval_to_lower (gdk_unicode_to_keyval (c));
4222             }
4223
4224           while (src < next_src)
4225             *dest++ = *src++;
4226
4227           underscore = FALSE;
4228         }
4229       else
4230         {
4231           if (c == '_')
4232             {
4233               underscore = TRUE;
4234               src = next_src;
4235             }
4236           else
4237             {
4238               while (src < next_src)
4239                 *dest++ = *src++;
4240
4241               *pattern_dest++ = ' ';
4242             }
4243         }
4244     }
4245
4246   *dest = 0;
4247   *pattern_dest = 0;
4248
4249   return TRUE;
4250 }
4251
4252 static void
4253 gtk_label_set_uline_text_internal (GtkLabel    *label,
4254                                    const gchar *str)
4255 {
4256   GtkLabelPrivate *priv = label->priv;
4257   guint accel_key = GDK_KEY_VoidSymbol;
4258   gchar *new_str;
4259   gchar *pattern;
4260
4261   g_return_if_fail (GTK_IS_LABEL (label));
4262   g_return_if_fail (str != NULL);
4263
4264   /* Split text into the base text and a separate pattern
4265    * of underscores.
4266    */
4267   if (!separate_uline_pattern (str, &accel_key, &new_str, &pattern))
4268     return;
4269
4270   gtk_label_set_text_internal (label, new_str);
4271   gtk_label_set_pattern_internal (label, pattern, TRUE);
4272   priv->mnemonic_keyval = accel_key;
4273
4274   g_free (pattern);
4275 }
4276
4277 /**
4278  * gtk_label_set_text_with_mnemonic:
4279  * @label: a #GtkLabel
4280  * @str: a string
4281  * 
4282  * Sets the label's text from the string @str.
4283  * If characters in @str are preceded by an underscore, they are underlined
4284  * indicating that they represent a keyboard accelerator called a mnemonic.
4285  * The mnemonic key can be used to activate another widget, chosen 
4286  * automatically, or explicitly using gtk_label_set_mnemonic_widget().
4287  **/
4288 void
4289 gtk_label_set_text_with_mnemonic (GtkLabel    *label,
4290                                   const gchar *str)
4291 {
4292   g_return_if_fail (GTK_IS_LABEL (label));
4293   g_return_if_fail (str != NULL);
4294
4295   g_object_freeze_notify (G_OBJECT (label));
4296
4297   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
4298   gtk_label_set_use_markup_internal (label, FALSE);
4299   gtk_label_set_use_underline_internal (label, TRUE);
4300   
4301   gtk_label_recalculate (label);
4302
4303   g_object_thaw_notify (G_OBJECT (label));
4304 }
4305
4306 static void
4307 gtk_label_realize (GtkWidget *widget)
4308 {
4309   GtkLabel *label = GTK_LABEL (widget);
4310   GtkLabelPrivate *priv = label->priv;
4311
4312   GTK_WIDGET_CLASS (gtk_label_parent_class)->realize (widget);
4313
4314   if (priv->select_info)
4315     gtk_label_create_window (label);
4316 }
4317
4318 static void
4319 gtk_label_unrealize (GtkWidget *widget)
4320 {
4321   GtkLabel *label = GTK_LABEL (widget);
4322   GtkLabelPrivate *priv = label->priv;
4323
4324   if (priv->select_info)
4325     gtk_label_destroy_window (label);
4326
4327   GTK_WIDGET_CLASS (gtk_label_parent_class)->unrealize (widget);
4328 }
4329
4330 static void
4331 gtk_label_map (GtkWidget *widget)
4332 {
4333   GtkLabel *label = GTK_LABEL (widget);
4334   GtkLabelPrivate *priv = label->priv;
4335
4336   GTK_WIDGET_CLASS (gtk_label_parent_class)->map (widget);
4337
4338   if (priv->select_info)
4339     gdk_window_show (priv->select_info->window);
4340 }
4341
4342 static void
4343 gtk_label_unmap (GtkWidget *widget)
4344 {
4345   GtkLabel *label = GTK_LABEL (widget);
4346   GtkLabelPrivate *priv = label->priv;
4347
4348   if (priv->select_info)
4349     gdk_window_hide (priv->select_info->window);
4350
4351   GTK_WIDGET_CLASS (gtk_label_parent_class)->unmap (widget);
4352 }
4353
4354 static void
4355 window_to_layout_coords (GtkLabel *label,
4356                          gint     *x,
4357                          gint     *y)
4358 {
4359   GtkAllocation allocation;
4360   gint lx, ly;
4361   GtkWidget *widget;
4362
4363   widget = GTK_WIDGET (label);
4364   
4365   /* get layout location in widget->window coords */
4366   get_layout_location (label, &lx, &ly);
4367
4368   gtk_widget_get_allocation (widget, &allocation);
4369
4370   if (x)
4371     {
4372       *x += allocation.x; /* go to widget->window */
4373       *x -= lx;                   /* go to layout */
4374     }
4375
4376   if (y)
4377     {
4378       *y += allocation.y; /* go to widget->window */
4379       *y -= ly;                   /* go to layout */
4380     }
4381 }
4382
4383 #if 0
4384 static void
4385 layout_to_window_coords (GtkLabel *label,
4386                          gint     *x,
4387                          gint     *y)
4388 {
4389   gint lx, ly;
4390   GtkWidget *widget;
4391
4392   widget = GTK_WIDGET (label);
4393   
4394   /* get layout location in widget->window coords */
4395   get_layout_location (label, &lx, &ly);
4396   
4397   if (x)
4398     {
4399       *x += lx;                   /* go to widget->window */
4400       *x -= widget->allocation.x; /* go to selection window */
4401     }
4402
4403   if (y)
4404     {
4405       *y += ly;                   /* go to widget->window */
4406       *y -= widget->allocation.y; /* go to selection window */
4407     }
4408 }
4409 #endif
4410
4411 static gboolean
4412 get_layout_index (GtkLabel *label,
4413                   gint      x,
4414                   gint      y,
4415                   gint     *index)
4416 {
4417   GtkLabelPrivate *priv = label->priv;
4418   gint trailing = 0;
4419   const gchar *cluster;
4420   const gchar *cluster_end;
4421   gboolean inside;
4422
4423   *index = 0;
4424
4425   gtk_label_ensure_layout (label);
4426
4427   window_to_layout_coords (label, &x, &y);
4428
4429   x *= PANGO_SCALE;
4430   y *= PANGO_SCALE;
4431
4432   inside = pango_layout_xy_to_index (priv->layout,
4433                                      x, y,
4434                                      index, &trailing);
4435
4436   cluster = priv->text + *index;
4437   cluster_end = cluster;
4438   while (trailing)
4439     {
4440       cluster_end = g_utf8_next_char (cluster_end);
4441       --trailing;
4442     }
4443
4444   *index += (cluster_end - cluster);
4445
4446   return inside;
4447 }
4448
4449 static void
4450 gtk_label_select_word (GtkLabel *label)
4451 {
4452   GtkLabelPrivate *priv = label->priv;
4453   gint min, max;
4454
4455   gint start_index = gtk_label_move_backward_word (label, priv->select_info->selection_end);
4456   gint end_index = gtk_label_move_forward_word (label, priv->select_info->selection_end);
4457
4458   min = MIN (priv->select_info->selection_anchor,
4459              priv->select_info->selection_end);
4460   max = MAX (priv->select_info->selection_anchor,
4461              priv->select_info->selection_end);
4462
4463   min = MIN (min, start_index);
4464   max = MAX (max, end_index);
4465
4466   gtk_label_select_region_index (label, min, max);
4467 }
4468
4469 static void
4470 gtk_label_grab_focus (GtkWidget *widget)
4471 {
4472   GtkLabel *label = GTK_LABEL (widget);
4473   GtkLabelPrivate *priv = label->priv;
4474   gboolean select_on_focus;
4475   GtkLabelLink *link;
4476
4477   if (priv->select_info == NULL)
4478     return;
4479
4480   GTK_WIDGET_CLASS (gtk_label_parent_class)->grab_focus (widget);
4481
4482   if (priv->select_info->selectable)
4483     {
4484       g_object_get (gtk_widget_get_settings (widget),
4485                     "gtk-label-select-on-focus",
4486                     &select_on_focus,
4487                     NULL);
4488
4489       if (select_on_focus && !priv->in_click)
4490         gtk_label_select_region (label, 0, -1);
4491     }
4492   else
4493     {
4494       if (priv->select_info->links && !priv->in_click)
4495         {
4496           link = priv->select_info->links->data;
4497           priv->select_info->selection_anchor = link->start;
4498           priv->select_info->selection_end = link->start;
4499         }
4500     }
4501 }
4502
4503 static gboolean
4504 gtk_label_focus (GtkWidget        *widget,
4505                  GtkDirectionType  direction)
4506 {
4507   GtkLabel *label = GTK_LABEL (widget);
4508   GtkLabelPrivate *priv = label->priv;
4509   GtkLabelSelectionInfo *info = priv->select_info;
4510   GtkLabelLink *focus_link;
4511   GList *l;
4512
4513   if (!gtk_widget_is_focus (widget))
4514     {
4515       gtk_widget_grab_focus (widget);
4516       if (info)
4517         {
4518           focus_link = gtk_label_get_focus_link (label);
4519           if (focus_link && direction == GTK_DIR_TAB_BACKWARD)
4520             {
4521               l = g_list_last (info->links);
4522               focus_link = l->data;
4523               info->selection_anchor = focus_link->start;
4524               info->selection_end = focus_link->start;
4525             }
4526         }
4527
4528       return TRUE;
4529     }
4530
4531   if (!info)
4532     return FALSE;
4533
4534   if (info->selectable)
4535     {
4536       gint index;
4537
4538       if (info->selection_anchor != info->selection_end)
4539         goto out;
4540
4541       index = info->selection_anchor;
4542
4543       if (direction == GTK_DIR_TAB_FORWARD)
4544         for (l = info->links; l; l = l->next)
4545           {
4546             GtkLabelLink *link = l->data;
4547
4548             if (link->start > index)
4549               {
4550                 gtk_label_select_region_index (label, link->start, link->start);
4551                 return TRUE;
4552               }
4553           }
4554       else if (direction == GTK_DIR_TAB_BACKWARD)
4555         for (l = g_list_last (info->links); l; l = l->prev)
4556           {
4557             GtkLabelLink *link = l->data;
4558
4559             if (link->end < index)
4560               {
4561                 gtk_label_select_region_index (label, link->start, link->start);
4562                 return TRUE;
4563               }
4564           }
4565
4566       goto out;
4567     }
4568   else
4569     {
4570       focus_link = gtk_label_get_focus_link (label);
4571       switch (direction)
4572         {
4573         case GTK_DIR_TAB_FORWARD:
4574           if (focus_link)
4575             {
4576               l = g_list_find (info->links, focus_link);
4577               l = l->next;
4578             }
4579           else
4580             l = info->links;
4581           break;
4582
4583         case GTK_DIR_TAB_BACKWARD:
4584           if (focus_link)
4585             {
4586               l = g_list_find (info->links, focus_link);
4587               l = l->prev;
4588             }
4589           else
4590             l = g_list_last (info->links);
4591           break;
4592
4593         default:
4594           goto out;
4595         }
4596
4597       if (l)
4598         {
4599           focus_link = l->data;
4600           info->selection_anchor = focus_link->start;
4601           info->selection_end = focus_link->start;
4602           gtk_widget_queue_draw (widget);
4603
4604           return TRUE;
4605         }
4606     }
4607
4608 out:
4609
4610   return FALSE;
4611 }
4612
4613 static gboolean
4614 gtk_label_button_press (GtkWidget      *widget,
4615                         GdkEventButton *event)
4616 {
4617   GtkLabel *label = GTK_LABEL (widget);
4618   GtkLabelPrivate *priv = label->priv;
4619   GtkLabelSelectionInfo *info = priv->select_info;
4620   gint index = 0;
4621   gint min, max;
4622
4623   if (info == NULL)
4624     return FALSE;
4625
4626   if (info->active_link)
4627     {
4628       if (gdk_event_triggers_context_menu ((GdkEvent *) event))
4629         {
4630           info->link_clicked = 1;
4631           gtk_label_do_popup (label, event);
4632           return TRUE;
4633         }
4634       else if (event->button == 1)
4635         {
4636           info->link_clicked = 1;
4637           gtk_widget_queue_draw (widget);
4638         }
4639     }
4640
4641   if (!info->selectable)
4642     return FALSE;
4643
4644   info->in_drag = FALSE;
4645   info->select_words = FALSE;
4646
4647   if (gdk_event_triggers_context_menu ((GdkEvent *) event))
4648     {
4649       gtk_label_do_popup (label, event);
4650
4651       return TRUE;
4652     }
4653   else if (event->button == 1)
4654     {
4655       if (!gtk_widget_has_focus (widget))
4656         {
4657           priv->in_click = TRUE;
4658           gtk_widget_grab_focus (widget);
4659           priv->in_click = FALSE;
4660         }
4661
4662       if (event->type == GDK_3BUTTON_PRESS)
4663         {
4664           gtk_label_select_region_index (label, 0, strlen (priv->text));
4665           return TRUE;
4666         }
4667
4668       if (event->type == GDK_2BUTTON_PRESS)
4669         {
4670           info->select_words = TRUE;
4671           gtk_label_select_word (label);
4672           return TRUE;
4673         }
4674
4675       get_layout_index (label, event->x, event->y, &index);
4676
4677       min = MIN (info->selection_anchor, info->selection_end);
4678       max = MAX (info->selection_anchor, info->selection_end);
4679
4680       if ((info->selection_anchor != info->selection_end) &&
4681           (event->state & GDK_SHIFT_MASK))
4682         {
4683           if (index > min && index < max)
4684             {
4685               /* truncate selection, but keep it as big as possible */
4686               if (index - min > max - index)
4687                 max = index;
4688               else
4689                 min = index;
4690             }
4691           else
4692             {
4693               /* extend (same as motion) */
4694               min = MIN (min, index);
4695               max = MAX (max, index);
4696             }
4697
4698           /* ensure the anchor is opposite index */
4699           if (index == min)
4700             {
4701               gint tmp = min;
4702               min = max;
4703               max = tmp;
4704             }
4705
4706           gtk_label_select_region_index (label, min, max);
4707         }
4708       else
4709         {
4710           if (event->type == GDK_3BUTTON_PRESS)
4711             gtk_label_select_region_index (label, 0, strlen (priv->text));
4712           else if (event->type == GDK_2BUTTON_PRESS)
4713             gtk_label_select_word (label);
4714           else if (min < max && min <= index && index <= max)
4715             {
4716               info->in_drag = TRUE;
4717               info->drag_start_x = event->x;
4718               info->drag_start_y = event->y;
4719             }
4720           else
4721             /* start a replacement */
4722             gtk_label_select_region_index (label, index, index);
4723         }
4724
4725       return TRUE;
4726     }
4727
4728   return FALSE;
4729 }
4730
4731 static gboolean
4732 gtk_label_button_release (GtkWidget      *widget,
4733                           GdkEventButton *event)
4734
4735 {
4736   GtkLabel *label = GTK_LABEL (widget);
4737   GtkLabelPrivate *priv = label->priv;
4738   GtkLabelSelectionInfo *info = priv->select_info;
4739   gint index;
4740
4741   if (info == NULL)
4742     return FALSE;
4743
4744   if (info->in_drag)
4745     {
4746       info->in_drag = 0;
4747
4748       get_layout_index (label, event->x, event->y, &index);
4749       gtk_label_select_region_index (label, index, index);
4750
4751       return FALSE;
4752     }
4753
4754   if (event->button != 1)
4755     return FALSE;
4756
4757   if (info->active_link &&
4758       info->selection_anchor == info->selection_end &&
4759       info->link_clicked)
4760     {
4761       emit_activate_link (label, info->active_link);
4762       info->link_clicked = 0;
4763
4764       return TRUE;
4765     }
4766
4767   /* The goal here is to return TRUE iff we ate the
4768    * button press to start selecting.
4769    */
4770   return TRUE;
4771 }
4772
4773 static void
4774 connect_mnemonics_visible_notify (GtkLabel *label)
4775 {
4776   GtkLabelPrivate *priv = label->priv;
4777   GtkWidget *toplevel;
4778   gboolean connected;
4779
4780   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (label));
4781
4782   if (!GTK_IS_WINDOW (toplevel))
4783     return;
4784
4785   /* always set up this widgets initial value */
4786   priv->mnemonics_visible =
4787     gtk_window_get_mnemonics_visible (GTK_WINDOW (toplevel));
4788
4789   connected =
4790     GPOINTER_TO_INT (g_object_get_data (G_OBJECT (toplevel),
4791                                         "gtk-label-mnemonics-visible-connected"));
4792
4793   if (!connected)
4794     {
4795       g_signal_connect (toplevel,
4796                         "notify::mnemonics-visible",
4797                         G_CALLBACK (label_mnemonics_visible_changed),
4798                         label);
4799       g_object_set_data (G_OBJECT (toplevel),
4800                          "gtk-label-mnemonics-visible-connected",
4801                          GINT_TO_POINTER (1));
4802     }
4803 }
4804
4805 static void
4806 drag_begin_cb (GtkWidget      *widget,
4807                GdkDragContext *context,
4808                gpointer        data)
4809 {
4810   GtkLabel *label = GTK_LABEL (widget);
4811   GtkLabelPrivate *priv = label->priv;
4812   cairo_surface_t *surface = NULL;
4813
4814   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
4815
4816   if ((priv->select_info->selection_anchor !=
4817        priv->select_info->selection_end) &&
4818       priv->text)
4819     {
4820       gint start, end;
4821       gint len;
4822
4823       start = MIN (priv->select_info->selection_anchor,
4824                    priv->select_info->selection_end);
4825       end = MAX (priv->select_info->selection_anchor,
4826                  priv->select_info->selection_end);
4827
4828       len = strlen (priv->text);
4829
4830       if (end > len)
4831         end = len;
4832
4833       if (start > len)
4834         start = len;
4835
4836       surface = _gtk_text_util_create_drag_icon (widget,
4837                                                  priv->text + start,
4838                                                  end - start);
4839     }
4840
4841   if (surface)
4842     {
4843       gtk_drag_set_icon_surface (context, surface);
4844       cairo_surface_destroy (surface);
4845     }
4846   else
4847     {
4848       gtk_drag_set_icon_default (context);
4849     }
4850 }
4851
4852 static gboolean
4853 gtk_label_motion (GtkWidget      *widget,
4854                   GdkEventMotion *event)
4855 {
4856   GtkLabel *label = GTK_LABEL (widget);
4857   GtkLabelPrivate *priv = label->priv;
4858   GtkLabelSelectionInfo *info = priv->select_info;
4859   gint index;
4860
4861   if (info == NULL)
4862     return FALSE;
4863
4864   if (info->links && !info->in_drag)
4865     {
4866       GList *l;
4867       GtkLabelLink *link;
4868       gboolean found = FALSE;
4869
4870       if (info->selection_anchor == info->selection_end)
4871         {
4872           if (get_layout_index (label, event->x, event->y, &index))
4873             {
4874               for (l = info->links; l != NULL; l = l->next)
4875                 {
4876                   link = l->data;
4877                   if (index >= link->start && index <= link->end)
4878                     {
4879                       found = TRUE;
4880                       break;
4881                     }
4882                 }
4883             }
4884         }
4885
4886       if (found)
4887         {
4888           if (info->active_link != link)
4889             {
4890               info->link_clicked = 0;
4891               info->active_link = link;
4892               gtk_label_update_cursor (label);
4893               gtk_widget_queue_draw (widget);
4894             }
4895         }
4896       else
4897         {
4898           if (info->active_link != NULL)
4899             {
4900               info->link_clicked = 0;
4901               info->active_link = NULL;
4902               gtk_label_update_cursor (label);
4903               gtk_widget_queue_draw (widget);
4904             }
4905         }
4906     }
4907
4908   if (!info->selectable)
4909     return FALSE;
4910
4911   if ((event->state & GDK_BUTTON1_MASK) == 0)
4912     return FALSE;
4913
4914   if (info->in_drag)
4915     {
4916       if (gtk_drag_check_threshold (widget,
4917                                     info->drag_start_x,
4918                                     info->drag_start_y,
4919                                     event->x, event->y))
4920         {
4921           GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
4922
4923           gtk_target_list_add_text_targets (target_list, 0);
4924
4925           g_signal_connect (widget, "drag-begin",
4926                             G_CALLBACK (drag_begin_cb), NULL);
4927           gtk_drag_begin (widget, target_list,
4928                           GDK_ACTION_COPY,
4929                           1, (GdkEvent *)event);
4930
4931           info->in_drag = FALSE;
4932
4933           gtk_target_list_unref (target_list);
4934         }
4935     }
4936   else
4937     {
4938       gint x, y;
4939
4940       gdk_window_get_device_position (info->window, event->device, &x, &y, NULL);
4941       get_layout_index (label, x, y, &index);
4942
4943       if (info->select_words)
4944         {
4945           gint min, max;
4946           gint old_min, old_max;
4947           gint anchor, end;
4948
4949           min = gtk_label_move_backward_word (label, index);
4950           max = gtk_label_move_forward_word (label, index);
4951
4952           anchor = info->selection_anchor;
4953           end = info->selection_end;
4954
4955           old_min = MIN (anchor, end);
4956           old_max = MAX (anchor, end);
4957
4958           if (min < old_min)
4959             {
4960               anchor = min;
4961               end = old_max;
4962             }
4963           else if (old_max < max)
4964             {
4965               anchor = max;
4966               end = old_min;
4967             }
4968           else if (anchor == old_min)
4969             {
4970               if (anchor != min)
4971                 anchor = max;
4972             }
4973           else
4974             {
4975               if (anchor != max)
4976                 anchor = min;
4977             }
4978
4979           gtk_label_select_region_index (label, anchor, end);
4980         }
4981       else
4982         gtk_label_select_region_index (label, info->selection_anchor, index);
4983     }
4984
4985   return TRUE;
4986 }
4987
4988 static gboolean
4989 gtk_label_leave_notify (GtkWidget        *widget,
4990                         GdkEventCrossing *event)
4991 {
4992   GtkLabel *label = GTK_LABEL (widget);
4993   GtkLabelPrivate *priv = label->priv;
4994
4995   if (priv->select_info)
4996     {
4997       priv->select_info->active_link = NULL;
4998       gtk_label_update_cursor (label);
4999       gtk_widget_queue_draw (widget);
5000     }
5001
5002   if (GTK_WIDGET_CLASS (gtk_label_parent_class)->leave_notify_event)
5003     return GTK_WIDGET_CLASS (gtk_label_parent_class)->leave_notify_event (widget, event);
5004
5005  return FALSE;
5006 }
5007
5008 static void
5009 gtk_label_create_window (GtkLabel *label)
5010 {
5011   GtkLabelPrivate *priv = label->priv;
5012   GtkAllocation allocation;
5013   GtkWidget *widget;
5014   GdkWindowAttr attributes;
5015   gint attributes_mask;
5016
5017   g_assert (priv->select_info);
5018   widget = GTK_WIDGET (label);
5019   g_assert (gtk_widget_get_realized (widget));
5020
5021   if (priv->select_info->window)
5022     return;
5023
5024   gtk_widget_get_allocation (widget, &allocation);
5025
5026   attributes.x = allocation.x;
5027   attributes.y = allocation.y;
5028   attributes.width = allocation.width;
5029   attributes.height = allocation.height;
5030   attributes.window_type = GDK_WINDOW_CHILD;
5031   attributes.wclass = GDK_INPUT_ONLY;
5032   attributes.override_redirect = TRUE;
5033   attributes.event_mask = gtk_widget_get_events (widget) |
5034     GDK_BUTTON_PRESS_MASK        |
5035     GDK_BUTTON_RELEASE_MASK      |
5036     GDK_LEAVE_NOTIFY_MASK        |
5037     GDK_BUTTON_MOTION_MASK       |
5038     GDK_POINTER_MOTION_MASK      |
5039     GDK_POINTER_MOTION_HINT_MASK;
5040   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_NOREDIR;
5041   if (gtk_widget_is_sensitive (widget))
5042     {
5043       attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget),
5044                                                       GDK_XTERM);
5045       attributes_mask |= GDK_WA_CURSOR;
5046     }
5047
5048
5049   priv->select_info->window = gdk_window_new (gtk_widget_get_window (widget),
5050                                                &attributes, attributes_mask);
5051   gdk_window_set_user_data (priv->select_info->window, widget);
5052
5053   if (attributes_mask & GDK_WA_CURSOR)
5054     g_object_unref (attributes.cursor);
5055 }
5056
5057 static void
5058 gtk_label_destroy_window (GtkLabel *label)
5059 {
5060   GtkLabelPrivate *priv = label->priv;
5061
5062   g_assert (priv->select_info);
5063
5064   if (priv->select_info->window == NULL)
5065     return;
5066
5067   gdk_window_set_user_data (priv->select_info->window, NULL);
5068   gdk_window_destroy (priv->select_info->window);
5069   priv->select_info->window = NULL;
5070 }
5071
5072 static void
5073 gtk_label_ensure_select_info (GtkLabel *label)
5074 {
5075   GtkLabelPrivate *priv = label->priv;
5076
5077   if (priv->select_info == NULL)
5078     {
5079       priv->select_info = g_new0 (GtkLabelSelectionInfo, 1);
5080
5081       gtk_widget_set_can_focus (GTK_WIDGET (label), TRUE);
5082
5083       if (gtk_widget_get_realized (GTK_WIDGET (label)))
5084         gtk_label_create_window (label);
5085
5086       if (gtk_widget_get_mapped (GTK_WIDGET (label)))
5087         gdk_window_show (priv->select_info->window);
5088     }
5089 }
5090
5091 static void
5092 gtk_label_clear_select_info (GtkLabel *label)
5093 {
5094   GtkLabelPrivate *priv = label->priv;
5095
5096   if (priv->select_info == NULL)
5097     return;
5098
5099   if (!priv->select_info->selectable && !priv->select_info->links)
5100     {
5101       gtk_label_destroy_window (label);
5102
5103       g_free (priv->select_info);
5104       priv->select_info = NULL;
5105
5106       gtk_widget_set_can_focus (GTK_WIDGET (label), FALSE);
5107     }
5108 }
5109
5110 /**
5111  * gtk_label_set_selectable:
5112  * @label: a #GtkLabel
5113  * @setting: %TRUE to allow selecting text in the label
5114  *
5115  * Selectable labels allow the user to select text from the label, for
5116  * copy-and-paste.
5117  **/
5118 void
5119 gtk_label_set_selectable (GtkLabel *label,
5120                           gboolean  setting)
5121 {
5122   GtkLabelPrivate *priv;
5123   gboolean old_setting;
5124
5125   g_return_if_fail (GTK_IS_LABEL (label));
5126
5127   priv = label->priv;
5128
5129   setting = setting != FALSE;
5130   old_setting = priv->select_info && priv->select_info->selectable;
5131
5132   if (setting)
5133     {
5134       gtk_label_ensure_select_info (label);
5135       priv->select_info->selectable = TRUE;
5136       gtk_label_update_cursor (label);
5137     }
5138   else
5139     {
5140       if (old_setting)
5141         {
5142           /* unselect, to give up the selection */
5143           gtk_label_select_region (label, 0, 0);
5144
5145           priv->select_info->selectable = FALSE;
5146           gtk_label_clear_select_info (label);
5147           gtk_label_update_cursor (label);
5148         }
5149     }
5150   if (setting != old_setting)
5151     {
5152       g_object_freeze_notify (G_OBJECT (label));
5153       g_object_notify (G_OBJECT (label), "selectable");
5154       g_object_notify (G_OBJECT (label), "cursor-position");
5155       g_object_notify (G_OBJECT (label), "selection-bound");
5156       g_object_thaw_notify (G_OBJECT (label));
5157       gtk_widget_queue_draw (GTK_WIDGET (label));
5158     }
5159 }
5160
5161 /**
5162  * gtk_label_get_selectable:
5163  * @label: a #GtkLabel
5164  * 
5165  * Gets the value set by gtk_label_set_selectable().
5166  * 
5167  * Return value: %TRUE if the user can copy text from the label
5168  **/
5169 gboolean
5170 gtk_label_get_selectable (GtkLabel *label)
5171 {
5172   GtkLabelPrivate *priv;
5173
5174   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5175
5176   priv = label->priv;
5177
5178   return priv->select_info && priv->select_info->selectable;
5179 }
5180
5181 /**
5182  * gtk_label_set_angle:
5183  * @label: a #GtkLabel
5184  * @angle: the angle that the baseline of the label makes with
5185  *   the horizontal, in degrees, measured counterclockwise
5186  * 
5187  * Sets the angle of rotation for the label. An angle of 90 reads from
5188  * from bottom to top, an angle of 270, from top to bottom. The angle
5189  * setting for the label is ignored if the label is selectable,
5190  * wrapped, or ellipsized.
5191  *
5192  * Since: 2.6
5193  **/
5194 void
5195 gtk_label_set_angle (GtkLabel *label,
5196                      gdouble   angle)
5197 {
5198   GtkLabelPrivate *priv;
5199
5200   g_return_if_fail (GTK_IS_LABEL (label));
5201
5202   priv = label->priv;
5203
5204   /* Canonicalize to [0,360]. We don't canonicalize 360 to 0, because
5205    * double property ranges are inclusive, and changing 360 to 0 would
5206    * make a property editor behave strangely.
5207    */
5208   if (angle < 0 || angle > 360.0)
5209     angle = angle - 360. * floor (angle / 360.);
5210
5211   if (priv->angle != angle)
5212     {
5213       priv->angle = angle;
5214       
5215       gtk_label_clear_layout (label);
5216       gtk_widget_queue_resize (GTK_WIDGET (label));
5217
5218       g_object_notify (G_OBJECT (label), "angle");
5219     }
5220 }
5221
5222 /**
5223  * gtk_label_get_angle:
5224  * @label: a #GtkLabel
5225  * 
5226  * Gets the angle of rotation for the label. See
5227  * gtk_label_set_angle().
5228  * 
5229  * Return value: the angle of rotation for the label
5230  *
5231  * Since: 2.6
5232  **/
5233 gdouble
5234 gtk_label_get_angle  (GtkLabel *label)
5235 {
5236   g_return_val_if_fail (GTK_IS_LABEL (label), 0.0);
5237   
5238   return label->priv->angle;
5239 }
5240
5241 static void
5242 gtk_label_set_selection_text (GtkLabel         *label,
5243                               GtkSelectionData *selection_data)
5244 {
5245   GtkLabelPrivate *priv = label->priv;
5246
5247   if (priv->select_info &&
5248       (priv->select_info->selection_anchor !=
5249        priv->select_info->selection_end) &&
5250       priv->text)
5251     {
5252       gint start, end;
5253       gint len;
5254
5255       start = MIN (priv->select_info->selection_anchor,
5256                    priv->select_info->selection_end);
5257       end = MAX (priv->select_info->selection_anchor,
5258                  priv->select_info->selection_end);
5259
5260       len = strlen (priv->text);
5261
5262       if (end > len)
5263         end = len;
5264
5265       if (start > len)
5266         start = len;
5267
5268       gtk_selection_data_set_text (selection_data,
5269                                    priv->text + start,
5270                                    end - start);
5271     }
5272 }
5273
5274 static void
5275 gtk_label_drag_data_get (GtkWidget        *widget,
5276                          GdkDragContext   *context,
5277                          GtkSelectionData *selection_data,
5278                          guint             info,
5279                          guint             time)
5280 {
5281   gtk_label_set_selection_text (GTK_LABEL (widget), selection_data);
5282 }
5283
5284 static void
5285 get_text_callback (GtkClipboard     *clipboard,
5286                    GtkSelectionData *selection_data,
5287                    guint             info,
5288                    gpointer          user_data_or_owner)
5289 {
5290   gtk_label_set_selection_text (GTK_LABEL (user_data_or_owner), selection_data);
5291 }
5292
5293 static void
5294 clear_text_callback (GtkClipboard     *clipboard,
5295                      gpointer          user_data_or_owner)
5296 {
5297   GtkLabel *label;
5298   GtkLabelPrivate *priv;
5299
5300   label = GTK_LABEL (user_data_or_owner);
5301   priv = label->priv;
5302
5303   if (priv->select_info)
5304     {
5305       priv->select_info->selection_anchor = priv->select_info->selection_end;
5306
5307       gtk_widget_queue_draw (GTK_WIDGET (label));
5308     }
5309 }
5310
5311 static void
5312 gtk_label_select_region_index (GtkLabel *label,
5313                                gint      anchor_index,
5314                                gint      end_index)
5315 {
5316   GtkLabelPrivate *priv;
5317
5318   g_return_if_fail (GTK_IS_LABEL (label));
5319
5320   priv = label->priv;
5321
5322   if (priv->select_info && priv->select_info->selectable)
5323     {
5324       GtkClipboard *clipboard;
5325
5326       if (priv->select_info->selection_anchor == anchor_index &&
5327           priv->select_info->selection_end == end_index)
5328         return;
5329
5330       g_object_freeze_notify (G_OBJECT (label));
5331
5332       if (priv->select_info->selection_anchor != anchor_index)
5333         g_object_notify (G_OBJECT (label), "selection-bound");
5334       if (priv->select_info->selection_end != end_index)
5335         g_object_notify (G_OBJECT (label), "cursor-position");
5336
5337       priv->select_info->selection_anchor = anchor_index;
5338       priv->select_info->selection_end = end_index;
5339
5340       if (gtk_widget_has_screen (GTK_WIDGET (label)))
5341         clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label),
5342                                               GDK_SELECTION_PRIMARY);
5343       else
5344         clipboard = NULL;
5345
5346       if (anchor_index != end_index)
5347         {
5348           GtkTargetList *list;
5349           GtkTargetEntry *targets;
5350           gint n_targets;
5351
5352           list = gtk_target_list_new (NULL, 0);
5353           gtk_target_list_add_text_targets (list, 0);
5354           targets = gtk_target_table_new_from_list (list, &n_targets);
5355
5356           if (clipboard)
5357             gtk_clipboard_set_with_owner (clipboard,
5358                                           targets, n_targets,
5359                                           get_text_callback,
5360                                           clear_text_callback,
5361                                           G_OBJECT (label));
5362
5363           gtk_target_table_free (targets, n_targets);
5364           gtk_target_list_unref (list);
5365         }
5366       else
5367         {
5368           if (clipboard &&
5369               gtk_clipboard_get_owner (clipboard) == G_OBJECT (label))
5370             gtk_clipboard_clear (clipboard);
5371         }
5372
5373       gtk_widget_queue_draw (GTK_WIDGET (label));
5374
5375       g_object_thaw_notify (G_OBJECT (label));
5376     }
5377 }
5378
5379 /**
5380  * gtk_label_select_region:
5381  * @label: a #GtkLabel
5382  * @start_offset: start offset (in characters not bytes)
5383  * @end_offset: end offset (in characters not bytes)
5384  *
5385  * Selects a range of characters in the label, if the label is selectable.
5386  * See gtk_label_set_selectable(). If the label is not selectable,
5387  * this function has no effect. If @start_offset or
5388  * @end_offset are -1, then the end of the label will be substituted.
5389  **/
5390 void
5391 gtk_label_select_region  (GtkLabel *label,
5392                           gint      start_offset,
5393                           gint      end_offset)
5394 {
5395   GtkLabelPrivate *priv;
5396
5397   g_return_if_fail (GTK_IS_LABEL (label));
5398
5399   priv = label->priv;
5400
5401   if (priv->text && priv->select_info)
5402     {
5403       if (start_offset < 0)
5404         start_offset = g_utf8_strlen (priv->text, -1);
5405       
5406       if (end_offset < 0)
5407         end_offset = g_utf8_strlen (priv->text, -1);
5408       
5409       gtk_label_select_region_index (label,
5410                                      g_utf8_offset_to_pointer (priv->text, start_offset) - priv->text,
5411                                      g_utf8_offset_to_pointer (priv->text, end_offset) - priv->text);
5412     }
5413 }
5414
5415 /**
5416  * gtk_label_get_selection_bounds:
5417  * @label: a #GtkLabel
5418  * @start: (out): return location for start of selection, as a character offset
5419  * @end: (out): return location for end of selection, as a character offset
5420  * 
5421  * Gets the selected range of characters in the label, returning %TRUE
5422  * if there's a selection.
5423  * 
5424  * Return value: %TRUE if selection is non-empty
5425  **/
5426 gboolean
5427 gtk_label_get_selection_bounds (GtkLabel  *label,
5428                                 gint      *start,
5429                                 gint      *end)
5430 {
5431   GtkLabelPrivate *priv;
5432
5433   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5434
5435   priv = label->priv;
5436
5437   if (priv->select_info == NULL)
5438     {
5439       /* not a selectable label */
5440       if (start)
5441         *start = 0;
5442       if (end)
5443         *end = 0;
5444
5445       return FALSE;
5446     }
5447   else
5448     {
5449       gint start_index, end_index;
5450       gint start_offset, end_offset;
5451       gint len;
5452       
5453       start_index = MIN (priv->select_info->selection_anchor,
5454                    priv->select_info->selection_end);
5455       end_index = MAX (priv->select_info->selection_anchor,
5456                  priv->select_info->selection_end);
5457
5458       len = strlen (priv->text);
5459
5460       if (end_index > len)
5461         end_index = len;
5462
5463       if (start_index > len)
5464         start_index = len;
5465       
5466       start_offset = g_utf8_strlen (priv->text, start_index);
5467       end_offset = g_utf8_strlen (priv->text, end_index);
5468
5469       if (start_offset > end_offset)
5470         {
5471           gint tmp = start_offset;
5472           start_offset = end_offset;
5473           end_offset = tmp;
5474         }
5475       
5476       if (start)
5477         *start = start_offset;
5478
5479       if (end)
5480         *end = end_offset;
5481
5482       return start_offset != end_offset;
5483     }
5484 }
5485
5486
5487 /**
5488  * gtk_label_get_layout:
5489  * @label: a #GtkLabel
5490  * 
5491  * Gets the #PangoLayout used to display the label.
5492  * The layout is useful to e.g. convert text positions to
5493  * pixel positions, in combination with gtk_label_get_layout_offsets().
5494  * The returned layout is owned by the @label so need not be
5495  * freed by the caller. The @label is free to recreate its layout at
5496  * any time, so it should be considered read-only.
5497  *
5498  * Return value: (transfer none): the #PangoLayout for this label
5499  **/
5500 PangoLayout*
5501 gtk_label_get_layout (GtkLabel *label)
5502 {
5503   GtkLabelPrivate *priv;
5504
5505   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
5506
5507   priv = label->priv;
5508
5509   gtk_label_ensure_layout (label);
5510
5511   return priv->layout;
5512 }
5513
5514 /**
5515  * gtk_label_get_layout_offsets:
5516  * @label: a #GtkLabel
5517  * @x: (out) (allow-none): location to store X offset of layout, or %NULL
5518  * @y: (out) (allow-none): location to store Y offset of layout, or %NULL
5519  *
5520  * Obtains the coordinates where the label will draw the #PangoLayout
5521  * representing the text in the label; useful to convert mouse events
5522  * into coordinates inside the #PangoLayout, e.g. to take some action
5523  * if some part of the label is clicked. Of course you will need to
5524  * create a #GtkEventBox to receive the events, and pack the label
5525  * inside it, since labels are a #GTK_NO_WINDOW widget. Remember
5526  * when using the #PangoLayout functions you need to convert to
5527  * and from pixels using PANGO_PIXELS() or #PANGO_SCALE.
5528  **/
5529 void
5530 gtk_label_get_layout_offsets (GtkLabel *label,
5531                               gint     *x,
5532                               gint     *y)
5533 {
5534   g_return_if_fail (GTK_IS_LABEL (label));
5535
5536   gtk_label_ensure_layout (label);
5537
5538   get_layout_location (label, x, y);
5539 }
5540
5541 /**
5542  * gtk_label_set_use_markup:
5543  * @label: a #GtkLabel
5544  * @setting: %TRUE if the label's text should be parsed for markup.
5545  *
5546  * Sets whether the text of the label contains markup in <link
5547  * linkend="PangoMarkupFormat">Pango's text markup
5548  * language</link>. See gtk_label_set_markup().
5549  **/
5550 void
5551 gtk_label_set_use_markup (GtkLabel *label,
5552                           gboolean  setting)
5553 {
5554   g_return_if_fail (GTK_IS_LABEL (label));
5555
5556   g_object_freeze_notify (G_OBJECT (label));
5557
5558   gtk_label_set_use_markup_internal (label, setting);
5559   gtk_label_recalculate (label);
5560
5561   g_object_thaw_notify (G_OBJECT (label));
5562 }
5563
5564 /**
5565  * gtk_label_get_use_markup:
5566  * @label: a #GtkLabel
5567  *
5568  * Returns whether the label's text is interpreted as marked up with
5569  * the <link linkend="PangoMarkupFormat">Pango text markup
5570  * language</link>. See gtk_label_set_use_markup ().
5571  *
5572  * Return value: %TRUE if the label's text will be parsed for markup.
5573  **/
5574 gboolean
5575 gtk_label_get_use_markup (GtkLabel *label)
5576 {
5577   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5578
5579   return label->priv->use_markup;
5580 }
5581
5582 /**
5583  * gtk_label_set_use_underline:
5584  * @label: a #GtkLabel
5585  * @setting: %TRUE if underlines in the text indicate mnemonics
5586  *
5587  * If true, an underline in the text indicates the next character should be
5588  * used for the mnemonic accelerator key.
5589  */
5590 void
5591 gtk_label_set_use_underline (GtkLabel *label,
5592                              gboolean  setting)
5593 {
5594   g_return_if_fail (GTK_IS_LABEL (label));
5595
5596   g_object_freeze_notify (G_OBJECT (label));
5597
5598   gtk_label_set_use_underline_internal (label, setting);
5599   gtk_label_recalculate (label);
5600
5601   g_object_thaw_notify (G_OBJECT (label));
5602 }
5603
5604 /**
5605  * gtk_label_get_use_underline:
5606  * @label: a #GtkLabel
5607  *
5608  * Returns whether an embedded underline in the label indicates a
5609  * mnemonic. See gtk_label_set_use_underline().
5610  *
5611  * Return value: %TRUE whether an embedded underline in the label indicates
5612  *               the mnemonic accelerator keys.
5613  **/
5614 gboolean
5615 gtk_label_get_use_underline (GtkLabel *label)
5616 {
5617   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5618
5619   return label->priv->use_underline;
5620 }
5621
5622 /**
5623  * gtk_label_set_single_line_mode:
5624  * @label: a #GtkLabel
5625  * @single_line_mode: %TRUE if the label should be in single line mode
5626  *
5627  * Sets whether the label is in single line mode.
5628  *
5629  * Since: 2.6
5630  */
5631 void
5632 gtk_label_set_single_line_mode (GtkLabel *label,
5633                                 gboolean single_line_mode)
5634 {
5635   GtkLabelPrivate *priv;
5636
5637   g_return_if_fail (GTK_IS_LABEL (label));
5638
5639   priv = label->priv;
5640
5641   single_line_mode = single_line_mode != FALSE;
5642
5643   if (priv->single_line_mode != single_line_mode)
5644     {
5645       priv->single_line_mode = single_line_mode;
5646
5647       gtk_label_clear_layout (label);
5648       gtk_widget_queue_resize (GTK_WIDGET (label));
5649
5650       g_object_notify (G_OBJECT (label), "single-line-mode");
5651     }
5652 }
5653
5654 /**
5655  * gtk_label_get_single_line_mode:
5656  * @label: a #GtkLabel
5657  *
5658  * Returns whether the label is in single line mode.
5659  *
5660  * Return value: %TRUE when the label is in single line mode.
5661  *
5662  * Since: 2.6
5663  **/
5664 gboolean
5665 gtk_label_get_single_line_mode  (GtkLabel *label)
5666 {
5667   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5668
5669   return label->priv->single_line_mode;
5670 }
5671
5672 /* Compute the X position for an offset that corresponds to the "more important
5673  * cursor position for that offset. We use this when trying to guess to which
5674  * end of the selection we should go to when the user hits the left or
5675  * right arrow key.
5676  */
5677 static void
5678 get_better_cursor (GtkLabel *label,
5679                    gint      index,
5680                    gint      *x,
5681                    gint      *y)
5682 {
5683   GtkLabelPrivate *priv = label->priv;
5684   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
5685   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
5686   PangoDirection cursor_direction = get_cursor_direction (label);
5687   gboolean split_cursor;
5688   PangoRectangle strong_pos, weak_pos;
5689   
5690   g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
5691                 "gtk-split-cursor", &split_cursor,
5692                 NULL);
5693
5694   gtk_label_ensure_layout (label);
5695   
5696   pango_layout_get_cursor_pos (priv->layout, index,
5697                                &strong_pos, &weak_pos);
5698
5699   if (split_cursor)
5700     {
5701       *x = strong_pos.x / PANGO_SCALE;
5702       *y = strong_pos.y / PANGO_SCALE;
5703     }
5704   else
5705     {
5706       if (keymap_direction == cursor_direction)
5707         {
5708           *x = strong_pos.x / PANGO_SCALE;
5709           *y = strong_pos.y / PANGO_SCALE;
5710         }
5711       else
5712         {
5713           *x = weak_pos.x / PANGO_SCALE;
5714           *y = weak_pos.y / PANGO_SCALE;
5715         }
5716     }
5717 }
5718
5719
5720 static gint
5721 gtk_label_move_logically (GtkLabel *label,
5722                           gint      start,
5723                           gint      count)
5724 {
5725   GtkLabelPrivate *priv = label->priv;
5726   gint offset = g_utf8_pointer_to_offset (priv->text,
5727                                           priv->text + start);
5728
5729   if (priv->text)
5730     {
5731       PangoLogAttr *log_attrs;
5732       gint n_attrs;
5733       gint length;
5734
5735       gtk_label_ensure_layout (label);
5736       
5737       length = g_utf8_strlen (priv->text, -1);
5738
5739       pango_layout_get_log_attrs (priv->layout, &log_attrs, &n_attrs);
5740
5741       while (count > 0 && offset < length)
5742         {
5743           do
5744             offset++;
5745           while (offset < length && !log_attrs[offset].is_cursor_position);
5746           
5747           count--;
5748         }
5749       while (count < 0 && offset > 0)
5750         {
5751           do
5752             offset--;
5753           while (offset > 0 && !log_attrs[offset].is_cursor_position);
5754           
5755           count++;
5756         }
5757       
5758       g_free (log_attrs);
5759     }
5760
5761   return g_utf8_offset_to_pointer (priv->text, offset) - priv->text;
5762 }
5763
5764 static gint
5765 gtk_label_move_visually (GtkLabel *label,
5766                          gint      start,
5767                          gint      count)
5768 {
5769   GtkLabelPrivate *priv = label->priv;
5770   gint index;
5771
5772   index = start;
5773   
5774   while (count != 0)
5775     {
5776       int new_index, new_trailing;
5777       gboolean split_cursor;
5778       gboolean strong;
5779
5780       gtk_label_ensure_layout (label);
5781
5782       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
5783                     "gtk-split-cursor", &split_cursor,
5784                     NULL);
5785
5786       if (split_cursor)
5787         strong = TRUE;
5788       else
5789         {
5790           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
5791           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
5792
5793           strong = keymap_direction == get_cursor_direction (label);
5794         }
5795       
5796       if (count > 0)
5797         {
5798           pango_layout_move_cursor_visually (priv->layout, strong, index, 0, 1, &new_index, &new_trailing);
5799           count--;
5800         }
5801       else
5802         {
5803           pango_layout_move_cursor_visually (priv->layout, strong, index, 0, -1, &new_index, &new_trailing);
5804           count++;
5805         }
5806
5807       if (new_index < 0 || new_index == G_MAXINT)
5808         break;
5809
5810       index = new_index;
5811       
5812       while (new_trailing--)
5813         index = g_utf8_next_char (priv->text + new_index) - priv->text;
5814     }
5815   
5816   return index;
5817 }
5818
5819 static gint
5820 gtk_label_move_forward_word (GtkLabel *label,
5821                              gint      start)
5822 {
5823   GtkLabelPrivate *priv = label->priv;
5824   gint new_pos = g_utf8_pointer_to_offset (priv->text,
5825                                            priv->text + start);
5826   gint length;
5827
5828   length = g_utf8_strlen (priv->text, -1);
5829   if (new_pos < length)
5830     {
5831       PangoLogAttr *log_attrs;
5832       gint n_attrs;
5833
5834       gtk_label_ensure_layout (label);
5835
5836       pango_layout_get_log_attrs (priv->layout, &log_attrs, &n_attrs);
5837
5838       /* Find the next word end */
5839       new_pos++;
5840       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
5841         new_pos++;
5842
5843       g_free (log_attrs);
5844     }
5845
5846   return g_utf8_offset_to_pointer (priv->text, new_pos) - priv->text;
5847 }
5848
5849
5850 static gint
5851 gtk_label_move_backward_word (GtkLabel *label,
5852                               gint      start)
5853 {
5854   GtkLabelPrivate *priv = label->priv;
5855   gint new_pos = g_utf8_pointer_to_offset (priv->text,
5856                                            priv->text + start);
5857
5858   if (new_pos > 0)
5859     {
5860       PangoLogAttr *log_attrs;
5861       gint n_attrs;
5862
5863       gtk_label_ensure_layout (label);
5864
5865       pango_layout_get_log_attrs (priv->layout, &log_attrs, &n_attrs);
5866
5867       new_pos -= 1;
5868
5869       /* Find the previous word beginning */
5870       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
5871         new_pos--;
5872
5873       g_free (log_attrs);
5874     }
5875
5876   return g_utf8_offset_to_pointer (priv->text, new_pos) - priv->text;
5877 }
5878
5879 static void
5880 gtk_label_move_cursor (GtkLabel       *label,
5881                        GtkMovementStep step,
5882                        gint            count,
5883                        gboolean        extend_selection)
5884 {
5885   GtkLabelPrivate *priv = label->priv;
5886   gint old_pos;
5887   gint new_pos;
5888
5889   if (priv->select_info == NULL)
5890     return;
5891
5892   old_pos = new_pos = priv->select_info->selection_end;
5893
5894   if (priv->select_info->selection_end != priv->select_info->selection_anchor &&
5895       !extend_selection)
5896     {
5897       /* If we have a current selection and aren't extending it, move to the
5898        * start/or end of the selection as appropriate
5899        */
5900       switch (step)
5901         {
5902         case GTK_MOVEMENT_VISUAL_POSITIONS:
5903           {
5904             gint end_x, end_y;
5905             gint anchor_x, anchor_y;
5906             gboolean end_is_left;
5907
5908             get_better_cursor (label, priv->select_info->selection_end, &end_x, &end_y);
5909             get_better_cursor (label, priv->select_info->selection_anchor, &anchor_x, &anchor_y);
5910
5911             end_is_left = (end_y < anchor_y) || (end_y == anchor_y && end_x < anchor_x);
5912
5913             if (count < 0)
5914               new_pos = end_is_left ? priv->select_info->selection_end : priv->select_info->selection_anchor;
5915             else
5916               new_pos = !end_is_left ? priv->select_info->selection_end : priv->select_info->selection_anchor;
5917             break;
5918           }
5919         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5920         case GTK_MOVEMENT_WORDS:
5921           if (count < 0)
5922             new_pos = MIN (priv->select_info->selection_end, priv->select_info->selection_anchor);
5923           else
5924             new_pos = MAX (priv->select_info->selection_end, priv->select_info->selection_anchor);
5925           break;
5926         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5927         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5928         case GTK_MOVEMENT_BUFFER_ENDS:
5929           /* FIXME: Can do better here */
5930           new_pos = count < 0 ? 0 : strlen (priv->text);
5931           break;
5932         case GTK_MOVEMENT_DISPLAY_LINES:
5933         case GTK_MOVEMENT_PARAGRAPHS:
5934         case GTK_MOVEMENT_PAGES:
5935         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5936           break;
5937         }
5938     }
5939   else
5940     {
5941       switch (step)
5942         {
5943         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5944           new_pos = gtk_label_move_logically (label, new_pos, count);
5945           break;
5946         case GTK_MOVEMENT_VISUAL_POSITIONS:
5947           new_pos = gtk_label_move_visually (label, new_pos, count);
5948           if (new_pos == old_pos)
5949             {
5950               if (!extend_selection)
5951                 {
5952                   if (!gtk_widget_keynav_failed (GTK_WIDGET (label),
5953                                                  count > 0 ?
5954                                                  GTK_DIR_RIGHT : GTK_DIR_LEFT))
5955                     {
5956                       GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (label));
5957
5958                       if (toplevel)
5959                         gtk_widget_child_focus (toplevel,
5960                                                 count > 0 ?
5961                                                 GTK_DIR_RIGHT : GTK_DIR_LEFT);
5962                     }
5963                 }
5964               else
5965                 {
5966                   gtk_widget_error_bell (GTK_WIDGET (label));
5967                 }
5968             }
5969           break;
5970         case GTK_MOVEMENT_WORDS:
5971           while (count > 0)
5972             {
5973               new_pos = gtk_label_move_forward_word (label, new_pos);
5974               count--;
5975             }
5976           while (count < 0)
5977             {
5978               new_pos = gtk_label_move_backward_word (label, new_pos);
5979               count++;
5980             }
5981           if (new_pos == old_pos)
5982             gtk_widget_error_bell (GTK_WIDGET (label));
5983           break;
5984         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5985         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5986         case GTK_MOVEMENT_BUFFER_ENDS:
5987           /* FIXME: Can do better here */
5988           new_pos = count < 0 ? 0 : strlen (priv->text);
5989           if (new_pos == old_pos)
5990             gtk_widget_error_bell (GTK_WIDGET (label));
5991           break;
5992         case GTK_MOVEMENT_DISPLAY_LINES:
5993         case GTK_MOVEMENT_PARAGRAPHS:
5994         case GTK_MOVEMENT_PAGES:
5995         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5996           break;
5997         }
5998     }
5999
6000   if (extend_selection)
6001     gtk_label_select_region_index (label,
6002                                    priv->select_info->selection_anchor,
6003                                    new_pos);
6004   else
6005     gtk_label_select_region_index (label, new_pos, new_pos);
6006 }
6007
6008 static void
6009 gtk_label_copy_clipboard (GtkLabel *label)
6010 {
6011   GtkLabelPrivate *priv = label->priv;
6012
6013   if (priv->text && priv->select_info)
6014     {
6015       gint start, end;
6016       gint len;
6017       GtkClipboard *clipboard;
6018
6019       start = MIN (priv->select_info->selection_anchor,
6020                    priv->select_info->selection_end);
6021       end = MAX (priv->select_info->selection_anchor,
6022                  priv->select_info->selection_end);
6023
6024       len = strlen (priv->text);
6025
6026       if (end > len)
6027         end = len;
6028
6029       if (start > len)
6030         start = len;
6031
6032       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label), GDK_SELECTION_CLIPBOARD);
6033
6034       if (start != end)
6035         gtk_clipboard_set_text (clipboard, priv->text + start, end - start);
6036       else
6037         {
6038           GtkLabelLink *link;
6039
6040           link = gtk_label_get_focus_link (label);
6041           if (link)
6042             gtk_clipboard_set_text (clipboard, link->uri, -1);
6043         }
6044     }
6045 }
6046
6047 static void
6048 gtk_label_select_all (GtkLabel *label)
6049 {
6050   GtkLabelPrivate *priv = label->priv;
6051
6052   gtk_label_select_region_index (label, 0, strlen (priv->text));
6053 }
6054
6055 /* Quick hack of a popup menu
6056  */
6057 static void
6058 activate_cb (GtkWidget *menuitem,
6059              GtkLabel  *label)
6060 {
6061   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
6062   g_signal_emit_by_name (label, signal);
6063 }
6064
6065 static void
6066 append_action_signal (GtkLabel     *label,
6067                       GtkWidget    *menu,
6068                       const gchar  *stock_id,
6069                       const gchar  *signal,
6070                       gboolean      sensitive)
6071 {
6072   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
6073
6074   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
6075   g_signal_connect (menuitem, "activate",
6076                     G_CALLBACK (activate_cb), label);
6077
6078   gtk_widget_set_sensitive (menuitem, sensitive);
6079   
6080   gtk_widget_show (menuitem);
6081   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6082 }
6083
6084 static void
6085 popup_menu_detach (GtkWidget *attach_widget,
6086                    GtkMenu   *menu)
6087 {
6088   GtkLabel *label = GTK_LABEL (attach_widget);
6089   GtkLabelPrivate *priv = label->priv;
6090
6091   if (priv->select_info)
6092     priv->select_info->popup_menu = NULL;
6093 }
6094
6095 static void
6096 popup_position_func (GtkMenu   *menu,
6097                      gint      *x,
6098                      gint      *y,
6099                      gboolean  *push_in,
6100                      gpointer   user_data)
6101 {
6102   GtkLabel *label;
6103   GtkWidget *widget;
6104   GtkAllocation allocation;
6105   GtkRequisition req;
6106   GdkScreen *screen;
6107
6108   label = GTK_LABEL (user_data);
6109   widget = GTK_WIDGET (label);
6110
6111   g_return_if_fail (gtk_widget_get_realized (widget));
6112
6113   screen = gtk_widget_get_screen (widget);
6114   gdk_window_get_origin (gtk_widget_get_window (widget), x, y);
6115
6116   gtk_widget_get_allocation (widget, &allocation);
6117
6118   *x += allocation.x;
6119   *y += allocation.y;
6120
6121   gtk_widget_get_preferred_size (GTK_WIDGET (menu),
6122                                  &req, NULL);
6123
6124   gtk_widget_get_allocation (widget, &allocation);
6125
6126   *x += allocation.width / 2;
6127   *y += allocation.height;
6128
6129   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
6130   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
6131 }
6132
6133 static void
6134 open_link_activate_cb (GtkMenuItem *menu_item,
6135                        GtkLabel    *label)
6136 {
6137   GtkLabelLink *link;
6138
6139   link = gtk_label_get_current_link (label);
6140
6141   if (link)
6142     emit_activate_link (label, link);
6143 }
6144
6145 static void
6146 copy_link_activate_cb (GtkMenuItem *menu_item,
6147                        GtkLabel    *label)
6148 {
6149   GtkClipboard *clipboard;
6150   const gchar *uri;
6151
6152   uri = gtk_label_get_current_uri (label);
6153   if (uri)
6154     {
6155       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label), GDK_SELECTION_CLIPBOARD);
6156       gtk_clipboard_set_text (clipboard, uri, -1);
6157     }
6158 }
6159
6160 static gboolean
6161 gtk_label_popup_menu (GtkWidget *widget)
6162 {
6163   gtk_label_do_popup (GTK_LABEL (widget), NULL);
6164
6165   return TRUE;
6166 }
6167
6168 static void
6169 gtk_label_do_popup (GtkLabel       *label,
6170                     GdkEventButton *event)
6171 {
6172   GtkLabelPrivate *priv = label->priv;
6173   GtkWidget *menuitem;
6174   GtkWidget *menu;
6175   GtkWidget *image;
6176   gboolean have_selection;
6177   GtkLabelLink *link;
6178
6179   if (!priv->select_info)
6180     return;
6181
6182   if (priv->select_info->popup_menu)
6183     gtk_widget_destroy (priv->select_info->popup_menu);
6184
6185   priv->select_info->popup_menu = menu = gtk_menu_new ();
6186
6187   gtk_menu_attach_to_widget (GTK_MENU (menu), GTK_WIDGET (label), popup_menu_detach);
6188
6189   have_selection =
6190     priv->select_info->selection_anchor != priv->select_info->selection_end;
6191
6192   if (event)
6193     {
6194       if (priv->select_info->link_clicked)
6195         link = priv->select_info->active_link;
6196       else
6197         link = NULL;
6198     }
6199   else
6200     link = gtk_label_get_focus_link (label);
6201
6202   if (!have_selection && link)
6203     {
6204       /* Open Link */
6205       menuitem = gtk_image_menu_item_new_with_mnemonic (_("_Open Link"));
6206       gtk_widget_show (menuitem);
6207       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6208
6209       g_signal_connect (G_OBJECT (menuitem), "activate",
6210                         G_CALLBACK (open_link_activate_cb), label);
6211
6212       image = gtk_image_new_from_stock (GTK_STOCK_JUMP_TO, GTK_ICON_SIZE_MENU);
6213       gtk_widget_show (image);
6214       gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (menuitem), image);
6215
6216       /* Copy Link Address */
6217       menuitem = gtk_image_menu_item_new_with_mnemonic (_("Copy _Link Address"));
6218       gtk_widget_show (menuitem);
6219       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6220
6221       g_signal_connect (G_OBJECT (menuitem), "activate",
6222                         G_CALLBACK (copy_link_activate_cb), label);
6223
6224       image = gtk_image_new_from_stock (GTK_STOCK_COPY, GTK_ICON_SIZE_MENU);
6225       gtk_widget_show (image);
6226       gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (menuitem), image);
6227     }
6228   else
6229     {
6230       append_action_signal (label, menu, GTK_STOCK_CUT, "cut-clipboard", FALSE);
6231       append_action_signal (label, menu, GTK_STOCK_COPY, "copy-clipboard", have_selection);
6232       append_action_signal (label, menu, GTK_STOCK_PASTE, "paste-clipboard", FALSE);
6233   
6234       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
6235       gtk_widget_set_sensitive (menuitem, FALSE);
6236       gtk_widget_show (menuitem);
6237       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6238
6239       menuitem = gtk_separator_menu_item_new ();
6240       gtk_widget_show (menuitem);
6241       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6242
6243       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
6244       g_signal_connect_swapped (menuitem, "activate",
6245                                 G_CALLBACK (gtk_label_select_all), label);
6246       gtk_widget_show (menuitem);
6247       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
6248     }
6249
6250   g_signal_emit (label, signals[POPULATE_POPUP], 0, menu);
6251
6252   if (event)
6253     gtk_menu_popup (GTK_MENU (menu), NULL, NULL,
6254                     NULL, NULL,
6255                     event->button, event->time);
6256   else
6257     {
6258       gtk_menu_popup (GTK_MENU (menu), NULL, NULL,
6259                       popup_position_func, label,
6260                       0, gtk_get_current_event_time ());
6261       gtk_menu_shell_select_first (GTK_MENU_SHELL (menu), FALSE);
6262     }
6263 }
6264
6265 static void
6266 gtk_label_clear_links (GtkLabel *label)
6267 {
6268   GtkLabelPrivate *priv = label->priv;
6269
6270   if (!priv->select_info)
6271     return;
6272
6273   g_list_foreach (priv->select_info->links, (GFunc)link_free, NULL);
6274   g_list_free (priv->select_info->links);
6275   priv->select_info->links = NULL;
6276   priv->select_info->active_link = NULL;
6277 }
6278
6279 static void
6280 gtk_label_rescan_links (GtkLabel *label)
6281 {
6282   GtkLabelPrivate *priv = label->priv;
6283   PangoLayout *layout = priv->layout;
6284   PangoAttrList *attlist;
6285   PangoAttrIterator *iter;
6286   GList *links;
6287
6288   if (!priv->select_info || !priv->select_info->links)
6289     return;
6290
6291   attlist = pango_layout_get_attributes (layout);
6292
6293   if (attlist == NULL)
6294     return;
6295
6296   iter = pango_attr_list_get_iterator (attlist);
6297
6298   links = priv->select_info->links;
6299
6300   do
6301     {
6302       PangoAttribute *underline;
6303       PangoAttribute *color;
6304
6305       underline = pango_attr_iterator_get (iter, PANGO_ATTR_UNDERLINE);
6306       color = pango_attr_iterator_get (iter, PANGO_ATTR_FOREGROUND);
6307
6308       if (underline != NULL && color != NULL)
6309         {
6310           gint start, end;
6311           PangoRectangle start_pos;
6312           PangoRectangle end_pos;
6313           GtkLabelLink *link;
6314
6315           pango_attr_iterator_range (iter, &start, &end);
6316           pango_layout_index_to_pos (layout, start, &start_pos);
6317           pango_layout_index_to_pos (layout, end, &end_pos);
6318
6319           if (links == NULL)
6320             {
6321               g_warning ("Ran out of links");
6322               break;
6323             }
6324           link = links->data;
6325           links = links->next;
6326           link->start = start;
6327           link->end = end;
6328         }
6329       } while (pango_attr_iterator_next (iter));
6330
6331     pango_attr_iterator_destroy (iter);
6332 }
6333
6334 static gboolean
6335 gtk_label_activate_link (GtkLabel    *label,
6336                          const gchar *uri)
6337 {
6338   GtkWidget *widget = GTK_WIDGET (label);
6339   GError *error = NULL;
6340
6341   if (!gtk_show_uri (gtk_widget_get_screen (widget),
6342                      uri, gtk_get_current_event_time (), &error))
6343     {
6344       g_warning ("Unable to show '%s': %s", uri, error->message);
6345       g_error_free (error);
6346     }
6347
6348   return TRUE;
6349 }
6350
6351 static void
6352 emit_activate_link (GtkLabel     *label,
6353                     GtkLabelLink *link)
6354 {
6355   GtkLabelPrivate *priv = label->priv;
6356   gboolean handled;
6357
6358   g_signal_emit (label, signals[ACTIVATE_LINK], 0, link->uri, &handled);
6359   if (handled && priv->track_links && !link->visited)
6360     {
6361       link->visited = TRUE;
6362       /* FIXME: shouldn't have to redo everything here */
6363       gtk_label_recalculate (label);
6364     }
6365 }
6366
6367 static void
6368 gtk_label_activate_current_link (GtkLabel *label)
6369 {
6370   GtkLabelLink *link;
6371   GtkWidget *widget = GTK_WIDGET (label);
6372
6373   link = gtk_label_get_focus_link (label);
6374
6375   if (link)
6376     {
6377       emit_activate_link (label, link);
6378     }
6379   else
6380     {
6381       GtkWidget *toplevel;
6382       GtkWindow *window;
6383       GtkWidget *default_widget, *focus_widget;
6384
6385       toplevel = gtk_widget_get_toplevel (widget);
6386       if (GTK_IS_WINDOW (toplevel))
6387         {
6388           window = GTK_WINDOW (toplevel);
6389
6390           if (window)
6391             {
6392               default_widget = gtk_window_get_default_widget (window);
6393               focus_widget = gtk_window_get_focus (window);
6394
6395               if (default_widget != widget &&
6396                   !(widget == focus_widget && (!default_widget || !gtk_widget_is_sensitive (default_widget))))
6397                 gtk_window_activate_default (window);
6398             }
6399         }
6400     }
6401 }
6402
6403 static GtkLabelLink *
6404 gtk_label_get_current_link (GtkLabel *label)
6405 {
6406   GtkLabelPrivate *priv = label->priv;
6407   GtkLabelLink *link;
6408
6409   if (!priv->select_info)
6410     return NULL;
6411
6412   if (priv->select_info->link_clicked)
6413     link = priv->select_info->active_link;
6414   else
6415     link = gtk_label_get_focus_link (label);
6416
6417   return link;
6418 }
6419
6420 /**
6421  * gtk_label_get_current_uri:
6422  * @label: a #GtkLabel
6423  *
6424  * Returns the URI for the currently active link in the label.
6425  * The active link is the one under the mouse pointer or, in a
6426  * selectable label, the link in which the text cursor is currently
6427  * positioned.
6428  *
6429  * This function is intended for use in a #GtkLabel::activate-link handler
6430  * or for use in a #GtkWidget::query-tooltip handler.
6431  *
6432  * Returns: the currently active URI. The string is owned by GTK+ and must
6433  *   not be freed or modified.
6434  *
6435  * Since: 2.18
6436  */
6437 const gchar *
6438 gtk_label_get_current_uri (GtkLabel *label)
6439 {
6440   GtkLabelLink *link;
6441
6442   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
6443
6444   link = gtk_label_get_current_link (label);
6445
6446   if (link)
6447     return link->uri;
6448
6449   return NULL;
6450 }
6451
6452 /**
6453  * gtk_label_set_track_visited_links:
6454  * @label: a #GtkLabel
6455  * @track_links: %TRUE to track visited links
6456  *
6457  * Sets whether the label should keep track of clicked
6458  * links (and use a different color for them).
6459  *
6460  * Since: 2.18
6461  */
6462 void
6463 gtk_label_set_track_visited_links (GtkLabel *label,
6464                                    gboolean  track_links)
6465 {
6466   GtkLabelPrivate *priv;
6467
6468   g_return_if_fail (GTK_IS_LABEL (label));
6469
6470   priv = label->priv;
6471
6472   track_links = track_links != FALSE;
6473
6474   if (priv->track_links != track_links)
6475     {
6476       priv->track_links = track_links;
6477
6478       /* FIXME: shouldn't have to redo everything here */
6479       gtk_label_recalculate (label);
6480
6481       g_object_notify (G_OBJECT (label), "track-visited-links");
6482     }
6483 }
6484
6485 /**
6486  * gtk_label_get_track_visited_links:
6487  * @label: a #GtkLabel
6488  *
6489  * Returns whether the label is currently keeping track
6490  * of clicked links.
6491  *
6492  * Returns: %TRUE if clicked links are remembered
6493  *
6494  * Since: 2.18
6495  */
6496 gboolean
6497 gtk_label_get_track_visited_links (GtkLabel *label)
6498 {
6499   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
6500
6501   return label->priv->track_links;
6502 }
6503
6504 static gboolean
6505 gtk_label_query_tooltip (GtkWidget  *widget,
6506                          gint        x,
6507                          gint        y,
6508                          gboolean    keyboard_tip,
6509                          GtkTooltip *tooltip)
6510 {
6511   GtkLabel *label = GTK_LABEL (widget);
6512   GtkLabelPrivate *priv = label->priv;
6513   GtkLabelSelectionInfo *info = priv->select_info;
6514   gint index = -1;
6515   GList *l;
6516
6517   if (info && info->links)
6518     {
6519       if (keyboard_tip)
6520         {
6521           if (info->selection_anchor == info->selection_end)
6522             index = info->selection_anchor;
6523         }
6524       else
6525         {
6526           if (!get_layout_index (label, x, y, &index))
6527             index = -1;
6528         }
6529
6530       if (index != -1)
6531         {
6532           for (l = info->links; l != NULL; l = l->next)
6533             {
6534               GtkLabelLink *link = l->data;
6535               if (index >= link->start && index <= link->end)
6536                 {
6537                   if (link->title)
6538                     {
6539                       gtk_tooltip_set_markup (tooltip, link->title);
6540                       return TRUE;
6541                     }
6542                   break;
6543                 }
6544             }
6545         }
6546     }
6547
6548   return GTK_WIDGET_CLASS (gtk_label_parent_class)->query_tooltip (widget,
6549                                                                    x, y,
6550                                                                    keyboard_tip,
6551                                                                    tooltip);
6552 }
6553
6554 gint
6555 _gtk_label_get_cursor_position (GtkLabel *label)
6556 {
6557   GtkLabelPrivate *priv = label->priv;
6558
6559   if (priv->select_info && priv->select_info->selectable)
6560     return g_utf8_pointer_to_offset (priv->text,
6561                                      priv->text + priv->select_info->selection_end);
6562
6563   return 0;
6564 }
6565
6566 gint
6567 _gtk_label_get_selection_bound (GtkLabel *label)
6568 {
6569   GtkLabelPrivate *priv = label->priv;
6570
6571   if (priv->select_info && priv->select_info->selectable)
6572     return g_utf8_pointer_to_offset (priv->text,
6573                                      priv->text + priv->select_info->selection_anchor);
6574
6575   return 0;
6576 }