]> Pileus Git - ~andy/gtk/blob - gtk/gtkentry.c
x
[~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 void
1177 _gtk_entry_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   _gtk_entry_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   _gtk_entry_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, 0);
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->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[entry->current_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               if (gdk_keymap_get_direction (keymap) == PANGO_DIRECTION_RTL)
2972                 pango_dir = PANGO_DIRECTION_RTL;
2973               else
2974                 pango_dir = PANGO_DIRECTION_LTR;
2975             }
2976           else
2977             {
2978               if (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL)
2979                 pango_dir = PANGO_DIRECTION_RTL;
2980               else
2981                 pango_dir = PANGO_DIRECTION_LTR;
2982             }
2983         }
2984
2985       pango_context_set_base_dir (gtk_widget_get_pango_context (widget),
2986                                   pango_dir);
2987
2988       pango_layout_set_alignment (layout, pango_dir);
2989
2990       entry->resolved_dir = pango_dir;
2991       
2992       if (entry->visible)
2993         {
2994           pango_layout_set_text (layout, entry->text, entry->n_bytes);
2995         }
2996       else
2997         {
2998           GString *str = g_string_new (NULL);
2999           gunichar invisible_char;
3000           
3001           if (entry->invisible_char != 0)
3002             invisible_char = entry->invisible_char;
3003           else
3004             invisible_char = ' '; /* just pick a char */
3005           
3006           append_char (str, invisible_char, entry->text_length);
3007           pango_layout_set_text (layout, str->str, str->len);
3008           g_string_free (str, TRUE);
3009         }
3010     }
3011       
3012   pango_layout_set_attributes (layout, tmp_attrs);
3013
3014   if (preedit_string)
3015     g_free (preedit_string);
3016   if (preedit_attrs)
3017     pango_attr_list_unref (preedit_attrs);
3018       
3019   pango_attr_list_unref (tmp_attrs);
3020
3021   return layout;
3022 }
3023
3024 static PangoLayout *
3025 gtk_entry_ensure_layout (GtkEntry *entry,
3026                          gboolean  include_preedit)
3027 {
3028   if (entry->preedit_length > 0 &&
3029       !include_preedit != !entry->cache_includes_preedit)
3030     gtk_entry_reset_layout (entry);
3031
3032   if (!entry->cached_layout)
3033     {
3034       entry->cached_layout = gtk_entry_create_layout (entry, include_preedit);
3035       entry->cache_includes_preedit = include_preedit;
3036     }
3037   
3038   return entry->cached_layout;
3039 }
3040
3041 static void
3042 get_layout_position (GtkEntry *entry,
3043                      gint     *x,
3044                      gint     *y)
3045 {
3046   PangoLayout *layout;
3047   PangoRectangle logical_rect;
3048   gint area_width, area_height;
3049   gint y_pos;
3050   PangoLayoutLine *line;
3051   
3052   layout = gtk_entry_ensure_layout (entry, TRUE);
3053
3054   get_text_area_size (entry, NULL, NULL, &area_width, &area_height);      
3055       
3056   area_height = PANGO_SCALE * (area_height - 2 * INNER_BORDER);
3057   
3058   line = pango_layout_get_lines (layout)->data;
3059   pango_layout_line_get_extents (line, NULL, &logical_rect);
3060   
3061   /* Align primarily for locale's ascent/descent */
3062   y_pos = ((area_height - entry->ascent - entry->descent) / 2 + 
3063            entry->ascent + logical_rect.y);
3064   
3065   /* Now see if we need to adjust to fit in actual drawn string */
3066   if (logical_rect.height > area_height)
3067     y_pos = (area_height - logical_rect.height) / 2;
3068   else if (y_pos < 0)
3069     y_pos = 0;
3070   else if (y_pos + logical_rect.height > area_height)
3071     y_pos = area_height - logical_rect.height;
3072   
3073   y_pos = INNER_BORDER + y_pos / PANGO_SCALE;
3074
3075   if (x)
3076     *x = INNER_BORDER - entry->scroll_offset;
3077
3078   if (y)
3079     *y = y_pos;
3080 }
3081
3082 static void
3083 gtk_entry_draw_text (GtkEntry *entry)
3084 {
3085   GtkWidget *widget;
3086   
3087   if (!entry->visible && entry->invisible_char == 0)
3088     return;
3089   
3090   if (GTK_WIDGET_DRAWABLE (entry))
3091     {
3092       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
3093       gint x, y;
3094       gint start_pos, end_pos;
3095       
3096       widget = GTK_WIDGET (entry);
3097       
3098       get_layout_position (entry, &x, &y);
3099
3100       gdk_draw_layout (entry->text_area, widget->style->text_gc [widget->state],       
3101                        x, y,
3102                        layout);
3103       
3104       if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start_pos, &end_pos))
3105         {
3106           gint *ranges;
3107           gint n_ranges, i;
3108           PangoRectangle logical_rect;
3109           GdkGC *selection_gc, *text_gc;
3110           GdkRegion *clip_region;
3111
3112           pango_layout_get_pixel_extents (layout, NULL, &logical_rect);
3113           gtk_entry_get_pixel_ranges (entry, &ranges, &n_ranges);
3114
3115           if (GTK_WIDGET_HAS_FOCUS (entry))
3116             {
3117               selection_gc = widget->style->base_gc [GTK_STATE_SELECTED];
3118               text_gc = widget->style->text_gc [GTK_STATE_SELECTED];
3119             }
3120           else
3121             {
3122               selection_gc = widget->style->base_gc [GTK_STATE_ACTIVE];
3123               text_gc = widget->style->text_gc [GTK_STATE_ACTIVE];
3124             }
3125           
3126           clip_region = gdk_region_new ();
3127           for (i = 0; i < n_ranges; ++i)
3128             {
3129               GdkRectangle rect;
3130
3131               rect.x = INNER_BORDER - entry->scroll_offset + ranges[2 * i];
3132               rect.y = y;
3133               rect.width = ranges[2 * i + 1];
3134               rect.height = logical_rect.height;
3135                 
3136               gdk_draw_rectangle (entry->text_area, selection_gc, TRUE,
3137                                   rect.x, rect.y, rect.width, rect.height);
3138
3139               gdk_region_union_with_rect (clip_region, &rect);
3140             }
3141           
3142           gdk_gc_set_clip_region (text_gc, clip_region);
3143           gdk_draw_layout (entry->text_area, text_gc, 
3144                            x, y,
3145                            layout);
3146           gdk_gc_set_clip_region (text_gc, NULL);
3147           
3148           gdk_region_destroy (clip_region);
3149           g_free (ranges);
3150         }
3151     }
3152 }
3153
3154 static void
3155 draw_insertion_cursor (GtkEntry      *entry,
3156                        GdkRectangle  *cursor_location,
3157                        gboolean       is_primary,
3158                        PangoDirection direction,
3159                        gboolean       draw_arrow)
3160 {
3161   GtkWidget *widget = GTK_WIDGET (entry);
3162   GtkTextDirection text_dir;
3163
3164   if (direction == PANGO_DIRECTION_LTR)
3165     text_dir = GTK_TEXT_DIR_LTR;
3166   else
3167     text_dir = GTK_TEXT_DIR_RTL;
3168
3169   gtk_draw_insertion_cursor (widget, entry->text_area, NULL,
3170                              cursor_location,
3171                              is_primary, text_dir, draw_arrow);
3172 }
3173
3174 static void
3175 gtk_entry_draw_cursor (GtkEntry  *entry,
3176                        CursorType type)
3177 {
3178   GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
3179   PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3180   
3181   if (GTK_WIDGET_DRAWABLE (entry))
3182     {
3183       GtkWidget *widget = GTK_WIDGET (entry);
3184       GdkRectangle cursor_location;
3185       gboolean split_cursor;
3186
3187       gint xoffset = INNER_BORDER - entry->scroll_offset;
3188       gint strong_x, weak_x;
3189       gint text_area_height;
3190       PangoDirection dir1 = PANGO_DIRECTION_NEUTRAL;
3191       PangoDirection dir2 = PANGO_DIRECTION_NEUTRAL;
3192       gint x1 = 0;
3193       gint x2 = 0;
3194
3195       gdk_drawable_get_size (entry->text_area, NULL, &text_area_height);
3196       
3197       gtk_entry_get_cursor_locations (entry, type, &strong_x, &weak_x);
3198
3199       g_object_get (gtk_widget_get_settings (widget),
3200                     "gtk-split-cursor", &split_cursor,
3201                     NULL);
3202
3203       dir1 = entry->resolved_dir;
3204       
3205       if (split_cursor)
3206         {
3207           x1 = strong_x;
3208
3209           if (weak_x != strong_x)
3210             {
3211               dir2 = (entry->resolved_dir == PANGO_DIRECTION_LTR) ? PANGO_DIRECTION_RTL : PANGO_DIRECTION_LTR;
3212               x2 = weak_x;
3213             }
3214         }
3215       else
3216         {
3217           if (keymap_direction == entry->resolved_dir)
3218             x1 = strong_x;
3219           else
3220             x1 = weak_x;
3221         }
3222
3223       cursor_location.x = xoffset + x1;
3224       cursor_location.y = INNER_BORDER;
3225       cursor_location.width = 0;
3226       cursor_location.height = text_area_height - 2 * INNER_BORDER ;
3227
3228       draw_insertion_cursor (entry,
3229                              &cursor_location, TRUE, dir1,
3230                              dir2 != PANGO_DIRECTION_NEUTRAL);
3231       
3232       if (dir2 != PANGO_DIRECTION_NEUTRAL)
3233         {
3234           cursor_location.x = xoffset + x2;
3235           draw_insertion_cursor (entry,
3236                                  &cursor_location, FALSE, dir2,
3237                                  TRUE);
3238         }
3239     }
3240 }
3241
3242 static void
3243 gtk_entry_queue_draw (GtkEntry *entry)
3244 {
3245   if (GTK_WIDGET_REALIZED (entry))
3246     gdk_window_invalidate_rect (entry->text_area, NULL, FALSE);
3247 }
3248
3249 static void
3250 gtk_entry_reset_im_context (GtkEntry *entry)
3251 {
3252   if (entry->need_im_reset)
3253     {
3254       entry->need_im_reset = 0;
3255       gtk_im_context_reset (entry->im_context);
3256     }
3257 }
3258
3259 static gint
3260 gtk_entry_find_position (GtkEntry *entry,
3261                          gint      x)
3262 {
3263   PangoLayout *layout;
3264   PangoLayoutLine *line;
3265   gint index;
3266   gint pos;
3267   gboolean trailing;
3268   const gchar *text;
3269   gint cursor_index;
3270   
3271   layout = gtk_entry_ensure_layout (entry, TRUE);
3272   text = pango_layout_get_text (layout);
3273   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
3274   
3275   line = pango_layout_get_lines (layout)->data;
3276   pango_layout_line_x_to_index (line, x * PANGO_SCALE, &index, &trailing);
3277
3278   if (index >= cursor_index && entry->preedit_length)
3279     {
3280       if (index >= cursor_index + entry->preedit_length)
3281         index -= entry->preedit_length;
3282       else
3283         {
3284           index = cursor_index;
3285           trailing = 0;
3286         }
3287     }
3288
3289   pos = g_utf8_pointer_to_offset (text, text + index);
3290   pos += trailing;
3291
3292   return pos;
3293 }
3294
3295 static void
3296 gtk_entry_get_cursor_locations (GtkEntry   *entry,
3297                                 CursorType  type,
3298                                 gint       *strong_x,
3299                                 gint       *weak_x)
3300 {
3301   if (!entry->visible && !entry->invisible_char)
3302     {
3303       if (strong_x)
3304         *strong_x = 0;
3305       
3306       if (weak_x)
3307         *weak_x = 0;
3308     }
3309   else
3310     {
3311       PangoLayout *layout = gtk_entry_ensure_layout (entry, TRUE);
3312       const gchar *text = pango_layout_get_text (layout);
3313       PangoRectangle strong_pos, weak_pos;
3314       gint index;
3315   
3316       if (type == CURSOR_STANDARD)
3317         {
3318           index = g_utf8_offset_to_pointer (text, entry->current_pos + entry->preedit_cursor) - text;
3319         }
3320       else /* type == CURSOR_DND */
3321         {
3322           index = g_utf8_offset_to_pointer (text, entry->dnd_position) - text;
3323
3324           if (entry->dnd_position > entry->current_pos)
3325             {
3326               if (entry->visible)
3327                 index += entry->preedit_length;
3328               else
3329                 {
3330                   gint preedit_len_chars = g_utf8_strlen (text, -1) - entry->text_length;
3331                   index += preedit_len_chars * g_unichar_to_utf8 (entry->invisible_char, NULL);
3332                 }
3333             }
3334         }
3335       
3336       pango_layout_get_cursor_pos (layout, index, &strong_pos, &weak_pos);
3337       
3338       if (strong_x)
3339         *strong_x = strong_pos.x / PANGO_SCALE;
3340       
3341       if (weak_x)
3342         *weak_x = weak_pos.x / PANGO_SCALE;
3343     }
3344 }
3345
3346 static void
3347 gtk_entry_adjust_scroll (GtkEntry *entry)
3348 {
3349   GtkEntryPrivate *priv = GTK_ENTRY_GET_PRIVATE (entry);
3350   gint min_offset, max_offset;
3351   gint text_area_width, text_width;
3352   gint strong_x, weak_x;
3353   gint strong_xoffset, weak_xoffset;
3354   gfloat xalign;
3355   PangoLayout *layout;
3356   PangoLayoutLine *line;
3357   PangoRectangle logical_rect;
3358
3359   if (!GTK_WIDGET_REALIZED (entry))
3360     return;
3361   
3362   gdk_drawable_get_size (entry->text_area, &text_area_width, NULL);
3363   text_area_width -= 2 * INNER_BORDER;
3364
3365   layout = gtk_entry_ensure_layout (entry, TRUE);
3366   line = pango_layout_get_lines (layout)->data;
3367
3368   pango_layout_line_get_extents (line, NULL, &logical_rect);
3369
3370   /* Display as much text as we can */
3371
3372   if (entry->resolved_dir == PANGO_DIRECTION_LTR)
3373       xalign = priv->xalign;
3374   else
3375       xalign = 1.0 - priv->xalign;
3376
3377   text_width = PANGO_PIXELS(logical_rect.width);
3378
3379   if (text_width > text_area_width)
3380     {
3381       min_offset = 0;
3382       max_offset = text_width - text_area_width;
3383     }
3384   else
3385     {
3386       min_offset = (text_width - text_area_width) * xalign;
3387       max_offset = min_offset;
3388     }
3389
3390   entry->scroll_offset = CLAMP (entry->scroll_offset, min_offset, max_offset);
3391
3392   /* And make sure cursors are on screen. Note that the cursor is
3393    * actually drawn one pixel into the INNER_BORDER space on
3394    * the right, when the scroll is at the utmost right. This
3395    * looks better to to me than confining the cursor inside the
3396    * border entirely, though it means that the cursor gets one
3397    * pixel closer to the edge of the widget on the right than
3398    * on the left. This might need changing if one changed
3399    * INNER_BORDER from 2 to 1, as one would do on a
3400    * small-screen-real-estate display.
3401    *
3402    * We always make sure that the strong cursor is on screen, and
3403    * put the weak cursor on screen if possible.
3404    */
3405
3406   gtk_entry_get_cursor_locations (entry, CURSOR_STANDARD, &strong_x, &weak_x);
3407   
3408   strong_xoffset = strong_x - entry->scroll_offset;
3409
3410   if (strong_xoffset < 0)
3411     {
3412       entry->scroll_offset += strong_xoffset;
3413       strong_xoffset = 0;
3414     }
3415   else if (strong_xoffset > text_area_width)
3416     {
3417       entry->scroll_offset += strong_xoffset - text_area_width;
3418       strong_xoffset = text_area_width;
3419     }
3420
3421   weak_xoffset = weak_x - entry->scroll_offset;
3422
3423   if (weak_xoffset < 0 && strong_xoffset - weak_xoffset <= text_area_width)
3424     {
3425       entry->scroll_offset += weak_xoffset;
3426     }
3427   else if (weak_xoffset > text_area_width &&
3428            strong_xoffset - (weak_xoffset - text_area_width) >= 0)
3429     {
3430       entry->scroll_offset += weak_xoffset - text_area_width;
3431     }
3432
3433   g_object_notify (G_OBJECT (entry), "scroll_offset");
3434 }
3435
3436 static gint
3437 gtk_entry_move_visually (GtkEntry *entry,
3438                          gint      start,
3439                          gint      count)
3440 {
3441   gint index;
3442   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3443   const gchar *text;
3444
3445   text = pango_layout_get_text (layout);
3446   
3447   index = g_utf8_offset_to_pointer (text, start) - text;
3448
3449   while (count != 0)
3450     {
3451       int new_index, new_trailing;
3452       gboolean split_cursor;
3453       gboolean strong;
3454
3455       g_object_get (gtk_widget_get_settings (GTK_WIDGET (entry)),
3456                     "gtk-split-cursor", &split_cursor,
3457                     NULL);
3458
3459       if (split_cursor)
3460         strong = TRUE;
3461       else
3462         {
3463           GdkKeymap *keymap = gdk_keymap_get_for_display (gtk_widget_get_display (GTK_WIDGET (entry)));
3464           PangoDirection keymap_direction = gdk_keymap_get_direction (keymap);
3465
3466           strong = keymap_direction == entry->resolved_dir;
3467         }
3468       
3469       if (count > 0)
3470         {
3471           pango_layout_move_cursor_visually (layout, strong, index, 0, 1, &new_index, &new_trailing);
3472           count--;
3473         }
3474       else
3475         {
3476           pango_layout_move_cursor_visually (layout, strong, index, 0, -1, &new_index, &new_trailing);
3477           count++;
3478         }
3479
3480       if (new_index < 0)
3481         index = 0;
3482       else if (new_index != G_MAXINT)
3483         index = new_index;
3484       
3485       while (new_trailing--)
3486         index = g_utf8_next_char (text + index) - text;
3487     }
3488   
3489   return g_utf8_pointer_to_offset (text, text + index);
3490 }
3491
3492 static gint
3493 gtk_entry_move_logically (GtkEntry *entry,
3494                           gint      start,
3495                           gint      count)
3496 {
3497   gint new_pos = start;
3498
3499   /* Prevent any leak of information */
3500   if (!entry->visible)
3501     {
3502       new_pos = CLAMP (start + count, 0, entry->text_length);
3503     }
3504   else if (entry->text)
3505     {
3506       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3507       PangoLogAttr *log_attrs;
3508       gint n_attrs;
3509
3510       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3511
3512       while (count > 0 && new_pos < entry->text_length)
3513         {
3514           do
3515             new_pos++;
3516           while (new_pos < entry->text_length && !log_attrs[new_pos].is_cursor_position);
3517           
3518           count--;
3519         }
3520       while (count < 0 && new_pos > 0)
3521         {
3522           do
3523             new_pos--;
3524           while (new_pos > 0 && !log_attrs[new_pos].is_cursor_position);
3525           
3526           count++;
3527         }
3528       
3529       g_free (log_attrs);
3530     }
3531
3532   return new_pos;
3533 }
3534
3535 static gint
3536 gtk_entry_move_forward_word (GtkEntry *entry,
3537                              gint      start)
3538 {
3539   gint new_pos = start;
3540
3541   /* Prevent any leak of information */
3542   if (!entry->visible)
3543     {
3544       new_pos = entry->text_length;
3545     }
3546   else if (entry->text && (new_pos < entry->text_length))
3547     {
3548       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3549       PangoLogAttr *log_attrs;
3550       gint n_attrs;
3551
3552       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3553       
3554       /* Find the next word end */
3555       new_pos++;
3556       while (new_pos < n_attrs && !log_attrs[new_pos].is_word_end)
3557         new_pos++;
3558
3559       g_free (log_attrs);
3560     }
3561
3562   return new_pos;
3563 }
3564
3565
3566 static gint
3567 gtk_entry_move_backward_word (GtkEntry *entry,
3568                               gint      start)
3569 {
3570   gint new_pos = start;
3571
3572   /* Prevent any leak of information */
3573   if (!entry->visible)
3574     {
3575       new_pos = 0;
3576     }
3577   else if (entry->text && start > 0)
3578     {
3579       PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3580       PangoLogAttr *log_attrs;
3581       gint n_attrs;
3582
3583       pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3584
3585       new_pos = start - 1;
3586
3587       /* Find the previous word beginning */
3588       while (new_pos > 0 && !log_attrs[new_pos].is_word_start)
3589         new_pos--;
3590
3591       g_free (log_attrs);
3592     }
3593
3594   return new_pos;
3595 }
3596
3597 static void
3598 gtk_entry_delete_whitespace (GtkEntry *entry)
3599 {
3600   PangoLayout *layout = gtk_entry_ensure_layout (entry, FALSE);
3601   PangoLogAttr *log_attrs;
3602   gint n_attrs;
3603   gint start, end;
3604
3605   pango_layout_get_log_attrs (layout, &log_attrs, &n_attrs);
3606
3607   start = end = entry->current_pos;
3608   
3609   while (start > 0 && log_attrs[start-1].is_white)
3610     start--;
3611
3612   while (end < n_attrs && log_attrs[end].is_white)
3613     end++;
3614
3615   g_free (log_attrs);
3616
3617   if (start != end)
3618     gtk_editable_delete_text (GTK_EDITABLE (entry), start, end);
3619 }
3620
3621
3622 static void
3623 gtk_entry_select_word (GtkEntry *entry)
3624 {
3625   gint start_pos = gtk_entry_move_backward_word (entry, entry->current_pos);
3626   gint end_pos = gtk_entry_move_forward_word (entry, entry->current_pos);
3627
3628   gtk_editable_select_region (GTK_EDITABLE (entry), start_pos, end_pos);
3629 }
3630
3631 static void
3632 gtk_entry_select_line (GtkEntry *entry)
3633 {
3634   gtk_editable_select_region (GTK_EDITABLE (entry), 0, -1);
3635 }
3636
3637 /*
3638  * Like gtk_editable_get_chars, but handle not-visible entries
3639  * correctly.
3640  */
3641 static char *    
3642 gtk_entry_get_public_chars (GtkEntry *entry,
3643                             gint      start,
3644                             gint      end)
3645 {
3646   if (end < 0)
3647     end = entry->text_length;
3648   
3649   if (entry->visible)
3650     return gtk_editable_get_chars (GTK_EDITABLE (entry), start, end);
3651   else if (!entry->invisible_char)
3652     return g_strdup ("");
3653   else
3654     {
3655       GString *str = g_string_new (NULL);
3656       append_char (str, entry->invisible_char, end - start);
3657       return g_string_free (str, FALSE);
3658     }
3659 }
3660
3661 static void
3662 paste_received (GtkClipboard *clipboard,
3663                 const gchar  *text,
3664                 gpointer      data)
3665 {
3666   GtkEntry *entry = GTK_ENTRY (data);
3667   GtkEditable *editable = GTK_EDITABLE (entry);
3668   GtkEntryPrivate *priv = GTK_ENTRY_GET_PRIVATE (entry);
3669       
3670   if (entry->button == 2)
3671     {
3672       gint pos, start, end;
3673       pos = priv->insert_pos;
3674       gtk_editable_get_selection_bounds (editable, &start, &end);
3675       if (!((start <= pos && pos <= end) || (end <= pos && pos <= start)))
3676         gtk_editable_select_region (editable, pos, pos);
3677     }
3678       
3679   if (text)
3680     {
3681       gint pos, start, end;
3682       GtkEntryCompletion *completion = gtk_entry_get_completion (entry);
3683
3684       if (completion)
3685         {
3686           g_signal_handler_block (entry, completion->priv->changed_id);
3687           if (GTK_WIDGET_MAPPED (completion->priv->popup_window))
3688             _gtk_entry_completion_popdown (completion);
3689         }
3690
3691       if (gtk_editable_get_selection_bounds (editable, &start, &end))
3692         gtk_editable_delete_text (editable, start, end);
3693
3694       pos = entry->current_pos;
3695       gtk_editable_insert_text (editable, text, -1, &pos);
3696       gtk_editable_set_position (editable, pos);
3697
3698       if (completion)
3699         g_signal_handler_unblock (entry, completion->priv->changed_id);
3700     }
3701
3702   g_object_unref (entry);
3703 }
3704
3705 static void
3706 gtk_entry_paste (GtkEntry *entry,
3707                  GdkAtom   selection)
3708 {
3709   g_object_ref (entry);
3710   gtk_clipboard_request_text (gtk_widget_get_clipboard (GTK_WIDGET (entry), selection),
3711                               paste_received, entry);
3712 }
3713
3714 static void
3715 primary_get_cb (GtkClipboard     *clipboard,
3716                 GtkSelectionData *selection_data,
3717                 guint             info,
3718                 gpointer          data)
3719 {
3720   GtkEntry *entry = GTK_ENTRY (data);
3721   gint start, end;
3722   
3723   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3724     {
3725       gchar *str = gtk_entry_get_public_chars (entry, start, end);
3726       gtk_selection_data_set_text (selection_data, str, -1);
3727       g_free (str);
3728     }
3729 }
3730
3731 static void
3732 primary_clear_cb (GtkClipboard *clipboard,
3733                   gpointer      data)
3734 {
3735   GtkEntry *entry = GTK_ENTRY (data);
3736
3737   gtk_editable_select_region (GTK_EDITABLE (entry), entry->current_pos, entry->current_pos);
3738 }
3739
3740 static void
3741 gtk_entry_update_primary_selection (GtkEntry *entry)
3742 {
3743   static GtkTargetEntry targets[] = {
3744     { "UTF8_STRING", 0, 0 },
3745     { "STRING", 0, 0 },
3746     { "TEXT",   0, 0 }, 
3747     { "COMPOUND_TEXT", 0, 0 },
3748     { "text/plain;charset=utf-8",   0, 0 }, 
3749     { NULL,   0, 0 },
3750     { "text/plain", 0, 0 }
3751   };
3752   
3753   GtkClipboard *clipboard;
3754   gint start, end;
3755
3756   if (targets[5].target == NULL)
3757     {
3758       const gchar *charset;
3759
3760       g_get_charset (&charset);
3761       targets[5].target = g_strdup_printf ("text/plain;charset=%s", charset);
3762     }
3763
3764   if (!GTK_WIDGET_REALIZED (entry))
3765     return;
3766
3767   clipboard = gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_PRIMARY);
3768   
3769   if (gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &start, &end))
3770     {
3771       if (!gtk_clipboard_set_with_owner (clipboard, targets, G_N_ELEMENTS (targets),
3772                                          primary_get_cb, primary_clear_cb, G_OBJECT (entry)))
3773         primary_clear_cb (clipboard, entry);
3774     }
3775   else
3776     {
3777       if (gtk_clipboard_get_owner (clipboard) == G_OBJECT (entry))
3778         gtk_clipboard_clear (clipboard);
3779     }
3780 }
3781
3782 /* Public API
3783  */
3784
3785 GtkWidget*
3786 gtk_entry_new (void)
3787 {
3788   return g_object_new (GTK_TYPE_ENTRY, NULL);
3789 }
3790
3791 /**
3792  * gtk_entry_new_with_max_length:
3793  * @max: the maximum length of the entry, or 0 for no maximum.
3794  *   (other than the maximum length of entries.) The value passed in will
3795  *   be clamped to the range 0-65536.
3796  *
3797  * Creates a new #GtkEntry widget with the given maximum length.
3798  * 
3799  * Note: the existence of this function is inconsistent
3800  * with the rest of the GTK+ API. The normal setup would
3801  * be to just require the user to make an extra call
3802  * to gtk_entry_set_max_length() instead. It is not
3803  * expected that this function will be removed, but
3804  * it would be better practice not to use it.
3805  * 
3806  * Return value: a new #GtkEntry.
3807  **/
3808 GtkWidget*
3809 gtk_entry_new_with_max_length (gint max)
3810 {
3811   GtkEntry *entry;
3812
3813   max = CLAMP (max, 0, MAX_SIZE);
3814
3815   entry = g_object_new (GTK_TYPE_ENTRY, NULL);
3816   entry->text_max_length = max;
3817
3818   return GTK_WIDGET (entry);
3819 }
3820
3821 void
3822 gtk_entry_set_text (GtkEntry    *entry,
3823                     const gchar *text)
3824 {
3825   gint tmp_pos;
3826   GtkEntryCompletion *completion;
3827
3828   g_return_if_fail (GTK_IS_ENTRY (entry));
3829   g_return_if_fail (text != NULL);
3830
3831   /* Actually setting the text will affect the cursor and selection;
3832    * if the contents don't actually change, this will look odd to the user.
3833    */
3834   if (strcmp (entry->text, text) == 0)
3835     return;
3836
3837   completion = gtk_entry_get_completion (entry);
3838   if (completion)
3839     g_signal_handler_block (entry, completion->priv->changed_id);
3840
3841   gtk_editable_delete_text (GTK_EDITABLE (entry), 0, -1);
3842
3843   tmp_pos = 0;
3844   gtk_editable_insert_text (GTK_EDITABLE (entry), text, strlen (text), &tmp_pos);
3845
3846   if (completion)
3847     g_signal_handler_unblock (entry, completion->priv->changed_id);
3848 }
3849
3850 void
3851 gtk_entry_append_text (GtkEntry *entry,
3852                        const gchar *text)
3853 {
3854   gint tmp_pos;
3855
3856   g_return_if_fail (GTK_IS_ENTRY (entry));
3857   g_return_if_fail (text != NULL);
3858
3859   tmp_pos = entry->text_length;
3860   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3861 }
3862
3863 void
3864 gtk_entry_prepend_text (GtkEntry *entry,
3865                         const gchar *text)
3866 {
3867   gint tmp_pos;
3868
3869   g_return_if_fail (GTK_IS_ENTRY (entry));
3870   g_return_if_fail (text != NULL);
3871
3872   tmp_pos = 0;
3873   gtk_editable_insert_text (GTK_EDITABLE (entry), text, -1, &tmp_pos);
3874 }
3875
3876 void
3877 gtk_entry_set_position (GtkEntry *entry,
3878                         gint       position)
3879 {
3880   g_return_if_fail (GTK_IS_ENTRY (entry));
3881
3882   gtk_editable_set_position (GTK_EDITABLE (entry), position);
3883 }
3884
3885 void
3886 gtk_entry_set_visibility (GtkEntry *entry,
3887                           gboolean visible)
3888 {
3889   g_return_if_fail (GTK_IS_ENTRY (entry));
3890
3891   entry->visible = visible ? TRUE : FALSE;
3892   g_object_notify (G_OBJECT (entry), "visibility");
3893   gtk_entry_recompute (entry);
3894 }
3895
3896 /**
3897  * gtk_entry_get_visibility:
3898  * @entry: a #GtkEntry
3899  *
3900  * Retrieves whether the text in @entry is visible. See
3901  * gtk_entry_set_visibility().
3902  *
3903  * Return value: %TRUE if the text is currently visible
3904  **/
3905 gboolean
3906 gtk_entry_get_visibility (GtkEntry *entry)
3907 {
3908   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
3909
3910   return entry->visible;
3911 }
3912
3913 /**
3914  * gtk_entry_set_invisible_char:
3915  * @entry: a #GtkEntry
3916  * @ch: a Unicode character
3917  * 
3918  * Sets the character to use in place of the actual text when
3919  * gtk_entry_set_visibility() has been called to set text visibility
3920  * to %FALSE. i.e. this is the character used in "password mode" to
3921  * show the user how many characters have been typed. The default
3922  * invisible char is an asterisk ('*').  If you set the invisible char
3923  * to 0, then the user will get no feedback at all; there will be
3924  * no text on the screen as they type.
3925  * 
3926  **/
3927 void
3928 gtk_entry_set_invisible_char (GtkEntry *entry,
3929                               gunichar  ch)
3930 {
3931   g_return_if_fail (GTK_IS_ENTRY (entry));
3932
3933   if (ch == entry->invisible_char)
3934     return;
3935
3936   entry->invisible_char = ch;
3937   g_object_notify (G_OBJECT (entry), "invisible_char");
3938   gtk_entry_recompute (entry);  
3939 }
3940
3941 /**
3942  * gtk_entry_get_invisible_char:
3943  * @entry: a #GtkEntry
3944  *
3945  * Retrieves the character displayed in place of the real characters
3946  * for entries with visisbility set to false. See gtk_entry_set_invisible_char().
3947  *
3948  * Return value: the current invisible char, or 0, if the entry does not
3949  *               show invisible text at all. 
3950  **/
3951 gunichar
3952 gtk_entry_get_invisible_char (GtkEntry *entry)
3953 {
3954   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
3955
3956   return entry->invisible_char;
3957 }
3958
3959 void
3960 gtk_entry_set_editable (GtkEntry *entry,
3961                         gboolean  editable)
3962 {
3963   g_return_if_fail (GTK_IS_ENTRY (entry));
3964
3965   gtk_editable_set_editable (GTK_EDITABLE (entry), editable);
3966 }
3967
3968 /**
3969  * gtk_entry_get_text:
3970  * @entry: a #GtkEntry
3971  *
3972  * Retrieves the contents of the entry widget.
3973  * See also gtk_editable_get_chars().
3974  *
3975  * Return value: a pointer to the contents of the widget as a
3976  *      string.  This string points to internally allocated
3977  *      storage in the widget and must not be freed, modified or
3978  *      stored.
3979  **/
3980 G_CONST_RETURN gchar*
3981 gtk_entry_get_text (GtkEntry *entry)
3982 {
3983   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
3984
3985   return entry->text;
3986 }
3987
3988 void       
3989 gtk_entry_select_region  (GtkEntry       *entry,
3990                           gint            start,
3991                           gint            end)
3992 {
3993   gtk_editable_select_region (GTK_EDITABLE (entry), start, end);
3994 }
3995
3996 /**
3997  * gtk_entry_set_max_length:
3998  * @entry: a #GtkEntry.
3999  * @max: the maximum length of the entry, or 0 for no maximum.
4000  *   (other than the maximum length of entries.) The value passed in will
4001  *   be clamped to the range 0-65536.
4002  * 
4003  * Sets the maximum allowed length of the contents of the widget. If
4004  * the current contents are longer than the given length, then they
4005  * will be truncated to fit.
4006  **/
4007 void
4008 gtk_entry_set_max_length (GtkEntry     *entry,
4009                           gint          max)
4010 {
4011   g_return_if_fail (GTK_IS_ENTRY (entry));
4012
4013   max = CLAMP (max, 0, MAX_SIZE);
4014
4015   if (max > 0 && entry->text_length > max)
4016     gtk_editable_delete_text (GTK_EDITABLE (entry), max, -1);
4017   
4018   entry->text_max_length = max;
4019   g_object_notify (G_OBJECT (entry), "max_length");
4020 }
4021
4022 /**
4023  * gtk_entry_get_max_length:
4024  * @entry: a #GtkEntry
4025  *
4026  * Retrieves the maximum allowed length of the text in
4027  * @entry. See gtk_entry_set_max_length().
4028  *
4029  * Return value: the maximum allowed number of characters
4030  *               in #GtkEntry, or 0 if there is no maximum.
4031  **/
4032 gint
4033 gtk_entry_get_max_length (GtkEntry *entry)
4034 {
4035   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
4036
4037   return entry->text_max_length;
4038 }
4039
4040 /**
4041  * gtk_entry_set_activates_default:
4042  * @entry: a #GtkEntry
4043  * @setting: %TRUE to activate window's default widget on Enter keypress
4044  *
4045  * If @setting is %TRUE, pressing Enter in the @entry will activate the default
4046  * widget for the window containing the entry. This usually means that
4047  * the dialog box containing the entry will be closed, since the default
4048  * widget is usually one of the dialog buttons.
4049  *
4050  * (For experts: if @setting is %TRUE, the entry calls
4051  * gtk_window_activate_default() on the window containing the entry, in
4052  * the default handler for the "activate" signal.)
4053  * 
4054  **/
4055 void
4056 gtk_entry_set_activates_default (GtkEntry *entry,
4057                                  gboolean  setting)
4058 {
4059   g_return_if_fail (GTK_IS_ENTRY (entry));
4060   setting = setting != FALSE;
4061
4062   if (setting != entry->activates_default)
4063     {
4064       entry->activates_default = setting;
4065       g_object_notify (G_OBJECT (entry), "activates_default");
4066     }
4067 }
4068
4069 /**
4070  * gtk_entry_get_activates_default:
4071  * @entry: a #GtkEntry
4072  * 
4073  * Retrieves the value set by gtk_entry_set_activates_default().
4074  * 
4075  * Return value: %TRUE if the entry will activate the default widget
4076  **/
4077 gboolean
4078 gtk_entry_get_activates_default (GtkEntry *entry)
4079 {
4080   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
4081
4082   return entry->activates_default;
4083 }
4084
4085 /**
4086  * gtk_entry_set_width_chars:
4087  * @entry: a #GtkEntry
4088  * @n_chars: width in chars
4089  *
4090  * Changes the size request of the entry to be about the right size
4091  * for @n_chars characters. Note that it changes the size
4092  * <emphasis>request</emphasis>, the size can still be affected by
4093  * how you pack the widget into containers. If @n_chars is -1, the
4094  * size reverts to the default entry size.
4095  * 
4096  **/
4097 void
4098 gtk_entry_set_width_chars (GtkEntry *entry,
4099                            gint      n_chars)
4100 {
4101   g_return_if_fail (GTK_IS_ENTRY (entry));
4102
4103   if (entry->width_chars != n_chars)
4104     {
4105       entry->width_chars = n_chars;
4106       g_object_notify (G_OBJECT (entry), "width_chars");
4107       gtk_widget_queue_resize (GTK_WIDGET (entry));
4108     }
4109 }
4110
4111 /**
4112  * gtk_entry_get_width_chars:
4113  * @entry: a #GtkEntry
4114  * 
4115  * Gets the value set by gtk_entry_set_width_chars().
4116  * 
4117  * Return value: number of chars to request space for, or negative if unset
4118  **/
4119 gint
4120 gtk_entry_get_width_chars (GtkEntry *entry)
4121 {
4122   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
4123
4124   return entry->width_chars;
4125 }
4126
4127 /**
4128  * gtk_entry_set_has_frame:
4129  * @entry: a #GtkEntry
4130  * @setting: new value
4131  * 
4132  * Sets whether the entry has a beveled frame around it.
4133  **/
4134 void
4135 gtk_entry_set_has_frame (GtkEntry *entry,
4136                          gboolean  setting)
4137 {
4138   g_return_if_fail (GTK_IS_ENTRY (entry));
4139
4140   setting = (setting != FALSE);
4141
4142   if (entry->has_frame == setting)
4143     return;
4144
4145   gtk_widget_queue_resize (GTK_WIDGET (entry));
4146   entry->has_frame = setting;
4147   g_object_notify (G_OBJECT (entry), "has_frame");
4148 }
4149
4150 /**
4151  * gtk_entry_get_has_frame:
4152  * @entry: a #GtkEntry
4153  * 
4154  * Gets the value set by gtk_entry_set_has_frame().
4155  * 
4156  * Return value: whether the entry has a beveled frame
4157  **/
4158 gboolean
4159 gtk_entry_get_has_frame (GtkEntry *entry)
4160 {
4161   g_return_val_if_fail (GTK_IS_ENTRY (entry), FALSE);
4162
4163   return entry->has_frame;
4164 }
4165
4166
4167 /**
4168  * gtk_entry_get_layout:
4169  * @entry: a #GtkEntry
4170  * 
4171  * Gets the #PangoLayout used to display the entry.
4172  * The layout is useful to e.g. convert text positions to
4173  * pixel positions, in combination with gtk_entry_get_layout_offsets().
4174  * The returned layout is owned by the entry so need not be
4175  * freed by the caller.
4176  *
4177  * Keep in mind that the layout text may contain a preedit string, so
4178  * gtk_entry_layout_index_to_text_index() and
4179  * gtk_entry_text_index_to_layout_index() are needed to convert byte
4180  * indices in the layout to byte indices in the entry contents.
4181  * 
4182  * Return value: the #PangoLayout for this entry
4183  **/
4184 PangoLayout*
4185 gtk_entry_get_layout (GtkEntry *entry)
4186 {
4187   PangoLayout *layout;
4188   
4189   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
4190
4191   layout = gtk_entry_ensure_layout (entry, TRUE);
4192
4193   return layout;
4194 }
4195
4196
4197 /**
4198  * gtk_entry_layout_index_to_text_index:
4199  * @entry: a #GtkEntry
4200  * @layout_index: byte index into the entry layout text
4201  * 
4202  * Converts from a position in the entry contents (returned
4203  * by gtk_entry_get_text()) to a position in the
4204  * entry's #PangoLayout (returned by gtk_entry_get_layout(),
4205  * with text retrieved via pango_layout_get_text()).
4206  * 
4207  * Return value: byte index into the entry contents
4208  **/
4209 gint
4210 gtk_entry_layout_index_to_text_index (GtkEntry *entry,
4211                                       gint      layout_index)
4212 {
4213   PangoLayout *layout;
4214   const gchar *text;
4215   gint cursor_index;
4216   
4217   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
4218
4219   layout = gtk_entry_ensure_layout (entry, TRUE);
4220   text = pango_layout_get_text (layout);
4221   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
4222   
4223   if (layout_index >= cursor_index && entry->preedit_length)
4224     {
4225       if (layout_index >= cursor_index + entry->preedit_length)
4226         layout_index -= entry->preedit_length;
4227       else
4228         layout_index = cursor_index;
4229     }
4230
4231   return layout_index;
4232 }
4233
4234 /**
4235  * gtk_entry_text_index_to_layout_index:
4236  * @entry: a #GtkEntry
4237  * @text_index: byte index into the entry contents
4238  * 
4239  * Converts from a position in the entry's #PangoLayout (returned by
4240  * gtk_entry_get_layout()) to a position in the entry contents
4241  * (returned by gtk_entry_get_text()).
4242  * 
4243  * Return value: byte index into the entry layout text
4244  **/
4245 gint
4246 gtk_entry_text_index_to_layout_index (GtkEntry *entry,
4247                                       gint      text_index)
4248 {
4249   PangoLayout *layout;
4250   const gchar *text;
4251   gint cursor_index;
4252   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0);
4253
4254   layout = gtk_entry_ensure_layout (entry, TRUE);
4255   text = pango_layout_get_text (layout);
4256   cursor_index = g_utf8_offset_to_pointer (text, entry->current_pos) - text;
4257   
4258   if (text_index > cursor_index)
4259     text_index += entry->preedit_length;
4260
4261   return text_index;
4262 }
4263
4264 /**
4265  * gtk_entry_get_layout_offsets:
4266  * @entry: a #GtkEntry
4267  * @x: location to store X offset of layout, or %NULL
4268  * @y: location to store Y offset of layout, or %NULL
4269  *
4270  *
4271  * Obtains the position of the #PangoLayout used to render text
4272  * in the entry, in widget coordinates. Useful if you want to line
4273  * up the text in an entry with some other text, e.g. when using the
4274  * entry to implement editable cells in a sheet widget.
4275  *
4276  * Also useful to convert mouse events into coordinates inside the
4277  * #PangoLayout, e.g. to take some action if some part of the entry text
4278  * is clicked.
4279  * 
4280  * Note that as the user scrolls around in the entry the offsets will
4281  * change; you'll need to connect to the "notify::scroll-offset"
4282  * signal to track this. Remember when using the #PangoLayout
4283  * functions you need to convert to and from pixels using
4284  * PANGO_PIXELS() or #PANGO_SCALE.
4285  *
4286  * Keep in mind that the layout text may contain a preedit string, so
4287  * gtk_entry_layout_index_to_text_index() and
4288  * gtk_entry_text_index_to_layout_index() are needed to convert byte
4289  * indices in the layout to byte indices in the entry contents.
4290  * 
4291  **/
4292 void
4293 gtk_entry_get_layout_offsets (GtkEntry *entry,
4294                               gint     *x,
4295                               gint     *y)
4296 {
4297   gint text_area_x, text_area_y;
4298   
4299   g_return_if_fail (GTK_IS_ENTRY (entry));
4300
4301   /* this gets coords relative to text area */
4302   get_layout_position (entry, x, y);
4303
4304   /* convert to widget coords */
4305   get_text_area_size (entry, &text_area_x, &text_area_y, NULL, NULL);
4306   
4307   if (x)
4308     *x += text_area_x;
4309
4310   if (y)
4311     *y += text_area_y;
4312 }
4313
4314
4315 /**
4316  * gtk_entry_set_alignment:
4317  * @entry: a #GtkEntry
4318  * @xalign: The horizontal alignment, from 0 (left) to 1 (right).
4319  *          Reversed for RTL layouts
4320  * 
4321  * Sets the alignment for the contents of the entry. This controls
4322  * the horizontal positioning of the contents when the displayed
4323  * text is shorter than the width of the entry.
4324  *
4325  * Since: 2.4
4326  **/
4327 void
4328 gtk_entry_set_alignment (GtkEntry *entry, gfloat xalign)
4329 {
4330   GtkEntryPrivate *priv;
4331   
4332   g_return_if_fail (GTK_IS_ENTRY (entry));
4333
4334   priv = GTK_ENTRY_GET_PRIVATE (entry);
4335
4336   if (xalign < 0.0)
4337     xalign = 0.0;
4338   else if (xalign > 1.0)
4339     xalign = 1.0;
4340
4341   if (xalign != priv->xalign)
4342     {
4343       priv->xalign = xalign;
4344
4345       gtk_entry_recompute (entry);
4346
4347       g_object_notify (G_OBJECT (entry), "xalign");
4348     }
4349 }
4350
4351 /**
4352  * gtk_entry_get_alignment:
4353  * @entry: a #GtkEntry
4354  * 
4355  * Gets the value set by gtk_entry_set_alignment().
4356  * 
4357  * Return value: the alignment
4358  *
4359  * Since: 2.4
4360  **/
4361 gfloat
4362 gtk_entry_get_alignment (GtkEntry *entry)
4363 {
4364   GtkEntryPrivate *priv;
4365   
4366   g_return_val_if_fail (GTK_IS_ENTRY (entry), 0.0);
4367
4368   priv = GTK_ENTRY_GET_PRIVATE (entry);
4369
4370   return priv->xalign;
4371 }
4372
4373 /* Quick hack of a popup menu
4374  */
4375 static void
4376 activate_cb (GtkWidget *menuitem,
4377              GtkEntry  *entry)
4378 {
4379   const gchar *signal = g_object_get_data (G_OBJECT (menuitem), "gtk-signal");
4380   g_signal_emit_by_name (entry, signal);
4381 }
4382
4383
4384 static gboolean
4385 gtk_entry_mnemonic_activate (GtkWidget *widget,
4386                              gboolean   group_cycling)
4387 {
4388   gtk_widget_grab_focus (widget);
4389   return TRUE;
4390 }
4391
4392 static void
4393 append_action_signal (GtkEntry     *entry,
4394                       GtkWidget    *menu,
4395                       const gchar  *stock_id,
4396                       const gchar  *signal,
4397                       gboolean      sensitive)
4398 {
4399   GtkWidget *menuitem = gtk_image_menu_item_new_from_stock (stock_id, NULL);
4400
4401   g_object_set_data (G_OBJECT (menuitem), "gtk-signal", (char *)signal);
4402   g_signal_connect (menuitem, "activate",
4403                     G_CALLBACK (activate_cb), entry);
4404
4405   gtk_widget_set_sensitive (menuitem, sensitive);
4406   
4407   gtk_widget_show (menuitem);
4408   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menuitem);
4409 }
4410         
4411 static void
4412 popup_menu_detach (GtkWidget *attach_widget,
4413                    GtkMenu   *menu)
4414 {
4415   GTK_ENTRY (attach_widget)->popup_menu = NULL;
4416 }
4417
4418 static void
4419 popup_position_func (GtkMenu   *menu,
4420                      gint      *x,
4421                      gint      *y,
4422                      gboolean  *push_in,
4423                      gpointer   user_data)
4424 {
4425   GtkEntry *entry = GTK_ENTRY (user_data);
4426   GtkWidget *widget = GTK_WIDGET (entry);
4427   GdkScreen *screen = gtk_widget_get_screen (widget);
4428   GtkRequisition req;
4429   gint monitor_num;
4430   GdkRectangle monitor;
4431   
4432   g_return_if_fail (GTK_WIDGET_REALIZED (entry));
4433
4434   gdk_window_get_origin (widget->window, x, y); 
4435      
4436   gtk_widget_size_request (entry->popup_menu, &req);
4437   
4438   *x += widget->allocation.width / 2;
4439   *y += widget->allocation.height;
4440
4441   monitor_num = gdk_screen_get_monitor_at_point (screen, *x, *y);
4442   gtk_menu_set_monitor (menu, monitor_num);
4443   gdk_screen_get_monitor_geometry (screen, monitor_num, &monitor);
4444
4445   *x = CLAMP (*x, monitor.x, monitor.x + MAX (0, monitor.width - req.width));
4446   *y = CLAMP (*y, monitor.y, monitor.y + MAX (0, monitor.height - req.height));
4447
4448   *push_in = FALSE;
4449 }
4450
4451
4452 static void
4453 unichar_chosen_func (const char *text,
4454                      gpointer    data)
4455 {
4456   GtkEntry *entry = GTK_ENTRY (data);
4457
4458   if (entry->editable)
4459     gtk_entry_enter_text (entry, text);
4460 }
4461
4462 typedef struct
4463 {
4464   GtkEntry *entry;
4465   gint button;
4466   guint time;
4467 } PopupInfo;
4468
4469 static void
4470 popup_targets_received (GtkClipboard     *clipboard,
4471                         GtkSelectionData *data,
4472                         gpointer          user_data)
4473 {
4474   PopupInfo *info = user_data;
4475   GtkEntry *entry = info->entry;
4476   
4477   if (GTK_WIDGET_REALIZED (entry))
4478     {
4479       gboolean clipboard_contains_text = gtk_selection_data_targets_include_text (data);
4480       GtkWidget *menuitem;
4481       GtkWidget *submenu;
4482       
4483       if (entry->popup_menu)
4484         gtk_widget_destroy (entry->popup_menu);
4485       
4486       entry->popup_menu = gtk_menu_new ();
4487       
4488       gtk_menu_attach_to_widget (GTK_MENU (entry->popup_menu),
4489                                  GTK_WIDGET (entry),
4490                                  popup_menu_detach);
4491       
4492       append_action_signal (entry, entry->popup_menu, GTK_STOCK_CUT, "cut_clipboard",
4493                             entry->editable && entry->current_pos != entry->selection_bound);
4494       append_action_signal (entry, entry->popup_menu, GTK_STOCK_COPY, "copy_clipboard",
4495                             entry->current_pos != entry->selection_bound);
4496       append_action_signal (entry, entry->popup_menu, GTK_STOCK_PASTE, "paste_clipboard",
4497                             entry->editable && clipboard_contains_text);
4498       
4499       menuitem = gtk_image_menu_item_new_from_stock (GTK_STOCK_DELETE, NULL);
4500       gtk_widget_set_sensitive (menuitem, entry->current_pos != entry->selection_bound);
4501       g_signal_connect_swapped (menuitem, "activate",
4502                                 G_CALLBACK (gtk_entry_delete_cb), entry);
4503       gtk_widget_show (menuitem);
4504       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4505
4506       menuitem = gtk_separator_menu_item_new ();
4507       gtk_widget_show (menuitem);
4508       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4509       
4510       menuitem = gtk_menu_item_new_with_mnemonic (_("Select _All"));
4511       g_signal_connect_swapped (menuitem, "activate",
4512                                 G_CALLBACK (gtk_entry_select_all), entry);
4513       gtk_widget_show (menuitem);
4514       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4515       
4516       menuitem = gtk_separator_menu_item_new ();
4517       gtk_widget_show (menuitem);
4518       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4519       
4520       menuitem = gtk_menu_item_new_with_mnemonic (_("Input _Methods"));
4521       gtk_widget_set_sensitive (menuitem, entry->editable);      
4522       gtk_widget_show (menuitem);
4523       submenu = gtk_menu_new ();
4524       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4525       
4526       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);
4527       
4528       gtk_im_multicontext_append_menuitems (GTK_IM_MULTICONTEXT (entry->im_context),
4529                                             GTK_MENU_SHELL (submenu));
4530       
4531       menuitem = gtk_menu_item_new_with_mnemonic (_("_Insert Unicode Control Character"));
4532       gtk_widget_show (menuitem);
4533       
4534       submenu = gtk_menu_new ();
4535       gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
4536       gtk_menu_shell_append (GTK_MENU_SHELL (entry->popup_menu), menuitem);      
4537
4538       _gtk_text_util_append_special_char_menuitems (GTK_MENU_SHELL (submenu),
4539                                                     unichar_chosen_func,
4540                                                     entry);
4541       if (!entry->editable)
4542         gtk_widget_set_sensitive (menuitem, FALSE);
4543       
4544       g_signal_emit (entry,
4545                      signals[POPULATE_POPUP],
4546                      0,
4547                      entry->popup_menu);
4548   
4549
4550       if (info->button)
4551         gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4552                         NULL, NULL,
4553                         info->button, info->time);
4554       else
4555         {
4556           gtk_menu_popup (GTK_MENU (entry->popup_menu), NULL, NULL,
4557                           popup_position_func, entry,
4558                           info->button, info->time);
4559           gtk_menu_shell_select_first (GTK_MENU_SHELL (entry->popup_menu), FALSE);
4560         }
4561     }
4562
4563   g_object_unref (entry);
4564   g_free (info);
4565 }
4566                         
4567 static void
4568 gtk_entry_do_popup (GtkEntry       *entry,
4569                     GdkEventButton *event)
4570 {
4571   PopupInfo *info = g_new (PopupInfo, 1);
4572
4573   /* In order to know what entries we should make sensitive, we
4574    * ask for the current targets of the clipboard, and when
4575    * we get them, then we actually pop up the menu.
4576    */
4577   info->entry = g_object_ref (entry);
4578   
4579   if (event)
4580     {
4581       info->button = event->button;
4582       info->time = event->time;
4583     }
4584   else
4585     {
4586       info->button = 0;
4587       info->time = gtk_get_current_event_time ();
4588     }
4589
4590   gtk_clipboard_request_contents (gtk_widget_get_clipboard (GTK_WIDGET (entry), GDK_SELECTION_CLIPBOARD),
4591                                   gdk_atom_intern ("TARGETS", FALSE),
4592                                   popup_targets_received,
4593                                   info);
4594 }
4595
4596 static gboolean
4597 gtk_entry_popup_menu (GtkWidget *widget)
4598 {
4599   gtk_entry_do_popup (GTK_ENTRY (widget), NULL);
4600   return TRUE;
4601 }
4602
4603 static void
4604 gtk_entry_drag_leave (GtkWidget        *widget,
4605                       GdkDragContext   *context,
4606                       guint             time)
4607 {
4608   GtkEntry *entry = GTK_ENTRY (widget);
4609
4610   entry->dnd_position = -1;
4611   gtk_widget_queue_draw (widget);
4612 }
4613
4614 static gboolean
4615 gtk_entry_drag_drop  (GtkWidget        *widget,
4616                       GdkDragContext   *context,
4617                       gint              x,
4618                       gint              y,
4619                       guint             time)
4620 {
4621   GtkEntry *entry = GTK_ENTRY (widget);
4622   GdkAtom target = GDK_NONE;
4623   
4624   if (entry->editable)
4625     target = gtk_drag_dest_find_target (widget, context, NULL);
4626
4627   if (target != GDK_NONE)
4628     gtk_drag_get_data (widget, context, target, time);
4629   else
4630     gtk_drag_finish (context, FALSE, FALSE, time);
4631   
4632   return TRUE;
4633 }
4634
4635 static gboolean
4636 gtk_entry_drag_motion (GtkWidget        *widget,
4637                        GdkDragContext   *context,
4638                        gint              x,
4639                        gint              y,
4640                        guint             time)
4641 {
4642   GtkEntry *entry = GTK_ENTRY (widget);
4643   GtkWidget *source_widget;
4644   GdkDragAction suggested_action;
4645   gint new_position, old_position;
4646   gint sel1, sel2;
4647   
4648   x -= widget->style->xthickness;
4649   y -= widget->style->ythickness;
4650   
4651   old_position = entry->dnd_position;
4652   new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4653
4654   if (entry->editable &&
4655       gtk_drag_dest_find_target (widget, context, NULL) != GDK_NONE)
4656     {
4657       source_widget = gtk_drag_get_source_widget (context);
4658       suggested_action = context->suggested_action;
4659
4660       if (!gtk_editable_get_selection_bounds (GTK_EDITABLE (entry), &sel1, &sel2) ||
4661           new_position < sel1 || new_position > sel2)
4662         {
4663           if (source_widget == widget)
4664             {
4665               /* Default to MOVE, unless the user has
4666                * pressed ctrl or alt to affect available actions
4667                */
4668               if ((context->actions & GDK_ACTION_MOVE) != 0)
4669                 suggested_action = GDK_ACTION_MOVE;
4670             }
4671               
4672           entry->dnd_position = new_position;
4673         }
4674       else
4675         {
4676           if (source_widget == widget)
4677             suggested_action = 0;       /* Can't drop in selection where drag started */
4678           
4679           entry->dnd_position = -1;
4680         }
4681     }
4682   else
4683     {
4684       /* Entry not editable, or no text */
4685       suggested_action = 0;
4686       entry->dnd_position = -1;
4687     }
4688   
4689   gdk_drag_status (context, suggested_action, time);
4690   
4691   if (entry->dnd_position != old_position)
4692     gtk_widget_queue_draw (widget);
4693
4694   return TRUE;
4695 }
4696
4697 static void
4698 gtk_entry_drag_data_received (GtkWidget        *widget,
4699                               GdkDragContext   *context,
4700                               gint              x,
4701                               gint              y,
4702                               GtkSelectionData *selection_data,
4703                               guint             info,
4704                               guint             time)
4705 {
4706   GtkEntry *entry = GTK_ENTRY (widget);
4707   GtkEditable *editable = GTK_EDITABLE (widget);
4708   gchar *str;
4709
4710   str = gtk_selection_data_get_text (selection_data);
4711
4712   if (str && entry->editable)
4713     {
4714       gint new_position;
4715       gint sel1, sel2;
4716
4717       new_position = gtk_entry_find_position (entry, x + entry->scroll_offset);
4718
4719       if (!gtk_editable_get_selection_bounds (editable, &sel1, &sel2) ||
4720           new_position < sel1 || new_position > sel2)
4721         {
4722           gtk_editable_insert_text (editable, str, -1, &new_position);
4723         }
4724       else
4725         {
4726           /* Replacing selection */
4727           gtk_editable_delete_text (editable, sel1, sel2);
4728           gtk_editable_insert_text (editable, str, -1, &sel1);
4729         }
4730       
4731       g_free (str);
4732       gtk_drag_finish (context, TRUE, context->action == GDK_ACTION_MOVE, time);
4733     }
4734   else
4735     {
4736       /* Drag and drop didn't happen! */
4737       gtk_drag_finish (context, FALSE, FALSE, time);
4738     }
4739 }
4740
4741 static void
4742 gtk_entry_drag_data_get (GtkWidget        *widget,
4743                          GdkDragContext   *context,
4744                          GtkSelectionData *selection_data,
4745                          guint             info,
4746                          guint             time)
4747 {
4748   gint sel_start, sel_end;
4749
4750   GtkEditable *editable = GTK_EDITABLE (widget);
4751   
4752   if (gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4753     {
4754       gchar *str = gtk_entry_get_public_chars (GTK_ENTRY (widget), sel_start, sel_end);
4755
4756       gtk_selection_data_set_text (selection_data, str, -1);
4757       
4758       g_free (str);
4759     }
4760
4761 }
4762
4763 static void
4764 gtk_entry_drag_data_delete (GtkWidget      *widget,
4765                             GdkDragContext *context)
4766 {
4767   gint sel_start, sel_end;
4768
4769   GtkEditable *editable = GTK_EDITABLE (widget);
4770   
4771   if (GTK_ENTRY (widget)->editable &&
4772       gtk_editable_get_selection_bounds (editable, &sel_start, &sel_end))
4773     gtk_editable_delete_text (editable, sel_start, sel_end);
4774 }
4775
4776 /* We display the cursor when
4777  *
4778  *  - the selection is empty, AND
4779  *  - the widget has focus
4780  */
4781
4782 #define CURSOR_ON_MULTIPLIER 0.66
4783 #define CURSOR_OFF_MULTIPLIER 0.34
4784 #define CURSOR_PEND_MULTIPLIER 1.0
4785
4786 static gboolean
4787 cursor_blinks (GtkEntry *entry)
4788 {
4789   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4790   gboolean blink;
4791
4792   if (GTK_WIDGET_HAS_FOCUS (entry) &&
4793       entry->selection_bound == entry->current_pos)
4794     {
4795       g_object_get (settings, "gtk-cursor-blink", &blink, NULL);
4796       return blink;
4797     }
4798   else
4799     return FALSE;
4800 }
4801
4802 static gint
4803 get_cursor_time (GtkEntry *entry)
4804 {
4805   GtkSettings *settings = gtk_widget_get_settings (GTK_WIDGET (entry));
4806   gint time;
4807
4808   g_object_get (settings, "gtk-cursor-blink-time", &time, NULL);
4809
4810   return time;
4811 }
4812
4813 static void
4814 show_cursor (GtkEntry *entry)
4815 {
4816   if (!entry->cursor_visible)
4817     {
4818       entry->cursor_visible = TRUE;
4819
4820       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4821         gtk_widget_queue_draw (GTK_WIDGET (entry));
4822     }
4823 }
4824
4825 static void
4826 hide_cursor (GtkEntry *entry)
4827 {
4828   if (entry->cursor_visible)
4829     {
4830       entry->cursor_visible = FALSE;
4831
4832       if (GTK_WIDGET_HAS_FOCUS (entry) && entry->selection_bound == entry->current_pos)
4833         gtk_widget_queue_draw (GTK_WIDGET (entry));
4834     }
4835 }
4836
4837 /*
4838  * Blink!
4839  */
4840 static gint
4841 blink_cb (gpointer data)
4842 {
4843   GtkEntry *entry;
4844
4845   GDK_THREADS_ENTER ();
4846
4847   entry = GTK_ENTRY (data);
4848
4849   if (!GTK_WIDGET_HAS_FOCUS (entry))
4850     {
4851       g_warning ("GtkEntry - did not receive focus-out-event. If you\n"
4852                  "connect a handler to this signal, it must return\n"
4853                  "FALSE so the entry gets the event as well");
4854     }
4855   
4856   g_assert (GTK_WIDGET_HAS_FOCUS (entry));
4857   g_assert (entry->selection_bound == entry->current_pos);
4858
4859   if (entry->cursor_visible)
4860     {
4861       hide_cursor (entry);
4862       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_OFF_MULTIPLIER,
4863                                             blink_cb,
4864                                             entry);
4865     }
4866   else
4867     {
4868       show_cursor (entry);
4869       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4870                                             blink_cb,
4871                                             entry);
4872     }
4873
4874   GDK_THREADS_LEAVE ();
4875
4876   /* Remove ourselves */
4877   return FALSE;
4878 }
4879
4880 static void
4881 gtk_entry_check_cursor_blink (GtkEntry *entry)
4882 {
4883   if (cursor_blinks (entry))
4884     {
4885       if (!entry->blink_timeout)
4886         {
4887           entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_ON_MULTIPLIER,
4888                                                 blink_cb,
4889                                                 entry);
4890           show_cursor (entry);
4891         }
4892     }
4893   else
4894     {
4895       if (entry->blink_timeout)  
4896         { 
4897           g_source_remove (entry->blink_timeout);
4898           entry->blink_timeout = 0;
4899         }
4900       
4901       entry->cursor_visible = TRUE;
4902     }
4903   
4904 }
4905
4906 static void
4907 gtk_entry_pend_cursor_blink (GtkEntry *entry)
4908 {
4909   if (cursor_blinks (entry))
4910     {
4911       if (entry->blink_timeout != 0)
4912         g_source_remove (entry->blink_timeout);
4913       
4914       entry->blink_timeout = g_timeout_add (get_cursor_time (entry) * CURSOR_PEND_MULTIPLIER,
4915                                             blink_cb,
4916                                             entry);
4917       show_cursor (entry);
4918     }
4919 }
4920
4921 /* completion */
4922 static gint
4923 gtk_entry_completion_timeout (gpointer data)
4924 {
4925   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (data);
4926
4927   GDK_THREADS_ENTER ();
4928
4929   completion->priv->completion_timeout = 0;
4930
4931   if (completion->priv->filter_model &&
4932       g_utf8_strlen (gtk_entry_get_text (GTK_ENTRY (completion->priv->entry)), -1)
4933       >= completion->priv->minimum_key_length)
4934     {
4935       gint matches;
4936       gint actions;
4937       GtkTreeSelection *s;
4938
4939       gtk_entry_completion_complete (completion);
4940       matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4941
4942       gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
4943
4944       s = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view));
4945
4946       gtk_tree_selection_unselect_all (s);
4947
4948       actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
4949
4950       if (matches > 0 || actions > 0)
4951         { 
4952           if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4953             _gtk_entry_completion_resize_popup (completion);
4954           else
4955             _gtk_entry_completion_popup (completion);
4956         }
4957       else 
4958         _gtk_entry_completion_popdown (completion);
4959     }
4960   else if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
4961     _gtk_entry_completion_popdown (completion);
4962
4963   GDK_THREADS_LEAVE ();
4964
4965   return FALSE;
4966 }
4967
4968 static inline gboolean
4969 keyval_is_cursor_move (guint keyval)
4970 {
4971   if (keyval == GDK_Up || keyval == GDK_KP_Up)
4972     return TRUE;
4973
4974   if (keyval == GDK_Down || keyval == GDK_KP_Down)
4975     return TRUE;
4976
4977   if (keyval == GDK_Page_Up)
4978     return TRUE;
4979
4980   if (keyval == GDK_Page_Down)
4981     return TRUE;
4982
4983   return FALSE;
4984 }
4985
4986 static gboolean
4987 gtk_entry_completion_key_press (GtkWidget   *widget,
4988                                 GdkEventKey *event,
4989                                 gpointer     user_data)
4990 {
4991   gint matches, actions = 0;
4992   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
4993
4994   if (!GTK_WIDGET_MAPPED (completion->priv->popup_window))
4995     return FALSE;
4996
4997   matches = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->filter_model), NULL);
4998
4999   if (completion->priv->actions)
5000     actions = gtk_tree_model_iter_n_children (GTK_TREE_MODEL (completion->priv->actions), NULL);
5001
5002   if (keyval_is_cursor_move (event->keyval))
5003     {
5004       GtkTreePath *path = NULL;
5005       
5006       if (event->keyval == GDK_Up || event->keyval == GDK_KP_Up)
5007         {
5008           if (completion->priv->current_selected < 0)
5009             completion->priv->current_selected = matches + actions - 1;
5010           else
5011             completion->priv->current_selected--;
5012         }
5013       else if (event->keyval == GDK_Down || event->keyval == GDK_KP_Down)
5014         {
5015           if (completion->priv->current_selected < matches + actions - 1)
5016             completion->priv->current_selected++;
5017           else
5018             completion->priv->current_selected = -1;
5019         }
5020       else if (event->keyval == GDK_Page_Up)
5021         {
5022           if (completion->priv->current_selected < 0)
5023             completion->priv->current_selected = matches + actions - 1;
5024           else if (completion->priv->current_selected == 0)
5025             completion->priv->current_selected = -1;
5026           else if (completion->priv->current_selected < matches) 
5027             {
5028               completion->priv->current_selected -= 14;
5029               if (completion->priv->current_selected < 0)
5030                 completion->priv->current_selected = 0;
5031             }
5032           else 
5033             {
5034               completion->priv->current_selected -= 14;
5035               if (completion->priv->current_selected < matches - 1)
5036                 completion->priv->current_selected = matches - 1;
5037             }
5038         }
5039       else if (event->keyval == GDK_Page_Down)
5040         {
5041           if (completion->priv->current_selected < 0)
5042             completion->priv->current_selected = 0;
5043           else if (completion->priv->current_selected < matches - 1)
5044             {
5045               completion->priv->current_selected += 14;
5046               if (completion->priv->current_selected > matches - 1)
5047                 completion->priv->current_selected = matches - 1;
5048             }
5049           else if (completion->priv->current_selected == matches + actions - 1)
5050             {
5051               completion->priv->current_selected = -1;
5052             }
5053           else
5054             {
5055               completion->priv->current_selected += 14;
5056               if (completion->priv->current_selected > matches + actions - 1)
5057                 completion->priv->current_selected = matches + actions - 1;
5058             }
5059         }
5060
5061       if (completion->priv->current_selected < 0)
5062         {
5063           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
5064           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
5065         }
5066       else if (completion->priv->current_selected < matches)
5067         {
5068           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->action_view)));
5069
5070           path = gtk_tree_path_new_from_indices (completion->priv->current_selected, -1);
5071           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->tree_view),
5072                                     path, NULL, FALSE);
5073         }
5074       else if (completion->priv->current_selected - matches >= 0)
5075         {
5076           gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view)));
5077
5078           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
5079           gtk_tree_view_set_cursor (GTK_TREE_VIEW (completion->priv->action_view),
5080                                     path, NULL, FALSE);
5081         }
5082
5083       gtk_tree_path_free (path);
5084
5085       return TRUE;
5086     }
5087   else if (event->keyval == GDK_Escape) 
5088     {
5089       _gtk_entry_completion_popdown (completion);
5090
5091       return TRUE;
5092     }
5093   else if (event->keyval == GDK_Tab || 
5094            event->keyval == GDK_KP_Tab ||
5095            event->keyval == GDK_ISO_Left_Tab) 
5096     {
5097       GtkWidget *entry;
5098       GtkDirectionType dir = event->keyval == GDK_ISO_Left_Tab ? 
5099         GTK_DIR_TAB_BACKWARD : GTK_DIR_TAB_FORWARD;
5100
5101       _gtk_entry_completion_popdown (completion);
5102       
5103       entry = gtk_entry_completion_get_entry (completion);
5104
5105       gtk_widget_child_focus (gtk_widget_get_toplevel (entry), dir);
5106
5107       return TRUE;
5108     }
5109   else if (event->keyval == GDK_ISO_Enter ||
5110            event->keyval == GDK_KP_Enter ||
5111            event->keyval == GDK_Return)
5112     {
5113       _gtk_entry_completion_popdown (completion);
5114
5115       if (completion->priv->current_selected < matches)
5116         {
5117           GtkTreeIter iter;
5118           GtkTreeModel *model = NULL;
5119           GtkTreeSelection *sel;
5120           gboolean entry_set;
5121
5122           sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (completion->priv->tree_view));
5123           if (!gtk_tree_selection_get_selected (sel, &model, &iter))
5124             return FALSE;
5125
5126           g_signal_handler_block (completion->priv->entry,
5127                                   completion->priv->changed_id);
5128           g_signal_emit_by_name (completion, "match_selected",
5129                                  model, &iter, &entry_set);
5130           g_signal_handler_unblock (completion->priv->entry,
5131                                     completion->priv->changed_id);
5132
5133           if (!entry_set)
5134             {
5135               gchar *str = NULL;
5136
5137               gtk_tree_model_get (model, &iter,
5138                                   completion->priv->text_column, &str,
5139                                   -1);
5140
5141               g_signal_handler_block (widget, completion->priv->changed_id);
5142               gtk_entry_set_text (GTK_ENTRY (widget), str);
5143               g_signal_handler_unblock (widget, completion->priv->changed_id);
5144
5145               /* move the cursor to the end */
5146               gtk_editable_set_position (GTK_EDITABLE (widget), -1);
5147
5148              g_free (str);
5149             }
5150
5151           return TRUE;
5152         }
5153       else if (completion->priv->current_selected - matches >= 0)
5154         {
5155           GtkTreePath *path;
5156
5157           path = gtk_tree_path_new_from_indices (completion->priv->current_selected - matches, -1);
5158
5159           g_signal_emit_by_name (completion, "action_activated",
5160                                  gtk_tree_path_get_indices (path)[0]);
5161           gtk_tree_path_free (path);
5162
5163           return TRUE;
5164         }
5165     }
5166
5167   return FALSE;
5168 }
5169
5170 static void
5171 gtk_entry_completion_changed (GtkWidget *entry,
5172                               gpointer   user_data)
5173 {
5174   GtkEntryCompletion *completion = GTK_ENTRY_COMPLETION (user_data);
5175
5176   /* (re)install completion timeout */
5177   if (completion->priv->completion_timeout)
5178     g_source_remove (completion->priv->completion_timeout);
5179
5180   if (!gtk_entry_get_text (GTK_ENTRY (entry)))
5181     return;
5182
5183   /* no need to normalize for this test */
5184   if (completion->priv->minimum_key_length > 0 &&
5185       strcmp ("", gtk_entry_get_text (GTK_ENTRY (entry))) == 0)
5186     {
5187       if (GTK_WIDGET_VISIBLE (completion->priv->popup_window))
5188         _gtk_entry_completion_popdown (completion);
5189       return;
5190     }
5191
5192   completion->priv->completion_timeout =
5193     g_timeout_add (COMPLETION_TIMEOUT,
5194                    gtk_entry_completion_timeout,
5195                    completion);
5196 }
5197
5198 static gboolean
5199 check_completion_callback (GtkEntryCompletion *completion)
5200 {
5201   completion->priv->check_completion_idle = NULL;
5202   
5203   gtk_entry_completion_insert_prefix (completion);
5204
5205   return FALSE;
5206 }
5207
5208 static void
5209 clear_completion_callback (GtkEntry   *entry,
5210                            GParamSpec *pspec)
5211 {
5212   GtkEntryCompletion *completion = gtk_entry_get_completion (entry);
5213
5214   completion->priv->has_completion = FALSE;
5215 }
5216
5217 static gboolean
5218 accept_completion_callback (GtkEntry *entry)
5219 {
5220   GtkEntryCompletion *completion = gtk_entry_get_completion (entry);
5221
5222   if (completion->priv->has_completion)
5223     gtk_editable_set_position (GTK_EDITABLE (entry),
5224                                entry->text_length);
5225
5226   return FALSE;
5227 }
5228
5229 static void
5230 completion_insert_text_callback (GtkEntry           *entry,
5231                                  const gchar        *text,
5232                                  gint                length,
5233                                  gint                position,
5234                                  GtkEntryCompletion *completion)
5235 {
5236   /* idle to update the selection based on the file list */
5237   if (completion->priv->check_completion_idle == NULL)
5238     {
5239       completion->priv->check_completion_idle = g_idle_source_new ();
5240       g_source_set_priority (completion->priv->check_completion_idle, G_PRIORITY_HIGH);
5241       g_source_set_closure (completion->priv->check_completion_idle,
5242                             g_cclosure_new_object (G_CALLBACK (check_completion_callback),
5243                                                    G_OBJECT (completion)));
5244       g_source_attach (completion->priv->check_completion_idle, NULL);
5245     }
5246 }
5247
5248 static void
5249 completion_changed (GtkEntryCompletion *completion,
5250                     GParamSpec         *pspec,
5251                     gpointer            data)
5252 {
5253   GtkEntry *entry = GTK_ENTRY (data);
5254
5255   disconnect_completion_signals (entry, completion);
5256   connect_completion_signals (entry, completion);
5257 }
5258
5259 static void
5260 disconnect_completion_signals (GtkEntry           *entry,
5261                                GtkEntryCompletion *completion)
5262 {
5263   g_signal_handlers_disconnect_by_func (completion, 
5264                                        G_CALLBACK (completion_changed), entry);
5265   if (completion->priv->changed_id > 0 &&
5266       g_signal_handler_is_connected (entry, completion->priv->changed_id))
5267     g_signal_handler_disconnect (entry, completion->priv->changed_id);
5268   g_signal_handlers_disconnect_by_func (entry, 
5269                                         G_CALLBACK (gtk_entry_completion_key_press), completion);
5270   if (completion->priv->insert_text_id > 0 &&
5271       g_signal_handler_is_connected (entry, completion->priv->insert_text_id))
5272     g_signal_handler_disconnect (entry, completion->priv->insert_text_id);
5273   g_signal_handlers_disconnect_by_func (entry, 
5274                                         G_CALLBACK (completion_insert_text_callback), completion);
5275   g_signal_handlers_disconnect_by_func (entry, 
5276                                         G_CALLBACK (clear_completion_callback), completion);
5277   g_signal_handlers_disconnect_by_func (entry, 
5278                                         G_CALLBACK (accept_completion_callback), completion);
5279 }
5280
5281 static void
5282 connect_completion_signals (GtkEntry           *entry,
5283                             GtkEntryCompletion *completion)
5284 {
5285   if (completion->priv->popup_completion)
5286     {
5287       completion->priv->changed_id =
5288         g_signal_connect (entry, "changed",
5289                           G_CALLBACK (gtk_entry_completion_changed), completion);
5290       g_signal_connect (entry, "key_press_event",
5291                         G_CALLBACK (gtk_entry_completion_key_press), completion);
5292     }
5293  
5294   if (completion->priv->inline_completion)
5295     {
5296       completion->priv->insert_text_id =
5297         g_signal_connect (entry, "insert_text",
5298                           G_CALLBACK (completion_insert_text_callback), completion);
5299       g_signal_connect (entry, "notify::cursor-position",
5300                         G_CALLBACK (clear_completion_callback), completion);
5301       g_signal_connect (entry, "notify::selection-bound",
5302                         G_CALLBACK (clear_completion_callback), completion);
5303       g_signal_connect (entry, "activate",
5304                         G_CALLBACK (accept_completion_callback), completion);
5305       g_signal_connect (entry, "focus_out_event",
5306                         G_CALLBACK (accept_completion_callback), completion);
5307     }
5308   g_signal_connect (completion, "notify::popup-completion",
5309                     G_CALLBACK (completion_changed), entry);
5310   g_signal_connect (completion, "notify::inline-completion",
5311                     G_CALLBACK (completion_changed), entry);
5312 }
5313
5314 /**
5315  * gtk_entry_set_completion:
5316  * @entry: A #GtkEntry.
5317  * @completion: The #GtkEntryCompletion.
5318  *
5319  * Sets @completion to be the auxiliary completion object to use with @entry.
5320  * All further configuration of the completion mechanism is done on
5321  * @completion using the #GtkEntryCompletion API.
5322  *
5323  * Since: 2.4
5324  */
5325 void
5326 gtk_entry_set_completion (GtkEntry           *entry,
5327                           GtkEntryCompletion *completion)
5328 {
5329   GtkEntryCompletion *old;
5330
5331   g_return_if_fail (GTK_IS_ENTRY (entry));
5332   g_return_if_fail (!completion || GTK_IS_ENTRY_COMPLETION (completion));
5333
5334   old = gtk_entry_get_completion (entry);
5335
5336   if (old == completion)
5337     return;
5338   
5339   if (old)
5340     {
5341       if (old->priv->completion_timeout)
5342         {
5343           g_source_remove (old->priv->completion_timeout);
5344           old->priv->completion_timeout = 0;
5345         }
5346
5347       if (GTK_WIDGET_MAPPED (old->priv->popup_window))
5348         _gtk_entry_completion_popdown (old);
5349
5350       disconnect_completion_signals (entry, old);
5351       old->priv->entry = NULL;
5352
5353       g_object_unref (old);
5354     }
5355
5356   if (!completion)
5357     {
5358       g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, NULL);
5359       return;
5360     }
5361
5362   /* hook into the entry */
5363   g_object_ref (completion);
5364
5365   connect_completion_signals (entry, completion);    
5366   completion->priv->entry = GTK_WIDGET (entry);
5367   g_object_set_data (G_OBJECT (entry), GTK_ENTRY_COMPLETION_KEY, completion);
5368 }
5369
5370 /**
5371  * gtk_entry_get_completion:
5372  * @entry: A #GtkEntry.
5373  *
5374  * Returns the auxiliary completion object currently in use by @entry.
5375  *
5376  * Return value: The auxiliary completion object currently in use by @entry.
5377  *
5378  * Since: 2.4
5379  */
5380 GtkEntryCompletion *
5381 gtk_entry_get_completion (GtkEntry *entry)
5382 {
5383   GtkEntryCompletion *completion;
5384
5385   g_return_val_if_fail (GTK_IS_ENTRY (entry), NULL);
5386
5387   completion = GTK_ENTRY_COMPLETION (g_object_get_data (G_OBJECT (entry),
5388                                      GTK_ENTRY_COMPLETION_KEY));
5389
5390   return completion;
5391 }