]> Pileus Git - ~andy/gtk/blob - gtk/gtklabel.c
Don't pass NULL to pango_context_get_metrics. Use
[~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       return;
2012     }
2013   else
2014     pango_layout_get_extents (label->layout, NULL, &logical_rect);
2015
2016   if ((label->wrap || label->ellipsize || 
2017        priv->width_chars > 0 || priv->max_width_chars > 0) && 
2018       aux_info && aux_info->width > 0)
2019     width += aux_info->width;
2020   else if (label->ellipsize || priv->width_chars > 0 || priv->width_chars > 0)
2021     {
2022       PangoContext *context;
2023       PangoFontMetrics *metrics;
2024       gint char_width, digit_width, char_pixels, w;
2025
2026       context = pango_layout_get_context (label->layout);
2027       metrics = pango_context_get_metrics (context, widget->style->font_desc, 
2028                                            pango_context_get_language (context));
2029
2030       char_width = pango_font_metrics_get_approximate_char_width (metrics);
2031       digit_width = pango_font_metrics_get_approximate_digit_width (metrics);
2032       char_pixels = MAX (char_width, digit_width);
2033       pango_font_metrics_unref (metrics);
2034
2035       if (priv->width_chars < 0)
2036         {
2037           PangoRectangle rect;
2038
2039           pango_layout_set_width (label->layout, -1);
2040           pango_layout_get_extents (label->layout, NULL, &rect);
2041
2042           w = char_pixels * MAX (priv->max_width_chars, 3);
2043           w = MIN (rect.width, w);
2044         }
2045       else
2046         {
2047           /* enforce minimum width for ellipsized labels at ~3 chars */
2048           w = char_pixels * MAX (priv->width_chars, 3);
2049         }
2050
2051       width += PANGO_PIXELS (w);
2052     }
2053   else
2054     width += PANGO_PIXELS (logical_rect.width);
2055
2056   if (priv->single_line_mode)
2057     {
2058       PangoContext *context;
2059       PangoFontMetrics *metrics;
2060       gint ascent, descent;
2061
2062       context = pango_layout_get_context (label->layout);
2063       metrics = pango_context_get_metrics (context, widget->style->font_desc,
2064                                            pango_context_get_language (context));
2065
2066       ascent = pango_font_metrics_get_ascent (metrics);
2067       descent = pango_font_metrics_get_descent (metrics);
2068       pango_font_metrics_unref (metrics);
2069     
2070       height += PANGO_PIXELS (ascent + descent);
2071     }
2072   else
2073     height += PANGO_PIXELS (logical_rect.height);
2074
2075   requisition->width = width;
2076   requisition->height = height;
2077 }
2078
2079 static void
2080 gtk_label_size_allocate (GtkWidget     *widget,
2081                          GtkAllocation *allocation)
2082 {
2083   GtkLabel *label;
2084
2085   label = GTK_LABEL (widget);
2086
2087   (* GTK_WIDGET_CLASS (parent_class)->size_allocate) (widget, allocation);
2088
2089   if (label->ellipsize)
2090     {
2091       if (label->layout)
2092         pango_layout_set_width (label->layout, allocation->width * PANGO_SCALE);
2093     }
2094
2095   if (label->select_info && label->select_info->window)
2096     {
2097       gdk_window_move_resize (label->select_info->window,
2098                               allocation->x,
2099                               allocation->y,
2100                               allocation->width,
2101                               allocation->height);
2102     }
2103 }
2104
2105 static void
2106 gtk_label_state_changed (GtkWidget   *widget,
2107                          GtkStateType prev_state)
2108 {
2109   GtkLabel *label;
2110   
2111   label = GTK_LABEL (widget);
2112
2113   if (label->select_info)
2114     gtk_label_select_region (label, 0, 0);
2115
2116   if (GTK_WIDGET_CLASS (parent_class)->state_changed)
2117     GTK_WIDGET_CLASS (parent_class)->state_changed (widget, prev_state);
2118 }
2119
2120 static void 
2121 gtk_label_style_set (GtkWidget *widget,
2122                      GtkStyle  *previous_style)
2123 {
2124   GtkLabel *label;
2125   
2126   g_return_if_fail (GTK_IS_LABEL (widget));
2127   
2128   label = GTK_LABEL (widget);
2129
2130   /* We have to clear the layout, fonts etc. may have changed */
2131   gtk_label_clear_layout (label);
2132 }
2133
2134 static void 
2135 gtk_label_direction_changed (GtkWidget        *widget,
2136                              GtkTextDirection previous_dir)
2137 {
2138   GtkLabel *label = GTK_LABEL (widget);
2139
2140   if (label->layout)
2141     pango_layout_context_changed (label->layout);
2142
2143   GTK_WIDGET_CLASS (parent_class)->direction_changed (widget, previous_dir);
2144 }
2145
2146 static void
2147 get_layout_location (GtkLabel  *label,
2148                      gint      *xp,
2149                      gint      *yp)
2150 {
2151   GtkMisc *misc;
2152   GtkWidget *widget;
2153   gfloat xalign;
2154   gint req_width, x, y;
2155   
2156   misc = GTK_MISC (label);
2157   widget = GTK_WIDGET (label);
2158   
2159   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2160     xalign = misc->xalign;
2161   else
2162     xalign = 1.0 - misc->xalign;
2163
2164   if (label->ellipsize)
2165     {
2166       PangoRectangle ink_rect;
2167
2168       pango_layout_get_extents (label->layout, &ink_rect, NULL);
2169
2170       req_width = PANGO_PIXELS (ink_rect.width);
2171     }
2172   else
2173     req_width = widget->requisition.width;
2174
2175   x = floor (widget->allocation.x + (gint)misc->xpad +
2176               xalign * (widget->allocation.width - req_width)
2177               + 0.5);
2178
2179   if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2180     x = MAX (x, widget->allocation.x + misc->xpad);
2181   else
2182     x = MIN (x,
2183              widget->allocation.x + widget->allocation.width -
2184              req_width - misc->xpad);
2185
2186   y = floor (widget->allocation.y + (gint)misc->ypad 
2187              + MAX (((widget->allocation.height - widget->requisition.height) * misc->yalign)
2188                     + 0.5, 0));
2189
2190   if (xp)
2191     *xp = x;
2192
2193   if (yp)
2194     *yp = y;
2195 }
2196
2197 static void
2198 draw_insertion_cursor (GtkLabel      *label,
2199                        GdkRectangle  *cursor_location,
2200                        gboolean       is_primary,
2201                        PangoDirection direction,
2202                        gboolean       draw_arrow)
2203 {
2204   GtkWidget *widget = GTK_WIDGET (label);
2205   GtkTextDirection text_dir;
2206
2207   if (direction == PANGO_DIRECTION_LTR)
2208     text_dir = GTK_TEXT_DIR_LTR;
2209   else
2210     text_dir = GTK_TEXT_DIR_RTL;
2211
2212   gtk_draw_insertion_cursor (widget, widget->window, &(widget->allocation),
2213                              cursor_location,
2214                              is_primary, text_dir, draw_arrow);
2215 }
2216
2217 static PangoDirection
2218 get_cursor_direction (GtkLabel *label)
2219 {
2220   GSList *l;
2221
2222   g_assert (label->select_info);
2223
2224   gtk_label_ensure_layout (label);
2225
2226   for (l = pango_layout_get_lines (label->layout); l; l = l->next)
2227     {
2228       PangoLayoutLine *line = l->data;
2229
2230       /* If label->select_info->selection_end is at the very end of
2231        * the line, we don't know if the cursor is on this line or
2232        * the next without looking ahead at the next line. (End
2233        * of paragraph is different from line break.) But it's
2234        * definitely in this paragraph, which is good enough
2235        * to figure out the resolved direction.
2236        */
2237        if (line->start_index + line->length >= label->select_info->selection_end)
2238         return line->resolved_dir;
2239     }
2240
2241   return PANGO_DIRECTION_LTR;
2242 }
2243
2244 static void
2245 gtk_label_draw_cursor (GtkLabel  *label, gint xoffset, gint yoffset)
2246 {
2247   if (label->select_info == NULL)
2248     return;
2249   
2250   if (GTK_WIDGET_DRAWABLE (label))
2251     {
2252       GtkWidget *widget = GTK_WIDGET (label);
2253
2254       PangoDirection keymap_direction;
2255       PangoDirection cursor_direction;
2256       PangoRectangle strong_pos, weak_pos;
2257       gboolean split_cursor;
2258       PangoRectangle *cursor1 = NULL;
2259       PangoRectangle *cursor2 = NULL;
2260       GdkRectangle cursor_location;
2261       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
2262       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
2263
2264       keymap_direction = gdk_keymap_get_direction (gdk_keymap_get_for_display (gtk_widget_get_display (widget)));
2265       cursor_direction = get_cursor_direction (label);
2266
2267       gtk_label_ensure_layout (label);
2268       
2269       pango_layout_get_cursor_pos (label->layout, label->select_info->selection_end,
2270                                    &strong_pos, &weak_pos);
2271
2272       g_object_get (gtk_widget_get_settings (widget),
2273                     "gtk-split-cursor", &split_cursor,
2274                     NULL);
2275
2276       dir1 = cursor_direction;
2277       
2278       if (split_cursor)
2279         {
2280           cursor1 = &strong_pos;
2281
2282           if (strong_pos.x != weak_pos.x ||
2283               strong_pos.y != weak_pos.y)
2284             {
2285               dir2 = (cursor_direction == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
2286               cursor2 = &weak_pos;
2287             }
2288         }
2289       else
2290         {
2291           if (keymap_direction == cursor_direction)
2292             cursor1 = &strong_pos;
2293           else
2294             cursor1 = &weak_pos;
2295         }
2296       
2297       cursor_location.x = xoffset + PANGO_PIXELS (cursor1->x);
2298       cursor_location.y = yoffset + PANGO_PIXELS (cursor1->y);
2299       cursor_location.width = 0;
2300       cursor_location.height = PANGO_PIXELS (cursor1->height);
2301
2302       draw_insertion_cursor (label,
2303                              &cursor_location, TRUE, dir1,
2304                              dir2 != PANGO_DIRECTION_NEUTRAL);
2305       
2306       if (dir2 != PANGO_DIRECTION_NEUTRAL)
2307         {
2308           cursor_location.x = xoffset + PANGO_PIXELS (cursor2->x);
2309           cursor_location.y = yoffset + PANGO_PIXELS (cursor2->y);
2310           cursor_location.width = 0;
2311           cursor_location.height = PANGO_PIXELS (cursor2->height);
2312
2313           draw_insertion_cursor (label,
2314                                  &cursor_location, FALSE, dir2,
2315                                  TRUE);
2316         }
2317     }
2318 }
2319
2320
2321 static gint
2322 gtk_label_expose (GtkWidget      *widget,
2323                   GdkEventExpose *event)
2324 {
2325   GtkLabel *label;
2326   gint x, y;
2327   
2328   g_return_val_if_fail (GTK_IS_LABEL (widget), FALSE);
2329   g_return_val_if_fail (event != NULL, FALSE);
2330   
2331   label = GTK_LABEL (widget);
2332
2333   gtk_label_ensure_layout (label);
2334   
2335   if (GTK_WIDGET_VISIBLE (widget) && GTK_WIDGET_MAPPED (widget) &&
2336       label->text && (*label->text != '\0'))
2337     {
2338       get_layout_location (label, &x, &y);
2339
2340       gtk_paint_layout (widget->style,
2341                         widget->window,
2342                         GTK_WIDGET_STATE (widget),
2343                         FALSE,
2344                         &event->area,
2345                         widget,
2346                         "label",
2347                         x, y,
2348                         label->layout);
2349       
2350       if (label->select_info &&
2351           (label->select_info->selection_anchor !=
2352            label->select_info->selection_end))
2353         {
2354           gint range[2];
2355           GdkRegion *clip;
2356           GtkStateType state;
2357           
2358           range[0] = label->select_info->selection_anchor;
2359           range[1] = label->select_info->selection_end;
2360
2361           if (range[0] > range[1])
2362             {
2363               gint tmp = range[0];
2364               range[0] = range[1];
2365               range[1] = tmp;
2366             }
2367
2368           clip = gdk_pango_layout_get_clip_region (label->layout,
2369                                                    x, y,
2370                                                    range,
2371                                                    1);
2372           gdk_region_intersect (clip, event->region);
2373  
2374          /* FIXME should use gtk_paint, but it can't use a clip
2375            * region
2376            */
2377
2378           gdk_gc_set_clip_region (widget->style->black_gc, clip);
2379
2380
2381           state = GTK_STATE_SELECTED;
2382           if (!GTK_WIDGET_HAS_FOCUS (widget))
2383             state = GTK_STATE_ACTIVE;
2384               
2385           gdk_draw_layout_with_colors (widget->window,
2386                                        widget->style->black_gc,
2387                                        x, y,
2388                                        label->layout,
2389                                        &widget->style->text[state],
2390                                        &widget->style->base[state]);
2391
2392           gdk_gc_set_clip_region (widget->style->black_gc, NULL);
2393           gdk_region_destroy (clip);
2394         }
2395       else if (label->select_info && GTK_WIDGET_HAS_FOCUS (widget))
2396         gtk_label_draw_cursor (label, x, y);
2397     }
2398
2399   return FALSE;
2400 }
2401
2402 static void
2403 gtk_label_set_uline_text_internal (GtkLabel    *label,
2404                                    const gchar *str)
2405 {
2406   guint accel_key = GDK_VoidSymbol;
2407
2408   gchar *new_str;
2409   gchar *pattern;
2410   const gchar *src;
2411   gchar *dest, *pattern_dest;
2412   gboolean underscore;
2413       
2414   g_return_if_fail (GTK_IS_LABEL (label));
2415   g_return_if_fail (str != NULL);
2416
2417   /* Split text into the base text and a separate pattern
2418    * of underscores.
2419    */
2420   
2421   new_str = g_new (gchar, strlen (str) + 1);
2422   pattern = g_new (gchar, g_utf8_strlen (str, -1) + 1);
2423   
2424   underscore = FALSE;
2425
2426   if (str == NULL)
2427     str = "";
2428   
2429   src = str;
2430   dest = new_str;
2431   pattern_dest = pattern;
2432   
2433   while (*src)
2434     {
2435       gunichar c;
2436       gchar *next_src;
2437
2438       c = g_utf8_get_char (src);
2439       if (c == (gunichar)-1)
2440         {
2441           g_warning ("Invalid input string");
2442           g_free (new_str);
2443           g_free (pattern);
2444           return;
2445         }
2446       next_src = g_utf8_next_char (src);
2447       
2448       if (underscore)
2449         {
2450           if (c == '_')
2451             *pattern_dest++ = ' ';
2452           else
2453             {
2454               *pattern_dest++ = '_';
2455               if (accel_key == GDK_VoidSymbol)
2456                 accel_key = gdk_keyval_to_lower (gdk_unicode_to_keyval (c));
2457             }
2458
2459           while (src < next_src)
2460             *dest++ = *src++;
2461           
2462           underscore = FALSE;
2463         }
2464       else
2465         {
2466           if (c == '_')
2467             {
2468               underscore = TRUE;
2469               src = next_src;
2470             }
2471           else
2472             {
2473               while (src < next_src)
2474                 *dest++ = *src++;
2475           
2476               *pattern_dest++ = ' ';
2477             }
2478         }
2479     }
2480   *dest = 0;
2481   *pattern_dest = 0;
2482   
2483   gtk_label_set_text_internal (label, new_str);
2484   gtk_label_set_pattern_internal (label, pattern);
2485   
2486   g_free (pattern);
2487
2488   label->mnemonic_keyval = accel_key;
2489 }
2490
2491 guint      
2492 gtk_label_parse_uline (GtkLabel    *label,
2493                        const gchar *str)
2494 {
2495   guint keyval;
2496   guint orig_keyval;
2497   
2498   g_return_val_if_fail (GTK_IS_LABEL (label), GDK_VoidSymbol);
2499   g_return_val_if_fail (str != NULL, GDK_VoidSymbol);
2500
2501   orig_keyval = label->mnemonic_keyval;
2502
2503   g_object_freeze_notify (G_OBJECT (label));
2504   
2505   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2506   gtk_label_set_use_markup_internal (label, FALSE);
2507   gtk_label_set_use_underline_internal (label, TRUE);
2508   
2509   gtk_label_recalculate (label);
2510
2511   keyval = label->mnemonic_keyval;
2512   label->mnemonic_keyval = GDK_VoidSymbol;
2513   
2514   gtk_label_setup_mnemonic (label, orig_keyval);
2515   
2516   g_object_thaw_notify (G_OBJECT (label));
2517
2518   return keyval;
2519 }
2520
2521 /**
2522  * gtk_label_set_text_with_mnemonic:
2523  * @label: a #GtkLabel
2524  * @str: a string
2525  * 
2526  * Sets the label's text from the string @str.
2527  * If characters in @str are preceded by an underscore, they are underlined
2528  * indicating that they represent a keyboard accelerator called a mnemonic.
2529  * The mnemonic key can be used to activate another widget, chosen automatically,
2530  * or explicitly using gtk_label_set_mnemonic_widget().
2531  **/
2532 void
2533 gtk_label_set_text_with_mnemonic (GtkLabel    *label,
2534                                   const gchar *str)
2535 {
2536   guint last_keyval;
2537   
2538   g_return_if_fail (GTK_IS_LABEL (label));
2539   g_return_if_fail (str != NULL);
2540
2541   last_keyval = label->mnemonic_keyval;
2542
2543   g_object_freeze_notify (G_OBJECT (label));
2544
2545   gtk_label_set_label_internal (label, g_strdup (str ? str : ""));
2546   gtk_label_set_use_markup_internal (label, FALSE);
2547   gtk_label_set_use_underline_internal (label, TRUE);
2548   
2549   gtk_label_recalculate (label);
2550
2551   gtk_label_setup_mnemonic (label, last_keyval);
2552
2553   g_object_thaw_notify (G_OBJECT (label));
2554 }
2555
2556 static void
2557 gtk_label_realize (GtkWidget *widget)
2558 {
2559   GtkLabel *label;
2560
2561   label = GTK_LABEL (widget);
2562   
2563   (* GTK_WIDGET_CLASS (parent_class)->realize) (widget);
2564
2565   if (label->select_info)
2566     gtk_label_create_window (label);
2567 }
2568
2569 static void
2570 gtk_label_unrealize (GtkWidget *widget)
2571 {
2572   GtkLabel *label;
2573
2574   label = GTK_LABEL (widget);
2575
2576   if (label->select_info)
2577     gtk_label_destroy_window (label);
2578   
2579   (* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
2580 }
2581
2582 static void
2583 gtk_label_map (GtkWidget *widget)
2584 {
2585   GtkLabel *label;
2586
2587   label = GTK_LABEL (widget);
2588   
2589   (* GTK_WIDGET_CLASS (parent_class)->map) (widget);
2590   
2591   if (label->select_info)
2592     gdk_window_show (label->select_info->window);
2593 }
2594
2595 static void
2596 gtk_label_unmap (GtkWidget *widget)
2597 {
2598   GtkLabel *label;
2599
2600   label = GTK_LABEL (widget);
2601
2602   if (label->select_info)
2603     gdk_window_hide (label->select_info->window);
2604   
2605   (* GTK_WIDGET_CLASS (parent_class)->unmap) (widget);
2606 }
2607
2608 static void
2609 window_to_layout_coords (GtkLabel *label,
2610                          gint     *x,
2611                          gint     *y)
2612 {
2613   gint lx, ly;
2614   GtkWidget *widget;
2615
2616   widget = GTK_WIDGET (label);
2617   
2618   /* get layout location in widget->window coords */
2619   get_layout_location (label, &lx, &ly);
2620   
2621   if (x)
2622     {
2623       *x += widget->allocation.x; /* go to widget->window */
2624       *x -= lx;                   /* go to layout */
2625     }
2626
2627   if (y)
2628     {
2629       *y += widget->allocation.y; /* go to widget->window */
2630       *y -= ly;                   /* go to layout */
2631     }
2632 }
2633
2634 #if 0
2635 static void
2636 layout_to_window_coords (GtkLabel *label,
2637                          gint     *x,
2638                          gint     *y)
2639 {
2640   gint lx, ly;
2641   GtkWidget *widget;
2642
2643   widget = GTK_WIDGET (label);
2644   
2645   /* get layout location in widget->window coords */
2646   get_layout_location (label, &lx, &ly);
2647   
2648   if (x)
2649     {
2650       *x += lx;                   /* go to widget->window */
2651       *x -= widget->allocation.x; /* go to selection window */
2652     }
2653
2654   if (y)
2655     {
2656       *y += ly;                   /* go to widget->window */
2657       *y -= widget->allocation.y; /* go to selection window */
2658     }
2659 }
2660 #endif
2661
2662 static void
2663 get_layout_index (GtkLabel *label,
2664                   gint      x,
2665                   gint      y,
2666                   gint     *index)
2667 {
2668   gint trailing = 0;
2669   const gchar *cluster;
2670   const gchar *cluster_end;
2671
2672   *index = 0;
2673   
2674   gtk_label_ensure_layout (label);
2675   
2676   window_to_layout_coords (label, &x, &y);
2677
2678   x *= PANGO_SCALE;
2679   y *= PANGO_SCALE;
2680   
2681   pango_layout_xy_to_index (label->layout,
2682                             x, y,
2683                             index, &trailing);
2684
2685   
2686   cluster = label->text + *index;
2687   cluster_end = cluster;
2688   while (trailing)
2689     {
2690       cluster_end = g_utf8_next_char (cluster_end);
2691       --trailing;
2692     }
2693
2694   *index += (cluster_end - cluster);
2695 }
2696
2697 static void
2698 gtk_label_select_word (GtkLabel *label)
2699 {
2700   gint min, max;
2701   
2702   gint start_index = gtk_label_move_backward_word (label, label->select_info->selection_end);
2703   gint end_index = gtk_label_move_forward_word (label, label->select_info->selection_end);
2704
2705   min = MIN (label->select_info->selection_anchor,
2706              label->select_info->selection_end);
2707   max = MAX (label->select_info->selection_anchor,
2708              label->select_info->selection_end);
2709
2710   min = MIN (min, start_index);
2711   max = MAX (max, end_index);
2712
2713   gtk_label_select_region_index (label, min, max);
2714 }
2715
2716 static gboolean
2717 gtk_label_button_press (GtkWidget      *widget,
2718                         GdkEventButton *event)
2719 {
2720   GtkLabel *label;
2721   gint index = 0;
2722   gint min, max;  
2723   
2724   label = GTK_LABEL (widget);
2725
2726   if (label->select_info == NULL)
2727     return FALSE;
2728
2729   label->select_info->in_drag = FALSE;
2730   if (event->button == 1)
2731     {
2732       if (!GTK_WIDGET_HAS_FOCUS (widget))
2733         gtk_widget_grab_focus (widget);
2734
2735       if (event->type == GDK_3BUTTON_PRESS)
2736         {
2737           gtk_label_select_region_index (label, 0, strlen (label->text));
2738           return TRUE;
2739         }
2740       
2741       if (event->type == GDK_2BUTTON_PRESS)
2742         {
2743           gtk_label_select_word (label);
2744           return TRUE;
2745         }
2746       
2747       get_layout_index (label, event->x, event->y, &index);
2748       
2749       min = MIN (label->select_info->selection_anchor,
2750                  label->select_info->selection_end);
2751       max = MAX (label->select_info->selection_anchor,
2752                  label->select_info->selection_end);
2753           
2754       if ((label->select_info->selection_anchor !=
2755            label->select_info->selection_end) &&
2756           (event->state & GDK_SHIFT_MASK))
2757         {
2758           /* extend (same as motion) */
2759           min = MIN (min, index);
2760           max = MAX (max, index);
2761           
2762           /* ensure the anchor is opposite index */
2763           if (index == min)
2764             {
2765               gint tmp = min;
2766               min = max;
2767               max = tmp;
2768             }
2769           
2770           gtk_label_select_region_index (label, min, max);
2771         }
2772       else 
2773         {
2774           if (event->type == GDK_3BUTTON_PRESS)
2775             gtk_label_select_region_index (label, 0, strlen (label->text));
2776           else if (event->type == GDK_2BUTTON_PRESS)
2777             gtk_label_select_word (label);
2778           else if (min < max && min <= index && index <= max)
2779             {
2780               label->select_info->in_drag = TRUE;
2781               label->select_info->drag_start_x = event->x;
2782               label->select_info->drag_start_y = event->y;
2783             }
2784           else
2785             /* start a replacement */
2786             gtk_label_select_region_index (label, index, index);
2787         }
2788   
2789       return TRUE;
2790     }
2791   else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
2792     {
2793       gtk_label_do_popup (label, event);
2794
2795       return TRUE;
2796       
2797     }
2798   return FALSE;
2799 }
2800
2801 static gboolean
2802 gtk_label_button_release (GtkWidget      *widget,
2803                           GdkEventButton *event)
2804
2805 {
2806   GtkLabel *label = GTK_LABEL (widget);
2807   gint index;
2808   
2809   if (label->select_info == NULL)
2810     return FALSE;
2811   
2812   if (label->select_info->in_drag)
2813     {
2814       label->select_info->in_drag = 0;
2815
2816       get_layout_index (label, event->x, event->y, &index);
2817       gtk_label_select_region_index (label, index, index);
2818       
2819       return FALSE;
2820     }
2821
2822   if (event->button != 1)
2823     return FALSE;
2824   
2825   /* The goal here is to return TRUE iff we ate the
2826    * button press to start selecting.
2827    */
2828   
2829   return TRUE;
2830 }
2831
2832 static gboolean
2833 gtk_label_motion (GtkWidget      *widget,
2834                   GdkEventMotion *event)
2835 {
2836   GtkLabel *label;
2837   gint index;
2838   gint x, y;
2839   
2840   label = GTK_LABEL (widget);
2841   
2842   if (label->select_info == NULL)
2843     return FALSE;  
2844
2845
2846   if ((event->state & GDK_BUTTON1_MASK) == 0)
2847     return FALSE;
2848
2849   gdk_window_get_pointer (label->select_info->window,
2850                           &x, &y, NULL);
2851   
2852   if (label->select_info->in_drag)
2853     {
2854       if (gtk_drag_check_threshold (widget,
2855                                     label->select_info->drag_start_x, 
2856                                     label->select_info->drag_start_y,
2857                                     event->x, event->y))
2858         {
2859           GdkDragContext *context;
2860           GtkTargetList *target_list = gtk_target_list_new (NULL, 0);
2861
2862           gtk_target_list_add_text_targets (target_list, 0);
2863
2864           context = gtk_drag_begin (widget, target_list, 
2865                                     GDK_ACTION_COPY,
2866                                     1, (GdkEvent *)event);
2867
2868           
2869           label->select_info->in_drag = FALSE;
2870           
2871           gtk_target_list_unref (target_list);
2872           gtk_drag_set_icon_default (context);
2873         }
2874     }
2875   else
2876     {
2877       get_layout_index (label, x, y, &index);
2878       
2879       gtk_label_select_region_index (label,
2880                                      label->select_info->selection_anchor,
2881                                      index);
2882     }
2883
2884   return TRUE;
2885 }
2886
2887 static void
2888 gtk_label_create_window (GtkLabel *label)
2889 {
2890   GtkWidget *widget;
2891   GdkWindowAttr attributes;
2892   gint attributes_mask;
2893   
2894   g_assert (label->select_info);
2895   g_assert (GTK_WIDGET_REALIZED (label));
2896   
2897   if (label->select_info->window)
2898     return;
2899   
2900   widget = GTK_WIDGET (label);
2901
2902   attributes.x = widget->allocation.x;
2903   attributes.y = widget->allocation.y;
2904   attributes.width = widget->allocation.width;
2905   attributes.height = widget->allocation.height;
2906   attributes.window_type = GDK_WINDOW_TEMP;
2907   attributes.wclass = GDK_INPUT_ONLY;
2908   attributes.override_redirect = TRUE;
2909   attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget),
2910                                                   GDK_XTERM);
2911   attributes.event_mask = gtk_widget_get_events (widget) |
2912     GDK_BUTTON_PRESS_MASK        |
2913     GDK_BUTTON_RELEASE_MASK      |
2914     GDK_BUTTON_MOTION_MASK;
2915
2916   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_NOREDIR | GDK_WA_CURSOR;
2917
2918   label->select_info->window = gdk_window_new (widget->window,
2919                                                &attributes, attributes_mask);
2920   gdk_window_set_user_data (label->select_info->window, widget);
2921
2922   gdk_cursor_unref (attributes.cursor);
2923 }
2924
2925 static void
2926 gtk_label_destroy_window (GtkLabel *label)
2927 {
2928   g_assert (label->select_info);
2929
2930   if (label->select_info->window == NULL)
2931     return;
2932   
2933   gdk_window_set_user_data (label->select_info->window, NULL);
2934   gdk_window_destroy (label->select_info->window);
2935   label->select_info->window = NULL;
2936 }
2937
2938 /**
2939  * gtk_label_set_selectable:
2940  * @label: a #GtkLabel
2941  * @setting: %TRUE to allow selecting text in the label
2942  *
2943  * Selectable labels allow the user to select text from the label, for
2944  * copy-and-paste.
2945  * 
2946  **/
2947 void
2948 gtk_label_set_selectable (GtkLabel *label,
2949                           gboolean  setting)
2950 {
2951   gboolean old_setting;
2952   
2953   g_return_if_fail (GTK_IS_LABEL (label));
2954   
2955   setting = setting != FALSE;
2956   old_setting = label->select_info != NULL;
2957   
2958   if (setting)
2959     {
2960       if (label->select_info == NULL)
2961         {
2962           label->select_info = g_new0 (GtkLabelSelectionInfo, 1);
2963
2964           GTK_WIDGET_SET_FLAGS (label, GTK_CAN_FOCUS);
2965       
2966           if (GTK_WIDGET_REALIZED (label))
2967             gtk_label_create_window (label);
2968
2969           if (GTK_WIDGET_MAPPED (label))
2970             gdk_window_show (label->select_info->window);
2971         }
2972     }
2973   else
2974     {
2975       if (label->select_info)
2976         {
2977           /* unselect, to give up the selection */
2978           gtk_label_select_region (label, 0, 0);
2979           
2980           if (label->select_info->window)
2981             {
2982               gtk_label_destroy_window (label);
2983             }
2984
2985           g_free (label->select_info);
2986
2987           label->select_info = NULL;
2988
2989           GTK_WIDGET_UNSET_FLAGS (label, GTK_CAN_FOCUS);
2990         }
2991     }
2992   if (setting != old_setting)
2993     {
2994       g_object_freeze_notify (G_OBJECT (label));
2995       g_object_notify (G_OBJECT (label), "selectable");
2996       g_object_notify (G_OBJECT (label), "cursor_position");
2997       g_object_notify (G_OBJECT (label), "selection_bound");
2998       g_object_thaw_notify (G_OBJECT (label));
2999       gtk_widget_queue_draw (GTK_WIDGET (label));
3000     }
3001 }
3002
3003 /**
3004  * gtk_label_get_selectable:
3005  * @label: a #GtkLabel
3006  * 
3007  * Gets the value set by gtk_label_set_selectable().
3008  * 
3009  * Return value: %TRUE if the user can copy text from the label
3010  **/
3011 gboolean
3012 gtk_label_get_selectable (GtkLabel *label)
3013 {
3014   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3015
3016   return label->select_info != NULL;
3017 }
3018
3019 /**
3020  * gtk_label_set_angle:
3021  * @label: a #GtkLabel
3022  * @angle: the angle that the baseline of the label makes with
3023  *   the horizontal, in degrees, measured counterclockwise
3024  * 
3025  * Sets the angle of rotation for the label. An angle of 90 reads from
3026  * from bottom to top, an angle of 270, from top to bottom. The angle
3027  * setting for the label is ignored if the label is selectable,
3028  * wrapped, or ellipsized.
3029  *
3030  * Since: 2.6
3031  **/
3032 void
3033 gtk_label_set_angle (GtkLabel *label,
3034                      gdouble   angle)
3035 {
3036   GtkLabelPrivate *priv;
3037
3038   g_return_if_fail (GTK_IS_LABEL (label));
3039
3040   priv = GTK_LABEL_GET_PRIVATE (label);
3041
3042   /* Canonicalize to [0,360]. We don't canonicalize 360 to 0, because
3043    * double property ranges are inclusive, and changing 360 to 0 would
3044    * make a property editor behave strangely.
3045    */
3046   if (angle < 0 || angle > 360.0)
3047     angle = angle - 360. * floor (angle / 360.);
3048
3049   if (angle != priv->angle)
3050     {
3051       priv->angle = angle;
3052       
3053       gtk_label_clear_layout (label);
3054       gtk_widget_queue_resize (GTK_WIDGET (label));
3055
3056       g_object_notify (G_OBJECT (label), "angle");
3057     }
3058 }
3059
3060 /**
3061  * gtk_label_get_angle:
3062  * @label: a #GtkLabel
3063  * 
3064  * Gets the angle of rotation for the label. See
3065  * gtk_label_set_angle.
3066  * 
3067  * Return value: the angle of rotation for the label
3068  *
3069  * Since: 2.6
3070  **/
3071 gdouble
3072 gtk_label_get_angle  (GtkLabel *label)
3073 {
3074   GtkLabelPrivate *priv;
3075
3076   g_return_val_if_fail (GTK_IS_LABEL (label), 0.0);
3077
3078   priv = GTK_LABEL_GET_PRIVATE (label);
3079
3080   return priv->angle;
3081 }
3082
3083 static void
3084 gtk_label_set_selection_text (GtkLabel         *label,
3085                               GtkSelectionData *selection_data)
3086 {
3087   if ((label->select_info->selection_anchor !=
3088        label->select_info->selection_end) &&
3089       label->text)
3090     {
3091       gint start, end;
3092       gint len;
3093       
3094       start = MIN (label->select_info->selection_anchor,
3095                    label->select_info->selection_end);
3096       end = MAX (label->select_info->selection_anchor,
3097                  label->select_info->selection_end);
3098       
3099       len = strlen (label->text);
3100       
3101       if (end > len)
3102         end = len;
3103       
3104       if (start > len)
3105         start = len;
3106       
3107       gtk_selection_data_set_text (selection_data,
3108                                    label->text + start,
3109                                    end - start);
3110     }
3111 }
3112
3113 static void
3114 gtk_label_drag_data_get (GtkWidget        *widget,
3115                          GdkDragContext   *context,
3116                          GtkSelectionData *selection_data,
3117                          guint             info,
3118                          guint             time)
3119 {
3120   gtk_label_set_selection_text (GTK_LABEL (widget), selection_data);
3121 }
3122
3123 static void
3124 get_text_callback (GtkClipboard     *clipboard,
3125                    GtkSelectionData *selection_data,
3126                    guint             info,
3127                    gpointer          user_data_or_owner)
3128 {
3129   gtk_label_set_selection_text (GTK_LABEL (user_data_or_owner), selection_data);
3130 }
3131
3132 static void
3133 clear_text_callback (GtkClipboard     *clipboard,
3134                      gpointer          user_data_or_owner)
3135 {
3136   GtkLabel *label;
3137
3138   label = GTK_LABEL (user_data_or_owner);
3139
3140   if (label->select_info)
3141     {
3142       label->select_info->selection_anchor = label->select_info->selection_end;
3143       
3144       gtk_widget_queue_draw (GTK_WIDGET (label));
3145     }
3146 }
3147
3148 static void
3149 gtk_label_select_region_index (GtkLabel *label,
3150                                gint      anchor_index,
3151                                gint      end_index)
3152 {
3153   static const GtkTargetEntry targets[] = {
3154     { "STRING", 0, 0 },
3155     { "TEXT",   0, 0 }, 
3156     { "COMPOUND_TEXT", 0, 0 },
3157     { "UTF8_STRING", 0, 0 }
3158   };
3159
3160   g_return_if_fail (GTK_IS_LABEL (label));
3161   
3162   if (label->select_info)
3163     {
3164       GtkClipboard *clipboard;
3165
3166       if (label->select_info->selection_anchor == anchor_index &&
3167           label->select_info->selection_end == end_index)
3168         return;
3169
3170       label->select_info->selection_anchor = anchor_index;
3171       label->select_info->selection_end = end_index;
3172
3173       clipboard = gtk_widget_get_clipboard (GTK_WIDGET (label),
3174                                             GDK_SELECTION_PRIMARY);      
3175       
3176       if (anchor_index != end_index)
3177         {
3178           gtk_clipboard_set_with_owner (clipboard,
3179                                         targets,
3180                                         G_N_ELEMENTS (targets),
3181                                         get_text_callback,
3182                                         clear_text_callback,
3183                                         G_OBJECT (label));
3184         }
3185       else
3186         {
3187           if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (label))
3188             gtk_clipboard_clear (clipboard);
3189         }
3190
3191       gtk_widget_queue_draw (GTK_WIDGET (label));
3192
3193       g_object_freeze_notify (G_OBJECT (label));
3194       g_object_notify (G_OBJECT (label), "cursor_position");
3195       g_object_notify (G_OBJECT (label), "selection_bound");
3196       g_object_thaw_notify (G_OBJECT (label));
3197     }
3198 }
3199
3200 /**
3201  * gtk_label_select_region:
3202  * @label: a #GtkLabel
3203  * @start_offset: start offset (in characters not bytes)
3204  * @end_offset: end offset (in characters not bytes)
3205  *
3206  * Selects a range of characters in the label, if the label is selectable.
3207  * See gtk_label_set_selectable(). If the label is not selectable,
3208  * this function has no effect. If @start_offset or
3209  * @end_offset are -1, then the end of the label will be substituted.
3210  * 
3211  **/
3212 void
3213 gtk_label_select_region  (GtkLabel *label,
3214                           gint      start_offset,
3215                           gint      end_offset)
3216 {
3217   g_return_if_fail (GTK_IS_LABEL (label));
3218   
3219   if (label->text && label->select_info)
3220     {
3221       if (start_offset < 0)
3222         start_offset = g_utf8_strlen (label->text, -1);
3223       
3224       if (end_offset < 0)
3225         end_offset = g_utf8_strlen (label->text, -1);
3226       
3227       gtk_label_select_region_index (label,
3228                                      g_utf8_offset_to_pointer (label->text, start_offset) - label->text,
3229                                      g_utf8_offset_to_pointer (label->text, end_offset) - label->text);
3230     }
3231 }
3232
3233 /**
3234  * gtk_label_get_selection_bounds:
3235  * @label: a #GtkLabel
3236  * @start: return location for start of selection, as a character offset
3237  * @end: return location for end of selection, as a character offset
3238  * 
3239  * Gets the selected range of characters in the label, returning %TRUE
3240  * if there's a selection.
3241  * 
3242  * Return value: %TRUE if selection is non-empty
3243  **/
3244 gboolean
3245 gtk_label_get_selection_bounds (GtkLabel  *label,
3246                                 gint      *start,
3247                                 gint      *end)
3248 {
3249   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3250
3251   if (label->select_info == NULL)
3252     {
3253       /* not a selectable label */
3254       if (start)
3255         *start = 0;
3256       if (end)
3257         *end = 0;
3258
3259       return FALSE;
3260     }
3261   else
3262     {
3263       gint start_index, end_index;
3264       gint start_offset, end_offset;
3265       gint len;
3266       
3267       start_index = MIN (label->select_info->selection_anchor,
3268                    label->select_info->selection_end);
3269       end_index = MAX (label->select_info->selection_anchor,
3270                  label->select_info->selection_end);
3271
3272       len = strlen (label->text);
3273
3274       if (end_index > len)
3275         end_index = len;
3276
3277       if (start_index > len)
3278         start_index = len;
3279       
3280       start_offset = g_utf8_strlen (label->text, start_index);
3281       end_offset = g_utf8_strlen (label->text, end_index);
3282
3283       if (start_offset > end_offset)
3284         {
3285           gint tmp = start_offset;
3286           start_offset = end_offset;
3287           end_offset = tmp;
3288         }
3289       
3290       if (start)
3291         *start = start_offset;
3292
3293       if (end)
3294         *end = end_offset;
3295
3296       return start_offset != end_offset;
3297     }
3298 }
3299
3300
3301 /**
3302  * gtk_label_get_layout:
3303  * @label: a #GtkLabel
3304  * 
3305  * Gets the #PangoLayout used to display the label.
3306  * The layout is useful to e.g. convert text positions to
3307  * pixel positions, in combination with gtk_label_get_layout_offsets().
3308  * The returned layout is owned by the label so need not be
3309  * freed by the caller.
3310  * 
3311  * Return value: the #PangoLayout for this label
3312  **/
3313 PangoLayout*
3314 gtk_label_get_layout (GtkLabel *label)
3315 {
3316   g_return_val_if_fail (GTK_IS_LABEL (label), NULL);
3317
3318   gtk_label_ensure_layout (label);
3319
3320   return label->layout;
3321 }
3322
3323 /**
3324  * gtk_label_get_layout_offsets:
3325  * @label: a #GtkLabel
3326  * @x: location to store X offset of layout, or %NULL
3327  * @y: location to store Y offset of layout, or %NULL
3328  *
3329  * Obtains the coordinates where the label will draw the #PangoLayout
3330  * representing the text in the label; useful to convert mouse events
3331  * into coordinates inside the #PangoLayout, e.g. to take some action
3332  * if some part of the label is clicked. Of course you will need to
3333  * create a #GtkEventBox to receive the events, and pack the label
3334  * inside it, since labels are a #GTK_NO_WINDOW widget. Remember
3335  * when using the #PangoLayout functions you need to convert to
3336  * and from pixels using PANGO_PIXELS() or #PANGO_SCALE.
3337  * 
3338  **/
3339 void
3340 gtk_label_get_layout_offsets (GtkLabel *label,
3341                               gint     *x,
3342                               gint     *y)
3343 {
3344   g_return_if_fail (GTK_IS_LABEL (label));
3345   
3346   get_layout_location (label, x, y);
3347 }
3348
3349 /**
3350  * gtk_label_set_use_markup:
3351  * @label: a #GtkLabel
3352  * @setting: %TRUE if the label's text should be parsed for markup.
3353  *
3354  * Sets whether the text of the label contains markup in <link
3355  * linkend="PangoMarkupFormat">Pango's text markup
3356  * language</link>. See gtk_label_set_markup().
3357  **/
3358 void
3359 gtk_label_set_use_markup (GtkLabel *label,
3360                           gboolean  setting)
3361 {
3362   g_return_if_fail (GTK_IS_LABEL (label));
3363
3364   gtk_label_set_use_markup_internal (label, setting);
3365   gtk_label_recalculate (label);
3366 }
3367
3368 /**
3369  * gtk_label_get_use_markup:
3370  * @label: a #GtkLabel
3371  *
3372  * Returns whether the label's text is interpreted as marked up with
3373  * the <link linkend="PangoMarkupFormat">Pango text markup
3374  * language</link>. See gtk_label_set_use_markup ().
3375  *
3376  * Return value: %TRUE if the label's text will be parsed for markup.
3377  **/
3378 gboolean
3379 gtk_label_get_use_markup (GtkLabel *label)
3380 {
3381   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3382   
3383   return label->use_markup;
3384 }
3385
3386 /**
3387  * gtk_label_set_use_underline:
3388  * @label: a #GtkLabel
3389  * @setting: %TRUE if underlines in the text indicate mnemonics
3390  *
3391  * If true, an underline in the text indicates the next character should be
3392  * used for the mnemonic accelerator key.
3393  */
3394 void
3395 gtk_label_set_use_underline (GtkLabel *label,
3396                              gboolean  setting)
3397 {
3398   g_return_if_fail (GTK_IS_LABEL (label));
3399
3400   gtk_label_set_use_underline_internal (label, setting);
3401   gtk_label_recalculate (label);
3402   if (label->use_underline)
3403     gtk_label_setup_mnemonic (label, label->mnemonic_keyval);
3404 }
3405
3406 /**
3407  * gtk_label_get_use_underline:
3408  * @label: a #GtkLabel
3409  *
3410  * Returns whether an embedded underline in the label indicates a
3411  * mnemonic. See gtk_label_set_use_underline ().
3412  *
3413  * Return value: %TRUE whether an embedded underline in the label indicates
3414  *               the mnemonic accelerator keys.
3415  **/
3416 gboolean
3417 gtk_label_get_use_underline (GtkLabel *label)
3418 {
3419   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3420   
3421   return label->use_underline;
3422 }
3423
3424 /**
3425  * gtk_label_set_single_line_mode:
3426  * @label: a #GtkLabel
3427  * @single_line_mode: %TRUE if the label should be in single line mode
3428  *
3429  * Sets whether the label is in single line mode.
3430  *
3431  * Since: 2.6
3432  */
3433 void
3434 gtk_label_set_single_line_mode (GtkLabel *label,
3435                                 gboolean single_line_mode)
3436 {
3437   GtkLabelPrivate *priv;
3438
3439   g_return_if_fail (GTK_IS_LABEL (label));
3440
3441   single_line_mode = single_line_mode != FALSE;
3442
3443   priv = GTK_LABEL_GET_PRIVATE (label);
3444   if (priv->single_line_mode != single_line_mode)
3445     {
3446       priv->single_line_mode = single_line_mode;
3447
3448       gtk_label_clear_layout (label);
3449       gtk_widget_queue_resize (GTK_WIDGET (label));
3450
3451       g_object_notify (G_OBJECT (label), "single-line-mode");
3452     }
3453 }
3454
3455 /**
3456  * gtk_label_get_single_line_mode:
3457  * @label: a #GtkLabel
3458  *
3459  * Returns whether the label is in single line mode.
3460  *
3461  * Return value: %TRUE when the label is in single line mode.
3462  *
3463  * Since: 2.6
3464  **/
3465 gboolean
3466 gtk_label_get_single_line_mode  (GtkLabel *label)
3467 {
3468   GtkLabelPrivate *priv;
3469
3470   g_return_val_if_fail (GTK_IS_LABEL (label), FALSE);
3471
3472   priv = GTK_LABEL_GET_PRIVATE (label);
3473
3474   return priv->single_line_mode;
3475 }
3476
3477 /* Compute the X position for an offset that corresponds to the "more important
3478  * cursor position for that offset. We use this when trying to guess to which
3479  * end of the selection we should go to when the user hits the left or
3480  * right arrow key.
3481  */
3482 static void
3483 get_better_cursor (GtkLabel *label,
3484                    gint      index,
3485                    gint      *x,
3486                    gint      *y)
3487 {
3488   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
3489   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3490   PangoDirection cursor_direction = get_cursor_direction (label);
3491   gboolean split_cursor;
3492   PangoRectangle strong_pos, weak_pos;
3493   
3494   g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
3495                 "gtk-split-cursor", &split_cursor,
3496                 NULL);
3497
3498   gtk_label_ensure_layout (label);
3499   
3500   pango_layout_get_cursor_pos (label->layout, index,
3501                                &strong_pos, &weak_pos);
3502
3503   if (split_cursor)
3504     {
3505       *x = strong_pos.x / PANGO_SCALE;
3506       *y = strong_pos.y / PANGO_SCALE;
3507     }
3508   else
3509     {
3510       if (keymap_direction == cursor_direction)
3511         {
3512           *x = strong_pos.x / PANGO_SCALE;
3513           *y = strong_pos.y / PANGO_SCALE;
3514         }
3515       else
3516         {
3517           *x = weak_pos.x / PANGO_SCALE;
3518           *y = weak_pos.y / PANGO_SCALE;
3519         }
3520     }
3521 }
3522
3523
3524 static gint
3525 gtk_label_move_logically (GtkLabel *label,
3526                           gint      start,
3527                           gint      count)
3528 {
3529   gint offset = g_utf8_pointer_to_offset (label->text,
3530                                           label->text + start);
3531
3532   if (label->text)
3533     {
3534       PangoLogAttr *log_attrs;
3535       gint n_attrs;
3536       gint length;
3537
3538       gtk_label_ensure_layout (label);
3539       
3540       length = g_utf8_strlen (label->text, -1);
3541
3542       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3543
3544       while (count > 0 && offset < length)
3545         {
3546           do
3547             offset++;
3548           while (offset < length && !log_attrs[offset].is_cursor_position);
3549           
3550           count--;
3551         }
3552       while (count < 0 && offset > 0)
3553         {
3554           do
3555             offset--;
3556           while (offset > 0 && !log_attrs[offset].is_cursor_position);
3557           
3558           count++;
3559         }
3560       
3561       g_free (log_attrs);
3562     }
3563
3564   return g_utf8_offset_to_pointer (label->text, offset) - label->text;
3565 }
3566
3567 static gint
3568 gtk_label_move_visually (GtkLabel *label,
3569                          gint      start,
3570                          gint      count)
3571 {
3572   gint index;
3573
3574   index = start;
3575   
3576   while (count != 0)
3577     {
3578       int new_index, new_trailing;
3579       gboolean split_cursor;
3580       gboolean strong;
3581
3582       gtk_label_ensure_layout (label);
3583
3584       g_object_get (gtk_widget_get_settings (GTK_WIDGET (label)),
3585                     "gtk-split-cursor", &split_cursor,
3586                     NULL);
3587
3588       if (split_cursor)
3589         strong = TRUE;
3590       else
3591         {
3592           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (label)));
3593           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3594
3595           strong = keymap_direction == get_cursor_direction (label);
3596         }
3597       
3598       if (count > 0)
3599         {
3600           pango_layout_move_cursor_visually (label->layout, strong, index, 0, 1, &new_index, &new_trailing);
3601           count--;
3602         }
3603       else
3604         {
3605           pango_layout_move_cursor_visually (label->layout, strong, index, 0, -1, &new_index, &new_trailing);
3606           count++;
3607         }
3608
3609       if (new_index < 0 || new_index == G_MAXINT)
3610         break;
3611
3612       index = new_index;
3613       
3614       while (new_trailing--)
3615         index = g_utf8_next_char (label->text + new_index) - label->text;
3616     }
3617   
3618   return index;
3619 }
3620
3621 static gint
3622 gtk_label_move_forward_word (GtkLabel *label,
3623                              gint      start)
3624 {
3625   gint new_pos = g_utf8_pointer_to_offset (label->text,
3626                                            label->text + start);
3627   gint length;
3628
3629   length = g_utf8_strlen (label->text, -1);
3630   if (new_pos < length)
3631     {
3632       PangoLogAttr *log_attrs;
3633       gint n_attrs;
3634
3635       gtk_label_ensure_layout (label);
3636       
3637       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3638       
3639       /* Find the next word end */
3640       new_pos++;
3641       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
3642         new_pos++;
3643
3644       g_free (log_attrs);
3645     }
3646
3647   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
3648 }
3649
3650
3651 static gint
3652 gtk_label_move_backward_word (GtkLabel *label,
3653                               gint      start)
3654 {
3655   gint new_pos = g_utf8_pointer_to_offset (label->text,
3656                                            label->text + start);
3657   gint length;
3658
3659   length = g_utf8_strlen (label->text, -1);
3660   
3661   if (new_pos > 0)
3662     {
3663       PangoLogAttr *log_attrs;
3664       gint n_attrs;
3665
3666       gtk_label_ensure_layout (label);
3667       
3668       pango_layout_get_log_attrs (label->layout, &log_attrs, &n_attrs);
3669       
3670       new_pos -= 1;
3671
3672       /* Find the previous word beginning */
3673       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
3674         new_pos--;
3675
3676       g_free (log_attrs);
3677     }
3678
3679   return g_utf8_offset_to_pointer (label->text, new_pos) - label->text;
3680 }
3681
3682 static void
3683 gtk_label_move_cursor (GtkLabel       *label,
3684                        GtkMovementStep step,
3685                        gint            count,
3686                        gboolean        extend_selection)
3687 {
3688   gint new_pos;
3689   
3690   if (label->select_info == NULL)
3691     return;
3692   
3693   new_pos = label->select_info->selection_end;
3694
3695   if (label->select_info->selection_end != label->select_info->selection_anchor &&
3696       !extend_selection)
3697     {
3698       /* If we have a current selection and aren't extending it, move to the
3699        * start/or end of the selection as appropriate
3700        */
3701       switch (step)
3702         {
3703         case GTK_MOVEMENT_VISUAL_POSITIONS:
3704           {
3705             gint end_x, end_y;
3706             gint anchor_x, anchor_y;
3707             gboolean end_is_left;
3708             
3709             get_better_cursor (label, label->select_info->selection_end, &end_x, &end_y);
3710             get_better_cursor (label, label->select_info->selection_anchor, &anchor_x, &anchor_y);
3711
3712             end_is_left = (end_y < anchor_y) || (end_y == anchor_y && end_x < anchor_x);
3713             
3714             if (count < 0)
3715               new_pos = end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
3716             else
3717               new_pos = !end_is_left ? label->select_info->selection_end : label->select_info->selection_anchor;
3718
3719             break;
3720           }
3721         case GTK_MOVEMENT_LOGICAL_POSITIONS:
3722         case GTK_MOVEMENT_WORDS:
3723           if (count < 0)
3724             new_pos = MIN (label->select_info->selection_end, label->select_info->selection_anchor);
3725           else
3726             new_pos = MAX (label->select_info->selection_end, label->select_info->selection_anchor);
3727           break;
3728         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
3729         case GTK_MOVEMENT_PARAGRAPH_ENDS:
3730         case GTK_MOVEMENT_BUFFER_ENDS:
3731           /* FIXME: Can do better here */
3732           new_pos = count < 0 ? 0 : strlen (label->text);
3733           break;
3734         case GTK_MOVEMENT_DISPLAY_LINES:
3735         case GTK_MOVEMENT_PARAGRAPHS:
3736         case GTK_MOVEMENT_PAGES:
3737         case GTK_MOVEMENT_HORIZONTAL_PAGES:
3738           break;
3739         }
3740     }
3741   else
3742     {
3743       switch (step)
3744         {
3745         case GTK_MOVEMENT_LOGICAL_POSITIONS:
3746           new_pos = gtk_label_move_logically (label, new_pos, count);
3747           break;
3748         case GTK_MOVEMENT_VISUAL_POSITIONS:
3749           new_pos = gtk_label_move_visually (label, new_pos, count);
3750           break;
3751         case GTK_MOVEMENT_WORDS:
3752           while (count > 0)
3753             {
3754               new_pos = gtk_label_move_forward_word (label, new_pos);
3755               count--;
3756             }
3757           while (count < 0)
3758             {
3759               new_pos = gtk_label_move_backward_word (label, new_pos);
3760               count++;
3761             }
3762           break;
3763         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
3764         case GTK_MOVEMENT_PARAGRAPH_ENDS:
3765         case GTK_MOVEMENT_BUFFER_ENDS:
3766           /* FIXME: Can do better here */
3767           new_pos = count < 0 ? 0 : strlen (label->text);
3768           break;
3769         case GTK_MOVEMENT_DISPLAY_LINES:
3770         case GTK_MOVEMENT_PARAGRAPHS:
3771         case GTK_MOVEMENT_PAGES:
3772         case GTK_MOVEMENT_HORIZONTAL_PAGES:
3773           break;
3774         }
3775     }
3776
3777   if (extend_selection)
3778     gtk_label_select_region_index (label,
3779                                    label->select_info->selection_anchor,
3780                                    new_pos);
3781   else
3782     gtk_label_select_region_index (label, new_pos, new_pos);
3783 }
3784
3785 static void
3786 gtk_label_copy_clipboard (GtkLabel *label)
3787 {
3788   if (label->text && label->select_info)
3789     {
3790       gint start, end;
3791       gint len;
3792       
3793       start = MIN (label->select_info->selection_anchor,
3794                    label->select_info->selection_end);
3795       end = MAX (label->select_info->selection_anchor,
3796                  label->select_info->selection_end);
3797
3798       len = strlen (label->text);
3799
3800       if (end > len)
3801         end = len;
3802
3803       if (start > len)
3804         start = len;
3805
3806       if (start != end)
3807         gtk_clipboard_set_text (gtk_widget_get_clipboard (GTK_WIDGET (label),
3808                                                           GDK_SELECTION_CLIPBOARD),
3809                                 label->text + start, end - start);
3810     }
3811 }
3812
3813 static void
3814 gtk_label_select_all (GtkLabel *label)
3815 {
3816   gtk_label_select_region_index (label, 0, strlen (label->text));
3817 }
3818
3819 /* Quick hack of a popup menu
3820  */
3821 static void
3822 activate_cb (GtkWidget *menuitem,
3823              GtkLabel  *label)
3824 {
3825   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
3826   g_signal_emit_by_name (label, signal);
3827 }
3828
3829 static void
3830 append_action_signal (GtkLabel     *label,
3831                       GtkWidget    *menu,
3832                       const gchar  *stock_id,
3833                       const gchar  *signal,
3834                       gboolean      sensitive)
3835 {
3836   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
3837
3838   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
3839   g_signal_connect (menuitem, "activate",
3840                     G_CALLBACK (activate_cb), label);
3841
3842   gtk_widget_set_sensitive (menuitem, sensitive);
3843   
3844   gtk_widget_show (menuitem);
3845   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
3846 }
3847
3848 static void
3849 popup_menu_detach (GtkWidget *attach_widget,
3850                    GtkMenu   *menu)
3851 {
3852   GtkLabel *label;
3853   label = GTK_LABEL (attach_widget);
3854
3855   if (label->select_info)
3856     label->select_info->popup_menu = NULL;
3857 }
3858
3859 static void
3860 popup_position_func (GtkMenu   *menu,
3861                      gint      *x,
3862                      gint      *y,
3863                      gboolean  *push_in,
3864                      gpointer   user_data)
3865 {
3866   GtkLabel *label;
3867   GtkWidget *widget;
3868   GtkRequisition req;
3869   GdkScreen *screen;
3870   
3871   label = GTK_LABEL (user_data);  
3872   widget = GTK_WIDGET (label);
3873
3874   if (label->select_info == NULL)
3875     return;
3876   
3877   g_return_if_fail (GTK_WIDGET_REALIZED (label));
3878   
3879   screen = gtk_widget_get_screen (widget);
3880   gdk_window_get_origin (widget->window, x, y);      
3881
3882   gtk_widget_size_request (label->select_info->popup_menu, &req);
3883   
3884   *x += widget->allocation.width / 2;
3885   *y += widget->allocation.height;
3886
3887   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
3888   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
3889 }
3890
3891
3892 static void
3893 gtk_label_do_popup (GtkLabel       *label,
3894                     GdkEventButton *event)
3895 {
3896   GtkWidget *menuitem;
3897   gboolean have_selection;
3898
3899   if (label->select_info == NULL)
3900     return;
3901     
3902   if (label->select_info->popup_menu)
3903     gtk_widget_destroy (label->select_info->popup_menu);
3904   
3905   label->select_info->popup_menu = gtk_menu_new ();
3906
3907   gtk_menu_attach_to_widget (GTK_MENU (label->select_info->popup_menu),
3908                              GTK_WIDGET (label),
3909                              popup_menu_detach);
3910
3911   have_selection =
3912     label->select_info->selection_anchor != label->select_info->selection_end;
3913
3914
3915   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
3916                         FALSE);
3917   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
3918                         have_selection);
3919   append_action_signal (label, label->select_info->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
3920                         FALSE);
3921   
3922   menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
3923   gtk_widget_set_sensitive (menuitem, FALSE);
3924   gtk_widget_show (menuitem);
3925   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3926
3927   menuitem = gtk_separator_menu_item_new ();
3928   gtk_widget_show (menuitem);
3929   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3930       
3931   menuitem = gtk_menu_item_new_with_label (_("Select All"));
3932   g_signal_connect_swapped (menuitem, "activate",
3933                             G_CALLBACK (gtk_label_select_all), label);
3934   gtk_widget_show (menuitem);
3935   gtk_menu_shell_append (GTK_MENU_SHELL (label->select_info->popup_menu), menuitem);
3936
3937   g_signal_emit (label,
3938                  signals[POPULATE_POPUP],
3939                  0,
3940                  label->select_info->popup_menu);
3941   
3942   if (event)
3943     gtk_menu_popup (GTK_MENU (label->select_info->popup_menu), NULL, NULL,
3944                     NULL, NULL,
3945                     event->button, event->time);
3946   else
3947     gtk_menu_popup (GTK_MENU (label->select_info->popup_menu), NULL, NULL,
3948                     popup_position_func, label,
3949                     0, gtk_get_current_event_time ());
3950 }