]> Pileus Git - ~andy/gtk/blob - gtk/gtklabel.c
Don't use GTK_WIDGET_STATE in internal code anymore
[~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_has_window (GTK_WIDGET (label), FALSE);
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   GtkWidget *widget;
3261
3262   if (!label->select_info)
3263     return;
3264
3265   widget = GTK_WIDGET (label);
3266
3267   if (gtk_widget_get_realized (widget))
3268     {
3269       GdkDisplay *display;
3270       GdkCursor *cursor;
3271
3272       if (gtk_widget_is_sensitive (widget))
3273         {
3274           display = gtk_widget_get_display (widget);
3275
3276           if (label->select_info->active_link)
3277             cursor = gdk_cursor_new_for_display (display, GDK_HAND2);
3278           else if (label->select_info->selectable)
3279             cursor = gdk_cursor_new_for_display (display, GDK_XTERM);
3280           else
3281             cursor = NULL;
3282         }
3283       else
3284         cursor = NULL;
3285
3286       gdk_window_set_cursor (label->select_info->window, cursor);
3287
3288       if (cursor)
3289         gdk_cursor_unref (cursor);
3290     }
3291 }
3292
3293 static void
3294 gtk_label_state_changed (GtkWidget   *widget,
3295                          GtkStateType prev_state)
3296 {
3297   GtkLabel *label = GTK_LABEL (widget);
3298
3299   if (label->select_info)
3300     {
3301       gtk_label_select_region (label, 0, 0);
3302       gtk_label_update_cursor (label);
3303     }
3304
3305   if (GTK_WIDGET_CLASS (gtk_label_parent_class)->state_changed)
3306     GTK_WIDGET_CLASS (gtk_label_parent_class)->state_changed (widget, prev_state);
3307 }
3308
3309 static void
3310 gtk_label_style_set (GtkWidget *widget,
3311                      GtkStyle  *previous_style)
3312 {
3313   GtkLabel *label = GTK_LABEL (widget);
3314
3315   /* We have to clear the layout, fonts etc. may have changed */
3316   gtk_label_clear_layout (label);
3317   gtk_label_invalidate_wrap_width (label);
3318 }
3319
3320 static void 
3321 gtk_label_direction_changed (GtkWidget        *widget,
3322                              GtkTextDirection previous_dir)
3323 {
3324   GtkLabel *label = GTK_LABEL (widget);
3325
3326   if (label->layout)
3327     pango_layout_context_changed (label->layout);
3328
3329   GTK_WIDGET_CLASS (gtk_label_parent_class)->direction_changed (widget, previous_dir);
3330 }
3331
3332 static void
3333 get_layout_location (GtkLabel  *label,
3334                      gint      *xp,
3335                      gint      *yp)
3336 {
3337   GtkMisc *misc;
3338   GtkWidget *widget; 
3339   GtkLabelPrivate *priv;
3340   gfloat xalign;
3341   gint req_width, x, y;
3342   PangoRectangle logical;
3343   
3344   misc = GTK_MISC (label);
3345   widget = GTK_WIDGET (label);
3346   priv = GTK_LABEL_GET_PRIVATE (label);
3347
3348   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
3349     xalign = misc->xalign;
3350   else
3351     xalign = 1.0 - misc->xalign;
3352
3353   pango_layout_get_pixel_extents (label->layout, NULL, &logical);
3354
3355   if (label->ellipsize || priv->width_chars > 0)
3356     {
3357       int width;
3358
3359       width = pango_layout_get_width (label->layout);
3360
3361       req_width = logical.width;
3362       if (width != -1)
3363         req_width = MIN(PANGO_PIXELS (width), req_width);
3364       req_width += 2 * misc->xpad;
3365     }
3366   else
3367     req_width = widget->requisition.width;
3368
3369   x = floor (widget->allocation.x + (gint)misc->xpad +
3370               xalign * (widget->allocation.width - req_width));
3371
3372   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
3373     x = MAX (x, widget->allocation.x + misc->xpad);
3374   else
3375     x = MIN (x, widget->allocation.x + widget->allocation.width - misc->xpad);
3376   x -= logical.x;
3377
3378   /* bgo#315462 - For single-line labels, *do* align the requisition with
3379    * respect to the allocation, even if we are under-allocated.  For multi-line
3380    * labels, always show the top of the text when they are under-allocated.  The
3381    * rationale is this:
3382    *
3383    * - Single-line labels appear in GtkButtons, and it is very easy to get them
3384    *   to be smaller than their requisition.  The button may clip the label, but
3385    *   the label will still be able to show most of itself and the focus
3386    *   rectangle.  Also, it is fairly easy to read a single line of clipped text.
3387    *
3388    * - Multi-line labels should not be clipped to showing "something in the
3389    *   middle".  You want to read the first line, at least, to get some context.
3390    */
3391   if (pango_layout_get_line_count (label->layout) == 1)
3392     y = floor (widget->allocation.y + (gint)misc->ypad 
3393                + (widget->allocation.height - widget->requisition.height) * misc->yalign);
3394   else
3395     y = floor (widget->allocation.y + (gint)misc->ypad 
3396                + MAX (((widget->allocation.height - widget->requisition.height) * misc->yalign),
3397                       0));
3398
3399   if (xp)
3400     *xp = x;
3401
3402   if (yp)
3403     *yp = y;
3404 }
3405
3406 static void
3407 draw_insertion_cursor (GtkLabel      *label,
3408                        GdkRectangle  *cursor_location,
3409                        gboolean       is_primary,
3410                        PangoDirection direction,
3411                        gboolean       draw_arrow)
3412 {
3413   GtkWidget *widget = GTK_WIDGET (label);
3414   GtkTextDirection text_dir;
3415
3416   if (direction == PANGO_DIRECTION_LTR)
3417     text_dir = GTK_TEXT_DIR_LTR;
3418   else
3419     text_dir = GTK_TEXT_DIR_RTL;
3420
3421   gtk_draw_insertion_cursor (widget, widget->window, &(widget->allocation),
3422                              cursor_location,
3423                              is_primary, text_dir, draw_arrow);
3424 }
3425
3426 static PangoDirection
3427 get_cursor_direction (GtkLabel *label)
3428 {
3429   GSList *l;
3430
3431   g_assert (label->select_info);
3432
3433   gtk_label_ensure_layout (label);
3434
3435   for (l = pango_layout_get_lines_readonly (label->layout); l; l = l->next)
3436     {
3437       PangoLayoutLine *line = l->data;
3438
3439       /* If label->select_info->selection_end is at the very end of
3440        * the line, we don't know if the cursor is on this line or
3441        * the next without looking ahead at the next line. (End
3442        * of paragraph is different from line break.) But it's
3443        * definitely in this paragraph, which is good enough
3444        * to figure out the resolved direction.
3445        */
3446        if (line->start_index + line->length >= label->select_info->selection_end)
3447         return line->resolved_dir;
3448     }
3449
3450   return PANGO_DIRECTION_LTR;
3451 }
3452
3453 static void
3454 gtk_label_draw_cursor (GtkLabel  *label, gint xoffset, gint yoffset)
3455 {
3456   GtkWidget *widget;
3457
3458   if (label->select_info == NULL)
3459     return;
3460
3461   widget = GTK_WIDGET (label);
3462   
3463   if (gtk_widget_is_drawable (widget))
3464     {
3465       PangoDirection keymap_direction;
3466       PangoDirection cursor_direction;
3467       PangoRectangle strong_pos, weak_pos;
3468       gboolean split_cursor;
3469       PangoRectangle *cursor1 = NULL;
3470       PangoRectangle *cursor2 = NULL;
3471       GdkRectangle cursor_location;
3472       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
3473       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
3474
3475       keymap_direction = gdk_keymap_get_direction (gdk_keymap_get_for_display (gtk_widget_get_display (widget)));
3476       cursor_direction = get_cursor_direction (label);
3477
3478       gtk_label_ensure_layout (label);
3479       
3480       pango_layout_get_cursor_pos (label->layout, label->select_info->selection_end,
3481                                    &strong_pos, &weak_pos);
3482
3483       g_object_get (gtk_widget_get_settings (widget),
3484                     "gtk-split-cursor", &split_cursor,
3485                     NULL);
3486
3487       dir1 = cursor_direction;
3488       
3489       if (split_cursor)
3490         {
3491           cursor1 = &strong_pos;
3492
3493           if (strong_pos.x != weak_pos.x ||
3494               strong_pos.y != weak_pos.y)
3495             {
3496               dir2 = (cursor_direction == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
3497               cursor2 = &weak_pos;
3498             }
3499         }
3500       else
3501         {
3502           if (keymap_direction == cursor_direction)
3503             cursor1 = &strong_pos;
3504           else
3505             cursor1 = &weak_pos;
3506         }
3507       
3508       cursor_location.x = xoffset + PANGO_PIXELS (cursor1->x);
3509       cursor_location.y = yoffset + PANGO_PIXELS (cursor1->y);
3510       cursor_location.width = 0;
3511       cursor_location.height = PANGO_PIXELS (cursor1->height);
3512
3513       draw_insertion_cursor (label,
3514                              &cursor_location, TRUE, dir1,
3515                              dir2 != PANGO_DIRECTION_NEUTRAL);
3516       
3517       if (dir2 != PANGO_DIRECTION_NEUTRAL)
3518         {
3519           cursor_location.x = xoffset + PANGO_PIXELS (cursor2->x);
3520           cursor_location.y = yoffset + PANGO_PIXELS (cursor2->y);
3521           cursor_location.width = 0;
3522           cursor_location.height = PANGO_PIXELS (cursor2->height);
3523
3524           draw_insertion_cursor (label,
3525                                  &cursor_location, FALSE, dir2,
3526                                  TRUE);
3527         }
3528     }
3529 }
3530
3531 static GtkLabelLink *
3532 gtk_label_get_focus_link (GtkLabel *label)
3533 {
3534   GtkLabelSelectionInfo *info = label->select_info;
3535   GList *l;
3536
3537   if (!info)
3538     return NULL;
3539
3540   if (info->selection_anchor != info->selection_end)
3541     return NULL;
3542
3543   for (l = info->links; l; l = l->next)
3544     {
3545       GtkLabelLink *link = l->data;
3546       if (link->start <= info->selection_anchor &&
3547           info->selection_anchor <= link->end)
3548         return link;
3549     }
3550
3551   return NULL;
3552 }
3553
3554 static gint
3555 gtk_label_expose (GtkWidget      *widget,
3556                   GdkEventExpose *event)
3557 {
3558   GtkLabel *label = GTK_LABEL (widget);
3559   GtkLabelSelectionInfo *info = label->select_info;
3560   gint x, y;
3561
3562   gtk_label_ensure_layout (label);
3563   
3564   if (gtk_widget_get_visible (widget) && gtk_widget_get_mapped (widget) &&
3565       label->text && (*label->text != '\0'))
3566     {
3567       get_layout_location (label, &x, &y);
3568
3569       gtk_paint_layout (widget->style,
3570                         widget->window,
3571                         gtk_widget_get_state (widget),
3572                         FALSE,
3573                         &event->area,
3574                         widget,
3575                         "label",
3576                         x, y,
3577                         label->layout);
3578
3579       if (info &&
3580           (info->selection_anchor != info->selection_end))
3581         {
3582           gint range[2];
3583           GdkRegion *clip;
3584           GtkStateType state;
3585
3586           range[0] = info->selection_anchor;
3587           range[1] = info->selection_end;
3588
3589           if (range[0] > range[1])
3590             {
3591               gint tmp = range[0];
3592               range[0] = range[1];
3593               range[1] = tmp;
3594             }
3595
3596           clip = gdk_pango_layout_get_clip_region (label->layout,
3597                                                    x, y,
3598                                                    range,
3599                                                    1);
3600           gdk_region_intersect (clip, event->region);
3601
3602          /* FIXME should use gtk_paint, but it can't use a clip
3603            * region
3604            */
3605
3606           gdk_gc_set_clip_region (widget->style->black_gc, clip);
3607
3608
3609           state = GTK_STATE_SELECTED;
3610           if (!gtk_widget_has_focus (widget))
3611             state = GTK_STATE_ACTIVE;
3612
3613           gdk_draw_layout_with_colors (widget->window,
3614                                        widget->style->black_gc,
3615                                        x, y,
3616                                        label->layout,
3617                                        &widget->style->text[state],
3618                                        &widget->style->base[state]);
3619
3620           gdk_gc_set_clip_region (widget->style->black_gc, NULL);
3621           gdk_region_destroy (clip);
3622         }
3623       else if (info)
3624         {
3625           GtkLabelLink *focus_link;
3626           GtkLabelLink *active_link;
3627           gint range[2];
3628           GdkRegion *clip;
3629           GdkRectangle rect;
3630           GdkColor *text_color;
3631           GdkColor *base_color;
3632           GdkColor *link_color;
3633           GdkColor *visited_link_color;
3634
3635           if (info->selectable && gtk_widget_has_focus (widget))
3636             gtk_label_draw_cursor (label, x, y);
3637
3638           focus_link = gtk_label_get_focus_link (label);
3639           active_link = info->active_link;
3640
3641           if (active_link)
3642             {
3643               range[0] = active_link->start;
3644               range[1] = active_link->end;
3645
3646               clip = gdk_pango_layout_get_clip_region (label->layout,
3647                                                        x, y,
3648                                                        range,
3649                                                        1);
3650               gdk_gc_set_clip_region (widget->style->black_gc, clip);
3651
3652               gtk_label_get_link_colors (widget, &link_color, &visited_link_color);
3653               if (active_link->visited)
3654                 text_color = visited_link_color;
3655               else
3656                 text_color = link_color;
3657               if (info->link_clicked)
3658                 base_color = &widget->style->base[GTK_STATE_ACTIVE];
3659               else
3660                 base_color = &widget->style->base[GTK_STATE_PRELIGHT];
3661               gdk_draw_layout_with_colors (widget->window,
3662                                            widget->style->black_gc,
3663                                            x, y,
3664                                            label->layout,
3665                                            text_color,
3666                                            base_color);
3667               gdk_color_free (link_color);
3668               gdk_color_free (visited_link_color);
3669
3670               gdk_gc_set_clip_region (widget->style->black_gc, NULL);
3671               gdk_region_destroy (clip);
3672             }
3673
3674           if (focus_link && gtk_widget_has_focus (widget))
3675             {
3676               range[0] = focus_link->start;
3677               range[1] = focus_link->end;
3678
3679               clip = gdk_pango_layout_get_clip_region (label->layout,
3680                                                        x, y,
3681                                                        range,
3682                                                        1);
3683               gdk_region_get_clipbox (clip, &rect);
3684
3685               gtk_paint_focus (widget->style, widget->window, gtk_widget_get_state (widget),
3686                                &event->area, widget, "label",
3687                                rect.x, rect.y, rect.width, rect.height);
3688
3689               gdk_region_destroy (clip);
3690             }
3691         }
3692     }
3693
3694   return FALSE;
3695 }
3696
3697 static gboolean
3698 separate_uline_pattern (const gchar  *str,
3699                         guint        *accel_key,
3700                         gchar       **new_str,
3701                         gchar       **pattern)
3702 {
3703   gboolean underscore;
3704   const gchar *src;
3705   gchar *dest;
3706   gchar *pattern_dest;
3707
3708   *accel_key = GDK_VoidSymbol;
3709   *new_str = g_new (gchar, strlen (str) + 1);
3710   *pattern = g_new (gchar, g_utf8_strlen (str, -1) + 1);
3711
3712   underscore = FALSE;
3713
3714   src = str;
3715   dest = *new_str;
3716   pattern_dest = *pattern;
3717
3718   while (*src)
3719     {
3720       gunichar c;
3721       const gchar *next_src;
3722
3723       c = g_utf8_get_char (src);
3724       if (c == (gunichar)-1)
3725         {
3726           g_warning ("Invalid input string");
3727           g_free (*new_str);
3728           g_free (*pattern);
3729
3730           return FALSE;
3731         }
3732       next_src = g_utf8_next_char (src);
3733
3734       if (underscore)
3735         {
3736           if (c == '_')
3737             *pattern_dest++ = ' ';
3738           else
3739             {
3740               *pattern_dest++ = '_';
3741               if (*accel_key == GDK_VoidSymbol)
3742                 *accel_key = gdk_keyval_to_lower (gdk_unicode_to_keyval (c));
3743             }
3744
3745           while (src < next_src)
3746             *dest++ = *src++;
3747
3748           underscore = FALSE;
3749         }
3750       else
3751         {
3752           if (c == '_')
3753             {
3754               underscore = TRUE;
3755               src = next_src;
3756             }
3757           else
3758             {
3759               while (src < next_src)
3760                 *dest++ = *src++;
3761
3762               *pattern_dest++ = ' ';
3763             }
3764         }
3765     }
3766
3767   *dest = 0;
3768   *pattern_dest = 0;
3769
3770   return TRUE;
3771 }
3772
3773 static void
3774 gtk_label_set_uline_text_internal (GtkLabel    *label,
3775                                    const gchar *str)
3776 {
3777   guint accel_key = GDK_VoidSymbol;
3778   gchar *new_str;
3779   gchar *pattern;
3780
3781   g_return_if_fail (GTK_IS_LABEL (label));
3782   g_return_if_fail (str != NULL);
3783
3784   /* Split text into the base text and a separate pattern
3785    * of underscores.
3786    */
3787   if (!separate_uline_pattern (str, &accel_key, &new_str, &pattern))
3788     return;
3789
3790   gtk_label_set_text_internal (label, new_str);
3791   gtk_label_set_pattern_internal (label, pattern, TRUE);
3792   label->mnemonic_keyval = accel_key;
3793
3794   g_free (pattern);
3795 }
3796
3797 guint
3798 gtk_label_parse_uline (GtkLabel    *label,
3799                        const gchar *str)
3800 {
3801   guint keyval;
3802   
3803   g_return_val_if_fail (GTK_IS_LABEL (label), GDK_VoidSymbol);
3804   g_return_val_if_fail (str != NULL, GDK_VoidSymbol);
3805
3806   g_object_freeze_notify (G_OBJECT (label));
3807   
3808   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
3809   gtk_label_set_use_markup_internal (label, FALSE);
3810   gtk_label_set_use_underline_internal (label, TRUE);
3811   
3812   gtk_label_recalculate (label);
3813
3814   keyval = label->mnemonic_keyval;
3815   if (keyval != GDK_VoidSymbol)
3816     {
3817       label->mnemonic_keyval = GDK_VoidSymbol;
3818       gtk_label_setup_mnemonic (label, keyval);
3819       g_object_notify (G_OBJECT (label), "mnemonic-keyval");
3820     }
3821   
3822   g_object_thaw_notify (G_OBJECT (label));
3823
3824   return keyval;
3825 }
3826
3827 /**
3828  * gtk_label_set_text_with_mnemonic:
3829  * @label: a #GtkLabel
3830  * @str: a string
3831  * 
3832  * Sets the label's text from the string @str.
3833  * If characters in @str are preceded by an underscore, they are underlined
3834  * indicating that they represent a keyboard accelerator called a mnemonic.
3835  * The mnemonic key can be used to activate another widget, chosen 
3836  * automatically, or explicitly using gtk_label_set_mnemonic_widget().
3837  **/
3838 void
3839 gtk_label_set_text_with_mnemonic (GtkLabel    *label,
3840                                   const gchar *str)
3841 {
3842   g_return_if_fail (GTK_IS_LABEL (label));
3843   g_return_if_fail (str != NULL);
3844
3845   g_object_freeze_notify (G_OBJECT (label));
3846
3847   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
3848   gtk_label_set_use_markup_internal (label, FALSE);
3849   gtk_label_set_use_underline_internal (label, TRUE);
3850   
3851   gtk_label_recalculate (label);
3852
3853   g_object_thaw_notify (G_OBJECT (label));
3854 }
3855
3856 static void
3857 gtk_label_realize (GtkWidget *widget)
3858 {
3859   GtkLabel *label;
3860
3861   label = GTK_LABEL (widget);
3862
3863   GTK_WIDGET_CLASS (gtk_label_parent_class)->realize (widget);
3864
3865   if (label->select_info)
3866     gtk_label_create_window (label);
3867 }
3868
3869 static void
3870 gtk_label_unrealize (GtkWidget *widget)
3871 {
3872   GtkLabel *label;
3873
3874   label = GTK_LABEL (widget);
3875
3876   if (label->select_info)
3877     gtk_label_destroy_window (label);
3878
3879   GTK_WIDGET_CLASS (gtk_label_parent_class)->unrealize (widget);
3880 }
3881
3882 static void
3883 gtk_label_map (GtkWidget *widget)
3884 {
3885   GtkLabel *label;
3886
3887   label = GTK_LABEL (widget);
3888
3889   GTK_WIDGET_CLASS (gtk_label_parent_class)->map (widget);
3890
3891   if (label->select_info)
3892     gdk_window_show (label->select_info->window);
3893 }
3894
3895 static void
3896 gtk_label_unmap (GtkWidget *widget)
3897 {
3898   GtkLabel *label;
3899
3900   label = GTK_LABEL (widget);
3901
3902   if (label->select_info)
3903     gdk_window_hide (label->select_info->window);
3904
3905   GTK_WIDGET_CLASS (gtk_label_parent_class)->unmap (widget);
3906 }
3907
3908 static void
3909 window_to_layout_coords (GtkLabel *label,
3910                          gint     *x,
3911                          gint     *y)
3912 {
3913   gint lx, ly;
3914   GtkWidget *widget;
3915
3916   widget = GTK_WIDGET (label);
3917   
3918   /* get layout location in widget->window coords */
3919   get_layout_location (label, &lx, &ly);
3920   
3921   if (x)
3922     {
3923       *x += widget->allocation.x; /* go to widget->window */
3924       *x -= lx;                   /* go to layout */
3925     }
3926
3927   if (y)
3928     {
3929       *y += widget->allocation.y; /* go to widget->window */
3930       *y -= ly;                   /* go to layout */
3931     }
3932 }
3933
3934 #if 0
3935 static void
3936 layout_to_window_coords (GtkLabel *label,
3937                          gint     *x,
3938                          gint     *y)
3939 {
3940   gint lx, ly;
3941   GtkWidget *widget;
3942
3943   widget = GTK_WIDGET (label);
3944   
3945   /* get layout location in widget->window coords */
3946   get_layout_location (label, &lx, &ly);
3947   
3948   if (x)
3949     {
3950       *x += lx;                   /* go to widget->window */
3951       *x -= widget->allocation.x; /* go to selection window */
3952     }
3953
3954   if (y)
3955     {
3956       *y += ly;                   /* go to widget->window */
3957       *y -= widget->allocation.y; /* go to selection window */
3958     }
3959 }
3960 #endif
3961
3962 static gboolean
3963 get_layout_index (GtkLabel *label,
3964                   gint      x,
3965                   gint      y,
3966                   gint     *index)
3967 {
3968   gint trailing = 0;
3969   const gchar *cluster;
3970   const gchar *cluster_end;
3971   gboolean inside;
3972
3973   *index = 0;
3974
3975   gtk_label_ensure_layout (label);
3976
3977   window_to_layout_coords (label, &x, &y);
3978
3979   x *= PANGO_SCALE;
3980   y *= PANGO_SCALE;
3981
3982   inside = pango_layout_xy_to_index (label->layout,
3983                                      x, y,
3984                                      index, &trailing);
3985
3986   cluster = label->text + *index;
3987   cluster_end = cluster;
3988   while (trailing)
3989     {
3990       cluster_end = g_utf8_next_char (cluster_end);
3991       --trailing;
3992     }
3993
3994   *index += (cluster_end - cluster);
3995
3996   return inside;
3997 }
3998
3999 static void
4000 gtk_label_select_word (GtkLabel *label)
4001 {
4002   gint min, max;
4003   
4004   gint start_index = gtk_label_move_backward_word (label, label->select_info->selection_end);
4005   gint end_index = gtk_label_move_forward_word (label, label->select_info->selection_end);
4006
4007   min = MIN (label->select_info->selection_anchor,
4008              label->select_info->selection_end);
4009   max = MAX (label->select_info->selection_anchor,
4010              label->select_info->selection_end);
4011
4012   min = MIN (min, start_index);
4013   max = MAX (max, end_index);
4014
4015   gtk_label_select_region_index (label, min, max);
4016 }
4017
4018 static void
4019 gtk_label_grab_focus (GtkWidget *widget)
4020 {
4021   GtkLabel *label;
4022   gboolean select_on_focus;
4023   GtkLabelLink *link;
4024
4025   label = GTK_LABEL (widget);
4026
4027   if (label->select_info == NULL)
4028     return;
4029
4030   GTK_WIDGET_CLASS (gtk_label_parent_class)->grab_focus (widget);
4031
4032   if (label->select_info->selectable)
4033     {
4034       g_object_get (gtk_widget_get_settings (widget),
4035                     "gtk-label-select-on-focus",
4036                     &select_on_focus,
4037                     NULL);
4038
4039       if (select_on_focus && !label->in_click)
4040         gtk_label_select_region (label, 0, -1);
4041     }
4042   else
4043     {
4044       if (label->select_info->links && !label->in_click)
4045         {
4046           link = label->select_info->links->data;
4047           label->select_info->selection_anchor = link->start;
4048           label->select_info->selection_end = link->start;
4049         }
4050     }
4051 }
4052
4053 static gboolean
4054 gtk_label_focus (GtkWidget        *widget,
4055                  GtkDirectionType  direction)
4056 {
4057   GtkLabel *label = GTK_LABEL (widget);
4058   GtkLabelSelectionInfo *info = label->select_info;
4059   GtkLabelLink *focus_link;
4060   GList *l;
4061
4062   if (!gtk_widget_is_focus (widget))
4063     {
4064       gtk_widget_grab_focus (widget);
4065       if (info)
4066         {
4067           focus_link = gtk_label_get_focus_link (label);
4068           if (focus_link && direction == GTK_DIR_TAB_BACKWARD)
4069             {
4070               l = g_list_last (info->links);
4071               focus_link = l->data;
4072               info->selection_anchor = focus_link->start;
4073               info->selection_end = focus_link->start;
4074             }
4075         }
4076
4077       return TRUE;
4078     }
4079
4080   if (!info)
4081     return FALSE;
4082
4083   if (info->selectable)
4084     {
4085       gint index;
4086
4087       if (info->selection_anchor != info->selection_end)
4088         goto out;
4089
4090       index = info->selection_anchor;
4091
4092       if (direction == GTK_DIR_TAB_FORWARD)
4093         for (l = info->links; l; l = l->next)
4094           {
4095             GtkLabelLink *link = l->data;
4096
4097             if (link->start > index)
4098               {
4099                 gtk_label_select_region_index (label, link->start, link->start);
4100                 return TRUE;
4101               }
4102           }
4103       else if (direction == GTK_DIR_TAB_BACKWARD)
4104         for (l = g_list_last (info->links); l; l = l->prev)
4105           {
4106             GtkLabelLink *link = l->data;
4107
4108             if (link->end < index)
4109               {
4110                 gtk_label_select_region_index (label, link->start, link->start);
4111                 return TRUE;
4112               }
4113           }
4114
4115       goto out;
4116     }
4117   else
4118     {
4119       focus_link = gtk_label_get_focus_link (label);
4120       switch (direction)
4121         {
4122         case GTK_DIR_TAB_FORWARD:
4123           if (focus_link)
4124             {
4125               l = g_list_find (info->links, focus_link);
4126               l = l->next;
4127             }
4128           else
4129             l = info->links;
4130           break;
4131
4132         case GTK_DIR_TAB_BACKWARD:
4133           if (focus_link)
4134             {
4135               l = g_list_find (info->links, focus_link);
4136               l = l->prev;
4137             }
4138           else
4139             l = g_list_last (info->links);
4140           break;
4141
4142         default:
4143           goto out;
4144         }
4145
4146       if (l)
4147         {
4148           focus_link = l->data;
4149           info->selection_anchor = focus_link->start;
4150           info->selection_end = focus_link->start;
4151           gtk_widget_queue_draw (widget);
4152
4153           return TRUE;
4154         }
4155     }
4156
4157 out:
4158
4159   return FALSE;
4160 }
4161
4162 static gboolean
4163 gtk_label_button_press (GtkWidget      *widget,
4164                         GdkEventButton *event)
4165 {
4166   GtkLabel *label = GTK_LABEL (widget);
4167   GtkLabelSelectionInfo *info = label->select_info;
4168   gint index = 0;
4169   gint min, max;
4170
4171   if (info == NULL)
4172     return FALSE;
4173
4174   if (info->active_link)
4175     {
4176       if (event->button == 1)
4177         {
4178           info->link_clicked = 1;
4179           gtk_widget_queue_draw (widget);
4180         }
4181       else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
4182         {
4183           info->link_clicked = 1;
4184           gtk_label_do_popup (label, event);
4185           return TRUE;
4186         }
4187     }
4188
4189   if (!info->selectable)
4190     return FALSE;
4191
4192   info->in_drag = FALSE;
4193   info->select_words = FALSE;
4194
4195   if (event->button == 1)
4196     {
4197       if (!gtk_widget_has_focus (widget))
4198         {
4199           label->in_click = TRUE;
4200           gtk_widget_grab_focus (widget);
4201           label->in_click = FALSE;
4202         }
4203
4204       if (event->type == GDK_3BUTTON_PRESS)
4205         {
4206           gtk_label_select_region_index (label, 0, strlen (label->text));
4207           return TRUE;
4208         }
4209
4210       if (event->type == GDK_2BUTTON_PRESS)
4211         {
4212           info->select_words = TRUE;
4213           gtk_label_select_word (label);
4214           return TRUE;
4215         }
4216
4217       get_layout_index (label, event->x, event->y, &index);
4218
4219       min = MIN (info->selection_anchor, info->selection_end);
4220       max = MAX (info->selection_anchor, info->selection_end);
4221
4222       if ((info->selection_anchor != info->selection_end) &&
4223           (event->state & GDK_SHIFT_MASK))
4224         {
4225           /* extend (same as motion) */
4226           min = MIN (min, index);
4227           max = MAX (max, index);
4228
4229           /* ensure the anchor is opposite index */
4230           if (index == min)
4231             {
4232               gint tmp = min;
4233               min = max;
4234               max = tmp;
4235             }
4236
4237           gtk_label_select_region_index (label, min, max);
4238         }
4239       else
4240         {
4241           if (event->type == GDK_3BUTTON_PRESS)
4242             gtk_label_select_region_index (label, 0, strlen (label->text));
4243           else if (event->type == GDK_2BUTTON_PRESS)
4244             gtk_label_select_word (label);
4245           else if (min < max && min <= index && index <= max)
4246             {
4247               info->in_drag = TRUE;
4248               info->drag_start_x = event->x;
4249               info->drag_start_y = event->y;
4250             }
4251           else
4252             /* start a replacement */
4253             gtk_label_select_region_index (label, index, index);
4254         }
4255
4256       return TRUE;
4257     }
4258   else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
4259     {
4260       gtk_label_do_popup (label, event);
4261
4262       return TRUE;
4263     }
4264   return FALSE;
4265 }
4266
4267 static gboolean
4268 gtk_label_button_release (GtkWidget      *widget,
4269                           GdkEventButton *event)
4270
4271 {
4272   GtkLabel *label = GTK_LABEL (widget);
4273   GtkLabelSelectionInfo *info = label->select_info;
4274   gint index;
4275
4276   if (info == NULL)
4277     return FALSE;
4278
4279   if (info->in_drag)
4280     {
4281       info->in_drag = 0;
4282
4283       get_layout_index (label, event->x, event->y, &index);
4284       gtk_label_select_region_index (label, index, index);
4285
4286       return FALSE;
4287     }
4288
4289   if (event->button != 1)
4290     return FALSE;
4291
4292   if (info->active_link &&
4293       info->selection_anchor == info->selection_end &&
4294       info->link_clicked)
4295     {
4296       emit_activate_link (label, info->active_link);
4297       info->link_clicked = 0;
4298
4299       return TRUE;
4300     }
4301
4302   /* The goal here is to return TRUE iff we ate the
4303    * button press to start selecting.
4304    */
4305   return TRUE;
4306 }
4307
4308 static void
4309 connect_mnemonics_visible_notify (GtkLabel *label)
4310 {
4311   GtkLabelPrivate *priv = GTK_LABEL_GET_PRIVATE (label);
4312   GtkWidget *toplevel;
4313   gboolean connected;
4314
4315   toplevel = gtk_widget_get_toplevel (GTK_WIDGET (label));
4316
4317   if (!GTK_IS_WINDOW (toplevel))
4318     return;
4319
4320   /* always set up this widgets initial value */
4321   priv->mnemonics_visible =
4322     gtk_window_get_mnemonics_visible (GTK_WINDOW (toplevel));
4323
4324   connected =
4325     GPOINTER_TO_INT (g_object_get_data (G_OBJECT (toplevel),
4326                                         "gtk-label-mnemonics-visible-connected"));
4327
4328   if (!connected)
4329     {
4330       g_signal_connect (toplevel,
4331                         "notify::mnemonics-visible",
4332                         G_CALLBACK (label_mnemonics_visible_changed),
4333                         label);
4334       g_object_set_data (G_OBJECT (toplevel),
4335                          "gtk-label-mnemonics-visible-connected",
4336                          GINT_TO_POINTER (1));
4337     }
4338 }
4339
4340 static void
4341 drag_begin_cb (GtkWidget      *widget,
4342                GdkDragContext *context,
4343                gpointer        data)
4344 {
4345   GtkLabel *label;
4346   GdkPixmap *pixmap = NULL;
4347
4348   g_signal_handlers_disconnect_by_func (widget, drag_begin_cb, NULL);
4349
4350   label = GTK_LABEL (widget);
4351
4352   if ((label->select_info->selection_anchor !=
4353        label->select_info->selection_end) &&
4354       label->text)
4355     {
4356       gint start, end;
4357       gint len;
4358
4359       start = MIN (label->select_info->selection_anchor,
4360                    label->select_info->selection_end);
4361       end = MAX (label->select_info->selection_anchor,
4362                  label->select_info->selection_end);
4363       
4364       len = strlen (label->text);
4365       
4366       if (end > len)
4367         end = len;
4368       
4369       if (start > len)
4370         start = len;
4371       
4372       pixmap = _gtk_text_util_create_drag_icon (widget, 
4373                                                 label->text + start,
4374                                                 end - start);
4375     }
4376
4377   if (pixmap)
4378     gtk_drag_set_icon_pixmap (context,
4379                               gdk_drawable_get_colormap (pixmap),
4380                               pixmap,
4381                               NULL,
4382                               -2, -2);
4383   else
4384     gtk_drag_set_icon_default (context);
4385   
4386   if (pixmap)
4387     g_object_unref (pixmap);
4388 }
4389
4390 static gboolean
4391 gtk_label_motion (GtkWidget      *widget,
4392                   GdkEventMotion *event)
4393 {
4394   GtkLabel *label = GTK_LABEL (widget);
4395   GtkLabelSelectionInfo *info = label->select_info;
4396   gint index;
4397   gint x, y;
4398
4399   if (info == NULL)
4400     return FALSE;
4401
4402   if (info->links && !info->in_drag)
4403     {
4404       GList *l;
4405       GtkLabelLink *link;
4406       gboolean found = FALSE;
4407
4408       if (info->selection_anchor == info->selection_end)
4409         {
4410           gdk_window_get_pointer (event->window, &x, &y, NULL);
4411           if (get_layout_index (label, x, y, &index))
4412             {
4413               for (l = info->links; l != NULL; l = l->next)
4414                 {
4415                   link = l->data;
4416                   if (index >= link->start && index <= link->end)
4417                     {
4418                       found = TRUE;
4419                       break;
4420                     }
4421                 }
4422             }
4423         }
4424
4425       if (found)
4426         {
4427           if (info->active_link != link)
4428             {
4429               info->link_clicked = 0;
4430               info->active_link = link;
4431               gtk_label_update_cursor (label);
4432               gtk_widget_queue_draw (widget);
4433             }
4434         }
4435       else
4436         {
4437           if (info->active_link != NULL)
4438             {
4439               info->link_clicked = 0;
4440               info->active_link = NULL;
4441               gtk_label_update_cursor (label);
4442               gtk_widget_queue_draw (widget);
4443             }
4444         }
4445     }
4446
4447   if (!info->selectable)
4448     return FALSE;
4449
4450   if ((event->state & GDK_BUTTON1_MASK) == 0)
4451     return FALSE;
4452
4453   gdk_window_get_pointer (info->window, &x, &y, NULL);
4454  
4455   if (info->in_drag)
4456     {
4457       if (gtk_drag_check_threshold (widget,
4458                                     info->drag_start_x,
4459                                     info->drag_start_y,
4460                                     event->x, event->y))
4461         {
4462           GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
4463
4464           gtk_target_list_add_text_targets (target_list, 0);
4465
4466           g_signal_connect (widget, "drag-begin",
4467                             G_CALLBACK (drag_begin_cb), NULL);
4468           gtk_drag_begin (widget, target_list,
4469                           GDK_ACTION_COPY,
4470                           1, (GdkEvent *)event);
4471
4472           info->in_drag = FALSE;
4473
4474           gtk_target_list_unref (target_list);
4475         }
4476     }
4477   else
4478     {
4479       get_layout_index (label, x, y, &index);
4480
4481       if (info->select_words)
4482         {
4483           gint min, max;
4484           gint old_min, old_max;
4485           gint anchor, end;
4486
4487           min = gtk_label_move_backward_word (label, index);
4488           max = gtk_label_move_forward_word (label, index);
4489
4490           anchor = info->selection_anchor;
4491           end = info->selection_end;
4492
4493           old_min = MIN (anchor, end);
4494           old_max = MAX (anchor, end);
4495
4496           if (min < old_min)
4497             {
4498               anchor = min;
4499               end = old_max;
4500             }
4501           else if (old_max < max)
4502             {
4503               anchor = max;
4504               end = old_min;
4505             }
4506           else if (anchor == old_min)
4507             {
4508               if (anchor != min)
4509                 anchor = max;
4510             }
4511           else
4512             {
4513               if (anchor != max)
4514                 anchor = min;
4515             }
4516
4517           gtk_label_select_region_index (label, anchor, end);
4518         }
4519       else
4520         gtk_label_select_region_index (label, info->selection_anchor, index);
4521     }
4522
4523   return TRUE;
4524 }
4525
4526 static gboolean
4527 gtk_label_leave_notify (GtkWidget        *widget,
4528                         GdkEventCrossing *event)
4529 {
4530   GtkLabel *label = GTK_LABEL (widget);
4531
4532   if (label->select_info)
4533     {
4534       label->select_info->active_link = NULL;
4535       gtk_label_update_cursor (label);
4536       gtk_widget_queue_draw (widget);
4537     }
4538
4539   if (GTK_WIDGET_CLASS (gtk_label_parent_class)->leave_notify_event)
4540     return GTK_WIDGET_CLASS (gtk_label_parent_class)->leave_notify_event (widget, event);
4541
4542  return FALSE;
4543 }
4544
4545 static void
4546 gtk_label_create_window (GtkLabel *label)
4547 {
4548   GtkWidget *widget;
4549   GdkWindowAttr attributes;
4550   gint attributes_mask;
4551   
4552   g_assert (label->select_info);
4553   widget = GTK_WIDGET (label);
4554   g_assert (gtk_widget_get_realized (widget));
4555   
4556   if (label->select_info->window)
4557     return;
4558
4559   attributes.x = widget->allocation.x;
4560   attributes.y = widget->allocation.y;
4561   attributes.width = widget->allocation.width;
4562   attributes.height = widget->allocation.height;
4563   attributes.window_type = GDK_WINDOW_CHILD;
4564   attributes.wclass = GDK_INPUT_ONLY;
4565   attributes.override_redirect = TRUE;
4566   attributes.event_mask = gtk_widget_get_events (widget) |
4567     GDK_BUTTON_PRESS_MASK        |
4568     GDK_BUTTON_RELEASE_MASK      |
4569     GDK_LEAVE_NOTIFY_MASK        |
4570     GDK_BUTTON_MOTION_MASK       |
4571     GDK_POINTER_MOTION_MASK      |
4572     GDK_POINTER_MOTION_HINT_MASK;
4573   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_NOREDIR;
4574   if (gtk_widget_is_sensitive (widget))
4575     {
4576       attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget),
4577                                                       GDK_XTERM);
4578       attributes_mask |= GDK_WA_CURSOR;
4579     }
4580
4581
4582   label->select_info->window = gdk_window_new (widget->window,
4583                                                &attributes, attributes_mask);
4584   gdk_window_set_user_data (label->select_info->window, widget);
4585
4586   if (attributes_mask & GDK_WA_CURSOR)
4587     gdk_cursor_unref (attributes.cursor);
4588 }
4589
4590 static void
4591 gtk_label_destroy_window (GtkLabel *label)
4592 {
4593   g_assert (label->select_info);
4594
4595   if (label->select_info->window == NULL)
4596     return;
4597
4598   gdk_window_set_user_data (label->select_info->window, NULL);
4599   gdk_window_destroy (label->select_info->window);
4600   label->select_info->window = NULL;
4601 }
4602
4603 static void
4604 gtk_label_ensure_select_info (GtkLabel *label)
4605 {
4606   if (label->select_info == NULL)
4607     {
4608       label->select_info = g_new0 (GtkLabelSelectionInfo, 1);
4609
4610       gtk_widget_set_can_focus (GTK_WIDGET (label), TRUE);
4611
4612       if (gtk_widget_get_realized (GTK_WIDGET (label)))
4613         gtk_label_create_window (label);
4614
4615       if (gtk_widget_get_mapped (GTK_WIDGET (label)))
4616         gdk_window_show (label->select_info->window);
4617     }
4618 }
4619
4620 static void
4621 gtk_label_clear_select_info (GtkLabel *label)
4622 {
4623   if (label->select_info == NULL)
4624     return;
4625
4626   if (!label->select_info->selectable && !label->select_info->links)
4627     {
4628       gtk_label_destroy_window (label);
4629
4630       g_free (label->select_info);
4631       label->select_info = NULL;
4632
4633       gtk_widget_set_can_focus (GTK_WIDGET (label), FALSE);
4634     }
4635 }
4636
4637 /**
4638  * gtk_label_set_selectable:
4639  * @label: a #GtkLabel
4640  * @setting: %TRUE to allow selecting text in the label
4641  *
4642  * Selectable labels allow the user to select text from the label, for
4643  * copy-and-paste.
4644  **/
4645 void
4646 gtk_label_set_selectable (GtkLabel *label,
4647                           gboolean  setting)
4648 {
4649   gboolean old_setting;
4650
4651   g_return_if_fail (GTK_IS_LABEL (label));
4652
4653   setting = setting != FALSE;
4654   old_setting = label->select_info && label->select_info->selectable;
4655
4656   if (setting)
4657     {
4658       gtk_label_ensure_select_info (label);
4659       label->select_info->selectable = TRUE;
4660       gtk_label_update_cursor (label);
4661     }
4662   else
4663     {
4664       if (old_setting)
4665         {
4666           /* unselect, to give up the selection */
4667           gtk_label_select_region (label, 0, 0);
4668
4669           label->select_info->selectable = FALSE;
4670           gtk_label_clear_select_info (label);
4671           gtk_label_update_cursor (label);
4672         }
4673     }
4674   if (setting != old_setting)
4675     {
4676       g_object_freeze_notify (G_OBJECT (label));
4677       g_object_notify (G_OBJECT (label), "selectable");
4678       g_object_notify (G_OBJECT (label), "cursor-position");
4679       g_object_notify (G_OBJECT (label), "selection-bound");
4680       g_object_thaw_notify (G_OBJECT (label));
4681       gtk_widget_queue_draw (GTK_WIDGET (label));
4682     }
4683 }
4684
4685 /**
4686  * gtk_label_get_selectable:
4687  * @label: a #GtkLabel
4688  * 
4689  * Gets the value set by gtk_label_set_selectable().
4690  * 
4691  * Return value: %TRUE if the user can copy text from the label
4692  **/
4693 gboolean
4694 gtk_label_get_selectable (GtkLabel *label)
4695 {
4696   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
4697
4698   return label->select_info && label->select_info->selectable;
4699 }
4700
4701 static void
4702 free_angle (gpointer angle)
4703 {
4704   g_slice_free (gdouble, angle);
4705 }
4706
4707 /**
4708  * gtk_label_set_angle:
4709  * @label: a #GtkLabel
4710  * @angle: the angle that the baseline of the label makes with
4711  *   the horizontal, in degrees, measured counterclockwise
4712  * 
4713  * Sets the angle of rotation for the label. An angle of 90 reads from
4714  * from bottom to top, an angle of 270, from top to bottom. The angle
4715  * setting for the label is ignored if the label is selectable,
4716  * wrapped, or ellipsized.
4717  *
4718  * Since: 2.6
4719  **/
4720 void
4721 gtk_label_set_angle (GtkLabel *label,
4722                      gdouble   angle)
4723 {
4724   gdouble *label_angle;
4725
4726   g_return_if_fail (GTK_IS_LABEL (label));
4727
4728   label_angle = (gdouble *)g_object_get_qdata (G_OBJECT (label), quark_angle);
4729
4730   if (!label_angle)
4731     {
4732       label_angle = g_slice_new (gdouble);
4733       *label_angle = 0.0;
4734       g_object_set_qdata_full (G_OBJECT (label), quark_angle, 
4735                                label_angle, free_angle);
4736     }
4737   
4738   /* Canonicalize to [0,360]. We don't canonicalize 360 to 0, because
4739    * double property ranges are inclusive, and changing 360 to 0 would
4740    * make a property editor behave strangely.
4741    */
4742   if (angle < 0 || angle > 360.0)
4743     angle = angle - 360. * floor (angle / 360.);
4744
4745   if (*label_angle != angle)
4746     {
4747       *label_angle = angle;
4748       
4749       gtk_label_clear_layout (label);
4750       gtk_widget_queue_resize (GTK_WIDGET (label));
4751
4752       g_object_notify (G_OBJECT (label), "angle");
4753     }
4754 }
4755
4756 /**
4757  * gtk_label_get_angle:
4758  * @label: a #GtkLabel
4759  * 
4760  * Gets the angle of rotation for the label. See
4761  * gtk_label_set_angle().
4762  * 
4763  * Return value: the angle of rotation for the label
4764  *
4765  * Since: 2.6
4766  **/
4767 gdouble
4768 gtk_label_get_angle  (GtkLabel *label)
4769 {
4770   gdouble *angle;
4771
4772   g_return_val_if_fail (GTK_IS_LABEL (label), 0.0);
4773   
4774   angle = (gdouble *)g_object_get_qdata (G_OBJECT (label), quark_angle);
4775
4776   if (angle)
4777     return *angle;
4778   else
4779     return 0.0;
4780 }
4781
4782 static void
4783 gtk_label_set_selection_text (GtkLabel         *label,
4784                               GtkSelectionData *selection_data)
4785 {
4786   if ((label->select_info->selection_anchor !=
4787        label->select_info->selection_end) &&
4788       label->text)
4789     {
4790       gint start, end;
4791       gint len;
4792       
4793       start = MIN (label->select_info->selection_anchor,
4794                    label->select_info->selection_end);
4795       end = MAX (label->select_info->selection_anchor,
4796                  label->select_info->selection_end);
4797       
4798       len = strlen (label->text);
4799       
4800       if (end > len)
4801         end = len;
4802       
4803       if (start > len)
4804         start = len;
4805       
4806       gtk_selection_data_set_text (selection_data,
4807                                    label->text + start,
4808                                    end - start);
4809     }
4810 }
4811
4812 static void
4813 gtk_label_drag_data_get (GtkWidget        *widget,
4814                          GdkDragContext   *context,
4815                          GtkSelectionData *selection_data,
4816                          guint             info,
4817                          guint             time)
4818 {
4819   gtk_label_set_selection_text (GTK_LABEL (widget), selection_data);
4820 }
4821
4822 static void
4823 get_text_callback (GtkClipboard     *clipboard,
4824                    GtkSelectionData *selection_data,
4825                    guint             info,
4826                    gpointer          user_data_or_owner)
4827 {
4828   gtk_label_set_selection_text (GTK_LABEL (user_data_or_owner), selection_data);
4829 }
4830
4831 static void
4832 clear_text_callback (GtkClipboard     *clipboard,
4833                      gpointer          user_data_or_owner)
4834 {
4835   GtkLabel *label;
4836
4837   label = GTK_LABEL (user_data_or_owner);
4838
4839   if (label->select_info)
4840     {
4841       label->select_info->selection_anchor = label->select_info->selection_end;
4842       
4843       gtk_widget_queue_draw (GTK_WIDGET (label));
4844     }
4845 }
4846
4847 static void
4848 gtk_label_select_region_index (GtkLabel *label,
4849                                gint      anchor_index,
4850                                gint      end_index)
4851 {
4852   g_return_if_fail (GTK_IS_LABEL (label));
4853   
4854   if (label->select_info && label->select_info->selectable)
4855     {
4856       GtkClipboard *clipboard;
4857
4858       if (label->select_info->selection_anchor == anchor_index &&
4859           label->select_info->selection_end == end_index)
4860         return;
4861
4862       label->select_info->selection_anchor = anchor_index;
4863       label->select_info->selection_end = end_index;
4864
4865       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label),
4866                                             GDK_SELECTION_PRIMARY);
4867
4868       if (anchor_index != end_index)
4869         {
4870           GtkTargetList *list;
4871           GtkTargetEntry *targets;
4872           gint n_targets;
4873
4874           list = gtk_target_list_new (NULL, 0);
4875           gtk_target_list_add_text_targets (list, 0);
4876           targets = gtk_target_table_new_from_list (list, &n_targets);
4877
4878           gtk_clipboard_set_with_owner (clipboard,
4879                                         targets, n_targets,
4880                                         get_text_callback,
4881                                         clear_text_callback,
4882                                         G_OBJECT (label));
4883
4884           gtk_target_table_free (targets, n_targets);
4885           gtk_target_list_unref (list);
4886         }
4887       else
4888         {
4889           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (label))
4890             gtk_clipboard_clear (clipboard);
4891         }
4892
4893       gtk_widget_queue_draw (GTK_WIDGET (label));
4894
4895       g_object_freeze_notify (G_OBJECT (label));
4896       g_object_notify (G_OBJECT (label), "cursor-position");
4897       g_object_notify (G_OBJECT (label), "selection-bound");
4898       g_object_thaw_notify (G_OBJECT (label));
4899     }
4900 }
4901
4902 /**
4903  * gtk_label_select_region:
4904  * @label: a #GtkLabel
4905  * @start_offset: start offset (in characters not bytes)
4906  * @end_offset: end offset (in characters not bytes)
4907  *
4908  * Selects a range of characters in the label, if the label is selectable.
4909  * See gtk_label_set_selectable(). If the label is not selectable,
4910  * this function has no effect. If @start_offset or
4911  * @end_offset are -1, then the end of the label will be substituted.
4912  **/
4913 void
4914 gtk_label_select_region  (GtkLabel *label,
4915                           gint      start_offset,
4916                           gint      end_offset)
4917 {
4918   g_return_if_fail (GTK_IS_LABEL (label));
4919   
4920   if (label->text && label->select_info)
4921     {
4922       if (start_offset < 0)
4923         start_offset = g_utf8_strlen (label->text, -1);
4924       
4925       if (end_offset < 0)
4926         end_offset = g_utf8_strlen (label->text, -1);
4927       
4928       gtk_label_select_region_index (label,
4929                                      g_utf8_offset_to_pointer (label->text, start_offset) - label->text,
4930                                      g_utf8_offset_to_pointer (label->text, end_offset) - label->text);
4931     }
4932 }
4933
4934 /**
4935  * gtk_label_get_selection_bounds:
4936  * @label: a #GtkLabel
4937  * @start: return location for start of selection, as a character offset
4938  * @end: return location for end of selection, as a character offset
4939  * 
4940  * Gets the selected range of characters in the label, returning %TRUE
4941  * if there's a selection.
4942  * 
4943  * Return value: %TRUE if selection is non-empty
4944  **/
4945 gboolean
4946 gtk_label_get_selection_bounds (GtkLabel  *label,
4947                                 gint      *start,
4948                                 gint      *end)
4949 {
4950   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
4951
4952   if (label->select_info == NULL)
4953     {
4954       /* not a selectable label */
4955       if (start)
4956         *start = 0;
4957       if (end)
4958         *end = 0;
4959
4960       return FALSE;
4961     }
4962   else
4963     {
4964       gint start_index, end_index;
4965       gint start_offset, end_offset;
4966       gint len;
4967       
4968       start_index = MIN (label->select_info->selection_anchor,
4969                    label->select_info->selection_end);
4970       end_index = MAX (label->select_info->selection_anchor,
4971                  label->select_info->selection_end);
4972
4973       len = strlen (label->text);
4974
4975       if (end_index > len)
4976         end_index = len;
4977
4978       if (start_index > len)
4979         start_index = len;
4980       
4981       start_offset = g_utf8_strlen (label->text, start_index);
4982       end_offset = g_utf8_strlen (label->text, end_index);
4983
4984       if (start_offset > end_offset)
4985         {
4986           gint tmp = start_offset;
4987           start_offset = end_offset;
4988           end_offset = tmp;
4989         }
4990       
4991       if (start)
4992         *start = start_offset;
4993
4994       if (end)
4995         *end = end_offset;
4996
4997       return start_offset != end_offset;
4998     }
4999 }
5000
5001
5002 /**
5003  * gtk_label_get_layout:
5004  * @label: a #GtkLabel
5005  * 
5006  * Gets the #PangoLayout used to display the label.
5007  * The layout is useful to e.g. convert text positions to
5008  * pixel positions, in combination with gtk_label_get_layout_offsets().
5009  * The returned layout is owned by the label so need not be
5010  * freed by the caller.
5011  *
5012  * Return value: (transfer none): the #PangoLayout for this label
5013  **/
5014 PangoLayout*
5015 gtk_label_get_layout (GtkLabel *label)
5016 {
5017   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
5018
5019   gtk_label_ensure_layout (label);
5020
5021   return label->layout;
5022 }
5023
5024 /**
5025  * gtk_label_get_layout_offsets:
5026  * @label: a #GtkLabel
5027  * @x: (allow-none): location to store X offset of layout, or %NULL
5028  * @y: (allow-none): location to store Y offset of layout, or %NULL
5029  *
5030  * Obtains the coordinates where the label will draw the #PangoLayout
5031  * representing the text in the label; useful to convert mouse events
5032  * into coordinates inside the #PangoLayout, e.g. to take some action
5033  * if some part of the label is clicked. Of course you will need to
5034  * create a #GtkEventBox to receive the events, and pack the label
5035  * inside it, since labels are a #GTK_NO_WINDOW widget. Remember
5036  * when using the #PangoLayout functions you need to convert to
5037  * and from pixels using PANGO_PIXELS() or #PANGO_SCALE.
5038  **/
5039 void
5040 gtk_label_get_layout_offsets (GtkLabel *label,
5041                               gint     *x,
5042                               gint     *y)
5043 {
5044   g_return_if_fail (GTK_IS_LABEL (label));
5045
5046   gtk_label_ensure_layout (label);
5047
5048   get_layout_location (label, x, y);
5049 }
5050
5051 /**
5052  * gtk_label_set_use_markup:
5053  * @label: a #GtkLabel
5054  * @setting: %TRUE if the label's text should be parsed for markup.
5055  *
5056  * Sets whether the text of the label contains markup in <link
5057  * linkend="PangoMarkupFormat">Pango's text markup
5058  * language</link>. See gtk_label_set_markup().
5059  **/
5060 void
5061 gtk_label_set_use_markup (GtkLabel *label,
5062                           gboolean  setting)
5063 {
5064   g_return_if_fail (GTK_IS_LABEL (label));
5065
5066   gtk_label_set_use_markup_internal (label, setting);
5067   gtk_label_recalculate (label);
5068 }
5069
5070 /**
5071  * gtk_label_get_use_markup:
5072  * @label: a #GtkLabel
5073  *
5074  * Returns whether the label's text is interpreted as marked up with
5075  * the <link linkend="PangoMarkupFormat">Pango text markup
5076  * language</link>. See gtk_label_set_use_markup ().
5077  *
5078  * Return value: %TRUE if the label's text will be parsed for markup.
5079  **/
5080 gboolean
5081 gtk_label_get_use_markup (GtkLabel *label)
5082 {
5083   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5084   
5085   return label->use_markup;
5086 }
5087
5088 /**
5089  * gtk_label_set_use_underline:
5090  * @label: a #GtkLabel
5091  * @setting: %TRUE if underlines in the text indicate mnemonics
5092  *
5093  * If true, an underline in the text indicates the next character should be
5094  * used for the mnemonic accelerator key.
5095  */
5096 void
5097 gtk_label_set_use_underline (GtkLabel *label,
5098                              gboolean  setting)
5099 {
5100   g_return_if_fail (GTK_IS_LABEL (label));
5101
5102   gtk_label_set_use_underline_internal (label, setting);
5103   gtk_label_recalculate (label);
5104 }
5105
5106 /**
5107  * gtk_label_get_use_underline:
5108  * @label: a #GtkLabel
5109  *
5110  * Returns whether an embedded underline in the label indicates a
5111  * mnemonic. See gtk_label_set_use_underline().
5112  *
5113  * Return value: %TRUE whether an embedded underline in the label indicates
5114  *               the mnemonic accelerator keys.
5115  **/
5116 gboolean
5117 gtk_label_get_use_underline (GtkLabel *label)
5118 {
5119   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5120   
5121   return label->use_underline;
5122 }
5123
5124 /**
5125  * gtk_label_set_single_line_mode:
5126  * @label: a #GtkLabel
5127  * @single_line_mode: %TRUE if the label should be in single line mode
5128  *
5129  * Sets whether the label is in single line mode.
5130  *
5131  * Since: 2.6
5132  */
5133 void
5134 gtk_label_set_single_line_mode (GtkLabel *label,
5135                                 gboolean single_line_mode)
5136 {
5137   g_return_if_fail (GTK_IS_LABEL (label));
5138
5139   single_line_mode = single_line_mode != FALSE;
5140
5141   if (label->single_line_mode != single_line_mode)
5142     {
5143       label->single_line_mode = single_line_mode;
5144
5145       gtk_label_clear_layout (label);
5146       gtk_widget_queue_resize (GTK_WIDGET (label));
5147
5148       g_object_notify (G_OBJECT (label), "single-line-mode");
5149     }
5150 }
5151
5152 /**
5153  * gtk_label_get_single_line_mode:
5154  * @label: a #GtkLabel
5155  *
5156  * Returns whether the label is in single line mode.
5157  *
5158  * Return value: %TRUE when the label is in single line mode.
5159  *
5160  * Since: 2.6
5161  **/
5162 gboolean
5163 gtk_label_get_single_line_mode  (GtkLabel *label)
5164 {
5165   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5166
5167   return label->single_line_mode;
5168 }
5169
5170 /* Compute the X position for an offset that corresponds to the "more important
5171  * cursor position for that offset. We use this when trying to guess to which
5172  * end of the selection we should go to when the user hits the left or
5173  * right arrow key.
5174  */
5175 static void
5176 get_better_cursor (GtkLabel *label,
5177                    gint      index,
5178                    gint      *x,
5179                    gint      *y)
5180 {
5181   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
5182   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
5183   PangoDirection cursor_direction = get_cursor_direction (label);
5184   gboolean split_cursor;
5185   PangoRectangle strong_pos, weak_pos;
5186   
5187   g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
5188                 "gtk-split-cursor", &split_cursor,
5189                 NULL);
5190
5191   gtk_label_ensure_layout (label);
5192   
5193   pango_layout_get_cursor_pos (label->layout, index,
5194                                &strong_pos, &weak_pos);
5195
5196   if (split_cursor)
5197     {
5198       *x = strong_pos.x / PANGO_SCALE;
5199       *y = strong_pos.y / PANGO_SCALE;
5200     }
5201   else
5202     {
5203       if (keymap_direction == cursor_direction)
5204         {
5205           *x = strong_pos.x / PANGO_SCALE;
5206           *y = strong_pos.y / PANGO_SCALE;
5207         }
5208       else
5209         {
5210           *x = weak_pos.x / PANGO_SCALE;
5211           *y = weak_pos.y / PANGO_SCALE;
5212         }
5213     }
5214 }
5215
5216
5217 static gint
5218 gtk_label_move_logically (GtkLabel *label,
5219                           gint      start,
5220                           gint      count)
5221 {
5222   gint offset = g_utf8_pointer_to_offset (label->text,
5223                                           label->text + start);
5224
5225   if (label->text)
5226     {
5227       PangoLogAttr *log_attrs;
5228       gint n_attrs;
5229       gint length;
5230
5231       gtk_label_ensure_layout (label);
5232       
5233       length = g_utf8_strlen (label->text, -1);
5234
5235       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
5236
5237       while (count > 0 && offset < length)
5238         {
5239           do
5240             offset++;
5241           while (offset < length && !log_attrs[offset].is_cursor_position);
5242           
5243           count--;
5244         }
5245       while (count < 0 && offset > 0)
5246         {
5247           do
5248             offset--;
5249           while (offset > 0 && !log_attrs[offset].is_cursor_position);
5250           
5251           count++;
5252         }
5253       
5254       g_free (log_attrs);
5255     }
5256
5257   return g_utf8_offset_to_pointer (label->text, offset) - label->text;
5258 }
5259
5260 static gint
5261 gtk_label_move_visually (GtkLabel *label,
5262                          gint      start,
5263                          gint      count)
5264 {
5265   gint index;
5266
5267   index = start;
5268   
5269   while (count != 0)
5270     {
5271       int new_index, new_trailing;
5272       gboolean split_cursor;
5273       gboolean strong;
5274
5275       gtk_label_ensure_layout (label);
5276
5277       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
5278                     "gtk-split-cursor", &split_cursor,
5279                     NULL);
5280
5281       if (split_cursor)
5282         strong = TRUE;
5283       else
5284         {
5285           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
5286           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
5287
5288           strong = keymap_direction == get_cursor_direction (label);
5289         }
5290       
5291       if (count > 0)
5292         {
5293           pango_layout_move_cursor_visually (label->layout, strong, index, 0, 1, &new_index, &new_trailing);
5294           count--;
5295         }
5296       else
5297         {
5298           pango_layout_move_cursor_visually (label->layout, strong, index, 0, -1, &new_index, &new_trailing);
5299           count++;
5300         }
5301
5302       if (new_index < 0 || new_index == G_MAXINT)
5303         break;
5304
5305       index = new_index;
5306       
5307       while (new_trailing--)
5308         index = g_utf8_next_char (label->text + new_index) - label->text;
5309     }
5310   
5311   return index;
5312 }
5313
5314 static gint
5315 gtk_label_move_forward_word (GtkLabel *label,
5316                              gint      start)
5317 {
5318   gint new_pos = g_utf8_pointer_to_offset (label->text,
5319                                            label->text + start);
5320   gint length;
5321
5322   length = g_utf8_strlen (label->text, -1);
5323   if (new_pos < length)
5324     {
5325       PangoLogAttr *log_attrs;
5326       gint n_attrs;
5327
5328       gtk_label_ensure_layout (label);
5329       
5330       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
5331       
5332       /* Find the next word end */
5333       new_pos++;
5334       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
5335         new_pos++;
5336
5337       g_free (log_attrs);
5338     }
5339
5340   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
5341 }
5342
5343
5344 static gint
5345 gtk_label_move_backward_word (GtkLabel *label,
5346                               gint      start)
5347 {
5348   gint new_pos = g_utf8_pointer_to_offset (label->text,
5349                                            label->text + start);
5350
5351   if (new_pos > 0)
5352     {
5353       PangoLogAttr *log_attrs;
5354       gint n_attrs;
5355
5356       gtk_label_ensure_layout (label);
5357       
5358       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
5359       
5360       new_pos -= 1;
5361
5362       /* Find the previous word beginning */
5363       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
5364         new_pos--;
5365
5366       g_free (log_attrs);
5367     }
5368
5369   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
5370 }
5371
5372 static void
5373 gtk_label_move_cursor (GtkLabel       *label,
5374                        GtkMovementStep step,
5375                        gint            count,
5376                        gboolean        extend_selection)
5377 {
5378   gint old_pos;
5379   gint new_pos;
5380   
5381   if (label->select_info == NULL)
5382     return;
5383
5384   old_pos = new_pos = label->select_info->selection_end;
5385
5386   if (label->select_info->selection_end != label->select_info->selection_anchor &&
5387       !extend_selection)
5388     {
5389       /* If we have a current selection and aren't extending it, move to the
5390        * start/or end of the selection as appropriate
5391        */
5392       switch (step)
5393         {
5394         case GTK_MOVEMENT_VISUAL_POSITIONS:
5395           {
5396             gint end_x, end_y;
5397             gint anchor_x, anchor_y;
5398             gboolean end_is_left;
5399             
5400             get_better_cursor (label, label->select_info->selection_end, &end_x, &end_y);
5401             get_better_cursor (label, label->select_info->selection_anchor, &anchor_x, &anchor_y);
5402
5403             end_is_left = (end_y < anchor_y) || (end_y == anchor_y && end_x < anchor_x);
5404             
5405             if (count < 0)
5406               new_pos = end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
5407             else
5408               new_pos = !end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
5409             break;
5410           }
5411         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5412         case GTK_MOVEMENT_WORDS:
5413           if (count < 0)
5414             new_pos = MIN (label->select_info->selection_end, label->select_info->selection_anchor);
5415           else
5416             new_pos = MAX (label->select_info->selection_end, label->select_info->selection_anchor);
5417           break;
5418         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5419         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5420         case GTK_MOVEMENT_BUFFER_ENDS:
5421           /* FIXME: Can do better here */
5422           new_pos = count < 0 ? 0 : strlen (label->text);
5423           break;
5424         case GTK_MOVEMENT_DISPLAY_LINES:
5425         case GTK_MOVEMENT_PARAGRAPHS:
5426         case GTK_MOVEMENT_PAGES:
5427         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5428           break;
5429         }
5430     }
5431   else
5432     {
5433       switch (step)
5434         {
5435         case GTK_MOVEMENT_LOGICAL_POSITIONS:
5436           new_pos = gtk_label_move_logically (label, new_pos, count);
5437           break;
5438         case GTK_MOVEMENT_VISUAL_POSITIONS:
5439           new_pos = gtk_label_move_visually (label, new_pos, count);
5440           if (new_pos == old_pos)
5441             {
5442               if (!extend_selection)
5443                 {
5444                   if (!gtk_widget_keynav_failed (GTK_WIDGET (label),
5445                                                  count > 0 ?
5446                                                  GTK_DIR_RIGHT : GTK_DIR_LEFT))
5447                     {
5448                       GtkWidget *toplevel = gtk_widget_get_toplevel (GTK_WIDGET (label));
5449
5450                       if (toplevel)
5451                         gtk_widget_child_focus (toplevel,
5452                                                 count > 0 ?
5453                                                 GTK_DIR_RIGHT : GTK_DIR_LEFT);
5454                     }
5455                 }
5456               else
5457                 {
5458                   gtk_widget_error_bell (GTK_WIDGET (label));
5459                 }
5460             }
5461           break;
5462         case GTK_MOVEMENT_WORDS:
5463           while (count > 0)
5464             {
5465               new_pos = gtk_label_move_forward_word (label, new_pos);
5466               count--;
5467             }
5468           while (count < 0)
5469             {
5470               new_pos = gtk_label_move_backward_word (label, new_pos);
5471               count++;
5472             }
5473           if (new_pos == old_pos)
5474             gtk_widget_error_bell (GTK_WIDGET (label));
5475           break;
5476         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
5477         case GTK_MOVEMENT_PARAGRAPH_ENDS:
5478         case GTK_MOVEMENT_BUFFER_ENDS:
5479           /* FIXME: Can do better here */
5480           new_pos = count < 0 ? 0 : strlen (label->text);
5481           if (new_pos == old_pos)
5482             gtk_widget_error_bell (GTK_WIDGET (label));
5483           break;
5484         case GTK_MOVEMENT_DISPLAY_LINES:
5485         case GTK_MOVEMENT_PARAGRAPHS:
5486         case GTK_MOVEMENT_PAGES:
5487         case GTK_MOVEMENT_HORIZONTAL_PAGES:
5488           break;
5489         }
5490     }
5491
5492   if (extend_selection)
5493     gtk_label_select_region_index (label,
5494                                    label->select_info->selection_anchor,
5495                                    new_pos);
5496   else
5497     gtk_label_select_region_index (label, new_pos, new_pos);
5498 }
5499
5500 static void
5501 gtk_label_copy_clipboard (GtkLabel *label)
5502 {
5503   if (label->text && label->select_info)
5504     {
5505       gint start, end;
5506       gint len;
5507       GtkClipboard *clipboard;
5508
5509       start = MIN (label->select_info->selection_anchor,
5510                    label->select_info->selection_end);
5511       end = MAX (label->select_info->selection_anchor,
5512                  label->select_info->selection_end);
5513
5514       len = strlen (label->text);
5515
5516       if (end > len)
5517         end = len;
5518
5519       if (start > len)
5520         start = len;
5521
5522       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label), GDK_SELECTION_CLIPBOARD);
5523
5524       if (start != end)
5525         gtk_clipboard_set_text (clipboard, label->text + start, end - start);
5526       else
5527         {
5528           GtkLabelLink *link;
5529
5530           link = gtk_label_get_focus_link (label);
5531           if (link)
5532             gtk_clipboard_set_text (clipboard, link->uri, -1);
5533         }
5534     }
5535 }
5536
5537 static void
5538 gtk_label_select_all (GtkLabel *label)
5539 {
5540   gtk_label_select_region_index (label, 0, strlen (label->text));
5541 }
5542
5543 /* Quick hack of a popup menu
5544  */
5545 static void
5546 activate_cb (GtkWidget *menuitem,
5547              GtkLabel  *label)
5548 {
5549   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
5550   g_signal_emit_by_name (label, signal);
5551 }
5552
5553 static void
5554 append_action_signal (GtkLabel     *label,
5555                       GtkWidget    *menu,
5556                       const gchar  *stock_id,
5557                       const gchar  *signal,
5558                       gboolean      sensitive)
5559 {
5560   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
5561
5562   g_object_set_data (G_OBJECT (menuitem), I_("gtk-signal"), (char *)signal);
5563   g_signal_connect (menuitem, "activate",
5564                     G_CALLBACK (activate_cb), label);
5565
5566   gtk_widget_set_sensitive (menuitem, sensitive);
5567   
5568   gtk_widget_show (menuitem);
5569   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5570 }
5571
5572 static void
5573 popup_menu_detach (GtkWidget *attach_widget,
5574                    GtkMenu   *menu)
5575 {
5576   GtkLabel *label = GTK_LABEL (attach_widget);
5577
5578   if (label->select_info)
5579     label->select_info->popup_menu = NULL;
5580 }
5581
5582 static void
5583 popup_position_func (GtkMenu   *menu,
5584                      gint      *x,
5585                      gint      *y,
5586                      gboolean  *push_in,
5587                      gpointer   user_data)
5588 {
5589   GtkLabel *label;
5590   GtkWidget *widget;
5591   GtkRequisition req;
5592   GdkScreen *screen;
5593
5594   label = GTK_LABEL (user_data);
5595   widget = GTK_WIDGET (label);
5596
5597   g_return_if_fail (gtk_widget_get_realized (widget));
5598
5599   screen = gtk_widget_get_screen (widget);
5600   gdk_window_get_origin (widget->window, x, y);
5601
5602   *x += widget->allocation.x;
5603   *y += widget->allocation.y;
5604
5605   gtk_widget_size_request (GTK_WIDGET (menu), &req);
5606
5607   *x += widget->allocation.width / 2;
5608   *y += widget->allocation.height;
5609
5610   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
5611   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
5612 }
5613
5614 static void
5615 open_link_activate_cb (GtkMenuItem *menu_item,
5616                        GtkLabel    *label)
5617 {
5618   GtkLabelLink *link;
5619
5620   link = gtk_label_get_current_link (label);
5621
5622   if (link)
5623     emit_activate_link (label, link);
5624 }
5625
5626 static void
5627 copy_link_activate_cb (GtkMenuItem *menu_item,
5628                        GtkLabel    *label)
5629 {
5630   GtkClipboard *clipboard;
5631   const gchar *uri;
5632
5633   uri = gtk_label_get_current_uri (label);
5634   if (uri)
5635     {
5636       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label), GDK_SELECTION_CLIPBOARD);
5637       gtk_clipboard_set_text (clipboard, uri, -1);
5638     }
5639 }
5640
5641 static gboolean
5642 gtk_label_popup_menu (GtkWidget *widget)
5643 {
5644   gtk_label_do_popup (GTK_LABEL (widget), NULL);
5645
5646   return TRUE;
5647 }
5648
5649 static void
5650 gtk_label_do_popup (GtkLabel       *label,
5651                     GdkEventButton *event)
5652 {
5653   GtkWidget *menuitem;
5654   GtkWidget *menu;
5655   GtkWidget *image;
5656   gboolean have_selection;
5657   GtkLabelLink *link;
5658
5659   if (!label->select_info)
5660     return;
5661
5662   if (label->select_info->popup_menu)
5663     gtk_widget_destroy (label->select_info->popup_menu);
5664
5665   label->select_info->popup_menu = menu = gtk_menu_new ();
5666
5667   gtk_menu_attach_to_widget (GTK_MENU (menu), GTK_WIDGET (label), popup_menu_detach);
5668
5669   have_selection =
5670     label->select_info->selection_anchor != label->select_info->selection_end;
5671
5672   if (event)
5673     {
5674       if (label->select_info->link_clicked)
5675         link = label->select_info->active_link;
5676       else
5677         link = NULL;
5678     }
5679   else
5680     link = gtk_label_get_focus_link (label);
5681
5682   if (!have_selection && link)
5683     {
5684       /* Open Link */
5685       menuitem = gtk_image_menu_item_new_with_mnemonic (_("_Open Link"));
5686       gtk_widget_show (menuitem);
5687       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5688
5689       g_signal_connect (G_OBJECT (menuitem), "activate",
5690                         G_CALLBACK (open_link_activate_cb), label);
5691
5692       image = gtk_image_new_from_stock (GTK_STOCK_JUMP_TO, GTK_ICON_SIZE_MENU);
5693       gtk_widget_show (image);
5694       gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (menuitem), image);
5695
5696       /* Copy Link Address */
5697       menuitem = gtk_image_menu_item_new_with_mnemonic (_("Copy _Link Address"));
5698       gtk_widget_show (menuitem);
5699       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5700
5701       g_signal_connect (G_OBJECT (menuitem), "activate",
5702                         G_CALLBACK (copy_link_activate_cb), label);
5703
5704       image = gtk_image_new_from_stock (GTK_STOCK_COPY, GTK_ICON_SIZE_MENU);
5705       gtk_widget_show (image);
5706       gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (menuitem), image);
5707     }
5708   else
5709     {
5710       append_action_signal (label, menu, GTK_STOCK_CUT, "cut-clipboard", FALSE);
5711       append_action_signal (label, menu, GTK_STOCK_COPY, "copy-clipboard", have_selection);
5712       append_action_signal (label, menu, GTK_STOCK_PASTE, "paste-clipboard", FALSE);
5713   
5714       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
5715       gtk_widget_set_sensitive (menuitem, FALSE);
5716       gtk_widget_show (menuitem);
5717       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5718
5719       menuitem = gtk_separator_menu_item_new ();
5720       gtk_widget_show (menuitem);
5721       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5722
5723       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_SELECT_ALL, NULL);
5724       g_signal_connect_swapped (menuitem, "activate",
5725                                 G_CALLBACK (gtk_label_select_all), label);
5726       gtk_widget_show (menuitem);
5727       gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
5728     }
5729
5730   g_signal_emit (label, signals[POPULATE_POPUP], 0, menu);
5731
5732   if (event)
5733     gtk_menu_popup (GTK_MENU (menu), NULL, NULL,
5734                     NULL, NULL,
5735                     event->button, event->time);
5736   else
5737     {
5738       gtk_menu_popup (GTK_MENU (menu), NULL, NULL,
5739                       popup_position_func, label,
5740                       0, gtk_get_current_event_time ());
5741       gtk_menu_shell_select_first (GTK_MENU_SHELL (menu), FALSE);
5742     }
5743 }
5744
5745 static void
5746 gtk_label_clear_links (GtkLabel *label)
5747 {
5748   if (!label->select_info)
5749     return;
5750
5751   g_list_foreach (label->select_info->links, (GFunc)link_free, NULL);
5752   g_list_free (label->select_info->links);
5753   label->select_info->links = NULL;
5754   label->select_info->active_link = NULL;
5755 }
5756
5757 static void
5758 gtk_label_rescan_links (GtkLabel *label)
5759 {
5760   PangoLayout *layout = label->layout;
5761   PangoAttrList *attlist;
5762   PangoAttrIterator *iter;
5763   GList *links;
5764
5765   if (!label->select_info || !label->select_info->links)
5766     return;
5767
5768   attlist = pango_layout_get_attributes (layout);
5769
5770   if (attlist == NULL)
5771     return;
5772
5773   iter = pango_attr_list_get_iterator (attlist);
5774
5775   links = label->select_info->links;
5776
5777   do
5778     {
5779       PangoAttribute *underline;
5780       PangoAttribute *color;
5781
5782       underline = pango_attr_iterator_get (iter, PANGO_ATTR_UNDERLINE);
5783       color = pango_attr_iterator_get (iter, PANGO_ATTR_FOREGROUND);
5784
5785       if (underline != NULL && color != NULL)
5786         {
5787           gint start, end;
5788           PangoRectangle start_pos;
5789           PangoRectangle end_pos;
5790           GtkLabelLink *link;
5791
5792           pango_attr_iterator_range (iter, &start, &end);
5793           pango_layout_index_to_pos (layout, start, &start_pos);
5794           pango_layout_index_to_pos (layout, end, &end_pos);
5795
5796           if (links == NULL)
5797             {
5798               g_warning ("Ran out of links");
5799               break;
5800             }
5801           link = links->data;
5802           links = links->next;
5803           link->start = start;
5804           link->end = end;
5805         }
5806       } while (pango_attr_iterator_next (iter));
5807
5808     pango_attr_iterator_destroy (iter);
5809 }
5810
5811 static gboolean
5812 gtk_label_activate_link (GtkLabel    *label,
5813                          const gchar *uri)
5814 {
5815   GtkWidget *widget = GTK_WIDGET (label);
5816   GError *error = NULL;
5817
5818   if (!gtk_show_uri (gtk_widget_get_screen (widget),
5819                      uri, gtk_get_current_event_time (), &error))
5820     {
5821       g_warning ("Unable to show '%s': %s", uri, error->message);
5822       g_error_free (error);
5823     }
5824
5825   return TRUE;
5826 }
5827
5828 static void
5829 emit_activate_link (GtkLabel     *label,
5830                     GtkLabelLink *link)
5831 {
5832   gboolean handled;
5833
5834   g_signal_emit (label, signals[ACTIVATE_LINK], 0, link->uri, &handled);
5835   if (handled && label->track_links && !link->visited)
5836     {
5837       link->visited = TRUE;
5838       /* FIXME: shouldn't have to redo everything here */
5839       gtk_label_recalculate (label);
5840     }
5841 }
5842
5843 static void
5844 gtk_label_activate_current_link (GtkLabel *label)
5845 {
5846   GtkLabelLink *link;
5847   GtkWidget *widget = GTK_WIDGET (label);
5848
5849   link = gtk_label_get_focus_link (label);
5850
5851   if (link)
5852     {
5853       emit_activate_link (label, link);
5854     }
5855   else
5856     {
5857       GtkWidget *toplevel;
5858       GtkWindow *window;
5859
5860       toplevel = gtk_widget_get_toplevel (widget);
5861       if (GTK_IS_WINDOW (toplevel))
5862         {
5863           window = GTK_WINDOW (toplevel);
5864
5865           if (window &&
5866               window->default_widget != widget &&
5867               !(widget == window->focus_widget &&
5868                 (!window->default_widget || !gtk_widget_is_sensitive (window->default_widget))))
5869             gtk_window_activate_default (window);
5870         }
5871     }
5872 }
5873
5874 static GtkLabelLink *
5875 gtk_label_get_current_link (GtkLabel *label)
5876 {
5877   GtkLabelLink *link;
5878
5879   if (!label->select_info)
5880     return NULL;
5881
5882   if (label->select_info->link_clicked)
5883     link = label->select_info->active_link;
5884   else
5885     link = gtk_label_get_focus_link (label);
5886
5887   return link;
5888 }
5889
5890 /**
5891  * gtk_label_get_current_uri:
5892  * @label: a #GtkLabel
5893  *
5894  * Returns the URI for the currently active link in the label.
5895  * The active link is the one under the mouse pointer or, in a
5896  * selectable label, the link in which the text cursor is currently
5897  * positioned.
5898  *
5899  * This function is intended for use in a #GtkLabel::activate-link handler
5900  * or for use in a #GtkWidget::query-tooltip handler.
5901  *
5902  * Returns: the currently active URI. The string is owned by GTK+ and must
5903  *   not be freed or modified.
5904  *
5905  * Since: 2.18
5906  */
5907 G_CONST_RETURN gchar *
5908 gtk_label_get_current_uri (GtkLabel *label)
5909 {
5910   GtkLabelLink *link;
5911   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
5912
5913   link = gtk_label_get_current_link (label);
5914
5915   if (link)
5916     return link->uri;
5917
5918   return NULL;
5919 }
5920
5921 /**
5922  * gtk_label_set_track_visited_links:
5923  * @label: a #GtkLabel
5924  * @track_links: %TRUE to track visited links
5925  *
5926  * Sets whether the label should keep track of clicked
5927  * links (and use a different color for them).
5928  *
5929  * Since: 2.18
5930  */
5931 void
5932 gtk_label_set_track_visited_links (GtkLabel *label,
5933                                    gboolean  track_links)
5934 {
5935   g_return_if_fail (GTK_IS_LABEL (label));
5936
5937   track_links = track_links != FALSE;
5938
5939   if (label->track_links != track_links)
5940     {
5941       label->track_links = track_links;
5942
5943       /* FIXME: shouldn't have to redo everything here */
5944       gtk_label_recalculate (label);
5945
5946       g_object_notify (G_OBJECT (label), "track-visited-links");
5947     }
5948 }
5949
5950 /**
5951  * gtk_label_get_track_visited_links:
5952  * @label: a #GtkLabel
5953  *
5954  * Returns whether the label is currently keeping track
5955  * of clicked links.
5956  *
5957  * Returns: %TRUE if clicked links are remembered
5958  *
5959  * Since: 2.18
5960  */
5961 gboolean
5962 gtk_label_get_track_visited_links (GtkLabel *label)
5963 {
5964   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
5965
5966   return label->track_links;
5967 }
5968
5969 static gboolean
5970 gtk_label_query_tooltip (GtkWidget  *widget,
5971                          gint        x,
5972                          gint        y,
5973                          gboolean    keyboard_tip,
5974                          GtkTooltip *tooltip)
5975 {
5976   GtkLabel *label = GTK_LABEL (widget);
5977   GtkLabelSelectionInfo *info = label->select_info;
5978   gint index = -1;
5979   GList *l;
5980
5981   if (info && info->links)
5982     {
5983       if (keyboard_tip)
5984         {
5985           if (info->selection_anchor == info->selection_end)
5986             index = info->selection_anchor;
5987         }
5988       else
5989         {
5990           if (!get_layout_index (label, x, y, &index))
5991             index = -1;
5992         }
5993
5994       if (index != -1)
5995         {
5996           for (l = info->links; l != NULL; l = l->next)
5997             {
5998               GtkLabelLink *link = l->data;
5999               if (index >= link->start && index <= link->end)
6000                 {
6001                   if (link->title)
6002                     {
6003                       gtk_tooltip_set_markup (tooltip, link->title);
6004                       return TRUE;
6005                     }
6006                   break;
6007                 }
6008             }
6009         }
6010     }
6011
6012   return GTK_WIDGET_CLASS (gtk_label_parent_class)->query_tooltip (widget,
6013                                                                    x, y,
6014                                                                    keyboard_tip,
6015                                                                    tooltip);
6016 }
6017
6018
6019 #define __GTK_LABEL_C__
6020 #include "gtkaliasdef.c"