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