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