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