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