]> Pileus Git - ~andy/gtk/blob - gtk/gtkentry.c
Updated Italian translation.
[~andy/gtk] / gtk / gtkentry.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
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 #include <config.h>
28 #include <string.h>
29
30 #include <pango/pango.h>
31
32 #include "gdk/gdkkeysyms.h"
33 #include "gtkbindings.h"
34 #include "gtkcelleditable.h"
35 #include "gtkclipboard.h"
36 #include "gtkdnd.h"
37 #include "gtkentry.h"
38 #include "gtkimagemenuitem.h"
39 #include "gtkimmulticontext.h"
40 #include "gtkintl.h"
41 #include "gtkmain.h"
42 #include "gtkmarshalers.h"
43 #include "gtkmenu.h"
44 #include "gtkmenuitem.h"
45 #include "gtkseparatormenuitem.h"
46 #include "gtkselection.h"
47 #include "gtksettings.h"
48 #include "gtkstock.h"
49 #include "gtktextutil.h"
50 #include "gtkwindow.h"
51 #include "gtktreeview.h"
52 #include "gtktreeselection.h"
53 #include "gtkentryprivate.h"
54 #include "gtkcelllayout.h"
55
56 #define GTK_ENTRY_COMPLETION_KEY "gtk-entry-completion-key"
57
58 #define MIN_ENTRY_WIDTH  150
59 #define DRAW_TIMEOUT     20
60 #define INNER_BORDER     2
61 #define COMPLETION_TIMEOUT 300
62
63 /* Initial size of buffer, in bytes */
64 #define MIN_SIZE 16
65
66 /* Maximum size of text buffer, in bytes */
67 #define MAX_SIZE G_MAXUSHORT
68
69 typedef struct _GtkEntryPrivate GtkEntryPrivate;
70
71 #define GTK_ENTRY_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_ENTRY, GtkEntryPrivate))
72
73 struct _GtkEntryPrivate 
74 {
75   gfloat xalign;
76 };
77
78 enum {
79   ACTIVATE,
80   POPULATE_POPUP,
81   MOVE_CURSOR,
82   INSERT_AT_CURSOR,
83   DELETE_FROM_CURSOR,
84   CUT_CLIPBOARD,
85   COPY_CLIPBOARD,
86   PASTE_CLIPBOARD,
87   TOGGLE_OVERWRITE,
88   LAST_SIGNAL
89 };
90
91 enum {
92   PROP_0,
93   PROP_CURSOR_POSITION,
94   PROP_SELECTION_BOUND,
95   PROP_EDITABLE,
96   PROP_MAX_LENGTH,
97   PROP_VISIBILITY,
98   PROP_HAS_FRAME,
99   PROP_INVISIBLE_CHAR,
100   PROP_ACTIVATES_DEFAULT,
101   PROP_WIDTH_CHARS,
102   PROP_SCROLL_OFFSET,
103   PROP_TEXT,
104   PROP_XALIGN
105 };
106
107 static guint signals[LAST_SIGNAL] = { 0 };
108
109 typedef enum {
110   CURSOR_STANDARD,
111   CURSOR_DND
112 } CursorType;
113
114 static const GtkTargetEntry target_table[] = {
115   { "UTF8_STRING",   0, 0 },
116   { "COMPOUND_TEXT", 0, 0 },
117   { "TEXT",          0, 0 },
118   { "STRING",        0, 0 }
119 };
120
121 /* GObject, GtkObject methods
122  */
123 static void   gtk_entry_class_init           (GtkEntryClass        *klass);
124 static void   gtk_entry_editable_init        (GtkEditableClass     *iface);
125 static void   gtk_entry_cell_editable_init   (GtkCellEditableIface *iface);
126 static void   gtk_entry_init                 (GtkEntry         *entry);
127 static void   gtk_entry_set_property (GObject         *object,
128                                       guint            prop_id,
129                                       const GValue    *value,
130                                       GParamSpec      *pspec);
131 static void   gtk_entry_get_property (GObject         *object,
132                                       guint            prop_id,
133                                       GValue          *value,
134                                       GParamSpec      *pspec);
135 static void   gtk_entry_finalize             (GObject          *object);
136
137 /* GtkWidget methods
138  */
139 static void   gtk_entry_realize              (GtkWidget        *widget);
140 static void   gtk_entry_unrealize            (GtkWidget        *widget);
141 static void   gtk_entry_size_request         (GtkWidget        *widget,
142                                               GtkRequisition   *requisition);
143 static void   gtk_entry_size_allocate        (GtkWidget        *widget,
144                                               GtkAllocation    *allocation);
145 static void   gtk_entry_draw_frame           (GtkWidget        *widget);
146 static gint   gtk_entry_expose               (GtkWidget        *widget,
147                                               GdkEventExpose   *event);
148 static gint   gtk_entry_button_press         (GtkWidget        *widget,
149                                               GdkEventButton   *event);
150 static gint   gtk_entry_button_release       (GtkWidget        *widget,
151                                               GdkEventButton   *event);
152 static gint   gtk_entry_motion_notify        (GtkWidget        *widget,
153                                               GdkEventMotion   *event);
154 static gint   gtk_entry_key_press            (GtkWidget        *widget,
155                                               GdkEventKey      *event);
156 static gint   gtk_entry_key_release          (GtkWidget        *widget,
157                                               GdkEventKey      *event);
158 static gint   gtk_entry_focus_in             (GtkWidget        *widget,
159                                               GdkEventFocus    *event);
160 static gint   gtk_entry_focus_out            (GtkWidget        *widget,
161                                               GdkEventFocus    *event);
162 static void   gtk_entry_grab_focus           (GtkWidget        *widget);
163 static void   gtk_entry_style_set            (GtkWidget        *widget,
164                                               GtkStyle         *previous_style);
165 static void   gtk_entry_direction_changed    (GtkWidget        *widget,
166                                               GtkTextDirection  previous_dir);
167 static void   gtk_entry_state_changed        (GtkWidget        *widget,
168                                               GtkStateType      previous_state);
169 static void   gtk_entry_screen_changed       (GtkWidget        *widget,
170                                               GdkScreen        *old_screen);
171
172 static gboolean gtk_entry_drag_drop          (GtkWidget        *widget,
173                                               GdkDragContext   *context,
174                                               gint              x,
175                                               gint              y,
176                                               guint             time);
177 static gboolean gtk_entry_drag_motion        (GtkWidget        *widget,
178                                               GdkDragContext   *context,
179                                               gint              x,
180                                               gint              y,
181                                               guint             time);
182 static void     gtk_entry_drag_leave         (GtkWidget        *widget,
183                                               GdkDragContext   *context,
184                                               guint             time);
185 static void     gtk_entry_drag_data_received (GtkWidget        *widget,
186                                               GdkDragContext   *context,
187                                               gint              x,
188                                               gint              y,
189                                               GtkSelectionData *selection_data,
190                                               guint             info,
191                                               guint             time);
192 static void     gtk_entry_drag_data_get      (GtkWidget        *widget,
193                                               GdkDragContext   *context,
194                                               GtkSelectionData *selection_data,
195                                               guint             info,
196                                               guint             time);
197 static void     gtk_entry_drag_data_delete   (GtkWidget        *widget,
198                                               GdkDragContext   *context);
199
200 /* GtkEditable method implementations
201  */
202 static void     gtk_entry_insert_text          (GtkEditable *editable,
203                                                 const gchar *new_text,
204                                                 gint         new_text_length,
205                                                 gint        *position);
206 static void     gtk_entry_delete_text          (GtkEditable *editable,
207                                                 gint         start_pos,
208                                                 gint         end_pos);
209 static gchar *  gtk_entry_get_chars            (GtkEditable *editable,
210                                                 gint         start_pos,
211                                                 gint         end_pos);
212 static void     gtk_entry_real_set_position    (GtkEditable *editable,
213                                                 gint         position);
214 static gint     gtk_entry_get_position         (GtkEditable *editable);
215 static void     gtk_entry_set_selection_bounds (GtkEditable *editable,
216                                                 gint         start,
217                                                 gint         end);
218 static gboolean gtk_entry_get_selection_bounds (GtkEditable *editable,
219                                                 gint        *start,
220                                                 gint        *end);
221
222 /* GtkCellEditable method implementations
223  */
224 static void gtk_entry_start_editing (GtkCellEditable *cell_editable,
225                                      GdkEvent        *event);
226
227 /* Default signal handlers
228  */
229 static void gtk_entry_real_insert_text   (GtkEditable     *editable,
230                                           const gchar     *new_text,
231                                           gint             new_text_length,
232                                           gint            *position);
233 static void gtk_entry_real_delete_text   (GtkEditable     *editable,
234                                           gint             start_pos,
235                                           gint             end_pos);
236 static void gtk_entry_move_cursor        (GtkEntry        *entry,
237                                           GtkMovementStep  step,
238                                           gint             count,
239                                           gboolean         extend_selection);
240 static void gtk_entry_insert_at_cursor   (GtkEntry        *entry,
241                                           const gchar     *str);
242 static void gtk_entry_delete_from_cursor (GtkEntry        *entry,
243                                           GtkDeleteType    type,
244                                           gint             count);
245 static void gtk_entry_cut_clipboard      (GtkEntry        *entry);
246 static void gtk_entry_copy_clipboard     (GtkEntry        *entry);
247 static void gtk_entry_paste_clipboard    (GtkEntry        *entry);
248 static void gtk_entry_toggle_overwrite   (GtkEntry        *entry);
249 static void gtk_entry_select_all         (GtkEntry        *entry);
250 static void gtk_entry_real_activate      (GtkEntry        *entry);
251 static gboolean gtk_entry_popup_menu     (GtkWidget      *widget);
252
253 static void gtk_entry_keymap_direction_changed (GdkKeymap *keymap,
254                                                 GtkEntry  *entry);
255 /* IM Context Callbacks
256  */
257 static void     gtk_entry_commit_cb               (GtkIMContext *context,
258                                                    const gchar  *str,
259                                                    GtkEntry     *entry);
260 static void     gtk_entry_preedit_changed_cb      (GtkIMContext *context,
261                                                    GtkEntry     *entry);
262 static gboolean gtk_entry_retrieve_surrounding_cb (GtkIMContext *context,
263                                                    GtkEntry     *entry);
264 static gboolean gtk_entry_delete_surrounding_cb   (GtkIMContext *context,
265                                                    gint          offset,
266                                                    gint          n_chars,
267                                                    GtkEntry     *entry);
268
269 /* Internal routines
270  */
271 static void         gtk_entry_enter_text               (GtkEntry       *entry,
272                                                         const gchar    *str);
273 static void         gtk_entry_set_positions            (GtkEntry       *entry,
274                                                         gint            current_pos,
275                                                         gint            selection_bound);
276 static void         gtk_entry_draw_text                (GtkEntry       *entry);
277 static void         gtk_entry_draw_cursor              (GtkEntry       *entry,
278                                                         CursorType      type);
279 static PangoLayout *gtk_entry_ensure_layout            (GtkEntry       *entry,
280                                                         gboolean        include_preedit);
281 static void         gtk_entry_reset_layout             (GtkEntry       *entry);
282 static void         gtk_entry_queue_draw               (GtkEntry       *entry);
283 static void         gtk_entry_reset_im_context         (GtkEntry       *entry);
284 static void         gtk_entry_recompute                (GtkEntry       *entry);
285 static gint         gtk_entry_find_position            (GtkEntry       *entry,
286                                                         gint            x);
287 static void         gtk_entry_get_cursor_locations     (GtkEntry       *entry,
288                                                         CursorType      type,
289                                                         gint           *strong_x,
290                                                         gint           *weak_x);
291 static void         gtk_entry_adjust_scroll            (GtkEntry       *entry);
292 static gint         gtk_entry_move_visually            (GtkEntry       *editable,
293                                                         gint            start,
294                                                         gint            count);
295 static gint         gtk_entry_move_logically           (GtkEntry       *entry,
296                                                         gint            start,
297                                                         gint            count);
298 static gint         gtk_entry_move_forward_word        (GtkEntry       *entry,
299                                                         gint            start);
300 static gint         gtk_entry_move_backward_word       (GtkEntry       *entry,
301                                                         gint            start);
302 static void         gtk_entry_delete_whitespace        (GtkEntry       *entry);
303 static void         gtk_entry_select_word              (GtkEntry       *entry);
304 static void         gtk_entry_select_line              (GtkEntry       *entry);
305 static char *       gtk_entry_get_public_chars         (GtkEntry       *entry,
306                                                         gint            start,
307                                                         gint            end);
308 static void         gtk_entry_paste                    (GtkEntry       *entry,
309                                                         GdkAtom         selection);
310 static void         gtk_entry_update_primary_selection (GtkEntry       *entry);
311 static void         gtk_entry_do_popup                 (GtkEntry       *entry,
312                                                         GdkEventButton *event);
313 static gboolean     gtk_entry_mnemonic_activate        (GtkWidget      *widget,
314                                                         gboolean        group_cycling);
315 static void         gtk_entry_state_changed            (GtkWidget      *widget,
316                                                         GtkStateType    previous_state);
317 static void         gtk_entry_check_cursor_blink       (GtkEntry       *entry);
318 static void         gtk_entry_pend_cursor_blink        (GtkEntry       *entry);
319 static void         get_text_area_size                 (GtkEntry       *entry,
320                                                         gint           *x,
321                                                         gint           *y,
322                                                         gint           *width,
323                                                         gint           *height);
324 static void         get_widget_window_size             (GtkEntry       *entry,
325                                                         gint           *x,
326                                                         gint           *y,
327                                                         gint           *width,
328                                                         gint           *height);
329
330 static GtkWidgetClass *parent_class = NULL;
331
332 GType
333 gtk_entry_get_type (void)
334 {
335   static GType entry_type = 0;
336
337   if (!entry_type)
338     {
339       static const GTypeInfo entry_info =
340       {
341         sizeof (GtkEntryClass),
342         NULL,           /* base_init */
343         NULL,           /* base_finalize */
344         (GClassInitFunc) gtk_entry_class_init,
345         NULL,           /* class_finalize */
346         NULL,           /* class_data */
347         sizeof (GtkEntry),
348         0,              /* n_preallocs */
349         (GInstanceInitFunc) gtk_entry_init,
350       };
351       
352       static const GInterfaceInfo editable_info =
353       {
354         (GInterfaceInitFunc) gtk_entry_editable_init,    /* interface_init */
355         NULL,                                            /* interface_finalize */
356         NULL                                             /* interface_data */
357       };
358
359       static const GInterfaceInfo cell_editable_info =
360       {
361         (GInterfaceInitFunc) gtk_entry_cell_editable_init,    /* interface_init */
362         NULL,                                                 /* interface_finalize */
363         NULL                                                  /* interface_data */
364       };
365       
366       entry_type = g_type_register_static (GTK_TYPE_WIDGET, "GtkEntry",
367                                            &entry_info, 0);
368
369       g_type_add_interface_static (entry_type,
370                                    GTK_TYPE_EDITABLE,
371                                    &editable_info);
372       g_type_add_interface_static (entry_type,
373                                    GTK_TYPE_CELL_EDITABLE,
374                                    &cell_editable_info);
375     }
376
377   return entry_type;
378 }
379
380 static void
381 add_move_binding (GtkBindingSet  *binding_set,
382                   guint           keyval,
383                   guint           modmask,
384                   GtkMovementStep step,
385                   gint            count)
386 {
387   g_return_if_fail ((modmask & GDK_SHIFT_MASK) == 0);
388   
389   gtk_binding_entry_add_signal (binding_set, keyval, modmask,
390                                 "move_cursor", 3,
391                                 G_TYPE_ENUM, step,
392                                 G_TYPE_INT, count,
393                                 G_TYPE_BOOLEAN, FALSE);
394
395   /* Selection-extending version */
396   gtk_binding_entry_add_signal (binding_set, keyval, modmask | GDK_SHIFT_MASK,
397                                 "move_cursor", 3,
398                                 G_TYPE_ENUM, step,
399                                 G_TYPE_INT, count,
400                                 G_TYPE_BOOLEAN, TRUE);
401 }
402
403 static void
404 gtk_entry_class_init (GtkEntryClass *class)
405 {
406   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
407   GtkWidgetClass *widget_class;
408   GtkBindingSet *binding_set;
409
410   widget_class = (GtkWidgetClass*) class;
411   parent_class = g_type_class_peek_parent (class);
412
413   gobject_class->finalize = gtk_entry_finalize;
414   gobject_class->set_property = gtk_entry_set_property;
415   gobject_class->get_property = gtk_entry_get_property;
416
417   widget_class->realize = gtk_entry_realize;
418   widget_class->unrealize = gtk_entry_unrealize;
419   widget_class->size_request = gtk_entry_size_request;
420   widget_class->size_allocate = gtk_entry_size_allocate;
421   widget_class->expose_event = gtk_entry_expose;
422   widget_class->button_press_event = gtk_entry_button_press;
423   widget_class->button_release_event = gtk_entry_button_release;
424   widget_class->motion_notify_event = gtk_entry_motion_notify;
425   widget_class->key_press_event = gtk_entry_key_press;
426   widget_class->key_release_event = gtk_entry_key_release;
427   widget_class->focus_in_event = gtk_entry_focus_in;
428   widget_class->focus_out_event = gtk_entry_focus_out;
429   widget_class->grab_focus = gtk_entry_grab_focus;
430   widget_class->style_set = gtk_entry_style_set;
431   widget_class->direction_changed = gtk_entry_direction_changed;
432   widget_class->state_changed = gtk_entry_state_changed;
433   widget_class->screen_changed = gtk_entry_screen_changed;
434   widget_class->mnemonic_activate = gtk_entry_mnemonic_activate;
435
436   widget_class->drag_drop = gtk_entry_drag_drop;
437   widget_class->drag_motion = gtk_entry_drag_motion;
438   widget_class->drag_leave = gtk_entry_drag_leave;
439   widget_class->drag_data_received = gtk_entry_drag_data_received;
440   widget_class->drag_data_get = gtk_entry_drag_data_get;
441   widget_class->drag_data_delete = gtk_entry_drag_data_delete;
442
443   widget_class->popup_menu = gtk_entry_popup_menu;
444
445   class->move_cursor = gtk_entry_move_cursor;
446   class->insert_at_cursor = gtk_entry_insert_at_cursor;
447   class->delete_from_cursor = gtk_entry_delete_from_cursor;
448   class->cut_clipboard = gtk_entry_cut_clipboard;
449   class->copy_clipboard = gtk_entry_copy_clipboard;
450   class->paste_clipboard = gtk_entry_paste_clipboard;
451   class->toggle_overwrite = gtk_entry_toggle_overwrite;
452   class->activate = gtk_entry_real_activate;
453   
454   g_object_class_install_property (gobject_class,
455                                    PROP_CURSOR_POSITION,
456                                    g_param_spec_int ("cursor_position",
457                                                      P_("Cursor Position"),
458                                                      P_("The current position of the insertion cursor in chars"),
459                                                      0,
460                                                      MAX_SIZE,
461                                                      0,
462                                                      G_PARAM_READABLE));
463   
464   g_object_class_install_property (gobject_class,
465                                    PROP_SELECTION_BOUND,
466                                    g_param_spec_int ("selection_bound",
467                                                      P_("Selection Bound"),
468                                                      P_("The position of the opposite end of the selection from the cursor in chars"),
469                                                      0,
470                                                      MAX_SIZE,
471                                                      0,
472                                                      G_PARAM_READABLE));
473   
474   g_object_class_install_property (gobject_class,
475                                    PROP_EDITABLE,
476                                    g_param_spec_boolean ("editable",
477                                                          P_("Editable"),
478                                                          P_("Whether the entry contents can be edited"),
479                                                          TRUE,
480                                                          G_PARAM_READABLE | G_PARAM_WRITABLE));
481   
482   g_object_class_install_property (gobject_class,
483                                    PROP_MAX_LENGTH,
484                                    g_param_spec_int ("max_length",
485                                                      P_("Maximum length"),
486                                                      P_("Maximum number of characters for this entry. Zero if no maximum"),
487                                                      0,
488                                                      MAX_SIZE,
489                                                      0,
490                                                      G_PARAM_READABLE | G_PARAM_WRITABLE));
491   g_object_class_install_property (gobject_class,
492                                    PROP_VISIBILITY,
493                                    g_param_spec_boolean ("visibility",
494                                                          P_("Visibility"),
495                                                          P_("FALSE displays the \"invisible char\" instead of the actual text (password mode)"),
496                                                          TRUE,
497                                                          G_PARAM_READABLE | G_PARAM_WRITABLE));
498
499   g_object_class_install_property (gobject_class,
500                                    PROP_HAS_FRAME,
501                                    g_param_spec_boolean ("has_frame",
502                                                          P_("Has Frame"),
503                                                          P_("FALSE removes outside bevel from entry"),
504                                                          TRUE,
505                                                          G_PARAM_READABLE | G_PARAM_WRITABLE));
506
507     g_object_class_install_property (gobject_class,
508                                    PROP_INVISIBLE_CHAR,
509                                    g_param_spec_unichar ("invisible_char",
510                                                          P_("Invisible character"),
511                                                          P_("The character to use when masking entry contents (in \"password mode\")"),
512                                                          '*',
513                                                          G_PARAM_READABLE | G_PARAM_WRITABLE));
514
515   g_object_class_install_property (gobject_class,
516                                    PROP_ACTIVATES_DEFAULT,
517                                    g_param_spec_boolean ("activates_default",
518                                                          P_("Activates default"),
519                                                          P_("Whether to activate the default widget (such as the default button in a dialog) when Enter is pressed"),
520                                                          FALSE,
521                                                          G_PARAM_READABLE | G_PARAM_WRITABLE));
522   g_object_class_install_property (gobject_class,
523                                    PROP_WIDTH_CHARS,
524                                    g_param_spec_int ("width_chars",
525                                                      P_("Width in chars"),
526                                                      P_("Number of characters to leave space for in the entry"),
527                                                      -1,
528                                                      G_MAXINT,
529                                                      -1,
530                                                      G_PARAM_READABLE | G_PARAM_WRITABLE));
531
532   g_object_class_install_property (gobject_class,
533                                    PROP_SCROLL_OFFSET,
534                                    g_param_spec_int ("scroll_offset",
535                                                      P_("Scroll offset"),
536                                                      P_("Number of pixels of the entry scrolled off the screen to the left"),
537                                                      0,
538                                                      G_MAXINT,
539                                                      0,
540                                                      G_PARAM_READABLE));
541
542   g_object_class_install_property (gobject_class,
543                                    PROP_TEXT,
544                                    g_param_spec_string ("text",
545                                                         P_("Text"),
546                                                         P_("The contents of the entry"),
547                                                         "",
548                                                         G_PARAM_READABLE | G_PARAM_WRITABLE));
549
550   g_object_class_install_property (gobject_class,
551                                    PROP_XALIGN,
552                                    g_param_spec_float ("xalign",
553                                                        P_("X align"),
554                                                        P_("The horizontal alignment, from 0 (left) to 1 (right). Reversed for RTL layouts"),
555                                                        0.0,
556                                                        1.0,
557                                                        0.0,
558                                                        G_PARAM_READABLE | G_PARAM_WRITABLE));
559   
560   signals[POPULATE_POPUP] =
561     g_signal_new ("populate_popup",
562                   G_OBJECT_CLASS_TYPE (gobject_class),
563                   G_SIGNAL_RUN_LAST,
564                   G_STRUCT_OFFSET (GtkEntryClass, populate_popup),
565                   NULL, NULL,
566                   _gtk_marshal_VOID__OBJECT,
567                   G_TYPE_NONE, 1,
568                   GTK_TYPE_MENU);
569   
570  /* Action signals */
571   
572   signals[ACTIVATE] =
573     g_signal_new ("activate",
574                   G_OBJECT_CLASS_TYPE (gobject_class),
575                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
576                   G_STRUCT_OFFSET (GtkEntryClass, activate),
577                   NULL, NULL,
578                   _gtk_marshal_VOID__VOID,
579                   G_TYPE_NONE, 0);
580   widget_class->activate_signal = signals[ACTIVATE];
581
582   signals[MOVE_CURSOR] = 
583     g_signal_new ("move_cursor",
584                   G_OBJECT_CLASS_TYPE (gobject_class),
585                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
586                   G_STRUCT_OFFSET (GtkEntryClass, move_cursor),
587                   NULL, NULL,
588                   _gtk_marshal_VOID__ENUM_INT_BOOLEAN,
589                   G_TYPE_NONE, 3,
590                   GTK_TYPE_MOVEMENT_STEP,
591                   G_TYPE_INT,
592                   G_TYPE_BOOLEAN);
593
594   signals[INSERT_AT_CURSOR] = 
595     g_signal_new ("insert_at_cursor",
596                   G_OBJECT_CLASS_TYPE (gobject_class),
597                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
598                   G_STRUCT_OFFSET (GtkEntryClass, insert_at_cursor),
599                   NULL, NULL,
600                   _gtk_marshal_VOID__STRING,
601                   G_TYPE_NONE, 1,
602                   G_TYPE_STRING);
603
604   signals[DELETE_FROM_CURSOR] = 
605     g_signal_new ("delete_from_cursor",
606                   G_OBJECT_CLASS_TYPE (gobject_class),
607                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
608                   G_STRUCT_OFFSET (GtkEntryClass, delete_from_cursor),
609                   NULL, NULL,
610                   _gtk_marshal_VOID__ENUM_INT,
611                   G_TYPE_NONE, 2,
612                   GTK_TYPE_DELETE_TYPE,
613                   G_TYPE_INT);
614
615   signals[CUT_CLIPBOARD] =
616     g_signal_new ("cut_clipboard",
617                   G_OBJECT_CLASS_TYPE (gobject_class),
618                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
619                   G_STRUCT_OFFSET (GtkEntryClass, cut_clipboard),
620                   NULL, NULL,
621                   _gtk_marshal_VOID__VOID,
622                   G_TYPE_NONE, 0);
623
624   signals[COPY_CLIPBOARD] =
625     g_signal_new ("copy_clipboard",
626                   G_OBJECT_CLASS_TYPE (gobject_class),
627                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
628                   G_STRUCT_OFFSET (GtkEntryClass, copy_clipboard),
629                   NULL, NULL,
630                   _gtk_marshal_VOID__VOID,
631                   G_TYPE_NONE, 0);
632
633   signals[PASTE_CLIPBOARD] =
634     g_signal_new ("paste_clipboard",
635                   G_OBJECT_CLASS_TYPE (gobject_class),
636                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
637                   G_STRUCT_OFFSET (GtkEntryClass, paste_clipboard),
638                   NULL, NULL,
639                   _gtk_marshal_VOID__VOID,
640                   G_TYPE_NONE, 0);
641
642   signals[TOGGLE_OVERWRITE] =
643     g_signal_new ("toggle_overwrite",
644                   G_OBJECT_CLASS_TYPE (gobject_class),
645                   G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
646                   G_STRUCT_OFFSET (GtkEntryClass, toggle_overwrite),
647                   NULL, NULL,
648                   _gtk_marshal_VOID__VOID,
649                   G_TYPE_NONE, 0);
650
651   /*
652    * Key bindings
653    */
654
655   binding_set = gtk_binding_set_by_class (class);
656
657   /* Moving the insertion point */
658   add_move_binding (binding_set, GDK_Right, 0,
659                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
660   
661   add_move_binding (binding_set, GDK_Left, 0,
662                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
663
664   add_move_binding (binding_set, GDK_KP_Right, 0,
665                     GTK_MOVEMENT_VISUAL_POSITIONS, 1);
666   
667   add_move_binding (binding_set, GDK_KP_Left, 0,
668                     GTK_MOVEMENT_VISUAL_POSITIONS, -1);
669   
670   add_move_binding (binding_set, GDK_Right, GDK_CONTROL_MASK,
671                     GTK_MOVEMENT_WORDS, 1);
672
673   add_move_binding (binding_set, GDK_Left, GDK_CONTROL_MASK,
674                     GTK_MOVEMENT_WORDS, -1);
675
676   add_move_binding (binding_set, GDK_KP_Right, GDK_CONTROL_MASK,
677                     GTK_MOVEMENT_WORDS, 1);
678
679   add_move_binding (binding_set, GDK_KP_Left, GDK_CONTROL_MASK,
680                     GTK_MOVEMENT_WORDS, -1);
681   
682   add_move_binding (binding_set, GDK_Home, 0,
683                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
684
685   add_move_binding (binding_set, GDK_End, 0,
686                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
687
688   add_move_binding (binding_set, GDK_KP_Home, 0,
689                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, -1);
690
691   add_move_binding (binding_set, GDK_KP_End, 0,
692                     GTK_MOVEMENT_DISPLAY_LINE_ENDS, 1);
693   
694   add_move_binding (binding_set, GDK_Home, GDK_CONTROL_MASK,
695                     GTK_MOVEMENT_BUFFER_ENDS, -1);
696
697   add_move_binding (binding_set, GDK_End, GDK_CONTROL_MASK,
698                     GTK_MOVEMENT_BUFFER_ENDS, 1);
699
700   add_move_binding (binding_set, GDK_KP_Home, GDK_CONTROL_MASK,
701                     GTK_MOVEMENT_BUFFER_ENDS, -1);
702
703   add_move_binding (binding_set, GDK_KP_End, GDK_CONTROL_MASK,
704                     GTK_MOVEMENT_BUFFER_ENDS, 1);
705
706   /* Select all
707    */
708   gtk_binding_entry_add_signal (binding_set, GDK_a, GDK_CONTROL_MASK,
709                                 "move_cursor", 3,
710                                 GTK_TYPE_MOVEMENT_STEP, GTK_MOVEMENT_BUFFER_ENDS,
711                                 G_TYPE_INT, -1,
712                                 G_TYPE_BOOLEAN, FALSE);
713   gtk_binding_entry_add_signal (binding_set, GDK_a, GDK_CONTROL_MASK,
714                                 "move_cursor", 3,
715                                 GTK_TYPE_MOVEMENT_STEP, GTK_MOVEMENT_BUFFER_ENDS,
716                                 G_TYPE_INT, 1,
717                                 G_TYPE_BOOLEAN, TRUE);
718
719
720   /* Activate
721    */
722   gtk_binding_entry_add_signal (binding_set, GDK_Return, 0,
723                                 "activate", 0);
724   gtk_binding_entry_add_signal (binding_set, GDK_KP_Enter, 0,
725                                 "activate", 0);
726   
727   /* Deleting text */
728   gtk_binding_entry_add_signal (binding_set, GDK_Delete, 0,
729                                 "delete_from_cursor", 2,
730                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
731                                 G_TYPE_INT, 1);
732
733   gtk_binding_entry_add_signal (binding_set, GDK_KP_Delete, 0,
734                                 "delete_from_cursor", 2,
735                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
736                                 G_TYPE_INT, 1);
737   
738   gtk_binding_entry_add_signal (binding_set, GDK_BackSpace, 0,
739                                 "delete_from_cursor", 2,
740                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
741                                 G_TYPE_INT, -1);
742
743   /* Make this do the same as Backspace, to help with mis-typing */
744   gtk_binding_entry_add_signal (binding_set, GDK_BackSpace, GDK_SHIFT_MASK,
745                                 "delete_from_cursor", 2,
746                                 G_TYPE_ENUM, GTK_DELETE_CHARS,
747                                 G_TYPE_INT, -1);
748
749   gtk_binding_entry_add_signal (binding_set, GDK_Delete, GDK_CONTROL_MASK,
750                                 "delete_from_cursor", 2,
751                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
752                                 G_TYPE_INT, 1);
753
754   gtk_binding_entry_add_signal (binding_set, GDK_KP_Delete, GDK_CONTROL_MASK,
755                                 "delete_from_cursor", 2,
756                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
757                                 G_TYPE_INT, 1);
758   
759   gtk_binding_entry_add_signal (binding_set, GDK_BackSpace, GDK_CONTROL_MASK,
760                                 "delete_from_cursor", 2,
761                                 G_TYPE_ENUM, GTK_DELETE_WORD_ENDS,
762                                 G_TYPE_INT, -1);
763
764   /* Cut/copy/paste */
765
766   gtk_binding_entry_add_signal (binding_set, GDK_x, GDK_CONTROL_MASK,
767                                 "cut_clipboard", 0);
768   gtk_binding_entry_add_signal (binding_set, GDK_c, GDK_CONTROL_MASK,
769                                 "copy_clipboard", 0);
770   gtk_binding_entry_add_signal (binding_set, GDK_v, GDK_CONTROL_MASK,
771                                 "paste_clipboard", 0);
772
773   gtk_binding_entry_add_signal (binding_set, GDK_Delete, GDK_SHIFT_MASK,
774                                 "cut_clipboard", 0);
775   gtk_binding_entry_add_signal (binding_set, GDK_Insert, GDK_CONTROL_MASK,
776                                 "copy_clipboard", 0);
777   gtk_binding_entry_add_signal (binding_set, GDK_Insert, GDK_SHIFT_MASK,
778                                 "paste_clipboard", 0);
779
780   /* Overwrite */
781   gtk_binding_entry_add_signal (binding_set, GDK_Insert, 0,
782                                 "toggle_overwrite", 0);
783   gtk_binding_entry_add_signal (binding_set, GDK_KP_Insert, 0,
784                                 "toggle_overwrite", 0);
785
786   gtk_settings_install_property (g_param_spec_boolean ("gtk-entry-select-on-focus",
787                                                        P_("Select on focus"),
788                                                        P_("Whether to select the contents of an entry when it is focused"),
789                                                        TRUE,
790                                                        G_PARAM_READWRITE));
791
792   g_type_class_add_private (gobject_class, sizeof (GtkEntryPrivate));
793 }
794
795 static void
796 gtk_entry_editable_init (GtkEditableClass *iface)
797 {
798   iface->do_insert_text = gtk_entry_insert_text;
799   iface->do_delete_text = gtk_entry_delete_text;
800   iface->insert_text = gtk_entry_real_insert_text;
801   iface->delete_text = gtk_entry_real_delete_text;
802   iface->get_chars = gtk_entry_get_chars;
803   iface->set_selection_bounds = gtk_entry_set_selection_bounds;
804   iface->get_selection_bounds = gtk_entry_get_selection_bounds;
805   iface->set_position = gtk_entry_real_set_position;
806   iface->get_position = gtk_entry_get_position;
807 }
808
809 static void
810 gtk_entry_cell_editable_init (GtkCellEditableIface *iface)
811 {
812   iface->start_editing = gtk_entry_start_editing;
813 }
814
815 static void
816 gtk_entry_set_property (GObject         *object,
817                         guint            prop_id,
818                         const GValue    *value,
819                         GParamSpec      *pspec)
820 {
821   GtkEntry *entry = GTK_ENTRY (object);
822
823   switch (prop_id)
824     {
825     case PROP_EDITABLE:
826       {
827         gboolean new_value = g_value_get_boolean (value);
828
829         if (new_value != entry->editable)
830           {
831             entry->editable = new_value;
832             gtk_entry_queue_draw (entry);
833
834             if (!entry->editable)
835               gtk_entry_reset_im_context (entry);
836           }
837       }
838       break;
839
840     case PROP_MAX_LENGTH:
841       gtk_entry_set_max_length (entry, g_value_get_int (value));
842       break;
843       
844     case PROP_VISIBILITY:
845       gtk_entry_set_visibility (entry, g_value_get_boolean (value));
846       break;
847
848     case PROP_HAS_FRAME:
849       gtk_entry_set_has_frame (entry, g_value_get_boolean (value));
850       break;
851
852     case PROP_INVISIBLE_CHAR:
853       gtk_entry_set_invisible_char (entry, g_value_get_uint (value));
854       break;
855
856     case PROP_ACTIVATES_DEFAULT:
857       gtk_entry_set_activates_default (entry, g_value_get_boolean (value));
858       break;
859
860     case PROP_WIDTH_CHARS:
861       gtk_entry_set_width_chars (entry, g_value_get_int (value));
862       break;
863
864     case PROP_TEXT:
865       gtk_entry_set_text (entry, g_value_get_string (value));
866       break;
867
868     case PROP_XALIGN:
869       gtk_entry_set_alignment (entry, g_value_get_float (value));
870       break;
871
872     case PROP_SCROLL_OFFSET:
873     case PROP_CURSOR_POSITION:
874     default:
875       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
876       break;
877     }
878 }
879
880 static void
881 gtk_entry_get_property (GObject         *object,
882                         guint            prop_id,
883                         GValue          *value,
884                         GParamSpec      *pspec)
885 {
886   GtkEntry *entry = GTK_ENTRY (object);
887
888   switch (prop_id)
889     {
890     case PROP_CURSOR_POSITION:
891       g_value_set_int (value, entry->current_pos);
892       break;
893     case PROP_SELECTION_BOUND:
894       g_value_set_int (value, entry->selection_bound);
895       break;
896     case PROP_EDITABLE:
897       g_value_set_boolean (value, entry->editable);
898       break;
899     case PROP_MAX_LENGTH:
900       g_value_set_int (value, entry->text_max_length); 
901       break;
902     case PROP_VISIBILITY:
903       g_value_set_boolean (value, entry->visible);
904       break;
905     case PROP_HAS_FRAME:
906       g_value_set_boolean (value, entry->has_frame);
907       break;
908     case PROP_INVISIBLE_CHAR:
909       g_value_set_uint (value, entry->invisible_char);
910       break;
911     case PROP_ACTIVATES_DEFAULT:
912       g_value_set_boolean (value, entry->activates_default);
913       break;
914     case PROP_WIDTH_CHARS:
915       g_value_set_int (value, entry->width_chars);
916       break;
917     case PROP_SCROLL_OFFSET:
918       g_value_set_int (value, entry->scroll_offset);
919       break;
920     case PROP_TEXT:
921       g_value_set_string (value, gtk_entry_get_text (entry));
922       break;
923     case PROP_XALIGN:
924       g_value_set_float (value, gtk_entry_get_alignment (entry));
925       break;
926       
927     default:
928       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
929       break;
930     }
931 }
932
933 static void
934 gtk_entry_init (GtkEntry *entry)
935 {
936   GtkEntryPrivate *priv = GTK_ENTRY_GET_PRIVATE (entry);
937   
938   GTK_WIDGET_SET_FLAGS (entry, GTK_CAN_FOCUS);
939
940   entry->text_size = MIN_SIZE;
941   entry->text = g_malloc (entry->text_size);
942   entry->text[0] = '\0';
943
944   entry->editable = TRUE;
945   entry->visible = TRUE;
946   entry->invisible_char = '*';
947   entry->dnd_position = -1;
948   entry->width_chars = -1;
949   entry->is_cell_renderer = FALSE;
950   entry->editing_canceled = FALSE;
951   entry->has_frame = TRUE;
952   priv->xalign = 0.0;
953
954   gtk_drag_dest_set (GTK_WIDGET (entry),
955                      GTK_DEST_DEFAULT_HIGHLIGHT,
956                      target_table, G_N_ELEMENTS (target_table),
957                      GDK_ACTION_COPY | GDK_ACTION_MOVE);
958
959   /* This object is completely private. No external entity can gain a reference
960    * to it; so we create it here and destroy it in finalize().
961    */
962   entry->im_context = gtk_im_multicontext_new ();
963   
964   g_signal_connect (entry->im_context, "commit",
965                     G_CALLBACK (gtk_entry_commit_cb), entry);
966   g_signal_connect (entry->im_context, "preedit_changed",
967                     G_CALLBACK (gtk_entry_preedit_changed_cb), entry);
968   g_signal_connect (entry->im_context, "retrieve_surrounding",
969                     G_CALLBACK (gtk_entry_retrieve_surrounding_cb), entry);
970   g_signal_connect (entry->im_context, "delete_surrounding",
971                     G_CALLBACK (gtk_entry_delete_surrounding_cb), entry);
972 }
973
974 static void
975 gtk_entry_finalize (GObject *object)
976 {
977   GtkEntry *entry = GTK_ENTRY (object);
978
979   gtk_entry_set_completion (entry, NULL);
980
981   if (entry->cached_layout)
982     g_object_unref (entry->cached_layout);
983
984   g_object_unref (entry->im_context);
985
986   if (entry->blink_timeout)
987     g_source_remove (entry->blink_timeout);
988
989   if (entry->recompute_idle)
990     g_source_remove (entry->recompute_idle);
991
992   entry->text_size = 0;
993
994   if (entry->text)
995     g_free (entry->text);
996   entry->text = NULL;
997
998   G_OBJECT_CLASS (parent_class)->finalize (object);
999 }
1000
1001 static void
1002 gtk_entry_realize (GtkWidget *widget)
1003 {
1004   GtkEntry *entry;
1005   GtkEditable *editable;
1006   GdkWindowAttr attributes;
1007   gint attributes_mask;
1008
1009   GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
1010   entry = GTK_ENTRY (widget);
1011   editable = GTK_EDITABLE (widget);
1012
1013   attributes.window_type = GDK_WINDOW_CHILD;
1014   
1015   get_widget_window_size (entry, &attributes.x, &attributes.y, &attributes.width, &attributes.height);
1016
1017   attributes.wclass = GDK_INPUT_OUTPUT;
1018   attributes.visual = gtk_widget_get_visual (widget);
1019   attributes.colormap = gtk_widget_get_colormap (widget);
1020   attributes.event_mask = gtk_widget_get_events (widget);
1021   attributes.event_mask |= (GDK_EXPOSURE_MASK |
1022                             GDK_BUTTON_PRESS_MASK |
1023                             GDK_BUTTON_RELEASE_MASK |
1024                             GDK_BUTTON1_MOTION_MASK |
1025                             GDK_BUTTON3_MOTION_MASK |
1026                             GDK_POINTER_MOTION_HINT_MASK |
1027                             GDK_POINTER_MOTION_MASK |
1028                             GDK_ENTER_NOTIFY_MASK |
1029                             GDK_LEAVE_NOTIFY_MASK);
1030   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
1031
1032   widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask);
1033   gdk_window_set_user_data (widget->window, entry);
1034
1035   get_text_area_size (entry, &attributes.x, &attributes.y, &attributes.width, &attributes.height);
1036
1037   attributes.cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
1038   attributes_mask |= GDK_WA_CURSOR;
1039
1040   entry->text_area = gdk_window_new (widget->window, &attributes, attributes_mask);
1041   gdk_window_set_user_data (entry->text_area, entry);
1042
1043   gdk_cursor_unref (attributes.cursor);
1044
1045   widget->style = gtk_style_attach (widget->style, widget->window);
1046
1047   gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1048   gdk_window_set_background (entry->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1049
1050   gdk_window_show (entry->text_area);
1051
1052   gtk_im_context_set_client_window (entry->im_context, entry->text_area);
1053
1054   gtk_entry_adjust_scroll (entry);
1055   gtk_entry_update_primary_selection (entry);
1056 }
1057
1058 static void
1059 gtk_entry_unrealize (GtkWidget *widget)
1060 {
1061   GtkEntry *entry = GTK_ENTRY (widget);
1062   GtkClipboard *clipboard;
1063
1064   gtk_entry_reset_layout (entry);
1065   
1066   gtk_im_context_set_client_window (entry->im_context, NULL);
1067
1068   clipboard = gtk_widget_get_clipboard (widget, GDK_SELECTION_PRIMARY);
1069   if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (entry))
1070     gtk_clipboard_clear (clipboard);
1071   
1072   if (entry->text_area)
1073     {
1074       gdk_window_set_user_data (entry->text_area, NULL);
1075       gdk_window_destroy (entry->text_area);
1076       entry->text_area = NULL;
1077     }
1078
1079   if (entry->popup_menu)
1080     {
1081       gtk_widget_destroy (entry->popup_menu);
1082       entry->popup_menu = NULL;
1083     }
1084
1085   if (GTK_WIDGET_CLASS (parent_class)->unrealize)
1086     (* GTK_WIDGET_CLASS (parent_class)->unrealize) (widget);
1087 }
1088
1089 static void
1090 get_borders (GtkEntry *entry,
1091              gint     *xborder,
1092              gint     *yborder)
1093 {
1094   GtkWidget *widget = GTK_WIDGET (entry);
1095   gint focus_width;
1096   gboolean interior_focus;
1097
1098   gtk_widget_style_get (widget,
1099                         "interior-focus", &interior_focus,
1100                         "focus-line-width", &focus_width,
1101                         NULL);
1102
1103   if (entry->has_frame)
1104     {
1105       *xborder = widget->style->xthickness;
1106       *yborder = widget->style->ythickness;
1107     }
1108   else
1109     {
1110       *xborder = 0;
1111       *yborder = 0;
1112     }
1113
1114   if (!interior_focus)
1115     {
1116       *xborder += focus_width;
1117       *yborder += focus_width;
1118     }
1119 }
1120
1121 static void
1122 gtk_entry_size_request (GtkWidget      *widget,
1123                         GtkRequisition *requisition)
1124 {
1125   GtkEntry *entry = GTK_ENTRY (widget);
1126   PangoFontMetrics *metrics;
1127   gint xborder, yborder;
1128   PangoContext *context;
1129   
1130   context = gtk_widget_get_pango_context (widget);
1131   metrics = pango_context_get_metrics (context,
1132                                        widget->style->font_desc,
1133                                        pango_context_get_language (context));
1134
1135   entry->ascent = pango_font_metrics_get_ascent (metrics);
1136   entry->descent = pango_font_metrics_get_descent (metrics);
1137
1138   get_borders (entry, &xborder, &yborder);
1139   
1140   xborder += INNER_BORDER;
1141   yborder += INNER_BORDER;
1142   
1143   if (entry->width_chars < 0)
1144     requisition->width = MIN_ENTRY_WIDTH + xborder * 2;
1145   else
1146     {
1147       gint char_width = pango_font_metrics_get_approximate_char_width (metrics);
1148       gint digit_width = pango_font_metrics_get_approximate_digit_width (metrics);
1149       gint char_pixels = (MAX (char_width, digit_width) + PANGO_SCALE - 1) / PANGO_SCALE;
1150       
1151       requisition->width = char_pixels * entry->width_chars + xborder * 2;
1152     }
1153     
1154   requisition->height = PANGO_PIXELS (entry->ascent + entry->descent) + yborder * 2;
1155
1156   pango_font_metrics_unref (metrics);
1157 }
1158
1159 static void
1160 get_text_area_size (GtkEntry *entry,
1161                     gint     *x,
1162                     gint     *y,
1163                     gint     *width,
1164                     gint     *height)
1165 {
1166   gint xborder, yborder;
1167   GtkRequisition requisition;
1168   GtkWidget *widget = GTK_WIDGET (entry);
1169
1170   gtk_widget_get_child_requisition (widget, &requisition);
1171
1172   get_borders (entry, &xborder, &yborder);
1173
1174   if (x)
1175     *x = xborder;
1176
1177   if (y)
1178     *y = yborder;
1179   
1180   if (width)
1181     *width = GTK_WIDGET (entry)->allocation.width - xborder * 2;
1182
1183   if (height)
1184     *height = requisition.height - yborder * 2;
1185 }
1186
1187 static void
1188 get_widget_window_size (GtkEntry *entry,
1189                         gint     *x,
1190                         gint     *y,
1191                         gint     *width,
1192                         gint     *height)
1193 {
1194   GtkRequisition requisition;
1195   GtkWidget *widget = GTK_WIDGET (entry);
1196       
1197   gtk_widget_get_child_requisition (widget, &requisition);
1198
1199   if (x)
1200     *x = widget->allocation.x;
1201
1202   if (y)
1203     {
1204       if (entry->is_cell_renderer)
1205         *y = widget->allocation.y;
1206       else
1207         *y = widget->allocation.y + (widget->allocation.height - requisition.height) / 2;
1208     }
1209
1210   if (width)
1211     *width = widget->allocation.width;
1212
1213   if (height)
1214     {
1215       if (entry->is_cell_renderer)
1216         *height = widget->allocation.height;
1217       else
1218         *height = requisition.height;
1219     }
1220 }
1221
1222 static void
1223 gtk_entry_size_allocate (GtkWidget     *widget,
1224                          GtkAllocation *allocation)
1225 {
1226   GtkEntry *entry = GTK_ENTRY (widget);
1227   
1228   widget->allocation = *allocation;
1229   
1230   if (GTK_WIDGET_REALIZED (widget))
1231     {
1232       /* We call gtk_widget_get_child_requisition, since we want (for
1233        * backwards compatibility reasons) the realization here to
1234        * be affected by the usize of the entry, if set
1235        */
1236       gint x, y, width, height;
1237
1238       get_widget_window_size (entry, &x, &y, &width, &height);
1239       
1240       gdk_window_move_resize (widget->window,
1241                               x, y, width, height);   
1242
1243       get_text_area_size (entry, &x, &y, &width, &height);
1244       
1245       gdk_window_move_resize (entry->text_area,
1246                               x, y, width, height);
1247
1248       gtk_entry_recompute (entry);
1249     }
1250 }
1251
1252 static void
1253 gtk_entry_draw_frame (GtkWidget *widget)
1254 {
1255   gint x = 0, y = 0;
1256   gint width, height;
1257   gboolean interior_focus;
1258   gint focus_width;
1259   
1260   gtk_widget_style_get (widget,
1261                         "interior-focus", &interior_focus,
1262                         "focus-line-width", &focus_width,
1263                         NULL);
1264   
1265   gdk_drawable_get_size (widget->window, &width, &height);
1266   
1267   if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
1268     {
1269       x += focus_width;
1270       y += focus_width;
1271       width -= 2 * focus_width;
1272       height -= 2 * focus_width;
1273     }
1274
1275   gtk_paint_shadow (widget->style, widget->window,
1276                     GTK_STATE_NORMAL, GTK_SHADOW_IN,
1277                     NULL, widget, "entry",
1278                     x, y, width, height);
1279
1280   if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
1281     {
1282       x -= focus_width;
1283       y -= focus_width;
1284       width += 2 * focus_width;
1285       height += 2 * focus_width;
1286       
1287       gtk_paint_focus (widget->style, widget->window, GTK_WIDGET_STATE (widget), 
1288                        NULL, widget, "entry",
1289                        0, 0, width, height);
1290     }
1291 }
1292
1293 static gint
1294 gtk_entry_expose (GtkWidget      *widget,
1295                   GdkEventExpose *event)
1296 {
1297   GtkEntry *entry = GTK_ENTRY (widget);
1298
1299   if (widget->window == event->window)
1300     gtk_entry_draw_frame (widget);
1301   else if (entry->text_area == event->window)
1302     {
1303       gint area_width, area_height;
1304
1305       get_text_area_size (entry, NULL, NULL, &area_width, &area_height);
1306
1307       gtk_paint_flat_box (widget->style, entry->text_area, 
1308                           GTK_WIDGET_STATE(widget), GTK_SHADOW_NONE,
1309                           NULL, widget, "entry_bg", 
1310                           0, 0, area_width, area_height);
1311       
1312       if ((entry->visible || entry->invisible_char != 0) &&
1313           GTK_WIDGET_HAS_FOCUS (widget) &&
1314           entry->selection_bound == entry->current_pos && entry->cursor_visible)
1315         gtk_entry_draw_cursor (GTK_ENTRY (widget), CURSOR_STANDARD);
1316
1317       if (entry->dnd_position != -1)
1318         gtk_entry_draw_cursor (GTK_ENTRY (widget), CURSOR_DND);
1319       
1320       gtk_entry_draw_text (GTK_ENTRY (widget));
1321     }
1322
1323   return FALSE;
1324 }
1325
1326 static gint
1327 gtk_entry_button_press (GtkWidget      *widget,
1328                         GdkEventButton *event)
1329 {
1330   GtkEntry *entry = GTK_ENTRY (widget);
1331   GtkEditable *editable = GTK_EDITABLE (widget);
1332   gint tmp_pos;
1333   gint sel_start, sel_end;
1334
1335   if (event->window != entry->text_area ||
1336       (entry->button && event->button != entry->button))
1337     return FALSE;
1338
1339   entry->button = event->button;
1340   
1341   if (!GTK_WIDGET_HAS_FOCUS (widget))
1342     {
1343       entry->in_click = TRUE;
1344       gtk_widget_grab_focus (widget);
1345       entry->in_click = FALSE;
1346     }
1347   
1348   tmp_pos = gtk_entry_find_position (entry, event->x + entry->scroll_offset);
1349     
1350   if (event->button == 1)
1351     {
1352       gboolean have_selection = gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end);
1353       
1354       entry->select_words = FALSE;
1355       entry->select_lines = FALSE;
1356
1357       if (event->state & GDK_SHIFT_MASK)
1358         {
1359           gtk_entry_reset_im_context (entry);
1360           
1361           if (!have_selection) /* select from the current position to the clicked position */
1362             sel_start = sel_end = entry->current_pos;
1363           
1364           if (tmp_pos > sel_start && tmp_pos < sel_end)
1365             {
1366               /* Truncate current selection */
1367               gtk_entry_set_positions (entry, tmp_pos, -1);
1368             }
1369           else
1370             {
1371               gboolean extend_to_left;
1372               gint start, end;
1373
1374               /* Figure out what click selects and extend current selection */
1375               switch (event->type)
1376                 {
1377                 case GDK_BUTTON_PRESS:
1378                   gtk_entry_set_positions (entry, tmp_pos, tmp_pos);
1379                   break;
1380                   
1381                 case GDK_2BUTTON_PRESS:
1382                   entry->select_words = TRUE;
1383                   gtk_entry_select_word (entry);
1384                   break;
1385                   
1386                 case GDK_3BUTTON_PRESS:
1387                   entry->select_lines = TRUE;
1388                   gtk_entry_select_line (entry);
1389                   break;
1390
1391                 default:
1392                   break;
1393                 }
1394
1395               start = MIN (entry->current_pos, entry->selection_bound);
1396               start = MIN (sel_start, start);
1397               
1398               end = MAX (entry->current_pos, entry->selection_bound);
1399               end = MAX (sel_end, end);
1400
1401               if (tmp_pos == sel_start || tmp_pos == sel_end)
1402                 extend_to_left = (tmp_pos == start);
1403               else
1404                 extend_to_left = (end == sel_end);
1405               
1406               if (extend_to_left)
1407                 gtk_entry_set_positions (entry, start, end);
1408               else
1409                 gtk_entry_set_positions (entry, end, start);
1410             }
1411         }
1412       else /* no shift key */
1413         switch (event->type)
1414         {
1415         case GDK_BUTTON_PRESS:
1416           if (have_selection && tmp_pos >= sel_start && tmp_pos <= sel_end)
1417             {
1418               /* Click inside the selection - we'll either start a drag, or
1419                * clear the selection
1420                */
1421
1422               entry->in_drag = TRUE;
1423               entry->drag_start_x = event->x + entry->scroll_offset;
1424               entry->drag_start_y = event->y + entry->scroll_offset;
1425             }
1426           else
1427             gtk_editable_set_position (editable, tmp_pos);
1428           
1429           break;
1430
1431  
1432         case GDK_2BUTTON_PRESS:
1433           /* We ALWAYS receive a GDK_BUTTON_PRESS immediately before 
1434            * receiving a GDK_2BUTTON_PRESS so we need to reset
1435            * entry->in_drag which may have been set above
1436            */
1437           entry->in_drag = FALSE;
1438           entry->select_words = TRUE;
1439           gtk_entry_select_word (entry);
1440           break;
1441         
1442         case GDK_3BUTTON_PRESS:
1443           /* We ALWAYS receive a GDK_BUTTON_PRESS immediately before
1444            * receiving a GDK_3BUTTON_PRESS so we need to reset
1445            * entry->in_drag which may have been set above
1446            */
1447           entry->in_drag = FALSE;
1448           entry->select_lines = TRUE;
1449           gtk_entry_select_line (entry);
1450           break;
1451
1452         default:
1453           break;
1454         }
1455
1456       return TRUE;
1457     }
1458   else if (event->button == 2 && event->type == GDK_BUTTON_PRESS && entry->editable)
1459     {
1460       gtk_editable_select_region (editable, tmp_pos, tmp_pos);
1461       gtk_entry_paste (entry, GDK_SELECTION_PRIMARY);
1462
1463       return TRUE;
1464     }
1465   else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
1466     {
1467       gtk_entry_do_popup (entry, event);
1468       entry->button = 0;        /* Don't wait for release, since the menu will gtk_grab_add */
1469
1470       return TRUE;
1471     }
1472
1473   return FALSE;
1474 }
1475
1476 static gint
1477 gtk_entry_button_release (GtkWidget      *widget,
1478                           GdkEventButton *event)
1479 {
1480   GtkEntry *entry = GTK_ENTRY (widget);
1481
1482   if (event->window != entry->text_area || entry->button != event->button)
1483     return FALSE;
1484
1485   if (entry->in_drag)
1486     {
1487       gint tmp_pos = gtk_entry_find_position (entry, entry->drag_start_x);
1488
1489       gtk_editable_set_position (GTK_EDITABLE (entry), tmp_pos);
1490
1491       entry->in_drag = 0;
1492     }
1493   
1494   entry->button = 0;
1495   
1496   gtk_entry_update_primary_selection (entry);
1497               
1498   return TRUE;
1499 }
1500
1501 static gint
1502 gtk_entry_motion_notify (GtkWidget      *widget,
1503                          GdkEventMotion *event)
1504 {
1505   GtkEntry *entry = GTK_ENTRY (widget);
1506   gint tmp_pos;
1507
1508   if (entry->mouse_cursor_obscured)
1509     {
1510       GdkCursor *cursor;
1511       
1512       cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
1513       gdk_window_set_cursor (entry->text_area, cursor);
1514       gdk_cursor_unref (cursor);
1515       entry->mouse_cursor_obscured = FALSE;
1516     }
1517
1518   if (event->window != entry->text_area || entry->button != 1)
1519     return FALSE;
1520
1521   if (entry->select_lines)
1522     return TRUE;
1523
1524   if (event->is_hint || (entry->text_area != event->window))
1525     gdk_window_get_pointer (entry->text_area, NULL, NULL, NULL);
1526
1527   if (entry->in_drag)
1528     {
1529       if (gtk_drag_check_threshold (widget,
1530                                     entry->drag_start_x, entry->drag_start_y,
1531                                     event->x + entry->scroll_offset, event->y))
1532         {
1533           GdkDragContext *context;
1534           GtkTargetList *target_list = gtk_target_list_new (target_table, G_N_ELEMENTS (target_table));
1535           guint actions = entry->editable ? GDK_ACTION_COPY | GDK_ACTION_MOVE : GDK_ACTION_COPY;
1536           
1537           context = gtk_drag_begin (widget, target_list, actions,
1538                           entry->button, (GdkEvent *)event);
1539
1540           
1541           entry->in_drag = FALSE;
1542           entry->button = 0;
1543           
1544           gtk_target_list_unref (target_list);
1545           gtk_drag_set_icon_default (context);
1546         }
1547     }
1548   else
1549     {
1550       gint height;
1551       gdk_drawable_get_size (entry->text_area, NULL, &height);
1552
1553       if (event->y < 0)
1554         tmp_pos = 0;
1555       else if (event->y >= height)
1556         tmp_pos = entry->text_length;
1557       else
1558         tmp_pos = gtk_entry_find_position (entry, event->x + entry->scroll_offset);
1559       
1560       if (entry->select_words) 
1561         {
1562           gint min, max;
1563           gint old_min, old_max;
1564           gint pos, bound;
1565           
1566           min = gtk_entry_move_backward_word (entry, tmp_pos);
1567           max = gtk_entry_move_forward_word (entry, tmp_pos);
1568           
1569           pos = entry->current_pos;
1570           bound = entry->selection_bound;
1571
1572           old_min = MIN(entry->current_pos, entry->selection_bound);
1573           old_max = MAX(entry->current_pos, entry->selection_bound);
1574           
1575           if (min < old_min)
1576             {
1577               pos = min;
1578               bound = old_max;
1579             }
1580           else if (old_max < max) 
1581             {
1582               pos = max;
1583               bound = old_min;
1584             }
1585           else if (pos == old_min) 
1586             {
1587               if (entry->current_pos != min)
1588                 pos = max;
1589             }
1590           else 
1591             {
1592               if (entry->current_pos != max)
1593                 pos = min;
1594             }
1595         
1596           gtk_entry_set_positions (entry, pos, bound);
1597         }
1598       else
1599       gtk_entry_set_positions (entry, tmp_pos, -1);
1600     }
1601       
1602   return TRUE;
1603 }
1604
1605 static void
1606 set_invisible_cursor (GdkWindow *window)
1607 {
1608   GdkBitmap *empty_bitmap;
1609   GdkCursor *cursor;
1610   GdkColor useless;
1611   char invisible_cursor_bits[] = { 0x0 };       
1612         
1613   useless.red = useless.green = useless.blue = 0;
1614   useless.pixel = 0;
1615   
1616   empty_bitmap = gdk_bitmap_create_from_data (window,
1617                                               invisible_cursor_bits,
1618                                               1, 1);
1619   
1620   cursor = gdk_cursor_new_from_pixmap (empty_bitmap,
1621                                        empty_bitmap,
1622                                        &useless,
1623                                        &useless, 0, 0);
1624   
1625   gdk_window_set_cursor (window, cursor);
1626   
1627   gdk_cursor_unref (cursor);
1628   
1629   g_object_unref (empty_bitmap);
1630 }
1631
1632 static void
1633 gtk_entry_obscure_mouse_cursor (GtkEntry *entry)
1634 {
1635   if (entry->mouse_cursor_obscured)
1636     return;
1637
1638   set_invisible_cursor (entry->text_area);
1639   
1640   entry->mouse_cursor_obscured = TRUE;  
1641 }
1642
1643 static gint
1644 gtk_entry_key_press (GtkWidget   *widget,
1645                      GdkEventKey *event)
1646 {
1647   GtkEntry *entry = GTK_ENTRY (widget);
1648
1649   gtk_entry_pend_cursor_blink (entry);
1650
1651   if (entry->editable)
1652     {
1653       if (gtk_im_context_filter_keypress (entry->im_context, event))
1654         {
1655           gtk_entry_obscure_mouse_cursor (entry);
1656           entry->need_im_reset = TRUE;
1657           return TRUE;
1658         }
1659     }
1660
1661   if (event->keyval == GDK_Return || event->keyval == GDK_ISO_Enter
1662       || event->keyval == GDK_Escape)
1663     {
1664       GtkEntryCompletion *completion = gtk_entry_get_completion (entry);
1665
1666       if (completion && completion->priv->completion_timeout)
1667         {
1668           g_source_remove (completion->priv->completion_timeout);
1669           completion->priv->completion_timeout = 0;
1670         }
1671     }
1672
1673   if (GTK_WIDGET_CLASS (parent_class)->key_press_event (widget, event))
1674     /* Activate key bindings
1675      */
1676     return TRUE;
1677
1678   return FALSE;
1679 }
1680
1681 static gint
1682 gtk_entry_key_release (GtkWidget   *widget,
1683                        GdkEventKey *event)
1684 {
1685   GtkEntry *entry = GTK_ENTRY (widget);
1686
1687   if (entry->editable)
1688     {
1689       if (gtk_im_context_filter_keypress (entry->im_context, event))
1690         {
1691           entry->need_im_reset = TRUE;
1692           return TRUE;
1693         }
1694     }
1695
1696   return GTK_WIDGET_CLASS (parent_class)->key_release_event (widget, event);
1697 }
1698
1699 static gint
1700 gtk_entry_focus_in (GtkWidget     *widget,
1701                     GdkEventFocus *event)
1702 {
1703   GtkEntry *entry = GTK_ENTRY (widget);
1704   
1705   gtk_widget_queue_draw (widget);
1706   
1707   entry->need_im_reset = TRUE;
1708   gtk_im_context_focus_in (entry->im_context);
1709
1710   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
1711                     "direction_changed",
1712                     G_CALLBACK (gtk_entry_keymap_direction_changed), entry);
1713
1714   gtk_entry_check_cursor_blink (entry);
1715
1716   return FALSE;
1717 }
1718
1719 static gint
1720 gtk_entry_focus_out (GtkWidget     *widget,
1721                      GdkEventFocus *event)
1722 {
1723   GtkEntry *entry = GTK_ENTRY (widget);
1724   GtkEntryCompletion *completion;
1725   
1726   gtk_widget_queue_draw (widget);
1727
1728   entry->need_im_reset = TRUE;
1729   gtk_im_context_focus_out (entry->im_context);
1730
1731   gtk_entry_check_cursor_blink (entry);
1732   
1733   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
1734                                         gtk_entry_keymap_direction_changed,
1735                                         entry);
1736
1737   completion = gtk_entry_get_completion (entry);
1738   if (completion)
1739     _gtk_entry_completion_popdown (completion);
1740   
1741   return FALSE;
1742 }
1743
1744 static void
1745 gtk_entry_grab_focus (GtkWidget        *widget)
1746 {
1747   GtkEntry *entry = GTK_ENTRY (widget);
1748   gboolean select_on_focus;
1749   
1750   GTK_WIDGET_CLASS (parent_class)->grab_focus (widget);
1751
1752   g_object_get (gtk_widget_get_settings (widget),
1753                 "gtk-entry-select-on-focus",
1754                 &select_on_focus,
1755                 NULL);
1756   
1757   if (select_on_focus && entry->editable && !entry->in_click)
1758     gtk_editable_select_region (GTK_EDITABLE (widget), 0, -1);
1759 }
1760
1761 static void 
1762 gtk_entry_direction_changed (GtkWidget        *widget,
1763                              GtkTextDirection  previous_dir)
1764 {
1765   GtkEntry *entry = GTK_ENTRY (widget);
1766
1767   gtk_entry_recompute (entry);
1768       
1769   GTK_WIDGET_CLASS (parent_class)->direction_changed (widget, previous_dir);
1770 }
1771
1772 static void
1773 gtk_entry_state_changed (GtkWidget      *widget,
1774                          GtkStateType    previous_state)
1775 {
1776   GtkEntry *entry = GTK_ENTRY (widget);
1777   
1778   if (GTK_WIDGET_REALIZED (widget))
1779     {
1780       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1781       gdk_window_set_background (entry->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1782     }
1783
1784   if (!GTK_WIDGET_IS_SENSITIVE (widget))
1785     {
1786       /* Clear any selection */
1787       gtk_editable_select_region (GTK_EDITABLE (entry), entry->current_pos, entry->current_pos);      
1788     }
1789   
1790   gtk_widget_queue_draw (widget);
1791 }
1792
1793 static void
1794 gtk_entry_screen_changed (GtkWidget *widget,
1795                           GdkScreen *old_screen)
1796 {
1797   gtk_entry_recompute (GTK_ENTRY (widget));
1798 }
1799
1800 /* GtkEditable method implementations
1801  */
1802 static void
1803 gtk_entry_insert_text (GtkEditable *editable,
1804                        const gchar *new_text,
1805                        gint         new_text_length,
1806                        gint        *position)
1807 {
1808   GtkEntry *entry = GTK_ENTRY (editable);
1809   gchar buf[64];
1810   gchar *text;
1811
1812   if (*position < 0 || *position > entry->text_length)
1813     *position = entry->text_length;
1814   
1815   g_object_ref (editable);
1816   
1817   if (new_text_length <= 63)
1818     text = buf;
1819   else
1820     text = g_new (gchar, new_text_length + 1);
1821
1822   text[new_text_length] = '\0';
1823   strncpy (text, new_text, new_text_length);
1824   
1825   g_signal_emit_by_name (editable, "insert_text", text, new_text_length, position);
1826
1827   if (new_text_length > 63)
1828     g_free (text);
1829
1830   g_object_unref (editable);
1831 }
1832
1833 static void
1834 gtk_entry_delete_text (GtkEditable *editable,
1835                        gint         start_pos,
1836                        gint         end_pos)
1837 {
1838   GtkEntry *entry = GTK_ENTRY (editable);
1839
1840   if (end_pos < 0 || end_pos > entry->text_length)
1841     end_pos = entry->text_length;
1842   if (start_pos < 0)
1843     start_pos = 0;
1844   if (start_pos > end_pos)
1845     start_pos = end_pos;
1846   
1847   g_object_ref (editable);
1848
1849   g_signal_emit_by_name (editable, "delete_text", start_pos, end_pos);
1850
1851   g_object_unref (editable);
1852 }
1853
1854 static gchar *    
1855 gtk_entry_get_chars      (GtkEditable   *editable,
1856                           gint           start_pos,
1857                           gint           end_pos)
1858 {
1859   GtkEntry *entry = GTK_ENTRY (editable);
1860   gint start_index, end_index;
1861   
1862   if (end_pos < 0)
1863     end_pos = entry->text_length;
1864
1865   start_pos = MIN (entry->text_length, start_pos);
1866   end_pos = MIN (entry->text_length, end_pos);
1867
1868   start_index = g_utf8_offset_to_pointer (entry->text, start_pos) - entry->text;
1869   end_index = g_utf8_offset_to_pointer (entry->text, end_pos) - entry->text;
1870
1871   return g_strndup (entry->text + start_index, end_index - start_index);
1872 }
1873
1874 static void
1875 gtk_entry_set_position_internal (GtkEntry    *entry,
1876                                  gint         position,
1877                                  gboolean     reset_im)
1878 {
1879   if (position < 0 || position > entry->text_length)
1880     position = entry->text_length;
1881
1882   if (position != entry->current_pos ||
1883       position != entry->selection_bound)
1884     {
1885       if (reset_im)
1886         gtk_entry_reset_im_context (entry);
1887       gtk_entry_set_positions (entry, position, position);
1888     }
1889 }
1890
1891 static void
1892 gtk_entry_real_set_position (GtkEditable *editable,
1893                              gint         position)
1894 {
1895   gtk_entry_set_position_internal (GTK_ENTRY (editable), position, TRUE);
1896 }
1897
1898 static gint
1899 gtk_entry_get_position (GtkEditable *editable)
1900 {
1901   return GTK_ENTRY (editable)->current_pos;
1902 }
1903
1904 static void
1905 gtk_entry_set_selection_bounds (GtkEditable *editable,
1906                                 gint         start,
1907                                 gint         end)
1908 {
1909   GtkEntry *entry = GTK_ENTRY (editable);
1910
1911   if (start < 0)
1912     start = entry->text_length;
1913   if (end < 0)
1914     end = entry->text_length;
1915   
1916   gtk_entry_reset_im_context (entry);
1917
1918   gtk_entry_set_positions (entry,
1919                            MIN (end, entry->text_length),
1920                            MIN (start, entry->text_length));
1921
1922   gtk_entry_update_primary_selection (entry);
1923 }
1924
1925 static gboolean
1926 gtk_entry_get_selection_bounds (GtkEditable *editable,
1927                                 gint        *start,
1928                                 gint        *end)
1929 {
1930   GtkEntry *entry = GTK_ENTRY (editable);
1931
1932   *start = entry->selection_bound;
1933   *end = entry->current_pos;
1934
1935   return (entry->selection_bound != entry->current_pos);
1936 }
1937
1938 static void 
1939 gtk_entry_style_set     (GtkWidget      *widget,
1940                          GtkStyle       *previous_style)
1941 {
1942   GtkEntry *entry = GTK_ENTRY (widget);
1943
1944   gtk_entry_recompute (entry);
1945
1946   if (previous_style && GTK_WIDGET_REALIZED (widget))
1947     {
1948       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1949       gdk_window_set_background (entry->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1950     }
1951 }
1952
1953 /* GtkCellEditable method implementations
1954  */
1955 static void
1956 gtk_cell_editable_entry_activated (GtkEntry *entry, gpointer data)
1957 {
1958   gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1959   gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1960 }
1961
1962 static gboolean
1963 gtk_cell_editable_key_press_event (GtkEntry    *entry,
1964                                    GdkEventKey *key_event,
1965                                    gpointer     data)
1966 {
1967   if (key_event->keyval == GDK_Escape)
1968     {
1969       entry->editing_canceled = TRUE;
1970       gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1971       gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1972
1973       return TRUE;
1974     }
1975
1976   /* override focus */
1977   if (key_event->keyval == GDK_Up || key_event->keyval == GDK_Down)
1978     {
1979       gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1980       gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1981
1982       return TRUE;
1983     }
1984
1985   return FALSE;
1986 }
1987
1988 static void
1989 gtk_entry_start_editing (GtkCellEditable *cell_editable,
1990                          GdkEvent        *event)
1991 {
1992   GTK_ENTRY (cell_editable)->is_cell_renderer = TRUE;
1993
1994   g_signal_connect (cell_editable, "activate",
1995                     G_CALLBACK (gtk_cell_editable_entry_activated), NULL);
1996   g_signal_connect (cell_editable, "key_press_event",
1997                     G_CALLBACK (gtk_cell_editable_key_press_event), NULL);
1998 }
1999
2000 /* Default signal handlers
2001  */
2002 static void
2003 gtk_entry_real_insert_text (GtkEditable *editable,
2004                             const gchar *new_text,
2005                             gint         new_text_length,
2006                             gint        *position)
2007 {
2008   gint index;
2009   gint n_chars;
2010
2011   GtkEntry *entry = GTK_ENTRY (editable);
2012
2013   if (new_text_length < 0)
2014     new_text_length = strlen (new_text);
2015
2016   n_chars = g_utf8_strlen (new_text, new_text_length);
2017   if (entry->text_max_length > 0 && n_chars + entry->text_length > entry->text_max_length)
2018     {
2019       gdk_display_beep (gtk_widget_get_display (GTK_WIDGET (entry)));
2020       n_chars = entry->text_max_length - entry->text_length;
2021       new_text_length = g_utf8_offset_to_pointer (new_text, n_chars) - new_text;
2022     }
2023
2024   if (new_text_length + entry->n_bytes + 1 > entry->text_size)
2025     {
2026       while (new_text_length + entry->n_bytes + 1 > entry->text_size)
2027         {
2028           if (entry->text_size == 0)
2029             entry->text_size = MIN_SIZE;
2030           else
2031             {
2032               if (2 * (guint)entry->text_size < MAX_SIZE &&
2033                   2 * (guint)entry->text_size > entry->text_size)
2034                 entry->text_size *= 2;
2035               else
2036                 {
2037                   entry->text_size = MAX_SIZE;
2038                   if (new_text_length > (gint)entry->text_size - (gint)entry->n_bytes - 1)
2039                     {
2040                       new_text_length = (gint)entry->text_size - (gint)entry->n_bytes - 1;
2041                       new_text_length = g_utf8_find_prev_char (new_text, new_text + new_text_length + 1) - new_text;
2042                       n_chars = g_utf8_strlen (new_text, new_text_length);
2043                     }
2044                   break;
2045                 }
2046             }
2047         }
2048
2049       entry->text = g_realloc (entry->text, entry->text_size);
2050     }
2051
2052   index = g_utf8_offset_to_pointer (entry->text, *position) - entry->text;
2053
2054   g_memmove (entry->text + index + new_text_length, entry->text + index, entry->n_bytes - index);
2055   memcpy (entry->text + index, new_text, new_text_length);
2056
2057   entry->n_bytes += new_text_length;
2058   entry->text_length += n_chars;
2059
2060   /* NUL terminate for safety and convenience */
2061   entry->text[entry->n_bytes] = '\0';
2062   
2063   if (entry->current_pos > *position)
2064     entry->current_pos += n_chars;
2065   
2066   if (entry->selection_bound > *position)
2067     entry->selection_bound += n_chars;
2068
2069   *position += n_chars;
2070
2071   gtk_entry_recompute (entry);
2072
2073   g_signal_emit_by_name (editable, "changed");
2074   g_object_notify (G_OBJECT (editable), "text");
2075 }
2076
2077 static void
2078 gtk_entry_real_delete_text (GtkEditable *editable,
2079                             gint         start_pos,
2080                             gint         end_pos)
2081 {
2082   GtkEntry *entry = GTK_ENTRY (editable);
2083
2084   if (start_pos < 0)
2085     start_pos = 0;
2086   if (end_pos < 0 || end_pos > entry->text_length)
2087     end_pos = entry->text_length;
2088   
2089   if (start_pos < end_pos)
2090     {
2091       gint start_index = g_utf8_offset_to_pointer (entry->text, start_pos) - entry->text;
2092       gint end_index = g_utf8_offset_to_pointer (entry->text, end_pos) - entry->text;
2093       gint current_pos;
2094       gint selection_bound;
2095
2096       g_memmove (entry->text + start_index, entry->text + end_index, entry->n_bytes + 1 - end_index);
2097       entry->text_length -= (end_pos - start_pos);
2098       entry->n_bytes -= (end_index - start_index);
2099       
2100       current_pos = entry->current_pos;
2101       if (current_pos > start_pos)
2102         current_pos -= MIN (current_pos, end_pos) - start_pos;
2103
2104       selection_bound = entry->selection_bound;
2105       if (selection_bound > start_pos)
2106         selection_bound -= MIN (selection_bound, end_pos) - start_pos;
2107
2108       gtk_entry_set_positions (entry, current_pos, selection_bound);
2109
2110       /* We might have deleted the selection
2111        */
2112       gtk_entry_update_primary_selection (entry);
2113       
2114       gtk_entry_recompute (entry);
2115
2116       g_signal_emit_by_name (editable, "changed");
2117       g_object_notify (G_OBJECT (editable), "text");
2118     }
2119 }
2120
2121 /* Compute the X position for an offset that corresponds to the "more important
2122  * cursor position for that offset. We use this when trying to guess to which
2123  * end of the selection we should go to when the user hits the left or
2124  * right arrow key.
2125  */
2126 static gint
2127 get_better_cursor_x (GtkEntry *entry,
2128                      gint      offset)
2129 {
2130   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
2131   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
2132   gboolean split_cursor;
2133   
2134   PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
2135   const gchar *text = pango_layout_get_text (layout);
2136   gint index = g_utf8_offset_to_pointer (text, offset) - text;
2137   
2138   PangoRectangle strong_pos, weak_pos;
2139   
2140   g_object_get (gtk_widget_get_settings (GTK_WIDGET (entry)),
2141                 "gtk-split-cursor", &split_cursor,
2142                 NULL);
2143
2144   pango_layout_get_cursor_pos (layout, index, &strong_pos, &weak_pos);
2145
2146   if (split_cursor)
2147     return strong_pos.x / PANGO_SCALE;
2148   else
2149     return (keymap_direction == entry->resolved_dir) ? strong_pos.x / PANGO_SCALE : weak_pos.x / PANGO_SCALE;
2150 }
2151
2152 static void
2153 gtk_entry_move_cursor (GtkEntry       *entry,
2154                        GtkMovementStep step,
2155                        gint            count,
2156                        gboolean        extend_selection)
2157 {
2158   gint new_pos = entry->current_pos;
2159
2160   gtk_entry_reset_im_context (entry);
2161
2162   if (entry->current_pos != entry->selection_bound && !extend_selection)
2163     {
2164       /* If we have a current selection and aren't extending it, move to the
2165        * start/or end of the selection as appropriate
2166        */
2167       switch (step)
2168         {
2169         case GTK_MOVEMENT_VISUAL_POSITIONS:
2170           {
2171             gint current_x = get_better_cursor_x (entry, entry->current_pos);
2172             gint bound_x = get_better_cursor_x (entry, entry->selection_bound);
2173
2174             if (count < 0)
2175               new_pos = current_x < bound_x ? entry->current_pos : entry->selection_bound;
2176             else
2177               new_pos = current_x > bound_x ? entry->current_pos : entry->selection_bound;
2178
2179             break;
2180           }
2181         case GTK_MOVEMENT_LOGICAL_POSITIONS:
2182         case GTK_MOVEMENT_WORDS:
2183           if (count < 0)
2184             new_pos = MIN (entry->current_pos, entry->selection_bound);
2185           else
2186             new_pos = MAX (entry->current_pos, entry->selection_bound);
2187           break;
2188         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
2189         case GTK_MOVEMENT_PARAGRAPH_ENDS:
2190         case GTK_MOVEMENT_BUFFER_ENDS:
2191           new_pos = count < 0 ? 0 : entry->text_length;
2192           break;
2193         case GTK_MOVEMENT_DISPLAY_LINES:
2194         case GTK_MOVEMENT_PARAGRAPHS:
2195         case GTK_MOVEMENT_PAGES:
2196         case GTK_MOVEMENT_HORIZONTAL_PAGES:
2197           break;
2198         }
2199     }
2200   else
2201     {
2202       switch (step)
2203         {
2204         case GTK_MOVEMENT_LOGICAL_POSITIONS:
2205           new_pos = gtk_entry_move_logically (entry, new_pos, count);
2206           break;
2207         case GTK_MOVEMENT_VISUAL_POSITIONS:
2208           new_pos = gtk_entry_move_visually (entry, new_pos, count);
2209           break;
2210         case GTK_MOVEMENT_WORDS:
2211           while (count > 0)
2212             {
2213               new_pos = gtk_entry_move_forward_word (entry, new_pos);
2214               count--;
2215             }
2216           while (count < 0)
2217             {
2218               new_pos = gtk_entry_move_backward_word (entry, new_pos);
2219               count++;
2220             }
2221           break;
2222         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
2223         case GTK_MOVEMENT_PARAGRAPH_ENDS:
2224         case GTK_MOVEMENT_BUFFER_ENDS:
2225           new_pos = count < 0 ? 0 : entry->text_length;
2226           break;
2227         case GTK_MOVEMENT_DISPLAY_LINES:
2228         case GTK_MOVEMENT_PARAGRAPHS:
2229         case GTK_MOVEMENT_PAGES:
2230         case GTK_MOVEMENT_HORIZONTAL_PAGES:
2231           break;
2232         }
2233     }
2234
2235   if (extend_selection)
2236     gtk_editable_select_region (GTK_EDITABLE (entry), entry->selection_bound, new_pos);
2237   else
2238     gtk_editable_set_position (GTK_EDITABLE (entry), new_pos);
2239   
2240   gtk_entry_pend_cursor_blink (entry);
2241 }
2242
2243 static void
2244 gtk_entry_insert_at_cursor (GtkEntry    *entry,
2245                             const gchar *str)
2246 {
2247   GtkEditable *editable = GTK_EDITABLE (entry);
2248   gint pos = entry->current_pos;
2249
2250   if (entry->editable)
2251     {
2252       gtk_entry_reset_im_context (entry);
2253
2254       gtk_editable_insert_text (editable, str, -1, &pos);
2255       gtk_editable_set_position (editable, pos);
2256     }
2257 }
2258
2259 static void
2260 gtk_entry_delete_from_cursor (GtkEntry       *entry,
2261                               GtkDeleteType   type,
2262                               gint            count)
2263 {
2264   GtkEditable *editable = GTK_EDITABLE (entry);
2265   gint start_pos = entry->current_pos;
2266   gint end_pos = entry->current_pos;
2267   
2268   gtk_entry_reset_im_context (entry);
2269
2270   if (!entry->editable)
2271     return;
2272
2273   if (entry->selection_bound != entry->current_pos)
2274     {
2275       gtk_editable_delete_selection (editable);
2276       return;
2277     }
2278   
2279   switch (type)
2280     {
2281     case GTK_DELETE_CHARS:
2282       end_pos = gtk_entry_move_logically (entry, entry->current_pos, count);
2283       gtk_editable_delete_text (editable, MIN (start_pos, end_pos), MAX (start_pos, end_pos));
2284       break;
2285     case GTK_DELETE_WORDS:
2286       if (count < 0)
2287         {
2288           /* Move to end of current word, or if not on a word, end of previous word */
2289           end_pos = gtk_entry_move_backward_word (entry, end_pos);
2290           end_pos = gtk_entry_move_forward_word (entry, end_pos);
2291         }
2292       else if (count > 0)
2293         {
2294           /* Move to beginning of current word, or if not on a word, begining of next word */
2295           start_pos = gtk_entry_move_forward_word (entry, start_pos);
2296           start_pos = gtk_entry_move_backward_word (entry, start_pos);
2297         }
2298         
2299       /* Fall through */
2300     case GTK_DELETE_WORD_ENDS:
2301       while (count < 0)
2302         {
2303           start_pos = gtk_entry_move_backward_word (entry, start_pos);
2304           count++;
2305         }
2306       while (count > 0)
2307         {
2308           end_pos = gtk_entry_move_forward_word (entry, end_pos);
2309           count--;
2310         }
2311       gtk_editable_delete_text (editable, start_pos, end_pos);
2312       break;
2313     case GTK_DELETE_DISPLAY_LINE_ENDS:
2314     case GTK_DELETE_PARAGRAPH_ENDS:
2315       if (count < 0)
2316         gtk_editable_delete_text (editable, 0, entry->current_pos);
2317       else
2318         gtk_editable_delete_text (editable, entry->current_pos, -1);
2319       break;
2320     case GTK_DELETE_DISPLAY_LINES:
2321     case GTK_DELETE_PARAGRAPHS:
2322       gtk_editable_delete_text (editable, 0, -1);  
2323       break;
2324     case GTK_DELETE_WHITESPACE:
2325       gtk_entry_delete_whitespace (entry);
2326       break;
2327     }
2328   
2329   gtk_entry_pend_cursor_blink (entry);
2330 }
2331
2332 static void
2333 gtk_entry_copy_clipboard (GtkEntry *entry)
2334 {
2335   GtkEditable *editable = GTK_EDITABLE (entry);
2336   gint start, end;
2337
2338   if (gtk_editable_get_selection_bounds (editable, &start, &end))
2339     {
2340       gchar *str = gtk_entry_get_public_chars (entry, start, end);
2341       gtk_clipboard_set_text (gtk_widget_get_clipboard (GTK_WIDGET (entry),
2342                                                         GDK_SELECTION_CLIPBOARD),
2343                               str, -1);
2344       g_free (str);
2345     }
2346 }
2347
2348 static void
2349 gtk_entry_cut_clipboard (GtkEntry *entry)
2350 {
2351   GtkEditable *editable = GTK_EDITABLE (entry);
2352   gint start, end;
2353
2354   gtk_entry_copy_clipboard (entry);
2355
2356   if (entry->editable)
2357     {
2358       if (gtk_editable_get_selection_bounds (editable, &start, &end))
2359         gtk_editable_delete_text (editable, start, end);
2360     }
2361 }
2362
2363 static void
2364 gtk_entry_paste_clipboard (GtkEntry *entry)
2365 {
2366   if (entry->editable)
2367     gtk_entry_paste (entry, GDK_NONE);
2368 }
2369
2370 static void
2371 gtk_entry_delete_cb (GtkEntry *entry)
2372 {
2373   GtkEditable *editable = GTK_EDITABLE (entry);
2374   gint start, end;
2375
2376   if (entry->editable)
2377     {
2378       if (gtk_editable_get_selection_bounds (editable, &start, &end))
2379         gtk_editable_delete_text (editable, start, end);
2380     }
2381 }
2382
2383 static void
2384 gtk_entry_toggle_overwrite (GtkEntry *entry)
2385 {
2386   entry->overwrite_mode = !entry->overwrite_mode;
2387 }
2388
2389 static void
2390 gtk_entry_select_all (GtkEntry *entry)
2391 {
2392   gtk_entry_select_line (entry);
2393 }
2394
2395 static void
2396 gtk_entry_real_activate (GtkEntry *entry)
2397 {
2398   GtkWindow *window;
2399   GtkWidget *toplevel;
2400   GtkWidget *widget;
2401
2402   widget = GTK_WIDGET (entry);
2403
2404   if (entry->activates_default)
2405     {
2406       toplevel = gtk_widget_get_toplevel (widget);
2407       if (GTK_IS_WINDOW (toplevel))
2408         {
2409           window = GTK_WINDOW (toplevel);
2410       
2411           if (window &&
2412               widget != window->default_widget &&
2413               !(widget == window->focus_widget &&
2414                 (!window->default_widget || !GTK_WIDGET_SENSITIVE (window->default_widget))))
2415             gtk_window_activate_default (window);
2416         }
2417     }
2418 }
2419
2420 static void
2421 gtk_entry_keymap_direction_changed (GdkKeymap *keymap,
2422                                     GtkEntry  *entry)
2423 {
2424   gtk_entry_recompute (entry);
2425 }
2426
2427 /* IM Context Callbacks
2428  */
2429
2430 static void
2431 gtk_entry_commit_cb (GtkIMContext *context,
2432                      const gchar  *str,
2433                      GtkEntry     *entry)
2434 {
2435   gtk_entry_enter_text (entry, str);
2436 }
2437
2438 static void 
2439 gtk_entry_preedit_changed_cb (GtkIMContext *context,
2440                               GtkEntry     *entry)
2441 {
2442   gchar *preedit_string;
2443   gint cursor_pos;
2444   
2445   gtk_im_context_get_preedit_string (entry->im_context,
2446                                      &preedit_string, NULL,
2447                                      &cursor_pos);
2448   entry->preedit_length = strlen (preedit_string);
2449   cursor_pos = CLAMP (cursor_pos, 0, g_utf8_strlen (preedit_string, -1));
2450   entry->preedit_cursor = cursor_pos;
2451   g_free (preedit_string);
2452
2453   gtk_entry_recompute (entry);
2454 }
2455
2456 static gboolean
2457 gtk_entry_retrieve_surrounding_cb (GtkIMContext *context,
2458                                GtkEntry     *entry)
2459 {
2460   gtk_im_context_set_surrounding (context,
2461                                   entry->text,
2462                                   entry->n_bytes,
2463                                   g_utf8_offset_to_pointer (entry->text, entry->current_pos) - entry->text);
2464
2465   return TRUE;
2466 }
2467
2468 static gboolean
2469 gtk_entry_delete_surrounding_cb (GtkIMContext *slave,
2470                                  gint          offset,
2471                                  gint          n_chars,
2472                                  GtkEntry     *entry)
2473 {
2474   gtk_editable_delete_text (GTK_EDITABLE (entry),
2475                             entry->current_pos + offset,
2476                             entry->current_pos + offset + n_chars);
2477
2478   return TRUE;
2479 }
2480
2481 /* Internal functions
2482  */
2483
2484 /* Used for im_commit_cb and inserting Unicode chars */
2485 static void
2486 gtk_entry_enter_text (GtkEntry       *entry,
2487                       const gchar    *str)
2488 {
2489   GtkEditable *editable = GTK_EDITABLE (entry);
2490   gint tmp_pos;
2491
2492   if (gtk_editable_get_selection_bounds (editable, NULL, NULL))
2493     gtk_editable_delete_selection (editable);
2494   else
2495     {
2496       if (entry->overwrite_mode)
2497         gtk_entry_delete_from_cursor (entry, GTK_DELETE_CHARS, 1);
2498     }
2499
2500   tmp_pos = entry->current_pos;
2501   gtk_editable_insert_text (editable, str, strlen (str), &tmp_pos);
2502   gtk_entry_set_position_internal (entry, tmp_pos, FALSE);
2503 }
2504
2505 /* All changes to entry->current_pos and entry->selection_bound
2506  * should go through this function.
2507  */
2508 static void
2509 gtk_entry_set_positions (GtkEntry *entry,
2510                          gint      current_pos,
2511                          gint      selection_bound)
2512 {
2513   gboolean changed = FALSE;
2514
2515   g_object_freeze_notify (G_OBJECT (entry));
2516   
2517   if (current_pos != -1 &&
2518       entry->current_pos != current_pos)
2519     {
2520       entry->current_pos = current_pos;
2521       changed = TRUE;
2522
2523       g_object_notify (G_OBJECT (entry), "cursor_position");
2524     }
2525
2526   if (selection_bound != -1 &&
2527       entry->selection_bound != selection_bound)
2528     {
2529       entry->selection_bound = selection_bound;
2530       changed = TRUE;
2531       
2532       g_object_notify (G_OBJECT (entry), "selection_bound");
2533     }
2534
2535   g_object_thaw_notify (G_OBJECT (entry));
2536
2537   if (changed)
2538     gtk_entry_recompute (entry);
2539 }
2540
2541 static void
2542 gtk_entry_reset_layout (GtkEntry *entry)
2543 {
2544   if (entry->cached_layout)
2545     {
2546       g_object_unref (entry->cached_layout);
2547       entry->cached_layout = NULL;
2548     }
2549 }
2550
2551 static void
2552 update_im_cursor_location (GtkEntry *entry)
2553 {
2554   GdkRectangle area;
2555   gint strong_x;
2556   gint strong_xoffset;
2557   gint area_width, area_height;
2558
2559   gtk_entry_get_cursor_locations (entry, CURSOR_STANDARD, &strong_x, NULL)
2560 ;
2561   get_text_area_size (entry, NULL, NULL, &area_width, &area_height);
2562
2563   strong_xoffset = strong_x - entry->scroll_offset;
2564   if (strong_xoffset < 0)
2565     {
2566       strong_xoffset = 0;
2567     }
2568   else if (strong_xoffset > area_width)
2569     {
2570       strong_xoffset = area_width;
2571     }
2572   area.x = strong_xoffset;
2573   area.y = 0;
2574   area.width = 0;
2575   area.height = area_height;
2576
2577   gtk_im_context_set_cursor_location (entry->im_context, &area);
2578 }
2579
2580 static gboolean
2581 recompute_idle_func (gpointer data)
2582 {
2583   GtkEntry *entry;
2584
2585   GDK_THREADS_ENTER ();
2586
2587   entry = GTK_ENTRY (data);
2588
2589   entry->recompute_idle = 0;
2590   
2591   if (gtk_widget_has_screen (GTK_WIDGET (entry)))
2592     {
2593       gtk_entry_adjust_scroll (entry);
2594       gtk_entry_queue_draw (entry);
2595       
2596       update_im_cursor_location (entry);
2597     }
2598
2599   GDK_THREADS_LEAVE ();
2600
2601   return FALSE;
2602 }
2603
2604 static void
2605 gtk_entry_recompute (GtkEntry *entry)
2606 {
2607   gtk_entry_reset_layout (entry);
2608   gtk_entry_check_cursor_blink (entry);
2609   
2610   if (!entry->recompute_idle)
2611     {
2612       entry->recompute_idle = g_idle_add_full (G_PRIORITY_HIGH_IDLE + 15, /* between resize and redraw */
2613                                                recompute_idle_func, entry, NULL); 
2614     }
2615 }
2616
2617 static void
2618 append_char (GString *str,
2619              gunichar ch,
2620              gint     count)
2621 {
2622   gint i;
2623   gint char_len;
2624   gchar buf[7];
2625   
2626   char_len = g_unichar_to_utf8 (ch, buf);
2627   
2628   i = 0;
2629   while (i < count)
2630     {
2631       g_string_append_len (str, buf, char_len);
2632       ++i;
2633     }
2634 }
2635      
2636 static PangoLayout *
2637 gtk_entry_create_layout (GtkEntry *entry,
2638                          gboolean  include_preedit)
2639 {
2640   GtkWidget *widget = GTK_WIDGET (entry);
2641   PangoLayout *layout = gtk_widget_create_pango_layout (widget, NULL);
2642   PangoAttrList *tmp_attrs = pango_attr_list_new ();
2643   
2644   gchar *preedit_string = NULL;
2645   gint preedit_length = 0;
2646   PangoAttrList *preedit_attrs = NULL;
2647
2648   pango_layout_set_single_paragraph_mode (layout, TRUE);
2649   
2650   if (include_preedit)
2651     {
2652       gtk_im_context_get_preedit_string (entry->im_context,
2653                                          &preedit_string, &preedit_attrs, NULL);
2654       preedit_length = entry->preedit_length;
2655     }
2656
2657   if (preedit_length)
2658     {
2659       GString *tmp_string = g_string_new (NULL);
2660       
2661       gint cursor_index = g_utf8_offset_to_pointer (entry->text, entry->current_pos) - entry->text;
2662       
2663       if (entry->visible)
2664         {
2665           g_string_prepend_len (tmp_string, entry->text, entry->n_bytes);
2666           g_string_insert (tmp_string, cursor_index, preedit_string);
2667         }
2668       else
2669         {
2670           gint ch_len;
2671           gint preedit_len_chars;
2672           gunichar invisible_char;
2673           
2674           ch_len = g_utf8_strlen (entry->text, entry->n_bytes);
2675           preedit_len_chars = g_utf8_strlen (preedit_string, -1);
2676           ch_len += preedit_len_chars;
2677
2678           if (entry->invisible_char != 0)
2679             invisible_char = entry->invisible_char;
2680           else
2681             invisible_char = ' '; /* just pick a char */
2682           
2683           append_char (tmp_string, invisible_char, ch_len);
2684           
2685           /* Fix cursor index to point to invisible char corresponding
2686            * to the preedit, fix preedit_length to be the length of
2687            * the invisible chars representing the preedit
2688            */
2689           cursor_index =
2690             g_utf8_offset_to_pointer (tmp_string->str, entry->current_pos) -
2691             tmp_string->str;
2692           preedit_length =
2693             preedit_len_chars *
2694             g_unichar_to_utf8 (invisible_char, NULL);
2695         }
2696       
2697       pango_layout_set_text (layout, tmp_string->str, tmp_string->len);
2698       
2699       pango_attr_list_splice (tmp_attrs, preedit_attrs,
2700                               cursor_index, preedit_length);
2701       
2702       g_string_free (tmp_string, TRUE);
2703     }
2704   else
2705     {
2706       PangoDirection pango_dir;
2707       
2708       pango_dir = pango_find_base_dir (entry->text, entry->n_bytes);
2709       if (pango_dir == PANGO_DIRECTION_NEUTRAL)
2710         {
2711           if (GTK_WIDGET_HAS_FOCUS (widget))
2712             {
2713               GdkDisplay *display = gtk_widget_get_display (widget);
2714               GdkKeymap *keymap = gdk_keymap_get_for_display (display);
2715               pango_dir = gdk_keymap_get_direction (keymap);
2716             }
2717           else
2718             {
2719               if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2720                 pango_dir = PANGO_DIRECTION_LTR;
2721               else
2722                 pango_dir = PANGO_DIRECTION_RTL;
2723             }
2724         }
2725
2726       pango_context_set_base_dir (gtk_widget_get_pango_context (widget),
2727                                   pango_dir);
2728
2729       pango_layout_set_alignment (layout, pango_dir);
2730
2731       entry->resolved_dir = pango_dir;
2732       
2733       if (entry->visible)
2734         {
2735           pango_layout_set_text (layout, entry->text, entry->n_bytes);
2736         }
2737       else
2738         {
2739           GString *str = g_string_new (NULL);
2740           gunichar invisible_char;
2741           
2742           if (entry->invisible_char != 0)
2743             invisible_char = entry->invisible_char;
2744           else
2745             invisible_char = ' '; /* just pick a char */
2746           
2747           append_char (str, invisible_char, entry->text_length);
2748           pango_layout_set_text (layout, str->str, str->len);
2749           g_string_free (str, TRUE);
2750         }
2751     }
2752       
2753   pango_layout_set_attributes (layout, tmp_attrs);
2754
2755   if (preedit_string)
2756     g_free (preedit_string);
2757   if (preedit_attrs)
2758     pango_attr_list_unref (preedit_attrs);
2759       
2760   pango_attr_list_unref (tmp_attrs);
2761
2762   return layout;
2763 }
2764
2765 static PangoLayout *
2766 gtk_entry_ensure_layout (GtkEntry *entry,
2767                          gboolean  include_preedit)
2768 {
2769   if (entry->preedit_length > 0 &&
2770       !include_preedit != !entry->cache_includes_preedit)
2771     gtk_entry_reset_layout (entry);
2772
2773   if (!entry->cached_layout)
2774     {
2775       entry->cached_layout = gtk_entry_create_layout (entry, include_preedit);
2776       entry->cache_includes_preedit = include_preedit;
2777     }
2778   
2779   return entry->cached_layout;
2780 }
2781
2782 static void
2783 get_layout_position (GtkEntry *entry,
2784                      gint     *x,
2785                      gint     *y)
2786 {
2787   PangoLayout *layout;
2788   PangoRectangle logical_rect;
2789   gint area_width, area_height;
2790   gint y_pos;
2791   PangoLayoutLine *line;
2792   
2793   layout = gtk_entry_ensure_layout (entry, TRUE);
2794
2795   get_text_area_size (entry, NULL, NULL, &area_width, &area_height);      
2796       
2797   area_height = PANGO_SCALE * (area_height - 2 * INNER_BORDER);
2798   
2799   line = pango_layout_get_lines (layout)->data;
2800   pango_layout_line_get_extents (line, NULL, &logical_rect);
2801   
2802   /* Align primarily for locale's ascent/descent */
2803   y_pos = ((area_height - entry->ascent - entry->descent) / 2 + 
2804            entry->ascent + logical_rect.y);
2805   
2806   /* Now see if we need to adjust to fit in actual drawn string */
2807   if (logical_rect.height > area_height)
2808     y_pos = (area_height - logical_rect.height) / 2;
2809   else if (y_pos < 0)
2810     y_pos = 0;
2811   else if (y_pos + logical_rect.height > area_height)
2812     y_pos = area_height - logical_rect.height;
2813   
2814   y_pos = INNER_BORDER + y_pos / PANGO_SCALE;
2815
2816   if (x)
2817     *x = INNER_BORDER - entry->scroll_offset;
2818
2819   if (y)
2820     *y = y_pos;
2821 }
2822
2823 static void
2824 gtk_entry_draw_text (GtkEntry *entry)
2825 {
2826   GtkWidget *widget;
2827   PangoLayoutLine *line;
2828   
2829   if (!entry->visible && entry->invisible_char == 0)
2830     return;
2831   
2832   if (GTK_WIDGET_DRAWABLE (entry))
2833     {
2834       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
2835       gint x, y;
2836       gint start_pos, end_pos;
2837       
2838       widget = GTK_WIDGET (entry);
2839       
2840       get_layout_position (entry, &x, &y);
2841
2842       gdk_draw_layout (entry->text_area, widget->style->text_gc [widget->state],       
2843                        x, y,
2844                        layout);
2845       
2846       if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start_pos, &end_pos))
2847         {
2848           gint *ranges;
2849           gint n_ranges, i;
2850           PangoRectangle logical_rect;
2851           const gchar *text = pango_layout_get_text (layout);
2852           gint start_index = g_utf8_offset_to_pointer (text, start_pos) - text;
2853           gint end_index = g_utf8_offset_to_pointer (text, end_pos) - text;
2854           GdkRegion *clip_region = gdk_region_new ();
2855           GdkGC *text_gc;
2856           GdkGC *selection_gc;
2857
2858           line = pango_layout_get_lines (layout)->data;
2859           
2860           pango_layout_line_get_x_ranges (line, start_index, end_index, &ranges, &n_ranges);
2861
2862           pango_layout_get_extents (layout, NULL, &logical_rect);
2863           
2864           if (GTK_WIDGET_HAS_FOCUS (entry))
2865             {
2866               selection_gc = widget->style->base_gc [GTK_STATE_SELECTED];
2867               text_gc = widget->style->text_gc [GTK_STATE_SELECTED];
2868             }
2869           else
2870             {
2871               selection_gc = widget->style->base_gc [GTK_STATE_ACTIVE];
2872               text_gc = widget->style->text_gc [GTK_STATE_ACTIVE];
2873             }
2874           
2875           for (i=0; i < n_ranges; i++)
2876             {
2877               GdkRectangle rect;
2878
2879               rect.x = INNER_BORDER - entry->scroll_offset + ranges[2*i] / PANGO_SCALE;
2880               rect.y = y;
2881               rect.width = (ranges[2*i + 1] - ranges[2*i]) / PANGO_SCALE;
2882               rect.height = logical_rect.height / PANGO_SCALE;
2883                 
2884               gdk_draw_rectangle (entry->text_area, selection_gc, TRUE,
2885                                   rect.x, rect.y, rect.width, rect.height);
2886
2887               gdk_region_union_with_rect (clip_region, &rect);
2888             }
2889
2890           gdk_gc_set_clip_region (text_gc, clip_region);
2891           gdk_draw_layout (entry->text_area, text_gc, 
2892                            x, y,
2893                            layout);
2894           gdk_gc_set_clip_region (text_gc, NULL);
2895           
2896           gdk_region_destroy (clip_region);
2897           g_free (ranges);
2898         }
2899     }
2900 }
2901
2902 static void
2903 draw_insertion_cursor (GtkEntry      *entry,
2904                        GdkRectangle  *cursor_location,
2905                        gboolean       is_primary,
2906                        PangoDirection direction,
2907                        gboolean       draw_arrow)
2908 {
2909   GtkWidget *widget = GTK_WIDGET (entry);
2910   GtkTextDirection text_dir;
2911
2912   if (direction == PANGO_DIRECTION_LTR)
2913     text_dir = GTK_TEXT_DIR_LTR;
2914   else
2915     text_dir = GTK_TEXT_DIR_RTL;
2916
2917   gtk_draw_insertion_cursor (widget, entry->text_area, NULL,
2918                              cursor_location,
2919                              is_primary, text_dir, draw_arrow);
2920 }
2921
2922 static void
2923 gtk_entry_draw_cursor (GtkEntry  *entry,
2924                        CursorType type)
2925 {
2926   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
2927   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
2928   
2929   if (GTK_WIDGET_DRAWABLE (entry))
2930     {
2931       GtkWidget *widget = GTK_WIDGET (entry);
2932       GdkRectangle cursor_location;
2933       gboolean split_cursor;
2934
2935       gint xoffset = INNER_BORDER - entry->scroll_offset;
2936       gint strong_x, weak_x;
2937       gint text_area_height;
2938       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
2939       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
2940       gint x1 = 0;
2941       gint x2 = 0;
2942
2943       gdk_drawable_get_size (entry->text_area, NULL, &text_area_height);
2944       
2945       gtk_entry_get_cursor_locations (entry, type, &strong_x, &weak_x);
2946
2947       g_object_get (gtk_widget_get_settings (widget),
2948                     "gtk-split-cursor", &split_cursor,
2949                     NULL);
2950
2951       dir1 = entry->resolved_dir;
2952       
2953       if (split_cursor)
2954         {
2955           x1 = strong_x;
2956
2957           if (weak_x != strong_x)
2958             {
2959               dir2 = (entry->resolved_dir == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
2960               x2 = weak_x;
2961             }
2962         }
2963       else
2964         {
2965           if (keymap_direction == entry->resolved_dir)
2966             x1 = strong_x;
2967           else
2968             x1 = weak_x;
2969         }
2970
2971       cursor_location.x = xoffset + x1;
2972       cursor_location.y = INNER_BORDER;
2973       cursor_location.width = 0;
2974       cursor_location.height = text_area_height - 2 * INNER_BORDER ;
2975
2976       draw_insertion_cursor (entry,
2977                              &cursor_location, TRUE, dir1,
2978                              dir2 != PANGO_DIRECTION_NEUTRAL);
2979       
2980       if (dir2 != PANGO_DIRECTION_NEUTRAL)
2981         {
2982           cursor_location.x = xoffset + x2;
2983           draw_insertion_cursor (entry,
2984                                  &cursor_location, FALSE, dir2,
2985                                  TRUE);
2986         }
2987     }
2988 }
2989
2990 static void
2991 gtk_entry_queue_draw (GtkEntry *entry)
2992 {
2993   if (GTK_WIDGET_REALIZED (entry))
2994     gdk_window_invalidate_rect (entry->text_area, NULL, FALSE);
2995 }
2996
2997 static void
2998 gtk_entry_reset_im_context (GtkEntry *entry)
2999 {
3000   if (entry->need_im_reset)
3001     {
3002       entry->need_im_reset = 0;
3003       gtk_im_context_reset (entry->im_context);
3004     }
3005 }
3006
3007 static gint
3008 gtk_entry_find_position (GtkEntry *entry,
3009                          gint      x)
3010 {
3011   PangoLayout *layout;
3012   PangoLayoutLine *line;
3013   gint index;
3014   gint pos;
3015   gboolean trailing;
3016   const gchar *text;
3017   gint cursor_index;
3018   
3019   layout = gtk_entry_ensure_layout (entry, TRUE);
3020   text = pango_layout_get_text (layout);
3021   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3022   
3023   line = pango_layout_get_lines (layout)->data;
3024   pango_layout_line_x_to_index (line, x * PANGO_SCALE, &index, &trailing);
3025
3026   if (index >= cursor_index && entry->preedit_length)
3027     {
3028       if (index >= cursor_index + entry->preedit_length)
3029         index -= entry->preedit_length;
3030       else
3031         {
3032           index = cursor_index;
3033           trailing = 0;
3034         }
3035     }
3036
3037   pos = g_utf8_pointer_to_offset (text, text + index);
3038   pos += trailing;
3039
3040   return pos;
3041 }
3042
3043 static void
3044 gtk_entry_get_cursor_locations (GtkEntry   *entry,
3045                                 CursorType  type,
3046                                 gint       *strong_x,
3047                                 gint       *weak_x)
3048 {
3049   if (!entry->visible && !entry->invisible_char)
3050     {
3051       if (strong_x)
3052         *strong_x = 0;
3053       
3054       if (weak_x)
3055         *weak_x = 0;
3056     }
3057   else
3058     {
3059       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
3060       const gchar *text = pango_layout_get_text (layout);
3061       PangoRectangle strong_pos, weak_pos;
3062       gint index;
3063   
3064       if (type == CURSOR_STANDARD)
3065         {
3066           index = g_utf8_offset_to_pointer (text, entry->current_pos + entry->preedit_cursor) - text;
3067         }
3068       else /* type == CURSOR_DND */
3069         {
3070           index = g_utf8_offset_to_pointer (text, entry->dnd_position) - text;
3071
3072           if (entry->dnd_position > entry->current_pos)
3073             {
3074               if (entry->visible)
3075                 index += entry->preedit_length;
3076               else
3077                 {
3078                   gint preedit_len_chars = g_utf8_strlen (text, -1) - entry->text_length;
3079                   index += preedit_len_chars * g_unichar_to_utf8 (entry->invisible_char, NULL);
3080                 }
3081             }
3082         }
3083       
3084       pango_layout_get_cursor_pos (layout, index, &strong_pos, &weak_pos);
3085       
3086       if (strong_x)
3087         *strong_x = strong_pos.x / PANGO_SCALE;
3088       
3089       if (weak_x)
3090         *weak_x = weak_pos.x / PANGO_SCALE;
3091     }
3092 }
3093
3094 static void
3095 gtk_entry_adjust_scroll (GtkEntry *entry)
3096 {
3097   GtkEntryPrivate *priv = GTK_ENTRY_GET_PRIVATE (entry);
3098   gint min_offset, max_offset;
3099   gint text_area_width, text_width;
3100   gint strong_x, weak_x;
3101   gint strong_xoffset, weak_xoffset;
3102   gfloat xalign;
3103   PangoLayout *layout;
3104   PangoLayoutLine *line;
3105   PangoRectangle logical_rect;
3106
3107   if (!GTK_WIDGET_REALIZED (entry))
3108     return;
3109   
3110   gdk_drawable_get_size (entry->text_area, &text_area_width, NULL);
3111   text_area_width -= 2 * INNER_BORDER;
3112
3113   layout = gtk_entry_ensure_layout (entry, TRUE);
3114   line = pango_layout_get_lines (layout)->data;
3115
3116   pango_layout_line_get_extents (line, NULL, &logical_rect);
3117
3118   /* Display as much text as we can */
3119
3120   if (entry->resolved_dir == PANGO_DIRECTION_LTR)
3121       xalign = priv->xalign;
3122   else
3123       xalign = 1.0 - priv->xalign;
3124
3125   text_width = PANGO_PIXELS(logical_rect.width);
3126
3127   if (text_width > text_area_width)
3128     {
3129       min_offset = 0;
3130       max_offset = text_width - text_area_width;
3131     }
3132   else
3133     {
3134       min_offset = (text_width - text_area_width) * xalign;
3135       max_offset = min_offset;
3136     }
3137
3138   entry->scroll_offset = CLAMP (entry->scroll_offset, min_offset, max_offset);
3139
3140   /* And make sure cursors are on screen. Note that the cursor is
3141    * actually drawn one pixel into the INNER_BORDER space on
3142    * the right, when the scroll is at the utmost right. This
3143    * looks better to to me than confining the cursor inside the
3144    * border entirely, though it means that the cursor gets one
3145    * pixel closer to the the edge of the widget on the right than
3146    * on the left. This might need changing if one changed
3147    * INNER_BORDER from 2 to 1, as one would do on a
3148    * small-screen-real-estate display.
3149    *
3150    * We always make sure that the strong cursor is on screen, and
3151    * put the weak cursor on screen if possible.
3152    */
3153
3154   gtk_entry_get_cursor_locations (entry, CURSOR_STANDARD, &strong_x, &weak_x);
3155   
3156   strong_xoffset = strong_x - entry->scroll_offset;
3157
3158   if (strong_xoffset < 0)
3159     {
3160       entry->scroll_offset += strong_xoffset;
3161       strong_xoffset = 0;
3162     }
3163   else if (strong_xoffset > text_area_width)
3164     {
3165       entry->scroll_offset += strong_xoffset - text_area_width;
3166       strong_xoffset = text_area_width;
3167     }
3168
3169   weak_xoffset = weak_x - entry->scroll_offset;
3170
3171   if (weak_xoffset < 0 && strong_xoffset - weak_xoffset <= text_area_width)
3172     {
3173       entry->scroll_offset += weak_xoffset;
3174     }
3175   else if (weak_xoffset > text_area_width &&
3176            strong_xoffset - (weak_xoffset - text_area_width) >= 0)
3177     {
3178       entry->scroll_offset += weak_xoffset - text_area_width;
3179     }
3180
3181   g_object_notify (G_OBJECT (entry), "scroll_offset");
3182 }
3183
3184 static gint
3185 gtk_entry_move_visually (GtkEntry *entry,
3186                          gint      start,
3187                          gint      count)
3188 {
3189   gint index;
3190   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3191   const gchar *text;
3192
3193   text = pango_layout_get_text (layout);
3194   
3195   index = g_utf8_offset_to_pointer (text, start) - text;
3196
3197   while (count != 0)
3198     {
3199       int new_index, new_trailing;
3200       gboolean split_cursor;
3201       gboolean strong;
3202
3203       g_object_get (gtk_widget_get_settings (GTK_WIDGET (entry)),
3204                     "gtk-split-cursor", &split_cursor,
3205                     NULL);
3206
3207       if (split_cursor)
3208         strong = TRUE;
3209       else
3210         {
3211           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
3212           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3213
3214           strong = keymap_direction == entry->resolved_dir;
3215         }
3216       
3217       if (count > 0)
3218         {
3219           pango_layout_move_cursor_visually (layout, strong, index, 0, 1, &new_index, &new_trailing);
3220           count--;
3221         }
3222       else
3223         {
3224           pango_layout_move_cursor_visually (layout, strong, index, 0, -1, &new_index, &new_trailing);
3225           count++;
3226         }
3227
3228       if (new_index < 0 || new_index == G_MAXINT)
3229         break;
3230
3231       index = new_index;
3232       
3233       while (new_trailing--)
3234         index = g_utf8_next_char (text + new_index) - text;
3235     }
3236   
3237   return g_utf8_pointer_to_offset (text, text + index);
3238 }
3239
3240 static gint
3241 gtk_entry_move_logically (GtkEntry *entry,
3242                           gint      start,
3243                           gint      count)
3244 {
3245   gint new_pos = start;
3246
3247   /* Prevent any leak of information */
3248   if (!entry->visible)
3249     {
3250       new_pos = CLAMP (start + count, 0, entry->text_length);
3251     }
3252   else if (entry->text)
3253     {
3254       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3255       PangoLogAttr *log_attrs;
3256       gint n_attrs;
3257
3258       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3259
3260       while (count > 0 && new_pos < entry->text_length)
3261         {
3262           do
3263             new_pos++;
3264           while (new_pos < entry->text_length && !log_attrs[new_pos].is_cursor_position);
3265           
3266           count--;
3267         }
3268       while (count < 0 && new_pos > 0)
3269         {
3270           do
3271             new_pos--;
3272           while (new_pos > 0 && !log_attrs[new_pos].is_cursor_position);
3273           
3274           count++;
3275         }
3276       
3277       g_free (log_attrs);
3278     }
3279
3280   return new_pos;
3281 }
3282
3283 static gint
3284 gtk_entry_move_forward_word (GtkEntry *entry,
3285                              gint      start)
3286 {
3287   gint new_pos = start;
3288
3289   /* Prevent any leak of information */
3290   if (!entry->visible)
3291     {
3292       new_pos = entry->text_length;
3293     }
3294   else if (entry->text && (new_pos < entry->text_length))
3295     {
3296       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3297       PangoLogAttr *log_attrs;
3298       gint n_attrs;
3299
3300       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3301       
3302       /* Find the next word end */
3303       new_pos++;
3304       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
3305         new_pos++;
3306
3307       g_free (log_attrs);
3308     }
3309
3310   return new_pos;
3311 }
3312
3313
3314 static gint
3315 gtk_entry_move_backward_word (GtkEntry *entry,
3316                               gint      start)
3317 {
3318   gint new_pos = start;
3319
3320   /* Prevent any leak of information */
3321   if (!entry->visible)
3322     {
3323       new_pos = 0;
3324     }
3325   else if (entry->text && start > 0)
3326     {
3327       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3328       PangoLogAttr *log_attrs;
3329       gint n_attrs;
3330
3331       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3332
3333       new_pos = start - 1;
3334
3335       /* Find the previous word beginning */
3336       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
3337         new_pos--;
3338
3339       g_free (log_attrs);
3340     }
3341
3342   return new_pos;
3343 }
3344
3345 static void
3346 gtk_entry_delete_whitespace (GtkEntry *entry)
3347 {
3348   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3349   PangoLogAttr *log_attrs;
3350   gint n_attrs;
3351   gint start, end;
3352
3353   pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3354
3355   start = end = entry->current_pos;
3356   
3357   while (start > 0 && log_attrs[start-1].is_white)
3358     start--;
3359
3360   while (end < n_attrs && log_attrs[end].is_white)
3361     end++;
3362
3363   g_free (log_attrs);
3364
3365   if (start != end)
3366     gtk_editable_delete_text (GTK_EDITABLE (entry), start, end);
3367 }
3368
3369
3370 static void
3371 gtk_entry_select_word (GtkEntry *entry)
3372 {
3373   gint start_pos = gtk_entry_move_backward_word (entry, entry->current_pos);
3374   gint end_pos = gtk_entry_move_forward_word (entry, entry->current_pos);
3375
3376   gtk_editable_select_region (GTK_EDITABLE (entry), start_pos, end_pos);
3377 }
3378
3379 static void
3380 gtk_entry_select_line (GtkEntry *entry)
3381 {
3382   gtk_editable_select_region (GTK_EDITABLE (entry), 0, -1);
3383 }
3384
3385 /*
3386  * Like gtk_editable_get_chars, but handle not-visible entries
3387  * correctly.
3388  */
3389 static char *    
3390 gtk_entry_get_public_chars (GtkEntry *entry,
3391                             gint      start,
3392                             gint      end)
3393 {
3394   if (end < 0)
3395     end = entry->text_length;
3396   
3397   if (entry->visible)
3398     return gtk_editable_get_chars (GTK_EDITABLE (entry), start, end);
3399   else if (!entry->invisible_char)
3400     return g_strdup ("");
3401   else
3402     {
3403       GString *str = g_string_new (NULL);
3404       append_char (str, entry->invisible_char, end - start);
3405       return g_string_free (str, FALSE);
3406     }
3407 }
3408
3409 static void
3410 paste_received (GtkClipboard *clipboard,
3411                 const gchar  *text,
3412                 gpointer      data)
3413 {
3414   GtkEntry *entry = GTK_ENTRY (data);
3415   GtkEditable *editable = GTK_EDITABLE (entry);
3416       
3417   if (text)
3418     {
3419       gint pos, start, end;
3420       
3421       if (gtk_editable_get_selection_bounds (editable, &start, &end))
3422         gtk_editable_delete_text (editable, start, end);
3423
3424       pos = entry->current_pos;
3425       gtk_editable_insert_text (editable, text, -1, &pos);
3426       gtk_editable_set_position (editable, pos);
3427     }
3428
3429   g_object_unref (entry);
3430 }
3431
3432 static void
3433 gtk_entry_paste (GtkEntry *entry,
3434                  GdkAtom   selection)
3435 {
3436   g_object_ref (entry);
3437   gtk_clipboard_request_text (gtk_widget_get_clipboard (GTK_WIDGET (entry), selection),
3438                               paste_received, entry);
3439 }
3440
3441 static void
3442 primary_get_cb (GtkClipboard     *clipboard,
3443                 GtkSelectionData *selection_data,
3444                 guint             info,
3445                 gpointer          data)
3446 {
3447   GtkEntry *entry = GTK_ENTRY (data);
3448   gint start, end;
3449   
3450   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3451     {
3452       gchar *str = gtk_entry_get_public_chars (entry, start, end);
3453       gtk_selection_data_set_text (selection_data, str, -1);
3454       g_free (str);
3455     }
3456 }
3457
3458 static void
3459 primary_clear_cb (GtkClipboard *clipboard,
3460                   gpointer      data)
3461 {
3462   GtkEntry *entry = GTK_ENTRY (data);
3463
3464   gtk_editable_select_region (GTK_EDITABLE (entry), entry->current_pos, entry->current_pos);
3465 }
3466
3467 static void
3468 gtk_entry_update_primary_selection (GtkEntry *entry)
3469 {
3470   static const GtkTargetEntry targets[] = {
3471     { "UTF8_STRING", 0, 0 },
3472     { "STRING", 0, 0 },
3473     { "TEXT",   0, 0 }, 
3474     { "COMPOUND_TEXT", 0, 0 }
3475   };
3476   
3477   GtkClipboard *clipboard;
3478   gint start, end;
3479
3480   if (!GTK_WIDGET_REALIZED (entry))
3481     return;
3482
3483   clipboard = gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_PRIMARY);
3484   
3485   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3486     {
3487       if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3488                                          primary_get_cb, primary_clear_cb, G_OBJECT (entry)))
3489         primary_clear_cb (clipboard, entry);
3490     }
3491   else
3492     {
3493       if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (entry))
3494         gtk_clipboard_clear (clipboard);
3495     }
3496 }
3497
3498 /* Public API
3499  */
3500
3501 GtkWidget*
3502 gtk_entry_new (void)
3503 {
3504   return g_object_new (GTK_TYPE_ENTRY, NULL);
3505 }
3506
3507 /**
3508  * gtk_entry_new_with_max_length:
3509  * @max: the maximum length of the entry, or 0 for no maximum.
3510  *   (other than the maximum length of entries.) The value passed in will
3511  *   be clamped to the range 0-65536.
3512  *
3513  * Creates a new #GtkEntry widget with the given maximum length.
3514  * 
3515  * Note: the existence of this function is inconsistent
3516  * with the rest of the GTK+ API. The normal setup would
3517  * be to just require the user to make an extra call
3518  * to gtk_entry_set_max_length() instead. It is not
3519  * expected that this function will be removed, but
3520  * it would be better practice not to use it.
3521  * 
3522  * Return value: a new #GtkEntry.
3523  **/
3524 GtkWidget*
3525 gtk_entry_new_with_max_length (gint max)
3526 {
3527   GtkEntry *entry;
3528
3529   max = CLAMP (max, 0, MAX_SIZE);
3530
3531   entry = g_object_new (GTK_TYPE_ENTRY, NULL);
3532   entry->text_max_length = max;
3533
3534   return GTK_WIDGET (entry);
3535 }
3536
3537 void
3538 gtk_entry_set_text (GtkEntry    *entry,
3539                     const gchar *text)
3540 {
3541   gint tmp_pos;
3542   GtkEntryCompletion *completion;
3543
3544   g_return_if_fail (GTK_IS_ENTRY (entry));
3545   g_return_if_fail (text != NULL);
3546
3547   /* Actually setting the text will affect the cursor and selection;
3548    * if the contents don't actually change, this will look odd to the user.
3549    */
3550   if (strcmp (entry->text, text) == 0)
3551     return;
3552
3553   completion = gtk_entry_get_completion (entry);
3554   if (completion)
3555     g_signal_handler_block (entry, completion->priv->changed_id);
3556
3557   gtk_editable_delete_text (GTK_EDITABLE (entry), 0, -1);
3558
3559   tmp_pos = 0;
3560   gtk_editable_insert_text (GTK_EDITABLE (entry), text, strlen (text), &tmp_pos);
3561
3562   if (completion)
3563     g_signal_handler_unblock (entry, completion->priv->changed_id);
3564 }
3565
3566 void
3567 gtk_entry_append_text (GtkEntry *entry,
3568                        const gchar *text)
3569 {
3570   gint tmp_pos;
3571
3572   g_return_if_fail (GTK_IS_ENTRY (entry));
3573   g_return_if_fail (text != NULL);
3574
3575   tmp_pos = entry->text_length;
3576   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3577 }
3578
3579 void
3580 gtk_entry_prepend_text (GtkEntry *entry,
3581                         const gchar *text)
3582 {
3583   gint tmp_pos;
3584
3585   g_return_if_fail (GTK_IS_ENTRY (entry));
3586   g_return_if_fail (text != NULL);
3587
3588   tmp_pos = 0;
3589   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3590 }
3591
3592 void
3593 gtk_entry_set_position (GtkEntry *entry,
3594                         gint       position)
3595 {
3596   g_return_if_fail (GTK_IS_ENTRY (entry));
3597
3598   gtk_editable_set_position (GTK_EDITABLE (entry), position);
3599 }
3600
3601 void
3602 gtk_entry_set_visibility (GtkEntry *entry,
3603                           gboolean visible)
3604 {
3605   g_return_if_fail (GTK_IS_ENTRY (entry));
3606
3607   entry->visible = visible ? TRUE : FALSE;
3608   g_object_notify (G_OBJECT (entry), "visibility");
3609   gtk_entry_recompute (entry);
3610 }
3611
3612 /**
3613  * gtk_entry_get_visibility:
3614  * @entry: a #GtkEntry
3615  *
3616  * Retrieves whether the text in @entry is visible. See
3617  * gtk_entry_set_visibility().
3618  *
3619  * Return value: %TRUE if the text is currently visible
3620  **/
3621 gboolean
3622 gtk_entry_get_visibility (GtkEntry *entry)
3623 {
3624   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3625
3626   return entry->visible;
3627 }
3628
3629 /**
3630  * gtk_entry_set_invisible_char:
3631  * @entry: a #GtkEntry
3632  * @ch: a Unicode character
3633  * 
3634  * Sets the character to use in place of the actual text when
3635  * gtk_entry_set_visibility() has been called to set text visibility
3636  * to %FALSE. i.e. this is the character used in "password mode" to
3637  * show the user how many characters have been typed. The default
3638  * invisible char is an asterisk ('*').  If you set the invisible char
3639  * to 0, then the user will get no feedback at all; there will be
3640  * no text on the screen as they type.
3641  * 
3642  **/
3643 void
3644 gtk_entry_set_invisible_char (GtkEntry *entry,
3645                               gunichar  ch)
3646 {
3647   g_return_if_fail (GTK_IS_ENTRY (entry));
3648
3649   if (ch == entry->invisible_char)
3650     return;
3651
3652   entry->invisible_char = ch;
3653   g_object_notify (G_OBJECT (entry), "invisible_char");
3654   gtk_entry_recompute (entry);  
3655 }
3656
3657 /**
3658  * gtk_entry_get_invisible_char:
3659  * @entry: a #GtkEntry
3660  *
3661  * Retrieves the character displayed in place of the real characters
3662  * for entries with visisbility set to false. See gtk_entry_set_invisible_char().
3663  *
3664  * Return value: the current invisible char, or 0, if the entry does not
3665  *               show invisible text at all. 
3666  **/
3667 gunichar
3668 gtk_entry_get_invisible_char (GtkEntry *entry)
3669 {
3670   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3671
3672   return entry->invisible_char;
3673 }
3674
3675 void
3676 gtk_entry_set_editable (GtkEntry *entry,
3677                         gboolean  editable)
3678 {
3679   g_return_if_fail (GTK_IS_ENTRY (entry));
3680
3681   gtk_editable_set_editable (GTK_EDITABLE (entry), editable);
3682 }
3683
3684 /**
3685  * gtk_entry_get_text:
3686  * @entry: a #GtkEntry
3687  *
3688  * Retrieves the contents of the entry widget.
3689  * See also gtk_editable_get_chars().
3690  *
3691  * Return value: a pointer to the contents of the widget as a
3692  *      string.  This string points to internally allocated
3693  *      storage in the widget and must not be freed, modified or
3694  *      stored.
3695  **/
3696 G_CONST_RETURN gchar*
3697 gtk_entry_get_text (GtkEntry *entry)
3698 {
3699   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
3700
3701   return entry->text;
3702 }
3703
3704 void       
3705 gtk_entry_select_region  (GtkEntry       *entry,
3706                           gint            start,
3707                           gint            end)
3708 {
3709   gtk_editable_select_region (GTK_EDITABLE (entry), start, end);
3710 }
3711
3712 /**
3713  * gtk_entry_set_max_length:
3714  * @entry: a #GtkEntry.
3715  * @max: the maximum length of the entry, or 0 for no maximum.
3716  *   (other than the maximum length of entries.) The value passed in will
3717  *   be clamped to the range 0-65536.
3718  * 
3719  * Sets the maximum allowed length of the contents of the widget. If
3720  * the current contents are longer than the given length, then they
3721  * will be truncated to fit.
3722  **/
3723 void
3724 gtk_entry_set_max_length (GtkEntry     *entry,
3725                           gint          max)
3726 {
3727   g_return_if_fail (GTK_IS_ENTRY (entry));
3728
3729   max = CLAMP (max, 0, MAX_SIZE);
3730
3731   if (max > 0 && entry->text_length > max)
3732     gtk_editable_delete_text (GTK_EDITABLE (entry), max, -1);
3733   
3734   entry->text_max_length = max;
3735   g_object_notify (G_OBJECT (entry), "max_length");
3736 }
3737
3738 /**
3739  * gtk_entry_get_max_length:
3740  * @entry: a #GtkEntry
3741  *
3742  * Retrieves the maximum allowed length of the text in
3743  * @entry. See gtk_entry_set_max_length().
3744  *
3745  * Return value: the maximum allowed number of characters
3746  *               in #GtkEntry, or 0 if there is no maximum.
3747  **/
3748 gint
3749 gtk_entry_get_max_length (GtkEntry *entry)
3750 {
3751   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3752
3753   return entry->text_max_length;
3754 }
3755
3756 /**
3757  * gtk_entry_set_activates_default:
3758  * @entry: a #GtkEntry
3759  * @setting: %TRUE to activate window's default widget on Enter keypress
3760  *
3761  * If @setting is %TRUE, pressing Enter in the @entry will activate the default
3762  * widget for the window containing the entry. This usually means that
3763  * the dialog box containing the entry will be closed, since the default
3764  * widget is usually one of the dialog buttons.
3765  *
3766  * (For experts: if @setting is %TRUE, the entry calls
3767  * gtk_window_activate_default() on the window containing the entry, in
3768  * the default handler for the "activate" signal.)
3769  * 
3770  **/
3771 void
3772 gtk_entry_set_activates_default (GtkEntry *entry,
3773                                  gboolean  setting)
3774 {
3775   g_return_if_fail (GTK_IS_ENTRY (entry));
3776   setting = setting != FALSE;
3777
3778   if (setting != entry->activates_default)
3779     {
3780       entry->activates_default = setting;
3781       g_object_notify (G_OBJECT (entry), "activates_default");
3782     }
3783 }
3784
3785 /**
3786  * gtk_entry_get_activates_default:
3787  * @entry: a #GtkEntry
3788  * 
3789  * Retrieves the value set by gtk_entry_set_activates_default().
3790  * 
3791  * Return value: %TRUE if the entry will activate the default widget
3792  **/
3793 gboolean
3794 gtk_entry_get_activates_default (GtkEntry *entry)
3795 {
3796   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3797
3798   return entry->activates_default;
3799 }
3800
3801 /**
3802  * gtk_entry_set_width_chars:
3803  * @entry: a #GtkEntry
3804  * @n_chars: width in chars
3805  *
3806  * Changes the size request of the entry to be about the right size
3807  * for @n_chars characters. Note that it changes the size
3808  * <emphasis>request</emphasis>, the size can still be affected by
3809  * how you pack the widget into containers. If @n_chars is -1, the
3810  * size reverts to the default entry size.
3811  * 
3812  **/
3813 void
3814 gtk_entry_set_width_chars (GtkEntry *entry,
3815                            gint      n_chars)
3816 {
3817   g_return_if_fail (GTK_IS_ENTRY (entry));
3818
3819   if (entry->width_chars != n_chars)
3820     {
3821       entry->width_chars = n_chars;
3822       g_object_notify (G_OBJECT (entry), "width_chars");
3823       gtk_widget_queue_resize (GTK_WIDGET (entry));
3824     }
3825 }
3826
3827 /**
3828  * gtk_entry_get_width_chars:
3829  * @entry: a #GtkEntry
3830  * 
3831  * Gets the value set by gtk_entry_set_width_chars().
3832  * 
3833  * Return value: number of chars to request space for, or negative if unset
3834  **/
3835 gint
3836 gtk_entry_get_width_chars (GtkEntry *entry)
3837 {
3838   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3839
3840   return entry->width_chars;
3841 }
3842
3843 /**
3844  * gtk_entry_set_has_frame:
3845  * @entry: a #GtkEntry
3846  * @setting: new value
3847  * 
3848  * Sets whether the entry has a beveled frame around it.
3849  **/
3850 void
3851 gtk_entry_set_has_frame (GtkEntry *entry,
3852                          gboolean  setting)
3853 {
3854   g_return_if_fail (GTK_IS_ENTRY (entry));
3855
3856   setting = (setting != FALSE);
3857
3858   if (entry->has_frame == setting)
3859     return;
3860
3861   gtk_widget_queue_resize (GTK_WIDGET (entry));
3862   entry->has_frame = setting;
3863   g_object_notify (G_OBJECT (entry), "has_frame");
3864 }
3865
3866 /**
3867  * gtk_entry_get_has_frame:
3868  * @entry: a #GtkEntry
3869  * 
3870  * Gets the value set by gtk_entry_set_has_frame().
3871  * 
3872  * Return value: whether the entry has a beveled frame
3873  **/
3874 gboolean
3875 gtk_entry_get_has_frame (GtkEntry *entry)
3876 {
3877   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3878
3879   return entry->has_frame;
3880 }
3881
3882
3883 /**
3884  * gtk_entry_get_layout:
3885  * @entry: a #GtkEntry
3886  * 
3887  * Gets the #PangoLayout used to display the entry.
3888  * The layout is useful to e.g. convert text positions to
3889  * pixel positions, in combination with gtk_entry_get_layout_offsets().
3890  * The returned layout is owned by the entry so need not be
3891  * freed by the caller.
3892  *
3893  * Keep in mind that the layout text may contain a preedit string, so
3894  * gtk_entry_layout_index_to_text_index() and
3895  * gtk_entry_text_index_to_layout_index() are needed to convert byte
3896  * indices in the layout to byte indices in the entry contents.
3897  * 
3898  * Return value: the #PangoLayout for this entry
3899  **/
3900 PangoLayout*
3901 gtk_entry_get_layout (GtkEntry *entry)
3902 {
3903   PangoLayout *layout;
3904   
3905   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
3906
3907   layout = gtk_entry_ensure_layout (entry, TRUE);
3908
3909   return layout;
3910 }
3911
3912
3913 /**
3914  * gtk_entry_layout_index_to_text_index:
3915  * @entry: a #GtkEntry
3916  * @layout_index: byte index into the entry layout text
3917  * 
3918  * Converts from a position in the entry contents (returned
3919  * by gtk_entry_get_text()) to a position in the
3920  * entry's #PangoLayout (returned by gtk_entry_get_layout(),
3921  * with text retrieved via pango_layout_get_text()).
3922  * 
3923  * Return value: byte index into the entry contents
3924  **/
3925 gint
3926 gtk_entry_layout_index_to_text_index (GtkEntry *entry,
3927                                       gint      layout_index)
3928 {
3929   PangoLayout *layout;
3930   const gchar *text;
3931   gint cursor_index;
3932   
3933   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3934
3935   layout = gtk_entry_ensure_layout (entry, TRUE);
3936   text = pango_layout_get_text (layout);
3937   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3938   
3939   if (layout_index >= cursor_index && entry->preedit_length)
3940     {
3941       if (layout_index >= cursor_index + entry->preedit_length)
3942         layout_index -= entry->preedit_length;
3943       else
3944         layout_index = cursor_index;
3945     }
3946
3947   return layout_index;
3948 }
3949
3950 /**
3951  * gtk_entry_text_index_to_layout_index:
3952  * @entry: a #GtkEntry
3953  * @text_index: byte index into the entry contents
3954  * 
3955  * Converts from a position in the entry's #PangoLayout(returned by
3956  * gtk_entry_get_layout()) to a position in the entry contents
3957  * (returned by gtk_entry_get_text()).
3958  * 
3959  * Return value: byte index into the entry layout text
3960  **/
3961 gint
3962 gtk_entry_text_index_to_layout_index (GtkEntry *entry,
3963                                       gint      text_index)
3964 {
3965   PangoLayout *layout;
3966   const gchar *text;
3967   gint cursor_index;
3968   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3969
3970   layout = gtk_entry_ensure_layout (entry, TRUE);
3971   text = pango_layout_get_text (layout);
3972   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3973   
3974   if (text_index > cursor_index)
3975     text_index += entry->preedit_length;
3976
3977   return text_index;
3978 }
3979
3980 /**
3981  * gtk_entry_get_layout_offsets:
3982  * @entry: a #GtkEntry
3983  * @x: location to store X offset of layout, or %NULL
3984  * @y: location to store Y offset of layout, or %NULL
3985  *
3986  *
3987  * Obtains the position of the #PangoLayout used to render text
3988  * in the entry, in widget coordinates. Useful if you want to line
3989  * up the text in an entry with some other text, e.g. when using the
3990  * entry to implement editable cells in a sheet widget.
3991  *
3992  * Also useful to convert mouse events into coordinates inside the
3993  * #PangoLayout, e.g. to take some action if some part of the entry text
3994  * is clicked.
3995  * 
3996  * Note that as the user scrolls around in the entry the offsets will
3997  * change; you'll need to connect to the "notify::scroll_offset"
3998  * signal to track this. Remember when using the #PangoLayout
3999  * functions you need to convert to and from pixels using
4000  * PANGO_PIXELS() or #PANGO_SCALE.
4001  *
4002  * Keep in mind that the layout text may contain a preedit string, so
4003  * gtk_entry_layout_index_to_text_index() and
4004  * gtk_entry_text_index_to_layout_index() are needed to convert byte
4005  * indices in the layout to byte indices in the entry contents.
4006  * 
4007  **/
4008 void
4009 gtk_entry_get_layout_offsets (GtkEntry *entry,
4010                               gint     *x,
4011                               gint     *y)
4012 {
4013   gint text_area_x, text_area_y;
4014   
4015   g_return_if_fail (GTK_IS_ENTRY (entry));
4016
4017   /* this gets coords relative to text area */
4018   get_layout_position (entry, x, y);
4019
4020   /* convert to widget coords */
4021   get_text_area_size (entry, &text_area_x, &text_area_y, NULL, NULL);
4022   
4023   if (x)
4024     *x += text_area_x;
4025
4026   if (y)
4027     *y += text_area_y;
4028 }
4029
4030
4031 /**
4032  * gtk_entry_set_alignment:
4033  * @entry: a #GtkEntry
4034  * @xalign: The horizontal alignment, from 0 (left) to 1 (right).
4035  *          Reversed for RTL layouts
4036  * 
4037  * Sets the alignment for the contents of the entry. This controls
4038  * the horizontal positioning of the contents when the displayed
4039  * text is shorter than the width of the entry.
4040  **/
4041 void
4042 gtk_entry_set_alignment (GtkEntry *entry, gfloat xalign)
4043 {
4044   GtkEntryPrivate *priv;
4045   
4046   g_return_if_fail (GTK_IS_ENTRY (entry));
4047
4048   priv = GTK_ENTRY_GET_PRIVATE (entry);
4049
4050   if (xalign < 0.0)
4051     xalign = 0.0;
4052   else if (xalign > 1.0)
4053     xalign = 1.0;
4054
4055   if (xalign != priv->xalign)
4056     {
4057       priv->xalign = xalign;
4058
4059       gtk_entry_recompute (entry);
4060
4061       g_object_notify (G_OBJECT (entry), "xalign");
4062     }
4063 }
4064
4065 /**
4066  * gtk_entry_get_alignment:
4067  * @entry: a #GtkEntry
4068  * 
4069  * Gets the value set by gtk_entry_set_alignment().
4070  * 
4071  * Return value: the alignment
4072  **/
4073 gfloat
4074 gtk_entry_get_alignment (GtkEntry *entry)
4075 {
4076   GtkEntryPrivate *priv;
4077   
4078   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0.0);
4079
4080   priv = GTK_ENTRY_GET_PRIVATE (entry);
4081
4082   return priv->xalign;
4083 }
4084
4085 /* Quick hack of a popup menu
4086  */
4087 static void
4088 activate_cb (GtkWidget *menuitem,
4089              GtkEntry  *entry)
4090 {
4091   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
4092   g_signal_emit_by_name (entry, signal);
4093 }
4094
4095
4096 static gboolean
4097 gtk_entry_mnemonic_activate (GtkWidget *widget,
4098                              gboolean   group_cycling)
4099 {
4100   gtk_widget_grab_focus (widget);
4101   return TRUE;
4102 }
4103
4104 static void
4105 append_action_signal (GtkEntry     *entry,
4106                       GtkWidget    *menu,
4107                       const gchar  *stock_id,
4108                       const gchar  *signal,
4109                       gboolean      sensitive)
4110 {
4111   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
4112
4113   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
4114   g_signal_connect (menuitem, "activate",
4115                     G_CALLBACK (activate_cb), entry);
4116
4117   gtk_widget_set_sensitive (menuitem, sensitive);
4118   
4119   gtk_widget_show (menuitem);
4120   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
4121 }
4122         
4123 static void
4124 popup_menu_detach (GtkWidget *attach_widget,
4125                    GtkMenu   *menu)
4126 {
4127   GTK_ENTRY (attach_widget)->popup_menu = NULL;
4128 }
4129
4130 static void
4131 popup_position_func (GtkMenu   *menu,
4132                      gint      *x,
4133                      gint      *y,
4134                      gboolean  *push_in,
4135                      gpointer   user_data)
4136 {
4137   GtkEntry *entry = GTK_ENTRY (user_data);
4138   GtkWidget *widget = GTK_WIDGET (entry);
4139   GdkScreen *screen = gtk_widget_get_screen (widget);
4140   GtkRequisition req;
4141   
4142   g_return_if_fail (GTK_WIDGET_REALIZED (entry));
4143
4144   gdk_window_get_origin (widget->window, x, y);      
4145
4146   gtk_widget_size_request (entry->popup_menu, &req);
4147   
4148   *x += widget->allocation.width / 2;
4149   *y += widget->allocation.height;
4150
4151   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
4152   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
4153 }
4154
4155
4156 static void
4157 unichar_chosen_func (const char *text,
4158                      gpointer    data)
4159 {
4160   GtkEntry *entry = GTK_ENTRY (data);
4161
4162   if (entry->editable)
4163     gtk_entry_enter_text (entry, text);
4164 }
4165
4166 typedef struct
4167 {
4168   GtkEntry *entry;
4169   gint button;
4170   guint time;
4171 } PopupInfo;
4172
4173 static void
4174 popup_targets_received (GtkClipboard     *clipboard,
4175                         GtkSelectionData *data,
4176                         gpointer          user_data)
4177 {
4178   PopupInfo *info = user_data;
4179   GtkEntry *entry = info->entry;
4180   
4181   if (GTK_WIDGET_REALIZED (entry))
4182     {
4183       gboolean clipboard_contains_text = gtk_selection_data_targets_include_text (data);
4184       GtkWidget *menuitem;
4185       GtkWidget *submenu;
4186       
4187       if (entry->popup_menu)
4188         gtk_widget_destroy (entry->popup_menu);
4189       
4190       entry->popup_menu = gtk_menu_new ();
4191       
4192       gtk_menu_attach_to_widget (GTK_MENU (entry->popup_menu),
4193                                  GTK_WIDGET (entry),
4194                                  popup_menu_detach);
4195       
4196       append_action_signal (entry, entry->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
4197                             entry->editable && entry->current_pos != entry->selection_bound);
4198       append_action_signal (entry, entry->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
4199                             entry->current_pos != entry->selection_bound);
4200       append_action_signal (entry, entry->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
4201                             entry->editable && clipboard_contains_text);
4202       
4203       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
4204       gtk_widget_set_sensitive (menuitem, entry->current_pos != entry->selection_bound);
4205       g_signal_connect_swapped (menuitem, "activate",
4206                                 G_CALLBACK (gtk_entry_delete_cb), entry);
4207       gtk_widget_show (menuitem);
4208       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4209
4210       menuitem = gtk_separator_menu_item_new ();
4211       gtk_widget_show (menuitem);
4212       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4213       
4214       menuitem = gtk_menu_item_new_with_mnemonic (_("Select _All"));
4215       g_signal_connect_swapped (menuitem, "activate",
4216                                 G_CALLBACK (gtk_entry_select_all), entry);
4217       gtk_widget_show (menuitem);
4218       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4219       
4220       menuitem = gtk_separator_menu_item_new ();
4221       gtk_widget_show (menuitem);
4222       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4223       
4224       menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
4225       gtk_widget_show (menuitem);
4226       submenu = gtk_menu_new ();
4227       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4228       
4229       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4230       
4231       gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (entry->im_context),
4232                                             GTK_MENU_SHELL (submenu));
4233       
4234       menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
4235       gtk_widget_show (menuitem);
4236       
4237       submenu = gtk_menu_new ();
4238       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4239       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);      
4240
4241       _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
4242                                                     unichar_chosen_func,
4243                                                     entry);
4244       if (!entry->editable)
4245         gtk_widget_set_sensitive (menuitem, FALSE);
4246       
4247       g_signal_emit (entry,
4248                      signals[POPULATE_POPUP],
4249                      0,
4250                      entry->popup_menu);
4251   
4252
4253       if (info->button)
4254         gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4255                         NULL, NULL,
4256                         info->button, info->time);
4257       else
4258         {
4259           gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4260                           popup_position_func, entry,
4261                           info->button, info->time);
4262           gtk_menu_shell_select_first (GTK_MENU_SHELL (entry->popup_menu), FALSE);
4263         }
4264     }
4265
4266   g_object_unref (entry);
4267   g_free (info);
4268 }
4269                         
4270 static void
4271 gtk_entry_do_popup (GtkEntry       *entry,
4272                     GdkEventButton *event)
4273 {
4274   PopupInfo *info = g_new (PopupInfo, 1);
4275
4276   /* In order to know what entries we should make sensitive, we
4277    * ask for the current targets of the clipboard, and when
4278    * we get them, then we actually pop up the menu.
4279    */
4280   info->entry = g_object_ref (entry);
4281   
4282   if (event)
4283     {
4284       info->button = event->button;
4285       info->time = event->time;
4286     }
4287   else
4288     {
4289       info->button = 0;
4290       info->time = gtk_get_current_event_time ();
4291     }
4292
4293   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_CLIPBOARD),
4294                                   gdk_atom_intern ("TARGETS", FALSE),
4295                                   popup_targets_received,
4296                                   info);
4297 }
4298
4299 static gboolean
4300 gtk_entry_popup_menu (GtkWidget *widget)
4301 {
4302   gtk_entry_do_popup (GTK_ENTRY (widget), NULL);
4303   return TRUE;
4304 }
4305
4306 static void
4307 gtk_entry_drag_leave (GtkWidget        *widget,
4308                       GdkDragContext   *context,
4309                       guint             time)
4310 {
4311   GtkEntry *entry = GTK_ENTRY (widget);
4312
4313   entry->dnd_position = -1;
4314   gtk_widget_queue_draw (widget);
4315 }
4316
4317 static gboolean
4318 gtk_entry_drag_drop  (GtkWidget        *widget,
4319                       GdkDragContext   *context,
4320                       gint              x,
4321                       gint              y,
4322                       guint             time)
4323 {
4324   GtkEntry *entry = GTK_ENTRY (widget);
4325   GdkAtom target = GDK_NONE;
4326   
4327   if (entry->editable)
4328     target = gtk_drag_dest_find_target (widget, context, NULL);
4329
4330   if (target != GDK_NONE)
4331     gtk_drag_get_data (widget, context, target, time);
4332   else
4333     gtk_drag_finish (context, FALSE, FALSE, time);
4334   
4335   return TRUE;
4336 }
4337
4338 static gboolean
4339 gtk_entry_drag_motion (GtkWidget        *widget,
4340                        GdkDragContext   *context,
4341                        gint              x,
4342                        gint              y,
4343                        guint             time)
4344 {
4345   GtkEntry *entry = GTK_ENTRY (widget);
4346   GtkWidget *source_widget;
4347   GdkDragAction suggested_action;
4348   gint new_position, old_position;
4349   gint sel1, sel2;
4350   
4351   x -= widget->style->xthickness;
4352   y -= widget->style->ythickness;
4353   
4354   old_position = entry->dnd_position;
4355   new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4356
4357   if (entry->editable &&
4358       gtk_drag_dest_find_target (widget, context, NULL) != GDK_NONE)
4359     {
4360       source_widget = gtk_drag_get_source_widget (context);
4361       suggested_action = context->suggested_action;
4362
4363       if (!gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &sel1, &sel2) ||
4364           new_position < sel1 || new_position > sel2)
4365         {
4366           if (source_widget == widget)
4367             {
4368               /* Default to MOVE, unless the user has
4369                * pressed ctrl or alt to affect available actions
4370                */
4371               if ((context->actions & GDK_ACTION_MOVE) != 0)
4372                 suggested_action = GDK_ACTION_MOVE;
4373             }
4374               
4375           entry->dnd_position = new_position;
4376         }
4377       else
4378         {
4379           if (source_widget == widget)
4380             suggested_action = 0;       /* Can't drop in selection where drag started */
4381           
4382           entry->dnd_position = -1;
4383         }
4384     }
4385   else
4386     {
4387       /* Entry not editable, or no text */
4388       suggested_action = 0;
4389       entry->dnd_position = -1;
4390     }
4391   
4392   gdk_drag_status (context, suggested_action, time);
4393   
4394   if (entry->dnd_position != old_position)
4395     gtk_widget_queue_draw (widget);
4396
4397   return TRUE;
4398 }
4399
4400 static void
4401 gtk_entry_drag_data_received (GtkWidget        *widget,
4402                               GdkDragContext   *context,
4403                               gint              x,
4404                               gint              y,
4405                               GtkSelectionData *selection_data,
4406                               guint             info,
4407                               guint             time)
4408 {
4409   GtkEntry *entry = GTK_ENTRY (widget);
4410   GtkEditable *editable = GTK_EDITABLE (widget);
4411   gchar *str;
4412
4413   str = gtk_selection_data_get_text (selection_data);
4414
4415   if (str && entry->editable)
4416     {
4417       gint new_position;
4418       gint sel1, sel2;
4419
4420       new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4421
4422       if (!gtk_editable_get_selection_bounds (editable, &sel1, &sel2) ||
4423           new_position < sel1 || new_position > sel2)
4424         {
4425           gtk_editable_insert_text (editable, str, -1, &new_position);
4426         }
4427       else
4428         {
4429           /* Replacing selection */
4430           gtk_editable_delete_text (editable, sel1, sel2);
4431           gtk_editable_insert_text (editable, str, -1, &sel1);
4432         }
4433       
4434       g_free (str);
4435       gtk_drag_finish (context, TRUE, context->action == GDK_ACTION_MOVE, time);
4436     }
4437   else
4438     {
4439       /* Drag and drop didn't happen! */
4440       gtk_drag_finish (context, FALSE, FALSE, time);
4441     }
4442 }
4443
4444 static void
4445 gtk_entry_drag_data_get (GtkWidget        *widget,
4446                          GdkDragContext   *context,
4447                          GtkSelectionData *selection_data,
4448                          guint             info,
4449                          guint             time)
4450 {
4451   gint sel_start, sel_end;
4452
4453   GtkEditable *editable = GTK_EDITABLE (widget);
4454   
4455   if (gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4456     {
4457       gchar *str = gtk_entry_get_public_chars (GTK_ENTRY (widget), sel_start, sel_end);
4458
4459       gtk_selection_data_set_text (selection_data, str, -1);
4460       
4461       g_free (str);
4462     }
4463
4464 }
4465
4466 static void
4467 gtk_entry_drag_data_delete (GtkWidget      *widget,
4468                             GdkDragContext *context)
4469 {
4470   gint sel_start, sel_end;
4471
4472   GtkEditable *editable = GTK_EDITABLE (widget);
4473   
4474   if (GTK_ENTRY (widget)->editable &&
4475       gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4476     gtk_editable_delete_text (editable, sel_start, sel_end);
4477 }
4478
4479 /* We display the cursor when
4480  *
4481  *  - the selection is empty, AND
4482  *  - the widget has focus
4483  */
4484
4485 #define CURSOR_ON_MULTIPLIER 0.66
4486 #define CURSOR_OFF_MULTIPLIER 0.34
4487 #define CURSOR_PEND_MULTIPLIER 1.0
4488
4489 static gboolean
4490 cursor_blinks (GtkEntry *entry)
4491 {
4492   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4493   gboolean blink;
4494
4495   if (GTK_WIDGET_HAS_FOCUS (entry) &&
4496       entry->selection_bound == entry->current_pos)
4497     {
4498       g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
4499       return blink;
4500     }
4501   else
4502     return FALSE;
4503 }
4504
4505 static gint
4506 get_cursor_time (GtkEntry *entry)
4507 {
4508   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4509   gint time;
4510
4511   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
4512
4513   return time;
4514 }
4515
4516 static void
4517 show_cursor (GtkEntry *entry)
4518 {
4519   if (!entry->cursor_visible)
4520     {
4521       entry->cursor_visible = TRUE;
4522
4523       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4524         gtk_widget_queue_draw (GTK_WIDGET (entry));
4525     }
4526 }
4527
4528 static void
4529 hide_cursor (GtkEntry *entry)
4530 {
4531   if (entry->cursor_visible)
4532     {
4533       entry->cursor_visible = FALSE;
4534
4535       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4536         gtk_widget_queue_draw (GTK_WIDGET (entry));
4537     }
4538 }
4539
4540 /*
4541  * Blink!
4542  */
4543 static gint
4544 blink_cb (gpointer data)
4545 {
4546   GtkEntry *entry;
4547
4548   GDK_THREADS_ENTER ();
4549
4550   entry = GTK_ENTRY (data);
4551
4552   if (!GTK_WIDGET_HAS_FOCUS (entry))
4553     {
4554       g_warning ("GtkEntry - did not receive focus-out-event. If you\n"
4555                  "connect a handler to this signal, it must return\n"
4556                  "FALSE so the entry gets the event as well");
4557     }
4558   
4559   g_assert (GTK_WIDGET_HAS_FOCUS (entry));
4560   g_assert (entry->selection_bound == entry->current_pos);
4561
4562   if (entry->cursor_visible)
4563     {
4564       hide_cursor (entry);
4565       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_OFF_MULTIPLIER,
4566                                             blink_cb,
4567                                             entry);
4568     }
4569   else
4570     {
4571       show_cursor (entry);
4572       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4573                                             blink_cb,
4574                                             entry);
4575     }
4576
4577   GDK_THREADS_LEAVE ();
4578
4579   /* Remove ourselves */
4580   return FALSE;
4581 }
4582
4583 static void
4584 gtk_entry_check_cursor_blink (GtkEntry *entry)
4585 {
4586   if (cursor_blinks (entry))
4587     {
4588       if (!entry->blink_timeout)
4589         {
4590           entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4591                                                 blink_cb,
4592                                                 entry);
4593           show_cursor (entry);
4594         }
4595     }
4596   else
4597     {
4598       if (entry->blink_timeout)  
4599         { 
4600           g_source_remove (entry->blink_timeout);
4601           entry->blink_timeout = 0;
4602         }
4603       
4604       entry->cursor_visible = TRUE;
4605     }
4606   
4607 }
4608
4609 static void
4610 gtk_entry_pend_cursor_blink (GtkEntry *entry)
4611 {
4612   if (cursor_blinks (entry))
4613     {
4614       if (entry->blink_timeout != 0)
4615         g_source_remove (entry->blink_timeout);
4616       
4617       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_PEND_MULTIPLIER,
4618                                             blink_cb,
4619                                             entry);
4620       show_cursor (entry);
4621     }
4622 }
4623
4624 /* completion */
4625 static gint
4626 gtk_entry_completion_timeout (gpointer data)
4627 {
4628   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (data);
4629
4630   GDK_THREADS_ENTER ();
4631
4632   completion->priv->completion_timeout = 0;
4633
4634   if (strlen (gtk_entry_get_text (GTK_ENTRY (completion->priv->entry)))
4635       >= completion->priv->minimum_key_length)
4636     {
4637       gint matches;
4638       gint actions;
4639       GtkTreeSelection *s;
4640
4641       gtk_entry_completion_complete (completion);
4642       matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4643
4644       gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4645
4646       s = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view));
4647
4648       gtk_tree_selection_unselect_all (s);
4649
4650       actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
4651
4652       if ((matches > 0 || actions > 0)
4653           && ! GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4654         _gtk_entry_completion_popup (completion);
4655       else if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4656         _gtk_entry_completion_resize_popup (completion);
4657     }
4658   else if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4659     _gtk_entry_completion_popdown (completion);
4660
4661   GDK_THREADS_LEAVE ();
4662
4663   return FALSE;
4664 }
4665
4666 static inline gboolean
4667 keyval_is_cursor_move (guint keyval)
4668 {
4669   if (keyval == GDK_Up || keyval == GDK_KP_Up)
4670     return TRUE;
4671
4672   if (keyval == GDK_Down || keyval == GDK_KP_Down)
4673     return TRUE;
4674
4675   if (keyval == GDK_Page_Up)
4676     return TRUE;
4677
4678   if (keyval == GDK_Page_Down)
4679     return TRUE;
4680
4681   return FALSE;
4682 }
4683
4684 static gboolean
4685 gtk_entry_completion_key_press (GtkWidget   *widget,
4686                                 GdkEventKey *event,
4687                                 gpointer     user_data)
4688 {
4689   gint matches, actions = 0;
4690   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
4691
4692   if (!GTK_WIDGET_MAPPED (completion->priv->popup_window))
4693     return FALSE;
4694
4695   matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4696
4697   if (completion->priv->actions)
4698     actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
4699
4700   if (keyval_is_cursor_move (event->keyval))
4701     {
4702       GtkTreePath *path = NULL;
4703       
4704       if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
4705         {
4706           completion->priv->current_selected--;
4707           if (completion->priv->current_selected < -1)
4708             completion->priv->current_selected = -1;
4709         }
4710       else if (event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
4711         {
4712           completion->priv->current_selected++;
4713           if (completion->priv->current_selected > matches + actions - 1)
4714             completion->priv->current_selected = matches + actions - 1;
4715         }
4716       else if (event->keyval == GDK_Page_Up)
4717         {
4718           if (completion->priv->current_selected <= 0)
4719             completion->priv->current_selected = -1;
4720           else if (completion->priv->current_selected < matches) 
4721             {
4722               completion->priv->current_selected -= 14;
4723               if (completion->priv->current_selected < 0)
4724                 completion->priv->current_selected = 0;
4725             }
4726           else 
4727             {
4728               completion->priv->current_selected -= 14;
4729               if (completion->priv->current_selected < matches - 1)
4730                 completion->priv->current_selected = matches - 1;
4731             }
4732         }
4733       else if (event->keyval == GDK_Page_Down)
4734         {
4735           if (completion->priv->current_selected < 0)
4736             completion->priv->current_selected = 0;
4737           else if (completion->priv->current_selected < matches - 1)
4738             {
4739               completion->priv->current_selected += 14;
4740               if (completion->priv->current_selected > matches - 1)
4741                 completion->priv->current_selected = matches - 1;
4742             }
4743           else 
4744             {
4745               completion->priv->current_selected += 14;
4746               if (completion->priv->current_selected > matches + actions - 1)
4747                 completion->priv->current_selected = matches + actions - 1;
4748             }
4749         }
4750
4751       if (completion->priv->current_selected < 0)
4752         {
4753           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4754           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
4755         }
4756       else if (completion->priv->current_selected < matches)
4757         {
4758           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
4759
4760           path = gtk_tree_path_new_from_indices (completion->priv->current_selected, -1);
4761           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->tree_view),
4762                                     path, NULL, FALSE);
4763         }
4764       else if (completion->priv->current_selected - matches >= 0)
4765         {
4766           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4767
4768           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
4769           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->action_view),
4770                                     path, NULL, FALSE);
4771         }
4772
4773       gtk_tree_path_free (path);
4774
4775       return TRUE;
4776     }
4777   else if (event->keyval == GDK_Escape) 
4778     {
4779       _gtk_entry_completion_popdown (completion);
4780
4781       return TRUE;
4782     }
4783   else if (event->keyval == GDK_Tab || 
4784            event->keyval == GDK_KP_Tab ||
4785            event->keyval == GDK_ISO_Left_Tab) 
4786     {
4787       GtkWidget *entry;
4788       GtkDirectionType dir = event->keyval == GDK_ISO_Left_Tab ? 
4789         GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD;
4790
4791       _gtk_entry_completion_popdown (completion);
4792       
4793       entry = gtk_entry_completion_get_entry (completion);
4794
4795       gtk_widget_child_focus (gtk_widget_get_toplevel (entry), dir);
4796
4797       return TRUE;
4798     }
4799   else if (event->keyval == GDK_ISO_Enter || 
4800            event->keyval == GDK_Return)
4801     {
4802       _gtk_entry_completion_popdown (completion);
4803
4804       if (completion->priv->current_selected < matches)
4805         {
4806           GtkTreeIter iter;
4807           GtkTreeModel *model = NULL;
4808           GtkTreeSelection *sel;
4809           gboolean entry_set;
4810
4811           sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view));
4812           if (!gtk_tree_selection_get_selected (sel, &model, &iter))
4813             return FALSE;
4814
4815           g_signal_handler_block (completion->priv->entry,
4816                                   completion->priv->changed_id);
4817           g_signal_emit_by_name (completion, "match_selected",
4818                                  model, &iter, &entry_set);
4819           g_signal_handler_unblock (completion->priv->entry,
4820                                     completion->priv->changed_id);
4821
4822           if (!entry_set)
4823             {
4824               gchar *str = NULL;
4825
4826               gtk_tree_model_get (model, &iter,
4827                                   completion->priv->text_column, &str,
4828                                   -1);
4829
4830               g_signal_handler_block (widget, completion->priv->changed_id);
4831               gtk_entry_set_text (GTK_ENTRY (widget), str);
4832               g_signal_handler_unblock (widget, completion->priv->changed_id);
4833
4834               /* move the cursor to the end */
4835               gtk_editable_set_position (GTK_EDITABLE (widget), -1);
4836
4837              g_free (str);
4838             }
4839
4840           return TRUE;
4841         }
4842       else if (completion->priv->current_selected - matches >= 0)
4843         {
4844           GtkTreePath *path;
4845
4846           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
4847
4848           g_signal_emit_by_name (completion, "action_activated",
4849                                  gtk_tree_path_get_indices (path)[0]);
4850           gtk_tree_path_free (path);
4851
4852           return TRUE;
4853         }
4854     }
4855
4856   return FALSE;
4857 }
4858
4859 static void
4860 gtk_entry_completion_changed (GtkWidget *entry,
4861                               gpointer   user_data)
4862 {
4863   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
4864
4865   /* (re)install completion timeout */
4866   if (completion->priv->completion_timeout)
4867     g_source_remove (completion->priv->completion_timeout);
4868
4869   if (!gtk_entry_get_text (GTK_ENTRY (entry)))
4870     return;
4871
4872   /* no need to normalize for this test */
4873   if (! strcmp ("", gtk_entry_get_text (GTK_ENTRY (entry))))
4874     {
4875       if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4876         _gtk_entry_completion_popdown (completion);
4877       return;
4878     }
4879
4880   completion->priv->completion_timeout =
4881     g_timeout_add (COMPLETION_TIMEOUT,
4882                    gtk_entry_completion_timeout,
4883                    completion);
4884 }
4885
4886 /**
4887  * gtk_entry_set_completion:
4888  * @entry: A #GtkEntry.
4889  * @completion: The #GtkEntryCompletion.
4890  *
4891  * Sets @completion to be the auxiliary completion object to use with @entry.
4892  * All further configuration of the completion mechanism is done on
4893  * @completion using the #GtkEntryCompletion API.
4894  *
4895  * Since: 2.4
4896  */
4897 void
4898 gtk_entry_set_completion (GtkEntry           *entry,
4899                           GtkEntryCompletion *completion)
4900 {
4901   GtkEntryCompletion *old;
4902
4903   g_return_if_fail (GTK_IS_ENTRY (entry));
4904   g_return_if_fail (!completion || GTK_IS_ENTRY_COMPLETION (completion));
4905
4906   old = gtk_entry_get_completion (entry);
4907
4908   if (old == completion)
4909     return;
4910   
4911   if (old)
4912     {
4913       if (old->priv->completion_timeout)
4914         {
4915           g_source_remove (old->priv->completion_timeout);
4916           old->priv->completion_timeout = 0;
4917         }
4918
4919       if (GTK_WIDGET_MAPPED (old->priv->popup_window))
4920         _gtk_entry_completion_popdown (old);
4921
4922       gtk_cell_layout_clear (GTK_CELL_LAYOUT (old));
4923       old->priv->text_column = -1;
4924
4925       if (g_signal_handler_is_connected (entry, old->priv->changed_id))
4926         g_signal_handler_disconnect (entry, old->priv->changed_id);
4927       if (g_signal_handler_is_connected (entry, old->priv->key_press_id))
4928         g_signal_handler_disconnect (entry, old->priv->key_press_id);
4929
4930       old->priv->entry = NULL;
4931
4932       g_object_unref (old);
4933     }
4934
4935   if (!completion)
4936     {
4937       g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, NULL);
4938       return;
4939     }
4940
4941   /* hook into the entry */
4942   g_object_ref (completion);
4943
4944   completion->priv->changed_id =
4945     g_signal_connect (entry, "changed",
4946                       G_CALLBACK (gtk_entry_completion_changed), completion);
4947
4948   completion->priv->key_press_id =
4949     g_signal_connect (entry, "key_press_event",
4950                       G_CALLBACK (gtk_entry_completion_key_press), completion);
4951
4952   completion->priv->entry = GTK_WIDGET (entry);
4953   g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, completion);
4954 }
4955
4956 /**
4957  * gtk_entry_get_completion:
4958  * @entry: A #GtkEntry.
4959  *
4960  * Returns the auxiliary completion object currently in use by @entry.
4961  *
4962  * Return value: The auxiliary completion object currently in use by @entry.
4963  *
4964  * Since: 2.4
4965  */
4966 GtkEntryCompletion *
4967 gtk_entry_get_completion (GtkEntry *entry)
4968 {
4969   GtkEntryCompletion *completion;
4970
4971   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
4972
4973   completion = GTK_ENTRY_COMPLETION (g_object_get_data (G_OBJECT (entry),
4974                                      GTK_ENTRY_COMPLETION_KEY));
4975
4976   return completion;
4977 }