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