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