]> Pileus Git - ~andy/gtk/blob - gtk/gtkentry.c
Typo fix.
[~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   gtk_widget_ensure_style (widget);
1131   context = gtk_widget_get_pango_context (widget);
1132   metrics = pango_context_get_metrics (context,
1133                                        widget->style->font_desc,
1134                                        pango_context_get_language (context));
1135
1136   entry->ascent = pango_font_metrics_get_ascent (metrics);
1137   entry->descent = pango_font_metrics_get_descent (metrics);
1138   
1139   get_borders (entry, &xborder, &yborder);
1140   
1141   xborder += INNER_BORDER;
1142   yborder += INNER_BORDER;
1143   
1144   if (entry->width_chars < 0)
1145     requisition->width = MIN_ENTRY_WIDTH + xborder * 2;
1146   else
1147     {
1148       gint char_width = pango_font_metrics_get_approximate_char_width (metrics);
1149       gint digit_width = pango_font_metrics_get_approximate_digit_width (metrics);
1150       gint char_pixels = (MAX (char_width, digit_width) + PANGO_SCALE - 1) / PANGO_SCALE;
1151       
1152       requisition->width = char_pixels * entry->width_chars + xborder * 2;
1153     }
1154     
1155   requisition->height = PANGO_PIXELS (entry->ascent + entry->descent) + yborder * 2;
1156
1157   pango_font_metrics_unref (metrics);
1158 }
1159
1160 static void
1161 get_text_area_size (GtkEntry *entry,
1162                     gint     *x,
1163                     gint     *y,
1164                     gint     *width,
1165                     gint     *height)
1166 {
1167   gint xborder, yborder;
1168   GtkRequisition requisition;
1169   GtkWidget *widget = GTK_WIDGET (entry);
1170
1171   gtk_widget_get_child_requisition (widget, &requisition);
1172
1173   get_borders (entry, &xborder, &yborder);
1174
1175   if (x)
1176     *x = xborder;
1177
1178   if (y)
1179     *y = yborder;
1180   
1181   if (width)
1182     *width = GTK_WIDGET (entry)->allocation.width - xborder * 2;
1183
1184   if (height)
1185     *height = requisition.height - yborder * 2;
1186 }
1187
1188 static void
1189 get_widget_window_size (GtkEntry *entry,
1190                         gint     *x,
1191                         gint     *y,
1192                         gint     *width,
1193                         gint     *height)
1194 {
1195   GtkRequisition requisition;
1196   GtkWidget *widget = GTK_WIDGET (entry);
1197       
1198   gtk_widget_get_child_requisition (widget, &requisition);
1199
1200   if (x)
1201     *x = widget->allocation.x;
1202
1203   if (y)
1204     {
1205       if (entry->is_cell_renderer)
1206         *y = widget->allocation.y;
1207       else
1208         *y = widget->allocation.y + (widget->allocation.height - requisition.height) / 2;
1209     }
1210
1211   if (width)
1212     *width = widget->allocation.width;
1213
1214   if (height)
1215     {
1216       if (entry->is_cell_renderer)
1217         *height = widget->allocation.height;
1218       else
1219         *height = requisition.height;
1220     }
1221 }
1222
1223 static void
1224 gtk_entry_size_allocate (GtkWidget     *widget,
1225                          GtkAllocation *allocation)
1226 {
1227   GtkEntry *entry = GTK_ENTRY (widget);
1228   
1229   widget->allocation = *allocation;
1230   
1231   if (GTK_WIDGET_REALIZED (widget))
1232     {
1233       /* We call gtk_widget_get_child_requisition, since we want (for
1234        * backwards compatibility reasons) the realization here to
1235        * be affected by the usize of the entry, if set
1236        */
1237       gint x, y, width, height;
1238
1239       get_widget_window_size (entry, &x, &y, &width, &height);
1240       
1241       gdk_window_move_resize (widget->window,
1242                               x, y, width, height);   
1243
1244       get_text_area_size (entry, &x, &y, &width, &height);
1245       
1246       gdk_window_move_resize (entry->text_area,
1247                               x, y, width, height);
1248
1249       gtk_entry_recompute (entry);
1250     }
1251 }
1252
1253 static void
1254 gtk_entry_draw_frame (GtkWidget *widget)
1255 {
1256   gint x = 0, y = 0;
1257   gint width, height;
1258   gboolean interior_focus;
1259   gint focus_width;
1260   
1261   gtk_widget_style_get (widget,
1262                         "interior-focus", &interior_focus,
1263                         "focus-line-width", &focus_width,
1264                         NULL);
1265   
1266   gdk_drawable_get_size (widget->window, &width, &height);
1267   
1268   if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
1269     {
1270       x += focus_width;
1271       y += focus_width;
1272       width -= 2 * focus_width;
1273       height -= 2 * focus_width;
1274     }
1275
1276   gtk_paint_shadow (widget->style, widget->window,
1277                     GTK_STATE_NORMAL, GTK_SHADOW_IN,
1278                     NULL, widget, "entry",
1279                     x, y, width, height);
1280
1281   if (GTK_WIDGET_HAS_FOCUS (widget) && !interior_focus)
1282     {
1283       x -= focus_width;
1284       y -= focus_width;
1285       width += 2 * focus_width;
1286       height += 2 * focus_width;
1287       
1288       gtk_paint_focus (widget->style, widget->window, GTK_WIDGET_STATE (widget), 
1289                        NULL, widget, "entry",
1290                        0, 0, width, height);
1291     }
1292 }
1293
1294 static gint
1295 gtk_entry_expose (GtkWidget      *widget,
1296                   GdkEventExpose *event)
1297 {
1298   GtkEntry *entry = GTK_ENTRY (widget);
1299
1300   if (widget->window == event->window)
1301     gtk_entry_draw_frame (widget);
1302   else if (entry->text_area == event->window)
1303     {
1304       gint area_width, area_height;
1305
1306       get_text_area_size (entry, NULL, NULL, &area_width, &area_height);
1307
1308       gtk_paint_flat_box (widget->style, entry->text_area, 
1309                           GTK_WIDGET_STATE(widget), GTK_SHADOW_NONE,
1310                           NULL, widget, "entry_bg", 
1311                           0, 0, area_width, area_height);
1312       
1313       if ((entry->visible || entry->invisible_char != 0) &&
1314           GTK_WIDGET_HAS_FOCUS (widget) &&
1315           entry->selection_bound == entry->current_pos && entry->cursor_visible)
1316         gtk_entry_draw_cursor (GTK_ENTRY (widget), CURSOR_STANDARD);
1317
1318       if (entry->dnd_position != -1)
1319         gtk_entry_draw_cursor (GTK_ENTRY (widget), CURSOR_DND);
1320       
1321       gtk_entry_draw_text (GTK_ENTRY (widget));
1322     }
1323
1324   return FALSE;
1325 }
1326
1327 static gint
1328 gtk_entry_button_press (GtkWidget      *widget,
1329                         GdkEventButton *event)
1330 {
1331   GtkEntry *entry = GTK_ENTRY (widget);
1332   GtkEditable *editable = GTK_EDITABLE (widget);
1333   gint tmp_pos;
1334   gint sel_start, sel_end;
1335
1336   if (event->window != entry->text_area ||
1337       (entry->button && event->button != entry->button))
1338     return FALSE;
1339
1340   entry->button = event->button;
1341   
1342   if (!GTK_WIDGET_HAS_FOCUS (widget))
1343     {
1344       entry->in_click = TRUE;
1345       gtk_widget_grab_focus (widget);
1346       entry->in_click = FALSE;
1347     }
1348   
1349   tmp_pos = gtk_entry_find_position (entry, event->x + entry->scroll_offset);
1350     
1351   if (event->button == 1)
1352     {
1353       gboolean have_selection = gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end);
1354       
1355       entry->select_words = FALSE;
1356       entry->select_lines = FALSE;
1357
1358       if (event->state & GDK_SHIFT_MASK)
1359         {
1360           gtk_entry_reset_im_context (entry);
1361           
1362           if (!have_selection) /* select from the current position to the clicked position */
1363             sel_start = sel_end = entry->current_pos;
1364           
1365           if (tmp_pos > sel_start && tmp_pos < sel_end)
1366             {
1367               /* Truncate current selection */
1368               gtk_entry_set_positions (entry, tmp_pos, -1);
1369             }
1370           else
1371             {
1372               gboolean extend_to_left;
1373               gint start, end;
1374
1375               /* Figure out what click selects and extend current selection */
1376               switch (event->type)
1377                 {
1378                 case GDK_BUTTON_PRESS:
1379                   gtk_entry_set_positions (entry, tmp_pos, tmp_pos);
1380                   break;
1381                   
1382                 case GDK_2BUTTON_PRESS:
1383                   entry->select_words = TRUE;
1384                   gtk_entry_select_word (entry);
1385                   break;
1386                   
1387                 case GDK_3BUTTON_PRESS:
1388                   entry->select_lines = TRUE;
1389                   gtk_entry_select_line (entry);
1390                   break;
1391
1392                 default:
1393                   break;
1394                 }
1395
1396               start = MIN (entry->current_pos, entry->selection_bound);
1397               start = MIN (sel_start, start);
1398               
1399               end = MAX (entry->current_pos, entry->selection_bound);
1400               end = MAX (sel_end, end);
1401
1402               if (tmp_pos == sel_start || tmp_pos == sel_end)
1403                 extend_to_left = (tmp_pos == start);
1404               else
1405                 extend_to_left = (end == sel_end);
1406               
1407               if (extend_to_left)
1408                 gtk_entry_set_positions (entry, start, end);
1409               else
1410                 gtk_entry_set_positions (entry, end, start);
1411             }
1412         }
1413       else /* no shift key */
1414         switch (event->type)
1415         {
1416         case GDK_BUTTON_PRESS:
1417           if (have_selection && tmp_pos >= sel_start && tmp_pos <= sel_end)
1418             {
1419               /* Click inside the selection - we'll either start a drag, or
1420                * clear the selection
1421                */
1422
1423               entry->in_drag = TRUE;
1424               entry->drag_start_x = event->x + entry->scroll_offset;
1425               entry->drag_start_y = event->y + entry->scroll_offset;
1426             }
1427           else
1428             gtk_editable_set_position (editable, tmp_pos);
1429           
1430           break;
1431
1432  
1433         case GDK_2BUTTON_PRESS:
1434           /* We ALWAYS receive a GDK_BUTTON_PRESS immediately before 
1435            * receiving a GDK_2BUTTON_PRESS so we need to reset
1436            * entry->in_drag which may have been set above
1437            */
1438           entry->in_drag = FALSE;
1439           entry->select_words = TRUE;
1440           gtk_entry_select_word (entry);
1441           break;
1442         
1443         case GDK_3BUTTON_PRESS:
1444           /* We ALWAYS receive a GDK_BUTTON_PRESS immediately before
1445            * receiving a GDK_3BUTTON_PRESS so we need to reset
1446            * entry->in_drag which may have been set above
1447            */
1448           entry->in_drag = FALSE;
1449           entry->select_lines = TRUE;
1450           gtk_entry_select_line (entry);
1451           break;
1452
1453         default:
1454           break;
1455         }
1456
1457       return TRUE;
1458     }
1459   else if (event->button == 2 && event->type == GDK_BUTTON_PRESS && entry->editable)
1460     {
1461       gtk_editable_select_region (editable, tmp_pos, tmp_pos);
1462       gtk_entry_paste (entry, GDK_SELECTION_PRIMARY);
1463
1464       return TRUE;
1465     }
1466   else if (event->button == 3 && event->type == GDK_BUTTON_PRESS)
1467     {
1468       gtk_entry_do_popup (entry, event);
1469       entry->button = 0;        /* Don't wait for release, since the menu will gtk_grab_add */
1470
1471       return TRUE;
1472     }
1473
1474   return FALSE;
1475 }
1476
1477 static gint
1478 gtk_entry_button_release (GtkWidget      *widget,
1479                           GdkEventButton *event)
1480 {
1481   GtkEntry *entry = GTK_ENTRY (widget);
1482
1483   if (event->window != entry->text_area || entry->button != event->button)
1484     return FALSE;
1485
1486   if (entry->in_drag)
1487     {
1488       gint tmp_pos = gtk_entry_find_position (entry, entry->drag_start_x);
1489
1490       gtk_editable_set_position (GTK_EDITABLE (entry), tmp_pos);
1491
1492       entry->in_drag = 0;
1493     }
1494   
1495   entry->button = 0;
1496   
1497   gtk_entry_update_primary_selection (entry);
1498               
1499   return TRUE;
1500 }
1501
1502 static gint
1503 gtk_entry_motion_notify (GtkWidget      *widget,
1504                          GdkEventMotion *event)
1505 {
1506   GtkEntry *entry = GTK_ENTRY (widget);
1507   gint tmp_pos;
1508
1509   if (entry->mouse_cursor_obscured)
1510     {
1511       GdkCursor *cursor;
1512       
1513       cursor = gdk_cursor_new_for_display (gtk_widget_get_display (widget), GDK_XTERM);
1514       gdk_window_set_cursor (entry->text_area, cursor);
1515       gdk_cursor_unref (cursor);
1516       entry->mouse_cursor_obscured = FALSE;
1517     }
1518
1519   if (event->window != entry->text_area || entry->button != 1)
1520     return FALSE;
1521
1522   if (entry->select_lines)
1523     return TRUE;
1524
1525   if (event->is_hint || (entry->text_area != event->window))
1526     gdk_window_get_pointer (entry->text_area, NULL, NULL, NULL);
1527
1528   if (entry->in_drag)
1529     {
1530       if (gtk_drag_check_threshold (widget,
1531                                     entry->drag_start_x, entry->drag_start_y,
1532                                     event->x + entry->scroll_offset, event->y))
1533         {
1534           GdkDragContext *context;
1535           GtkTargetList *target_list = gtk_target_list_new (target_table, G_N_ELEMENTS (target_table));
1536           guint actions = entry->editable ? GDK_ACTION_COPY | GDK_ACTION_MOVE : GDK_ACTION_COPY;
1537           
1538           context = gtk_drag_begin (widget, target_list, actions,
1539                           entry->button, (GdkEvent *)event);
1540
1541           
1542           entry->in_drag = FALSE;
1543           entry->button = 0;
1544           
1545           gtk_target_list_unref (target_list);
1546           gtk_drag_set_icon_default (context);
1547         }
1548     }
1549   else
1550     {
1551       gint height;
1552       gdk_drawable_get_size (entry->text_area, NULL, &height);
1553
1554       if (event->y < 0)
1555         tmp_pos = 0;
1556       else if (event->y >= height)
1557         tmp_pos = entry->text_length;
1558       else
1559         tmp_pos = gtk_entry_find_position (entry, event->x + entry->scroll_offset);
1560       
1561       if (entry->select_words) 
1562         {
1563           gint min, max;
1564           gint old_min, old_max;
1565           gint pos, bound;
1566           
1567           min = gtk_entry_move_backward_word (entry, tmp_pos);
1568           max = gtk_entry_move_forward_word (entry, tmp_pos);
1569           
1570           pos = entry->current_pos;
1571           bound = entry->selection_bound;
1572
1573           old_min = MIN(entry->current_pos, entry->selection_bound);
1574           old_max = MAX(entry->current_pos, entry->selection_bound);
1575           
1576           if (min < old_min)
1577             {
1578               pos = min;
1579               bound = old_max;
1580             }
1581           else if (old_max < max) 
1582             {
1583               pos = max;
1584               bound = old_min;
1585             }
1586           else if (pos == old_min) 
1587             {
1588               if (entry->current_pos != min)
1589                 pos = max;
1590             }
1591           else 
1592             {
1593               if (entry->current_pos != max)
1594                 pos = min;
1595             }
1596         
1597           gtk_entry_set_positions (entry, pos, bound);
1598         }
1599       else
1600       gtk_entry_set_positions (entry, tmp_pos, -1);
1601     }
1602       
1603   return TRUE;
1604 }
1605
1606 static void
1607 set_invisible_cursor (GdkWindow *window)
1608 {
1609   GdkBitmap *empty_bitmap;
1610   GdkCursor *cursor;
1611   GdkColor useless;
1612   char invisible_cursor_bits[] = { 0x0 };       
1613         
1614   useless.red = useless.green = useless.blue = 0;
1615   useless.pixel = 0;
1616   
1617   empty_bitmap = gdk_bitmap_create_from_data (window,
1618                                               invisible_cursor_bits,
1619                                               1, 1);
1620   
1621   cursor = gdk_cursor_new_from_pixmap (empty_bitmap,
1622                                        empty_bitmap,
1623                                        &useless,
1624                                        &useless, 0, 0);
1625   
1626   gdk_window_set_cursor (window, cursor);
1627   
1628   gdk_cursor_unref (cursor);
1629   
1630   g_object_unref (empty_bitmap);
1631 }
1632
1633 static void
1634 gtk_entry_obscure_mouse_cursor (GtkEntry *entry)
1635 {
1636   if (entry->mouse_cursor_obscured)
1637     return;
1638
1639   set_invisible_cursor (entry->text_area);
1640   
1641   entry->mouse_cursor_obscured = TRUE;  
1642 }
1643
1644 static gint
1645 gtk_entry_key_press (GtkWidget   *widget,
1646                      GdkEventKey *event)
1647 {
1648   GtkEntry *entry = GTK_ENTRY (widget);
1649
1650   gtk_entry_pend_cursor_blink (entry);
1651
1652   if (entry->editable)
1653     {
1654       if (gtk_im_context_filter_keypress (entry->im_context, event))
1655         {
1656           gtk_entry_obscure_mouse_cursor (entry);
1657           entry->need_im_reset = TRUE;
1658           return TRUE;
1659         }
1660     }
1661
1662   if (event->keyval == GDK_Return || event->keyval == GDK_ISO_Enter
1663       || event->keyval == GDK_Escape)
1664     {
1665       GtkEntryCompletion *completion = gtk_entry_get_completion (entry);
1666
1667       if (completion && completion->priv->completion_timeout)
1668         {
1669           g_source_remove (completion->priv->completion_timeout);
1670           completion->priv->completion_timeout = 0;
1671         }
1672     }
1673
1674   if (GTK_WIDGET_CLASS (parent_class)->key_press_event (widget, event))
1675     /* Activate key bindings
1676      */
1677     return TRUE;
1678
1679   return FALSE;
1680 }
1681
1682 static gint
1683 gtk_entry_key_release (GtkWidget   *widget,
1684                        GdkEventKey *event)
1685 {
1686   GtkEntry *entry = GTK_ENTRY (widget);
1687
1688   if (entry->editable)
1689     {
1690       if (gtk_im_context_filter_keypress (entry->im_context, event))
1691         {
1692           entry->need_im_reset = TRUE;
1693           return TRUE;
1694         }
1695     }
1696
1697   return GTK_WIDGET_CLASS (parent_class)->key_release_event (widget, event);
1698 }
1699
1700 static gint
1701 gtk_entry_focus_in (GtkWidget     *widget,
1702                     GdkEventFocus *event)
1703 {
1704   GtkEntry *entry = GTK_ENTRY (widget);
1705   
1706   gtk_widget_queue_draw (widget);
1707   
1708   entry->need_im_reset = TRUE;
1709   gtk_im_context_focus_in (entry->im_context);
1710
1711   g_signal_connect (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
1712                     "direction_changed",
1713                     G_CALLBACK (gtk_entry_keymap_direction_changed), entry);
1714
1715   gtk_entry_check_cursor_blink (entry);
1716
1717   return FALSE;
1718 }
1719
1720 static gint
1721 gtk_entry_focus_out (GtkWidget     *widget,
1722                      GdkEventFocus *event)
1723 {
1724   GtkEntry *entry = GTK_ENTRY (widget);
1725   GtkEntryCompletion *completion;
1726   
1727   gtk_widget_queue_draw (widget);
1728
1729   entry->need_im_reset = TRUE;
1730   gtk_im_context_focus_out (entry->im_context);
1731
1732   gtk_entry_check_cursor_blink (entry);
1733   
1734   g_signal_handlers_disconnect_by_func (gdk_keymap_get_for_display (gtk_widget_get_display (widget)),
1735                                         gtk_entry_keymap_direction_changed,
1736                                         entry);
1737
1738   completion = gtk_entry_get_completion (entry);
1739   if (completion)
1740     _gtk_entry_completion_popdown (completion);
1741   
1742   return FALSE;
1743 }
1744
1745 static void
1746 gtk_entry_grab_focus (GtkWidget        *widget)
1747 {
1748   GtkEntry *entry = GTK_ENTRY (widget);
1749   gboolean select_on_focus;
1750   
1751   GTK_WIDGET_CLASS (parent_class)->grab_focus (widget);
1752
1753   g_object_get (gtk_widget_get_settings (widget),
1754                 "gtk-entry-select-on-focus",
1755                 &select_on_focus,
1756                 NULL);
1757   
1758   if (select_on_focus && entry->editable && !entry->in_click)
1759     gtk_editable_select_region (GTK_EDITABLE (widget), 0, -1);
1760 }
1761
1762 static void 
1763 gtk_entry_direction_changed (GtkWidget        *widget,
1764                              GtkTextDirection  previous_dir)
1765 {
1766   GtkEntry *entry = GTK_ENTRY (widget);
1767
1768   gtk_entry_recompute (entry);
1769       
1770   GTK_WIDGET_CLASS (parent_class)->direction_changed (widget, previous_dir);
1771 }
1772
1773 static void
1774 gtk_entry_state_changed (GtkWidget      *widget,
1775                          GtkStateType    previous_state)
1776 {
1777   GtkEntry *entry = GTK_ENTRY (widget);
1778   
1779   if (GTK_WIDGET_REALIZED (widget))
1780     {
1781       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1782       gdk_window_set_background (entry->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1783     }
1784
1785   if (!GTK_WIDGET_IS_SENSITIVE (widget))
1786     {
1787       /* Clear any selection */
1788       gtk_editable_select_region (GTK_EDITABLE (entry), entry->current_pos, entry->current_pos);      
1789     }
1790   
1791   gtk_widget_queue_draw (widget);
1792 }
1793
1794 static void
1795 gtk_entry_screen_changed (GtkWidget *widget,
1796                           GdkScreen *old_screen)
1797 {
1798   gtk_entry_recompute (GTK_ENTRY (widget));
1799 }
1800
1801 /* GtkEditable method implementations
1802  */
1803 static void
1804 gtk_entry_insert_text (GtkEditable *editable,
1805                        const gchar *new_text,
1806                        gint         new_text_length,
1807                        gint        *position)
1808 {
1809   GtkEntry *entry = GTK_ENTRY (editable);
1810   gchar buf[64];
1811   gchar *text;
1812
1813   if (*position < 0 || *position > entry->text_length)
1814     *position = entry->text_length;
1815   
1816   g_object_ref (editable);
1817   
1818   if (new_text_length <= 63)
1819     text = buf;
1820   else
1821     text = g_new (gchar, new_text_length + 1);
1822
1823   text[new_text_length] = '\0';
1824   strncpy (text, new_text, new_text_length);
1825   
1826   g_signal_emit_by_name (editable, "insert_text", text, new_text_length, position);
1827
1828   if (new_text_length > 63)
1829     g_free (text);
1830
1831   g_object_unref (editable);
1832 }
1833
1834 static void
1835 gtk_entry_delete_text (GtkEditable *editable,
1836                        gint         start_pos,
1837                        gint         end_pos)
1838 {
1839   GtkEntry *entry = GTK_ENTRY (editable);
1840
1841   if (end_pos < 0 || end_pos > entry->text_length)
1842     end_pos = entry->text_length;
1843   if (start_pos < 0)
1844     start_pos = 0;
1845   if (start_pos > end_pos)
1846     start_pos = end_pos;
1847   
1848   g_object_ref (editable);
1849
1850   g_signal_emit_by_name (editable, "delete_text", start_pos, end_pos);
1851
1852   g_object_unref (editable);
1853 }
1854
1855 static gchar *    
1856 gtk_entry_get_chars      (GtkEditable   *editable,
1857                           gint           start_pos,
1858                           gint           end_pos)
1859 {
1860   GtkEntry *entry = GTK_ENTRY (editable);
1861   gint start_index, end_index;
1862   
1863   if (end_pos < 0)
1864     end_pos = entry->text_length;
1865
1866   start_pos = MIN (entry->text_length, start_pos);
1867   end_pos = MIN (entry->text_length, end_pos);
1868
1869   start_index = g_utf8_offset_to_pointer (entry->text, start_pos) - entry->text;
1870   end_index = g_utf8_offset_to_pointer (entry->text, end_pos) - entry->text;
1871
1872   return g_strndup (entry->text + start_index, end_index - start_index);
1873 }
1874
1875 static void
1876 gtk_entry_set_position_internal (GtkEntry    *entry,
1877                                  gint         position,
1878                                  gboolean     reset_im)
1879 {
1880   if (position < 0 || position > entry->text_length)
1881     position = entry->text_length;
1882
1883   if (position != entry->current_pos ||
1884       position != entry->selection_bound)
1885     {
1886       if (reset_im)
1887         gtk_entry_reset_im_context (entry);
1888       gtk_entry_set_positions (entry, position, position);
1889     }
1890 }
1891
1892 static void
1893 gtk_entry_real_set_position (GtkEditable *editable,
1894                              gint         position)
1895 {
1896   gtk_entry_set_position_internal (GTK_ENTRY (editable), position, TRUE);
1897 }
1898
1899 static gint
1900 gtk_entry_get_position (GtkEditable *editable)
1901 {
1902   return GTK_ENTRY (editable)->current_pos;
1903 }
1904
1905 static void
1906 gtk_entry_set_selection_bounds (GtkEditable *editable,
1907                                 gint         start,
1908                                 gint         end)
1909 {
1910   GtkEntry *entry = GTK_ENTRY (editable);
1911
1912   if (start < 0)
1913     start = entry->text_length;
1914   if (end < 0)
1915     end = entry->text_length;
1916   
1917   gtk_entry_reset_im_context (entry);
1918
1919   gtk_entry_set_positions (entry,
1920                            MIN (end, entry->text_length),
1921                            MIN (start, entry->text_length));
1922
1923   gtk_entry_update_primary_selection (entry);
1924 }
1925
1926 static gboolean
1927 gtk_entry_get_selection_bounds (GtkEditable *editable,
1928                                 gint        *start,
1929                                 gint        *end)
1930 {
1931   GtkEntry *entry = GTK_ENTRY (editable);
1932
1933   *start = entry->selection_bound;
1934   *end = entry->current_pos;
1935
1936   return (entry->selection_bound != entry->current_pos);
1937 }
1938
1939 static void 
1940 gtk_entry_style_set     (GtkWidget      *widget,
1941                          GtkStyle       *previous_style)
1942 {
1943   GtkEntry *entry = GTK_ENTRY (widget);
1944
1945   gtk_entry_recompute (entry);
1946
1947   if (previous_style && GTK_WIDGET_REALIZED (widget))
1948     {
1949       gdk_window_set_background (widget->window, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1950       gdk_window_set_background (entry->text_area, &widget->style->base[GTK_WIDGET_STATE (widget)]);
1951     }
1952 }
1953
1954 /* GtkCellEditable method implementations
1955  */
1956 static void
1957 gtk_cell_editable_entry_activated (GtkEntry *entry, gpointer data)
1958 {
1959   gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1960   gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1961 }
1962
1963 static gboolean
1964 gtk_cell_editable_key_press_event (GtkEntry    *entry,
1965                                    GdkEventKey *key_event,
1966                                    gpointer     data)
1967 {
1968   if (key_event->keyval == GDK_Escape)
1969     {
1970       entry->editing_canceled = TRUE;
1971       gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1972       gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1973
1974       return TRUE;
1975     }
1976
1977   /* override focus */
1978   if (key_event->keyval == GDK_Up || key_event->keyval == GDK_Down)
1979     {
1980       gtk_cell_editable_editing_done (GTK_CELL_EDITABLE (entry));
1981       gtk_cell_editable_remove_widget (GTK_CELL_EDITABLE (entry));
1982
1983       return TRUE;
1984     }
1985
1986   return FALSE;
1987 }
1988
1989 static void
1990 gtk_entry_start_editing (GtkCellEditable *cell_editable,
1991                          GdkEvent        *event)
1992 {
1993   GTK_ENTRY (cell_editable)->is_cell_renderer = TRUE;
1994
1995   g_signal_connect (cell_editable, "activate",
1996                     G_CALLBACK (gtk_cell_editable_entry_activated), NULL);
1997   g_signal_connect (cell_editable, "key_press_event",
1998                     G_CALLBACK (gtk_cell_editable_key_press_event), NULL);
1999 }
2000
2001 /* Default signal handlers
2002  */
2003 static void
2004 gtk_entry_real_insert_text (GtkEditable *editable,
2005                             const gchar *new_text,
2006                             gint         new_text_length,
2007                             gint        *position)
2008 {
2009   gint index;
2010   gint n_chars;
2011
2012   GtkEntry *entry = GTK_ENTRY (editable);
2013
2014   if (new_text_length < 0)
2015     new_text_length = strlen (new_text);
2016
2017   n_chars = g_utf8_strlen (new_text, new_text_length);
2018   if (entry->text_max_length > 0 && n_chars + entry->text_length > entry->text_max_length)
2019     {
2020       gdk_display_beep (gtk_widget_get_display (GTK_WIDGET (entry)));
2021       n_chars = entry->text_max_length - entry->text_length;
2022       new_text_length = g_utf8_offset_to_pointer (new_text, n_chars) - new_text;
2023     }
2024
2025   if (new_text_length + entry->n_bytes + 1 > entry->text_size)
2026     {
2027       while (new_text_length + entry->n_bytes + 1 > entry->text_size)
2028         {
2029           if (entry->text_size == 0)
2030             entry->text_size = MIN_SIZE;
2031           else
2032             {
2033               if (2 * (guint)entry->text_size < MAX_SIZE &&
2034                   2 * (guint)entry->text_size > entry->text_size)
2035                 entry->text_size *= 2;
2036               else
2037                 {
2038                   entry->text_size = MAX_SIZE;
2039                   if (new_text_length > (gint)entry->text_size - (gint)entry->n_bytes - 1)
2040                     {
2041                       new_text_length = (gint)entry->text_size - (gint)entry->n_bytes - 1;
2042                       new_text_length = g_utf8_find_prev_char (new_text, new_text + new_text_length + 1) - new_text;
2043                       n_chars = g_utf8_strlen (new_text, new_text_length);
2044                     }
2045                   break;
2046                 }
2047             }
2048         }
2049
2050       entry->text = g_realloc (entry->text, entry->text_size);
2051     }
2052
2053   index = g_utf8_offset_to_pointer (entry->text, *position) - entry->text;
2054
2055   g_memmove (entry->text + index + new_text_length, entry->text + index, entry->n_bytes - index);
2056   memcpy (entry->text + index, new_text, new_text_length);
2057
2058   entry->n_bytes += new_text_length;
2059   entry->text_length += n_chars;
2060
2061   /* NUL terminate for safety and convenience */
2062   entry->text[entry->n_bytes] = '\0';
2063   
2064   if (entry->current_pos > *position)
2065     entry->current_pos += n_chars;
2066   
2067   if (entry->selection_bound > *position)
2068     entry->selection_bound += n_chars;
2069
2070   *position += n_chars;
2071
2072   gtk_entry_recompute (entry);
2073
2074   g_signal_emit_by_name (editable, "changed");
2075   g_object_notify (G_OBJECT (editable), "text");
2076 }
2077
2078 static void
2079 gtk_entry_real_delete_text (GtkEditable *editable,
2080                             gint         start_pos,
2081                             gint         end_pos)
2082 {
2083   GtkEntry *entry = GTK_ENTRY (editable);
2084
2085   if (start_pos < 0)
2086     start_pos = 0;
2087   if (end_pos < 0 || end_pos > entry->text_length)
2088     end_pos = entry->text_length;
2089   
2090   if (start_pos < end_pos)
2091     {
2092       gint start_index = g_utf8_offset_to_pointer (entry->text, start_pos) - entry->text;
2093       gint end_index = g_utf8_offset_to_pointer (entry->text, end_pos) - entry->text;
2094       gint current_pos;
2095       gint selection_bound;
2096
2097       g_memmove (entry->text + start_index, entry->text + end_index, entry->n_bytes + 1 - end_index);
2098       entry->text_length -= (end_pos - start_pos);
2099       entry->n_bytes -= (end_index - start_index);
2100       
2101       current_pos = entry->current_pos;
2102       if (current_pos > start_pos)
2103         current_pos -= MIN (current_pos, end_pos) - start_pos;
2104
2105       selection_bound = entry->selection_bound;
2106       if (selection_bound > start_pos)
2107         selection_bound -= MIN (selection_bound, end_pos) - start_pos;
2108
2109       gtk_entry_set_positions (entry, current_pos, selection_bound);
2110
2111       /* We might have deleted the selection
2112        */
2113       gtk_entry_update_primary_selection (entry);
2114       
2115       gtk_entry_recompute (entry);
2116
2117       g_signal_emit_by_name (editable, "changed");
2118       g_object_notify (G_OBJECT (editable), "text");
2119     }
2120 }
2121
2122 /* Compute the X position for an offset that corresponds to the "more important
2123  * cursor position for that offset. We use this when trying to guess to which
2124  * end of the selection we should go to when the user hits the left or
2125  * right arrow key.
2126  */
2127 static gint
2128 get_better_cursor_x (GtkEntry *entry,
2129                      gint      offset)
2130 {
2131   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
2132   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
2133   gboolean split_cursor;
2134   
2135   PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
2136   const gchar *text = pango_layout_get_text (layout);
2137   gint index = g_utf8_offset_to_pointer (text, offset) - text;
2138   
2139   PangoRectangle strong_pos, weak_pos;
2140   
2141   g_object_get (gtk_widget_get_settings (GTK_WIDGET (entry)),
2142                 "gtk-split-cursor", &split_cursor,
2143                 NULL);
2144
2145   pango_layout_get_cursor_pos (layout, index, &strong_pos, &weak_pos);
2146
2147   if (split_cursor)
2148     return strong_pos.x / PANGO_SCALE;
2149   else
2150     return (keymap_direction == entry->resolved_dir) ? strong_pos.x / PANGO_SCALE : weak_pos.x / PANGO_SCALE;
2151 }
2152
2153 static void
2154 gtk_entry_move_cursor (GtkEntry       *entry,
2155                        GtkMovementStep step,
2156                        gint            count,
2157                        gboolean        extend_selection)
2158 {
2159   gint new_pos = entry->current_pos;
2160
2161   gtk_entry_reset_im_context (entry);
2162
2163   if (entry->current_pos != entry->selection_bound && !extend_selection)
2164     {
2165       /* If we have a current selection and aren't extending it, move to the
2166        * start/or end of the selection as appropriate
2167        */
2168       switch (step)
2169         {
2170         case GTK_MOVEMENT_VISUAL_POSITIONS:
2171           {
2172             gint current_x = get_better_cursor_x (entry, entry->current_pos);
2173             gint bound_x = get_better_cursor_x (entry, entry->selection_bound);
2174
2175             if (count < 0)
2176               new_pos = current_x < bound_x ? entry->current_pos : entry->selection_bound;
2177             else
2178               new_pos = current_x > bound_x ? entry->current_pos : entry->selection_bound;
2179
2180             break;
2181           }
2182         case GTK_MOVEMENT_LOGICAL_POSITIONS:
2183         case GTK_MOVEMENT_WORDS:
2184           if (count < 0)
2185             new_pos = MIN (entry->current_pos, entry->selection_bound);
2186           else
2187             new_pos = MAX (entry->current_pos, entry->selection_bound);
2188           break;
2189         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
2190         case GTK_MOVEMENT_PARAGRAPH_ENDS:
2191         case GTK_MOVEMENT_BUFFER_ENDS:
2192           new_pos = count < 0 ? 0 : entry->text_length;
2193           break;
2194         case GTK_MOVEMENT_DISPLAY_LINES:
2195         case GTK_MOVEMENT_PARAGRAPHS:
2196         case GTK_MOVEMENT_PAGES:
2197         case GTK_MOVEMENT_HORIZONTAL_PAGES:
2198           break;
2199         }
2200     }
2201   else
2202     {
2203       switch (step)
2204         {
2205         case GTK_MOVEMENT_LOGICAL_POSITIONS:
2206           new_pos = gtk_entry_move_logically (entry, new_pos, count);
2207           break;
2208         case GTK_MOVEMENT_VISUAL_POSITIONS:
2209           new_pos = gtk_entry_move_visually (entry, new_pos, count);
2210           break;
2211         case GTK_MOVEMENT_WORDS:
2212           while (count > 0)
2213             {
2214               new_pos = gtk_entry_move_forward_word (entry, new_pos);
2215               count--;
2216             }
2217           while (count < 0)
2218             {
2219               new_pos = gtk_entry_move_backward_word (entry, new_pos);
2220               count++;
2221             }
2222           break;
2223         case GTK_MOVEMENT_DISPLAY_LINE_ENDS:
2224         case GTK_MOVEMENT_PARAGRAPH_ENDS:
2225         case GTK_MOVEMENT_BUFFER_ENDS:
2226           new_pos = count < 0 ? 0 : entry->text_length;
2227           break;
2228         case GTK_MOVEMENT_DISPLAY_LINES:
2229         case GTK_MOVEMENT_PARAGRAPHS:
2230         case GTK_MOVEMENT_PAGES:
2231         case GTK_MOVEMENT_HORIZONTAL_PAGES:
2232           break;
2233         }
2234     }
2235
2236   if (extend_selection)
2237     gtk_editable_select_region (GTK_EDITABLE (entry), entry->selection_bound, new_pos);
2238   else
2239     gtk_editable_set_position (GTK_EDITABLE (entry), new_pos);
2240   
2241   gtk_entry_pend_cursor_blink (entry);
2242 }
2243
2244 static void
2245 gtk_entry_insert_at_cursor (GtkEntry    *entry,
2246                             const gchar *str)
2247 {
2248   GtkEditable *editable = GTK_EDITABLE (entry);
2249   gint pos = entry->current_pos;
2250
2251   if (entry->editable)
2252     {
2253       gtk_entry_reset_im_context (entry);
2254
2255       gtk_editable_insert_text (editable, str, -1, &pos);
2256       gtk_editable_set_position (editable, pos);
2257     }
2258 }
2259
2260 static void
2261 gtk_entry_delete_from_cursor (GtkEntry       *entry,
2262                               GtkDeleteType   type,
2263                               gint            count)
2264 {
2265   GtkEditable *editable = GTK_EDITABLE (entry);
2266   gint start_pos = entry->current_pos;
2267   gint end_pos = entry->current_pos;
2268   
2269   gtk_entry_reset_im_context (entry);
2270
2271   if (!entry->editable)
2272     return;
2273
2274   if (entry->selection_bound != entry->current_pos)
2275     {
2276       gtk_editable_delete_selection (editable);
2277       return;
2278     }
2279   
2280   switch (type)
2281     {
2282     case GTK_DELETE_CHARS:
2283       end_pos = gtk_entry_move_logically (entry, entry->current_pos, count);
2284       gtk_editable_delete_text (editable, MIN (start_pos, end_pos), MAX (start_pos, end_pos));
2285       break;
2286     case GTK_DELETE_WORDS:
2287       if (count < 0)
2288         {
2289           /* Move to end of current word, or if not on a word, end of previous word */
2290           end_pos = gtk_entry_move_backward_word (entry, end_pos);
2291           end_pos = gtk_entry_move_forward_word (entry, end_pos);
2292         }
2293       else if (count > 0)
2294         {
2295           /* Move to beginning of current word, or if not on a word, begining of next word */
2296           start_pos = gtk_entry_move_forward_word (entry, start_pos);
2297           start_pos = gtk_entry_move_backward_word (entry, start_pos);
2298         }
2299         
2300       /* Fall through */
2301     case GTK_DELETE_WORD_ENDS:
2302       while (count < 0)
2303         {
2304           start_pos = gtk_entry_move_backward_word (entry, start_pos);
2305           count++;
2306         }
2307       while (count > 0)
2308         {
2309           end_pos = gtk_entry_move_forward_word (entry, end_pos);
2310           count--;
2311         }
2312       gtk_editable_delete_text (editable, start_pos, end_pos);
2313       break;
2314     case GTK_DELETE_DISPLAY_LINE_ENDS:
2315     case GTK_DELETE_PARAGRAPH_ENDS:
2316       if (count < 0)
2317         gtk_editable_delete_text (editable, 0, entry->current_pos);
2318       else
2319         gtk_editable_delete_text (editable, entry->current_pos, -1);
2320       break;
2321     case GTK_DELETE_DISPLAY_LINES:
2322     case GTK_DELETE_PARAGRAPHS:
2323       gtk_editable_delete_text (editable, 0, -1);  
2324       break;
2325     case GTK_DELETE_WHITESPACE:
2326       gtk_entry_delete_whitespace (entry);
2327       break;
2328     }
2329   
2330   gtk_entry_pend_cursor_blink (entry);
2331 }
2332
2333 static void
2334 gtk_entry_copy_clipboard (GtkEntry *entry)
2335 {
2336   GtkEditable *editable = GTK_EDITABLE (entry);
2337   gint start, end;
2338
2339   if (gtk_editable_get_selection_bounds (editable, &start, &end))
2340     {
2341       gchar *str = gtk_entry_get_public_chars (entry, start, end);
2342       gtk_clipboard_set_text (gtk_widget_get_clipboard (GTK_WIDGET (entry),
2343                                                         GDK_SELECTION_CLIPBOARD),
2344                               str, -1);
2345       g_free (str);
2346     }
2347 }
2348
2349 static void
2350 gtk_entry_cut_clipboard (GtkEntry *entry)
2351 {
2352   GtkEditable *editable = GTK_EDITABLE (entry);
2353   gint start, end;
2354
2355   gtk_entry_copy_clipboard (entry);
2356
2357   if (entry->editable)
2358     {
2359       if (gtk_editable_get_selection_bounds (editable, &start, &end))
2360         gtk_editable_delete_text (editable, start, end);
2361     }
2362 }
2363
2364 static void
2365 gtk_entry_paste_clipboard (GtkEntry *entry)
2366 {
2367   if (entry->editable)
2368     gtk_entry_paste (entry, GDK_NONE);
2369 }
2370
2371 static void
2372 gtk_entry_delete_cb (GtkEntry *entry)
2373 {
2374   GtkEditable *editable = GTK_EDITABLE (entry);
2375   gint start, end;
2376
2377   if (entry->editable)
2378     {
2379       if (gtk_editable_get_selection_bounds (editable, &start, &end))
2380         gtk_editable_delete_text (editable, start, end);
2381     }
2382 }
2383
2384 static void
2385 gtk_entry_toggle_overwrite (GtkEntry *entry)
2386 {
2387   entry->overwrite_mode = !entry->overwrite_mode;
2388 }
2389
2390 static void
2391 gtk_entry_select_all (GtkEntry *entry)
2392 {
2393   gtk_entry_select_line (entry);
2394 }
2395
2396 static void
2397 gtk_entry_real_activate (GtkEntry *entry)
2398 {
2399   GtkWindow *window;
2400   GtkWidget *toplevel;
2401   GtkWidget *widget;
2402
2403   widget = GTK_WIDGET (entry);
2404
2405   if (entry->activates_default)
2406     {
2407       toplevel = gtk_widget_get_toplevel (widget);
2408       if (GTK_IS_WINDOW (toplevel))
2409         {
2410           window = GTK_WINDOW (toplevel);
2411       
2412           if (window &&
2413               widget != window->default_widget &&
2414               !(widget == window->focus_widget &&
2415                 (!window->default_widget || !GTK_WIDGET_SENSITIVE (window->default_widget))))
2416             gtk_window_activate_default (window);
2417         }
2418     }
2419 }
2420
2421 static void
2422 gtk_entry_keymap_direction_changed (GdkKeymap *keymap,
2423                                     GtkEntry  *entry)
2424 {
2425   gtk_entry_recompute (entry);
2426 }
2427
2428 /* IM Context Callbacks
2429  */
2430
2431 static void
2432 gtk_entry_commit_cb (GtkIMContext *context,
2433                      const gchar  *str,
2434                      GtkEntry     *entry)
2435 {
2436   gtk_entry_enter_text (entry, str);
2437 }
2438
2439 static void 
2440 gtk_entry_preedit_changed_cb (GtkIMContext *context,
2441                               GtkEntry     *entry)
2442 {
2443   gchar *preedit_string;
2444   gint cursor_pos;
2445   
2446   gtk_im_context_get_preedit_string (entry->im_context,
2447                                      &preedit_string, NULL,
2448                                      &cursor_pos);
2449   entry->preedit_length = strlen (preedit_string);
2450   cursor_pos = CLAMP (cursor_pos, 0, g_utf8_strlen (preedit_string, -1));
2451   entry->preedit_cursor = cursor_pos;
2452   g_free (preedit_string);
2453
2454   gtk_entry_recompute (entry);
2455 }
2456
2457 static gboolean
2458 gtk_entry_retrieve_surrounding_cb (GtkIMContext *context,
2459                                GtkEntry     *entry)
2460 {
2461   gtk_im_context_set_surrounding (context,
2462                                   entry->text,
2463                                   entry->n_bytes,
2464                                   g_utf8_offset_to_pointer (entry->text, entry->current_pos) - entry->text);
2465
2466   return TRUE;
2467 }
2468
2469 static gboolean
2470 gtk_entry_delete_surrounding_cb (GtkIMContext *slave,
2471                                  gint          offset,
2472                                  gint          n_chars,
2473                                  GtkEntry     *entry)
2474 {
2475   gtk_editable_delete_text (GTK_EDITABLE (entry),
2476                             entry->current_pos + offset,
2477                             entry->current_pos + offset + n_chars);
2478
2479   return TRUE;
2480 }
2481
2482 /* Internal functions
2483  */
2484
2485 /* Used for im_commit_cb and inserting Unicode chars */
2486 static void
2487 gtk_entry_enter_text (GtkEntry       *entry,
2488                       const gchar    *str)
2489 {
2490   GtkEditable *editable = GTK_EDITABLE (entry);
2491   gint tmp_pos;
2492
2493   if (gtk_editable_get_selection_bounds (editable, NULL, NULL))
2494     gtk_editable_delete_selection (editable);
2495   else
2496     {
2497       if (entry->overwrite_mode)
2498         gtk_entry_delete_from_cursor (entry, GTK_DELETE_CHARS, 1);
2499     }
2500
2501   tmp_pos = entry->current_pos;
2502   gtk_editable_insert_text (editable, str, strlen (str), &tmp_pos);
2503   gtk_entry_set_position_internal (entry, tmp_pos, FALSE);
2504 }
2505
2506 /* All changes to entry->current_pos and entry->selection_bound
2507  * should go through this function.
2508  */
2509 static void
2510 gtk_entry_set_positions (GtkEntry *entry,
2511                          gint      current_pos,
2512                          gint      selection_bound)
2513 {
2514   gboolean changed = FALSE;
2515
2516   g_object_freeze_notify (G_OBJECT (entry));
2517   
2518   if (current_pos != -1 &&
2519       entry->current_pos != current_pos)
2520     {
2521       entry->current_pos = current_pos;
2522       changed = TRUE;
2523
2524       g_object_notify (G_OBJECT (entry), "cursor_position");
2525     }
2526
2527   if (selection_bound != -1 &&
2528       entry->selection_bound != selection_bound)
2529     {
2530       entry->selection_bound = selection_bound;
2531       changed = TRUE;
2532       
2533       g_object_notify (G_OBJECT (entry), "selection_bound");
2534     }
2535
2536   g_object_thaw_notify (G_OBJECT (entry));
2537
2538   if (changed)
2539     gtk_entry_recompute (entry);
2540 }
2541
2542 static void
2543 gtk_entry_reset_layout (GtkEntry *entry)
2544 {
2545   if (entry->cached_layout)
2546     {
2547       g_object_unref (entry->cached_layout);
2548       entry->cached_layout = NULL;
2549     }
2550 }
2551
2552 static void
2553 update_im_cursor_location (GtkEntry *entry)
2554 {
2555   GdkRectangle area;
2556   gint strong_x;
2557   gint strong_xoffset;
2558   gint area_width, area_height;
2559
2560   gtk_entry_get_cursor_locations (entry, CURSOR_STANDARD, &strong_x, NULL)
2561 ;
2562   get_text_area_size (entry, NULL, NULL, &area_width, &area_height);
2563
2564   strong_xoffset = strong_x - entry->scroll_offset;
2565   if (strong_xoffset < 0)
2566     {
2567       strong_xoffset = 0;
2568     }
2569   else if (strong_xoffset > area_width)
2570     {
2571       strong_xoffset = area_width;
2572     }
2573   area.x = strong_xoffset;
2574   area.y = 0;
2575   area.width = 0;
2576   area.height = area_height;
2577
2578   gtk_im_context_set_cursor_location (entry->im_context, &area);
2579 }
2580
2581 static gboolean
2582 recompute_idle_func (gpointer data)
2583 {
2584   GtkEntry *entry;
2585
2586   GDK_THREADS_ENTER ();
2587
2588   entry = GTK_ENTRY (data);
2589
2590   entry->recompute_idle = 0;
2591   
2592   if (gtk_widget_has_screen (GTK_WIDGET (entry)))
2593     {
2594       gtk_entry_adjust_scroll (entry);
2595       gtk_entry_queue_draw (entry);
2596       
2597       update_im_cursor_location (entry);
2598     }
2599
2600   GDK_THREADS_LEAVE ();
2601
2602   return FALSE;
2603 }
2604
2605 static void
2606 gtk_entry_recompute (GtkEntry *entry)
2607 {
2608   gtk_entry_reset_layout (entry);
2609   gtk_entry_check_cursor_blink (entry);
2610   
2611   if (!entry->recompute_idle)
2612     {
2613       entry->recompute_idle = g_idle_add_full (G_PRIORITY_HIGH_IDLE + 15, /* between resize and redraw */
2614                                                recompute_idle_func, entry, NULL); 
2615     }
2616 }
2617
2618 static void
2619 append_char (GString *str,
2620              gunichar ch,
2621              gint     count)
2622 {
2623   gint i;
2624   gint char_len;
2625   gchar buf[7];
2626   
2627   char_len = g_unichar_to_utf8 (ch, buf);
2628   
2629   i = 0;
2630   while (i < count)
2631     {
2632       g_string_append_len (str, buf, char_len);
2633       ++i;
2634     }
2635 }
2636      
2637 static PangoLayout *
2638 gtk_entry_create_layout (GtkEntry *entry,
2639                          gboolean  include_preedit)
2640 {
2641   GtkWidget *widget = GTK_WIDGET (entry);
2642   PangoLayout *layout = gtk_widget_create_pango_layout (widget, NULL);
2643   PangoAttrList *tmp_attrs = pango_attr_list_new ();
2644   
2645   gchar *preedit_string = NULL;
2646   gint preedit_length = 0;
2647   PangoAttrList *preedit_attrs = NULL;
2648
2649   pango_layout_set_single_paragraph_mode (layout, TRUE);
2650   
2651   if (include_preedit)
2652     {
2653       gtk_im_context_get_preedit_string (entry->im_context,
2654                                          &preedit_string, &preedit_attrs, NULL);
2655       preedit_length = entry->preedit_length;
2656     }
2657
2658   if (preedit_length)
2659     {
2660       GString *tmp_string = g_string_new (NULL);
2661       
2662       gint cursor_index = g_utf8_offset_to_pointer (entry->text, entry->current_pos) - entry->text;
2663       
2664       if (entry->visible)
2665         {
2666           g_string_prepend_len (tmp_string, entry->text, entry->n_bytes);
2667           g_string_insert (tmp_string, cursor_index, preedit_string);
2668         }
2669       else
2670         {
2671           gint ch_len;
2672           gint preedit_len_chars;
2673           gunichar invisible_char;
2674           
2675           ch_len = g_utf8_strlen (entry->text, entry->n_bytes);
2676           preedit_len_chars = g_utf8_strlen (preedit_string, -1);
2677           ch_len += preedit_len_chars;
2678
2679           if (entry->invisible_char != 0)
2680             invisible_char = entry->invisible_char;
2681           else
2682             invisible_char = ' '; /* just pick a char */
2683           
2684           append_char (tmp_string, invisible_char, ch_len);
2685           
2686           /* Fix cursor index to point to invisible char corresponding
2687            * to the preedit, fix preedit_length to be the length of
2688            * the invisible chars representing the preedit
2689            */
2690           cursor_index =
2691             g_utf8_offset_to_pointer (tmp_string->str, entry->current_pos) -
2692             tmp_string->str;
2693           preedit_length =
2694             preedit_len_chars *
2695             g_unichar_to_utf8 (invisible_char, NULL);
2696         }
2697       
2698       pango_layout_set_text (layout, tmp_string->str, tmp_string->len);
2699       
2700       pango_attr_list_splice (tmp_attrs, preedit_attrs,
2701                               cursor_index, preedit_length);
2702       
2703       g_string_free (tmp_string, TRUE);
2704     }
2705   else
2706     {
2707       PangoDirection pango_dir;
2708       
2709       pango_dir = pango_find_base_dir (entry->text, entry->n_bytes);
2710       if (pango_dir == PANGO_DIRECTION_NEUTRAL)
2711         {
2712           if (GTK_WIDGET_HAS_FOCUS (widget))
2713             {
2714               GdkDisplay *display = gtk_widget_get_display (widget);
2715               GdkKeymap *keymap = gdk_keymap_get_for_display (display);
2716               pango_dir = gdk_keymap_get_direction (keymap);
2717             }
2718           else
2719             {
2720               if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_LTR)
2721                 pango_dir = PANGO_DIRECTION_LTR;
2722               else
2723                 pango_dir = PANGO_DIRECTION_RTL;
2724             }
2725         }
2726
2727       pango_context_set_base_dir (gtk_widget_get_pango_context (widget),
2728                                   pango_dir);
2729
2730       pango_layout_set_alignment (layout, pango_dir);
2731
2732       entry->resolved_dir = pango_dir;
2733       
2734       if (entry->visible)
2735         {
2736           pango_layout_set_text (layout, entry->text, entry->n_bytes);
2737         }
2738       else
2739         {
2740           GString *str = g_string_new (NULL);
2741           gunichar invisible_char;
2742           
2743           if (entry->invisible_char != 0)
2744             invisible_char = entry->invisible_char;
2745           else
2746             invisible_char = ' '; /* just pick a char */
2747           
2748           append_char (str, invisible_char, entry->text_length);
2749           pango_layout_set_text (layout, str->str, str->len);
2750           g_string_free (str, TRUE);
2751         }
2752     }
2753       
2754   pango_layout_set_attributes (layout, tmp_attrs);
2755
2756   if (preedit_string)
2757     g_free (preedit_string);
2758   if (preedit_attrs)
2759     pango_attr_list_unref (preedit_attrs);
2760       
2761   pango_attr_list_unref (tmp_attrs);
2762
2763   return layout;
2764 }
2765
2766 static PangoLayout *
2767 gtk_entry_ensure_layout (GtkEntry *entry,
2768                          gboolean  include_preedit)
2769 {
2770   if (entry->preedit_length > 0 &&
2771       !include_preedit != !entry->cache_includes_preedit)
2772     gtk_entry_reset_layout (entry);
2773
2774   if (!entry->cached_layout)
2775     {
2776       entry->cached_layout = gtk_entry_create_layout (entry, include_preedit);
2777       entry->cache_includes_preedit = include_preedit;
2778     }
2779   
2780   return entry->cached_layout;
2781 }
2782
2783 static void
2784 get_layout_position (GtkEntry *entry,
2785                      gint     *x,
2786                      gint     *y)
2787 {
2788   PangoLayout *layout;
2789   PangoRectangle logical_rect;
2790   gint area_width, area_height;
2791   gint y_pos;
2792   PangoLayoutLine *line;
2793   
2794   layout = gtk_entry_ensure_layout (entry, TRUE);
2795
2796   get_text_area_size (entry, NULL, NULL, &area_width, &area_height);      
2797       
2798   area_height = PANGO_SCALE * (area_height - 2 * INNER_BORDER);
2799   
2800   line = pango_layout_get_lines (layout)->data;
2801   pango_layout_line_get_extents (line, NULL, &logical_rect);
2802   
2803   /* Align primarily for locale's ascent/descent */
2804   y_pos = ((area_height - entry->ascent - entry->descent) / 2 + 
2805            entry->ascent + logical_rect.y);
2806   
2807   /* Now see if we need to adjust to fit in actual drawn string */
2808   if (logical_rect.height > area_height)
2809     y_pos = (area_height - logical_rect.height) / 2;
2810   else if (y_pos < 0)
2811     y_pos = 0;
2812   else if (y_pos + logical_rect.height > area_height)
2813     y_pos = area_height - logical_rect.height;
2814   
2815   y_pos = INNER_BORDER + y_pos / PANGO_SCALE;
2816
2817   if (x)
2818     *x = INNER_BORDER - entry->scroll_offset;
2819
2820   if (y)
2821     *y = y_pos;
2822 }
2823
2824 static void
2825 gtk_entry_draw_text (GtkEntry *entry)
2826 {
2827   GtkWidget *widget;
2828   PangoLayoutLine *line;
2829   
2830   if (!entry->visible && entry->invisible_char == 0)
2831     return;
2832   
2833   if (GTK_WIDGET_DRAWABLE (entry))
2834     {
2835       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
2836       gint x, y;
2837       gint start_pos, end_pos;
2838       
2839       widget = GTK_WIDGET (entry);
2840       
2841       get_layout_position (entry, &x, &y);
2842
2843       gdk_draw_layout (entry->text_area, widget->style->text_gc [widget->state],       
2844                        x, y,
2845                        layout);
2846       
2847       if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start_pos, &end_pos))
2848         {
2849           gint *ranges;
2850           gint n_ranges, i;
2851           PangoRectangle logical_rect;
2852           const gchar *text = pango_layout_get_text (layout);
2853           gint start_index = g_utf8_offset_to_pointer (text, start_pos) - text;
2854           gint end_index = g_utf8_offset_to_pointer (text, end_pos) - text;
2855           GdkRegion *clip_region = gdk_region_new ();
2856           GdkGC *text_gc;
2857           GdkGC *selection_gc;
2858
2859           line = pango_layout_get_lines (layout)->data;
2860           
2861           pango_layout_line_get_x_ranges (line, start_index, end_index, &ranges, &n_ranges);
2862
2863           pango_layout_get_extents (layout, NULL, &logical_rect);
2864           
2865           if (GTK_WIDGET_HAS_FOCUS (entry))
2866             {
2867               selection_gc = widget->style->base_gc [GTK_STATE_SELECTED];
2868               text_gc = widget->style->text_gc [GTK_STATE_SELECTED];
2869             }
2870           else
2871             {
2872               selection_gc = widget->style->base_gc [GTK_STATE_ACTIVE];
2873               text_gc = widget->style->text_gc [GTK_STATE_ACTIVE];
2874             }
2875           
2876           for (i=0; i < n_ranges; i++)
2877             {
2878               GdkRectangle rect;
2879
2880               rect.x = INNER_BORDER - entry->scroll_offset + ranges[2*i] / PANGO_SCALE;
2881               rect.y = y;
2882               rect.width = (ranges[2*i + 1] - ranges[2*i]) / PANGO_SCALE;
2883               rect.height = logical_rect.height / PANGO_SCALE;
2884                 
2885               gdk_draw_rectangle (entry->text_area, selection_gc, TRUE,
2886                                   rect.x, rect.y, rect.width, rect.height);
2887
2888               gdk_region_union_with_rect (clip_region, &rect);
2889             }
2890
2891           gdk_gc_set_clip_region (text_gc, clip_region);
2892           gdk_draw_layout (entry->text_area, text_gc, 
2893                            x, y,
2894                            layout);
2895           gdk_gc_set_clip_region (text_gc, NULL);
2896           
2897           gdk_region_destroy (clip_region);
2898           g_free (ranges);
2899         }
2900     }
2901 }
2902
2903 static void
2904 draw_insertion_cursor (GtkEntry      *entry,
2905                        GdkRectangle  *cursor_location,
2906                        gboolean       is_primary,
2907                        PangoDirection direction,
2908                        gboolean       draw_arrow)
2909 {
2910   GtkWidget *widget = GTK_WIDGET (entry);
2911   GtkTextDirection text_dir;
2912
2913   if (direction == PANGO_DIRECTION_LTR)
2914     text_dir = GTK_TEXT_DIR_LTR;
2915   else
2916     text_dir = GTK_TEXT_DIR_RTL;
2917
2918   gtk_draw_insertion_cursor (widget, entry->text_area, NULL,
2919                              cursor_location,
2920                              is_primary, text_dir, draw_arrow);
2921 }
2922
2923 static void
2924 gtk_entry_draw_cursor (GtkEntry  *entry,
2925                        CursorType type)
2926 {
2927   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
2928   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
2929   
2930   if (GTK_WIDGET_DRAWABLE (entry))
2931     {
2932       GtkWidget *widget = GTK_WIDGET (entry);
2933       GdkRectangle cursor_location;
2934       gboolean split_cursor;
2935
2936       gint xoffset = INNER_BORDER - entry->scroll_offset;
2937       gint strong_x, weak_x;
2938       gint text_area_height;
2939       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
2940       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
2941       gint x1 = 0;
2942       gint x2 = 0;
2943
2944       gdk_drawable_get_size (entry->text_area, NULL, &text_area_height);
2945       
2946       gtk_entry_get_cursor_locations (entry, type, &strong_x, &weak_x);
2947
2948       g_object_get (gtk_widget_get_settings (widget),
2949                     "gtk-split-cursor", &split_cursor,
2950                     NULL);
2951
2952       dir1 = entry->resolved_dir;
2953       
2954       if (split_cursor)
2955         {
2956           x1 = strong_x;
2957
2958           if (weak_x != strong_x)
2959             {
2960               dir2 = (entry->resolved_dir == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
2961               x2 = weak_x;
2962             }
2963         }
2964       else
2965         {
2966           if (keymap_direction == entry->resolved_dir)
2967             x1 = strong_x;
2968           else
2969             x1 = weak_x;
2970         }
2971
2972       cursor_location.x = xoffset + x1;
2973       cursor_location.y = INNER_BORDER;
2974       cursor_location.width = 0;
2975       cursor_location.height = text_area_height - 2 * INNER_BORDER ;
2976
2977       draw_insertion_cursor (entry,
2978                              &cursor_location, TRUE, dir1,
2979                              dir2 != PANGO_DIRECTION_NEUTRAL);
2980       
2981       if (dir2 != PANGO_DIRECTION_NEUTRAL)
2982         {
2983           cursor_location.x = xoffset + x2;
2984           draw_insertion_cursor (entry,
2985                                  &cursor_location, FALSE, dir2,
2986                                  TRUE);
2987         }
2988     }
2989 }
2990
2991 static void
2992 gtk_entry_queue_draw (GtkEntry *entry)
2993 {
2994   if (GTK_WIDGET_REALIZED (entry))
2995     gdk_window_invalidate_rect (entry->text_area, NULL, FALSE);
2996 }
2997
2998 static void
2999 gtk_entry_reset_im_context (GtkEntry *entry)
3000 {
3001   if (entry->need_im_reset)
3002     {
3003       entry->need_im_reset = 0;
3004       gtk_im_context_reset (entry->im_context);
3005     }
3006 }
3007
3008 static gint
3009 gtk_entry_find_position (GtkEntry *entry,
3010                          gint      x)
3011 {
3012   PangoLayout *layout;
3013   PangoLayoutLine *line;
3014   gint index;
3015   gint pos;
3016   gboolean trailing;
3017   const gchar *text;
3018   gint cursor_index;
3019   
3020   layout = gtk_entry_ensure_layout (entry, TRUE);
3021   text = pango_layout_get_text (layout);
3022   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3023   
3024   line = pango_layout_get_lines (layout)->data;
3025   pango_layout_line_x_to_index (line, x * PANGO_SCALE, &index, &trailing);
3026
3027   if (index >= cursor_index && entry->preedit_length)
3028     {
3029       if (index >= cursor_index + entry->preedit_length)
3030         index -= entry->preedit_length;
3031       else
3032         {
3033           index = cursor_index;
3034           trailing = 0;
3035         }
3036     }
3037
3038   pos = g_utf8_pointer_to_offset (text, text + index);
3039   pos += trailing;
3040
3041   return pos;
3042 }
3043
3044 static void
3045 gtk_entry_get_cursor_locations (GtkEntry   *entry,
3046                                 CursorType  type,
3047                                 gint       *strong_x,
3048                                 gint       *weak_x)
3049 {
3050   if (!entry->visible && !entry->invisible_char)
3051     {
3052       if (strong_x)
3053         *strong_x = 0;
3054       
3055       if (weak_x)
3056         *weak_x = 0;
3057     }
3058   else
3059     {
3060       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
3061       const gchar *text = pango_layout_get_text (layout);
3062       PangoRectangle strong_pos, weak_pos;
3063       gint index;
3064   
3065       if (type == CURSOR_STANDARD)
3066         {
3067           index = g_utf8_offset_to_pointer (text, entry->current_pos + entry->preedit_cursor) - text;
3068         }
3069       else /* type == CURSOR_DND */
3070         {
3071           index = g_utf8_offset_to_pointer (text, entry->dnd_position) - text;
3072
3073           if (entry->dnd_position > entry->current_pos)
3074             {
3075               if (entry->visible)
3076                 index += entry->preedit_length;
3077               else
3078                 {
3079                   gint preedit_len_chars = g_utf8_strlen (text, -1) - entry->text_length;
3080                   index += preedit_len_chars * g_unichar_to_utf8 (entry->invisible_char, NULL);
3081                 }
3082             }
3083         }
3084       
3085       pango_layout_get_cursor_pos (layout, index, &strong_pos, &weak_pos);
3086       
3087       if (strong_x)
3088         *strong_x = strong_pos.x / PANGO_SCALE;
3089       
3090       if (weak_x)
3091         *weak_x = weak_pos.x / PANGO_SCALE;
3092     }
3093 }
3094
3095 static void
3096 gtk_entry_adjust_scroll (GtkEntry *entry)
3097 {
3098   GtkEntryPrivate *priv = GTK_ENTRY_GET_PRIVATE (entry);
3099   gint min_offset, max_offset;
3100   gint text_area_width, text_width;
3101   gint strong_x, weak_x;
3102   gint strong_xoffset, weak_xoffset;
3103   gfloat xalign;
3104   PangoLayout *layout;
3105   PangoLayoutLine *line;
3106   PangoRectangle logical_rect;
3107
3108   if (!GTK_WIDGET_REALIZED (entry))
3109     return;
3110   
3111   gdk_drawable_get_size (entry->text_area, &text_area_width, NULL);
3112   text_area_width -= 2 * INNER_BORDER;
3113
3114   layout = gtk_entry_ensure_layout (entry, TRUE);
3115   line = pango_layout_get_lines (layout)->data;
3116
3117   pango_layout_line_get_extents (line, NULL, &logical_rect);
3118
3119   /* Display as much text as we can */
3120
3121   if (entry->resolved_dir == PANGO_DIRECTION_LTR)
3122       xalign = priv->xalign;
3123   else
3124       xalign = 1.0 - priv->xalign;
3125
3126   text_width = PANGO_PIXELS(logical_rect.width);
3127
3128   if (text_width > text_area_width)
3129     {
3130       min_offset = 0;
3131       max_offset = text_width - text_area_width;
3132     }
3133   else
3134     {
3135       min_offset = (text_width - text_area_width) * xalign;
3136       max_offset = min_offset;
3137     }
3138
3139   entry->scroll_offset = CLAMP (entry->scroll_offset, min_offset, max_offset);
3140
3141   /* And make sure cursors are on screen. Note that the cursor is
3142    * actually drawn one pixel into the INNER_BORDER space on
3143    * the right, when the scroll is at the utmost right. This
3144    * looks better to to me than confining the cursor inside the
3145    * border entirely, though it means that the cursor gets one
3146    * pixel closer to the the edge of the widget on the right than
3147    * on the left. This might need changing if one changed
3148    * INNER_BORDER from 2 to 1, as one would do on a
3149    * small-screen-real-estate display.
3150    *
3151    * We always make sure that the strong cursor is on screen, and
3152    * put the weak cursor on screen if possible.
3153    */
3154
3155   gtk_entry_get_cursor_locations (entry, CURSOR_STANDARD, &strong_x, &weak_x);
3156   
3157   strong_xoffset = strong_x - entry->scroll_offset;
3158
3159   if (strong_xoffset < 0)
3160     {
3161       entry->scroll_offset += strong_xoffset;
3162       strong_xoffset = 0;
3163     }
3164   else if (strong_xoffset > text_area_width)
3165     {
3166       entry->scroll_offset += strong_xoffset - text_area_width;
3167       strong_xoffset = text_area_width;
3168     }
3169
3170   weak_xoffset = weak_x - entry->scroll_offset;
3171
3172   if (weak_xoffset < 0 && strong_xoffset - weak_xoffset <= text_area_width)
3173     {
3174       entry->scroll_offset += weak_xoffset;
3175     }
3176   else if (weak_xoffset > text_area_width &&
3177            strong_xoffset - (weak_xoffset - text_area_width) >= 0)
3178     {
3179       entry->scroll_offset += weak_xoffset - text_area_width;
3180     }
3181
3182   g_object_notify (G_OBJECT (entry), "scroll_offset");
3183 }
3184
3185 static gint
3186 gtk_entry_move_visually (GtkEntry *entry,
3187                          gint      start,
3188                          gint      count)
3189 {
3190   gint index;
3191   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3192   const gchar *text;
3193
3194   text = pango_layout_get_text (layout);
3195   
3196   index = g_utf8_offset_to_pointer (text, start) - text;
3197
3198   while (count != 0)
3199     {
3200       int new_index, new_trailing;
3201       gboolean split_cursor;
3202       gboolean strong;
3203
3204       g_object_get (gtk_widget_get_settings (GTK_WIDGET (entry)),
3205                     "gtk-split-cursor", &split_cursor,
3206                     NULL);
3207
3208       if (split_cursor)
3209         strong = TRUE;
3210       else
3211         {
3212           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
3213           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3214
3215           strong = keymap_direction == entry->resolved_dir;
3216         }
3217       
3218       if (count > 0)
3219         {
3220           pango_layout_move_cursor_visually (layout, strong, index, 0, 1, &new_index, &new_trailing);
3221           count--;
3222         }
3223       else
3224         {
3225           pango_layout_move_cursor_visually (layout, strong, index, 0, -1, &new_index, &new_trailing);
3226           count++;
3227         }
3228
3229       if (new_index < 0 || new_index == G_MAXINT)
3230         break;
3231
3232       index = new_index;
3233       
3234       while (new_trailing--)
3235         index = g_utf8_next_char (text + new_index) - text;
3236     }
3237   
3238   return g_utf8_pointer_to_offset (text, text + index);
3239 }
3240
3241 static gint
3242 gtk_entry_move_logically (GtkEntry *entry,
3243                           gint      start,
3244                           gint      count)
3245 {
3246   gint new_pos = start;
3247
3248   /* Prevent any leak of information */
3249   if (!entry->visible)
3250     {
3251       new_pos = CLAMP (start + count, 0, entry->text_length);
3252     }
3253   else if (entry->text)
3254     {
3255       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3256       PangoLogAttr *log_attrs;
3257       gint n_attrs;
3258
3259       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3260
3261       while (count > 0 && new_pos < entry->text_length)
3262         {
3263           do
3264             new_pos++;
3265           while (new_pos < entry->text_length && !log_attrs[new_pos].is_cursor_position);
3266           
3267           count--;
3268         }
3269       while (count < 0 && new_pos > 0)
3270         {
3271           do
3272             new_pos--;
3273           while (new_pos > 0 && !log_attrs[new_pos].is_cursor_position);
3274           
3275           count++;
3276         }
3277       
3278       g_free (log_attrs);
3279     }
3280
3281   return new_pos;
3282 }
3283
3284 static gint
3285 gtk_entry_move_forward_word (GtkEntry *entry,
3286                              gint      start)
3287 {
3288   gint new_pos = start;
3289
3290   /* Prevent any leak of information */
3291   if (!entry->visible)
3292     {
3293       new_pos = entry->text_length;
3294     }
3295   else if (entry->text && (new_pos < entry->text_length))
3296     {
3297       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3298       PangoLogAttr *log_attrs;
3299       gint n_attrs;
3300
3301       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3302       
3303       /* Find the next word end */
3304       new_pos++;
3305       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
3306         new_pos++;
3307
3308       g_free (log_attrs);
3309     }
3310
3311   return new_pos;
3312 }
3313
3314
3315 static gint
3316 gtk_entry_move_backward_word (GtkEntry *entry,
3317                               gint      start)
3318 {
3319   gint new_pos = start;
3320
3321   /* Prevent any leak of information */
3322   if (!entry->visible)
3323     {
3324       new_pos = 0;
3325     }
3326   else if (entry->text && start > 0)
3327     {
3328       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3329       PangoLogAttr *log_attrs;
3330       gint n_attrs;
3331
3332       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3333
3334       new_pos = start - 1;
3335
3336       /* Find the previous word beginning */
3337       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
3338         new_pos--;
3339
3340       g_free (log_attrs);
3341     }
3342
3343   return new_pos;
3344 }
3345
3346 static void
3347 gtk_entry_delete_whitespace (GtkEntry *entry)
3348 {
3349   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3350   PangoLogAttr *log_attrs;
3351   gint n_attrs;
3352   gint start, end;
3353
3354   pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3355
3356   start = end = entry->current_pos;
3357   
3358   while (start > 0 && log_attrs[start-1].is_white)
3359     start--;
3360
3361   while (end < n_attrs && log_attrs[end].is_white)
3362     end++;
3363
3364   g_free (log_attrs);
3365
3366   if (start != end)
3367     gtk_editable_delete_text (GTK_EDITABLE (entry), start, end);
3368 }
3369
3370
3371 static void
3372 gtk_entry_select_word (GtkEntry *entry)
3373 {
3374   gint start_pos = gtk_entry_move_backward_word (entry, entry->current_pos);
3375   gint end_pos = gtk_entry_move_forward_word (entry, entry->current_pos);
3376
3377   gtk_editable_select_region (GTK_EDITABLE (entry), start_pos, end_pos);
3378 }
3379
3380 static void
3381 gtk_entry_select_line (GtkEntry *entry)
3382 {
3383   gtk_editable_select_region (GTK_EDITABLE (entry), 0, -1);
3384 }
3385
3386 /*
3387  * Like gtk_editable_get_chars, but handle not-visible entries
3388  * correctly.
3389  */
3390 static char *    
3391 gtk_entry_get_public_chars (GtkEntry *entry,
3392                             gint      start,
3393                             gint      end)
3394 {
3395   if (end < 0)
3396     end = entry->text_length;
3397   
3398   if (entry->visible)
3399     return gtk_editable_get_chars (GTK_EDITABLE (entry), start, end);
3400   else if (!entry->invisible_char)
3401     return g_strdup ("");
3402   else
3403     {
3404       GString *str = g_string_new (NULL);
3405       append_char (str, entry->invisible_char, end - start);
3406       return g_string_free (str, FALSE);
3407     }
3408 }
3409
3410 static void
3411 paste_received (GtkClipboard *clipboard,
3412                 const gchar  *text,
3413                 gpointer      data)
3414 {
3415   GtkEntry *entry = GTK_ENTRY (data);
3416   GtkEditable *editable = GTK_EDITABLE (entry);
3417       
3418   if (text)
3419     {
3420       gint pos, start, end;
3421       
3422       if (gtk_editable_get_selection_bounds (editable, &start, &end))
3423         gtk_editable_delete_text (editable, start, end);
3424
3425       pos = entry->current_pos;
3426       gtk_editable_insert_text (editable, text, -1, &pos);
3427       gtk_editable_set_position (editable, pos);
3428     }
3429
3430   g_object_unref (entry);
3431 }
3432
3433 static void
3434 gtk_entry_paste (GtkEntry *entry,
3435                  GdkAtom   selection)
3436 {
3437   g_object_ref (entry);
3438   gtk_clipboard_request_text (gtk_widget_get_clipboard (GTK_WIDGET (entry), selection),
3439                               paste_received, entry);
3440 }
3441
3442 static void
3443 primary_get_cb (GtkClipboard     *clipboard,
3444                 GtkSelectionData *selection_data,
3445                 guint             info,
3446                 gpointer          data)
3447 {
3448   GtkEntry *entry = GTK_ENTRY (data);
3449   gint start, end;
3450   
3451   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3452     {
3453       gchar *str = gtk_entry_get_public_chars (entry, start, end);
3454       gtk_selection_data_set_text (selection_data, str, -1);
3455       g_free (str);
3456     }
3457 }
3458
3459 static void
3460 primary_clear_cb (GtkClipboard *clipboard,
3461                   gpointer      data)
3462 {
3463   GtkEntry *entry = GTK_ENTRY (data);
3464
3465   gtk_editable_select_region (GTK_EDITABLE (entry), entry->current_pos, entry->current_pos);
3466 }
3467
3468 static void
3469 gtk_entry_update_primary_selection (GtkEntry *entry)
3470 {
3471   static const GtkTargetEntry targets[] = {
3472     { "UTF8_STRING", 0, 0 },
3473     { "STRING", 0, 0 },
3474     { "TEXT",   0, 0 }, 
3475     { "COMPOUND_TEXT", 0, 0 }
3476   };
3477   
3478   GtkClipboard *clipboard;
3479   gint start, end;
3480
3481   if (!GTK_WIDGET_REALIZED (entry))
3482     return;
3483
3484   clipboard = gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_PRIMARY);
3485   
3486   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3487     {
3488       if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3489                                          primary_get_cb, primary_clear_cb, G_OBJECT (entry)))
3490         primary_clear_cb (clipboard, entry);
3491     }
3492   else
3493     {
3494       if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (entry))
3495         gtk_clipboard_clear (clipboard);
3496     }
3497 }
3498
3499 /* Public API
3500  */
3501
3502 GtkWidget*
3503 gtk_entry_new (void)
3504 {
3505   return g_object_new (GTK_TYPE_ENTRY, NULL);
3506 }
3507
3508 /**
3509  * gtk_entry_new_with_max_length:
3510  * @max: the maximum length of the entry, or 0 for no maximum.
3511  *   (other than the maximum length of entries.) The value passed in will
3512  *   be clamped to the range 0-65536.
3513  *
3514  * Creates a new #GtkEntry widget with the given maximum length.
3515  * 
3516  * Note: the existence of this function is inconsistent
3517  * with the rest of the GTK+ API. The normal setup would
3518  * be to just require the user to make an extra call
3519  * to gtk_entry_set_max_length() instead. It is not
3520  * expected that this function will be removed, but
3521  * it would be better practice not to use it.
3522  * 
3523  * Return value: a new #GtkEntry.
3524  **/
3525 GtkWidget*
3526 gtk_entry_new_with_max_length (gint max)
3527 {
3528   GtkEntry *entry;
3529
3530   max = CLAMP (max, 0, MAX_SIZE);
3531
3532   entry = g_object_new (GTK_TYPE_ENTRY, NULL);
3533   entry->text_max_length = max;
3534
3535   return GTK_WIDGET (entry);
3536 }
3537
3538 void
3539 gtk_entry_set_text (GtkEntry    *entry,
3540                     const gchar *text)
3541 {
3542   gint tmp_pos;
3543   GtkEntryCompletion *completion;
3544
3545   g_return_if_fail (GTK_IS_ENTRY (entry));
3546   g_return_if_fail (text != NULL);
3547
3548   /* Actually setting the text will affect the cursor and selection;
3549    * if the contents don't actually change, this will look odd to the user.
3550    */
3551   if (strcmp (entry->text, text) == 0)
3552     return;
3553
3554   completion = gtk_entry_get_completion (entry);
3555   if (completion)
3556     g_signal_handler_block (entry, completion->priv->changed_id);
3557
3558   gtk_editable_delete_text (GTK_EDITABLE (entry), 0, -1);
3559
3560   tmp_pos = 0;
3561   gtk_editable_insert_text (GTK_EDITABLE (entry), text, strlen (text), &tmp_pos);
3562
3563   if (completion)
3564     g_signal_handler_unblock (entry, completion->priv->changed_id);
3565 }
3566
3567 void
3568 gtk_entry_append_text (GtkEntry *entry,
3569                        const gchar *text)
3570 {
3571   gint tmp_pos;
3572
3573   g_return_if_fail (GTK_IS_ENTRY (entry));
3574   g_return_if_fail (text != NULL);
3575
3576   tmp_pos = entry->text_length;
3577   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3578 }
3579
3580 void
3581 gtk_entry_prepend_text (GtkEntry *entry,
3582                         const gchar *text)
3583 {
3584   gint tmp_pos;
3585
3586   g_return_if_fail (GTK_IS_ENTRY (entry));
3587   g_return_if_fail (text != NULL);
3588
3589   tmp_pos = 0;
3590   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3591 }
3592
3593 void
3594 gtk_entry_set_position (GtkEntry *entry,
3595                         gint       position)
3596 {
3597   g_return_if_fail (GTK_IS_ENTRY (entry));
3598
3599   gtk_editable_set_position (GTK_EDITABLE (entry), position);
3600 }
3601
3602 void
3603 gtk_entry_set_visibility (GtkEntry *entry,
3604                           gboolean visible)
3605 {
3606   g_return_if_fail (GTK_IS_ENTRY (entry));
3607
3608   entry->visible = visible ? TRUE : FALSE;
3609   g_object_notify (G_OBJECT (entry), "visibility");
3610   gtk_entry_recompute (entry);
3611 }
3612
3613 /**
3614  * gtk_entry_get_visibility:
3615  * @entry: a #GtkEntry
3616  *
3617  * Retrieves whether the text in @entry is visible. See
3618  * gtk_entry_set_visibility().
3619  *
3620  * Return value: %TRUE if the text is currently visible
3621  **/
3622 gboolean
3623 gtk_entry_get_visibility (GtkEntry *entry)
3624 {
3625   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3626
3627   return entry->visible;
3628 }
3629
3630 /**
3631  * gtk_entry_set_invisible_char:
3632  * @entry: a #GtkEntry
3633  * @ch: a Unicode character
3634  * 
3635  * Sets the character to use in place of the actual text when
3636  * gtk_entry_set_visibility() has been called to set text visibility
3637  * to %FALSE. i.e. this is the character used in "password mode" to
3638  * show the user how many characters have been typed. The default
3639  * invisible char is an asterisk ('*').  If you set the invisible char
3640  * to 0, then the user will get no feedback at all; there will be
3641  * no text on the screen as they type.
3642  * 
3643  **/
3644 void
3645 gtk_entry_set_invisible_char (GtkEntry *entry,
3646                               gunichar  ch)
3647 {
3648   g_return_if_fail (GTK_IS_ENTRY (entry));
3649
3650   if (ch == entry->invisible_char)
3651     return;
3652
3653   entry->invisible_char = ch;
3654   g_object_notify (G_OBJECT (entry), "invisible_char");
3655   gtk_entry_recompute (entry);  
3656 }
3657
3658 /**
3659  * gtk_entry_get_invisible_char:
3660  * @entry: a #GtkEntry
3661  *
3662  * Retrieves the character displayed in place of the real characters
3663  * for entries with visisbility set to false. See gtk_entry_set_invisible_char().
3664  *
3665  * Return value: the current invisible char, or 0, if the entry does not
3666  *               show invisible text at all. 
3667  **/
3668 gunichar
3669 gtk_entry_get_invisible_char (GtkEntry *entry)
3670 {
3671   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3672
3673   return entry->invisible_char;
3674 }
3675
3676 void
3677 gtk_entry_set_editable (GtkEntry *entry,
3678                         gboolean  editable)
3679 {
3680   g_return_if_fail (GTK_IS_ENTRY (entry));
3681
3682   gtk_editable_set_editable (GTK_EDITABLE (entry), editable);
3683 }
3684
3685 /**
3686  * gtk_entry_get_text:
3687  * @entry: a #GtkEntry
3688  *
3689  * Retrieves the contents of the entry widget.
3690  * See also gtk_editable_get_chars().
3691  *
3692  * Return value: a pointer to the contents of the widget as a
3693  *      string.  This string points to internally allocated
3694  *      storage in the widget and must not be freed, modified or
3695  *      stored.
3696  **/
3697 G_CONST_RETURN gchar*
3698 gtk_entry_get_text (GtkEntry *entry)
3699 {
3700   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
3701
3702   return entry->text;
3703 }
3704
3705 void       
3706 gtk_entry_select_region  (GtkEntry       *entry,
3707                           gint            start,
3708                           gint            end)
3709 {
3710   gtk_editable_select_region (GTK_EDITABLE (entry), start, end);
3711 }
3712
3713 /**
3714  * gtk_entry_set_max_length:
3715  * @entry: a #GtkEntry.
3716  * @max: the maximum length of the entry, or 0 for no maximum.
3717  *   (other than the maximum length of entries.) The value passed in will
3718  *   be clamped to the range 0-65536.
3719  * 
3720  * Sets the maximum allowed length of the contents of the widget. If
3721  * the current contents are longer than the given length, then they
3722  * will be truncated to fit.
3723  **/
3724 void
3725 gtk_entry_set_max_length (GtkEntry     *entry,
3726                           gint          max)
3727 {
3728   g_return_if_fail (GTK_IS_ENTRY (entry));
3729
3730   max = CLAMP (max, 0, MAX_SIZE);
3731
3732   if (max > 0 && entry->text_length > max)
3733     gtk_editable_delete_text (GTK_EDITABLE (entry), max, -1);
3734   
3735   entry->text_max_length = max;
3736   g_object_notify (G_OBJECT (entry), "max_length");
3737 }
3738
3739 /**
3740  * gtk_entry_get_max_length:
3741  * @entry: a #GtkEntry
3742  *
3743  * Retrieves the maximum allowed length of the text in
3744  * @entry. See gtk_entry_set_max_length().
3745  *
3746  * Return value: the maximum allowed number of characters
3747  *               in #GtkEntry, or 0 if there is no maximum.
3748  **/
3749 gint
3750 gtk_entry_get_max_length (GtkEntry *entry)
3751 {
3752   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3753
3754   return entry->text_max_length;
3755 }
3756
3757 /**
3758  * gtk_entry_set_activates_default:
3759  * @entry: a #GtkEntry
3760  * @setting: %TRUE to activate window's default widget on Enter keypress
3761  *
3762  * If @setting is %TRUE, pressing Enter in the @entry will activate the default
3763  * widget for the window containing the entry. This usually means that
3764  * the dialog box containing the entry will be closed, since the default
3765  * widget is usually one of the dialog buttons.
3766  *
3767  * (For experts: if @setting is %TRUE, the entry calls
3768  * gtk_window_activate_default() on the window containing the entry, in
3769  * the default handler for the "activate" signal.)
3770  * 
3771  **/
3772 void
3773 gtk_entry_set_activates_default (GtkEntry *entry,
3774                                  gboolean  setting)
3775 {
3776   g_return_if_fail (GTK_IS_ENTRY (entry));
3777   setting = setting != FALSE;
3778
3779   if (setting != entry->activates_default)
3780     {
3781       entry->activates_default = setting;
3782       g_object_notify (G_OBJECT (entry), "activates_default");
3783     }
3784 }
3785
3786 /**
3787  * gtk_entry_get_activates_default:
3788  * @entry: a #GtkEntry
3789  * 
3790  * Retrieves the value set by gtk_entry_set_activates_default().
3791  * 
3792  * Return value: %TRUE if the entry will activate the default widget
3793  **/
3794 gboolean
3795 gtk_entry_get_activates_default (GtkEntry *entry)
3796 {
3797   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3798
3799   return entry->activates_default;
3800 }
3801
3802 /**
3803  * gtk_entry_set_width_chars:
3804  * @entry: a #GtkEntry
3805  * @n_chars: width in chars
3806  *
3807  * Changes the size request of the entry to be about the right size
3808  * for @n_chars characters. Note that it changes the size
3809  * <emphasis>request</emphasis>, the size can still be affected by
3810  * how you pack the widget into containers. If @n_chars is -1, the
3811  * size reverts to the default entry size.
3812  * 
3813  **/
3814 void
3815 gtk_entry_set_width_chars (GtkEntry *entry,
3816                            gint      n_chars)
3817 {
3818   g_return_if_fail (GTK_IS_ENTRY (entry));
3819
3820   if (entry->width_chars != n_chars)
3821     {
3822       entry->width_chars = n_chars;
3823       g_object_notify (G_OBJECT (entry), "width_chars");
3824       gtk_widget_queue_resize (GTK_WIDGET (entry));
3825     }
3826 }
3827
3828 /**
3829  * gtk_entry_get_width_chars:
3830  * @entry: a #GtkEntry
3831  * 
3832  * Gets the value set by gtk_entry_set_width_chars().
3833  * 
3834  * Return value: number of chars to request space for, or negative if unset
3835  **/
3836 gint
3837 gtk_entry_get_width_chars (GtkEntry *entry)
3838 {
3839   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3840
3841   return entry->width_chars;
3842 }
3843
3844 /**
3845  * gtk_entry_set_has_frame:
3846  * @entry: a #GtkEntry
3847  * @setting: new value
3848  * 
3849  * Sets whether the entry has a beveled frame around it.
3850  **/
3851 void
3852 gtk_entry_set_has_frame (GtkEntry *entry,
3853                          gboolean  setting)
3854 {
3855   g_return_if_fail (GTK_IS_ENTRY (entry));
3856
3857   setting = (setting != FALSE);
3858
3859   if (entry->has_frame == setting)
3860     return;
3861
3862   gtk_widget_queue_resize (GTK_WIDGET (entry));
3863   entry->has_frame = setting;
3864   g_object_notify (G_OBJECT (entry), "has_frame");
3865 }
3866
3867 /**
3868  * gtk_entry_get_has_frame:
3869  * @entry: a #GtkEntry
3870  * 
3871  * Gets the value set by gtk_entry_set_has_frame().
3872  * 
3873  * Return value: whether the entry has a beveled frame
3874  **/
3875 gboolean
3876 gtk_entry_get_has_frame (GtkEntry *entry)
3877 {
3878   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3879
3880   return entry->has_frame;
3881 }
3882
3883
3884 /**
3885  * gtk_entry_get_layout:
3886  * @entry: a #GtkEntry
3887  * 
3888  * Gets the #PangoLayout used to display the entry.
3889  * The layout is useful to e.g. convert text positions to
3890  * pixel positions, in combination with gtk_entry_get_layout_offsets().
3891  * The returned layout is owned by the entry so need not be
3892  * freed by the caller.
3893  *
3894  * Keep in mind that the layout text may contain a preedit string, so
3895  * gtk_entry_layout_index_to_text_index() and
3896  * gtk_entry_text_index_to_layout_index() are needed to convert byte
3897  * indices in the layout to byte indices in the entry contents.
3898  * 
3899  * Return value: the #PangoLayout for this entry
3900  **/
3901 PangoLayout*
3902 gtk_entry_get_layout (GtkEntry *entry)
3903 {
3904   PangoLayout *layout;
3905   
3906   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
3907
3908   layout = gtk_entry_ensure_layout (entry, TRUE);
3909
3910   return layout;
3911 }
3912
3913
3914 /**
3915  * gtk_entry_layout_index_to_text_index:
3916  * @entry: a #GtkEntry
3917  * @layout_index: byte index into the entry layout text
3918  * 
3919  * Converts from a position in the entry contents (returned
3920  * by gtk_entry_get_text()) to a position in the
3921  * entry's #PangoLayout (returned by gtk_entry_get_layout(),
3922  * with text retrieved via pango_layout_get_text()).
3923  * 
3924  * Return value: byte index into the entry contents
3925  **/
3926 gint
3927 gtk_entry_layout_index_to_text_index (GtkEntry *entry,
3928                                       gint      layout_index)
3929 {
3930   PangoLayout *layout;
3931   const gchar *text;
3932   gint cursor_index;
3933   
3934   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3935
3936   layout = gtk_entry_ensure_layout (entry, TRUE);
3937   text = pango_layout_get_text (layout);
3938   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3939   
3940   if (layout_index >= cursor_index && entry->preedit_length)
3941     {
3942       if (layout_index >= cursor_index + entry->preedit_length)
3943         layout_index -= entry->preedit_length;
3944       else
3945         layout_index = cursor_index;
3946     }
3947
3948   return layout_index;
3949 }
3950
3951 /**
3952  * gtk_entry_text_index_to_layout_index:
3953  * @entry: a #GtkEntry
3954  * @text_index: byte index into the entry contents
3955  * 
3956  * Converts from a position in the entry's #PangoLayout(returned by
3957  * gtk_entry_get_layout()) to a position in the entry contents
3958  * (returned by gtk_entry_get_text()).
3959  * 
3960  * Return value: byte index into the entry layout text
3961  **/
3962 gint
3963 gtk_entry_text_index_to_layout_index (GtkEntry *entry,
3964                                       gint      text_index)
3965 {
3966   PangoLayout *layout;
3967   const gchar *text;
3968   gint cursor_index;
3969   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3970
3971   layout = gtk_entry_ensure_layout (entry, TRUE);
3972   text = pango_layout_get_text (layout);
3973   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3974   
3975   if (text_index > cursor_index)
3976     text_index += entry->preedit_length;
3977
3978   return text_index;
3979 }
3980
3981 /**
3982  * gtk_entry_get_layout_offsets:
3983  * @entry: a #GtkEntry
3984  * @x: location to store X offset of layout, or %NULL
3985  * @y: location to store Y offset of layout, or %NULL
3986  *
3987  *
3988  * Obtains the position of the #PangoLayout used to render text
3989  * in the entry, in widget coordinates. Useful if you want to line
3990  * up the text in an entry with some other text, e.g. when using the
3991  * entry to implement editable cells in a sheet widget.
3992  *
3993  * Also useful to convert mouse events into coordinates inside the
3994  * #PangoLayout, e.g. to take some action if some part of the entry text
3995  * is clicked.
3996  * 
3997  * Note that as the user scrolls around in the entry the offsets will
3998  * change; you'll need to connect to the "notify::scroll_offset"
3999  * signal to track this. Remember when using the #PangoLayout
4000  * functions you need to convert to and from pixels using
4001  * PANGO_PIXELS() or #PANGO_SCALE.
4002  *
4003  * Keep in mind that the layout text may contain a preedit string, so
4004  * gtk_entry_layout_index_to_text_index() and
4005  * gtk_entry_text_index_to_layout_index() are needed to convert byte
4006  * indices in the layout to byte indices in the entry contents.
4007  * 
4008  **/
4009 void
4010 gtk_entry_get_layout_offsets (GtkEntry *entry,
4011                               gint     *x,
4012                               gint     *y)
4013 {
4014   gint text_area_x, text_area_y;
4015   
4016   g_return_if_fail (GTK_IS_ENTRY (entry));
4017
4018   /* this gets coords relative to text area */
4019   get_layout_position (entry, x, y);
4020
4021   /* convert to widget coords */
4022   get_text_area_size (entry, &text_area_x, &text_area_y, NULL, NULL);
4023   
4024   if (x)
4025     *x += text_area_x;
4026
4027   if (y)
4028     *y += text_area_y;
4029 }
4030
4031
4032 /**
4033  * gtk_entry_set_alignment:
4034  * @entry: a #GtkEntry
4035  * @xalign: The horizontal alignment, from 0 (left) to 1 (right).
4036  *          Reversed for RTL layouts
4037  * 
4038  * Sets the alignment for the contents of the entry. This controls
4039  * the horizontal positioning of the contents when the displayed
4040  * text is shorter than the width of the entry.
4041  **/
4042 void
4043 gtk_entry_set_alignment (GtkEntry *entry, gfloat xalign)
4044 {
4045   GtkEntryPrivate *priv;
4046   
4047   g_return_if_fail (GTK_IS_ENTRY (entry));
4048
4049   priv = GTK_ENTRY_GET_PRIVATE (entry);
4050
4051   if (xalign < 0.0)
4052     xalign = 0.0;
4053   else if (xalign > 1.0)
4054     xalign = 1.0;
4055
4056   if (xalign != priv->xalign)
4057     {
4058       priv->xalign = xalign;
4059
4060       gtk_entry_recompute (entry);
4061
4062       g_object_notify (G_OBJECT (entry), "xalign");
4063     }
4064 }
4065
4066 /**
4067  * gtk_entry_get_alignment:
4068  * @entry: a #GtkEntry
4069  * 
4070  * Gets the value set by gtk_entry_set_alignment().
4071  * 
4072  * Return value: the alignment
4073  **/
4074 gfloat
4075 gtk_entry_get_alignment (GtkEntry *entry)
4076 {
4077   GtkEntryPrivate *priv;
4078   
4079   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0.0);
4080
4081   priv = GTK_ENTRY_GET_PRIVATE (entry);
4082
4083   return priv->xalign;
4084 }
4085
4086 /* Quick hack of a popup menu
4087  */
4088 static void
4089 activate_cb (GtkWidget *menuitem,
4090              GtkEntry  *entry)
4091 {
4092   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
4093   g_signal_emit_by_name (entry, signal);
4094 }
4095
4096
4097 static gboolean
4098 gtk_entry_mnemonic_activate (GtkWidget *widget,
4099                              gboolean   group_cycling)
4100 {
4101   gtk_widget_grab_focus (widget);
4102   return TRUE;
4103 }
4104
4105 static void
4106 append_action_signal (GtkEntry     *entry,
4107                       GtkWidget    *menu,
4108                       const gchar  *stock_id,
4109                       const gchar  *signal,
4110                       gboolean      sensitive)
4111 {
4112   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
4113
4114   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
4115   g_signal_connect (menuitem, "activate",
4116                     G_CALLBACK (activate_cb), entry);
4117
4118   gtk_widget_set_sensitive (menuitem, sensitive);
4119   
4120   gtk_widget_show (menuitem);
4121   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
4122 }
4123         
4124 static void
4125 popup_menu_detach (GtkWidget *attach_widget,
4126                    GtkMenu   *menu)
4127 {
4128   GTK_ENTRY (attach_widget)->popup_menu = NULL;
4129 }
4130
4131 static void
4132 popup_position_func (GtkMenu   *menu,
4133                      gint      *x,
4134                      gint      *y,
4135                      gboolean  *push_in,
4136                      gpointer   user_data)
4137 {
4138   GtkEntry *entry = GTK_ENTRY (user_data);
4139   GtkWidget *widget = GTK_WIDGET (entry);
4140   GdkScreen *screen = gtk_widget_get_screen (widget);
4141   GtkRequisition req;
4142   
4143   g_return_if_fail (GTK_WIDGET_REALIZED (entry));
4144
4145   gdk_window_get_origin (widget->window, x, y);      
4146
4147   gtk_widget_size_request (entry->popup_menu, &req);
4148   
4149   *x += widget->allocation.width / 2;
4150   *y += widget->allocation.height;
4151
4152   *x = CLAMP (*x, 0, MAX (0, gdk_screen_get_width (screen) - req.width));
4153   *y = CLAMP (*y, 0, MAX (0, gdk_screen_get_height (screen) - req.height));
4154 }
4155
4156
4157 static void
4158 unichar_chosen_func (const char *text,
4159                      gpointer    data)
4160 {
4161   GtkEntry *entry = GTK_ENTRY (data);
4162
4163   if (entry->editable)
4164     gtk_entry_enter_text (entry, text);
4165 }
4166
4167 typedef struct
4168 {
4169   GtkEntry *entry;
4170   gint button;
4171   guint time;
4172 } PopupInfo;
4173
4174 static void
4175 popup_targets_received (GtkClipboard     *clipboard,
4176                         GtkSelectionData *data,
4177                         gpointer          user_data)
4178 {
4179   PopupInfo *info = user_data;
4180   GtkEntry *entry = info->entry;
4181   
4182   if (GTK_WIDGET_REALIZED (entry))
4183     {
4184       gboolean clipboard_contains_text = gtk_selection_data_targets_include_text (data);
4185       GtkWidget *menuitem;
4186       GtkWidget *submenu;
4187       
4188       if (entry->popup_menu)
4189         gtk_widget_destroy (entry->popup_menu);
4190       
4191       entry->popup_menu = gtk_menu_new ();
4192       
4193       gtk_menu_attach_to_widget (GTK_MENU (entry->popup_menu),
4194                                  GTK_WIDGET (entry),
4195                                  popup_menu_detach);
4196       
4197       append_action_signal (entry, entry->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
4198                             entry->editable && entry->current_pos != entry->selection_bound);
4199       append_action_signal (entry, entry->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
4200                             entry->current_pos != entry->selection_bound);
4201       append_action_signal (entry, entry->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
4202                             entry->editable && clipboard_contains_text);
4203       
4204       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
4205       gtk_widget_set_sensitive (menuitem, entry->current_pos != entry->selection_bound);
4206       g_signal_connect_swapped (menuitem, "activate",
4207                                 G_CALLBACK (gtk_entry_delete_cb), entry);
4208       gtk_widget_show (menuitem);
4209       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4210
4211       menuitem = gtk_separator_menu_item_new ();
4212       gtk_widget_show (menuitem);
4213       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4214       
4215       menuitem = gtk_menu_item_new_with_mnemonic (_("Select _All"));
4216       g_signal_connect_swapped (menuitem, "activate",
4217                                 G_CALLBACK (gtk_entry_select_all), entry);
4218       gtk_widget_show (menuitem);
4219       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4220       
4221       menuitem = gtk_separator_menu_item_new ();
4222       gtk_widget_show (menuitem);
4223       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4224       
4225       menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
4226       gtk_widget_show (menuitem);
4227       submenu = gtk_menu_new ();
4228       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4229       
4230       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4231       
4232       gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (entry->im_context),
4233                                             GTK_MENU_SHELL (submenu));
4234       
4235       menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
4236       gtk_widget_show (menuitem);
4237       
4238       submenu = gtk_menu_new ();
4239       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4240       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);      
4241
4242       _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
4243                                                     unichar_chosen_func,
4244                                                     entry);
4245       if (!entry->editable)
4246         gtk_widget_set_sensitive (menuitem, FALSE);
4247       
4248       g_signal_emit (entry,
4249                      signals[POPULATE_POPUP],
4250                      0,
4251                      entry->popup_menu);
4252   
4253
4254       if (info->button)
4255         gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4256                         NULL, NULL,
4257                         info->button, info->time);
4258       else
4259         {
4260           gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4261                           popup_position_func, entry,
4262                           info->button, info->time);
4263           gtk_menu_shell_select_first (GTK_MENU_SHELL (entry->popup_menu), FALSE);
4264         }
4265     }
4266
4267   g_object_unref (entry);
4268   g_free (info);
4269 }
4270                         
4271 static void
4272 gtk_entry_do_popup (GtkEntry       *entry,
4273                     GdkEventButton *event)
4274 {
4275   PopupInfo *info = g_new (PopupInfo, 1);
4276
4277   /* In order to know what entries we should make sensitive, we
4278    * ask for the current targets of the clipboard, and when
4279    * we get them, then we actually pop up the menu.
4280    */
4281   info->entry = g_object_ref (entry);
4282   
4283   if (event)
4284     {
4285       info->button = event->button;
4286       info->time = event->time;
4287     }
4288   else
4289     {
4290       info->button = 0;
4291       info->time = gtk_get_current_event_time ();
4292     }
4293
4294   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_CLIPBOARD),
4295                                   gdk_atom_intern ("TARGETS", FALSE),
4296                                   popup_targets_received,
4297                                   info);
4298 }
4299
4300 static gboolean
4301 gtk_entry_popup_menu (GtkWidget *widget)
4302 {
4303   gtk_entry_do_popup (GTK_ENTRY (widget), NULL);
4304   return TRUE;
4305 }
4306
4307 static void
4308 gtk_entry_drag_leave (GtkWidget        *widget,
4309                       GdkDragContext   *context,
4310                       guint             time)
4311 {
4312   GtkEntry *entry = GTK_ENTRY (widget);
4313
4314   entry->dnd_position = -1;
4315   gtk_widget_queue_draw (widget);
4316 }
4317
4318 static gboolean
4319 gtk_entry_drag_drop  (GtkWidget        *widget,
4320                       GdkDragContext   *context,
4321                       gint              x,
4322                       gint              y,
4323                       guint             time)
4324 {
4325   GtkEntry *entry = GTK_ENTRY (widget);
4326   GdkAtom target = GDK_NONE;
4327   
4328   if (entry->editable)
4329     target = gtk_drag_dest_find_target (widget, context, NULL);
4330
4331   if (target != GDK_NONE)
4332     gtk_drag_get_data (widget, context, target, time);
4333   else
4334     gtk_drag_finish (context, FALSE, FALSE, time);
4335   
4336   return TRUE;
4337 }
4338
4339 static gboolean
4340 gtk_entry_drag_motion (GtkWidget        *widget,
4341                        GdkDragContext   *context,
4342                        gint              x,
4343                        gint              y,
4344                        guint             time)
4345 {
4346   GtkEntry *entry = GTK_ENTRY (widget);
4347   GtkWidget *source_widget;
4348   GdkDragAction suggested_action;
4349   gint new_position, old_position;
4350   gint sel1, sel2;
4351   
4352   x -= widget->style->xthickness;
4353   y -= widget->style->ythickness;
4354   
4355   old_position = entry->dnd_position;
4356   new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4357
4358   if (entry->editable &&
4359       gtk_drag_dest_find_target (widget, context, NULL) != GDK_NONE)
4360     {
4361       source_widget = gtk_drag_get_source_widget (context);
4362       suggested_action = context->suggested_action;
4363
4364       if (!gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &sel1, &sel2) ||
4365           new_position < sel1 || new_position > sel2)
4366         {
4367           if (source_widget == widget)
4368             {
4369               /* Default to MOVE, unless the user has
4370                * pressed ctrl or alt to affect available actions
4371                */
4372               if ((context->actions & GDK_ACTION_MOVE) != 0)
4373                 suggested_action = GDK_ACTION_MOVE;
4374             }
4375               
4376           entry->dnd_position = new_position;
4377         }
4378       else
4379         {
4380           if (source_widget == widget)
4381             suggested_action = 0;       /* Can't drop in selection where drag started */
4382           
4383           entry->dnd_position = -1;
4384         }
4385     }
4386   else
4387     {
4388       /* Entry not editable, or no text */
4389       suggested_action = 0;
4390       entry->dnd_position = -1;
4391     }
4392   
4393   gdk_drag_status (context, suggested_action, time);
4394   
4395   if (entry->dnd_position != old_position)
4396     gtk_widget_queue_draw (widget);
4397
4398   return TRUE;
4399 }
4400
4401 static void
4402 gtk_entry_drag_data_received (GtkWidget        *widget,
4403                               GdkDragContext   *context,
4404                               gint              x,
4405                               gint              y,
4406                               GtkSelectionData *selection_data,
4407                               guint             info,
4408                               guint             time)
4409 {
4410   GtkEntry *entry = GTK_ENTRY (widget);
4411   GtkEditable *editable = GTK_EDITABLE (widget);
4412   gchar *str;
4413
4414   str = gtk_selection_data_get_text (selection_data);
4415
4416   if (str && entry->editable)
4417     {
4418       gint new_position;
4419       gint sel1, sel2;
4420
4421       new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4422
4423       if (!gtk_editable_get_selection_bounds (editable, &sel1, &sel2) ||
4424           new_position < sel1 || new_position > sel2)
4425         {
4426           gtk_editable_insert_text (editable, str, -1, &new_position);
4427         }
4428       else
4429         {
4430           /* Replacing selection */
4431           gtk_editable_delete_text (editable, sel1, sel2);
4432           gtk_editable_insert_text (editable, str, -1, &sel1);
4433         }
4434       
4435       g_free (str);
4436       gtk_drag_finish (context, TRUE, context->action == GDK_ACTION_MOVE, time);
4437     }
4438   else
4439     {
4440       /* Drag and drop didn't happen! */
4441       gtk_drag_finish (context, FALSE, FALSE, time);
4442     }
4443 }
4444
4445 static void
4446 gtk_entry_drag_data_get (GtkWidget        *widget,
4447                          GdkDragContext   *context,
4448                          GtkSelectionData *selection_data,
4449                          guint             info,
4450                          guint             time)
4451 {
4452   gint sel_start, sel_end;
4453
4454   GtkEditable *editable = GTK_EDITABLE (widget);
4455   
4456   if (gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4457     {
4458       gchar *str = gtk_entry_get_public_chars (GTK_ENTRY (widget), sel_start, sel_end);
4459
4460       gtk_selection_data_set_text (selection_data, str, -1);
4461       
4462       g_free (str);
4463     }
4464
4465 }
4466
4467 static void
4468 gtk_entry_drag_data_delete (GtkWidget      *widget,
4469                             GdkDragContext *context)
4470 {
4471   gint sel_start, sel_end;
4472
4473   GtkEditable *editable = GTK_EDITABLE (widget);
4474   
4475   if (GTK_ENTRY (widget)->editable &&
4476       gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4477     gtk_editable_delete_text (editable, sel_start, sel_end);
4478 }
4479
4480 /* We display the cursor when
4481  *
4482  *  - the selection is empty, AND
4483  *  - the widget has focus
4484  */
4485
4486 #define CURSOR_ON_MULTIPLIER 0.66
4487 #define CURSOR_OFF_MULTIPLIER 0.34
4488 #define CURSOR_PEND_MULTIPLIER 1.0
4489
4490 static gboolean
4491 cursor_blinks (GtkEntry *entry)
4492 {
4493   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4494   gboolean blink;
4495
4496   if (GTK_WIDGET_HAS_FOCUS (entry) &&
4497       entry->selection_bound == entry->current_pos)
4498     {
4499       g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
4500       return blink;
4501     }
4502   else
4503     return FALSE;
4504 }
4505
4506 static gint
4507 get_cursor_time (GtkEntry *entry)
4508 {
4509   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4510   gint time;
4511
4512   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
4513
4514   return time;
4515 }
4516
4517 static void
4518 show_cursor (GtkEntry *entry)
4519 {
4520   if (!entry->cursor_visible)
4521     {
4522       entry->cursor_visible = TRUE;
4523
4524       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4525         gtk_widget_queue_draw (GTK_WIDGET (entry));
4526     }
4527 }
4528
4529 static void
4530 hide_cursor (GtkEntry *entry)
4531 {
4532   if (entry->cursor_visible)
4533     {
4534       entry->cursor_visible = FALSE;
4535
4536       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4537         gtk_widget_queue_draw (GTK_WIDGET (entry));
4538     }
4539 }
4540
4541 /*
4542  * Blink!
4543  */
4544 static gint
4545 blink_cb (gpointer data)
4546 {
4547   GtkEntry *entry;
4548
4549   GDK_THREADS_ENTER ();
4550
4551   entry = GTK_ENTRY (data);
4552
4553   if (!GTK_WIDGET_HAS_FOCUS (entry))
4554     {
4555       g_warning ("GtkEntry - did not receive focus-out-event. If you\n"
4556                  "connect a handler to this signal, it must return\n"
4557                  "FALSE so the entry gets the event as well");
4558     }
4559   
4560   g_assert (GTK_WIDGET_HAS_FOCUS (entry));
4561   g_assert (entry->selection_bound == entry->current_pos);
4562
4563   if (entry->cursor_visible)
4564     {
4565       hide_cursor (entry);
4566       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_OFF_MULTIPLIER,
4567                                             blink_cb,
4568                                             entry);
4569     }
4570   else
4571     {
4572       show_cursor (entry);
4573       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4574                                             blink_cb,
4575                                             entry);
4576     }
4577
4578   GDK_THREADS_LEAVE ();
4579
4580   /* Remove ourselves */
4581   return FALSE;
4582 }
4583
4584 static void
4585 gtk_entry_check_cursor_blink (GtkEntry *entry)
4586 {
4587   if (cursor_blinks (entry))
4588     {
4589       if (!entry->blink_timeout)
4590         {
4591           entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4592                                                 blink_cb,
4593                                                 entry);
4594           show_cursor (entry);
4595         }
4596     }
4597   else
4598     {
4599       if (entry->blink_timeout)  
4600         { 
4601           g_source_remove (entry->blink_timeout);
4602           entry->blink_timeout = 0;
4603         }
4604       
4605       entry->cursor_visible = TRUE;
4606     }
4607   
4608 }
4609
4610 static void
4611 gtk_entry_pend_cursor_blink (GtkEntry *entry)
4612 {
4613   if (cursor_blinks (entry))
4614     {
4615       if (entry->blink_timeout != 0)
4616         g_source_remove (entry->blink_timeout);
4617       
4618       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_PEND_MULTIPLIER,
4619                                             blink_cb,
4620                                             entry);
4621       show_cursor (entry);
4622     }
4623 }
4624
4625 /* completion */
4626 static gint
4627 gtk_entry_completion_timeout (gpointer data)
4628 {
4629   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (data);
4630
4631   GDK_THREADS_ENTER ();
4632
4633   completion->priv->completion_timeout = 0;
4634
4635   if (strlen (gtk_entry_get_text (GTK_ENTRY (completion->priv->entry)))
4636       >= completion->priv->minimum_key_length)
4637     {
4638       gint matches;
4639       gint actions;
4640       GtkTreeSelection *s;
4641
4642       gtk_entry_completion_complete (completion);
4643       matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4644
4645       gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4646
4647       s = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view));
4648
4649       gtk_tree_selection_unselect_all (s);
4650
4651       actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
4652
4653       if ((matches > 0 || actions > 0)
4654           && ! GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4655         _gtk_entry_completion_popup (completion);
4656       else if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4657         _gtk_entry_completion_resize_popup (completion);
4658     }
4659   else if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4660     _gtk_entry_completion_popdown (completion);
4661
4662   GDK_THREADS_LEAVE ();
4663
4664   return FALSE;
4665 }
4666
4667 static inline gboolean
4668 keyval_is_cursor_move (guint keyval)
4669 {
4670   if (keyval == GDK_Up || keyval == GDK_KP_Up)
4671     return TRUE;
4672
4673   if (keyval == GDK_Down || keyval == GDK_KP_Down)
4674     return TRUE;
4675
4676   if (keyval == GDK_Page_Up)
4677     return TRUE;
4678
4679   if (keyval == GDK_Page_Down)
4680     return TRUE;
4681
4682   return FALSE;
4683 }
4684
4685 static gboolean
4686 gtk_entry_completion_key_press (GtkWidget   *widget,
4687                                 GdkEventKey *event,
4688                                 gpointer     user_data)
4689 {
4690   gint matches, actions = 0;
4691   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
4692
4693   if (!GTK_WIDGET_MAPPED (completion->priv->popup_window))
4694     return FALSE;
4695
4696   matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4697
4698   if (completion->priv->actions)
4699     actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
4700
4701   if (keyval_is_cursor_move (event->keyval))
4702     {
4703       GtkTreePath *path = NULL;
4704       
4705       if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
4706         {
4707           if (completion->priv->current_selected < 0)
4708             completion->priv->current_selected = matches + actions - 1;
4709           else
4710             completion->priv->current_selected--;
4711         }
4712       else if (event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
4713         {
4714           if (completion->priv->current_selected < matches + actions - 1)
4715             completion->priv->current_selected++;
4716           else
4717             completion->priv->current_selected = -1;
4718         }
4719       else if (event->keyval == GDK_Page_Up)
4720         {
4721           if (completion->priv->current_selected < 0)
4722             completion->priv->current_selected = matches + actions - 1;
4723           else if (completion->priv->current_selected == 0)
4724             completion->priv->current_selected = -1;
4725           else if (completion->priv->current_selected < matches) 
4726             {
4727               completion->priv->current_selected -= 14;
4728               if (completion->priv->current_selected < 0)
4729                 completion->priv->current_selected = 0;
4730             }
4731           else 
4732             {
4733               completion->priv->current_selected -= 14;
4734               if (completion->priv->current_selected < matches - 1)
4735                 completion->priv->current_selected = matches - 1;
4736             }
4737         }
4738       else if (event->keyval == GDK_Page_Down)
4739         {
4740           if (completion->priv->current_selected < 0)
4741             completion->priv->current_selected = 0;
4742           else if (completion->priv->current_selected < matches - 1)
4743             {
4744               completion->priv->current_selected += 14;
4745               if (completion->priv->current_selected > matches - 1)
4746                 completion->priv->current_selected = matches - 1;
4747             }
4748           else if (completion->priv->current_selected == matches + actions - 1)
4749             {
4750               completion->priv->current_selected = -1;
4751             }
4752           else
4753             {
4754               completion->priv->current_selected += 14;
4755               if (completion->priv->current_selected > matches + actions - 1)
4756                 completion->priv->current_selected = matches + actions - 1;
4757             }
4758         }
4759
4760       if (completion->priv->current_selected < 0)
4761         {
4762           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4763           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
4764         }
4765       else if (completion->priv->current_selected < matches)
4766         {
4767           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
4768
4769           path = gtk_tree_path_new_from_indices (completion->priv->current_selected, -1);
4770           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->tree_view),
4771                                     path, NULL, FALSE);
4772         }
4773       else if (completion->priv->current_selected - matches >= 0)
4774         {
4775           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4776
4777           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
4778           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->action_view),
4779                                     path, NULL, FALSE);
4780         }
4781
4782       gtk_tree_path_free (path);
4783
4784       return TRUE;
4785     }
4786   else if (event->keyval == GDK_Escape) 
4787     {
4788       _gtk_entry_completion_popdown (completion);
4789
4790       return TRUE;
4791     }
4792   else if (event->keyval == GDK_Tab || 
4793            event->keyval == GDK_KP_Tab ||
4794            event->keyval == GDK_ISO_Left_Tab) 
4795     {
4796       GtkWidget *entry;
4797       GtkDirectionType dir = event->keyval == GDK_ISO_Left_Tab ? 
4798         GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD;
4799
4800       _gtk_entry_completion_popdown (completion);
4801       
4802       entry = gtk_entry_completion_get_entry (completion);
4803
4804       gtk_widget_child_focus (gtk_widget_get_toplevel (entry), dir);
4805
4806       return TRUE;
4807     }
4808   else if (event->keyval == GDK_ISO_Enter || 
4809            event->keyval == GDK_Return)
4810     {
4811       _gtk_entry_completion_popdown (completion);
4812
4813       if (completion->priv->current_selected < matches)
4814         {
4815           GtkTreeIter iter;
4816           GtkTreeModel *model = NULL;
4817           GtkTreeSelection *sel;
4818           gboolean entry_set;
4819
4820           sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view));
4821           if (!gtk_tree_selection_get_selected (sel, &model, &iter))
4822             return FALSE;
4823
4824           g_signal_handler_block (completion->priv->entry,
4825                                   completion->priv->changed_id);
4826           g_signal_emit_by_name (completion, "match_selected",
4827                                  model, &iter, &entry_set);
4828           g_signal_handler_unblock (completion->priv->entry,
4829                                     completion->priv->changed_id);
4830
4831           if (!entry_set)
4832             {
4833               gchar *str = NULL;
4834
4835               gtk_tree_model_get (model, &iter,
4836                                   completion->priv->text_column, &str,
4837                                   -1);
4838
4839               g_signal_handler_block (widget, completion->priv->changed_id);
4840               gtk_entry_set_text (GTK_ENTRY (widget), str);
4841               g_signal_handler_unblock (widget, completion->priv->changed_id);
4842
4843               /* move the cursor to the end */
4844               gtk_editable_set_position (GTK_EDITABLE (widget), -1);
4845
4846              g_free (str);
4847             }
4848
4849           return TRUE;
4850         }
4851       else if (completion->priv->current_selected - matches >= 0)
4852         {
4853           GtkTreePath *path;
4854
4855           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
4856
4857           g_signal_emit_by_name (completion, "action_activated",
4858                                  gtk_tree_path_get_indices (path)[0]);
4859           gtk_tree_path_free (path);
4860
4861           return TRUE;
4862         }
4863     }
4864
4865   return FALSE;
4866 }
4867
4868 static void
4869 gtk_entry_completion_changed (GtkWidget *entry,
4870                               gpointer   user_data)
4871 {
4872   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
4873
4874   /* (re)install completion timeout */
4875   if (completion->priv->completion_timeout)
4876     g_source_remove (completion->priv->completion_timeout);
4877
4878   if (!gtk_entry_get_text (GTK_ENTRY (entry)))
4879     return;
4880
4881   /* no need to normalize for this test */
4882   if (! strcmp ("", gtk_entry_get_text (GTK_ENTRY (entry))))
4883     {
4884       if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4885         _gtk_entry_completion_popdown (completion);
4886       return;
4887     }
4888
4889   completion->priv->completion_timeout =
4890     g_timeout_add (COMPLETION_TIMEOUT,
4891                    gtk_entry_completion_timeout,
4892                    completion);
4893 }
4894
4895 /**
4896  * gtk_entry_set_completion:
4897  * @entry: A #GtkEntry.
4898  * @completion: The #GtkEntryCompletion.
4899  *
4900  * Sets @completion to be the auxiliary completion object to use with @entry.
4901  * All further configuration of the completion mechanism is done on
4902  * @completion using the #GtkEntryCompletion API.
4903  *
4904  * Since: 2.4
4905  */
4906 void
4907 gtk_entry_set_completion (GtkEntry           *entry,
4908                           GtkEntryCompletion *completion)
4909 {
4910   GtkEntryCompletion *old;
4911
4912   g_return_if_fail (GTK_IS_ENTRY (entry));
4913   g_return_if_fail (!completion || GTK_IS_ENTRY_COMPLETION (completion));
4914
4915   old = gtk_entry_get_completion (entry);
4916
4917   if (old == completion)
4918     return;
4919   
4920   if (old)
4921     {
4922       if (old->priv->completion_timeout)
4923         {
4924           g_source_remove (old->priv->completion_timeout);
4925           old->priv->completion_timeout = 0;
4926         }
4927
4928       if (GTK_WIDGET_MAPPED (old->priv->popup_window))
4929         _gtk_entry_completion_popdown (old);
4930
4931       gtk_cell_layout_clear (GTK_CELL_LAYOUT (old));
4932       old->priv->text_column = -1;
4933
4934       if (g_signal_handler_is_connected (entry, old->priv->changed_id))
4935         g_signal_handler_disconnect (entry, old->priv->changed_id);
4936       if (g_signal_handler_is_connected (entry, old->priv->key_press_id))
4937         g_signal_handler_disconnect (entry, old->priv->key_press_id);
4938
4939       old->priv->entry = NULL;
4940
4941       g_object_unref (old);
4942     }
4943
4944   if (!completion)
4945     {
4946       g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, NULL);
4947       return;
4948     }
4949
4950   /* hook into the entry */
4951   g_object_ref (completion);
4952
4953   completion->priv->changed_id =
4954     g_signal_connect (entry, "changed",
4955                       G_CALLBACK (gtk_entry_completion_changed), completion);
4956
4957   completion->priv->key_press_id =
4958     g_signal_connect (entry, "key_press_event",
4959                       G_CALLBACK (gtk_entry_completion_key_press), completion);
4960
4961   completion->priv->entry = GTK_WIDGET (entry);
4962   g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, completion);
4963 }
4964
4965 /**
4966  * gtk_entry_get_completion:
4967  * @entry: A #GtkEntry.
4968  *
4969  * Returns the auxiliary completion object currently in use by @entry.
4970  *
4971  * Return value: The auxiliary completion object currently in use by @entry.
4972  *
4973  * Since: 2.4
4974  */
4975 GtkEntryCompletion *
4976 gtk_entry_get_completion (GtkEntry *entry)
4977 {
4978   GtkEntryCompletion *completion;
4979
4980   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
4981
4982   completion = GTK_ENTRY_COMPLETION (g_object_get_data (G_OBJECT (entry),
4983                                      GTK_ENTRY_COMPLETION_KEY));
4984
4985   return completion;
4986 }