]> Pileus Git - ~andy/gtk/blob - gtk/gtklabel.c
x
[~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 #include <math.h>
28 #include <string.h>
29 #include "gtkalias.h"
30 #include "gtklabel.h"
31 #include "gtkdnd.h"
32 #include "gtkmain.h"
33 #include "gtkmarshalers.h"
34 #include "gtkwindow.h"
35 #include "gdk/gdkkeysyms.h"
36 #include "gtkclipboard.h"
37 #include <pango/pango.h>
38 #include "gtkimagemenuitem.h"
39 #include "gtkintl.h"
40 #include "gtkseparatormenuitem.h"
41 #include "gtkmenuitem.h"
42 #include "gtknotebook.h"
43 #include "gtkstock.h"
44 #include "gtkbindings.h"
45
46 #define GTK_LABEL_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_LABEL, GtkLabelPrivate))
47
48 typedef struct
49 {
50   gint width_chars;
51   gint max_width_chars;
52   guint single_line_mode : 1;
53   guint have_transform : 1;
54   gdouble angle;
55 }
56 GtkLabelPrivate;
57
58 struct _GtkLabelSelectionInfo
59 {
60   GdkWindow *window;
61   gint selection_anchor;
62   gint selection_end;
63   GtkWidget *popup_menu;
64   
65   gint drag_start_x;
66   gint drag_start_y;
67
68   guint in_drag : 1;
69 };
70
71 enum {
72   MOVE_CURSOR,
73   COPY_CLIPBOARD,
74   POPULATE_POPUP,
75   LAST_SIGNAL
76 };
77
78 enum {
79   PROP_0,
80   PROP_LABEL,
81   PROP_ATTRIBUTES,
82   PROP_USE_MARKUP,
83   PROP_USE_UNDERLINE,
84   PROP_JUSTIFY,
85   PROP_PATTERN,
86   PROP_WRAP,
87   PROP_SELECTABLE,
88   PROP_MNEMONIC_KEYVAL,
89   PROP_MNEMONIC_WIDGET,
90   PROP_CURSOR_POSITION,
91   PROP_SELECTION_BOUND,
92   PROP_ELLIPSIZE,
93   PROP_WIDTH_CHARS,
94   PROP_SINGLE_LINE_MODE,
95   PROP_ANGLE,
96   PROP_MAX_WIDTH_CHARS
97 };
98
99 static guint signals[LAST_SIGNAL] = { 0 };
100
101 static void gtk_label_class_init        (GtkLabelClass    *klass);
102 static void gtk_label_init              (GtkLabel         *label);
103 static void gtk_label_set_property      (GObject          *object,
104                                          guint             prop_id,
105                                          const GValue     *value,
106                                          GParamSpec       *pspec);
107 static void gtk_label_get_property      (GObject          *object,
108                                          guint             prop_id,
109                                          GValue           *value,
110                                          GParamSpec       *pspec);
111 static void gtk_label_destroy           (GtkObject        *object);
112 static void gtk_label_finalize          (GObject          *object);
113 static void gtk_label_size_request      (GtkWidget        *widget,
114                                          GtkRequisition   *requisition);
115 static void gtk_label_size_allocate     (GtkWidget        *widget,
116                                          GtkAllocation    *allocation);
117 static void gtk_label_state_changed     (GtkWidget        *widget,
118                                          GtkStateType      state);
119 static void gtk_label_style_set         (GtkWidget        *widget,
120                                          GtkStyle         *previous_style);
121 static void gtk_label_direction_changed (GtkWidget        *widget,
122                                          GtkTextDirection  previous_dir);
123 static gint gtk_label_expose            (GtkWidget        *widget,
124                                          GdkEventExpose   *event);
125
126 static void gtk_label_realize           (GtkWidget        *widget);
127 static void gtk_label_unrealize         (GtkWidget        *widget);
128 static void gtk_label_map               (GtkWidget        *widget);
129 static void gtk_label_unmap             (GtkWidget        *widget);
130
131 static gboolean gtk_label_button_press      (GtkWidget        *widget,
132                                              GdkEventButton   *event);
133 static gboolean gtk_label_button_release    (GtkWidget        *widget,
134                                              GdkEventButton   *event);
135 static gboolean gtk_label_motion            (GtkWidget        *widget,
136                                              GdkEventMotion   *event);
137
138
139 static void gtk_label_set_text_internal          (GtkLabel      *label,
140                                                   gchar         *str);
141 static void gtk_label_set_label_internal         (GtkLabel      *label,
142                                                   gchar         *str);
143 static void gtk_label_set_use_markup_internal    (GtkLabel      *label,
144                                                   gboolean       val);
145 static void gtk_label_set_use_underline_internal (GtkLabel      *label,
146                                                   gboolean       val);
147 static void gtk_label_set_attributes_internal    (GtkLabel      *label,
148                                                   PangoAttrList *attrs);
149 static void gtk_label_set_uline_text_internal    (GtkLabel      *label,
150                                                   const gchar   *str);
151 static void gtk_label_set_pattern_internal       (GtkLabel      *label,
152                                                   const gchar   *pattern);
153 static void set_markup                           (GtkLabel      *label,
154                                                   const gchar   *str,
155                                                   gboolean       with_uline);
156 static void gtk_label_recalculate                (GtkLabel      *label);
157 static void gtk_label_hierarchy_changed          (GtkWidget     *widget,
158                                                   GtkWidget     *old_toplevel);
159 static void gtk_label_screen_changed             (GtkWidget     *widget,
160                                                   GdkScreen     *old_screen);
161
162 static void gtk_label_create_window       (GtkLabel *label);
163 static void gtk_label_destroy_window      (GtkLabel *label);
164 static void gtk_label_clear_layout        (GtkLabel *label);
165 static void gtk_label_ensure_layout       (GtkLabel *label);
166 static void gtk_label_select_region_index (GtkLabel *label,
167                                            gint      anchor_index,
168                                            gint      end_index);
169
170 static gboolean gtk_label_mnemonic_activate (GtkWidget         *widget,
171                                              gboolean           group_cycling);
172 static void     gtk_label_setup_mnemonic    (GtkLabel          *label,
173                                              guint              last_key);
174 static void     gtk_label_drag_data_get     (GtkWidget         *widget,
175                                              GdkDragContext    *context,
176                                              GtkSelectionData  *selection_data,
177                                              guint              info,
178                                              guint              time);
179
180
181 /* For selectable lables: */
182 static void gtk_label_move_cursor        (GtkLabel        *label,
183                                           GtkMovementStep  step,
184                                           gint             count,
185                                           gboolean         extend_selection);
186 static void gtk_label_copy_clipboard     (GtkLabel        *label);
187 static void gtk_label_select_all         (GtkLabel        *label);
188 static void gtk_label_do_popup           (GtkLabel        *label,
189                                           GdkEventButton  *event);
190
191 static gint gtk_label_move_forward_word  (GtkLabel        *label,
192                                           gint             start);
193 static gint gtk_label_move_backward_word (GtkLabel        *label,
194                                           gint             start);
195
196 static GtkMiscClass *parent_class = NULL;
197
198
199 GType
200 gtk_label_get_type (void)
201 {
202   static GType label_type = 0;
203   
204   if (!label_type)
205     {
206       static const GTypeInfo label_info =
207       {
208         sizeof (GtkLabelClass),
209         NULL,           /* base_init */
210         NULL,           /* base_finalize */
211         (GClassInitFunc) gtk_label_class_init,
212         NULL,           /* class_finalize */
213         NULL,           /* class_data */
214         sizeof (GtkLabel),
215         32,             /* n_preallocs */
216         (GInstanceInitFunc) gtk_label_init,
217       };
218
219       label_type = g_type_register_static (GTK_TYPE_MISC, "GtkLabel",
220                                            &label_info, 0);
221     }
222   
223   return label_type;
224 }
225
226 static void
227 add_move_binding (GtkBindingSet  *binding_set,
228                   guint           keyval,
229                   guint           modmask,
230                   GtkMovementStep step,
231                   gint            count)
232 {
233   g_return_if_fail ((modmask & GDK_SHIFT_MASK) == 0);
234   
235   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
236                                 "move_cursor", 3,
237                                 G_TYPE_ENUM, step,
238                                 G_TYPE_INT, count,
239                                 G_TYPE_BOOLEAN, FALSE);
240
241   /* Selection-extending version */
242   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
243                                 "move_cursor", 3,
244                                 G_TYPE_ENUM, step,
245                                 G_TYPE_INT, count,
246                                 G_TYPE_BOOLEAN, TRUE);
247 }
248
249 static void
250 gtk_label_class_init (GtkLabelClass *class)
251 {
252   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
253   GtkObjectClass *object_class = GTK_OBJECT_CLASS (class);
254   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
255   GtkBindingSet *binding_set;
256
257   parent_class = g_type_class_peek_parent (class);
258   
259   gobject_class->set_property = gtk_label_set_property;
260   gobject_class->get_property = gtk_label_get_property;
261   gobject_class->finalize = gtk_label_finalize;
262
263   object_class->destroy = gtk_label_destroy;
264   
265   widget_class->size_request = gtk_label_size_request;
266   widget_class->size_allocate = gtk_label_size_allocate;
267   widget_class->state_changed = gtk_label_state_changed;
268   widget_class->style_set = gtk_label_style_set;
269   widget_class->direction_changed = gtk_label_direction_changed;
270   widget_class->expose_event = gtk_label_expose;
271   widget_class->realize = gtk_label_realize;
272   widget_class->unrealize = gtk_label_unrealize;
273   widget_class->map = gtk_label_map;
274   widget_class->unmap = gtk_label_unmap;
275   widget_class->button_press_event = gtk_label_button_press;
276   widget_class->button_release_event = gtk_label_button_release;
277   widget_class->motion_notify_event = gtk_label_motion;
278   widget_class->hierarchy_changed = gtk_label_hierarchy_changed;
279   widget_class->screen_changed = gtk_label_screen_changed;
280   widget_class->mnemonic_activate = gtk_label_mnemonic_activate;
281   widget_class->drag_data_get = gtk_label_drag_data_get;
282
283   class->move_cursor = gtk_label_move_cursor;
284   class->copy_clipboard = gtk_label_copy_clipboard;
285   
286   signals[MOVE_CURSOR] = 
287     g_signal_new ("move_cursor",
288                   G_OBJECT_CLASS_TYPE (gobject_class),
289                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
290                   G_STRUCT_OFFSET (GtkLabelClass, move_cursor),
291                   NULL, NULL,
292                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN,
293                   G_TYPE_NONE, 3,
294                   GTK_TYPE_MOVEMENT_STEP,
295                   G_TYPE_INT,
296                   G_TYPE_BOOLEAN);
297   
298   signals[COPY_CLIPBOARD] =
299     g_signal_new ("copy_clipboard",
300                   G_OBJECT_CLASS_TYPE (gobject_class),
301                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
302                   G_STRUCT_OFFSET (GtkLabelClass, copy_clipboard),
303                   NULL, NULL,
304                   _gtk_marshal_VOID__VOID,
305                   G_TYPE_NONE, 0);
306   
307   signals[POPULATE_POPUP] =
308     g_signal_new ("populate_popup",
309                   G_OBJECT_CLASS_TYPE (gobject_class),
310                   G_SIGNAL_RUN_LAST,
311                   G_STRUCT_OFFSET (GtkLabelClass, populate_popup),
312                   NULL, NULL,
313                   _gtk_marshal_VOID__OBJECT,
314                   G_TYPE_NONE, 1,
315                   GTK_TYPE_MENU);
316
317   g_object_class_install_property (gobject_class,
318                                    PROP_LABEL,
319                                    g_param_spec_string ("label",
320                                                         P_("Label"),
321                                                         P_("The text of the label"),
322                                                         NULL,
323                                                         G_PARAM_READWRITE));
324   g_object_class_install_property (gobject_class,
325                                    PROP_ATTRIBUTES,
326                                    g_param_spec_boxed ("attributes",
327                                                        P_("Attributes"),
328                                                        P_("A list of style attributes to apply to the text of the label"),
329                                                        PANGO_TYPE_ATTR_LIST,
330                                                        G_PARAM_READWRITE));
331   g_object_class_install_property (gobject_class,
332                                    PROP_USE_MARKUP,
333                                    g_param_spec_boolean ("use-markup",
334                                                          P_("Use markup"),
335                                                          P_("The text of the label includes XML markup. See pango_parse_markup()"),
336                                                         FALSE,
337                                                         G_PARAM_READWRITE));
338   g_object_class_install_property (gobject_class,
339                                    PROP_USE_UNDERLINE,
340                                    g_param_spec_boolean ("use-underline",
341                                                          P_("Use underline"),
342                                                          P_("If set, an underline in the text indicates the next character should be used for the mnemonic accelerator key"),
343                                                         FALSE,
344                                                         G_PARAM_READWRITE));
345
346   g_object_class_install_property (gobject_class,
347                                    PROP_JUSTIFY,
348                                    g_param_spec_enum ("justify",
349                                                       P_("Justification"),
350                                                       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"),
351                                                       GTK_TYPE_JUSTIFICATION,
352                                                       GTK_JUSTIFY_LEFT,
353                                                       G_PARAM_READWRITE));
354
355   g_object_class_install_property (gobject_class,
356                                    PROP_PATTERN,
357                                    g_param_spec_string ("pattern",
358                                                         P_("Pattern"),
359                                                         P_("A string with _ characters in positions correspond to characters in the text to underline"),
360                                                         NULL,
361                                                         G_PARAM_WRITABLE));
362
363   g_object_class_install_property (gobject_class,
364                                    PROP_WRAP,
365                                    g_param_spec_boolean ("wrap",
366                                                         P_("Line wrap"),
367                                                         P_("If set, wrap lines if the text becomes too wide"),
368                                                         FALSE,
369                                                         G_PARAM_READWRITE));
370   g_object_class_install_property (gobject_class,
371                                    PROP_SELECTABLE,
372                                    g_param_spec_boolean ("selectable",
373                                                         P_("Selectable"),
374                                                         P_("Whether the label text can be selected with the mouse"),
375                                                         FALSE,
376                                                         G_PARAM_READWRITE));
377   g_object_class_install_property (gobject_class,
378                                    PROP_MNEMONIC_KEYVAL,
379                                    g_param_spec_uint ("mnemonic-keyval",
380                                                       P_("Mnemonic key"),
381                                                       P_("The mnemonic accelerator key for this label"),
382                                                       0,
383                                                       G_MAXUINT,
384                                                       GDK_VoidSymbol,
385                                                       G_PARAM_READABLE));
386   g_object_class_install_property (gobject_class,
387                                    PROP_MNEMONIC_WIDGET,
388                                    g_param_spec_object ("mnemonic-widget",
389                                                         P_("Mnemonic widget"),
390                                                         P_("The widget to be activated when the label's mnemonic "
391                                                           "key is pressed"),
392                                                         GTK_TYPE_WIDGET,
393                                                         G_PARAM_READWRITE));
394
395   g_object_class_install_property (gobject_class,
396                                    PROP_CURSOR_POSITION,
397                                    g_param_spec_int ("cursor-position",
398                                                      P_("Cursor Position"),
399                                                      P_("The current position of the insertion cursor in chars"),
400                                                      0,
401                                                      G_MAXINT,
402                                                      0,
403                                                      G_PARAM_READABLE));
404   
405   g_object_class_install_property (gobject_class,
406                                    PROP_SELECTION_BOUND,
407                                    g_param_spec_int ("selection-bound",
408                                                      P_("Selection Bound"),
409                                                      P_("The position of the opposite end of the selection from the cursor in chars"),
410                                                      0,
411                                                      G_MAXINT,
412                                                      0,
413                                                      G_PARAM_READABLE));
414   
415   /**
416    * GtkLabel:ellipsize:
417    *
418    * The preferred place to ellipsize the string, if the label does not have 
419    * enough room to display the entire string, specified as a #PangoEllisizeMode. 
420    *
421    * Note that setting this property to a value other than %PANGO_ELLIPSIZE_NONE 
422    * has the side-effect that the label requests only enough space to display the
423    * ellipsis "...". In particular, this means that ellipsizing labels don't
424    * work well in notebook tabs, unless the tab's ::tab-expand property is set
425    * to %TRUE. Other means to set a label's width are
426    * gtk_widget_set_size_request() and gtk_label_set_width_chars().
427    *
428    * Since: 2.6
429    */
430   g_object_class_install_property (gobject_class,
431                                    PROP_ELLIPSIZE,
432                                    g_param_spec_enum ("ellipsize",
433                                                       P_("Ellipsize"),
434                                                       P_("The preferred place to ellipsize the string, if the label does not have enough room to display the entire string, if at all"),
435                                                       PANGO_TYPE_ELLIPSIZE_MODE,
436                                                       PANGO_ELLIPSIZE_NONE,
437                                                       G_PARAM_READWRITE));
438
439   /**
440    * GtkLabel:width-chars:
441    * 
442    * The desired width of the label, in characters. If this property is set to
443    * -1, the width will be calculated automatically, otherwise the label will
444    * request either 3 characters or the property value, whichever is greater.
445    * If the width-chars property is set to a positive value, then the 
446    * max-width-chars property is ignored. 
447    *
448    * Since: 2.6
449    **/
450   g_object_class_install_property (gobject_class,
451                                    PROP_WIDTH_CHARS,
452                                    g_param_spec_int ("width-chars",
453                                                      P_("Width In Characters"),
454                                                      P_("The desired width of the label, in characters"),
455                                                      -1,
456                                                      G_MAXINT,
457                                                      -1,
458                                                      G_PARAM_READWRITE));
459   
460   /**
461    * GtkLabel:single-line-mode:
462    * 
463    * Whether the label is in single line mode. In single line mode,
464    * the height of the label does not depend on the actual text, it
465    * is always set to ascent + descent of the font. This can be an
466    * advantage in situations where resizing the label because of text 
467    * changes would be distracting, e.g. in a statusbar.
468    *
469    * Since: 2.6
470    **/
471   g_object_class_install_property (gobject_class,
472                                    PROP_SINGLE_LINE_MODE,
473                                    g_param_spec_boolean ("single-line-mode",
474                                                         P_("Single Line Mode"),
475                                                         P_("Whether the label is in single line mode"),
476                                                         FALSE,
477                                                         G_PARAM_READWRITE));
478
479   /**
480    * GtkLabel:angle:
481    * 
482    * The angle that the baseline of the label makes with the horizontal,
483    * in degrees, measured counterclockwise. An angle of 90 reads from
484    * from bottom to top, an angle of 270, from top to bottom. Ignored
485    * if the label is selectable, wrapped, or ellipsized.
486    *
487    * Since: 2.6
488    **/
489   g_object_class_install_property (gobject_class,
490                                    PROP_ANGLE,
491                                    g_param_spec_double ("angle",
492                                                         P_("Angle"),
493                                                         P_("Angle at which the label is rotated"),
494                                                         0.0,
495                                                         360.0,
496                                                         0.0, 
497                                                         G_PARAM_READWRITE));
498   
499   /**
500    * GtkLabel:max-width-chars:
501    * 
502    * The desired maximum width of the label, in characters. If this property 
503    * is set to -1, the width will be calculated automatically, otherwise the 
504    * label will request space for no more than the requested number of 
505    * characters. If the width-chars property is set to a positive value,
506    * then the max-width-chars property is ignored.
507    * 
508    * Since: 2.6
509    **/
510   g_object_class_install_property (gobject_class,
511                                    PROP_MAX_WIDTH_CHARS,
512                                    g_param_spec_int ("max-width-chars",
513                                                      P_("Maximum Width In Characters"),
514                                                      P_("The desired maximum width of the label, in characters"),
515                                                      -1,
516                                                      G_MAXINT,
517                                                      -1,
518                                                      G_PARAM_READWRITE));
519   /*
520    * Key bindings
521    */
522
523   binding_set = gtk_binding_set_by_class (class);
524
525   /* Moving the insertion point */
526   add_move_binding (binding_set, GDK_Right, 0,
527                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
528   
529   add_move_binding (binding_set, GDK_Left, 0,
530                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
531
532   add_move_binding (binding_set, GDK_KP_Right, 0,
533                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
534   
535   add_move_binding (binding_set, GDK_KP_Left, 0,
536                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
537   
538   add_move_binding (binding_set, GDK_f, GDK_CONTROL_MASK,
539                     GTK_MOVEMENT_LOGICAL_POSITIONS, 1);
540   
541   add_move_binding (binding_set, GDK_b, GDK_CONTROL_MASK,
542                     GTK_MOVEMENT_LOGICAL_POSITIONS, -1);
543   
544   add_move_binding (binding_set, GDK_Right, GDK_CONTROL_MASK,
545                     GTK_MOVEMENT_WORDS, 1);
546
547   add_move_binding (binding_set, GDK_Left, GDK_CONTROL_MASK,
548                     GTK_MOVEMENT_WORDS, -1);
549
550   add_move_binding (binding_set, GDK_KP_Right, GDK_CONTROL_MASK,
551                     GTK_MOVEMENT_WORDS, 1);
552
553   add_move_binding (binding_set, GDK_KP_Left, GDK_CONTROL_MASK,
554                     GTK_MOVEMENT_WORDS, -1);
555   
556   add_move_binding (binding_set, GDK_a, GDK_CONTROL_MASK,
557                     GTK_MOVEMENT_PARAGRAPH_ENDS, -1);
558
559   add_move_binding (binding_set, GDK_e, GDK_CONTROL_MASK,
560                     GTK_MOVEMENT_PARAGRAPH_ENDS, 1);
561
562   add_move_binding (binding_set, GDK_f, GDK_MOD1_MASK,
563                     GTK_MOVEMENT_WORDS, 1);
564
565   add_move_binding (binding_set, GDK_b, GDK_MOD1_MASK,
566                     GTK_MOVEMENT_WORDS, -1);
567
568   add_move_binding (binding_set, GDK_Home, 0,
569                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
570
571   add_move_binding (binding_set, GDK_End, 0,
572                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
573
574   add_move_binding (binding_set, GDK_KP_Home, 0,
575                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
576
577   add_move_binding (binding_set, GDK_KP_End, 0,
578                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
579   
580   add_move_binding (binding_set, GDK_Home, GDK_CONTROL_MASK,
581                     GTK_MOVEMENT_BUFFER_ENDS, -1);
582
583   add_move_binding (binding_set, GDK_End, GDK_CONTROL_MASK,
584                     GTK_MOVEMENT_BUFFER_ENDS, 1);
585
586   add_move_binding (binding_set, GDK_KP_Home, GDK_CONTROL_MASK,
587                     GTK_MOVEMENT_BUFFER_ENDS, -1);
588
589   add_move_binding (binding_set, GDK_KP_End, GDK_CONTROL_MASK,
590                     GTK_MOVEMENT_BUFFER_ENDS, 1);
591
592   /* copy */
593   gtk_binding_entry_add_signal (binding_set, GDK_c, GDK_CONTROL_MASK,
594                                 "copy_clipboard", 0);
595                                 
596   g_type_class_add_private (class, sizeof (GtkLabelPrivate));
597 }
598
599 static void 
600 gtk_label_set_property (GObject      *object,
601                         guint         prop_id,
602                         const GValue *value,
603                         GParamSpec   *pspec)
604 {
605   GtkLabel *label;
606
607   label = GTK_LABEL (object);
608   
609   switch (prop_id)
610     {
611     case PROP_LABEL:
612       gtk_label_set_label (label, g_value_get_string (value));
613       break;
614     case PROP_ATTRIBUTES:
615       gtk_label_set_attributes (label, g_value_get_boxed (value));
616       break;
617     case PROP_USE_MARKUP:
618       gtk_label_set_use_markup (label, g_value_get_boolean (value));
619       break;
620     case PROP_USE_UNDERLINE:
621       gtk_label_set_use_underline (label, g_value_get_boolean (value));
622       break;
623     case PROP_JUSTIFY:
624       gtk_label_set_justify (label, g_value_get_enum (value));
625       break;
626     case PROP_PATTERN:
627       gtk_label_set_pattern (label, g_value_get_string (value));
628       break;
629     case PROP_WRAP:
630       gtk_label_set_line_wrap (label, g_value_get_boolean (value));
631       break;      
632     case PROP_SELECTABLE:
633       gtk_label_set_selectable (label, g_value_get_boolean (value));
634       break;      
635     case PROP_MNEMONIC_WIDGET:
636       gtk_label_set_mnemonic_widget (label, (GtkWidget*) g_value_get_object (value));
637       break;
638     case PROP_ELLIPSIZE:
639       gtk_label_set_ellipsize (label, g_value_get_enum (value));
640       break;
641     case PROP_WIDTH_CHARS:
642       gtk_label_set_width_chars (label, g_value_get_int (value));
643       break;
644     case PROP_SINGLE_LINE_MODE:
645       gtk_label_set_single_line_mode (label, g_value_get_boolean (value));
646       break;      
647     case PROP_ANGLE:
648       gtk_label_set_angle (label, g_value_get_double (value));
649       break;
650     case PROP_MAX_WIDTH_CHARS:
651       gtk_label_set_max_width_chars (label, g_value_get_int (value));
652       break;
653     default:
654       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
655       break;
656     }
657 }
658
659 static void 
660 gtk_label_get_property (GObject     *object,
661                         guint        prop_id,
662                         GValue      *value,
663                         GParamSpec  *pspec)
664 {
665   GtkLabel *label;
666   
667   label = GTK_LABEL (object);
668   
669   switch (prop_id)
670     {
671     case PROP_LABEL:
672       g_value_set_string (value, label->label);
673       break;
674     case PROP_ATTRIBUTES:
675       g_value_set_boxed (value, label->attrs);
676       break;
677     case PROP_USE_MARKUP:
678       g_value_set_boolean (value, label->use_markup);
679       break;
680     case PROP_USE_UNDERLINE:
681       g_value_set_boolean (value, label->use_underline);
682       break;
683     case PROP_JUSTIFY:
684       g_value_set_enum (value, label->jtype);
685       break;
686     case PROP_WRAP:
687       g_value_set_boolean (value, label->wrap);
688       break;
689     case PROP_SELECTABLE:
690       g_value_set_boolean (value, gtk_label_get_selectable (label));
691       break;
692     case PROP_MNEMONIC_KEYVAL:
693       g_value_set_uint (value, label->mnemonic_keyval);
694       break;
695     case PROP_MNEMONIC_WIDGET:
696       g_value_set_object (value, (GObject*) label->mnemonic_widget);
697       break;
698     case PROP_CURSOR_POSITION:
699       if (label->select_info)
700         {
701           gint offset = g_utf8_pointer_to_offset (label->text,
702                                                   label->text + label->select_info->selection_end);
703           g_value_set_int (value, offset);
704         }
705       else
706         g_value_set_int (value, 0);
707       break;
708     case PROP_SELECTION_BOUND:
709       if (label->select_info)
710         {
711           gint offset = g_utf8_pointer_to_offset (label->text,
712                                                   label->text + label->select_info->selection_anchor);
713           g_value_set_int (value, offset);
714         }
715       else
716         g_value_set_int (value, 0);
717       break;
718     case PROP_ELLIPSIZE:
719       g_value_set_enum (value, label->ellipsize);
720       break;
721     case PROP_WIDTH_CHARS:
722       g_value_set_int (value, gtk_label_get_width_chars (label));
723       break;
724     case PROP_SINGLE_LINE_MODE:
725       g_value_set_boolean (value, gtk_label_get_single_line_mode (label));
726       break;
727     case PROP_ANGLE:
728       g_value_set_double (value, gtk_label_get_angle (label));
729       break;
730     case PROP_MAX_WIDTH_CHARS:
731       g_value_set_int (value, gtk_label_get_max_width_chars (label));
732       break;
733
734     default:
735       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
736       break;
737     }
738 }
739
740 static void
741 gtk_label_init (GtkLabel *label)
742 {
743   GtkLabelPrivate *priv;
744
745   GTK_WIDGET_SET_FLAGS (label, GTK_NO_WINDOW);
746
747   priv = GTK_LABEL_GET_PRIVATE (label);
748   priv->width_chars = -1;
749   priv->angle = 0.0;
750   priv->max_width_chars = -1;
751   label->label = NULL;
752
753   label->jtype = GTK_JUSTIFY_LEFT;
754   label->wrap = FALSE;
755   label->ellipsize = PANGO_ELLIPSIZE_NONE;
756
757   label->use_underline = FALSE;
758   label->use_markup = FALSE;
759   
760   label->mnemonic_keyval = GDK_VoidSymbol;
761   label->layout = NULL;
762   label->text = NULL;
763   label->attrs = NULL;
764
765   label->mnemonic_widget = NULL;
766   label->mnemonic_window = NULL;
767   
768   gtk_label_set_text (label, "");
769 }
770
771 /**
772  * gtk_label_new:
773  * @str: The text of the label
774  *
775  * Creates a new label with the given text inside it. You can
776  * pass %NULL to get an empty label widget.
777  *
778  * Return value: the new #GtkLabel
779  **/
780 GtkWidget*
781 gtk_label_new (const gchar *str)
782 {
783   GtkLabel *label;
784   
785   label = g_object_new (GTK_TYPE_LABEL, NULL);
786
787   if (str && *str)
788     gtk_label_set_text (label, str);
789   
790   return GTK_WIDGET (label);
791 }
792
793 /**
794  * gtk_label_new_with_mnemonic:
795  * @str: The text of the label, with an underscore in front of the
796  *       mnemonic character
797  *
798  * Creates a new #GtkLabel, containing the text in @str.
799  *
800  * If characters in @str are preceded by an underscore, they are
801  * underlined. If you need a literal underscore character in a label, use
802  * '__' (two underscores). The first underlined character represents a 
803  * keyboard accelerator called a mnemonic. The mnemonic key can be used 
804  * to activate another widget, chosen automatically, or explicitly using
805  * gtk_label_set_mnemonic_widget().
806  * 
807  * If gtk_label_set_mnemonic_widget()
808  * is not called, then the first activatable ancestor of the #GtkLabel
809  * will be chosen as the mnemonic widget. For instance, if the
810  * label is inside a button or menu item, the button or menu item will
811  * automatically become the mnemonic widget and be activated by
812  * the mnemonic.
813  *
814  * Return value: the new #GtkLabel
815  **/
816 GtkWidget*
817 gtk_label_new_with_mnemonic (const gchar *str)
818 {
819   GtkLabel *label;
820   
821   label = g_object_new (GTK_TYPE_LABEL, NULL);
822
823   if (str && *str)
824     gtk_label_set_text_with_mnemonic (label, str);
825   
826   return GTK_WIDGET (label);
827 }
828
829 static gboolean
830 gtk_label_mnemonic_activate (GtkWidget *widget,
831                              gboolean   group_cycling)
832 {
833   GtkWidget *parent;
834
835   if (GTK_LABEL (widget)->mnemonic_widget)
836     return gtk_widget_mnemonic_activate (GTK_LABEL (widget)->mnemonic_widget, group_cycling);
837
838   /* Try to find the widget to activate by traversing the
839    * widget's ancestry.
840    */
841   parent = widget->parent;
842
843   if (parent && GTK_IS_NOTEBOOK (parent))
844     return FALSE;
845   
846   while (parent)
847     {
848       if (GTK_WIDGET_CAN_FOCUS (parent) ||
849           (!group_cycling && GTK_WIDGET_GET_CLASS (parent)->activate_signal) ||
850           (parent->parent && GTK_IS_NOTEBOOK (parent->parent)) ||
851           (GTK_IS_MENU_ITEM (parent)))
852         return gtk_widget_mnemonic_activate (parent, group_cycling);
853       parent = parent->parent;
854     }
855
856   /* barf if there was nothing to activate */
857   g_warning ("Couldn't find a target for a mnemonic activation.");
858   gdk_display_beep (gtk_widget_get_display (widget));
859   
860   return FALSE;
861 }
862
863 static void
864 gtk_label_setup_mnemonic (GtkLabel *label,
865                           guint     last_key)
866 {
867   GtkWidget *widget = GTK_WIDGET (label);
868   GtkWidget *toplevel;
869   GtkWidget *mnemonic_menu;
870   
871   mnemonic_menu = g_object_get_data (G_OBJECT (label), "gtk-mnemonic-menu");
872   
873   if (last_key != GDK_VoidSymbol)
874     {
875       if (label->mnemonic_window)
876         {
877           gtk_window_remove_mnemonic  (label->mnemonic_window,
878                                        last_key,
879                                        widget);
880           label->mnemonic_window = NULL;
881         }
882       if (mnemonic_menu)
883         {
884           _gtk_menu_shell_remove_mnemonic (GTK_MENU_SHELL (mnemonic_menu),
885                                            last_key,
886                                            widget);
887           mnemonic_menu = NULL;
888         }
889     }
890   
891   if (label->mnemonic_keyval == GDK_VoidSymbol)
892     goto done;
893
894   toplevel = gtk_widget_get_toplevel (widget);
895   if (GTK_WIDGET_TOPLEVEL (toplevel))
896     {
897       GtkWidget *menu_shell;
898       
899       menu_shell = gtk_widget_get_ancestor (widget,
900                                             GTK_TYPE_MENU_SHELL);
901
902       if (menu_shell)
903         {
904           _gtk_menu_shell_add_mnemonic (GTK_MENU_SHELL (menu_shell),
905                                         label->mnemonic_keyval,
906                                         widget);
907           mnemonic_menu = menu_shell;
908         }
909       
910       if (!(menu_shell && GTK_IS_MENU (menu_shell)))
911         {
912           gtk_window_add_mnemonic (GTK_WINDOW (toplevel),
913                                    label->mnemonic_keyval,
914                                    widget);
915           label->mnemonic_window = GTK_WINDOW (toplevel);
916         }
917     }
918   
919  done:
920   g_object_set_data (G_OBJECT (label), "gtk-mnemonic-menu", mnemonic_menu);
921 }
922
923 static void
924 gtk_label_hierarchy_changed (GtkWidget *widget,
925                              GtkWidget *old_toplevel)
926 {
927   GtkLabel *label = GTK_LABEL (widget);
928
929   gtk_label_setup_mnemonic (label, label->mnemonic_keyval);
930 }
931
932 static void
933 gtk_label_screen_changed (GtkWidget *widget,
934                           GdkScreen *old_screen)
935 {
936   gtk_label_clear_layout (GTK_LABEL (widget));
937 }
938
939 static void
940 label_mnemonic_widget_weak_notify (gpointer      data,
941                                    GObject      *where_the_object_was)
942 {
943   GtkLabel *label = data;
944
945   label->mnemonic_widget = NULL;
946   g_object_notify (G_OBJECT (label), "mnemonic_widget");
947 }
948
949 /**
950  * gtk_label_set_mnemonic_widget:
951  * @label: a #GtkLabel
952  * @widget: the target #GtkWidget 
953  *
954  * If the label has been set so that it has an mnemonic key (using
955  * i.e.  gtk_label_set_markup_with_mnemonic(),
956  * gtk_label_set_text_with_mnemonic(), gtk_label_new_with_mnemonic()
957  * or the "use_underline" property) the label can be associated with a
958  * widget that is the target of the mnemonic. When the label is inside
959  * a widget (like a #GtkButton or a #GtkNotebook tab) it is
960  * automatically associated with the correct widget, but sometimes
961  * (i.e. when the target is a #GtkEntry next to the label) you need to
962  * set it explicitly using this function.
963  *
964  * The target widget will be accelerated by emitting "mnemonic_activate" on it.
965  * The default handler for this signal will activate the widget if there are no
966  * mnemonic collisions and toggle focus between the colliding widgets otherwise.
967  **/
968 void
969 gtk_label_set_mnemonic_widget (GtkLabel  *label,
970                                GtkWidget *widget)
971 {
972   g_return_if_fail (GTK_IS_LABEL (label));
973   if (widget)
974     g_return_if_fail (GTK_IS_WIDGET (widget));
975
976   if (label->mnemonic_widget)
977     {
978       gtk_widget_remove_mnemonic_label (label->mnemonic_widget, GTK_WIDGET (label));
979       g_object_weak_unref (G_OBJECT (label->mnemonic_widget),
980                            label_mnemonic_widget_weak_notify,
981                            label);
982     }
983   label->mnemonic_widget = widget;
984   if (label->mnemonic_widget)
985     {
986       g_object_weak_ref (G_OBJECT (label->mnemonic_widget),
987                          label_mnemonic_widget_weak_notify,
988                          label);
989       gtk_widget_add_mnemonic_label (label->mnemonic_widget, GTK_WIDGET (label));
990     }
991   
992   g_object_notify (G_OBJECT (label), "mnemonic_widget");
993 }
994
995 /**
996  * gtk_label_get_mnemonic_widget:
997  * @label: a #GtkLabel
998  *
999  * Retrieves the target of the mnemonic (keyboard shortcut) of this
1000  * label. See gtk_label_set_mnemonic_widget ().
1001  *
1002  * Return value: the target of the label's mnemonic, or %NULL if none
1003  *               has been set and the default algorithm will be used.
1004  **/
1005 GtkWidget *
1006 gtk_label_get_mnemonic_widget (GtkLabel *label)
1007 {
1008   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
1009
1010   return label->mnemonic_widget;
1011 }
1012
1013 /**
1014  * gtk_label_get_mnemonic_keyval:
1015  * @label: a #GtkLabel
1016  *
1017  * If the label has been set so that it has an mnemonic key this function
1018  * returns the keyval used for the mnemonic accelerator. If there is no
1019  * mnemonic set up it returns #GDK_VoidSymbol.
1020  *
1021  * Returns: GDK keyval usable for accelerators, or #GDK_VoidSymbol
1022  **/
1023 guint
1024 gtk_label_get_mnemonic_keyval (GtkLabel *label)
1025 {
1026   g_return_val_if_fail (GTK_IS_LABEL (label), GDK_VoidSymbol);
1027
1028   return label->mnemonic_keyval;
1029 }
1030
1031 static void
1032 gtk_label_set_text_internal (GtkLabel *label,
1033                              gchar    *str)
1034 {
1035   g_free (label->text);
1036   
1037   label->text = str;
1038
1039   gtk_label_select_region_index (label, 0, 0);
1040 }
1041
1042 static void
1043 gtk_label_set_label_internal (GtkLabel *label,
1044                               gchar    *str)
1045 {
1046   g_free (label->label);
1047   
1048   label->label = str;
1049
1050   g_object_notify (G_OBJECT (label), "label");
1051 }
1052
1053 static void
1054 gtk_label_set_use_markup_internal (GtkLabel *label,
1055                                    gboolean  val)
1056 {
1057   val = val != FALSE;
1058   if (label->use_markup != val)
1059     {
1060       g_object_notify (G_OBJECT (label), "use_markup");
1061       label->use_markup = val;
1062     }
1063 }
1064
1065 static void
1066 gtk_label_set_use_underline_internal (GtkLabel *label,
1067                                       gboolean val)
1068 {
1069   val = val != FALSE;
1070   if (label->use_underline != val)
1071     {
1072       g_object_notify (G_OBJECT (label), "use_underline");
1073       label->use_underline = val;
1074     }
1075 }
1076
1077 static void
1078 gtk_label_set_attributes_internal (GtkLabel      *label,
1079                                    PangoAttrList *attrs)
1080 {
1081   if (attrs)
1082     pango_attr_list_ref (attrs);
1083   
1084   if (label->attrs)
1085     pango_attr_list_unref (label->attrs);
1086
1087   if (!label->use_markup && !label->use_underline)
1088     {
1089       if (attrs)
1090         pango_attr_list_ref (attrs);
1091       if (label->effective_attrs)
1092         pango_attr_list_unref (label->effective_attrs);
1093       label->effective_attrs = attrs;
1094     }
1095
1096   label->attrs = attrs;
1097   g_object_notify (G_OBJECT (label), "attributes");
1098 }
1099
1100
1101 /* Calculates text, attrs and mnemonic_keyval from
1102  * label, use_underline and use_markup
1103  */
1104 static void
1105 gtk_label_recalculate (GtkLabel *label)
1106 {
1107   if (label->use_markup)
1108     set_markup (label, label->label, label->use_underline);
1109   else
1110     {
1111       if (label->use_underline)
1112         gtk_label_set_uline_text_internal (label, label->label);
1113       else
1114         {
1115           gtk_label_set_text_internal (label, g_strdup (label->label));
1116           if (label->attrs)
1117             pango_attr_list_ref (label->attrs);
1118           if (label->effective_attrs)
1119             pango_attr_list_unref (label->effective_attrs);
1120           label->effective_attrs = label->attrs;
1121         }
1122     }
1123
1124   if (!label->use_underline)
1125     {
1126       guint keyval = label->mnemonic_keyval;
1127
1128       label->mnemonic_keyval = GDK_VoidSymbol;
1129       gtk_label_setup_mnemonic (label, keyval);
1130     }
1131
1132   gtk_label_clear_layout (label);  
1133   gtk_widget_queue_resize (GTK_WIDGET (label));
1134 }
1135
1136 /**
1137  * gtk_label_set_text:
1138  * @label: a #GtkLabel
1139  * @str: The text you want to set.
1140  *
1141  * Sets the text within the #GtkLabel widget.  It overwrites any text that
1142  * was there before.  
1143  *
1144  * This will also clear any previously set mnemonic accelerators.
1145  **/
1146 void
1147 gtk_label_set_text (GtkLabel    *label,
1148                     const gchar *str)
1149 {
1150   g_return_if_fail (GTK_IS_LABEL (label));
1151   
1152   g_object_freeze_notify (G_OBJECT (label));
1153
1154   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
1155   gtk_label_set_use_markup_internal (label, FALSE);
1156   gtk_label_set_use_underline_internal (label, FALSE);
1157   
1158   gtk_label_recalculate (label);
1159
1160   g_object_thaw_notify (G_OBJECT (label));
1161 }
1162
1163 /**
1164  * gtk_label_set_attributes:
1165  * @label: a #GtkLabel
1166  * @attrs: a #PangoAttrList
1167  * 
1168  * Sets a #PangoAttrList; the attributes in the list are applied to the
1169  * label text. The attributes set with this function will be ignored
1170  * if the "use_underline" property or the "use_markup" property
1171  * is %TRUE.
1172  **/
1173 void
1174 gtk_label_set_attributes (GtkLabel         *label,
1175                           PangoAttrList    *attrs)
1176 {
1177   g_return_if_fail (GTK_IS_LABEL (label));
1178
1179   gtk_label_set_attributes_internal (label, attrs);
1180   
1181   gtk_label_clear_layout (label);  
1182   gtk_widget_queue_resize (GTK_WIDGET (label));
1183 }
1184
1185 /**
1186  * gtk_label_get_attributes:
1187  * @label: a #GtkLabel
1188  *
1189  * Gets the attribute list that was set on the label using
1190  * gtk_label_set_attributes(), if any. This function does
1191  * not reflect attributes that come from the labels markup
1192  * (see gtk_label_set_markup()). If you want to get the
1193  * effective attributes for the label, use
1194  * pango_layout_get_attribute (gtk_label_get_layout (label)).
1195  *
1196  * Return value: the attribute list, or %NULL if none was set.
1197  **/
1198 PangoAttrList *
1199 gtk_label_get_attributes (GtkLabel *label)
1200 {
1201   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
1202
1203   return label->attrs;
1204 }
1205
1206 /**
1207  * gtk_label_set_label:
1208  * @label: a #GtkLabel
1209  * @str: the new text to set for the label
1210  *
1211  * Sets the text of the label. The label is interpreted as
1212  * including embedded underlines and/or Pango markup depending
1213  * on the values of label->use_underline and label->use_markup.
1214  **/
1215 void
1216 gtk_label_set_label (GtkLabel    *label,
1217                      const gchar *str)
1218 {
1219   guint last_keyval;
1220
1221   g_return_if_fail (GTK_IS_LABEL (label));
1222   g_return_if_fail (str != NULL);
1223
1224   last_keyval = label->mnemonic_keyval;
1225
1226   gtk_label_set_label_internal (label, g_strdup (str));
1227   gtk_label_recalculate (label);
1228   if (last_keyval != label->mnemonic_keyval)
1229     gtk_label_setup_mnemonic (label, last_keyval);
1230 }
1231
1232 /**
1233  * gtk_label_get_label:
1234  * @label: a #GtkLabel
1235  *
1236  * Fetches the text from a label widget including any embedded
1237  * underlines indicating mnemonics and Pango markup. (See
1238  * gtk_label_get_text ()).
1239  *
1240  * Return value: the text of the label widget. This string is
1241  *   owned by the widget and must not be modified or freed.
1242  **/
1243 G_CONST_RETURN gchar *
1244 gtk_label_get_label (GtkLabel *label)
1245 {
1246   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
1247
1248   return label->label;
1249 }
1250
1251 static void
1252 set_markup (GtkLabel    *label,
1253             const gchar *str,
1254             gboolean     with_uline)
1255 {
1256   gchar *text = NULL;
1257   GError *error = NULL;
1258   PangoAttrList *attrs = NULL;
1259   gunichar accel_char = 0;
1260
1261   if (!pango_parse_markup (str,
1262                            -1,
1263                            with_uline ? '_' : 0,
1264                            &attrs,
1265                            &text,
1266                            with_uline ? &accel_char : NULL,
1267                            &error))
1268     {
1269       g_warning ("Failed to set label from markup due to error parsing markup: %s",
1270                  error->message);
1271       g_error_free (error);
1272       return;
1273     }
1274
1275   if (text)
1276     gtk_label_set_text_internal (label, text);
1277
1278   if (attrs)
1279     {
1280       if (label->effective_attrs)
1281         pango_attr_list_unref (label->effective_attrs);
1282       label->effective_attrs = attrs;
1283     }
1284
1285   if (accel_char != 0)
1286     label->mnemonic_keyval = gdk_keyval_to_lower (gdk_unicode_to_keyval (accel_char));
1287   else
1288     label->mnemonic_keyval = GDK_VoidSymbol;
1289 }
1290
1291 /**
1292  * gtk_label_set_markup:
1293  * @label: a #GtkLabel
1294  * @str: a markup string (see <link linkend="PangoMarkupFormat">Pango markup format</link>)
1295  * 
1296  * Parses @str which is marked up with the <link
1297  * linkend="PangoMarkupFormat">Pango text markup language</link>, setting the
1298  * label's text and attribute list based on the parse results.  If the @str is
1299  * external data, you may need to escape it with g_markup_escape_text() or
1300  * g_markup_printf_escaped()<!-- -->:
1301  * <informalexample><programlisting>
1302  * char *markup;
1303  * <!-- -->
1304  * markup = g_markup_printf_escaped ("&lt;span style=\"italic\"&gt;%s&lt;/span&gt;", str);
1305  * gtk_label_set_markup (GTK_LABEL (label), markup);
1306  * g_free (markup);
1307  * </programlisting></informalexample>
1308  **/
1309 void
1310 gtk_label_set_markup (GtkLabel    *label,
1311                       const gchar *str)
1312 {  
1313   g_return_if_fail (GTK_IS_LABEL (label));
1314
1315   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
1316   gtk_label_set_use_markup_internal (label, TRUE);
1317   gtk_label_set_use_underline_internal (label, FALSE);
1318   
1319   gtk_label_recalculate (label);
1320 }
1321
1322 /**
1323  * gtk_label_set_markup_with_mnemonic:
1324  * @label: a #GtkLabel
1325  * @str: a markup string (see <link linkend="PangoMarkupFormat">Pango markup format</link>)
1326  * 
1327  * Parses @str which is marked up with the <link linkend="PangoMarkupFormat">Pango text markup language</link>,
1328  * setting the label's text and attribute list based on the parse results.
1329  * If characters in @str are preceded by an underscore, they are underlined
1330  * indicating that they represent a keyboard accelerator called a mnemonic.
1331  *
1332  * The mnemonic key can be used to activate another widget, chosen automatically,
1333  * or explicitly using gtk_label_set_mnemonic_widget().
1334  **/
1335 void
1336 gtk_label_set_markup_with_mnemonic (GtkLabel    *label,
1337                                     const gchar *str)
1338 {
1339   guint last_keyval;
1340   g_return_if_fail (GTK_IS_LABEL (label));
1341
1342   last_keyval = label->mnemonic_keyval;
1343   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
1344   gtk_label_set_use_markup_internal (label, TRUE);
1345   gtk_label_set_use_underline_internal (label, TRUE);
1346   
1347   gtk_label_recalculate (label);
1348   gtk_label_setup_mnemonic (label, last_keyval);
1349 }
1350
1351 /**
1352  * gtk_label_get_text:
1353  * @label: a #GtkLabel
1354  * 
1355  * Fetches the text from a label widget, as displayed on the
1356  * screen. This does not include any embedded underlines
1357  * indicating mnemonics or Pango markup. (See gtk_label_get_label())
1358  * 
1359  * Return value: the text in the label widget. This is the internal
1360  *   string used by the label, and must not be modified.
1361  **/
1362 G_CONST_RETURN gchar *
1363 gtk_label_get_text (GtkLabel *label)
1364 {
1365   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
1366
1367   return label->text;
1368 }
1369
1370 static PangoAttrList *
1371 gtk_label_pattern_to_attrs (GtkLabel      *label,
1372                             const gchar   *pattern)
1373 {
1374   const char *start;
1375   const char *p = label->text;
1376   const char *q = pattern;
1377   PangoAttrList *attrs;
1378
1379   attrs = pango_attr_list_new ();
1380
1381   while (1)
1382     {
1383       while (*p && *q && *q != '_')
1384         {
1385           p = g_utf8_next_char (p);
1386           q++;
1387         }
1388       start = p;
1389       while (*p && *q && *q == '_')
1390         {
1391           p = g_utf8_next_char (p);
1392           q++;
1393         }
1394       
1395       if (p > start)
1396         {
1397           PangoAttribute *attr = pango_attr_underline_new (PANGO_UNDERLINE_LOW);
1398           attr->start_index = start - label->text;
1399           attr->end_index = p - label->text;
1400           
1401           pango_attr_list_insert (attrs, attr);
1402         }
1403       else
1404         break;
1405     }
1406
1407   return attrs;
1408 }
1409
1410 static void
1411 gtk_label_set_pattern_internal (GtkLabel    *label,
1412                                 const gchar *pattern)
1413 {
1414   PangoAttrList *attrs;
1415   g_return_if_fail (GTK_IS_LABEL (label));
1416   
1417   if (pattern)
1418     attrs = gtk_label_pattern_to_attrs (label, pattern);
1419   else
1420     attrs = NULL;
1421
1422   if (label->effective_attrs)
1423     pango_attr_list_unref (label->effective_attrs);
1424   label->effective_attrs = attrs;
1425 }
1426
1427 void
1428 gtk_label_set_pattern (GtkLabel    *label,
1429                        const gchar *pattern)
1430 {
1431   g_return_if_fail (GTK_IS_LABEL (label));
1432   
1433   gtk_label_set_pattern_internal (label, pattern);
1434
1435   gtk_label_clear_layout (label);  
1436   gtk_widget_queue_resize (GTK_WIDGET (label));
1437 }
1438
1439
1440 /**
1441  * gtk_label_set_justify:
1442  * @label: a #GtkLabel
1443  * @jtype: a #GtkJustification
1444  *
1445  * Sets the alignment of the lines in the text of the label relative to
1446  * each other.  %GTK_JUSTIFY_LEFT is the default value when the
1447  * widget is first created with gtk_label_new(). If you instead want
1448  * to set the alignment of the label as a whole, use
1449  * gtk_misc_set_alignment() instead. gtk_label_set_justify() has no
1450  * effect on labels containing only a single line.
1451  **/
1452 void
1453 gtk_label_set_justify (GtkLabel        *label,
1454                        GtkJustification jtype)
1455 {
1456   g_return_if_fail (GTK_IS_LABEL (label));
1457   g_return_if_fail (jtype >= GTK_JUSTIFY_LEFT && jtype <= GTK_JUSTIFY_FILL);
1458   
1459   if ((GtkJustification) label->jtype != jtype)
1460     {
1461       label->jtype = jtype;
1462
1463       /* No real need to be this drastic, but easier than duplicating the code */
1464       gtk_label_clear_layout (label);
1465       
1466       g_object_notify (G_OBJECT (label), "justify");
1467       gtk_widget_queue_resize (GTK_WIDGET (label));
1468     }
1469 }
1470
1471 /**
1472  * gtk_label_get_justify:
1473  * @label: a #GtkLabel
1474  *
1475  * Returns the justification of the label. See gtk_label_set_justify ().
1476  *
1477  * Return value: #GtkJustification
1478  **/
1479 GtkJustification
1480 gtk_label_get_justify (GtkLabel *label)
1481 {
1482   g_return_val_if_fail (GTK_IS_LABEL (label), 0);
1483
1484   return label->jtype;
1485 }
1486
1487 /**
1488  * gtk_label_set_ellipsize:
1489  * @label: a #GtkLabel
1490  * @mode: a #PangoEllipsizeMode
1491  *
1492  * Sets the mode used to ellipsize (add an ellipsis: "...") to the text if there
1493  * is not enough space to render the entire string.
1494  *
1495  * Since: 2.6
1496  **/
1497 void
1498 gtk_label_set_ellipsize (GtkLabel          *label,
1499                          PangoEllipsizeMode mode)
1500 {
1501   g_return_if_fail (GTK_IS_LABEL (label));
1502   g_return_if_fail (mode >= PANGO_ELLIPSIZE_NONE && mode <= PANGO_ELLIPSIZE_END);
1503   
1504   if ((PangoEllipsizeMode) label->ellipsize != mode)
1505     {
1506       label->ellipsize = mode;
1507
1508       /* No real need to be this drastic, but easier than duplicating the code */
1509       gtk_label_clear_layout (label);
1510       
1511       g_object_notify (G_OBJECT (label), "ellipsize");
1512       gtk_widget_queue_resize (GTK_WIDGET (label));
1513     }
1514 }
1515
1516 /**
1517  * gtk_label_get_ellipsize:
1518  * @label: a #GtkLabel
1519  *
1520  * Returns the ellipsizing position of the label. See gtk_label_set_ellipsize().
1521  *
1522  * Return value: #PangoEllipsizeMode
1523  *
1524  * Since: 2.6
1525  **/
1526 PangoEllipsizeMode
1527 gtk_label_get_ellipsize (GtkLabel *label)
1528 {
1529   g_return_val_if_fail (GTK_IS_LABEL (label), PANGO_ELLIPSIZE_NONE);
1530
1531   return label->ellipsize;
1532 }
1533
1534 /**
1535  * gtk_label_set_width_chars:
1536  * @label: a #GtkLabel
1537  * @n_chars: the new desired width, in characters.
1538  * 
1539  * Sets the desired width in characters of @label to @n_chars.
1540  * 
1541  * Since: 2.6
1542  **/
1543 void
1544 gtk_label_set_width_chars (GtkLabel *label,
1545                            gint      n_chars)
1546 {
1547   GtkLabelPrivate *priv;
1548
1549   g_return_if_fail (GTK_IS_LABEL (label));
1550
1551   priv = GTK_LABEL_GET_PRIVATE (label);
1552
1553   if (priv->width_chars != n_chars)
1554     {
1555       priv->width_chars = n_chars;
1556       g_object_notify (G_OBJECT (label), "width-chars");
1557       gtk_widget_queue_resize (GTK_WIDGET (label));
1558     }
1559 }
1560
1561 /**
1562  * gtk_label_get_width_chars:
1563  * @label: a #GtkLabel
1564  * 
1565  * Retrieves the desired width of @label, in characters. See
1566  * gtk_label_set_width_chars().
1567  * 
1568  * Return value: the width of the label in characters.
1569  * 
1570  * Since: 2.6
1571  **/
1572 gint
1573 gtk_label_get_width_chars (GtkLabel *label)
1574 {
1575   g_return_val_if_fail (GTK_IS_LABEL (label), -1);
1576
1577   return GTK_LABEL_GET_PRIVATE (label)->width_chars;
1578 }
1579
1580 /**
1581  * gtk_label_set_max_width_chars:
1582  * @label: a #GtkLabel
1583  * @n_chars: the new desired maximum width, in characters.
1584  * 
1585  * Sets the desired maximum width in characters of @label to @n_chars.
1586  * 
1587  * Since: 2.6
1588  **/
1589 void
1590 gtk_label_set_max_width_chars (GtkLabel *label,
1591                                gint      n_chars)
1592 {
1593   GtkLabelPrivate *priv;
1594
1595   g_return_if_fail (GTK_IS_LABEL (label));
1596
1597   priv = GTK_LABEL_GET_PRIVATE (label);
1598
1599   if (priv->max_width_chars != n_chars)
1600     {
1601       priv->max_width_chars = n_chars;
1602
1603       g_object_notify (G_OBJECT (label), "max-width-chars");
1604       gtk_widget_queue_resize (GTK_WIDGET (label));
1605     }
1606 }
1607
1608 /**
1609  * gtk_label_get_max_width_chars:
1610  * @label: a #GtkLabel
1611  * 
1612  * Retrieves the desired maximum width of @label, in characters. See
1613  * gtk_label_set_width_chars().
1614  * 
1615  * Return value: the maximum width of the label in characters.
1616  * 
1617  * Since: 2.6
1618  **/
1619 gint
1620 gtk_label_get_max_width_chars (GtkLabel *label)
1621 {
1622   g_return_val_if_fail (GTK_IS_LABEL (label), -1);
1623
1624   return GTK_LABEL_GET_PRIVATE (label)->max_width_chars;
1625 }
1626
1627 /**
1628  * gtk_label_set_line_wrap:
1629  * @label: a #GtkLabel
1630  * @wrap: the setting
1631  *
1632  * Toggles line wrapping within the #GtkLabel widget.  %TRUE makes it break
1633  * lines if text exceeds the widget's size.  %FALSE lets the text get cut off
1634  * by the edge of the widget if it exceeds the widget size.
1635  **/
1636 void
1637 gtk_label_set_line_wrap (GtkLabel *label,
1638                          gboolean  wrap)
1639 {
1640   g_return_if_fail (GTK_IS_LABEL (label));
1641   
1642   wrap = wrap != FALSE;
1643   
1644   if (label->wrap != wrap)
1645     {
1646       label->wrap = wrap;
1647       g_object_notify (G_OBJECT (label), "wrap");
1648       
1649       gtk_widget_queue_resize (GTK_WIDGET (label));
1650     }
1651 }
1652
1653 /**
1654  * gtk_label_get_line_wrap:
1655  * @label: a #GtkLabel
1656  *
1657  * Returns whether lines in the label are automatically wrapped. See gtk_label_set_line_wrap ().
1658  *
1659  * Return value: %TRUE if the lines of the label are automatically wrapped.
1660  */
1661 gboolean
1662 gtk_label_get_line_wrap (GtkLabel *label)
1663 {
1664   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
1665
1666   return label->wrap;
1667 }
1668
1669 void
1670 gtk_label_get (GtkLabel *label,
1671                gchar   **str)
1672 {
1673   g_return_if_fail (GTK_IS_LABEL (label));
1674   g_return_if_fail (str != NULL);
1675   
1676   *str = label->text;
1677 }
1678
1679 static void
1680 gtk_label_destroy (GtkObject *object)
1681 {
1682   GtkLabel *label = GTK_LABEL (object);
1683
1684   gtk_label_set_mnemonic_widget (label, NULL);
1685
1686   GTK_OBJECT_CLASS (parent_class)->destroy (object);
1687 }
1688
1689 static void
1690 gtk_label_finalize (GObject *object)
1691 {
1692   GtkLabel *label;
1693   
1694   g_return_if_fail (GTK_IS_LABEL (object));
1695   
1696   label = GTK_LABEL (object);
1697   
1698   g_free (label->label);
1699   g_free (label->text);
1700
1701   if (label->layout)
1702     g_object_unref (label->layout);
1703
1704   if (label->attrs)
1705     pango_attr_list_unref (label->attrs);
1706
1707   if (label->effective_attrs)
1708     pango_attr_list_unref (label->effective_attrs);
1709
1710   g_free (label->select_info);
1711
1712   G_OBJECT_CLASS (parent_class)->finalize (object);
1713 }
1714
1715 static void
1716 gtk_label_clear_layout (GtkLabel *label)
1717 {
1718   if (label->layout)
1719     {
1720       g_object_unref (label->layout);
1721       label->layout = NULL;
1722     }
1723 }
1724
1725 typedef struct _LabelWrapWidth LabelWrapWidth;
1726 struct _LabelWrapWidth
1727 {
1728   gint width;
1729   PangoFontDescription *font_desc;
1730 };
1731
1732 static void
1733 label_wrap_width_free (gpointer data)
1734 {
1735   LabelWrapWidth *wrap_width = data;
1736   pango_font_description_free (wrap_width->font_desc);
1737   g_free (wrap_width);
1738 }
1739
1740 static gint
1741 get_label_wrap_width (GtkLabel *label)
1742 {
1743   PangoLayout *layout;
1744   GtkStyle *style = GTK_WIDGET (label)->style;
1745
1746   LabelWrapWidth *wrap_width = g_object_get_data (G_OBJECT (style), "gtk-label-wrap-width");
1747   if (!wrap_width)
1748     {
1749       wrap_width = g_new0 (LabelWrapWidth, 1);
1750       g_object_set_data_full (G_OBJECT (style), "gtk-label-wrap-width",
1751                               wrap_width, label_wrap_width_free);
1752     }
1753
1754   if (wrap_width->font_desc && pango_font_description_equal (wrap_width->font_desc, style->font_desc))
1755     return wrap_width->width;
1756
1757   if (wrap_width->font_desc)
1758     pango_font_description_free (wrap_width->font_desc);
1759
1760   wrap_width->font_desc = pango_font_description_copy (style->font_desc);
1761
1762   layout = gtk_widget_create_pango_layout (GTK_WIDGET (label), 
1763                                            "This long string gives a good enough length for any line to have.");
1764   pango_layout_get_size (layout, &wrap_width->width, NULL);
1765   g_object_unref (layout);
1766
1767   return wrap_width->width;
1768 }
1769
1770 static void
1771 gtk_label_ensure_layout (GtkLabel *label)
1772 {
1773   GtkWidget *widget;
1774   PangoRectangle logical_rect;
1775   gint rwidth, rheight;
1776   gboolean rtl;
1777
1778   widget = GTK_WIDGET (label);
1779
1780   rtl = gtk_widget_get_direction(widget) == GTK_TEXT_DIR_RTL;
1781   rwidth = label->misc.xpad * 2;
1782   rheight = label->misc.ypad * 2;
1783
1784   if (!label->layout)
1785     {
1786       PangoAlignment align = PANGO_ALIGN_LEFT; /* Quiet gcc */
1787       GtkLabelPrivate *priv = GTK_LABEL_GET_PRIVATE (label);
1788
1789       if (priv->angle != 0.0 && !label->wrap && !label->ellipsize && !label->select_info)
1790         {
1791           /* We rotate the standard singleton PangoContext for the widget,
1792            * depending on the fact that it's meant pretty much exclusively
1793            * for our use.
1794            */
1795           PangoMatrix matrix = PANGO_MATRIX_INIT;
1796           
1797           pango_matrix_rotate (&matrix, priv->angle);
1798
1799           pango_context_set_matrix (gtk_widget_get_pango_context (widget), &matrix);
1800           
1801           priv->have_transform = TRUE;
1802         }
1803       else 
1804         {
1805           if (priv->have_transform)
1806             pango_context_set_matrix (gtk_widget_get_pango_context (widget), NULL);
1807
1808           priv->have_transform = FALSE;
1809         }
1810
1811       label->layout = gtk_widget_create_pango_layout (widget, label->text);
1812
1813       if (label->effective_attrs)
1814         pango_layout_set_attributes (label->layout, label->effective_attrs);
1815       
1816       switch (label->jtype)
1817         {
1818         case GTK_JUSTIFY_LEFT:
1819           align = rtl ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
1820           break;
1821         case GTK_JUSTIFY_RIGHT:
1822           align = rtl ? PANGO_ALIGN_LEFT : PANGO_ALIGN_RIGHT;
1823           break;
1824         case GTK_JUSTIFY_CENTER:
1825           align = PANGO_ALIGN_CENTER;
1826           break;
1827         case GTK_JUSTIFY_FILL:
1828           /* FIXME: This just doesn't work to do this */
1829           align = rtl ? PANGO_ALIGN_RIGHT : PANGO_ALIGN_LEFT;
1830           pango_layout_set_justify (label->layout, TRUE);
1831           break;
1832         default:
1833           g_assert_not_reached();
1834         }
1835
1836       pango_layout_set_alignment (label->layout, align);
1837       pango_layout_set_ellipsize (label->layout, label->ellipsize);
1838       pango_layout_set_single_paragraph_mode (label->layout, priv->single_line_mode);
1839
1840       if (label->ellipsize)
1841         pango_layout_set_width (label->layout, 
1842                                 widget->allocation.width * PANGO_SCALE);
1843       else if (label->wrap)
1844         {
1845           GtkWidgetAuxInfo *aux_info;
1846           gint longest_paragraph;
1847           gint width, height;
1848           
1849           aux_info = _gtk_widget_get_aux_info (widget, FALSE);
1850           if (aux_info && aux_info->width > 0)
1851             pango_layout_set_width (label->layout, aux_info->width * PANGO_SCALE);
1852           else
1853             {
1854               GdkScreen *screen = gtk_widget_get_screen (GTK_WIDGET (label));
1855               gint wrap_width;
1856               
1857               pango_layout_set_width (label->layout, -1);
1858               pango_layout_get_extents (label->layout, NULL, &logical_rect);
1859
1860               width = logical_rect.width;
1861               
1862               /* Try to guess a reasonable maximum width */
1863               longest_paragraph = width;
1864
1865               wrap_width = get_label_wrap_width (label);
1866               width = MIN (width, wrap_width);
1867               width = MIN (width,
1868                            PANGO_SCALE * (gdk_screen_get_width (screen) + 1) / 2);
1869               
1870               pango_layout_set_width (label->layout, width);
1871               pango_layout_get_extents (label->layout, NULL, &logical_rect);
1872               width = logical_rect.width;
1873               height = logical_rect.height;
1874               
1875               /* Unfortunately, the above may leave us with a very unbalanced looking paragraph,
1876                * so we try short search for a narrower width that leaves us with the same height
1877                */
1878               if (longest_paragraph > 0)
1879                 {
1880                   gint nlines, perfect_width;
1881                   
1882                   nlines = pango_layout_get_line_count (label->layout);
1883                   perfect_width = (longest_paragraph + nlines - 1) / nlines;
1884                   
1885                   if (perfect_width < width)
1886                     {
1887                       pango_layout_set_width (label->layout, perfect_width);
1888                       pango_layout_get_extents (label->layout, NULL, &logical_rect);
1889                       
1890                       if (logical_rect.height <= height)
1891                         width = logical_rect.width;
1892                       else
1893                         {
1894                           gint mid_width = (perfect_width + width) / 2;
1895                           
1896                           if (mid_width > perfect_width)
1897                             {
1898                               pango_layout_set_width (label->layout, mid_width);
1899                               pango_layout_get_extents (label->layout, NULL, &logical_rect);
1900                               
1901                               if (logical_rect.height <= height)
1902                                 width = logical_rect.width;
1903                             }
1904                         }
1905                     }
1906                 }
1907               pango_layout_set_width (label->layout, width);
1908             }
1909         }
1910       else /* !label->wrap */
1911         pango_layout_set_width (label->layout, -1);
1912     }
1913 }
1914
1915 /* Gets the bounds of a layout in device coordinates. Note cut-and-paste
1916  * between here and gdkpango.c */
1917 static void
1918 get_rotated_layout_bounds (PangoLayout  *layout,
1919                            GdkRectangle *rect)
1920 {
1921   PangoContext *context = pango_layout_get_context (layout);
1922   const PangoMatrix *matrix = pango_context_get_matrix (context);
1923   gdouble x_min = 0, x_max = 0, y_min = 0, y_max = 0; /* quiet gcc */
1924   PangoRectangle logical_rect;
1925   gint i, j;
1926
1927   pango_layout_get_extents (layout, NULL, &logical_rect);
1928   
1929   for (i = 0; i < 2; i++)
1930     {
1931       gdouble x = (i == 0) ? logical_rect.x : logical_rect.x + logical_rect.width;
1932       for (j = 0; j < 2; j++)
1933         {
1934           gdouble y = (j == 0) ? logical_rect.y : logical_rect.y + logical_rect.height;
1935           
1936           gdouble xt = (x * matrix->xx + y * matrix->xy) / PANGO_SCALE + matrix->x0;
1937           gdouble yt = (x * matrix->yx + y * matrix->yy) / PANGO_SCALE + matrix->y0;
1938           
1939           if (i == 0 && j == 0)
1940             {
1941               x_min = x_max = xt;
1942               y_min = y_max = yt;
1943             }
1944           else
1945             {
1946               if (xt < x_min)
1947                 x_min = xt;
1948               if (yt < y_min)
1949                 y_min = yt;
1950               if (xt > x_max)
1951                 x_max = xt;
1952               if (yt > y_max)
1953                 y_max = yt;
1954             }
1955         }
1956     }
1957   
1958   rect->x = floor (x_min);
1959   rect->width = ceil (x_max) - rect->x;
1960   rect->y = floor (y_min);
1961   rect->height = floor (y_max) - rect->y;
1962 }
1963
1964 static void
1965 gtk_label_size_request (GtkWidget      *widget,
1966                         GtkRequisition *requisition)
1967 {
1968   GtkLabel *label;
1969   GtkLabelPrivate *priv;
1970   gint width, height;
1971   PangoRectangle logical_rect;
1972   GtkWidgetAuxInfo *aux_info;
1973   
1974   g_return_if_fail (GTK_IS_LABEL (widget));
1975   g_return_if_fail (requisition != NULL);
1976   
1977   label = GTK_LABEL (widget);
1978   priv = GTK_LABEL_GET_PRIVATE (widget);
1979
1980   /*  
1981    * If word wrapping is on, then the height requisition can depend
1982    * on:
1983    *
1984    *   - Any width set on the widget via gtk_widget_set_usize().
1985    *   - The padding of the widget (xpad, set by gtk_misc_set_padding)
1986    *
1987    * Instead of trying to detect changes to these quantities, if we
1988    * are wrapping, we just rewrap for each size request. Since
1989    * size requisitions are cached by the GTK+ core, this is not
1990    * expensive.
1991    */
1992
1993   if (label->wrap)
1994     gtk_label_clear_layout (label);
1995
1996   gtk_label_ensure_layout (label);
1997
1998   width = label->misc.xpad * 2;
1999   height = label->misc.ypad * 2;
2000
2001   aux_info = _gtk_widget_get_aux_info (widget, FALSE);
2002
2003   if (priv->have_transform)
2004     {
2005       GdkRectangle rect;
2006
2007       get_rotated_layout_bounds (label->layout, &rect);
2008       
2009       requisition->width = width + rect.width;
2010       requisition->height = height + rect.height;
2011
2012       return;
2013     }
2014   else
2015     pango_layout_get_extents (label->layout, NULL, &logical_rect);
2016
2017   if ((label->wrap || label->ellipsize || 
2018        priv->width_chars > 0 || priv->max_width_chars > 0) && 
2019       aux_info && aux_info->width > 0)
2020     width += aux_info->width;
2021   else if (label->ellipsize || priv->width_chars > 0 || priv->max_width_chars > 0)
2022     {
2023       PangoContext *context;
2024       PangoFontMetrics *metrics;
2025       gint char_width, digit_width, char_pixels, w;
2026
2027       context = pango_layout_get_context (label->layout);
2028       metrics = pango_context_get_metrics (context, widget->style->font_desc, 
2029                                            pango_context_get_language (context));
2030
2031       char_width = pango_font_metrics_get_approximate_char_width (metrics);
2032       digit_width = pango_font_metrics_get_approximate_digit_width (metrics);
2033       char_pixels = MAX (char_width, digit_width);
2034       pango_font_metrics_unref (metrics);
2035
2036       if (priv->width_chars < 0)
2037         {
2038           PangoRectangle rect;
2039
2040           pango_layout_set_width (label->layout, -1);
2041           pango_layout_get_extents (label->layout, NULL, &rect);
2042
2043           w = char_pixels * MAX (priv->max_width_chars, 3);
2044           w = MIN (rect.width, w);
2045         }
2046       else
2047         {
2048           /* enforce minimum width for ellipsized labels at ~3 chars */
2049           w = char_pixels * MAX (priv->width_chars, 3);
2050         }
2051
2052       width += PANGO_PIXELS (w);
2053     }
2054   else
2055     width += PANGO_PIXELS (logical_rect.width);
2056
2057   if (priv->single_line_mode)
2058     {
2059       PangoContext *context;
2060       PangoFontMetrics *metrics;
2061       gint ascent, descent;
2062
2063       context = pango_layout_get_context (label->layout);
2064       metrics = pango_context_get_metrics (context, widget->style->font_desc,
2065                                            pango_context_get_language (context));
2066
2067       ascent = pango_font_metrics_get_ascent (metrics);
2068       descent = pango_font_metrics_get_descent (metrics);
2069       pango_font_metrics_unref (metrics);
2070     
2071       height += PANGO_PIXELS (ascent + descent);
2072     }
2073   else
2074     height += PANGO_PIXELS (logical_rect.height);
2075
2076   requisition->width = width;
2077   requisition->height = height;
2078 }
2079
2080 static void
2081 gtk_label_size_allocate (GtkWidget     *widget,
2082                          GtkAllocation *allocation)
2083 {
2084   GtkLabel *label;
2085   GtkLabelPrivate *priv;
2086
2087   label = GTK_LABEL (widget);
2088   priv = GTK_LABEL_GET_PRIVATE (widget);
2089
2090   (* GTK_WIDGET_CLASS (parent_class)->size_allocate) (widget, allocation);
2091
2092   if (label->ellipsize)
2093     {
2094       if (label->layout)
2095         pango_layout_set_width (label->layout, allocation->width * PANGO_SCALE);
2096     }
2097
2098   if (label->select_info && label->select_info->window)
2099     {
2100       gdk_window_move_resize (label->select_info->window,
2101                               allocation->x,
2102                               allocation->y,
2103                               allocation->width,
2104                               allocation->height);
2105     }
2106 }
2107
2108 static void
2109 gtk_label_state_changed (GtkWidget   *widget,
2110                          GtkStateType prev_state)
2111 {
2112   GtkLabel *label;
2113   
2114   label = GTK_LABEL (widget);
2115
2116   if (label->select_info)
2117     gtk_label_select_region (label, 0, 0);
2118
2119   if (GTK_WIDGET_CLASS (parent_class)->state_changed)
2120     GTK_WIDGET_CLASS (parent_class)->state_changed (widget, prev_state);
2121 }
2122
2123 static void 
2124 gtk_label_style_set (GtkWidget *widget,
2125                      GtkStyle  *previous_style)
2126 {
2127   GtkLabel *label;
2128   
2129   g_return_if_fail (GTK_IS_LABEL (widget));
2130   
2131   label = GTK_LABEL (widget);
2132
2133   /* We have to clear the layout, fonts etc. may have changed */
2134   gtk_label_clear_layout (label);
2135 }
2136
2137 static void 
2138 gtk_label_direction_changed (GtkWidget        *widget,
2139                              GtkTextDirection previous_dir)
2140 {
2141   GtkLabel *label = GTK_LABEL (widget);
2142
2143   if (label->layout)
2144     pango_layout_context_changed (label->layout);
2145
2146   GTK_WIDGET_CLASS (parent_class)->direction_changed (widget, previous_dir);
2147 }
2148
2149 static void
2150 get_layout_location (GtkLabel  *label,
2151                      gint      *xp,
2152                      gint      *yp)
2153 {
2154   GtkMisc *misc;
2155   GtkWidget *widget;
2156   gfloat xalign;
2157   gint req_width, x, y;
2158   
2159   misc = GTK_MISC (label);
2160   widget = GTK_WIDGET (label);
2161   
2162   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2163     xalign = misc->xalign;
2164   else
2165     xalign = 1.0 - misc->xalign;
2166
2167   if (label->ellipsize)
2168     {
2169       PangoRectangle ink_rect;
2170
2171       pango_layout_get_extents (label->layout, &ink_rect, NULL);
2172
2173       req_width = PANGO_PIXELS (ink_rect.width);
2174     }
2175   else
2176     req_width = widget->requisition.width;
2177
2178   x = floor (widget->allocation.x + (gint)misc->xpad +
2179               xalign * (widget->allocation.width - req_width)
2180               + 0.5);
2181
2182   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2183     x = MAX (x, widget->allocation.x + misc->xpad);
2184   else
2185     x = MIN (x,
2186              widget->allocation.x + widget->allocation.width -
2187              req_width - misc->xpad);
2188
2189   y = floor (widget->allocation.y + (gint)misc->ypad 
2190              + MAX (((widget->allocation.height - widget->requisition.height) * misc->yalign)
2191                     + 0.5, 0));
2192
2193   if (xp)
2194     *xp = x;
2195
2196   if (yp)
2197     *yp = y;
2198 }
2199
2200 static void
2201 draw_insertion_cursor (GtkLabel      *label,
2202                        GdkRectangle  *cursor_location,
2203                        gboolean       is_primary,
2204                        PangoDirection direction,
2205                        gboolean       draw_arrow)
2206 {
2207   GtkWidget *widget = GTK_WIDGET (label);
2208   GtkTextDirection text_dir;
2209
2210   if (direction == PANGO_DIRECTION_LTR)
2211     text_dir = GTK_TEXT_DIR_LTR;
2212   else
2213     text_dir = GTK_TEXT_DIR_RTL;
2214
2215   gtk_draw_insertion_cursor (widget, widget->window, &(widget->allocation),
2216                              cursor_location,
2217                              is_primary, text_dir, draw_arrow);
2218 }
2219
2220 static PangoDirection
2221 get_cursor_direction (GtkLabel *label)
2222 {
2223   GSList *l;
2224
2225   g_assert (label->select_info);
2226
2227   gtk_label_ensure_layout (label);
2228
2229   for (l = pango_layout_get_lines (label->layout); l; l = l->next)
2230     {
2231       PangoLayoutLine *line = l->data;
2232
2233       /* If label->select_info->selection_end is at the very end of
2234        * the line, we don't know if the cursor is on this line or
2235        * the next without looking ahead at the next line. (End
2236        * of paragraph is different from line break.) But it's
2237        * definitely in this paragraph, which is good enough
2238        * to figure out the resolved direction.
2239        */
2240        if (line->start_index + line->length >= label->select_info->selection_end)
2241         return line->resolved_dir;
2242     }
2243
2244   return PANGO_DIRECTION_LTR;
2245 }
2246
2247 static void
2248 gtk_label_draw_cursor (GtkLabel  *label, gint xoffset, gint yoffset)
2249 {
2250   if (label->select_info == NULL)
2251     return;
2252   
2253   if (GTK_WIDGET_DRAWABLE (label))
2254     {
2255       GtkWidget *widget = GTK_WIDGET (label);
2256
2257       PangoDirection keymap_direction;
2258       PangoDirection cursor_direction;
2259       PangoRectangle strong_pos, weak_pos;
2260       gboolean split_cursor;
2261       PangoRectangle *cursor1 = NULL;
2262       PangoRectangle *cursor2 = NULL;
2263       GdkRectangle cursor_location;
2264       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
2265       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
2266
2267       keymap_direction = gdk_keymap_get_direction (gdk_keymap_get_for_display (gtk_widget_get_display (widget)));
2268       cursor_direction = get_cursor_direction (label);
2269
2270       gtk_label_ensure_layout (label);
2271       
2272       pango_layout_get_cursor_pos (label->layout, label->select_info->selection_end,
2273                                    &strong_pos, &weak_pos);
2274
2275       g_object_get (gtk_widget_get_settings (widget),
2276                     "gtk-split-cursor", &split_cursor,
2277                     NULL);
2278
2279       dir1 = cursor_direction;
2280       
2281       if (split_cursor)
2282         {
2283           cursor1 = &strong_pos;
2284
2285           if (strong_pos.x != weak_pos.x ||
2286               strong_pos.y != weak_pos.y)
2287             {
2288               dir2 = (cursor_direction == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
2289               cursor2 = &weak_pos;
2290             }
2291         }
2292       else
2293         {
2294           if (keymap_direction == cursor_direction)
2295             cursor1 = &strong_pos;
2296           else
2297             cursor1 = &weak_pos;
2298         }
2299       
2300       cursor_location.x = xoffset + PANGO_PIXELS (cursor1->x);
2301       cursor_location.y = yoffset + PANGO_PIXELS (cursor1->y);
2302       cursor_location.width = 0;
2303       cursor_location.height = PANGO_PIXELS (cursor1->height);
2304
2305       draw_insertion_cursor (label,
2306                              &cursor_location, TRUE, dir1,
2307                              dir2 != PANGO_DIRECTION_NEUTRAL);
2308       
2309       if (dir2 != PANGO_DIRECTION_NEUTRAL)
2310         {
2311           cursor_location.x = xoffset + PANGO_PIXELS (cursor2->x);
2312           cursor_location.y = yoffset + PANGO_PIXELS (cursor2->y);
2313           cursor_location.width = 0;
2314           cursor_location.height = PANGO_PIXELS (cursor2->height);
2315
2316           draw_insertion_cursor (label,
2317                                  &cursor_location, FALSE, dir2,
2318                                  TRUE);
2319         }
2320     }
2321 }
2322
2323
2324 static gint
2325 gtk_label_expose (GtkWidget      *widget,
2326                   GdkEventExpose *event)
2327 {
2328   GtkLabel *label;
2329   gint x, y;
2330   
2331   g_return_val_if_fail (GTK_IS_LABEL (widget), FALSE);
2332   g_return_val_if_fail (event != NULL, FALSE);
2333   
2334   label = GTK_LABEL (widget);
2335
2336   gtk_label_ensure_layout (label);
2337   
2338   if (GTK_WIDGET_VISIBLE (widget) && GTK_WIDGET_MAPPED (widget) &&
2339       label->text && (*label->text != '\0'))
2340     {
2341       get_layout_location (label, &x, &y);
2342
2343       gtk_paint_layout (widget->style,
2344                         widget->window,
2345                         GTK_WIDGET_STATE (widget),
2346                         FALSE,
2347                         &event->area,
2348                         widget,
2349                         "label",
2350                         x, y,
2351                         label->layout);
2352       
2353       if (label->select_info &&
2354           (label->select_info->selection_anchor !=
2355            label->select_info->selection_end))
2356         {
2357           gint range[2];
2358           GdkRegion *clip;
2359           GtkStateType state;
2360           
2361           range[0] = label->select_info->selection_anchor;
2362           range[1] = label->select_info->selection_end;
2363
2364           if (range[0] > range[1])
2365             {
2366               gint tmp = range[0];
2367               range[0] = range[1];
2368               range[1] = tmp;
2369             }
2370
2371           clip = gdk_pango_layout_get_clip_region (label->layout,
2372                                                    x, y,
2373                                                    range,
2374                                                    1);
2375           gdk_region_intersect (clip, event->region);
2376  
2377          /* FIXME should use gtk_paint, but it can't use a clip
2378            * region
2379            */
2380
2381           gdk_gc_set_clip_region (widget->style->black_gc, clip);
2382
2383
2384           state = GTK_STATE_SELECTED;
2385           if (!GTK_WIDGET_HAS_FOCUS (widget))
2386             state = GTK_STATE_ACTIVE;
2387               
2388           gdk_draw_layout_with_colors (widget->window,
2389                                        widget->style->black_gc,
2390                                        x, y,
2391                                        label->layout,
2392                                        &widget->style->text[state],
2393                                        &widget->style->base[state]);
2394
2395           gdk_gc_set_clip_region (widget->style->black_gc, NULL);
2396           gdk_region_destroy (clip);
2397         }
2398       else if (label->select_info && GTK_WIDGET_HAS_FOCUS (widget))
2399         gtk_label_draw_cursor (label, x, y);
2400     }
2401
2402   return FALSE;
2403 }
2404
2405 static void
2406 gtk_label_set_uline_text_internal (GtkLabel    *label,
2407                                    const gchar *str)
2408 {
2409   guint accel_key = GDK_VoidSymbol;
2410
2411   gchar *new_str;
2412   gchar *pattern;
2413   const gchar *src;
2414   gchar *dest, *pattern_dest;
2415   gboolean underscore;
2416       
2417   g_return_if_fail (GTK_IS_LABEL (label));
2418   g_return_if_fail (str != NULL);
2419
2420   /* Split text into the base text and a separate pattern
2421    * of underscores.
2422    */
2423   
2424   new_str = g_new (gchar, strlen (str) + 1);
2425   pattern = g_new (gchar, g_utf8_strlen (str, -1) + 1);
2426   
2427   underscore = FALSE;
2428
2429   if (str == NULL)
2430     str = "";
2431   
2432   src = str;
2433   dest = new_str;
2434   pattern_dest = pattern;
2435   
2436   while (*src)
2437     {
2438       gunichar c;
2439       gchar *next_src;
2440
2441       c = g_utf8_get_char (src);
2442       if (c == (gunichar)-1)
2443         {
2444           g_warning ("Invalid input string");
2445           g_free (new_str);
2446           g_free (pattern);
2447           return;
2448         }
2449       next_src = g_utf8_next_char (src);
2450       
2451       if (underscore)
2452         {
2453           if (c == '_')
2454             *pattern_dest++ = ' ';
2455           else
2456             {
2457               *pattern_dest++ = '_';
2458               if (accel_key == GDK_VoidSymbol)
2459                 accel_key = gdk_keyval_to_lower (gdk_unicode_to_keyval (c));
2460             }
2461
2462           while (src < next_src)
2463             *dest++ = *src++;
2464           
2465           underscore = FALSE;
2466         }
2467       else
2468         {
2469           if (c == '_')
2470             {
2471               underscore = TRUE;
2472               src = next_src;
2473             }
2474           else
2475             {
2476               while (src < next_src)
2477                 *dest++ = *src++;
2478           
2479               *pattern_dest++ = ' ';
2480             }
2481         }
2482     }
2483   *dest = 0;
2484   *pattern_dest = 0;
2485   
2486   gtk_label_set_text_internal (label, new_str);
2487   gtk_label_set_pattern_internal (label, pattern);
2488   
2489   g_free (pattern);
2490
2491   label->mnemonic_keyval = accel_key;
2492 }
2493
2494 guint      
2495 gtk_label_parse_uline (GtkLabel    *label,
2496                        const gchar *str)
2497 {
2498   guint keyval;
2499   guint orig_keyval;
2500   
2501   g_return_val_if_fail (GTK_IS_LABEL (label), GDK_VoidSymbol);
2502   g_return_val_if_fail (str != NULL, GDK_VoidSymbol);
2503
2504   orig_keyval = label->mnemonic_keyval;
2505
2506   g_object_freeze_notify (G_OBJECT (label));
2507   
2508   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2509   gtk_label_set_use_markup_internal (label, FALSE);
2510   gtk_label_set_use_underline_internal (label, TRUE);
2511   
2512   gtk_label_recalculate (label);
2513
2514   keyval = label->mnemonic_keyval;
2515   label->mnemonic_keyval = GDK_VoidSymbol;
2516   
2517   gtk_label_setup_mnemonic (label, orig_keyval);
2518   
2519   g_object_thaw_notify (G_OBJECT (label));
2520
2521   return keyval;
2522 }
2523
2524 /**
2525  * gtk_label_set_text_with_mnemonic:
2526  * @label: a #GtkLabel
2527  * @str: a string
2528  * 
2529  * Sets the label's text from the string @str.
2530  * If characters in @str are preceded by an underscore, they are underlined
2531  * indicating that they represent a keyboard accelerator called a mnemonic.
2532  * The mnemonic key can be used to activate another widget, chosen automatically,
2533  * or explicitly using gtk_label_set_mnemonic_widget().
2534  **/
2535 void
2536 gtk_label_set_text_with_mnemonic (GtkLabel    *label,
2537                                   const gchar *str)
2538 {
2539   guint last_keyval;
2540   
2541   g_return_if_fail (GTK_IS_LABEL (label));
2542   g_return_if_fail (str != NULL);
2543
2544   last_keyval = label->mnemonic_keyval;
2545
2546   g_object_freeze_notify (G_OBJECT (label));
2547
2548   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2549   gtk_label_set_use_markup_internal (label, FALSE);
2550   gtk_label_set_use_underline_internal (label, TRUE);
2551   
2552   gtk_label_recalculate (label);
2553
2554   gtk_label_setup_mnemonic (label, last_keyval);
2555
2556   g_object_thaw_notify (G_OBJECT (label));
2557 }
2558
2559 static void
2560 gtk_label_realize (GtkWidget *widget)
2561 {
2562   GtkLabel *label;
2563
2564   label = GTK_LABEL (widget);
2565   
2566   (* GTK_WIDGET_CLASS (parent_class)->realize) (widget);
2567
2568   if (label->select_info)
2569     gtk_label_create_window (label);
2570 }
2571
2572 static void
2573 gtk_label_unrealize (GtkWidget *widget)
2574 {
2575   GtkLabel *label;
2576
2577   label = GTK_LABEL (widget);
2578
2579   if (label->select_info)
2580     gtk_label_destroy_window (label);
2581   
2582   (* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
2583 }
2584
2585 static void
2586 gtk_label_map (GtkWidget *widget)
2587 {
2588   GtkLabel *label;
2589
2590   label = GTK_LABEL (widget);
2591   
2592   (* GTK_WIDGET_CLASS (parent_class)->map) (widget);
2593   
2594   if (label->select_info)
2595     gdk_window_show (label->select_info->window);
2596 }
2597
2598 static void
2599 gtk_label_unmap (GtkWidget *widget)
2600 {
2601   GtkLabel *label;
2602
2603   label = GTK_LABEL (widget);
2604
2605   if (label->select_info)
2606     gdk_window_hide (label->select_info->window);
2607   
2608   (* GTK_WIDGET_CLASS (parent_class)->unmap) (widget);
2609 }
2610
2611 static void
2612 window_to_layout_coords (GtkLabel *label,
2613                          gint     *x,
2614                          gint     *y)
2615 {
2616   gint lx, ly;
2617   GtkWidget *widget;
2618
2619   widget = GTK_WIDGET (label);
2620   
2621   /* get layout location in widget->window coords */
2622   get_layout_location (label, &lx, &ly);
2623   
2624   if (x)
2625     {
2626       *x += widget->allocation.x; /* go to widget->window */
2627       *x -= lx;                   /* go to layout */
2628     }
2629
2630   if (y)
2631     {
2632       *y += widget->allocation.y; /* go to widget->window */
2633       *y -= ly;                   /* go to layout */
2634     }
2635 }
2636
2637 #if 0
2638 static void
2639 layout_to_window_coords (GtkLabel *label,
2640                          gint     *x,
2641                          gint     *y)
2642 {
2643   gint lx, ly;
2644   GtkWidget *widget;
2645
2646   widget = GTK_WIDGET (label);
2647   
2648   /* get layout location in widget->window coords */
2649   get_layout_location (label, &lx, &ly);
2650   
2651   if (x)
2652     {
2653       *x += lx;                   /* go to widget->window */
2654       *x -= widget->allocation.x; /* go to selection window */
2655     }
2656
2657   if (y)
2658     {
2659       *y += ly;                   /* go to widget->window */
2660       *y -= widget->allocation.y; /* go to selection window */
2661     }
2662 }
2663 #endif
2664
2665 static void
2666 get_layout_index (GtkLabel *label,
2667                   gint      x,
2668                   gint      y,
2669                   gint     *index)
2670 {
2671   gint trailing = 0;
2672   const gchar *cluster;
2673   const gchar *cluster_end;
2674
2675   *index = 0;
2676   
2677   gtk_label_ensure_layout (label);
2678   
2679   window_to_layout_coords (label, &x, &y);
2680
2681   x *= PANGO_SCALE;
2682   y *= PANGO_SCALE;
2683   
2684   pango_layout_xy_to_index (label->layout,
2685                             x, y,
2686                             index, &trailing);
2687
2688   
2689   cluster = label->text + *index;
2690   cluster_end = cluster;
2691   while (trailing)
2692     {
2693       cluster_end = g_utf8_next_char (cluster_end);
2694       --trailing;
2695     }
2696
2697   *index += (cluster_end - cluster);
2698 }
2699
2700 static void
2701 gtk_label_select_word (GtkLabel *label)
2702 {
2703   gint min, max;
2704   
2705   gint start_index = gtk_label_move_backward_word (label, label->select_info->selection_end);
2706   gint end_index = gtk_label_move_forward_word (label, label->select_info->selection_end);
2707
2708   min = MIN (label->select_info->selection_anchor,
2709              label->select_info->selection_end);
2710   max = MAX (label->select_info->selection_anchor,
2711              label->select_info->selection_end);
2712
2713   min = MIN (min, start_index);
2714   max = MAX (max, end_index);
2715
2716   gtk_label_select_region_index (label, min, max);
2717 }
2718
2719 static gboolean
2720 gtk_label_button_press (GtkWidget      *widget,
2721                         GdkEventButton *event)
2722 {
2723   GtkLabel *label;
2724   gint index = 0;
2725   gint min, max;  
2726   
2727   label = GTK_LABEL (widget);
2728
2729   if (label->select_info == NULL)
2730     return FALSE;
2731
2732   label->select_info->in_drag = FALSE;
2733   if (event->button == 1)
2734     {
2735       if (!GTK_WIDGET_HAS_FOCUS (widget))
2736         gtk_widget_grab_focus (widget);
2737
2738       if (event->type == GDK_3BUTTON_PRESS)
2739         {
2740           gtk_label_select_region_index (label, 0, strlen (label->text));
2741           return TRUE;
2742         }
2743       
2744       if (event->type == GDK_2BUTTON_PRESS)
2745         {
2746           gtk_label_select_word (label);
2747           return TRUE;
2748         }
2749       
2750       get_layout_index (label, event->x, event->y, &index);
2751       
2752       min = MIN (label->select_info->selection_anchor,
2753                  label->select_info->selection_end);
2754       max = MAX (label->select_info->selection_anchor,
2755                  label->select_info->selection_end);
2756           
2757       if ((label->select_info->selection_anchor !=
2758            label->select_info->selection_end) &&
2759           (event->state & GDK_SHIFT_MASK))
2760         {
2761           /* extend (same as motion) */
2762           min = MIN (min, index);
2763           max = MAX (max, index);
2764           
2765           /* ensure the anchor is opposite index */
2766           if (index == min)
2767             {
2768               gint tmp = min;
2769               min = max;
2770               max = tmp;
2771             }
2772           
2773           gtk_label_select_region_index (label, min, max);
2774         }
2775       else 
2776         {
2777           if (event->type == GDK_3BUTTON_PRESS)
2778             gtk_label_select_region_index (label, 0, strlen (label->text));
2779           else if (event->type == GDK_2BUTTON_PRESS)
2780             gtk_label_select_word (label);
2781           else if (min < max && min <= index && index <= max)
2782             {
2783               label->select_info->in_drag = TRUE;
2784               label->select_info->drag_start_x = event->x;
2785               label->select_info->drag_start_y = event->y;
2786             }
2787           else
2788             /* start a replacement */
2789             gtk_label_select_region_index (label, index, index);
2790         }
2791   
2792       return TRUE;
2793     }
2794   else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
2795     {
2796       gtk_label_do_popup (label, event);
2797
2798       return TRUE;
2799       
2800     }
2801   return FALSE;
2802 }
2803
2804 static gboolean
2805 gtk_label_button_release (GtkWidget      *widget,
2806                           GdkEventButton *event)
2807
2808 {
2809   GtkLabel *label = GTK_LABEL (widget);
2810   gint index;
2811   
2812   if (label->select_info == NULL)
2813     return FALSE;
2814   
2815   if (label->select_info->in_drag)
2816     {
2817       label->select_info->in_drag = 0;
2818
2819       get_layout_index (label, event->x, event->y, &index);
2820       gtk_label_select_region_index (label, index, index);
2821       
2822       return FALSE;
2823     }
2824
2825   if (event->button != 1)
2826     return FALSE;
2827   
2828   /* The goal here is to return TRUE iff we ate the
2829    * button press to start selecting.
2830    */
2831   
2832   return TRUE;
2833 }
2834
2835 static gboolean
2836 gtk_label_motion (GtkWidget      *widget,
2837                   GdkEventMotion *event)
2838 {
2839   GtkLabel *label;
2840   gint index;
2841   gint x, y;
2842   
2843   label = GTK_LABEL (widget);
2844   
2845   if (label->select_info == NULL)
2846     return FALSE;  
2847
2848
2849   if ((event->state & GDK_BUTTON1_MASK) == 0)
2850     return FALSE;
2851
2852   gdk_window_get_pointer (label->select_info->window,
2853                           &x, &y, NULL);
2854   
2855   if (label->select_info->in_drag)
2856     {
2857       if (gtk_drag_check_threshold (widget,
2858                                     label->select_info->drag_start_x, 
2859                                     label->select_info->drag_start_y,
2860                                     event->x, event->y))
2861         {
2862           GdkDragContext *context;
2863           GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
2864
2865           gtk_target_list_add_text_targets (target_list, 0);
2866
2867           context = gtk_drag_begin (widget, target_list, 
2868                                     GDK_ACTION_COPY,
2869                                     1, (GdkEvent *)event);
2870
2871           
2872           label->select_info->in_drag = FALSE;
2873           
2874           gtk_target_list_unref (target_list);
2875           gtk_drag_set_icon_default (context);
2876         }
2877     }
2878   else
2879     {
2880       get_layout_index (label, x, y, &index);
2881       
2882       gtk_label_select_region_index (label,
2883                                      label->select_info->selection_anchor,
2884                                      index);
2885     }
2886
2887   return TRUE;
2888 }
2889
2890 static void
2891 gtk_label_create_window (GtkLabel *label)
2892 {
2893   GtkWidget *widget;
2894   GdkWindowAttr attributes;
2895   gint attributes_mask;
2896   
2897   g_assert (label->select_info);
2898   g_assert (GTK_WIDGET_REALIZED (label));
2899   
2900   if (label->select_info->window)
2901     return;
2902   
2903   widget = GTK_WIDGET (label);
2904
2905   attributes.x = widget->allocation.x;
2906   attributes.y = widget->allocation.y;
2907   attributes.width = widget->allocation.width;
2908   attributes.height = widget->allocation.height;
2909   attributes.window_type = GDK_WINDOW_TEMP;
2910   attributes.wclass = GDK_INPUT_ONLY;
2911   attributes.override_redirect = TRUE;
2912   attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget),
2913                                                   GDK_XTERM);
2914   attributes.event_mask = gtk_widget_get_events (widget) |
2915     GDK_BUTTON_PRESS_MASK        |
2916     GDK_BUTTON_RELEASE_MASK      |
2917     GDK_BUTTON_MOTION_MASK;
2918
2919   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_NOREDIR | GDK_WA_CURSOR;
2920
2921   label->select_info->window = gdk_window_new (widget->window,
2922                                                &attributes, attributes_mask);
2923   gdk_window_set_user_data (label->select_info->window, widget);
2924
2925   gdk_cursor_unref (attributes.cursor);
2926 }
2927
2928 static void
2929 gtk_label_destroy_window (GtkLabel *label)
2930 {
2931   g_assert (label->select_info);
2932
2933   if (label->select_info->window == NULL)
2934     return;
2935   
2936   gdk_window_set_user_data (label->select_info->window, NULL);
2937   gdk_window_destroy (label->select_info->window);
2938   label->select_info->window = NULL;
2939 }
2940
2941 /**
2942  * gtk_label_set_selectable:
2943  * @label: a #GtkLabel
2944  * @setting: %TRUE to allow selecting text in the label
2945  *
2946  * Selectable labels allow the user to select text from the label, for
2947  * copy-and-paste.
2948  * 
2949  **/
2950 void
2951 gtk_label_set_selectable (GtkLabel *label,
2952                           gboolean  setting)
2953 {
2954   gboolean old_setting;
2955   
2956   g_return_if_fail (GTK_IS_LABEL (label));
2957   
2958   setting = setting != FALSE;
2959   old_setting = label->select_info != NULL;
2960   
2961   if (setting)
2962     {
2963       if (label->select_info == NULL)
2964         {
2965           label->select_info = g_new0 (GtkLabelSelectionInfo, 1);
2966
2967           GTK_WIDGET_SET_FLAGS (label, GTK_CAN_FOCUS);
2968       
2969           if (GTK_WIDGET_REALIZED (label))
2970             gtk_label_create_window (label);
2971
2972           if (GTK_WIDGET_MAPPED (label))
2973             gdk_window_show (label->select_info->window);
2974         }
2975     }
2976   else
2977     {
2978       if (label->select_info)
2979         {
2980           /* unselect, to give up the selection */
2981           gtk_label_select_region (label, 0, 0);
2982           
2983           if (label->select_info->window)
2984             {
2985               gtk_label_destroy_window (label);
2986             }
2987
2988           g_free (label->select_info);
2989
2990           label->select_info = NULL;
2991
2992           GTK_WIDGET_UNSET_FLAGS (label, GTK_CAN_FOCUS);
2993         }
2994     }
2995   if (setting != old_setting)
2996     {
2997       g_object_freeze_notify (G_OBJECT (label));
2998       g_object_notify (G_OBJECT (label), "selectable");
2999       g_object_notify (G_OBJECT (label), "cursor_position");
3000       g_object_notify (G_OBJECT (label), "selection_bound");
3001       g_object_thaw_notify (G_OBJECT (label));
3002       gtk_widget_queue_draw (GTK_WIDGET (label));
3003     }
3004 }
3005
3006 /**
3007  * gtk_label_get_selectable:
3008  * @label: a #GtkLabel
3009  * 
3010  * Gets the value set by gtk_label_set_selectable().
3011  * 
3012  * Return value: %TRUE if the user can copy text from the label
3013  **/
3014 gboolean
3015 gtk_label_get_selectable (GtkLabel *label)
3016 {
3017   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3018
3019   return label->select_info != NULL;
3020 }
3021
3022 /**
3023  * gtk_label_set_angle:
3024  * @label: a #GtkLabel
3025  * @angle: the angle that the baseline of the label makes with
3026  *   the horizontal, in degrees, measured counterclockwise
3027  * 
3028  * Sets the angle of rotation for the label. An angle of 90 reads from
3029  * from bottom to top, an angle of 270, from top to bottom. The angle
3030  * setting for the label is ignored if the label is selectable,
3031  * wrapped, or ellipsized.
3032  *
3033  * Since: 2.6
3034  **/
3035 void
3036 gtk_label_set_angle (GtkLabel *label,
3037                      gdouble   angle)
3038 {
3039   GtkLabelPrivate *priv;
3040
3041   g_return_if_fail (GTK_IS_LABEL (label));
3042
3043   priv = GTK_LABEL_GET_PRIVATE (label);
3044
3045   /* Canonicalize to [0,360]. We don't canonicalize 360 to 0, because
3046    * double property ranges are inclusive, and changing 360 to 0 would
3047    * make a property editor behave strangely.
3048    */
3049   if (angle < 0 || angle > 360.0)
3050     angle = angle - 360. * floor (angle / 360.);
3051
3052   if (angle != priv->angle)
3053     {
3054       priv->angle = angle;
3055       
3056       gtk_label_clear_layout (label);
3057       gtk_widget_queue_resize (GTK_WIDGET (label));
3058
3059       g_object_notify (G_OBJECT (label), "angle");
3060     }
3061 }
3062
3063 /**
3064  * gtk_label_get_angle:
3065  * @label: a #GtkLabel
3066  * 
3067  * Gets the angle of rotation for the label. See
3068  * gtk_label_set_angle.
3069  * 
3070  * Return value: the angle of rotation for the label
3071  *
3072  * Since: 2.6
3073  **/
3074 gdouble
3075 gtk_label_get_angle  (GtkLabel *label)
3076 {
3077   GtkLabelPrivate *priv;
3078
3079   g_return_val_if_fail (GTK_IS_LABEL (label), 0.0);
3080
3081   priv = GTK_LABEL_GET_PRIVATE (label);
3082
3083   return priv->angle;
3084 }
3085
3086 static void
3087 gtk_label_set_selection_text (GtkLabel         *label,
3088                               GtkSelectionData *selection_data)
3089 {
3090   if ((label->select_info->selection_anchor !=
3091        label->select_info->selection_end) &&
3092       label->text)
3093     {
3094       gint start, end;
3095       gint len;
3096       
3097       start = MIN (label->select_info->selection_anchor,
3098                    label->select_info->selection_end);
3099       end = MAX (label->select_info->selection_anchor,
3100                  label->select_info->selection_end);
3101       
3102       len = strlen (label->text);
3103       
3104       if (end > len)
3105         end = len;
3106       
3107       if (start > len)
3108         start = len;
3109       
3110       gtk_selection_data_set_text (selection_data,
3111                                    label->text + start,
3112                                    end - start);
3113     }
3114 }
3115
3116 static void
3117 gtk_label_drag_data_get (GtkWidget        *widget,
3118                          GdkDragContext   *context,
3119                          GtkSelectionData *selection_data,
3120                          guint             info,
3121                          guint             time)
3122 {
3123   gtk_label_set_selection_text (GTK_LABEL (widget), selection_data);
3124 }
3125
3126 static void
3127 get_text_callback (GtkClipboard     *clipboard,
3128                    GtkSelectionData *selection_data,
3129                    guint             info,
3130                    gpointer          user_data_or_owner)
3131 {
3132   gtk_label_set_selection_text (GTK_LABEL (user_data_or_owner), selection_data);
3133 }
3134
3135 static void
3136 clear_text_callback (GtkClipboard     *clipboard,
3137                      gpointer          user_data_or_owner)
3138 {
3139   GtkLabel *label;
3140
3141   label = GTK_LABEL (user_data_or_owner);
3142
3143   if (label->select_info)
3144     {
3145       label->select_info->selection_anchor = label->select_info->selection_end;
3146       
3147       gtk_widget_queue_draw (GTK_WIDGET (label));
3148     }
3149 }
3150
3151 static void
3152 gtk_label_select_region_index (GtkLabel *label,
3153                                gint      anchor_index,
3154                                gint      end_index)
3155 {
3156   static const GtkTargetEntry targets[] = {
3157     { "STRING", 0, 0 },
3158     { "TEXT",   0, 0 }, 
3159     { "COMPOUND_TEXT", 0, 0 },
3160     { "UTF8_STRING", 0, 0 }
3161   };
3162
3163   g_return_if_fail (GTK_IS_LABEL (label));
3164   
3165   if (label->select_info)
3166     {
3167       GtkClipboard *clipboard;
3168
3169       if (label->select_info->selection_anchor == anchor_index &&
3170           label->select_info->selection_end == end_index)
3171         return;
3172
3173       label->select_info->selection_anchor = anchor_index;
3174       label->select_info->selection_end = end_index;
3175
3176       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label),
3177                                             GDK_SELECTION_PRIMARY);      
3178       
3179       if (anchor_index != end_index)
3180         {
3181           gtk_clipboard_set_with_owner (clipboard,
3182                                         targets,
3183                                         G_N_ELEMENTS (targets),
3184                                         get_text_callback,
3185                                         clear_text_callback,
3186                                         G_OBJECT (label));
3187         }
3188       else
3189         {
3190           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (label))
3191             gtk_clipboard_clear (clipboard);
3192         }
3193
3194       gtk_widget_queue_draw (GTK_WIDGET (label));
3195
3196       g_object_freeze_notify (G_OBJECT (label));
3197       g_object_notify (G_OBJECT (label), "cursor_position");
3198       g_object_notify (G_OBJECT (label), "selection_bound");
3199       g_object_thaw_notify (G_OBJECT (label));
3200     }
3201 }
3202
3203 /**
3204  * gtk_label_select_region:
3205  * @label: a #GtkLabel
3206  * @start_offset: start offset (in characters not bytes)
3207  * @end_offset: end offset (in characters not bytes)
3208  *
3209  * Selects a range of characters in the label, if the label is selectable.
3210  * See gtk_label_set_selectable(). If the label is not selectable,
3211  * this function has no effect. If @start_offset or
3212  * @end_offset are -1, then the end of the label will be substituted.
3213  * 
3214  **/
3215 void
3216 gtk_label_select_region  (GtkLabel *label,
3217                           gint      start_offset,
3218                           gint      end_offset)
3219 {
3220   g_return_if_fail (GTK_IS_LABEL (label));
3221   
3222   if (label->text && label->select_info)
3223     {
3224       if (start_offset < 0)
3225         start_offset = g_utf8_strlen (label->text, -1);
3226       
3227       if (end_offset < 0)
3228         end_offset = g_utf8_strlen (label->text, -1);
3229       
3230       gtk_label_select_region_index (label,
3231                                      g_utf8_offset_to_pointer (label->text, start_offset) - label->text,
3232                                      g_utf8_offset_to_pointer (label->text, end_offset) - label->text);
3233     }
3234 }
3235
3236 /**
3237  * gtk_label_get_selection_bounds:
3238  * @label: a #GtkLabel
3239  * @start: return location for start of selection, as a character offset
3240  * @end: return location for end of selection, as a character offset
3241  * 
3242  * Gets the selected range of characters in the label, returning %TRUE
3243  * if there's a selection.
3244  * 
3245  * Return value: %TRUE if selection is non-empty
3246  **/
3247 gboolean
3248 gtk_label_get_selection_bounds (GtkLabel  *label,
3249                                 gint      *start,
3250                                 gint      *end)
3251 {
3252   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3253
3254   if (label->select_info == NULL)
3255     {
3256       /* not a selectable label */
3257       if (start)
3258         *start = 0;
3259       if (end)
3260         *end = 0;
3261
3262       return FALSE;
3263     }
3264   else
3265     {
3266       gint start_index, end_index;
3267       gint start_offset, end_offset;
3268       gint len;
3269       
3270       start_index = MIN (label->select_info->selection_anchor,
3271                    label->select_info->selection_end);
3272       end_index = MAX (label->select_info->selection_anchor,
3273                  label->select_info->selection_end);
3274
3275       len = strlen (label->text);
3276
3277       if (end_index > len)
3278         end_index = len;
3279
3280       if (start_index > len)
3281         start_index = len;
3282       
3283       start_offset = g_utf8_strlen (label->text, start_index);
3284       end_offset = g_utf8_strlen (label->text, end_index);
3285
3286       if (start_offset > end_offset)
3287         {
3288           gint tmp = start_offset;
3289           start_offset = end_offset;
3290           end_offset = tmp;
3291         }
3292       
3293       if (start)
3294         *start = start_offset;
3295
3296       if (end)
3297         *end = end_offset;
3298
3299       return start_offset != end_offset;
3300     }
3301 }
3302
3303
3304 /**
3305  * gtk_label_get_layout:
3306  * @label: a #GtkLabel
3307  * 
3308  * Gets the #PangoLayout used to display the label.
3309  * The layout is useful to e.g. convert text positions to
3310  * pixel positions, in combination with gtk_label_get_layout_offsets().
3311  * The returned layout is owned by the label so need not be
3312  * freed by the caller.
3313  * 
3314  * Return value: the #PangoLayout for this label
3315  **/
3316 PangoLayout*
3317 gtk_label_get_layout (GtkLabel *label)
3318 {
3319   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
3320
3321   gtk_label_ensure_layout (label);
3322
3323   return label->layout;
3324 }
3325
3326 /**
3327  * gtk_label_get_layout_offsets:
3328  * @label: a #GtkLabel
3329  * @x: location to store X offset of layout, or %NULL
3330  * @y: location to store Y offset of layout, or %NULL
3331  *
3332  * Obtains the coordinates where the label will draw the #PangoLayout
3333  * representing the text in the label; useful to convert mouse events
3334  * into coordinates inside the #PangoLayout, e.g. to take some action
3335  * if some part of the label is clicked. Of course you will need to
3336  * create a #GtkEventBox to receive the events, and pack the label
3337  * inside it, since labels are a #GTK_NO_WINDOW widget. Remember
3338  * when using the #PangoLayout functions you need to convert to
3339  * and from pixels using PANGO_PIXELS() or #PANGO_SCALE.
3340  * 
3341  **/
3342 void
3343 gtk_label_get_layout_offsets (GtkLabel *label,
3344                               gint     *x,
3345                               gint     *y)
3346 {
3347   g_return_if_fail (GTK_IS_LABEL (label));
3348   
3349   get_layout_location (label, x, y);
3350 }
3351
3352 /**
3353  * gtk_label_set_use_markup:
3354  * @label: a #GtkLabel
3355  * @setting: %TRUE if the label's text should be parsed for markup.
3356  *
3357  * Sets whether the text of the label contains markup in <link
3358  * linkend="PangoMarkupFormat">Pango's text markup
3359  * language</link>. See gtk_label_set_markup().
3360  **/
3361 void
3362 gtk_label_set_use_markup (GtkLabel *label,
3363                           gboolean  setting)
3364 {
3365   g_return_if_fail (GTK_IS_LABEL (label));
3366
3367   gtk_label_set_use_markup_internal (label, setting);
3368   gtk_label_recalculate (label);
3369 }
3370
3371 /**
3372  * gtk_label_get_use_markup:
3373  * @label: a #GtkLabel
3374  *
3375  * Returns whether the label's text is interpreted as marked up with
3376  * the <link linkend="PangoMarkupFormat">Pango text markup
3377  * language</link>. See gtk_label_set_use_markup ().
3378  *
3379  * Return value: %TRUE if the label's text will be parsed for markup.
3380  **/
3381 gboolean
3382 gtk_label_get_use_markup (GtkLabel *label)
3383 {
3384   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3385   
3386   return label->use_markup;
3387 }
3388
3389 /**
3390  * gtk_label_set_use_underline:
3391  * @label: a #GtkLabel
3392  * @setting: %TRUE if underlines in the text indicate mnemonics
3393  *
3394  * If true, an underline in the text indicates the next character should be
3395  * used for the mnemonic accelerator key.
3396  */
3397 void
3398 gtk_label_set_use_underline (GtkLabel *label,
3399                              gboolean  setting)
3400 {
3401   g_return_if_fail (GTK_IS_LABEL (label));
3402
3403   gtk_label_set_use_underline_internal (label, setting);
3404   gtk_label_recalculate (label);
3405   if (label->use_underline)
3406     gtk_label_setup_mnemonic (label, label->mnemonic_keyval);
3407 }
3408
3409 /**
3410  * gtk_label_get_use_underline:
3411  * @label: a #GtkLabel
3412  *
3413  * Returns whether an embedded underline in the label indicates a
3414  * mnemonic. See gtk_label_set_use_underline ().
3415  *
3416  * Return value: %TRUE whether an embedded underline in the label indicates
3417  *               the mnemonic accelerator keys.
3418  **/
3419 gboolean
3420 gtk_label_get_use_underline (GtkLabel *label)
3421 {
3422   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3423   
3424   return label->use_underline;
3425 }
3426
3427 /**
3428  * gtk_label_set_single_line_mode:
3429  * @label: a #GtkLabel
3430  * @single_line_mode: %TRUE if the label should be in single line mode
3431  *
3432  * Sets whether the label is in single line mode.
3433  *
3434  * Since: 2.6
3435  */
3436 void
3437 gtk_label_set_single_line_mode (GtkLabel *label,
3438                                 gboolean single_line_mode)
3439 {
3440   GtkLabelPrivate *priv;
3441
3442   g_return_if_fail (GTK_IS_LABEL (label));
3443
3444   single_line_mode = single_line_mode != FALSE;
3445
3446   priv = GTK_LABEL_GET_PRIVATE (label);
3447   if (priv->single_line_mode != single_line_mode)
3448     {
3449       priv->single_line_mode = single_line_mode;
3450
3451       gtk_label_clear_layout (label);
3452       gtk_widget_queue_resize (GTK_WIDGET (label));
3453
3454       g_object_notify (G_OBJECT (label), "single-line-mode");
3455     }
3456 }
3457
3458 /**
3459  * gtk_label_get_single_line_mode:
3460  * @label: a #GtkLabel
3461  *
3462  * Returns whether the label is in single line mode.
3463  *
3464  * Return value: %TRUE when the label is in single line mode.
3465  *
3466  * Since: 2.6
3467  **/
3468 gboolean
3469 gtk_label_get_single_line_mode  (GtkLabel *label)
3470 {
3471   GtkLabelPrivate *priv;
3472
3473   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3474
3475   priv = GTK_LABEL_GET_PRIVATE (label);
3476
3477   return priv->single_line_mode;
3478 }
3479
3480 /* Compute the X position for an offset that corresponds to the "more important
3481  * cursor position for that offset. We use this when trying to guess to which
3482  * end of the selection we should go to when the user hits the left or
3483  * right arrow key.
3484  */
3485 static void
3486 get_better_cursor (GtkLabel *label,
3487                    gint      index,
3488                    gint      *x,
3489                    gint      *y)
3490 {
3491   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
3492   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3493   PangoDirection cursor_direction = get_cursor_direction (label);
3494   gboolean split_cursor;
3495   PangoRectangle strong_pos, weak_pos;
3496   
3497   g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
3498                 "gtk-split-cursor", &split_cursor,
3499                 NULL);
3500
3501   gtk_label_ensure_layout (label);
3502   
3503   pango_layout_get_cursor_pos (label->layout, index,
3504                                &strong_pos, &weak_pos);
3505
3506   if (split_cursor)
3507     {
3508       *x = strong_pos.x / PANGO_SCALE;
3509       *y = strong_pos.y / PANGO_SCALE;
3510     }
3511   else
3512     {
3513       if (keymap_direction == cursor_direction)
3514         {
3515           *x = strong_pos.x / PANGO_SCALE;
3516           *y = strong_pos.y / PANGO_SCALE;
3517         }
3518       else
3519         {
3520           *x = weak_pos.x / PANGO_SCALE;
3521           *y = weak_pos.y / PANGO_SCALE;
3522         }
3523     }
3524 }
3525
3526
3527 static gint
3528 gtk_label_move_logically (GtkLabel *label,
3529                           gint      start,
3530                           gint      count)
3531 {
3532   gint offset = g_utf8_pointer_to_offset (label->text,
3533                                           label->text + start);
3534
3535   if (label->text)
3536     {
3537       PangoLogAttr *log_attrs;
3538       gint n_attrs;
3539       gint length;
3540
3541       gtk_label_ensure_layout (label);
3542       
3543       length = g_utf8_strlen (label->text, -1);
3544
3545       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3546
3547       while (count > 0 && offset < length)
3548         {
3549           do
3550             offset++;
3551           while (offset < length && !log_attrs[offset].is_cursor_position);
3552           
3553           count--;
3554         }
3555       while (count < 0 && offset > 0)
3556         {
3557           do
3558             offset--;
3559           while (offset > 0 && !log_attrs[offset].is_cursor_position);
3560           
3561           count++;
3562         }
3563       
3564       g_free (log_attrs);
3565     }
3566
3567   return g_utf8_offset_to_pointer (label->text, offset) - label->text;
3568 }
3569
3570 static gint
3571 gtk_label_move_visually (GtkLabel *label,
3572                          gint      start,
3573                          gint      count)
3574 {
3575   gint index;
3576
3577   index = start;
3578   
3579   while (count != 0)
3580     {
3581       int new_index, new_trailing;
3582       gboolean split_cursor;
3583       gboolean strong;
3584
3585       gtk_label_ensure_layout (label);
3586
3587       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
3588                     "gtk-split-cursor", &split_cursor,
3589                     NULL);
3590
3591       if (split_cursor)
3592         strong = TRUE;
3593       else
3594         {
3595           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
3596           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3597
3598           strong = keymap_direction == get_cursor_direction (label);
3599         }
3600       
3601       if (count > 0)
3602         {
3603           pango_layout_move_cursor_visually (label->layout, strong, index, 0, 1, &new_index, &new_trailing);
3604           count--;
3605         }
3606       else
3607         {
3608           pango_layout_move_cursor_visually (label->layout, strong, index, 0, -1, &new_index, &new_trailing);
3609           count++;
3610         }
3611
3612       if (new_index < 0 || new_index == G_MAXINT)
3613         break;
3614
3615       index = new_index;
3616       
3617       while (new_trailing--)
3618         index = g_utf8_next_char (label->text + new_index) - label->text;
3619     }
3620   
3621   return index;
3622 }
3623
3624 static gint
3625 gtk_label_move_forward_word (GtkLabel *label,
3626                              gint      start)
3627 {
3628   gint new_pos = g_utf8_pointer_to_offset (label->text,
3629                                            label->text + start);
3630   gint length;
3631
3632   length = g_utf8_strlen (label->text, -1);
3633   if (new_pos < length)
3634     {
3635       PangoLogAttr *log_attrs;
3636       gint n_attrs;
3637
3638       gtk_label_ensure_layout (label);
3639       
3640       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3641       
3642       /* Find the next word end */
3643       new_pos++;
3644       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
3645         new_pos++;
3646
3647       g_free (log_attrs);
3648     }
3649
3650   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
3651 }
3652
3653
3654 static gint
3655 gtk_label_move_backward_word (GtkLabel *label,
3656                               gint      start)
3657 {
3658   gint new_pos = g_utf8_pointer_to_offset (label->text,
3659                                            label->text + start);
3660   gint length;
3661
3662   length = g_utf8_strlen (label->text, -1);
3663   
3664   if (new_pos > 0)
3665     {
3666       PangoLogAttr *log_attrs;
3667       gint n_attrs;
3668
3669       gtk_label_ensure_layout (label);
3670       
3671       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3672       
3673       new_pos -= 1;
3674
3675       /* Find the previous word beginning */
3676       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
3677         new_pos--;
3678
3679       g_free (log_attrs);
3680     }
3681
3682   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
3683 }
3684
3685 static void
3686 gtk_label_move_cursor (GtkLabel       *label,
3687                        GtkMovementStep step,
3688                        gint            count,
3689                        gboolean        extend_selection)
3690 {
3691   gint new_pos;
3692   
3693   if (label->select_info == NULL)
3694     return;
3695   
3696   new_pos = label->select_info->selection_end;
3697
3698   if (label->select_info->selection_end != label->select_info->selection_anchor &&
3699       !extend_selection)
3700     {
3701       /* If we have a current selection and aren't extending it, move to the
3702        * start/or end of the selection as appropriate
3703        */
3704       switch (step)
3705         {
3706         case GTK_MOVEMENT_VISUAL_POSITIONS:
3707           {
3708             gint end_x, end_y;
3709             gint anchor_x, anchor_y;
3710             gboolean end_is_left;
3711             
3712             get_better_cursor (label, label->select_info->selection_end, &end_x, &end_y);
3713             get_better_cursor (label, label->select_info->selection_anchor, &anchor_x, &anchor_y);
3714
3715             end_is_left = (end_y < anchor_y) || (end_y == anchor_y && end_x < anchor_x);
3716             
3717             if (count < 0)
3718               new_pos = end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
3719             else
3720               new_pos = !end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
3721
3722             break;
3723           }
3724         case GTK_MOVEMENT_LOGICAL_POSITIONS:
3725         case GTK_MOVEMENT_WORDS:
3726           if (count < 0)
3727             new_pos = MIN (label->select_info->selection_end, label->select_info->selection_anchor);
3728           else
3729             new_pos = MAX (label->select_info->selection_end, label->select_info->selection_anchor);
3730           break;
3731         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
3732         case GTK_MOVEMENT_PARAGRAPH_ENDS:
3733         case GTK_MOVEMENT_BUFFER_ENDS:
3734           /* FIXME: Can do better here */
3735           new_pos = count < 0 ? 0 : strlen (label->text);
3736           break;
3737         case GTK_MOVEMENT_DISPLAY_LINES:
3738         case GTK_MOVEMENT_PARAGRAPHS:
3739         case GTK_MOVEMENT_PAGES:
3740         case GTK_MOVEMENT_HORIZONTAL_PAGES:
3741           break;
3742         }
3743     }
3744   else
3745     {
3746       switch (step)
3747         {
3748         case GTK_MOVEMENT_LOGICAL_POSITIONS:
3749           new_pos = gtk_label_move_logically (label, new_pos, count);
3750           break;
3751         case GTK_MOVEMENT_VISUAL_POSITIONS:
3752           new_pos = gtk_label_move_visually (label, new_pos, count);
3753           break;
3754         case GTK_MOVEMENT_WORDS:
3755           while (count > 0)
3756             {
3757               new_pos = gtk_label_move_forward_word (label, new_pos);
3758               count--;
3759             }
3760           while (count < 0)
3761             {
3762               new_pos = gtk_label_move_backward_word (label, new_pos);
3763               count++;
3764             }
3765           break;
3766         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
3767         case GTK_MOVEMENT_PARAGRAPH_ENDS:
3768         case GTK_MOVEMENT_BUFFER_ENDS:
3769           /* FIXME: Can do better here */
3770           new_pos = count < 0 ? 0 : strlen (label->text);
3771           break;
3772         case GTK_MOVEMENT_DISPLAY_LINES:
3773         case GTK_MOVEMENT_PARAGRAPHS:
3774         case GTK_MOVEMENT_PAGES:
3775         case GTK_MOVEMENT_HORIZONTAL_PAGES:
3776           break;
3777         }
3778     }
3779
3780   if (extend_selection)
3781     gtk_label_select_region_index (label,
3782                                    label->select_info->selection_anchor,
3783                                    new_pos);
3784   else
3785     gtk_label_select_region_index (label, new_pos, new_pos);
3786 }
3787
3788 static void
3789 gtk_label_copy_clipboard (GtkLabel *label)
3790 {
3791   if (label->text && label->select_info)
3792     {
3793       gint start, end;
3794       gint len;
3795       
3796       start = MIN (label->select_info->selection_anchor,
3797                    label->select_info->selection_end);
3798       end = MAX (label->select_info->selection_anchor,
3799                  label->select_info->selection_end);
3800
3801       len = strlen (label->text);
3802
3803       if (end > len)
3804         end = len;
3805
3806       if (start > len)
3807         start = len;
3808
3809       if (start != end)
3810         gtk_clipboard_set_text (gtk_widget_get_clipboard (GTK_WIDGET (label),
3811                                                           GDK_SELECTION_CLIPBOARD),
3812                                 label->text + start, end - start);
3813     }
3814 }
3815
3816 static void
3817 gtk_label_select_all (GtkLabel *label)
3818 {
3819   gtk_label_select_region_index (label, 0, strlen (label->text));
3820 }
3821
3822 /* Quick hack of a popup menu
3823  */
3824 static void
3825 activate_cb (GtkWidget *menuitem,
3826              GtkLabel  *label)
3827 {
3828   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
3829   g_signal_emit_by_name (label, signal);
3830 }
3831
3832 static void
3833 append_action_signal (GtkLabel     *label,
3834                       GtkWidget    *menu,
3835                       const gchar  *stock_id,
3836                       const gchar  *signal,
3837                       gboolean      sensitive)
3838 {
3839   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
3840
3841   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
3842   g_signal_connect (menuitem, "activate",
3843                     G_CALLBACK (activate_cb), label);
3844
3845   gtk_widget_set_sensitive (menuitem, sensitive);
3846   
3847   gtk_widget_show (menuitem);
3848   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
3849 }
3850
3851 static void
3852 popup_menu_detach (GtkWidget *attach_widget,
3853                    GtkMenu   *menu)
3854 {
3855   GtkLabel *label;
3856   label = GTK_LABEL (attach_widget);
3857
3858   if (label->select_info)
3859     label->select_info->popup_menu = NULL;
3860 }
3861
3862 static void
3863 popup_position_func (GtkMenu   *menu,
3864                      gint      *x,
3865                      gint      *y,
3866                      gboolean  *push_in,
3867                      gpointer   user_data)
3868 {
3869   GtkLabel *label;
3870   GtkWidget *widget;
3871   GtkRequisition req;
3872   GdkScreen *screen;
3873   
3874   label = GTK_LABEL (user_data);  
3875   widget = GTK_WIDGET (label);
3876
3877   if (label->select_info == NULL)
3878     return;
3879   
3880   g_return_if_fail (GTK_WIDGET_REALIZED (label));
3881   
3882   screen = gtk_widget_get_screen (widget);
3883   gdk_window_get_origin (widget->window, x, y);      
3884
3885   gtk_widget_size_request (label->select_info->popup_menu, &req);
3886   
3887   *x += widget->allocation.width / 2;
3888   *y += widget->allocation.height;
3889
3890   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
3891   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
3892 }
3893
3894
3895 static void
3896 gtk_label_do_popup (GtkLabel       *label,
3897                     GdkEventButton *event)
3898 {
3899   GtkWidget *menuitem;
3900   gboolean have_selection;
3901
3902   if (label->select_info == NULL)
3903     return;
3904     
3905   if (label->select_info->popup_menu)
3906     gtk_widget_destroy (label->select_info->popup_menu);
3907   
3908   label->select_info->popup_menu = gtk_menu_new ();
3909
3910   gtk_menu_attach_to_widget (GTK_MENU (label->select_info->popup_menu),
3911                              GTK_WIDGET (label),
3912                              popup_menu_detach);
3913
3914   have_selection =
3915     label->select_info->selection_anchor != label->select_info->selection_end;
3916
3917
3918   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
3919                         FALSE);
3920   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
3921                         have_selection);
3922   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
3923                         FALSE);
3924   
3925   menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
3926   gtk_widget_set_sensitive (menuitem, FALSE);
3927   gtk_widget_show (menuitem);
3928   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3929
3930   menuitem = gtk_separator_menu_item_new ();
3931   gtk_widget_show (menuitem);
3932   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3933       
3934   menuitem = gtk_menu_item_new_with_label (_("Select All"));
3935   g_signal_connect_swapped (menuitem, "activate",
3936                             G_CALLBACK (gtk_label_select_all), label);
3937   gtk_widget_show (menuitem);
3938   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3939
3940   g_signal_emit (label,
3941                  signals[POPULATE_POPUP],
3942                  0,
3943                  label->select_info->popup_menu);
3944   
3945   if (event)
3946     gtk_menu_popup (GTK_MENU (label->select_info->popup_menu), NULL, NULL,
3947                     NULL, NULL,
3948                     event->button, event->time);
3949   else
3950     gtk_menu_popup (GTK_MENU (label->select_info->popup_menu), NULL, NULL,
3951                     popup_position_func, label,
3952                     0, gtk_get_current_event_time ());
3953 }