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