shlwapi: Beginning implementation of IUnknown_QueryServiceForWebBrowserApp.
[wine] / dlls / user32 / edit.c
1 /*
2  *      Edit control
3  *
4  *      Copyright  David W. Metcalfe, 1994
5  *      Copyright  William Magro, 1995, 1996
6  *      Copyright  Frans van Dorsselaer, 1996, 1997
7  *
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  * NOTES
24  *
25  * This code was audited for completeness against the documented features
26  * of Comctl32.dll version 6.0 on Oct. 8, 2004, by Dimitrie O. Paun.
27  * 
28  * Unless otherwise noted, we believe this code to be complete, as per
29  * the specification mentioned above.
30  * If you discover missing features, or bugs, please note them below.
31  *
32  * TODO:
33  *   - EDITBALLOONTIP structure
34  *   - EM_GETCUEBANNER/Edit_GetCueBannerText
35  *   - EM_HIDEBALLOONTIP/Edit_HideBalloonTip
36  *   - EM_SETCUEBANNER/Edit_SetCueBannerText
37  *   - EM_SHOWBALLOONTIP/Edit_ShowBalloonTip
38  *   - EM_GETIMESTATUS, EM_SETIMESTATUS
39  *   - EN_ALIGN_LTR_EC
40  *   - EN_ALIGN_RTL_EC
41  *   - ES_OEMCONVERT
42  *
43  */
44
45 #include "config.h"
46
47 #include <stdarg.h>
48 #include <string.h>
49 #include <stdlib.h>
50
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winnt.h"
54 #include "wownt32.h"
55 #include "win.h"
56 #include "imm.h"
57 #include "wine/winbase16.h"
58 #include "wine/winuser16.h"
59 #include "wine/unicode.h"
60 #include "controls.h"
61 #include "user_private.h"
62 #include "wine/debug.h"
63
64 WINE_DEFAULT_DEBUG_CHANNEL(edit);
65 WINE_DECLARE_DEBUG_CHANNEL(combo);
66 WINE_DECLARE_DEBUG_CHANNEL(relay);
67
68 #define BUFLIMIT_INITIAL    30000   /* initial buffer size */
69 #define GROWLENGTH              32      /* buffers granularity in bytes: must be power of 2 */
70 #define ROUND_TO_GROW(size)     (((size) + (GROWLENGTH - 1)) & ~(GROWLENGTH - 1))
71 #define HSCROLL_FRACTION        3       /* scroll window by 1/3 width */
72
73 /*
74  *      extra flags for EDITSTATE.flags field
75  */
76 #define EF_MODIFIED             0x0001  /* text has been modified */
77 #define EF_FOCUSED              0x0002  /* we have input focus */
78 #define EF_UPDATE               0x0004  /* notify parent of changed state */
79 #define EF_VSCROLL_TRACK        0x0008  /* don't SetScrollPos() since we are tracking the thumb */
80 #define EF_HSCROLL_TRACK        0x0010  /* don't SetScrollPos() since we are tracking the thumb */
81 #define EF_AFTER_WRAP           0x0080  /* the caret is displayed after the last character of a
82                                            wrapped line, instead of in front of the next character */
83 #define EF_USE_SOFTBRK          0x0100  /* Enable soft breaks in text. */
84 #define EF_APP_HAS_HANDLE       0x0200  /* Set when an app sends EM_[G|S]ETHANDLE.  We are in sole control of
85                                            the text buffer if this is clear. */
86 #define EF_DIALOGMODE           0x0400  /* Indicates that we are inside a dialog window */
87
88 typedef enum
89 {
90         END_0 = 0,                      /* line ends with terminating '\0' character */
91         END_WRAP,                       /* line is wrapped */
92         END_HARD,                       /* line ends with a hard return '\r\n' */
93         END_SOFT,                       /* line ends with a soft return '\r\r\n' */
94         END_RICH                        /* line ends with a single '\n' */
95 } LINE_END;
96
97 typedef struct tagLINEDEF {
98         INT length;                     /* bruto length of a line in bytes */
99         INT net_length;                 /* netto length of a line in visible characters */
100         LINE_END ending;
101         INT width;                      /* width of the line in pixels */
102         INT index;                      /* line index into the buffer */
103         struct tagLINEDEF *next;
104 } LINEDEF;
105
106 typedef struct
107 {
108         BOOL is_unicode;                /* how the control was created */
109         LPWSTR text;                    /* the actual contents of the control */
110         UINT text_length;               /* cached length of text buffer (in WCHARs) - use get_text_length() to retrieve */
111         UINT buffer_size;               /* the size of the buffer in characters */
112         UINT buffer_limit;              /* the maximum size to which the buffer may grow in characters */
113         HFONT font;                     /* NULL means standard system font */
114         INT x_offset;                   /* scroll offset        for multi lines this is in pixels
115                                                                 for single lines it's in characters */
116         INT line_height;                /* height of a screen line in pixels */
117         INT char_width;                 /* average character width in pixels */
118         DWORD style;                    /* sane version of wnd->dwStyle */
119         WORD flags;                     /* flags that are not in es->style or wnd->flags (EF_XXX) */
120         INT undo_insert_count;          /* number of characters inserted in sequence */
121         UINT undo_position;             /* character index of the insertion and deletion */
122         LPWSTR undo_text;               /* deleted text */
123         UINT undo_buffer_size;          /* size of the deleted text buffer */
124         INT selection_start;            /* == selection_end if no selection */
125         INT selection_end;              /* == current caret position */
126         WCHAR password_char;            /* == 0 if no password char, and for multi line controls */
127         INT left_margin;                /* in pixels */
128         INT right_margin;               /* in pixels */
129         RECT format_rect;
130         INT text_width;                 /* width of the widest line in pixels for multi line controls
131                                            and just line width for single line controls */
132         INT region_posx;                /* Position of cursor relative to region: */
133         INT region_posy;                /* -1: to left, 0: within, 1: to right */
134         void *word_break_proc;          /* 32-bit word break proc: ANSI or Unicode */
135         INT line_count;                 /* number of lines */
136         INT y_offset;                   /* scroll offset in number of lines */
137         BOOL bCaptureState;             /* flag indicating whether mouse was captured */
138         BOOL bEnableState;              /* flag keeping the enable state */
139         HWND hwndSelf;                  /* the our window handle */
140         HWND hwndParent;                /* Handle of parent for sending EN_* messages.
141                                            Even if parent will change, EN_* messages
142                                            should be sent to the first parent. */
143         HWND hwndListBox;               /* handle of ComboBox's listbox or NULL */
144         /*
145          *      only for multi line controls
146          */
147         INT lock_count;                 /* amount of re-entries in the EditWndProc */
148         INT tabs_count;
149         LPINT tabs;
150         LINEDEF *first_line_def;        /* linked list of (soft) linebreaks */
151         HLOCAL hloc32W;                 /* our unicode local memory block */
152         HLOCAL hloc32A;                 /* alias for ANSI control receiving EM_GETHANDLE
153                                            or EM_SETHANDLE */
154         /*
155          * IME Data
156          */
157         UINT composition_len;   /* length of composition, 0 == no composition */
158         int composition_start;  /* the character position for the composition */
159 } EDITSTATE;
160
161
162 #define SWAP_UINT32(x,y) do { UINT temp = (UINT)(x); (x) = (UINT)(y); (y) = temp; } while(0)
163 #define ORDER_UINT(x,y) do { if ((UINT)(y) < (UINT)(x)) SWAP_UINT32((x),(y)); } while(0)
164
165 /* used for disabled or read-only edit control */
166 #define EDIT_NOTIFY_PARENT(es, wNotifyCode) \
167         do \
168         { /* Notify parent which has created this edit control */ \
169             TRACE("notification " #wNotifyCode " sent to hwnd=%p\n", es->hwndParent); \
170             SendMessageW(es->hwndParent, WM_COMMAND, \
171                      MAKEWPARAM(GetWindowLongPtrW((es->hwndSelf),GWLP_ID), wNotifyCode), \
172                      (LPARAM)(es->hwndSelf)); \
173         } while(0)
174
175
176 /*********************************************************************
177  *
178  *      EM_CANUNDO
179  *
180  */
181 static inline BOOL EDIT_EM_CanUndo(const EDITSTATE *es)
182 {
183         return (es->undo_insert_count || strlenW(es->undo_text));
184 }
185
186
187 /*********************************************************************
188  *
189  *      EM_EMPTYUNDOBUFFER
190  *
191  */
192 static inline void EDIT_EM_EmptyUndoBuffer(EDITSTATE *es)
193 {
194         es->undo_insert_count = 0;
195         *es->undo_text = '\0';
196 }
197
198
199 /**********************************************************************
200  *         get_app_version
201  *
202  * Returns the window version in case Wine emulates a later version
203  * of windows than the application expects.
204  *
205  * In a number of cases when windows runs an application that was
206  * designed for an earlier windows version, windows reverts
207  * to "old" behaviour of that earlier version.
208  *
209  * An example is a disabled  edit control that needs to be painted.
210  * Old style behaviour is to send a WM_CTLCOLOREDIT message. This was
211  * changed in Win95, NT4.0 by a WM_CTLCOLORSTATIC message _only_ for
212  * applications with an expected version 0f 4.0 or higher.
213  *
214  */
215 static DWORD get_app_version(void)
216 {
217     static DWORD version;
218     if (!version)
219     {
220         DWORD dwEmulatedVersion;
221         OSVERSIONINFOW info;
222         DWORD dwProcVersion = GetProcessVersion(0);
223
224         info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
225         GetVersionExW( &info );
226         dwEmulatedVersion = MAKELONG( info.dwMinorVersion, info.dwMajorVersion );
227         /* FIXME: this may not be 100% correct; see discussion on the
228          * wine developer list in Nov 1999 */
229         version = dwProcVersion < dwEmulatedVersion ? dwProcVersion : dwEmulatedVersion;
230     }
231     return version;
232 }
233
234 static HBRUSH EDIT_NotifyCtlColor(EDITSTATE *es, HDC hdc)
235 {
236         HBRUSH hbrush;
237         UINT msg;
238
239         if ( get_app_version() >= 0x40000 && (!es->bEnableState || (es->style & ES_READONLY)))
240                 msg = WM_CTLCOLORSTATIC;
241         else
242                 msg = WM_CTLCOLOREDIT;
243
244         /* why do we notify to es->hwndParent, and we send this one to GetParent()? */
245         hbrush = (HBRUSH)SendMessageW(GetParent(es->hwndSelf), msg, (WPARAM)hdc, (LPARAM)es->hwndSelf);
246         if (!hbrush)
247             hbrush = (HBRUSH)DefWindowProcW(GetParent(es->hwndSelf), msg, (WPARAM)hdc, (LPARAM)es->hwndSelf);
248         return hbrush;
249 }
250
251
252 /**********************************************************************
253  * Support for word break proc thunks
254  */
255
256 #define MAX_THUNKS 32
257
258 #include <pshpack1.h>
259 static struct word_break_thunk
260 {
261     BYTE                popl_eax;       /* popl  %eax (return address) */
262     BYTE                pushl_proc16;   /* pushl proc16 */
263     EDITWORDBREAKPROC16 proc16;
264     BYTE                pushl_eax;      /* pushl %eax */
265     BYTE                jmp;            /* ljmp call_word_break_proc16 */
266     DWORD               callback;
267 } *word_break_thunks;
268 #include <poppack.h>
269
270 /**********************************************************************
271  *           call_word_break_proc16
272  */
273 static INT16 CALLBACK call_word_break_proc16( SEGPTR proc16, LPSTR text, INT index, INT count, INT action )
274 {
275     SEGPTR segptr;
276     WORD args[5];
277     DWORD result;
278
279     segptr = MapLS( text );
280     args[4] = SELECTOROF(segptr);
281     args[3] = OFFSETOF(segptr);
282     args[2] = index;
283     args[1] = count;
284     args[0] = action;
285     WOWCallback16Ex( proc16, WCB16_PASCAL, sizeof(args), args, &result );
286     UnMapLS( segptr );
287     return LOWORD(result);
288 }
289
290 /******************************************************************
291  *              add_word_break_thunk
292  */
293 static struct word_break_thunk *add_word_break_thunk( EDITWORDBREAKPROC16 proc16 )
294 {
295     struct word_break_thunk *thunk;
296
297     if (!word_break_thunks)
298     {
299         word_break_thunks = VirtualAlloc( NULL, MAX_THUNKS * sizeof(*thunk),
300                                           MEM_COMMIT, PAGE_EXECUTE_READWRITE );
301         if (!word_break_thunks) return NULL;
302
303         for (thunk = word_break_thunks; thunk < &word_break_thunks[MAX_THUNKS]; thunk++)
304         {
305             thunk->popl_eax     = 0x58;   /* popl  %eax */
306             thunk->pushl_proc16 = 0x68;   /* pushl proc16 */
307             thunk->pushl_eax    = 0x50;   /* pushl %eax */
308             thunk->jmp          = 0xe9;   /* jmp call_word_break_proc16 */
309             thunk->callback     = (char *)call_word_break_proc16 - (char *)(&thunk->callback + 1);
310         }
311     }
312     for (thunk = word_break_thunks; thunk < &word_break_thunks[MAX_THUNKS]; thunk++)
313         if (thunk->proc16 == proc16) return thunk;
314
315     for (thunk = word_break_thunks; thunk < &word_break_thunks[MAX_THUNKS]; thunk++)
316     {
317         if (thunk->proc16) continue;
318         thunk->proc16 = proc16;
319         return thunk;
320     }
321     FIXME("Out of word break thunks\n");
322     return NULL;
323 }
324
325 /******************************************************************
326  *              get_word_break_thunk
327  */
328 static EDITWORDBREAKPROC16 get_word_break_thunk( EDITWORDBREAKPROCA proc )
329 {
330     struct word_break_thunk *thunk = (struct word_break_thunk *)proc;
331     if (word_break_thunks && thunk >= word_break_thunks && thunk < &word_break_thunks[MAX_THUNKS])
332         return thunk->proc16;
333     return NULL;
334 }
335
336 /*********************************************************************
337  *
338  *      EDIT_WordBreakProc
339  *
340  *      Find the beginning of words.
341  *      Note:   unlike the specs for a WordBreakProc, this function only
342  *              allows to be called without linebreaks between s[0] up to
343  *              s[count - 1].  Remember it is only called
344  *              internally, so we can decide this for ourselves.
345  *
346  */
347 static INT EDIT_WordBreakProc(LPWSTR s, INT index, INT count, INT action)
348 {
349         INT ret = 0;
350
351         TRACE("s=%p, index=%d, count=%d, action=%d\n", s, index, count, action);
352
353         if(!s) return 0;
354
355         switch (action) {
356         case WB_LEFT:
357                 if (!count)
358                         break;
359                 if (index)
360                         index--;
361                 if (s[index] == ' ') {
362                         while (index && (s[index] == ' '))
363                                 index--;
364                         if (index) {
365                                 while (index && (s[index] != ' '))
366                                         index--;
367                                 if (s[index] == ' ')
368                                         index++;
369                         }
370                 } else {
371                         while (index && (s[index] != ' '))
372                                 index--;
373                         if (s[index] == ' ')
374                                 index++;
375                 }
376                 ret = index;
377                 break;
378         case WB_RIGHT:
379                 if (!count)
380                         break;
381                 if (index)
382                         index--;
383                 if (s[index] == ' ')
384                         while ((index < count) && (s[index] == ' ')) index++;
385                 else {
386                         while (s[index] && (s[index] != ' ') && (index < count))
387                                 index++;
388                         while ((s[index] == ' ') && (index < count)) index++;
389                 }
390                 ret = index;
391                 break;
392         case WB_ISDELIMITER:
393                 ret = (s[index] == ' ');
394                 break;
395         default:
396                 ERR("unknown action code, please report !\n");
397                 break;
398         }
399         return ret;
400 }
401
402
403 /*********************************************************************
404  *
405  *      EDIT_CallWordBreakProc
406  *
407  *      Call appropriate WordBreakProc (internal or external).
408  *
409  *      Note: The "start" argument should always be an index referring
410  *              to es->text.  The actual wordbreak proc might be
411  *              16 bit, so we can't always pass any 32 bit LPSTR.
412  *              Hence we assume that es->text is the buffer that holds
413  *              the string under examination (we can decide this for ourselves).
414  *
415  */
416 static INT EDIT_CallWordBreakProc(EDITSTATE *es, INT start, INT index, INT count, INT action)
417 {
418         INT ret;
419
420         if (es->word_break_proc)
421         {
422             if(es->is_unicode)
423             {
424                 EDITWORDBREAKPROCW wbpW = (EDITWORDBREAKPROCW)es->word_break_proc;
425
426                 TRACE_(relay)("(UNICODE wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
427                         es->word_break_proc, debugstr_wn(es->text + start, count), index, count, action);
428                 ret = wbpW(es->text + start, index, count, action);
429             }
430             else
431             {
432                 EDITWORDBREAKPROCA wbpA = (EDITWORDBREAKPROCA)es->word_break_proc;
433                 INT countA;
434                 CHAR *textA;
435
436                 countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
437                 textA = HeapAlloc(GetProcessHeap(), 0, countA);
438                 WideCharToMultiByte(CP_ACP, 0, es->text + start, count, textA, countA, NULL, NULL);
439                 TRACE_(relay)("(ANSI wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
440                         es->word_break_proc, debugstr_an(textA, countA), index, countA, action);
441                 ret = wbpA(textA, index, countA, action);
442                 HeapFree(GetProcessHeap(), 0, textA);
443             }
444         }
445         else
446             ret = EDIT_WordBreakProc(es->text + start, index, count, action);
447
448         return ret;
449 }
450
451 /*********************************************************************
452  *
453  *      EDIT_BuildLineDefs_ML
454  *
455  *      Build linked list of text lines.
456  *      Lines can end with '\0' (last line), a character (if it is wrapped),
457  *      a soft return '\r\r\n' or a hard return '\r\n'
458  *
459  */
460 static void EDIT_BuildLineDefs_ML(EDITSTATE *es, INT istart, INT iend, INT delta, HRGN hrgn)
461 {
462         HDC dc;
463         HFONT old_font = 0;
464         LPWSTR current_position, cp;
465         INT fw;
466         LINEDEF *current_line;
467         LINEDEF *previous_line;
468         LINEDEF *start_line;
469         INT line_index = 0, nstart_line = 0, nstart_index = 0;
470         INT line_count = es->line_count;
471         INT orig_net_length;
472         RECT rc;
473
474         if (istart == iend && delta == 0)
475                 return;
476
477         dc = GetDC(es->hwndSelf);
478         if (es->font)
479                 old_font = SelectObject(dc, es->font);
480
481         previous_line = NULL;
482         current_line = es->first_line_def;
483
484         /* Find starting line. istart must lie inside an existing line or
485          * at the end of buffer */
486         do {
487                 if (istart < current_line->index + current_line->length ||
488                                 current_line->ending == END_0)
489                         break;
490
491                 previous_line = current_line;
492                 current_line = current_line->next;
493                 line_index++;
494         } while (current_line);
495
496         if (!current_line) /* Error occurred start is not inside previous buffer */
497         {
498                 FIXME(" modification occurred outside buffer\n");
499                 ReleaseDC(es->hwndSelf, dc);
500                 return;
501         }
502
503         /* Remember start of modifications in order to calculate update region */
504         nstart_line = line_index;
505         nstart_index = current_line->index;
506
507         /* We must start to reformat from the previous line since the modifications
508          * may have caused the line to wrap upwards. */
509         if (!(es->style & ES_AUTOHSCROLL) && line_index > 0)
510         {
511                 line_index--;
512                 current_line = previous_line;
513         }
514         start_line = current_line;
515
516         fw = es->format_rect.right - es->format_rect.left;
517         current_position = es->text + current_line->index;
518         do {
519                 if (current_line != start_line)
520                 {
521                         if (!current_line || current_line->index + delta > current_position - es->text)
522                         {
523                                 /* The buffer has been expanded, create a new line and
524                                    insert it into the link list */
525                                 LINEDEF *new_line = HeapAlloc(GetProcessHeap(), 0, sizeof(LINEDEF));
526                                 new_line->next = previous_line->next;
527                                 previous_line->next = new_line;
528                                 current_line = new_line;
529                                 es->line_count++;
530                         }
531                         else if (current_line->index + delta < current_position - es->text)
532                         {
533                                 /* The previous line merged with this line so we delete this extra entry */
534                                 previous_line->next = current_line->next;
535                                 HeapFree(GetProcessHeap(), 0, current_line);
536                                 current_line = previous_line->next;
537                                 es->line_count--;
538                                 continue;
539                         }
540                         else /* current_line->index + delta == current_position */
541                         {
542                                 if (current_position - es->text > iend)
543                                         break; /* We reached end of line modifications */
544                                 /* else recalculate this line */
545                         }
546                 }
547
548                 current_line->index = current_position - es->text;
549                 orig_net_length = current_line->net_length;
550
551                 /* Find end of line */
552                 cp = current_position;
553                 while (*cp) {
554                     if (*cp == '\n') break;
555                         if ((*cp == '\r') && (*(cp + 1) == '\n'))
556                                 break;
557                         cp++;
558                 }
559
560                 /* Mark type of line termination */
561                 if (!(*cp)) {
562                         current_line->ending = END_0;
563                         current_line->net_length = strlenW(current_position);
564                 } else if ((cp > current_position) && (*(cp - 1) == '\r')) {
565                         current_line->ending = END_SOFT;
566                         current_line->net_length = cp - current_position - 1;
567                 } else if (*cp == '\n') {
568                         current_line->ending = END_RICH;
569                         current_line->net_length = cp - current_position;
570                 } else {
571                         current_line->ending = END_HARD;
572                         current_line->net_length = cp - current_position;
573                 }
574
575                 /* Calculate line width */
576                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
577                                         current_position, current_line->net_length,
578                                         es->tabs_count, es->tabs));
579
580                 /* FIXME: check here for lines that are too wide even in AUTOHSCROLL (> 32767 ???) */
581                 if (!(es->style & ES_AUTOHSCROLL)) {
582                    if (current_line->width > fw) {
583                         INT next = 0;
584                         INT prev;
585                         do {
586                                 prev = next;
587                                 next = EDIT_CallWordBreakProc(es, current_position - es->text,
588                                                 prev + 1, current_line->net_length, WB_RIGHT);
589                                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
590                                                         current_position, next, es->tabs_count, es->tabs));
591                         } while (current_line->width <= fw);
592                         if (!prev) { /* Didn't find a line break so force a break */
593                                 next = 0;
594                                 do {
595                                         prev = next;
596                                         next++;
597                                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
598                                                                 current_position, next, es->tabs_count, es->tabs));
599                                 } while (current_line->width <= fw);
600                                 if (!prev)
601                                         prev = 1;
602                         }
603
604                         /* If the first line we are calculating, wrapped before istart, we must
605                          * adjust istart in order for this to be reflected in the update region. */
606                         if (current_line->index == nstart_index && istart > current_line->index + prev)
607                                 istart = current_line->index + prev;
608                         /* else if we are updating the previous line before the first line we
609                          * are re-calculating and it expanded */
610                         else if (current_line == start_line &&
611                                         current_line->index != nstart_index && orig_net_length < prev)
612                         {
613                           /* Line expanded due to an upwards line wrap so we must partially include
614                            * previous line in update region */
615                                 nstart_line = line_index;
616                                 nstart_index = current_line->index;
617                                 istart = current_line->index + orig_net_length;
618                         }
619
620                         current_line->net_length = prev;
621                         current_line->ending = END_WRAP;
622                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc, current_position,
623                                         current_line->net_length, es->tabs_count, es->tabs));
624                     }
625                     else if (current_line == start_line &&
626                              current_line->index != nstart_index &&
627                              orig_net_length < current_line->net_length) {
628                         /* The previous line expanded but it's still not as wide as the client rect */
629                         /* The expansion is due to an upwards line wrap so we must partially include
630                            it in the update region */
631                         nstart_line = line_index;
632                         nstart_index = current_line->index;
633                         istart = current_line->index + orig_net_length;
634                     }
635                 }
636
637
638                 /* Adjust length to include line termination */
639                 switch (current_line->ending) {
640                 case END_SOFT:
641                         current_line->length = current_line->net_length + 3;
642                         break;
643                 case END_RICH:
644                         current_line->length = current_line->net_length + 1;
645                         break;
646                 case END_HARD:
647                         current_line->length = current_line->net_length + 2;
648                         break;
649                 case END_WRAP:
650                 case END_0:
651                         current_line->length = current_line->net_length;
652                         break;
653                 }
654                 es->text_width = max(es->text_width, current_line->width);
655                 current_position += current_line->length;
656                 previous_line = current_line;
657                 current_line = current_line->next;
658                 line_index++;
659         } while (previous_line->ending != END_0);
660
661         /* Finish adjusting line indexes by delta or remove hanging lines */
662         if (previous_line->ending == END_0)
663         {
664                 LINEDEF *pnext = NULL;
665
666                 previous_line->next = NULL;
667                 while (current_line)
668                 {
669                         pnext = current_line->next;
670                         HeapFree(GetProcessHeap(), 0, current_line);
671                         current_line = pnext;
672                         es->line_count--;
673                 }
674         }
675         else if (delta != 0)
676         {
677                 while (current_line)
678                 {
679                         current_line->index += delta;
680                         current_line = current_line->next;
681                 }
682         }
683
684         /* Calculate rest of modification rectangle */
685         if (hrgn)
686         {
687                 HRGN tmphrgn;
688            /*
689                 * We calculate two rectangles. One for the first line which may have
690                 * an indent with respect to the format rect. The other is a format-width
691                 * rectangle that spans the rest of the lines that changed or moved.
692                 */
693                 rc.top = es->format_rect.top + nstart_line * es->line_height -
694                         (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
695                 rc.bottom = rc.top + es->line_height;
696                 if ((es->style & ES_CENTER) || (es->style & ES_RIGHT))
697                         rc.left = es->format_rect.left;
698                 else
699                         rc.left = es->format_rect.left + (INT)LOWORD(GetTabbedTextExtentW(dc,
700                                         es->text + nstart_index, istart - nstart_index,
701                                         es->tabs_count, es->tabs)) - es->x_offset; /* Adjust for horz scroll */
702                 rc.right = es->format_rect.right;
703                 SetRectRgn(hrgn, rc.left, rc.top, rc.right, rc.bottom);
704
705                 rc.top = rc.bottom;
706                 rc.left = es->format_rect.left;
707                 rc.right = es->format_rect.right;
708            /*
709                 * If lines were added or removed we must re-paint the remainder of the
710             * lines since the remaining lines were either shifted up or down.
711                 */
712                 if (line_count < es->line_count) /* We added lines */
713                         rc.bottom = es->line_count * es->line_height;
714                 else if (line_count > es->line_count) /* We removed lines */
715                         rc.bottom = line_count * es->line_height;
716                 else
717                         rc.bottom = line_index * es->line_height;
718                 rc.bottom += es->format_rect.top;
719                 rc.bottom -= (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
720                 tmphrgn = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
721                 CombineRgn(hrgn, hrgn, tmphrgn, RGN_OR);
722                 DeleteObject(tmphrgn);
723         }
724
725         if (es->font)
726                 SelectObject(dc, old_font);
727
728         ReleaseDC(es->hwndSelf, dc);
729 }
730
731
732 static inline UINT get_text_length(EDITSTATE *es)
733 {
734     if(es->text_length == (UINT)-1)
735         es->text_length = strlenW(es->text);
736     return es->text_length;
737 }
738
739 /*********************************************************************
740  *
741  *      EDIT_GetPasswordPointer_SL
742  *
743  *      note: caller should free the (optionally) allocated buffer
744  *
745  */
746 static LPWSTR EDIT_GetPasswordPointer_SL(EDITSTATE *es)
747 {
748         if (es->style & ES_PASSWORD) {
749                 INT len = get_text_length(es);
750                 LPWSTR text = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
751                 text[len] = '\0';
752                 while(len) text[--len] = es->password_char;
753                 return text;
754         } else
755                 return es->text;
756 }
757
758
759 /*********************************************************************
760  *
761  *      EDIT_CalcLineWidth_SL
762  *
763  */
764 static void EDIT_CalcLineWidth_SL(EDITSTATE *es)
765 {
766         SIZE size;
767         LPWSTR text;
768         HDC dc;
769         HFONT old_font = 0;
770
771         text = EDIT_GetPasswordPointer_SL(es);
772
773         dc = GetDC(es->hwndSelf);
774         if (es->font)
775                 old_font = SelectObject(dc, es->font);
776
777         GetTextExtentPoint32W(dc, text, strlenW(text), &size);
778
779         if (es->font)
780                 SelectObject(dc, old_font);
781         ReleaseDC(es->hwndSelf, dc);
782
783         if (es->style & ES_PASSWORD)
784                 HeapFree(GetProcessHeap(), 0, text);
785
786         es->text_width = size.cx;
787 }
788
789 /*********************************************************************
790  *
791  *      EDIT_CharFromPos
792  *
793  *      Beware: This is not the function called on EM_CHARFROMPOS
794  *              The position _can_ be outside the formatting / client
795  *              rectangle
796  *              The return value is only the character index
797  *
798  */
799 static INT EDIT_CharFromPos(EDITSTATE *es, INT x, INT y, LPBOOL after_wrap)
800 {
801         INT index;
802         HDC dc;
803         HFONT old_font = 0;
804         INT x_high = 0, x_low = 0;
805
806         if (es->style & ES_MULTILINE) {
807                 INT line = (y - es->format_rect.top) / es->line_height + es->y_offset;
808                 INT line_index = 0;
809                 LINEDEF *line_def = es->first_line_def;
810                 INT low, high;
811                 while ((line > 0) && line_def->next) {
812                         line_index += line_def->length;
813                         line_def = line_def->next;
814                         line--;
815                 }
816                 x += es->x_offset - es->format_rect.left;
817                 if (es->style & ES_RIGHT)
818                         x -= (es->format_rect.right - es->format_rect.left) - line_def->width;
819                 else if (es->style & ES_CENTER)
820                         x -= ((es->format_rect.right - es->format_rect.left) - line_def->width) / 2;
821                 if (x >= line_def->width) {
822                         if (after_wrap)
823                                 *after_wrap = (line_def->ending == END_WRAP);
824                         return line_index + line_def->net_length;
825                 }
826                 if (x <= 0) {
827                         if (after_wrap)
828                                 *after_wrap = FALSE;
829                         return line_index;
830                 }
831                 dc = GetDC(es->hwndSelf);
832                 if (es->font)
833                         old_font = SelectObject(dc, es->font);
834                     low = line_index;
835                     high = line_index + line_def->net_length + 1;
836                     while (low < high - 1)
837                     {
838                         INT mid = (low + high) / 2;
839                         INT x_now = LOWORD(GetTabbedTextExtentW(dc, es->text + line_index, mid - line_index, es->tabs_count, es->tabs));
840                         if (x_now > x) {
841                             high = mid;
842                             x_high = x_now;
843                         } else {
844                             low = mid;
845                             x_low = x_now;
846                         }
847                     }
848                     if (abs(x_high - x) + 1 <= abs(x_low - x))
849                         index = high;
850                     else
851                         index = low;
852
853                 if (after_wrap)
854                         *after_wrap = ((index == line_index + line_def->net_length) &&
855                                                         (line_def->ending == END_WRAP));
856         } else {
857                 LPWSTR text;
858                 SIZE size;
859                 if (after_wrap)
860                         *after_wrap = FALSE;
861                 x -= es->format_rect.left;
862                 if (!x)
863                         return es->x_offset;
864
865                 if (!es->x_offset)
866                 {
867                         INT indent = (es->format_rect.right - es->format_rect.left) - es->text_width;
868                         if (es->style & ES_RIGHT)
869                                 x -= indent;
870                         else if (es->style & ES_CENTER)
871                                 x -= indent / 2;
872                 }
873
874                 text = EDIT_GetPasswordPointer_SL(es);
875                 dc = GetDC(es->hwndSelf);
876                 if (es->font)
877                         old_font = SelectObject(dc, es->font);
878                 if (x < 0)
879                 {
880                     INT low = 0;
881                     INT high = es->x_offset;
882                     while (low < high - 1)
883                     {
884                         INT mid = (low + high) / 2;
885                         GetTextExtentPoint32W( dc, text + mid,
886                                                es->x_offset - mid, &size );
887                         if (size.cx > -x) {
888                             low = mid;
889                             x_low = size.cx;
890                         } else {
891                             high = mid;
892                             x_high = size.cx;
893                         }
894                     }
895                     if (abs(x_high + x) <= abs(x_low + x) + 1)
896                         index = high;
897                     else
898                         index = low;
899                 }
900                 else
901                 {
902                     INT low = es->x_offset;
903                     INT high = get_text_length(es) + 1;
904                     while (low < high - 1)
905                     {
906                         INT mid = (low + high) / 2;
907                         GetTextExtentPoint32W( dc, text + es->x_offset,
908                                                mid - es->x_offset, &size );
909                         if (size.cx > x) {
910                                high = mid;
911                                x_high = size.cx;
912                         } else {
913                                low = mid;
914                                x_low = size.cx;
915                        }
916                     }
917                    if (abs(x_high - x) <= abs(x_low - x) + 1)
918                        index = high;
919                    else
920                        index = low;
921                 }
922                 if (es->style & ES_PASSWORD)
923                         HeapFree(GetProcessHeap(), 0, text);
924         }
925         if (es->font)
926                 SelectObject(dc, old_font);
927         ReleaseDC(es->hwndSelf, dc);
928         return index;
929 }
930
931
932 /*********************************************************************
933  *
934  *      EDIT_ConfinePoint
935  *
936  *      adjusts the point to be within the formatting rectangle
937  *      (so CharFromPos returns the nearest _visible_ character)
938  *
939  */
940 static void EDIT_ConfinePoint(const EDITSTATE *es, LPINT x, LPINT y)
941 {
942         *x = min(max(*x, es->format_rect.left), es->format_rect.right - 1);
943         *y = min(max(*y, es->format_rect.top), es->format_rect.bottom - 1);
944 }
945
946
947 /*********************************************************************
948  *
949  *      EM_LINEFROMCHAR
950  *
951  */
952 static INT EDIT_EM_LineFromChar(EDITSTATE *es, INT index)
953 {
954         INT line;
955         LINEDEF *line_def;
956
957         if (!(es->style & ES_MULTILINE))
958                 return 0;
959         if (index > (INT)get_text_length(es))
960                 return es->line_count - 1;
961         if (index == -1)
962                 index = min(es->selection_start, es->selection_end);
963
964         line = 0;
965         line_def = es->first_line_def;
966         index -= line_def->length;
967         while ((index >= 0) && line_def->next) {
968                 line++;
969                 line_def = line_def->next;
970                 index -= line_def->length;
971         }
972         return line;
973 }
974
975
976 /*********************************************************************
977  *
978  *      EM_LINEINDEX
979  *
980  */
981 static INT EDIT_EM_LineIndex(const EDITSTATE *es, INT line)
982 {
983         INT line_index;
984         const LINEDEF *line_def;
985
986         if (!(es->style & ES_MULTILINE))
987                 return 0;
988         if (line >= es->line_count)
989                 return -1;
990
991         line_index = 0;
992         line_def = es->first_line_def;
993         if (line == -1) {
994                 INT index = es->selection_end - line_def->length;
995                 while ((index >= 0) && line_def->next) {
996                         line_index += line_def->length;
997                         line_def = line_def->next;
998                         index -= line_def->length;
999                 }
1000         } else {
1001                 while (line > 0) {
1002                         line_index += line_def->length;
1003                         line_def = line_def->next;
1004                         line--;
1005                 }
1006         }
1007         return line_index;
1008 }
1009
1010
1011 /*********************************************************************
1012  *
1013  *      EM_LINELENGTH
1014  *
1015  */
1016 static INT EDIT_EM_LineLength(EDITSTATE *es, INT index)
1017 {
1018         LINEDEF *line_def;
1019
1020         if (!(es->style & ES_MULTILINE))
1021                 return get_text_length(es);
1022
1023         if (index == -1) {
1024                 /* get the number of remaining non-selected chars of selected lines */
1025                 INT32 l; /* line number */
1026                 INT32 li; /* index of first char in line */
1027                 INT32 count;
1028                 l = EDIT_EM_LineFromChar(es, es->selection_start);
1029                 /* # chars before start of selection area */
1030                 count = es->selection_start - EDIT_EM_LineIndex(es, l);
1031                 l = EDIT_EM_LineFromChar(es, es->selection_end);
1032                 /* # chars after end of selection */
1033                 li = EDIT_EM_LineIndex(es, l);
1034                 count += li + EDIT_EM_LineLength(es, li) - es->selection_end;
1035                 return count;
1036         }
1037         line_def = es->first_line_def;
1038         index -= line_def->length;
1039         while ((index >= 0) && line_def->next) {
1040                 line_def = line_def->next;
1041                 index -= line_def->length;
1042         }
1043         return line_def->net_length;
1044 }
1045
1046
1047 /*********************************************************************
1048  *
1049  *      EM_POSFROMCHAR
1050  *
1051  */
1052 static LRESULT EDIT_EM_PosFromChar(EDITSTATE *es, INT index, BOOL after_wrap)
1053 {
1054         INT len = get_text_length(es);
1055         INT l;
1056         INT li;
1057         INT x;
1058         INT y = 0;
1059         INT w;
1060         INT lw = 0;
1061         INT ll = 0;
1062         HDC dc;
1063         HFONT old_font = 0;
1064         SIZE size;
1065         LINEDEF *line_def;
1066
1067         index = min(index, len);
1068         dc = GetDC(es->hwndSelf);
1069         if (es->font)
1070                 old_font = SelectObject(dc, es->font);
1071         if (es->style & ES_MULTILINE) {
1072                 l = EDIT_EM_LineFromChar(es, index);
1073                 y = (l - es->y_offset) * es->line_height;
1074                 li = EDIT_EM_LineIndex(es, l);
1075                 if (after_wrap && (li == index) && l) {
1076                         INT l2 = l - 1;
1077                         line_def = es->first_line_def;
1078                         while (l2) {
1079                                 line_def = line_def->next;
1080                                 l2--;
1081                         }
1082                         if (line_def->ending == END_WRAP) {
1083                                 l--;
1084                                 y -= es->line_height;
1085                                 li = EDIT_EM_LineIndex(es, l);
1086                         }
1087                 }
1088
1089                 line_def = es->first_line_def;
1090                 while (line_def->index != li)
1091                         line_def = line_def->next;
1092
1093                 ll = line_def->net_length;
1094                 lw = line_def->width;
1095
1096                 w = es->format_rect.right - es->format_rect.left;
1097                 if (es->style & ES_RIGHT)
1098                 {
1099                         x = LOWORD(GetTabbedTextExtentW(dc, es->text + li + (index - li), ll - (index - li),
1100                                 es->tabs_count, es->tabs)) - es->x_offset;
1101                         x = w - x;
1102                 }
1103                 else if (es->style & ES_CENTER)
1104                 {
1105                         x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
1106                                 es->tabs_count, es->tabs)) - es->x_offset;
1107                         x += (w - lw) / 2;
1108                 }
1109                 else /* ES_LEFT */
1110                 {
1111                     x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
1112                                 es->tabs_count, es->tabs)) - es->x_offset;
1113                 }
1114         } else {
1115                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
1116                 if (index < es->x_offset) {
1117                         GetTextExtentPoint32W(dc, text + index,
1118                                         es->x_offset - index, &size);
1119                         x = -size.cx;
1120                 } else {
1121                         GetTextExtentPoint32W(dc, text + es->x_offset,
1122                                         index - es->x_offset, &size);
1123                          x = size.cx;
1124
1125                         if (!es->x_offset && (es->style & (ES_RIGHT | ES_CENTER)))
1126                         {
1127                                 w = es->format_rect.right - es->format_rect.left;
1128                                 if (w > es->text_width)
1129                                 {
1130                                         if (es->style & ES_RIGHT)
1131                                                 x += w - es->text_width;
1132                                         else if (es->style & ES_CENTER)
1133                                                 x += (w - es->text_width) / 2;
1134                                 }
1135                         }
1136                 }
1137                 y = 0;
1138                 if (es->style & ES_PASSWORD)
1139                         HeapFree(GetProcessHeap(), 0, text);
1140         }
1141         x += es->format_rect.left;
1142         y += es->format_rect.top;
1143         if (es->font)
1144                 SelectObject(dc, old_font);
1145         ReleaseDC(es->hwndSelf, dc);
1146         return MAKELONG((INT16)x, (INT16)y);
1147 }
1148
1149
1150 /*********************************************************************
1151  *
1152  *      EDIT_GetLineRect
1153  *
1154  *      Calculates the bounding rectangle for a line from a starting
1155  *      column to an ending column.
1156  *
1157  */
1158 static void EDIT_GetLineRect(EDITSTATE *es, INT line, INT scol, INT ecol, LPRECT rc)
1159 {
1160         INT line_index =  EDIT_EM_LineIndex(es, line);
1161
1162         if (es->style & ES_MULTILINE)
1163                 rc->top = es->format_rect.top + (line - es->y_offset) * es->line_height;
1164         else
1165                 rc->top = es->format_rect.top;
1166         rc->bottom = rc->top + es->line_height;
1167         rc->left = (scol == 0) ? es->format_rect.left : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + scol, TRUE));
1168         rc->right = (ecol == -1) ? es->format_rect.right : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + ecol, TRUE));
1169 }
1170
1171
1172 static inline void text_buffer_changed(EDITSTATE *es)
1173 {
1174     es->text_length = (UINT)-1;
1175 }
1176
1177 #define GWW_HANDLE16 sizeof(EDITSTATE*)
1178
1179 /*********************************************************************
1180  *      EDIT_LockBuffer16
1181  */
1182 static void EDIT_LockBuffer16(EDITSTATE *es)
1183 {
1184     STACK16FRAME* stack16 = MapSL(PtrToUlong(NtCurrentTeb()->WOW32Reserved));
1185     HLOCAL16 hloc16 = GetWindowWord( es->hwndSelf, GWW_HANDLE16 );
1186     HANDLE16 oldDS;
1187     HLOCAL hloc32;
1188     UINT size;
1189
1190     if (!hloc16) return;
1191     if (!(hloc32 = es->hloc32A)) return;
1192
1193     oldDS = stack16->ds;
1194     stack16->ds = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
1195     size = LocalSize16(hloc16);
1196     if (LocalReAlloc( hloc32, size, LMEM_MOVEABLE ))
1197     {
1198         char *text = MapSL( LocalLock16( hloc16 ));
1199         char *dest = LocalLock( hloc32 );
1200         memcpy( dest, text, size );
1201         LocalUnlock( hloc32 );
1202         LocalUnlock16( hloc16 );
1203     }
1204     stack16->ds = oldDS;
1205
1206 }
1207
1208 /*********************************************************************
1209  *      EDIT_UnlockBuffer16
1210  *
1211  */
1212 static void EDIT_UnlockBuffer16(EDITSTATE *es)
1213 {
1214     STACK16FRAME* stack16 = MapSL(PtrToUlong(NtCurrentTeb()->WOW32Reserved));
1215     HLOCAL16 hloc16 = GetWindowWord( es->hwndSelf, GWW_HANDLE16 );
1216     HANDLE16 oldDS;
1217     HLOCAL hloc32;
1218     UINT size;
1219
1220     if (!hloc16) return;
1221     if (!(hloc32 = es->hloc32A)) return;
1222     size = LocalSize( hloc32 );
1223
1224     oldDS = stack16->ds;
1225     stack16->ds = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
1226     if (LocalReAlloc16( hloc16, size, LMEM_MOVEABLE ))
1227     {
1228         char *text = LocalLock( hloc32 );
1229         char *dest = MapSL( LocalLock16( hloc16 ));
1230         memcpy( dest, text, size );
1231         LocalUnlock( hloc32 );
1232         LocalUnlock16( hloc16 );
1233     }
1234     stack16->ds = oldDS;
1235 }
1236
1237 /*********************************************************************
1238  *
1239  *      EDIT_LockBuffer
1240  *
1241  *      This acts as a LocalLock16(), but it locks only once.  This way
1242  *      you can call it whenever you like, without unlocking.
1243  *
1244  *      Initially the edit control allocates a HLOCAL32 buffer 
1245  *      (32 bit linear memory handler).  However, 16 bit application
1246  *      might send an EM_GETHANDLE message and expect a HLOCAL16 (16 bit SEG:OFF
1247  *      handler).  From that moment on we have to keep using this 16 bit memory
1248  *      handler, because it is supposed to be valid at all times after EM_GETHANDLE.
1249  *      What we do is create a HLOCAL16 buffer, copy the text, and do pointer
1250  *      conversion.
1251  *
1252  */
1253 static void EDIT_LockBuffer(EDITSTATE *es)
1254 {
1255         if (!es->text) {
1256
1257             if(!es->hloc32W) return;
1258
1259             EDIT_LockBuffer16(es);
1260
1261             if(es->hloc32A)
1262             {
1263                 CHAR *textA = LocalLock(es->hloc32A);
1264                 HLOCAL hloc32W_new;
1265                 UINT countW_new = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
1266                 if(countW_new > es->buffer_size + 1)
1267                 {
1268                     UINT alloc_size = ROUND_TO_GROW(countW_new * sizeof(WCHAR));
1269                     TRACE("Resizing 32-bit UNICODE buffer from %d+1 to %d WCHARs\n", es->buffer_size, countW_new);
1270                     hloc32W_new = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
1271                     if(hloc32W_new)
1272                     {
1273                         es->hloc32W = hloc32W_new;
1274                         es->buffer_size = LocalSize(hloc32W_new)/sizeof(WCHAR) - 1;
1275                         TRACE("Real new size %d+1 WCHARs\n", es->buffer_size);
1276                     }
1277                     else
1278                         WARN("FAILED! Will synchronize partially\n");
1279                 }
1280                 es->text = LocalLock(es->hloc32W);
1281                 MultiByteToWideChar(CP_ACP, 0, textA, -1, es->text, es->buffer_size + 1);
1282                 LocalUnlock(es->hloc32A);
1283             }
1284             else es->text = LocalLock(es->hloc32W);
1285         }
1286         if(es->flags & EF_APP_HAS_HANDLE) text_buffer_changed(es);
1287         es->lock_count++;
1288 }
1289
1290
1291 /*********************************************************************
1292  *
1293  *      EDIT_UnlockBuffer
1294  *
1295  */
1296 static void EDIT_UnlockBuffer(EDITSTATE *es, BOOL force)
1297 {
1298
1299         /* Edit window might be already destroyed */
1300         if(!IsWindow(es->hwndSelf))
1301         {
1302             WARN("edit hwnd %p already destroyed\n", es->hwndSelf);
1303             return;
1304         }
1305
1306         if (!es->lock_count) {
1307                 ERR("lock_count == 0 ... please report\n");
1308                 return;
1309         }
1310         if (!es->text) {
1311                 ERR("es->text == 0 ... please report\n");
1312                 return;
1313         }
1314
1315         if (force || (es->lock_count == 1)) {
1316             if (es->hloc32W) {
1317                 UINT countA = 0;
1318                 UINT countW = get_text_length(es) + 1;
1319
1320                 if(es->hloc32A)
1321                 {
1322                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
1323                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
1324                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
1325                     countA = LocalSize(es->hloc32A);
1326                     if(countA_new > countA)
1327                     {
1328                         HLOCAL hloc32A_new;
1329                         UINT alloc_size = ROUND_TO_GROW(countA_new);
1330                         TRACE("Resizing 32-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
1331                         hloc32A_new = LocalReAlloc(es->hloc32A, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
1332                         if(hloc32A_new)
1333                         {
1334                             es->hloc32A = hloc32A_new;
1335                             countA = LocalSize(hloc32A_new);
1336                             TRACE("Real new size %d bytes\n", countA);
1337                         }
1338                         else
1339                             WARN("FAILED! Will synchronize partially\n");
1340                     }
1341                     WideCharToMultiByte(CP_ACP, 0, es->text, countW,
1342                                         LocalLock(es->hloc32A), countA, NULL, NULL);
1343                     LocalUnlock(es->hloc32A);
1344                 }
1345
1346                 LocalUnlock(es->hloc32W);
1347                 es->text = NULL;
1348                 EDIT_UnlockBuffer16(es);
1349             }
1350             else {
1351                 ERR("no buffer ... please report\n");
1352                 return;
1353             }
1354         }
1355         es->lock_count--;
1356 }
1357
1358
1359 /*********************************************************************
1360  *
1361  *      EDIT_MakeFit
1362  *
1363  * Try to fit size + 1 characters in the buffer.
1364  */
1365 static BOOL EDIT_MakeFit(EDITSTATE *es, UINT size)
1366 {
1367         HLOCAL hNew32W;
1368
1369         if (size <= es->buffer_size)
1370                 return TRUE;
1371
1372         TRACE("trying to ReAlloc to %d+1 characters\n", size);
1373
1374         /* Force edit to unlock it's buffer. es->text now NULL */
1375         EDIT_UnlockBuffer(es, TRUE);
1376
1377         if (es->hloc32W) {
1378             UINT alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1379             if ((hNew32W = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT))) {
1380                 TRACE("Old 32 bit handle %p, new handle %p\n", es->hloc32W, hNew32W);
1381                 es->hloc32W = hNew32W;
1382                 es->buffer_size = LocalSize(hNew32W)/sizeof(WCHAR) - 1;
1383             }
1384         }
1385
1386         EDIT_LockBuffer(es);
1387
1388         if (es->buffer_size < size) {
1389                 WARN("FAILED !  We now have %d+1\n", es->buffer_size);
1390                 EDIT_NOTIFY_PARENT(es, EN_ERRSPACE);
1391                 return FALSE;
1392         } else {
1393                 TRACE("We now have %d+1\n", es->buffer_size);
1394                 return TRUE;
1395         }
1396 }
1397
1398
1399 /*********************************************************************
1400  *
1401  *      EDIT_MakeUndoFit
1402  *
1403  *      Try to fit size + 1 bytes in the undo buffer.
1404  *
1405  */
1406 static BOOL EDIT_MakeUndoFit(EDITSTATE *es, UINT size)
1407 {
1408         UINT alloc_size;
1409
1410         if (size <= es->undo_buffer_size)
1411                 return TRUE;
1412
1413         TRACE("trying to ReAlloc to %d+1\n", size);
1414
1415         alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1416         if ((es->undo_text = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, es->undo_text, alloc_size))) {
1417                 es->undo_buffer_size = alloc_size/sizeof(WCHAR) - 1;
1418                 return TRUE;
1419         }
1420         else
1421         {
1422                 WARN("FAILED !  We now have %d+1\n", es->undo_buffer_size);
1423                 return FALSE;
1424         }
1425 }
1426
1427
1428 /*********************************************************************
1429  *
1430  *      EDIT_UpdateTextRegion
1431  *
1432  */
1433 static void EDIT_UpdateTextRegion(EDITSTATE *es, HRGN hrgn, BOOL bErase)
1434 {
1435     if (es->flags & EF_UPDATE) {
1436         es->flags &= ~EF_UPDATE;
1437         EDIT_NOTIFY_PARENT(es, EN_UPDATE);
1438     }
1439     InvalidateRgn(es->hwndSelf, hrgn, bErase);
1440 }
1441
1442
1443 /*********************************************************************
1444  *
1445  *      EDIT_UpdateText
1446  *
1447  */
1448 static void EDIT_UpdateText(EDITSTATE *es, const RECT *rc, BOOL bErase)
1449 {
1450     if (es->flags & EF_UPDATE) {
1451         es->flags &= ~EF_UPDATE;
1452         EDIT_NOTIFY_PARENT(es, EN_UPDATE);
1453     }
1454     InvalidateRect(es->hwndSelf, rc, bErase);
1455 }
1456
1457 /*********************************************************************
1458  *
1459  *      EDIT_SL_InvalidateText
1460  *
1461  *      Called from EDIT_InvalidateText().
1462  *      Does the job for single-line controls only.
1463  *
1464  */
1465 static void EDIT_SL_InvalidateText(EDITSTATE *es, INT start, INT end)
1466 {
1467         RECT line_rect;
1468         RECT rc;
1469
1470         EDIT_GetLineRect(es, 0, start, end, &line_rect);
1471         if (IntersectRect(&rc, &line_rect, &es->format_rect))
1472                 EDIT_UpdateText(es, &rc, TRUE);
1473 }
1474
1475
1476 static inline INT get_vertical_line_count(EDITSTATE *es)
1477 {
1478         INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1479         return max(1,vlc);
1480 }
1481
1482 /*********************************************************************
1483  *
1484  *      EDIT_ML_InvalidateText
1485  *
1486  *      Called from EDIT_InvalidateText().
1487  *      Does the job for multi-line controls only.
1488  *
1489  */
1490 static void EDIT_ML_InvalidateText(EDITSTATE *es, INT start, INT end)
1491 {
1492         INT vlc = get_vertical_line_count(es);
1493         INT sl = EDIT_EM_LineFromChar(es, start);
1494         INT el = EDIT_EM_LineFromChar(es, end);
1495         INT sc;
1496         INT ec;
1497         RECT rc1;
1498         RECT rcWnd;
1499         RECT rcLine;
1500         RECT rcUpdate;
1501         INT l;
1502
1503         if ((el < es->y_offset) || (sl > es->y_offset + vlc))
1504                 return;
1505
1506         sc = start - EDIT_EM_LineIndex(es, sl);
1507         ec = end - EDIT_EM_LineIndex(es, el);
1508         if (sl < es->y_offset) {
1509                 sl = es->y_offset;
1510                 sc = 0;
1511         }
1512         if (el > es->y_offset + vlc) {
1513                 el = es->y_offset + vlc;
1514                 ec = EDIT_EM_LineLength(es, EDIT_EM_LineIndex(es, el));
1515         }
1516         GetClientRect(es->hwndSelf, &rc1);
1517         IntersectRect(&rcWnd, &rc1, &es->format_rect);
1518         if (sl == el) {
1519                 EDIT_GetLineRect(es, sl, sc, ec, &rcLine);
1520                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1521                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1522         } else {
1523                 EDIT_GetLineRect(es, sl, sc,
1524                                 EDIT_EM_LineLength(es,
1525                                         EDIT_EM_LineIndex(es, sl)),
1526                                 &rcLine);
1527                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1528                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1529                 for (l = sl + 1 ; l < el ; l++) {
1530                         EDIT_GetLineRect(es, l, 0,
1531                                 EDIT_EM_LineLength(es,
1532                                         EDIT_EM_LineIndex(es, l)),
1533                                 &rcLine);
1534                         if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1535                                 EDIT_UpdateText(es, &rcUpdate, TRUE);
1536                 }
1537                 EDIT_GetLineRect(es, el, 0, ec, &rcLine);
1538                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1539                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1540         }
1541 }
1542
1543
1544 /*********************************************************************
1545  *
1546  *      EDIT_InvalidateText
1547  *
1548  *      Invalidate the text from offset start up to, but not including,
1549  *      offset end.  Useful for (re)painting the selection.
1550  *      Regions outside the linewidth are not invalidated.
1551  *      end == -1 means end == TextLength.
1552  *      start and end need not be ordered.
1553  *
1554  */
1555 static void EDIT_InvalidateText(EDITSTATE *es, INT start, INT end)
1556 {
1557         if (end == start)
1558                 return;
1559
1560         if (end == -1)
1561                 end = get_text_length(es);
1562
1563         if (end < start) {
1564             INT tmp = start;
1565             start = end;
1566             end = tmp;
1567         }
1568
1569         if (es->style & ES_MULTILINE)
1570                 EDIT_ML_InvalidateText(es, start, end);
1571         else
1572                 EDIT_SL_InvalidateText(es, start, end);
1573 }
1574
1575
1576 /*********************************************************************
1577  *
1578  *      EDIT_EM_SetSel
1579  *
1580  *      note:   unlike the specs say: the order of start and end
1581  *              _is_ preserved in Windows.  (i.e. start can be > end)
1582  *              In other words: this handler is OK
1583  *
1584  */
1585 static void EDIT_EM_SetSel(EDITSTATE *es, UINT start, UINT end, BOOL after_wrap)
1586 {
1587         UINT old_start = es->selection_start;
1588         UINT old_end = es->selection_end;
1589         UINT len = get_text_length(es);
1590
1591         if (start == (UINT)-1) {
1592                 start = es->selection_end;
1593                 end = es->selection_end;
1594         } else {
1595                 start = min(start, len);
1596                 end = min(end, len);
1597         }
1598         es->selection_start = start;
1599         es->selection_end = end;
1600         if (after_wrap)
1601                 es->flags |= EF_AFTER_WRAP;
1602         else
1603                 es->flags &= ~EF_AFTER_WRAP;
1604         /* Compute the necessary invalidation region. */
1605         /* Note that we don't need to invalidate regions which have
1606          * "never" been selected, or those which are "still" selected.
1607          * In fact, every time we hit a selection boundary, we can
1608          * *toggle* whether we need to invalidate.  Thus we can optimize by
1609          * *sorting* the interval endpoints.  Let's assume that we sort them
1610          * in this order:
1611          *        start <= end <= old_start <= old_end
1612          * Knuth 5.3.1 (p 183) assures us that this can be done optimally
1613          * in 5 comparisons; i.e. it is impossible to do better than the
1614          * following: */
1615         ORDER_UINT(end, old_end);
1616         ORDER_UINT(start, old_start);
1617         ORDER_UINT(old_start, old_end);
1618         ORDER_UINT(start, end);
1619         /* Note that at this point 'end' and 'old_start' are not in order, but
1620          * start is definitely the min. and old_end is definitely the max. */
1621         if (end != old_start)
1622         {
1623 /*
1624  * One can also do
1625  *          ORDER_UINT32(end, old_start);
1626  *          EDIT_InvalidateText(es, start, end);
1627  *          EDIT_InvalidateText(es, old_start, old_end);
1628  * in place of the following if statement.
1629  * (That would complete the optimal five-comparison four-element sort.)
1630  */
1631             if (old_start > end )
1632             {
1633                 EDIT_InvalidateText(es, start, end);
1634                 EDIT_InvalidateText(es, old_start, old_end);
1635             }
1636             else
1637             {
1638                 EDIT_InvalidateText(es, start, old_start);
1639                 EDIT_InvalidateText(es, end, old_end);
1640             }
1641         }
1642         else EDIT_InvalidateText(es, start, old_end);
1643 }
1644
1645
1646 /*********************************************************************
1647  *
1648  *      EDIT_UpdateScrollInfo
1649  *
1650  */
1651 static void EDIT_UpdateScrollInfo(EDITSTATE *es)
1652 {
1653     if ((es->style & WS_VSCROLL) && !(es->flags & EF_VSCROLL_TRACK))
1654     {
1655         SCROLLINFO si;
1656         si.cbSize       = sizeof(SCROLLINFO);
1657         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
1658         si.nMin         = 0;
1659         si.nMax         = es->line_count - 1;
1660         si.nPage        = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1661         si.nPos         = es->y_offset;
1662         TRACE("SB_VERT, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
1663                 si.nMin, si.nMax, si.nPage, si.nPos);
1664         SetScrollInfo(es->hwndSelf, SB_VERT, &si, TRUE);
1665     }
1666
1667     if ((es->style & WS_HSCROLL) && !(es->flags & EF_HSCROLL_TRACK))
1668     {
1669         SCROLLINFO si;
1670         si.cbSize       = sizeof(SCROLLINFO);
1671         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
1672         si.nMin         = 0;
1673         si.nMax         = es->text_width - 1;
1674         si.nPage        = es->format_rect.right - es->format_rect.left;
1675         si.nPos         = es->x_offset;
1676         TRACE("SB_HORZ, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
1677                 si.nMin, si.nMax, si.nPage, si.nPos);
1678         SetScrollInfo(es->hwndSelf, SB_HORZ, &si, TRUE);
1679     }
1680 }
1681
1682
1683 /*********************************************************************
1684  *
1685  *      EDIT_EM_LineScroll_internal
1686  *
1687  *      Version of EDIT_EM_LineScroll for internal use.
1688  *      It doesn't refuse if ES_MULTILINE is set and assumes that
1689  *      dx is in pixels, dy - in lines.
1690  *
1691  */
1692 static BOOL EDIT_EM_LineScroll_internal(EDITSTATE *es, INT dx, INT dy)
1693 {
1694         INT nyoff;
1695         INT x_offset_in_pixels;
1696         INT lines_per_page = (es->format_rect.bottom - es->format_rect.top) /
1697                               es->line_height;
1698
1699         if (es->style & ES_MULTILINE)
1700         {
1701             x_offset_in_pixels = es->x_offset;
1702         }
1703         else
1704         {
1705             dy = 0;
1706             x_offset_in_pixels = (short)LOWORD(EDIT_EM_PosFromChar(es, es->x_offset, FALSE));
1707         }
1708
1709         if (-dx > x_offset_in_pixels)
1710                 dx = -x_offset_in_pixels;
1711         if (dx > es->text_width - x_offset_in_pixels)
1712                 dx = es->text_width - x_offset_in_pixels;
1713         nyoff = max(0, es->y_offset + dy);
1714         if (nyoff >= es->line_count - lines_per_page)
1715                 nyoff = max(0, es->line_count - lines_per_page);
1716         dy = (es->y_offset - nyoff) * es->line_height;
1717         if (dx || dy) {
1718                 RECT rc1;
1719                 RECT rc;
1720
1721                 es->y_offset = nyoff;
1722                 if(es->style & ES_MULTILINE)
1723                     es->x_offset += dx;
1724                 else
1725                     es->x_offset += dx / es->char_width;
1726
1727                 GetClientRect(es->hwndSelf, &rc1);
1728                 IntersectRect(&rc, &rc1, &es->format_rect);
1729                 ScrollWindowEx(es->hwndSelf, -dx, dy,
1730                                 NULL, &rc, NULL, NULL, SW_INVALIDATE);
1731                 /* force scroll info update */
1732                 EDIT_UpdateScrollInfo(es);
1733         }
1734         if (dx && !(es->flags & EF_HSCROLL_TRACK))
1735                 EDIT_NOTIFY_PARENT(es, EN_HSCROLL);
1736         if (dy && !(es->flags & EF_VSCROLL_TRACK))
1737                 EDIT_NOTIFY_PARENT(es, EN_VSCROLL);
1738         return TRUE;
1739 }
1740
1741 /*********************************************************************
1742  *
1743  *      EM_LINESCROLL
1744  *
1745  *      NOTE: dx is in average character widths, dy - in lines;
1746  *
1747  */
1748 static BOOL EDIT_EM_LineScroll(EDITSTATE *es, INT dx, INT dy)
1749 {
1750         if (!(es->style & ES_MULTILINE))
1751                 return FALSE;
1752
1753         dx *= es->char_width;
1754         return EDIT_EM_LineScroll_internal(es, dx, dy);
1755 }
1756
1757
1758 /*********************************************************************
1759  *
1760  *      EM_SCROLL
1761  *
1762  */
1763 static LRESULT EDIT_EM_Scroll(EDITSTATE *es, INT action)
1764 {
1765         INT dy;
1766
1767         if (!(es->style & ES_MULTILINE))
1768                 return (LRESULT)FALSE;
1769
1770         dy = 0;
1771
1772         switch (action) {
1773         case SB_LINEUP:
1774                 if (es->y_offset)
1775                         dy = -1;
1776                 break;
1777         case SB_LINEDOWN:
1778                 if (es->y_offset < es->line_count - 1)
1779                         dy = 1;
1780                 break;
1781         case SB_PAGEUP:
1782                 if (es->y_offset)
1783                         dy = -(es->format_rect.bottom - es->format_rect.top) / es->line_height;
1784                 break;
1785         case SB_PAGEDOWN:
1786                 if (es->y_offset < es->line_count - 1)
1787                         dy = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1788                 break;
1789         default:
1790                 return (LRESULT)FALSE;
1791         }
1792         if (dy) {
1793             INT vlc = get_vertical_line_count(es);
1794             /* check if we are going to move too far */
1795             if(es->y_offset + dy > es->line_count - vlc)
1796                 dy = es->line_count - vlc - es->y_offset;
1797
1798             /* Notification is done in EDIT_EM_LineScroll */
1799             if(dy)
1800                 EDIT_EM_LineScroll(es, 0, dy);
1801         }
1802         return MAKELONG((INT16)dy, (BOOL16)TRUE);
1803 }
1804
1805
1806 /*********************************************************************
1807  *
1808  *      EDIT_SetCaretPos
1809  *
1810  */
1811 static void EDIT_SetCaretPos(EDITSTATE *es, INT pos,
1812                              BOOL after_wrap)
1813 {
1814         LRESULT res = EDIT_EM_PosFromChar(es, pos, after_wrap);
1815         TRACE("%d - %dx%d\n", pos, (short)LOWORD(res), (short)HIWORD(res));
1816         SetCaretPos((short)LOWORD(res), (short)HIWORD(res));
1817 }
1818
1819
1820 /*********************************************************************
1821  *
1822  *      EM_SCROLLCARET
1823  *
1824  */
1825 static void EDIT_EM_ScrollCaret(EDITSTATE *es)
1826 {
1827         if (es->style & ES_MULTILINE) {
1828                 INT l;
1829                 INT vlc;
1830                 INT ww;
1831                 INT cw = es->char_width;
1832                 INT x;
1833                 INT dy = 0;
1834                 INT dx = 0;
1835
1836                 l = EDIT_EM_LineFromChar(es, es->selection_end);
1837                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP));
1838                 vlc = get_vertical_line_count(es);
1839                 if (l >= es->y_offset + vlc)
1840                         dy = l - vlc + 1 - es->y_offset;
1841                 if (l < es->y_offset)
1842                         dy = l - es->y_offset;
1843                 ww = es->format_rect.right - es->format_rect.left;
1844                 if (x < es->format_rect.left)
1845                         dx = x - es->format_rect.left - ww / HSCROLL_FRACTION / cw * cw;
1846                 if (x > es->format_rect.right)
1847                         dx = x - es->format_rect.left - (HSCROLL_FRACTION - 1) * ww / HSCROLL_FRACTION / cw * cw;
1848                 if (dy || dx || (es->y_offset && (es->line_count - es->y_offset < vlc)))
1849                 {
1850                     /* check if we are going to move too far */
1851                     if(es->x_offset + dx + ww > es->text_width)
1852                         dx = es->text_width - ww - es->x_offset;
1853                     if(dx || dy || (es->y_offset && (es->line_count - es->y_offset < vlc)))
1854                         EDIT_EM_LineScroll_internal(es, dx, dy);
1855                 }
1856         } else {
1857                 INT x;
1858                 INT goal;
1859                 INT format_width;
1860
1861                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
1862                 format_width = es->format_rect.right - es->format_rect.left;
1863                 if (x < es->format_rect.left) {
1864                         goal = es->format_rect.left + format_width / HSCROLL_FRACTION;
1865                         do {
1866                                 es->x_offset--;
1867                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
1868                         } while ((x < goal) && es->x_offset);
1869                         /* FIXME: use ScrollWindow() somehow to improve performance */
1870                         EDIT_UpdateText(es, NULL, TRUE);
1871                 } else if (x > es->format_rect.right) {
1872                         INT x_last;
1873                         INT len = get_text_length(es);
1874                         goal = es->format_rect.right - format_width / HSCROLL_FRACTION;
1875                         do {
1876                                 es->x_offset++;
1877                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
1878                                 x_last = (short)LOWORD(EDIT_EM_PosFromChar(es, len, FALSE));
1879                         } while ((x > goal) && (x_last > es->format_rect.right));
1880                         /* FIXME: use ScrollWindow() somehow to improve performance */
1881                         EDIT_UpdateText(es, NULL, TRUE);
1882                 }
1883         }
1884
1885     if(es->flags & EF_FOCUSED)
1886         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
1887 }
1888
1889
1890 /*********************************************************************
1891  *
1892  *      EDIT_MoveBackward
1893  *
1894  */
1895 static void EDIT_MoveBackward(EDITSTATE *es, BOOL extend)
1896 {
1897         INT e = es->selection_end;
1898
1899         if (e) {
1900                 e--;
1901                 if ((es->style & ES_MULTILINE) && e &&
1902                                 (es->text[e - 1] == '\r') && (es->text[e] == '\n')) {
1903                         e--;
1904                         if (e && (es->text[e - 1] == '\r'))
1905                                 e--;
1906                 }
1907         }
1908         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1909         EDIT_EM_ScrollCaret(es);
1910 }
1911
1912
1913 /*********************************************************************
1914  *
1915  *      EDIT_MoveDown_ML
1916  *
1917  *      Only for multi line controls
1918  *      Move the caret one line down, on a column with the nearest
1919  *      x coordinate on the screen (might be a different column).
1920  *
1921  */
1922 static void EDIT_MoveDown_ML(EDITSTATE *es, BOOL extend)
1923 {
1924         INT s = es->selection_start;
1925         INT e = es->selection_end;
1926         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1927         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1928         INT x = (short)LOWORD(pos);
1929         INT y = (short)HIWORD(pos);
1930
1931         e = EDIT_CharFromPos(es, x, y + es->line_height, &after_wrap);
1932         if (!extend)
1933                 s = e;
1934         EDIT_EM_SetSel(es, s, e, after_wrap);
1935         EDIT_EM_ScrollCaret(es);
1936 }
1937
1938
1939 /*********************************************************************
1940  *
1941  *      EDIT_MoveEnd
1942  *
1943  */
1944 static void EDIT_MoveEnd(EDITSTATE *es, BOOL extend, BOOL ctrl)
1945 {
1946         BOOL after_wrap = FALSE;
1947         INT e;
1948
1949         /* Pass a high value in x to make sure of receiving the end of the line */
1950         if (!ctrl && (es->style & ES_MULTILINE))
1951                 e = EDIT_CharFromPos(es, 0x3fffffff,
1952                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), &after_wrap);
1953         else
1954                 e = get_text_length(es);
1955         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, after_wrap);
1956         EDIT_EM_ScrollCaret(es);
1957 }
1958
1959
1960 /*********************************************************************
1961  *
1962  *      EDIT_MoveForward
1963  *
1964  */
1965 static void EDIT_MoveForward(EDITSTATE *es, BOOL extend)
1966 {
1967         INT e = es->selection_end;
1968
1969         if (es->text[e]) {
1970                 e++;
1971                 if ((es->style & ES_MULTILINE) && (es->text[e - 1] == '\r')) {
1972                         if (es->text[e] == '\n')
1973                                 e++;
1974                         else if ((es->text[e] == '\r') && (es->text[e + 1] == '\n'))
1975                                 e += 2;
1976                 }
1977         }
1978         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1979         EDIT_EM_ScrollCaret(es);
1980 }
1981
1982
1983 /*********************************************************************
1984  *
1985  *      EDIT_MoveHome
1986  *
1987  *      Home key: move to beginning of line.
1988  *
1989  */
1990 static void EDIT_MoveHome(EDITSTATE *es, BOOL extend, BOOL ctrl)
1991 {
1992         INT e;
1993
1994         /* Pass the x_offset in x to make sure of receiving the first position of the line */
1995         if (!ctrl && (es->style & ES_MULTILINE))
1996                 e = EDIT_CharFromPos(es, -es->x_offset,
1997                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), NULL);
1998         else
1999                 e = 0;
2000         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
2001         EDIT_EM_ScrollCaret(es);
2002 }
2003
2004
2005 /*********************************************************************
2006  *
2007  *      EDIT_MovePageDown_ML
2008  *
2009  *      Only for multi line controls
2010  *      Move the caret one page down, on a column with the nearest
2011  *      x coordinate on the screen (might be a different column).
2012  *
2013  */
2014 static void EDIT_MovePageDown_ML(EDITSTATE *es, BOOL extend)
2015 {
2016         INT s = es->selection_start;
2017         INT e = es->selection_end;
2018         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
2019         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
2020         INT x = (short)LOWORD(pos);
2021         INT y = (short)HIWORD(pos);
2022
2023         e = EDIT_CharFromPos(es, x,
2024                 y + (es->format_rect.bottom - es->format_rect.top),
2025                 &after_wrap);
2026         if (!extend)
2027                 s = e;
2028         EDIT_EM_SetSel(es, s, e, after_wrap);
2029         EDIT_EM_ScrollCaret(es);
2030 }
2031
2032
2033 /*********************************************************************
2034  *
2035  *      EDIT_MovePageUp_ML
2036  *
2037  *      Only for multi line controls
2038  *      Move the caret one page up, on a column with the nearest
2039  *      x coordinate on the screen (might be a different column).
2040  *
2041  */
2042 static void EDIT_MovePageUp_ML(EDITSTATE *es, BOOL extend)
2043 {
2044         INT s = es->selection_start;
2045         INT e = es->selection_end;
2046         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
2047         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
2048         INT x = (short)LOWORD(pos);
2049         INT y = (short)HIWORD(pos);
2050
2051         e = EDIT_CharFromPos(es, x,
2052                 y - (es->format_rect.bottom - es->format_rect.top),
2053                 &after_wrap);
2054         if (!extend)
2055                 s = e;
2056         EDIT_EM_SetSel(es, s, e, after_wrap);
2057         EDIT_EM_ScrollCaret(es);
2058 }
2059
2060
2061 /*********************************************************************
2062  *
2063  *      EDIT_MoveUp_ML
2064  *
2065  *      Only for multi line controls
2066  *      Move the caret one line up, on a column with the nearest
2067  *      x coordinate on the screen (might be a different column).
2068  *
2069  */
2070 static void EDIT_MoveUp_ML(EDITSTATE *es, BOOL extend)
2071 {
2072         INT s = es->selection_start;
2073         INT e = es->selection_end;
2074         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
2075         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
2076         INT x = (short)LOWORD(pos);
2077         INT y = (short)HIWORD(pos);
2078
2079         e = EDIT_CharFromPos(es, x, y - es->line_height, &after_wrap);
2080         if (!extend)
2081                 s = e;
2082         EDIT_EM_SetSel(es, s, e, after_wrap);
2083         EDIT_EM_ScrollCaret(es);
2084 }
2085
2086
2087 /*********************************************************************
2088  *
2089  *      EDIT_MoveWordBackward
2090  *
2091  */
2092 static void EDIT_MoveWordBackward(EDITSTATE *es, BOOL extend)
2093 {
2094         INT s = es->selection_start;
2095         INT e = es->selection_end;
2096         INT l;
2097         INT ll;
2098         INT li;
2099
2100         l = EDIT_EM_LineFromChar(es, e);
2101         ll = EDIT_EM_LineLength(es, e);
2102         li = EDIT_EM_LineIndex(es, l);
2103         if (e - li == 0) {
2104                 if (l) {
2105                         li = EDIT_EM_LineIndex(es, l - 1);
2106                         e = li + EDIT_EM_LineLength(es, li);
2107                 }
2108         } else {
2109                 e = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_LEFT);
2110         }
2111         if (!extend)
2112                 s = e;
2113         EDIT_EM_SetSel(es, s, e, FALSE);
2114         EDIT_EM_ScrollCaret(es);
2115 }
2116
2117
2118 /*********************************************************************
2119  *
2120  *      EDIT_MoveWordForward
2121  *
2122  */
2123 static void EDIT_MoveWordForward(EDITSTATE *es, BOOL extend)
2124 {
2125         INT s = es->selection_start;
2126         INT e = es->selection_end;
2127         INT l;
2128         INT ll;
2129         INT li;
2130
2131         l = EDIT_EM_LineFromChar(es, e);
2132         ll = EDIT_EM_LineLength(es, e);
2133         li = EDIT_EM_LineIndex(es, l);
2134         if (e - li == ll) {
2135                 if ((es->style & ES_MULTILINE) && (l != es->line_count - 1))
2136                         e = EDIT_EM_LineIndex(es, l + 1);
2137         } else {
2138                 e = li + EDIT_CallWordBreakProc(es,
2139                                 li, e - li + 1, ll, WB_RIGHT);
2140         }
2141         if (!extend)
2142                 s = e;
2143         EDIT_EM_SetSel(es, s, e, FALSE);
2144         EDIT_EM_ScrollCaret(es);
2145 }
2146
2147
2148 /*********************************************************************
2149  *
2150  *      EDIT_PaintText
2151  *
2152  */
2153 static INT EDIT_PaintText(EDITSTATE *es, HDC dc, INT x, INT y, INT line, INT col, INT count, BOOL rev)
2154 {
2155         COLORREF BkColor;
2156         COLORREF TextColor;
2157         LOGFONTW underline_font;
2158         HFONT hUnderline = 0;
2159         HFONT old_font = 0;
2160         INT ret;
2161         INT li;
2162         INT BkMode;
2163         SIZE size;
2164
2165         if (!count)
2166                 return 0;
2167         BkMode = GetBkMode(dc);
2168         BkColor = GetBkColor(dc);
2169         TextColor = GetTextColor(dc);
2170         if (rev) {
2171                 if (es->composition_len == 0)
2172                 {
2173                         SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT));
2174                         SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2175                         SetBkMode( dc, OPAQUE);
2176                 }
2177                 else
2178                 {
2179                         HFONT current = GetCurrentObject(dc,OBJ_FONT);
2180                         GetObjectW(current,sizeof(LOGFONTW),&underline_font);
2181                         underline_font.lfUnderline = TRUE;
2182                         hUnderline = CreateFontIndirectW(&underline_font);
2183                         old_font = SelectObject(dc,hUnderline);
2184                 }
2185         }
2186         li = EDIT_EM_LineIndex(es, line);
2187         if (es->style & ES_MULTILINE) {
2188                 ret = (INT)LOWORD(TabbedTextOutW(dc, x, y, es->text + li + col, count,
2189                                         es->tabs_count, es->tabs, es->format_rect.left - es->x_offset));
2190         } else {
2191                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2192                 TextOutW(dc, x, y, text + li + col, count);
2193                 GetTextExtentPoint32W(dc, text + li + col, count, &size);
2194                 ret = size.cx;
2195                 if (es->style & ES_PASSWORD)
2196                         HeapFree(GetProcessHeap(), 0, text);
2197         }
2198         if (rev) {
2199                 if (es->composition_len == 0)
2200                 {
2201                         SetBkColor(dc, BkColor);
2202                         SetTextColor(dc, TextColor);
2203                         SetBkMode( dc, BkMode);
2204                 }
2205                 else
2206                 {
2207                         if (old_font)
2208                                 SelectObject(dc,old_font);
2209                         if (hUnderline)
2210                                 DeleteObject(hUnderline);
2211                 }
2212         }
2213         return ret;
2214 }
2215
2216
2217 /*********************************************************************
2218  *
2219  *      EDIT_PaintLine
2220  *
2221  */
2222 static void EDIT_PaintLine(EDITSTATE *es, HDC dc, INT line, BOOL rev)
2223 {
2224         INT s = es->selection_start;
2225         INT e = es->selection_end;
2226         INT li;
2227         INT ll;
2228         INT x;
2229         INT y;
2230         LRESULT pos;
2231
2232         if (es->style & ES_MULTILINE) {
2233                 INT vlc = get_vertical_line_count(es);
2234
2235                 if ((line < es->y_offset) || (line > es->y_offset + vlc) || (line >= es->line_count))
2236                         return;
2237         } else if (line)
2238                 return;
2239
2240         TRACE("line=%d\n", line);
2241
2242         pos = EDIT_EM_PosFromChar(es, EDIT_EM_LineIndex(es, line), FALSE);
2243         x = (short)LOWORD(pos);
2244         y = (short)HIWORD(pos);
2245         li = EDIT_EM_LineIndex(es, line);
2246         ll = EDIT_EM_LineLength(es, li);
2247         s = min(es->selection_start, es->selection_end);
2248         e = max(es->selection_start, es->selection_end);
2249         s = min(li + ll, max(li, s));
2250         e = min(li + ll, max(li, e));
2251         if (rev && (s != e) &&
2252                         ((es->flags & EF_FOCUSED) || (es->style & ES_NOHIDESEL))) {
2253                 x += EDIT_PaintText(es, dc, x, y, line, 0, s - li, FALSE);
2254                 x += EDIT_PaintText(es, dc, x, y, line, s - li, e - s, TRUE);
2255                 x += EDIT_PaintText(es, dc, x, y, line, e - li, li + ll - e, FALSE);
2256         } else
2257                 x += EDIT_PaintText(es, dc, x, y, line, 0, ll, FALSE);
2258 }
2259
2260
2261 /*********************************************************************
2262  *
2263  *      EDIT_AdjustFormatRect
2264  *
2265  *      Adjusts the format rectangle for the current font and the
2266  *      current client rectangle.
2267  *
2268  */
2269 static void EDIT_AdjustFormatRect(EDITSTATE *es)
2270 {
2271         RECT ClientRect;
2272
2273         es->format_rect.right = max(es->format_rect.right, es->format_rect.left + es->char_width);
2274         if (es->style & ES_MULTILINE)
2275         {
2276             INT fw, vlc, max_x_offset, max_y_offset;
2277
2278             vlc = get_vertical_line_count(es);
2279             es->format_rect.bottom = es->format_rect.top + vlc * es->line_height;
2280
2281             /* correct es->x_offset */
2282             fw = es->format_rect.right - es->format_rect.left;
2283             max_x_offset = es->text_width - fw;
2284             if(max_x_offset < 0) max_x_offset = 0;
2285             if(es->x_offset > max_x_offset)
2286                 es->x_offset = max_x_offset;
2287
2288             /* correct es->y_offset */
2289             max_y_offset = es->line_count - vlc;
2290             if(max_y_offset < 0) max_y_offset = 0;
2291             if(es->y_offset > max_y_offset)
2292                 es->y_offset = max_y_offset;
2293
2294             /* force scroll info update */
2295             EDIT_UpdateScrollInfo(es);
2296         }
2297         else
2298         /* Windows doesn't care to fix text placement for SL controls */
2299                 es->format_rect.bottom = es->format_rect.top + es->line_height;
2300
2301         /* Always stay within the client area */
2302         GetClientRect(es->hwndSelf, &ClientRect);
2303         es->format_rect.bottom = min(es->format_rect.bottom, ClientRect.bottom);
2304
2305         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL))
2306                 EDIT_BuildLineDefs_ML(es, 0, get_text_length(es), 0, NULL);
2307         
2308         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
2309 }
2310
2311
2312 /*********************************************************************
2313  *
2314  *      EDIT_SetRectNP
2315  *
2316  *      note:   this is not (exactly) the handler called on EM_SETRECTNP
2317  *              it is also used to set the rect of a single line control
2318  *
2319  */
2320 static void EDIT_SetRectNP(EDITSTATE *es, const RECT *rc)
2321 {
2322         LONG_PTR ExStyle;
2323         INT bw, bh;
2324         ExStyle = GetWindowLongPtrW(es->hwndSelf, GWL_EXSTYLE);
2325         
2326         CopyRect(&es->format_rect, rc);
2327         
2328         if (ExStyle & WS_EX_CLIENTEDGE) {
2329                 es->format_rect.left++;
2330                 es->format_rect.right--;
2331                 
2332                 if (es->format_rect.bottom - es->format_rect.top
2333                     >= es->line_height + 2)
2334                 {
2335                         es->format_rect.top++;
2336                         es->format_rect.bottom--;
2337                 }
2338         }
2339         else if (es->style & WS_BORDER) {
2340                 bw = GetSystemMetrics(SM_CXBORDER) + 1;
2341                 bh = GetSystemMetrics(SM_CYBORDER) + 1;
2342                 es->format_rect.left += bw;
2343                 es->format_rect.right -= bw;
2344                 if (es->format_rect.bottom - es->format_rect.top
2345                   >= es->line_height + 2 * bh)
2346                 {
2347                     es->format_rect.top += bh;
2348                     es->format_rect.bottom -= bh;
2349                 }
2350         }
2351         
2352         es->format_rect.left += es->left_margin;
2353         es->format_rect.right -= es->right_margin;
2354         EDIT_AdjustFormatRect(es);
2355 }
2356
2357
2358 /*********************************************************************
2359  *
2360  *      EM_CHARFROMPOS
2361  *
2362  *      returns line number (not index) in high-order word of result.
2363  *      NB : Q137805 is unclear about this. POINT * pointer in lParam apply
2364  *      to Richedit, not to the edit control. Original documentation is valid.
2365  *      FIXME: do the specs mean to return -1 if outside client area or
2366  *              if outside formatting rectangle ???
2367  *
2368  */
2369 static LRESULT EDIT_EM_CharFromPos(EDITSTATE *es, INT x, INT y)
2370 {
2371         POINT pt;
2372         RECT rc;
2373         INT index;
2374
2375         pt.x = x;
2376         pt.y = y;
2377         GetClientRect(es->hwndSelf, &rc);
2378         if (!PtInRect(&rc, pt))
2379                 return -1;
2380
2381         index = EDIT_CharFromPos(es, x, y, NULL);
2382         return MAKELONG(index, EDIT_EM_LineFromChar(es, index));
2383 }
2384
2385
2386 /*********************************************************************
2387  *
2388  *      EM_FMTLINES
2389  *
2390  * Enable or disable soft breaks.
2391  * 
2392  * This means: insert or remove the soft linebreak character (\r\r\n).
2393  * Take care to check if the text still fits the buffer after insertion.
2394  * If not, notify with EN_ERRSPACE.
2395  * 
2396  */
2397 static BOOL EDIT_EM_FmtLines(EDITSTATE *es, BOOL add_eol)
2398 {
2399         es->flags &= ~EF_USE_SOFTBRK;
2400         if (add_eol) {
2401                 es->flags |= EF_USE_SOFTBRK;
2402                 FIXME("soft break enabled, not implemented\n");
2403         }
2404         return add_eol;
2405 }
2406
2407
2408 /*********************************************************************
2409  *
2410  *      EM_GETHANDLE
2411  *
2412  *      Hopefully this won't fire back at us.
2413  *      We always start with a fixed buffer in the local heap.
2414  *      Despite of the documentation says that the local heap is used
2415  *      only if DS_LOCALEDIT flag is set, NT and 2000 always allocate
2416  *      buffer on the local heap.
2417  *
2418  */
2419 static HLOCAL EDIT_EM_GetHandle(EDITSTATE *es)
2420 {
2421         HLOCAL hLocal;
2422
2423         if (!(es->style & ES_MULTILINE))
2424                 return 0;
2425
2426         if(es->is_unicode)
2427             hLocal = es->hloc32W;
2428         else
2429         {
2430             if(!es->hloc32A)
2431             {
2432                 CHAR *textA;
2433                 UINT countA, alloc_size;
2434                 TRACE("Allocating 32-bit ANSI alias buffer\n");
2435                 countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2436                 alloc_size = ROUND_TO_GROW(countA);
2437                 if(!(es->hloc32A = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
2438                 {
2439                     ERR("Could not allocate %d bytes for 32-bit ANSI alias buffer\n", alloc_size);
2440                     return 0;
2441                 }
2442                 textA = LocalLock(es->hloc32A);
2443                 WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2444                 LocalUnlock(es->hloc32A);
2445             }
2446             hLocal = es->hloc32A;
2447         }
2448
2449         es->flags |= EF_APP_HAS_HANDLE;
2450         TRACE("Returning %p, LocalSize() = %ld\n", hLocal, LocalSize(hLocal));
2451         return hLocal;
2452 }
2453
2454
2455 /*********************************************************************
2456  *
2457  *      EM_GETHANDLE16
2458  *
2459  *      Hopefully this won't fire back at us.
2460  *      We always start with a buffer in 32 bit linear memory.
2461  *      However, with this message a 16 bit application requests
2462  *      a handle of 16 bit local heap memory, where it expects to find
2463  *      the text.
2464  *      It's a pitty that from this moment on we have to use this
2465  *      local heap, because applications may rely on the handle
2466  *      in the future.
2467  *
2468  *      In this function we'll try to switch to local heap.
2469  */
2470 static HLOCAL16 EDIT_EM_GetHandle16( HWND hwnd )
2471 {
2472         CHAR *textA;
2473         UINT alloc_size;
2474         HLOCAL hloc;
2475         STACK16FRAME* stack16;
2476         HANDLE16 oldDS;
2477         HLOCAL16 hloc16 = GetWindowWord( hwnd, GWW_HANDLE16 );
2478
2479         if (hloc16) return hloc16;
2480
2481         if (!(hloc = (HLOCAL)SendMessageA( hwnd, EM_GETHANDLE, 0, 0 ))) return 0;
2482         alloc_size = LocalSize( hloc );
2483
2484         stack16 = MapSL(PtrToUlong(NtCurrentTeb()->WOW32Reserved));
2485         oldDS = stack16->ds;
2486         stack16->ds = GetWindowLongPtrW( hwnd, GWLP_HINSTANCE );
2487
2488         if (!LocalHeapSize16()) {
2489
2490                 if (!LocalInit16(stack16->ds, 0, GlobalSize16(stack16->ds))) {
2491                         ERR("could not initialize local heap\n");
2492                         goto done;
2493                 }
2494                 TRACE("local heap initialized\n");
2495         }
2496
2497         TRACE("Allocating 16-bit ANSI alias buffer\n");
2498         if (!(hloc16 = LocalAlloc16(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size))) {
2499                 ERR("could not allocate new 16 bit buffer\n");
2500                 goto done;
2501         }
2502
2503         if (!(textA = MapSL(LocalLock16( hloc16)))) {
2504                 ERR("could not lock new 16 bit buffer\n");
2505                 LocalFree16(hloc16);
2506                 hloc16 = 0;
2507                 goto done;
2508         }
2509         memcpy( textA, LocalLock( hloc ), alloc_size );
2510         LocalUnlock( hloc );
2511         LocalUnlock16( hloc16 );
2512         SetWindowWord( hwnd, GWW_HANDLE16, hloc16 );
2513
2514         TRACE("Returning %04X, LocalSize() = %d\n", hloc16, alloc_size);
2515
2516 done:
2517         stack16->ds = oldDS;
2518         return hloc16;
2519 }
2520
2521
2522 /*********************************************************************
2523  *
2524  *      EM_GETLINE
2525  *
2526  */
2527 static INT EDIT_EM_GetLine(EDITSTATE *es, INT line, LPWSTR dst, BOOL unicode)
2528 {
2529         LPWSTR src;
2530         INT line_len, dst_len;
2531         INT i;
2532
2533         if (es->style & ES_MULTILINE) {
2534                 if (line >= es->line_count)
2535                         return 0;
2536         } else
2537                 line = 0;
2538         i = EDIT_EM_LineIndex(es, line);
2539         src = es->text + i;
2540         line_len = EDIT_EM_LineLength(es, i);
2541         dst_len = *(WORD *)dst;
2542         if(unicode)
2543         {
2544             if(dst_len <= line_len)
2545             {
2546                 memcpy(dst, src, dst_len * sizeof(WCHAR));
2547                 return dst_len;
2548             }
2549             else /* Append 0 if enough space */
2550             {
2551                 memcpy(dst, src, line_len * sizeof(WCHAR));
2552                 dst[line_len] = 0;
2553                 return line_len;
2554             }
2555         }
2556         else
2557         {
2558             INT ret = WideCharToMultiByte(CP_ACP, 0, src, line_len, (LPSTR)dst, dst_len, NULL, NULL);
2559             if(!ret && line_len) /* Insufficient buffer size */
2560                 return dst_len;
2561             if(ret < dst_len) /* Append 0 if enough space */
2562                 ((LPSTR)dst)[ret] = 0;
2563             return ret;
2564         }
2565 }
2566
2567
2568 /*********************************************************************
2569  *
2570  *      EM_GETSEL
2571  *
2572  */
2573 static LRESULT EDIT_EM_GetSel(const EDITSTATE *es, PUINT start, PUINT end)
2574 {
2575         UINT s = es->selection_start;
2576         UINT e = es->selection_end;
2577
2578         ORDER_UINT(s, e);
2579         if (start)
2580                 *start = s;
2581         if (end)
2582                 *end = e;
2583         return MAKELONG(s, e);
2584 }
2585
2586
2587 /*********************************************************************
2588  *
2589  *      EM_REPLACESEL
2590  *
2591  *      FIXME: handle ES_NUMBER and ES_OEMCONVERT here
2592  *
2593  */
2594 static void EDIT_EM_ReplaceSel(EDITSTATE *es, BOOL can_undo, LPCWSTR lpsz_replace, BOOL send_update, BOOL honor_limit)
2595 {
2596         UINT strl = strlenW(lpsz_replace);
2597         UINT tl = get_text_length(es);
2598         UINT utl;
2599         UINT s;
2600         UINT e;
2601         UINT i;
2602         UINT size;
2603         LPWSTR p;
2604         HRGN hrgn = 0;
2605         LPWSTR buf = NULL;
2606         UINT bufl = 0;
2607
2608         TRACE("%s, can_undo %d, send_update %d\n",
2609             debugstr_w(lpsz_replace), can_undo, send_update);
2610
2611         s = es->selection_start;
2612         e = es->selection_end;
2613
2614         if ((s == e) && !strl)
2615                 return;
2616
2617         ORDER_UINT(s, e);
2618
2619         size = tl - (e - s) + strl;
2620         if (!size)
2621                 es->text_width = 0;
2622
2623         /* Issue the EN_MAXTEXT notification and continue with replacing text
2624          * such that buffer limit is honored. */
2625         if ((honor_limit) && (size > es->buffer_limit)) {
2626                 EDIT_NOTIFY_PARENT(es, EN_MAXTEXT);
2627                 /* Buffer limit can be smaller than the actual length of text in combobox */
2628                 if (es->buffer_limit < (tl - (e-s)))
2629                         strl = 0;
2630                 else
2631                         strl = es->buffer_limit - (tl - (e-s));
2632         }
2633
2634         if (!EDIT_MakeFit(es, tl - (e - s) + strl))
2635                 return;
2636
2637         if (e != s) {
2638                 /* there is something to be deleted */
2639                 TRACE("deleting stuff.\n");
2640                 bufl = e - s;
2641                 buf = HeapAlloc(GetProcessHeap(), 0, (bufl + 1) * sizeof(WCHAR));
2642                 if (!buf) return;
2643                 memcpy(buf, es->text + s, bufl * sizeof(WCHAR));
2644                 buf[bufl] = 0; /* ensure 0 termination */
2645                 /* now delete */
2646                 strcpyW(es->text + s, es->text + e);
2647                 text_buffer_changed(es);
2648         }
2649         if (strl) {
2650                 /* there is an insertion */
2651                 tl = get_text_length(es);
2652                 TRACE("inserting stuff (tl %d, strl %d, selstart %d (%s), text %s)\n", tl, strl, s, debugstr_w(es->text + s), debugstr_w(es->text));
2653                 for (p = es->text + tl ; p >= es->text + s ; p--)
2654                         p[strl] = p[0];
2655                 for (i = 0 , p = es->text + s ; i < strl ; i++)
2656                         p[i] = lpsz_replace[i];
2657                 if(es->style & ES_UPPERCASE)
2658                         CharUpperBuffW(p, strl);
2659                 else if(es->style & ES_LOWERCASE)
2660                         CharLowerBuffW(p, strl);
2661                 text_buffer_changed(es);
2662         }
2663         if (es->style & ES_MULTILINE)
2664         {
2665                 INT st = min(es->selection_start, es->selection_end);
2666                 INT vlc = get_vertical_line_count(es);
2667
2668                 hrgn = CreateRectRgn(0, 0, 0, 0);
2669                 EDIT_BuildLineDefs_ML(es, st, st + strl,
2670                                 strl - abs(es->selection_end - es->selection_start), hrgn);
2671                 /* if text is too long undo all changes */
2672                 if (honor_limit && !(es->style & ES_AUTOVSCROLL) && (es->line_count > vlc)) {
2673                         if (strl)
2674                                 strcpyW(es->text + e, es->text + e + strl);
2675                         if (e != s)
2676                                 for (i = 0 , p = es->text ; i < e - s ; i++)
2677                                         p[i + s] = buf[i];
2678                         text_buffer_changed(es);
2679                         EDIT_BuildLineDefs_ML(es, s, e, 
2680                                 abs(es->selection_end - es->selection_start) - strl, hrgn);
2681                         strl = 0;
2682                         e = s;
2683                         hrgn = CreateRectRgn(0, 0, 0, 0);
2684                         EDIT_NOTIFY_PARENT(es, EN_MAXTEXT);
2685                 }
2686         }
2687         else {
2688                 INT fw = es->format_rect.right - es->format_rect.left;
2689                 EDIT_CalcLineWidth_SL(es);
2690                 /* remove chars that don't fit */
2691                 if (honor_limit && !(es->style & ES_AUTOHSCROLL) && (es->text_width > fw)) {
2692                         while ((es->text_width > fw) && s + strl >= s) {
2693                                 strcpyW(es->text + s + strl - 1, es->text + s + strl);
2694                                 strl--;
2695                                 EDIT_CalcLineWidth_SL(es);
2696                         }
2697                         text_buffer_changed(es);
2698                         EDIT_NOTIFY_PARENT(es, EN_MAXTEXT);
2699                 }
2700         }
2701         
2702         if (e != s) {
2703                 if (can_undo) {
2704                         utl = strlenW(es->undo_text);
2705                         if (!es->undo_insert_count && (*es->undo_text && (s == es->undo_position))) {
2706                                 /* undo-buffer is extended to the right */
2707                                 EDIT_MakeUndoFit(es, utl + e - s);
2708                                 memcpy(es->undo_text + utl, buf, (e - s)*sizeof(WCHAR));
2709                                 (es->undo_text + utl)[e - s] = 0; /* ensure 0 termination */
2710                         } else if (!es->undo_insert_count && (*es->undo_text && (e == es->undo_position))) {
2711                                 /* undo-buffer is extended to the left */
2712                                 EDIT_MakeUndoFit(es, utl + e - s);
2713                                 for (p = es->undo_text + utl ; p >= es->undo_text ; p--)
2714                                         p[e - s] = p[0];
2715                                 for (i = 0 , p = es->undo_text ; i < e - s ; i++)
2716                                         p[i] = buf[i];
2717                                 es->undo_position = s;
2718                         } else {
2719                                 /* new undo-buffer */
2720                                 EDIT_MakeUndoFit(es, e - s);
2721                                 memcpy(es->undo_text, buf, (e - s)*sizeof(WCHAR));
2722                                 es->undo_text[e - s] = 0; /* ensure 0 termination */
2723                                 es->undo_position = s;
2724                         }
2725                         /* any deletion makes the old insertion-undo invalid */
2726                         es->undo_insert_count = 0;
2727                 } else
2728                         EDIT_EM_EmptyUndoBuffer(es);
2729         }
2730         if (strl) {
2731                 if (can_undo) {
2732                         if ((s == es->undo_position) ||
2733                                 ((es->undo_insert_count) &&
2734                                 (s == es->undo_position + es->undo_insert_count)))
2735                                 /*
2736                                  * insertion is new and at delete position or
2737                                  * an extension to either left or right
2738                                  */
2739                                 es->undo_insert_count += strl;
2740                         else {
2741                                 /* new insertion undo */
2742                                 es->undo_position = s;
2743                                 es->undo_insert_count = strl;
2744                                 /* new insertion makes old delete-buffer invalid */
2745                                 *es->undo_text = '\0';
2746                         }
2747                 } else
2748                         EDIT_EM_EmptyUndoBuffer(es);
2749         }
2750
2751         if (bufl)
2752                 HeapFree(GetProcessHeap(), 0, buf);
2753  
2754         s += strl;
2755
2756         /* If text has been deleted and we're right or center aligned then scroll rightward */
2757         if (es->style & (ES_RIGHT | ES_CENTER))
2758         {
2759                 INT delta = strl - abs(es->selection_end - es->selection_start);
2760
2761                 if (delta < 0 && es->x_offset)
2762                 {
2763                         if (abs(delta) > es->x_offset)
2764                                 es->x_offset = 0;
2765                         else
2766                                 es->x_offset += delta;
2767                 }
2768         }
2769
2770         EDIT_EM_SetSel(es, s, s, FALSE);
2771         es->flags |= EF_MODIFIED;
2772         if (send_update) es->flags |= EF_UPDATE;
2773         if (hrgn)
2774         {
2775                 EDIT_UpdateTextRegion(es, hrgn, TRUE);
2776                 DeleteObject(hrgn);
2777         }
2778         else
2779             EDIT_UpdateText(es, NULL, TRUE);
2780
2781         EDIT_EM_ScrollCaret(es);
2782
2783         /* force scroll info update */
2784         EDIT_UpdateScrollInfo(es);
2785
2786
2787         if(send_update || (es->flags & EF_UPDATE))
2788         {
2789             es->flags &= ~EF_UPDATE;
2790             EDIT_NOTIFY_PARENT(es, EN_CHANGE);
2791         }
2792 }
2793
2794
2795 /*********************************************************************
2796  *
2797  *      EM_SETHANDLE
2798  *
2799  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
2800  *
2801  */
2802 static void EDIT_EM_SetHandle(EDITSTATE *es, HLOCAL hloc)
2803 {
2804         if (!(es->style & ES_MULTILINE))
2805                 return;
2806
2807         if (!hloc) {
2808                 WARN("called with NULL handle\n");
2809                 return;
2810         }
2811
2812         EDIT_UnlockBuffer(es, TRUE);
2813
2814         if(es->is_unicode)
2815         {
2816             if(es->hloc32A)
2817             {
2818                 LocalFree(es->hloc32A);
2819                 es->hloc32A = NULL;
2820             }
2821             es->hloc32W = hloc;
2822         }
2823         else
2824         {
2825             INT countW, countA;
2826             HLOCAL hloc32W_new;
2827             WCHAR *textW;
2828             CHAR *textA;
2829
2830             countA = LocalSize(hloc);
2831             textA = LocalLock(hloc);
2832             countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
2833             if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
2834             {
2835                 ERR("Could not allocate new unicode buffer\n");
2836                 return;
2837             }
2838             textW = LocalLock(hloc32W_new);
2839             MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
2840             LocalUnlock(hloc32W_new);
2841             LocalUnlock(hloc);
2842
2843             if(es->hloc32W)
2844                 LocalFree(es->hloc32W);
2845
2846             es->hloc32W = hloc32W_new;
2847             es->hloc32A = hloc;
2848         }
2849
2850         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
2851
2852         es->flags |= EF_APP_HAS_HANDLE;
2853         EDIT_LockBuffer(es);
2854
2855         es->x_offset = es->y_offset = 0;
2856         es->selection_start = es->selection_end = 0;
2857         EDIT_EM_EmptyUndoBuffer(es);
2858         es->flags &= ~EF_MODIFIED;
2859         es->flags &= ~EF_UPDATE;
2860         EDIT_BuildLineDefs_ML(es, 0, get_text_length(es), 0, NULL);
2861         EDIT_UpdateText(es, NULL, TRUE);
2862         EDIT_EM_ScrollCaret(es);
2863         /* force scroll info update */
2864         EDIT_UpdateScrollInfo(es);
2865 }
2866
2867
2868 /*********************************************************************
2869  *
2870  *      EM_SETHANDLE16
2871  *
2872  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
2873  *
2874  */
2875 static void EDIT_EM_SetHandle16( HWND hwnd, HLOCAL16 hloc16 )
2876 {
2877         STACK16FRAME* stack16 = MapSL(PtrToUlong(NtCurrentTeb()->WOW32Reserved));
2878         HINSTANCE16 hInstance = GetWindowLongPtrW( hwnd, GWLP_HINSTANCE );
2879         HANDLE16 oldDS = stack16->ds;
2880         HLOCAL hloc32;
2881         INT count;
2882         CHAR *text;
2883
2884         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & ES_MULTILINE)) return;
2885
2886         if (!hloc16) {
2887                 WARN("called with NULL handle\n");
2888                 return;
2889         }
2890
2891         stack16->ds = hInstance;
2892         count = LocalSize16(hloc16);
2893         text = MapSL(LocalLock16(hloc16));
2894         if ((hloc32 = LocalAlloc(LMEM_MOVEABLE, count)))
2895         {
2896             memcpy( LocalLock(hloc32), text, count );
2897             LocalUnlock(hloc32);
2898             LocalUnlock16(hloc16);
2899             SetWindowWord( hwnd, GWW_HANDLE16, hloc16 );
2900         }
2901         stack16->ds = oldDS;
2902
2903         if (hloc32) SendMessageA( hwnd, EM_SETHANDLE, (WPARAM)hloc32, 0 );
2904         else ERR("Could not allocate new buffer\n");
2905 }
2906
2907
2908 /*********************************************************************
2909  *
2910  *      EM_SETLIMITTEXT
2911  *
2912  *      NOTE: this version currently implements WinNT limits
2913  *
2914  */
2915 static void EDIT_EM_SetLimitText(EDITSTATE *es, UINT limit)
2916 {
2917     if (!limit) limit = ~0u;
2918     if (!(es->style & ES_MULTILINE)) limit = min(limit, 0x7ffffffe);
2919     es->buffer_limit = limit;
2920 }
2921
2922
2923 /*********************************************************************
2924  *
2925  *      EM_SETMARGINS
2926  *
2927  * EC_USEFONTINFO is used as a left or right value i.e. lParam and not as an
2928  * action wParam despite what the docs say. EC_USEFONTINFO calculates the
2929  * margin according to the textmetrics of the current font.
2930  *
2931  * FIXME - With TrueType or vector fonts EC_USEFONTINFO currently sets one third
2932  * of the char's width as the margin, but this is not how Windows handles this.
2933  * For all other fonts Windows sets the margins to zero.
2934  *
2935  * FIXME - When EC_USEFONTINFO is used the margins only change if the
2936  * edit control is equal to or larger than a certain size.
2937  * Interestingly if one subtracts both the left and right margins from
2938  * this size one always seems to get an even number.  The extents of
2939  * the (four character) string "'**'" match this quite closely, so
2940  * we'll use this until we come up with a better idea.
2941  */
2942 static int calc_min_set_margin_size(HDC dc, INT left, INT right)
2943 {
2944     WCHAR magic_string[] = {'\'','*','*','\'', 0};
2945     SIZE sz;
2946
2947     GetTextExtentPointW(dc, magic_string, sizeof(magic_string)/sizeof(WCHAR) - 1, &sz);
2948     return sz.cx + left + right;
2949 }
2950
2951 static void EDIT_EM_SetMargins(EDITSTATE *es, INT action,
2952                                WORD left, WORD right, BOOL repaint)
2953 {
2954         TEXTMETRICW tm;
2955         INT default_left_margin  = 0; /* in pixels */
2956         INT default_right_margin = 0; /* in pixels */
2957
2958         /* Set the default margins depending on the font */
2959         if (es->font && (left == EC_USEFONTINFO || right == EC_USEFONTINFO)) {
2960             HDC dc = GetDC(es->hwndSelf);
2961             HFONT old_font = SelectObject(dc, es->font);
2962             GetTextMetricsW(dc, &tm);
2963             /* The default margins are only non zero for TrueType or Vector fonts */
2964             if (tm.tmPitchAndFamily & ( TMPF_VECTOR | TMPF_TRUETYPE )) {
2965                 int min_size;
2966                 RECT rc;
2967                 /* This must be calculated more exactly! But how? */
2968                 default_left_margin = tm.tmAveCharWidth / 2;
2969                 default_right_margin = tm.tmAveCharWidth / 2;
2970                 min_size = calc_min_set_margin_size(dc, default_left_margin, default_right_margin);
2971                 GetClientRect(es->hwndSelf, &rc);
2972                 if(rc.right - rc.left < min_size) {
2973                     default_left_margin = es->left_margin;
2974                     default_right_margin = es->right_margin;
2975                 }
2976             }
2977             SelectObject(dc, old_font);
2978             ReleaseDC(es->hwndSelf, dc);
2979         }
2980
2981         if (action & EC_LEFTMARGIN) {
2982                 es->format_rect.left -= es->left_margin;
2983                 if (left != EC_USEFONTINFO)
2984                         es->left_margin = left;
2985                 else
2986                         es->left_margin = default_left_margin;
2987                 es->format_rect.left += es->left_margin;
2988         }
2989
2990         if (action & EC_RIGHTMARGIN) {
2991                 es->format_rect.right += es->right_margin;
2992                 if (right != EC_USEFONTINFO)
2993                         es->right_margin = right;
2994                 else
2995                         es->right_margin = default_right_margin;
2996                 es->format_rect.right -= es->right_margin;
2997         }
2998         
2999         if (action & (EC_LEFTMARGIN | EC_RIGHTMARGIN)) {
3000                 EDIT_AdjustFormatRect(es);
3001                 if (repaint) EDIT_UpdateText(es, NULL, TRUE);
3002         }
3003         
3004         TRACE("left=%d, right=%d\n", es->left_margin, es->right_margin);
3005 }
3006
3007
3008 /*********************************************************************
3009  *
3010  *      EM_SETPASSWORDCHAR
3011  *
3012  */
3013 static void EDIT_EM_SetPasswordChar(EDITSTATE *es, WCHAR c)
3014 {
3015         LONG style;
3016
3017         if (es->style & ES_MULTILINE)
3018                 return;
3019
3020         if (es->password_char == c)
3021                 return;
3022
3023         style = GetWindowLongW( es->hwndSelf, GWL_STYLE );
3024         es->password_char = c;
3025         if (c) {
3026             SetWindowLongW( es->hwndSelf, GWL_STYLE, style | ES_PASSWORD );
3027             es->style |= ES_PASSWORD;
3028         } else {
3029             SetWindowLongW( es->hwndSelf, GWL_STYLE, style & ~ES_PASSWORD );
3030             es->style &= ~ES_PASSWORD;
3031         }
3032         EDIT_UpdateText(es, NULL, TRUE);
3033 }
3034
3035
3036 /*********************************************************************
3037  *
3038  *      EM_SETTABSTOPS
3039  *
3040  */
3041 static BOOL EDIT_EM_SetTabStops(EDITSTATE *es, INT count, const INT *tabs)
3042 {
3043         if (!(es->style & ES_MULTILINE))
3044                 return FALSE;
3045         HeapFree(GetProcessHeap(), 0, es->tabs);
3046         es->tabs_count = count;
3047         if (!count)
3048                 es->tabs = NULL;
3049         else {
3050                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3051                 memcpy(es->tabs, tabs, count * sizeof(INT));
3052         }
3053         return TRUE;
3054 }
3055
3056
3057 /*********************************************************************
3058  *
3059  *      EM_SETWORDBREAKPROC
3060  *
3061  */
3062 static void EDIT_EM_SetWordBreakProc(EDITSTATE *es, void *wbp)
3063 {
3064         if (es->word_break_proc == wbp)
3065                 return;
3066
3067         es->word_break_proc = wbp;
3068
3069         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3070                 EDIT_BuildLineDefs_ML(es, 0, get_text_length(es), 0, NULL);
3071                 EDIT_UpdateText(es, NULL, TRUE);
3072         }
3073 }
3074
3075
3076 /*********************************************************************
3077  *
3078  *      EM_UNDO / WM_UNDO
3079  *
3080  */
3081 static BOOL EDIT_EM_Undo(EDITSTATE *es)
3082 {
3083         INT ulength;
3084         LPWSTR utext;
3085
3086         /* As per MSDN spec, for a single-line edit control,
3087            the return value is always TRUE */
3088         if( es->style & ES_READONLY )
3089             return !(es->style & ES_MULTILINE);
3090
3091         ulength = strlenW(es->undo_text);
3092
3093         utext = HeapAlloc(GetProcessHeap(), 0, (ulength + 1) * sizeof(WCHAR));
3094
3095         strcpyW(utext, es->undo_text);
3096
3097         TRACE("before UNDO:insertion length = %d, deletion buffer = %s\n",
3098                      es->undo_insert_count, debugstr_w(utext));
3099
3100         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3101         EDIT_EM_EmptyUndoBuffer(es);
3102         EDIT_EM_ReplaceSel(es, TRUE, utext, TRUE, TRUE);
3103         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3104         /* send the notification after the selection start and end are set */
3105         EDIT_NOTIFY_PARENT(es, EN_CHANGE);
3106         EDIT_EM_ScrollCaret(es);
3107         HeapFree(GetProcessHeap(), 0, utext);
3108
3109         TRACE("after UNDO:insertion length = %d, deletion buffer = %s\n",
3110                         es->undo_insert_count, debugstr_w(es->undo_text));
3111         return TRUE;
3112 }
3113
3114
3115 /* Helper function for WM_CHAR
3116  *
3117  * According to an MSDN blog article titled "Just because you're a control
3118  * doesn't mean that you're necessarily inside a dialog box," multiline edit
3119  * controls without ES_WANTRETURN would attempt to detect whether it is inside
3120  * a dialog box or not.
3121  */
3122 static inline BOOL EDIT_IsInsideDialog(EDITSTATE *es)
3123 {
3124     return (es->flags & EF_DIALOGMODE);
3125 }
3126
3127
3128 /*********************************************************************
3129  *
3130  *      WM_PASTE
3131  *
3132  */
3133 static void EDIT_WM_Paste(EDITSTATE *es)
3134 {
3135         HGLOBAL hsrc;
3136         LPWSTR src;
3137
3138         /* Protect read-only edit control from modification */
3139         if(es->style & ES_READONLY)
3140             return;
3141
3142         OpenClipboard(es->hwndSelf);
3143         if ((hsrc = GetClipboardData(CF_UNICODETEXT))) {
3144                 src = GlobalLock(hsrc);
3145                 EDIT_EM_ReplaceSel(es, TRUE, src, TRUE, TRUE);
3146                 GlobalUnlock(hsrc);
3147         }
3148         else if (es->style & ES_PASSWORD) {
3149             /* clear selected text in password edit box even with empty clipboard */
3150             const WCHAR empty_strW[] = { 0 };
3151             EDIT_EM_ReplaceSel(es, TRUE, empty_strW, TRUE, TRUE);
3152         }
3153         CloseClipboard();
3154 }
3155
3156
3157 /*********************************************************************
3158  *
3159  *      WM_COPY
3160  *
3161  */
3162 static void EDIT_WM_Copy(EDITSTATE *es)
3163 {
3164         INT s = min(es->selection_start, es->selection_end);
3165         INT e = max(es->selection_start, es->selection_end);
3166         HGLOBAL hdst;
3167         LPWSTR dst;
3168         DWORD len;
3169
3170         if (e == s) return;
3171
3172         len = e - s;
3173         hdst = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (len + 1) * sizeof(WCHAR));
3174         dst = GlobalLock(hdst);
3175         memcpy(dst, es->text + s, len * sizeof(WCHAR));
3176         dst[len] = 0; /* ensure 0 termination */
3177         TRACE("%s\n", debugstr_w(dst));
3178         GlobalUnlock(hdst);
3179         OpenClipboard(es->hwndSelf);
3180         EmptyClipboard();
3181         SetClipboardData(CF_UNICODETEXT, hdst);
3182         CloseClipboard();
3183 }
3184
3185
3186 /*********************************************************************
3187  *
3188  *      WM_CLEAR
3189  *
3190  */
3191 static inline void EDIT_WM_Clear(EDITSTATE *es)
3192 {
3193         static const WCHAR empty_stringW[] = {0};
3194
3195         /* Protect read-only edit control from modification */
3196         if(es->style & ES_READONLY)
3197             return;
3198
3199         EDIT_EM_ReplaceSel(es, TRUE, empty_stringW, TRUE, TRUE);
3200 }
3201
3202
3203 /*********************************************************************
3204  *
3205  *      WM_CUT
3206  *
3207  */
3208 static inline void EDIT_WM_Cut(EDITSTATE *es)
3209 {
3210         EDIT_WM_Copy(es);
3211         EDIT_WM_Clear(es);
3212 }
3213
3214
3215 /*********************************************************************
3216  *
3217  *      WM_CHAR
3218  *
3219  */
3220 static LRESULT EDIT_WM_Char(EDITSTATE *es, WCHAR c)
3221 {
3222         BOOL control;
3223
3224         control = GetKeyState(VK_CONTROL) & 0x8000;
3225
3226         switch (c) {
3227         case '\r':
3228             /* If it's not a multiline edit box, it would be ignored below.
3229              * For multiline edit without ES_WANTRETURN, we have to make a
3230              * special case.
3231              */
3232             if ((es->style & ES_MULTILINE) && !(es->style & ES_WANTRETURN))
3233                 if (EDIT_IsInsideDialog(es))
3234                     break;
3235         case '\n':
3236                 if (es->style & ES_MULTILINE) {
3237                         if (es->style & ES_READONLY) {
3238                                 EDIT_MoveHome(es, FALSE, FALSE);
3239                                 EDIT_MoveDown_ML(es, FALSE);
3240                         } else {
3241                                 static const WCHAR cr_lfW[] = {'\r','\n',0};
3242                                 EDIT_EM_ReplaceSel(es, TRUE, cr_lfW, TRUE, TRUE);
3243                         }
3244                 }
3245                 break;
3246         case '\t':
3247                 if ((es->style & ES_MULTILINE) && !(es->style & ES_READONLY))
3248                 {
3249                         static const WCHAR tabW[] = {'\t',0};
3250                         if (EDIT_IsInsideDialog(es))
3251                             break;
3252                         EDIT_EM_ReplaceSel(es, TRUE, tabW, TRUE, TRUE);
3253                 }
3254                 break;
3255         case VK_BACK:
3256                 if (!(es->style & ES_READONLY) && !control) {
3257                         if (es->selection_start != es->selection_end)
3258                                 EDIT_WM_Clear(es);
3259                         else {
3260                                 /* delete character left of caret */
3261                                 EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3262                                 EDIT_MoveBackward(es, TRUE);
3263                                 EDIT_WM_Clear(es);
3264                         }
3265                 }
3266                 break;
3267         case 0x03: /* ^C */
3268                 if (!(es->style & ES_PASSWORD))
3269                     SendMessageW(es->hwndSelf, WM_COPY, 0, 0);
3270                 break;
3271         case 0x16: /* ^V */
3272                 if (!(es->style & ES_READONLY))
3273                     SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3274                 break;
3275         case 0x18: /* ^X */
3276                 if (!((es->style & ES_READONLY) || (es->style & ES_PASSWORD)))
3277                     SendMessageW(es->hwndSelf, WM_CUT, 0, 0);
3278                 break;
3279         case 0x1A: /* ^Z */
3280                 if (!(es->style & ES_READONLY))
3281                     SendMessageW(es->hwndSelf, WM_UNDO, 0, 0);
3282                 break;
3283
3284         default:
3285                 /*If Edit control style is ES_NUMBER allow users to key in only numeric values*/
3286                 if( (es->style & ES_NUMBER) && !( c >= '0' && c <= '9') )
3287                         break;
3288                         
3289                 if (!(es->style & ES_READONLY) && (c >= ' ') && (c != 127)) {
3290                         WCHAR str[2];
3291                         str[0] = c;
3292                         str[1] = '\0';
3293                         EDIT_EM_ReplaceSel(es, TRUE, str, TRUE, TRUE);
3294                 }
3295                 break;
3296         }
3297     return 1;
3298 }
3299
3300
3301 /*********************************************************************
3302  *
3303  *      WM_COMMAND
3304  *
3305  */
3306 static void EDIT_WM_Command(EDITSTATE *es, INT code, INT id, HWND control)
3307 {
3308         if (code || control)
3309                 return;
3310
3311         switch (id) {
3312                 case EM_UNDO:
3313                         SendMessageW(es->hwndSelf, WM_UNDO, 0, 0);
3314                         break;
3315                 case WM_CUT:
3316                         SendMessageW(es->hwndSelf, WM_CUT, 0, 0);
3317                         break;
3318                 case WM_COPY:
3319                         SendMessageW(es->hwndSelf, WM_COPY, 0, 0);
3320                         break;
3321                 case WM_PASTE:
3322                         SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3323                         break;
3324                 case WM_CLEAR:
3325                         SendMessageW(es->hwndSelf, WM_CLEAR, 0, 0);
3326                         break;
3327                 case EM_SETSEL:
3328                         EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
3329                         EDIT_EM_ScrollCaret(es);
3330                         break;
3331                 default:
3332                         ERR("unknown menu item, please report\n");
3333                         break;
3334         }
3335 }
3336
3337
3338 /*********************************************************************
3339  *
3340  *      WM_CONTEXTMENU
3341  *
3342  *      Note: the resource files resource/sysres_??.rc cannot define a
3343  *              single popup menu.  Hence we use a (dummy) menubar
3344  *              containing the single popup menu as its first item.
3345  *
3346  *      FIXME: the message identifiers have been chosen arbitrarily,
3347  *              hence we use MF_BYPOSITION.
3348  *              We might as well use the "real" values (anybody knows ?)
3349  *              The menu definition is in resources/sysres_??.rc.
3350  *              Once these are OK, we better use MF_BYCOMMAND here
3351  *              (as we do in EDIT_WM_Command()).
3352  *
3353  */
3354 static void EDIT_WM_ContextMenu(EDITSTATE *es, INT x, INT y)
3355 {
3356         HMENU menu = LoadMenuA(user32_module, "EDITMENU");
3357         HMENU popup = GetSubMenu(menu, 0);
3358         UINT start = es->selection_start;
3359         UINT end = es->selection_end;
3360
3361         ORDER_UINT(start, end);
3362
3363         /* undo */
3364         EnableMenuItem(popup, 0, MF_BYPOSITION | (EDIT_EM_CanUndo(es) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3365         /* cut */
3366         EnableMenuItem(popup, 2, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3367         /* copy */
3368         EnableMenuItem(popup, 3, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) ? MF_ENABLED : MF_GRAYED));
3369         /* paste */
3370         EnableMenuItem(popup, 4, MF_BYPOSITION | (IsClipboardFormatAvailable(CF_UNICODETEXT) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3371         /* delete */
3372         EnableMenuItem(popup, 5, MF_BYPOSITION | ((end - start) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3373         /* select all */
3374         EnableMenuItem(popup, 7, MF_BYPOSITION | (start || (end != get_text_length(es)) ? MF_ENABLED : MF_GRAYED));
3375
3376         if (x == -1 && y == -1) /* passed via VK_APPS press/release */
3377         {
3378             RECT rc;
3379             /* Windows places the menu at the edit's center in this case */
3380             GetClientRect(es->hwndSelf, &rc);
3381             MapWindowPoints(es->hwndSelf, 0, (POINT *)&rc, 2);
3382             x = rc.left + (rc.right - rc.left) / 2;
3383             y = rc.top + (rc.bottom - rc.top) / 2;
3384         }
3385
3386         TrackPopupMenu(popup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, es->hwndSelf, NULL);
3387         DestroyMenu(menu);
3388 }
3389
3390
3391 /*********************************************************************
3392  *
3393  *      WM_GETTEXT
3394  *
3395  */
3396 static INT EDIT_WM_GetText(const EDITSTATE *es, INT count, LPWSTR dst, BOOL unicode)
3397 {
3398     if(!count) return 0;
3399
3400     if(unicode)
3401     {
3402         lstrcpynW(dst, es->text, count);
3403         return strlenW(dst);
3404     }
3405     else
3406     {
3407         LPSTR textA = (LPSTR)dst;
3408         if (!WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, count, NULL, NULL))
3409             textA[count - 1] = 0; /* ensure 0 termination */
3410         return strlen(textA);
3411     }
3412 }
3413
3414 /*********************************************************************
3415  *
3416  *      EDIT_CheckCombo
3417  *
3418  */
3419 static BOOL EDIT_CheckCombo(EDITSTATE *es, UINT msg, INT key)
3420 {
3421    HWND hLBox = es->hwndListBox;
3422    HWND hCombo;
3423    BOOL bDropped;
3424    int  nEUI;
3425
3426    if (!hLBox)
3427       return FALSE;
3428
3429    hCombo   = GetParent(es->hwndSelf);
3430    bDropped = TRUE;
3431    nEUI     = 0;
3432
3433    TRACE_(combo)("[%p]: handling msg %x (%x)\n", es->hwndSelf, msg, key);
3434
3435    if (key == VK_UP || key == VK_DOWN)
3436    {
3437       if (SendMessageW(hCombo, CB_GETEXTENDEDUI, 0, 0))
3438          nEUI = 1;
3439
3440       if (msg == WM_KEYDOWN || nEUI)
3441           bDropped = (BOOL)SendMessageW(hCombo, CB_GETDROPPEDSTATE, 0, 0);
3442    }
3443
3444    switch (msg)
3445    {
3446       case WM_KEYDOWN:
3447          if (!bDropped && nEUI && (key == VK_UP || key == VK_DOWN))
3448          {
3449             /* make sure ComboLBox pops up */
3450             SendMessageW(hCombo, CB_SETEXTENDEDUI, FALSE, 0);
3451             key = VK_F4;
3452             nEUI = 2;
3453          }
3454
3455          SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)key, 0);
3456          break;
3457
3458       case WM_SYSKEYDOWN: /* Handle Alt+up/down arrows */
3459          if (nEUI)
3460             SendMessageW(hCombo, CB_SHOWDROPDOWN, bDropped ? FALSE : TRUE, 0);
3461          else
3462             SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)VK_F4, 0);
3463          break;
3464    }
3465
3466    if(nEUI == 2)
3467       SendMessageW(hCombo, CB_SETEXTENDEDUI, TRUE, 0);
3468
3469    return TRUE;
3470 }
3471
3472
3473 /*********************************************************************
3474  *
3475  *      WM_KEYDOWN
3476  *
3477  *      Handling of special keys that don't produce a WM_CHAR
3478  *      (i.e. non-printable keys) & Backspace & Delete
3479  *
3480  */
3481 static LRESULT EDIT_WM_KeyDown(EDITSTATE *es, INT key)
3482 {
3483         BOOL shift;
3484         BOOL control;
3485
3486         if (GetKeyState(VK_MENU) & 0x8000)
3487                 return 0;
3488
3489         shift = GetKeyState(VK_SHIFT) & 0x8000;
3490         control = GetKeyState(VK_CONTROL) & 0x8000;
3491
3492         switch (key) {
3493         case VK_F4:
3494         case VK_UP:
3495                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key) || key == VK_F4)
3496                         break;
3497
3498                 /* fall through */
3499         case VK_LEFT:
3500                 if ((es->style & ES_MULTILINE) && (key == VK_UP))
3501                         EDIT_MoveUp_ML(es, shift);
3502                 else
3503                         if (control)
3504                                 EDIT_MoveWordBackward(es, shift);
3505                         else
3506                                 EDIT_MoveBackward(es, shift);
3507                 break;
3508         case VK_DOWN:
3509                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key))
3510                         break;
3511                 /* fall through */
3512         case VK_RIGHT:
3513                 if ((es->style & ES_MULTILINE) && (key == VK_DOWN))
3514                         EDIT_MoveDown_ML(es, shift);
3515                 else if (control)
3516                         EDIT_MoveWordForward(es, shift);
3517                 else
3518                         EDIT_MoveForward(es, shift);
3519                 break;
3520         case VK_HOME:
3521                 EDIT_MoveHome(es, shift, control);
3522                 break;
3523         case VK_END:
3524                 EDIT_MoveEnd(es, shift, control);
3525                 break;
3526         case VK_PRIOR:
3527                 if (es->style & ES_MULTILINE)
3528                         EDIT_MovePageUp_ML(es, shift);
3529                 else
3530                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
3531                 break;
3532         case VK_NEXT:
3533                 if (es->style & ES_MULTILINE)
3534                         EDIT_MovePageDown_ML(es, shift);
3535                 else
3536                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
3537                 break;
3538         case VK_DELETE:
3539                 if (!(es->style & ES_READONLY) && !(shift && control)) {
3540                         if (es->selection_start != es->selection_end) {
3541                                 if (shift)
3542                                         EDIT_WM_Cut(es);
3543                                 else
3544                                         EDIT_WM_Clear(es);
3545                         } else {
3546                                 if (shift) {
3547                                         /* delete character left of caret */
3548                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3549                                         EDIT_MoveBackward(es, TRUE);
3550                                         EDIT_WM_Clear(es);
3551                                 } else if (control) {
3552                                         /* delete to end of line */
3553                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3554                                         EDIT_MoveEnd(es, TRUE, FALSE);
3555                                         EDIT_WM_Clear(es);
3556                                 } else {
3557                                         /* delete character right of caret */
3558                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3559                                         EDIT_MoveForward(es, TRUE);
3560                                         EDIT_WM_Clear(es);
3561                                 }
3562                         }
3563                 }
3564                 break;
3565         case VK_INSERT:
3566                 if (shift) {
3567                         if (!(es->style & ES_READONLY))
3568                                 EDIT_WM_Paste(es);
3569                 } else if (control)
3570                         EDIT_WM_Copy(es);
3571                 break;
3572         case VK_RETURN:
3573             /* If the edit doesn't want the return send a message to the default object */
3574             if(!(es->style & ES_MULTILINE) || !(es->style & ES_WANTRETURN))
3575             {
3576                 DWORD dw;
3577
3578                 if (!EDIT_IsInsideDialog(es)) break;
3579                 if (control) break;
3580                 dw = SendMessageW(es->hwndParent, DM_GETDEFID, 0, 0);
3581                 if (HIWORD(dw) == DC_HASDEFID)
3582                 {
3583                     HWND hwDefCtrl = GetDlgItem(es->hwndParent, LOWORD(dw));
3584                     if (hwDefCtrl)
3585                     {
3586                         SendMessageW(es->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, (LPARAM)TRUE);
3587                         PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
3588                     }
3589                 }
3590             }
3591             break;
3592         case VK_ESCAPE:
3593             if ((es->style & ES_MULTILINE) && EDIT_IsInsideDialog(es))
3594                 PostMessageW(es->hwndParent, WM_CLOSE, 0, 0);
3595             break;
3596         case VK_TAB:
3597             if ((es->style & ES_MULTILINE) && EDIT_IsInsideDialog(es))
3598                 SendMessageW(es->hwndParent, WM_NEXTDLGCTL, shift, 0);
3599             break;
3600         }
3601         return TRUE;
3602 }
3603
3604
3605 /*********************************************************************
3606  *
3607  *      WM_KILLFOCUS
3608  *
3609  */
3610 static LRESULT EDIT_WM_KillFocus(EDITSTATE *es)
3611 {
3612         es->flags &= ~EF_FOCUSED;
3613         DestroyCaret();
3614         if(!(es->style & ES_NOHIDESEL))
3615                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
3616         EDIT_NOTIFY_PARENT(es, EN_KILLFOCUS);
3617         return 0;
3618 }
3619
3620
3621 /*********************************************************************
3622  *
3623  *      WM_LBUTTONDBLCLK
3624  *
3625  *      The caret position has been set on the WM_LBUTTONDOWN message
3626  *
3627  */
3628 static LRESULT EDIT_WM_LButtonDblClk(EDITSTATE *es)
3629 {
3630         INT s;
3631         INT e = es->selection_end;
3632         INT l;
3633         INT li;
3634         INT ll;
3635
3636         es->bCaptureState = TRUE;
3637         SetCapture(es->hwndSelf);
3638
3639         l = EDIT_EM_LineFromChar(es, e);
3640         li = EDIT_EM_LineIndex(es, l);
3641         ll = EDIT_EM_LineLength(es, e);
3642         s = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_LEFT);
3643         e = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_RIGHT);
3644         EDIT_EM_SetSel(es, s, e, FALSE);
3645         EDIT_EM_ScrollCaret(es);
3646         es->region_posx = es->region_posy = 0;
3647         SetTimer(es->hwndSelf, 0, 100, NULL);
3648         return 0;
3649 }
3650
3651
3652 /*********************************************************************
3653  *
3654  *      WM_LBUTTONDOWN
3655  *
3656  */
3657 static LRESULT EDIT_WM_LButtonDown(EDITSTATE *es, DWORD keys, INT x, INT y)
3658 {
3659         INT e;
3660         BOOL after_wrap;
3661
3662         es->bCaptureState = TRUE;
3663         SetCapture(es->hwndSelf);
3664         EDIT_ConfinePoint(es, &x, &y);
3665         e = EDIT_CharFromPos(es, x, y, &after_wrap);
3666         EDIT_EM_SetSel(es, (keys & MK_SHIFT) ? es->selection_start : e, e, after_wrap);
3667         EDIT_EM_ScrollCaret(es);
3668         es->region_posx = es->region_posy = 0;
3669         SetTimer(es->hwndSelf, 0, 100, NULL);
3670
3671         if (!(es->flags & EF_FOCUSED))
3672             SetFocus(es->hwndSelf);
3673
3674         return 0;
3675 }
3676
3677
3678 /*********************************************************************
3679  *
3680  *      WM_LBUTTONUP
3681  *
3682  */
3683 static LRESULT EDIT_WM_LButtonUp(EDITSTATE *es)
3684 {
3685         if (es->bCaptureState) {
3686                 KillTimer(es->hwndSelf, 0);
3687                 if (GetCapture() == es->hwndSelf) ReleaseCapture();
3688         }
3689         es->bCaptureState = FALSE;
3690         return 0;
3691 }
3692
3693
3694 /*********************************************************************
3695  *
3696  *      WM_MBUTTONDOWN
3697  *
3698  */
3699 static LRESULT EDIT_WM_MButtonDown(EDITSTATE *es)
3700 {
3701     SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3702     return 0;
3703 }
3704
3705
3706 /*********************************************************************
3707  *
3708  *      WM_MOUSEMOVE
3709  *
3710  */
3711 static LRESULT EDIT_WM_MouseMove(EDITSTATE *es, INT x, INT y)
3712 {
3713         INT e;
3714         BOOL after_wrap;
3715         INT prex, prey;
3716
3717         /* If the mouse has been captured by process other than the edit control itself,
3718          * the windows edit controls will not select the strings with mouse move.
3719          */
3720         if (!es->bCaptureState || GetCapture() != es->hwndSelf)
3721                 return 0;
3722
3723         /*
3724          *      FIXME: gotta do some scrolling if outside client
3725          *              area.  Maybe reset the timer ?
3726          */
3727         prex = x; prey = y;
3728         EDIT_ConfinePoint(es, &x, &y);
3729         es->region_posx = (prex < x) ? -1 : ((prex > x) ? 1 : 0);
3730         es->region_posy = (prey < y) ? -1 : ((prey > y) ? 1 : 0);
3731         e = EDIT_CharFromPos(es, x, y, &after_wrap);
3732         EDIT_EM_SetSel(es, es->selection_start, e, after_wrap);
3733         EDIT_SetCaretPos(es,es->selection_end,es->flags & EF_AFTER_WRAP);
3734         return 0;
3735 }
3736
3737
3738 /*********************************************************************
3739  *
3740  *      WM_PAINT
3741  *
3742  */
3743 static void EDIT_WM_Paint(EDITSTATE *es, HDC hdc)
3744 {
3745         PAINTSTRUCT ps;
3746         INT i;
3747         HDC dc;
3748         HFONT old_font = 0;
3749         RECT rc;
3750         RECT rcClient;
3751         RECT rcLine;
3752         RECT rcRgn;
3753         HBRUSH brush;
3754         HBRUSH old_brush;
3755         INT bw, bh;
3756         BOOL rev = es->bEnableState &&
3757                                 ((es->flags & EF_FOCUSED) ||
3758                                         (es->style & ES_NOHIDESEL));
3759         dc = hdc ? hdc : BeginPaint(es->hwndSelf, &ps);
3760
3761         GetClientRect(es->hwndSelf, &rcClient);
3762
3763         /* get the background brush */
3764         brush = EDIT_NotifyCtlColor(es, dc);
3765
3766         /* paint the border and the background */
3767         IntersectClipRect(dc, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom);
3768         
3769         if(es->style & WS_BORDER) {
3770                 bw = GetSystemMetrics(SM_CXBORDER);
3771                 bh = GetSystemMetrics(SM_CYBORDER);
3772                 rc = rcClient;
3773                 if(es->style & ES_MULTILINE) {
3774                         if(es->style & WS_HSCROLL) rc.bottom+=bh;
3775                         if(es->style & WS_VSCROLL) rc.right+=bw;
3776                 }
3777                 
3778                 /* Draw the frame. Same code as in nonclient.c */
3779                 old_brush = SelectObject(dc, GetSysColorBrush(COLOR_WINDOWFRAME));
3780                 PatBlt(dc, rc.left, rc.top, rc.right - rc.left, bh, PATCOPY);
3781                 PatBlt(dc, rc.left, rc.top, bw, rc.bottom - rc.top, PATCOPY);
3782                 PatBlt(dc, rc.left, rc.bottom - 1, rc.right - rc.left, -bw, PATCOPY);
3783                 PatBlt(dc, rc.right - 1, rc.top, -bw, rc.bottom - rc.top, PATCOPY);
3784                 SelectObject(dc, old_brush);
3785                 
3786                 /* Keep the border clean */
3787                 IntersectClipRect(dc, rc.left+bw, rc.top+bh,
3788                     max(rc.right-bw, rc.left+bw), max(rc.bottom-bh, rc.top+bh));
3789         }
3790         
3791         GetClipBox(dc, &rc);
3792         FillRect(dc, &rc, brush);
3793
3794         IntersectClipRect(dc, es->format_rect.left,
3795                                 es->format_rect.top,
3796                                 es->format_rect.right,
3797                                 es->format_rect.bottom);
3798         if (es->style & ES_MULTILINE) {
3799                 rc = rcClient;
3800                 IntersectClipRect(dc, rc.left, rc.top, rc.right, rc.bottom);
3801         }
3802         if (es->font)
3803                 old_font = SelectObject(dc, es->font);
3804
3805         if (!es->bEnableState)
3806                 SetTextColor(dc, GetSysColor(COLOR_GRAYTEXT));
3807         GetClipBox(dc, &rcRgn);
3808         if (es->style & ES_MULTILINE) {
3809                 INT vlc = get_vertical_line_count(es);
3810                 for (i = es->y_offset ; i <= min(es->y_offset + vlc, es->y_offset + es->line_count - 1) ; i++) {
3811                         EDIT_GetLineRect(es, i, 0, -1, &rcLine);
3812                         if (IntersectRect(&rc, &rcRgn, &rcLine))
3813                                 EDIT_PaintLine(es, dc, i, rev);
3814                 }
3815         } else {
3816                 EDIT_GetLineRect(es, 0, 0, -1, &rcLine);
3817                 if (IntersectRect(&rc, &rcRgn, &rcLine))
3818                         EDIT_PaintLine(es, dc, 0, rev);
3819         }
3820         if (es->font)
3821                 SelectObject(dc, old_font);
3822
3823         if (!hdc)
3824             EndPaint(es->hwndSelf, &ps);
3825 }
3826
3827
3828 /*********************************************************************
3829  *
3830  *      WM_SETFOCUS
3831  *
3832  */
3833 static void EDIT_WM_SetFocus(EDITSTATE *es)
3834 {
3835         es->flags |= EF_FOCUSED;
3836
3837         if (!(es->style & ES_NOHIDESEL))
3838             EDIT_InvalidateText(es, es->selection_start, es->selection_end);
3839
3840         /* single line edit updates itself */
3841         if (!(es->style & ES_MULTILINE))
3842         {
3843             HDC hdc = GetDC(es->hwndSelf);
3844             EDIT_WM_Paint(es, hdc);
3845             ReleaseDC(es->hwndSelf, hdc);
3846         }
3847
3848         CreateCaret(es->hwndSelf, 0, 1, es->line_height);
3849         EDIT_SetCaretPos(es, es->selection_end,
3850                          es->flags & EF_AFTER_WRAP);
3851         ShowCaret(es->hwndSelf);
3852         EDIT_NOTIFY_PARENT(es, EN_SETFOCUS);
3853 }
3854
3855
3856 /*********************************************************************
3857  *
3858  *      WM_SETFONT
3859  *
3860  * With Win95 look the margins are set to default font value unless
3861  * the system font (font == 0) is being set, in which case they are left
3862  * unchanged.
3863  *
3864  */
3865 static void EDIT_WM_SetFont(EDITSTATE *es, HFONT font, BOOL redraw)
3866 {
3867         TEXTMETRICW tm;
3868         HDC dc;
3869         HFONT old_font = 0;
3870         RECT clientRect;
3871
3872         es->font = font;
3873         dc = GetDC(es->hwndSelf);
3874         if (font)
3875                 old_font = SelectObject(dc, font);
3876         GetTextMetricsW(dc, &tm);
3877         es->line_height = tm.tmHeight;
3878         es->char_width = tm.tmAveCharWidth;
3879         if (font)
3880                 SelectObject(dc, old_font);
3881         ReleaseDC(es->hwndSelf, dc);
3882         
3883         /* Reset the format rect and the margins */
3884         GetClientRect(es->hwndSelf, &clientRect);
3885         EDIT_SetRectNP(es, &clientRect);
3886         EDIT_EM_SetMargins(es, EC_LEFTMARGIN | EC_RIGHTMARGIN,
3887                            EC_USEFONTINFO, EC_USEFONTINFO, FALSE);
3888
3889         if (es->style & ES_MULTILINE)
3890                 EDIT_BuildLineDefs_ML(es, 0, get_text_length(es), 0, NULL);
3891         else
3892             EDIT_CalcLineWidth_SL(es);
3893
3894         if (redraw)
3895                 EDIT_UpdateText(es, NULL, TRUE);
3896         if (es->flags & EF_FOCUSED) {
3897                 DestroyCaret();
3898                 CreateCaret(es->hwndSelf, 0, 1, es->line_height);
3899                 EDIT_SetCaretPos(es, es->selection_end,
3900                                  es->flags & EF_AFTER_WRAP);
3901                 ShowCaret(es->hwndSelf);
3902         }
3903 }
3904
3905
3906 /*********************************************************************
3907  *
3908  *      WM_SETTEXT
3909  *
3910  * NOTES
3911  *  For multiline controls (ES_MULTILINE), reception of WM_SETTEXT triggers:
3912  *  The modified flag is reset. No notifications are sent.
3913  *
3914  *  For single-line controls, reception of WM_SETTEXT triggers:
3915  *  The modified flag is reset. EN_UPDATE and EN_CHANGE notifications are sent.
3916  *
3917  */
3918 static void EDIT_WM_SetText(EDITSTATE *es, LPCWSTR text, BOOL unicode)
3919 {
3920     LPWSTR textW = NULL;
3921     if (!unicode && text)
3922     {
3923         LPCSTR textA = (LPCSTR)text;
3924         INT countW = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
3925         textW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR));
3926         if (textW)
3927             MultiByteToWideChar(CP_ACP, 0, textA, -1, textW, countW);
3928         text = textW;
3929     }
3930
3931     if (es->flags & EF_UPDATE)
3932         /* fixed this bug once; complain if we see it about to happen again. */
3933         ERR("SetSel may generate UPDATE message whose handler may reset "
3934             "selection.\n");
3935
3936     EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
3937     if (text) 
3938     {
3939         TRACE("%s\n", debugstr_w(text));
3940         EDIT_EM_ReplaceSel(es, FALSE, text, FALSE, FALSE);
3941         if(!unicode)
3942             HeapFree(GetProcessHeap(), 0, textW);
3943     } 
3944     else 
3945     {
3946         static const WCHAR empty_stringW[] = {0};
3947         TRACE("<NULL>\n");
3948         EDIT_EM_ReplaceSel(es, FALSE, empty_stringW, FALSE, FALSE);
3949     }
3950     es->x_offset = 0;
3951     es->flags &= ~EF_MODIFIED;
3952     EDIT_EM_SetSel(es, 0, 0, FALSE);
3953
3954     /* Send the notification after the selection start and end have been set
3955      * edit control doesn't send notification on WM_SETTEXT
3956      * if it is multiline, or it is part of combobox
3957      */
3958     if( !((es->style & ES_MULTILINE) || es->hwndListBox))
3959     {
3960         EDIT_NOTIFY_PARENT(es, EN_UPDATE);
3961         EDIT_NOTIFY_PARENT(es, EN_CHANGE);
3962     }
3963     EDIT_EM_ScrollCaret(es);
3964     EDIT_UpdateScrollInfo(es);    
3965 }
3966
3967
3968 /*********************************************************************
3969  *
3970  *      WM_SIZE
3971  *
3972  */
3973 static void EDIT_WM_Size(EDITSTATE *es, UINT action, INT width, INT height)
3974 {
3975         if ((action == SIZE_MAXIMIZED) || (action == SIZE_RESTORED)) {
3976                 RECT rc;
3977                 TRACE("width = %d, height = %d\n", width, height);
3978                 SetRect(&rc, 0, 0, width, height);
3979                 EDIT_SetRectNP(es, &rc);
3980                 EDIT_UpdateText(es, NULL, TRUE);
3981         }
3982 }
3983
3984
3985 /*********************************************************************
3986  *
3987  *      WM_STYLECHANGED
3988  *
3989  * This message is sent by SetWindowLong on having changed either the Style
3990  * or the extended style.
3991  *
3992  * We ensure that the window's version of the styles and the EDITSTATE's agree.
3993  *
3994  * See also EDIT_WM_NCCreate
3995  *
3996  * It appears that the Windows version of the edit control allows the style
3997  * (as retrieved by GetWindowLong) to be any value and maintains an internal
3998  * style variable which will generally be different.  In this function we
3999  * update the internal style based on what changed in the externally visible
4000  * style.
4001  *
4002  * Much of this content as based upon the MSDN, especially:
4003  *  Platform SDK Documentation -> User Interface Services ->
4004  *      Windows User Interface -> Edit Controls -> Edit Control Reference ->
4005  *      Edit Control Styles
4006  */
4007 static LRESULT  EDIT_WM_StyleChanged ( EDITSTATE *es, WPARAM which, const STYLESTRUCT *style)
4008 {
4009         if (GWL_STYLE == which) {
4010                 DWORD style_change_mask;
4011                 DWORD new_style;
4012                 /* Only a subset of changes can be applied after the control
4013                  * has been created.
4014                  */
4015                 style_change_mask = ES_UPPERCASE | ES_LOWERCASE |
4016                                     ES_NUMBER;
4017                 if (es->style & ES_MULTILINE)
4018                         style_change_mask |= ES_WANTRETURN;
4019
4020                 new_style = style->styleNew & style_change_mask;
4021
4022                 /* Number overrides lowercase overrides uppercase (at least it
4023                  * does in Win95).  However I'll bet that ES_NUMBER would be
4024                  * invalid under Win 3.1.
4025                  */
4026                 if (new_style & ES_NUMBER) {
4027                         ; /* do not override the ES_NUMBER */
4028                 }  else if (new_style & ES_LOWERCASE) {
4029                         new_style &= ~ES_UPPERCASE;
4030                 }
4031
4032                 es->style = (es->style & ~style_change_mask) | new_style;
4033         } else if (GWL_EXSTYLE == which) {
4034                 ; /* FIXME - what is needed here */
4035         } else {
4036                 WARN ("Invalid style change %ld\n",which);
4037         }
4038
4039         return 0;
4040 }
4041
4042 /*********************************************************************
4043  *
4044  *      WM_SYSKEYDOWN
4045  *
4046  */
4047 static LRESULT EDIT_WM_SysKeyDown(EDITSTATE *es, INT key, DWORD key_data)
4048 {
4049         if ((key == VK_BACK) && (key_data & 0x2000)) {
4050                 if (EDIT_EM_CanUndo(es))
4051                         EDIT_EM_Undo(es);
4052                 return 0;
4053         } else if (key == VK_UP || key == VK_DOWN) {
4054                 if (EDIT_CheckCombo(es, WM_SYSKEYDOWN, key))
4055                         return 0;
4056         }
4057         return DefWindowProcW(es->hwndSelf, WM_SYSKEYDOWN, (WPARAM)key, (LPARAM)key_data);
4058 }
4059
4060
4061 /*********************************************************************
4062  *
4063  *      WM_TIMER
4064  *
4065  */
4066 static void EDIT_WM_Timer(EDITSTATE *es)
4067 {
4068         if (es->region_posx < 0) {
4069                 EDIT_MoveBackward(es, TRUE);
4070         } else if (es->region_posx > 0) {
4071                 EDIT_MoveForward(es, TRUE);
4072         }
4073 /*
4074  *      FIXME: gotta do some vertical scrolling here, like
4075  *              EDIT_EM_LineScroll(hwnd, 0, 1);
4076  */
4077 }
4078
4079 /*********************************************************************
4080  *
4081  *      WM_HSCROLL
4082  *
4083  */
4084 static LRESULT EDIT_WM_HScroll(EDITSTATE *es, INT action, INT pos)
4085 {
4086         INT dx;
4087         INT fw;
4088
4089         if (!(es->style & ES_MULTILINE))
4090                 return 0;
4091
4092         if (!(es->style & ES_AUTOHSCROLL))
4093                 return 0;
4094
4095         dx = 0;
4096         fw = es->format_rect.right - es->format_rect.left;
4097         switch (action) {
4098         case SB_LINELEFT:
4099                 TRACE("SB_LINELEFT\n");
4100                 if (es->x_offset)
4101                         dx = -es->char_width;
4102                 break;
4103         case SB_LINERIGHT:
4104                 TRACE("SB_LINERIGHT\n");
4105                 if (es->x_offset < es->text_width)
4106                         dx = es->char_width;
4107                 break;
4108         case SB_PAGELEFT:
4109                 TRACE("SB_PAGELEFT\n");
4110                 if (es->x_offset)
4111                         dx = -fw / HSCROLL_FRACTION / es->char_width * es->char_width;
4112                 break;
4113         case SB_PAGERIGHT:
4114                 TRACE("SB_PAGERIGHT\n");
4115                 if (es->x_offset < es->text_width)
4116                         dx = fw / HSCROLL_FRACTION / es->char_width * es->char_width;
4117                 break;
4118         case SB_LEFT:
4119                 TRACE("SB_LEFT\n");
4120                 if (es->x_offset)
4121                         dx = -es->x_offset;
4122                 break;
4123         case SB_RIGHT:
4124                 TRACE("SB_RIGHT\n");
4125                 if (es->x_offset < es->text_width)
4126                         dx = es->text_width - es->x_offset;
4127                 break;
4128         case SB_THUMBTRACK:
4129                 TRACE("SB_THUMBTRACK %d\n", pos);
4130                 es->flags |= EF_HSCROLL_TRACK;
4131                 if(es->style & WS_HSCROLL)
4132                     dx = pos - es->x_offset;
4133                 else
4134                 {
4135                     INT fw, new_x;
4136                     /* Sanity check */
4137                     if(pos < 0 || pos > 100) return 0;
4138                     /* Assume default scroll range 0-100 */
4139                     fw = es->format_rect.right - es->format_rect.left;
4140                     new_x = pos * (es->text_width - fw) / 100;
4141                     dx = es->text_width ? (new_x - es->x_offset) : 0;
4142                 }
4143                 break;
4144         case SB_THUMBPOSITION:
4145                 TRACE("SB_THUMBPOSITION %d\n", pos);
4146                 es->flags &= ~EF_HSCROLL_TRACK;
4147                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
4148                     dx = pos - es->x_offset;
4149                 else
4150                 {
4151                     INT fw, new_x;
4152                     /* Sanity check */
4153                     if(pos < 0 || pos > 100) return 0;
4154                     /* Assume default scroll range 0-100 */
4155                     fw = es->format_rect.right - es->format_rect.left;
4156                     new_x = pos * (es->text_width - fw) / 100;
4157                     dx = es->text_width ? (new_x - es->x_offset) : 0;
4158                 }
4159                 if (!dx) {
4160                         /* force scroll info update */
4161                         EDIT_UpdateScrollInfo(es);
4162                         EDIT_NOTIFY_PARENT(es, EN_HSCROLL);
4163                 }
4164                 break;
4165         case SB_ENDSCROLL:
4166                 TRACE("SB_ENDSCROLL\n");
4167                 break;
4168         /*
4169          *      FIXME : the next two are undocumented !
4170          *      Are we doing the right thing ?
4171          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
4172          *      although it's also a regular control message.
4173          */
4174         case EM_GETTHUMB: /* this one is used by NT notepad */
4175         case EM_GETTHUMB16:
4176         {
4177                 LRESULT ret;
4178                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
4179                     ret = GetScrollPos(es->hwndSelf, SB_HORZ);
4180                 else
4181                 {
4182                     /* Assume default scroll range 0-100 */
4183                     INT fw = es->format_rect.right - es->format_rect.left;
4184                     ret = es->text_width ? es->x_offset * 100 / (es->text_width - fw) : 0;
4185                 }
4186                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
4187                 return ret;
4188         }
4189         case EM_LINESCROLL16:
4190                 TRACE("EM_LINESCROLL16\n");
4191                 dx = pos;
4192                 break;
4193
4194         default:
4195                 ERR("undocumented WM_HSCROLL action %d (0x%04x), please report\n",
4196                     action, action);
4197                 return 0;
4198         }
4199         if (dx)
4200         {
4201             INT fw = es->format_rect.right - es->format_rect.left;
4202             /* check if we are going to move too far */
4203             if(es->x_offset + dx + fw > es->text_width)
4204                 dx = es->text_width - fw - es->x_offset;
4205             if(dx)
4206                 EDIT_EM_LineScroll_internal(es, dx, 0);
4207         }
4208         return 0;
4209 }
4210
4211
4212 /*********************************************************************
4213  *
4214  *      WM_VSCROLL
4215  *
4216  */
4217 static LRESULT EDIT_WM_VScroll(EDITSTATE *es, INT action, INT pos)
4218 {
4219         INT dy;
4220
4221         if (!(es->style & ES_MULTILINE))
4222                 return 0;
4223
4224         if (!(es->style & ES_AUTOVSCROLL))
4225                 return 0;
4226
4227         dy = 0;
4228         switch (action) {
4229         case SB_LINEUP:
4230         case SB_LINEDOWN:
4231         case SB_PAGEUP:
4232         case SB_PAGEDOWN:
4233                 TRACE("action %d (%s)\n", action, (action == SB_LINEUP ? "SB_LINEUP" :
4234                                                    (action == SB_LINEDOWN ? "SB_LINEDOWN" :
4235                                                     (action == SB_PAGEUP ? "SB_PAGEUP" :
4236                                                      "SB_PAGEDOWN"))));
4237                 EDIT_EM_Scroll(es, action);
4238                 return 0;
4239         case SB_TOP:
4240                 TRACE("SB_TOP\n");
4241                 dy = -es->y_offset;
4242                 break;
4243         case SB_BOTTOM:
4244                 TRACE("SB_BOTTOM\n");
4245                 dy = es->line_count - 1 - es->y_offset;
4246                 break;
4247         case SB_THUMBTRACK:
4248                 TRACE("SB_THUMBTRACK %d\n", pos);
4249                 es->flags |= EF_VSCROLL_TRACK;
4250                 if(es->style & WS_VSCROLL)
4251                     dy = pos - es->y_offset;
4252                 else
4253                 {
4254                     /* Assume default scroll range 0-100 */
4255                     INT vlc, new_y;
4256                     /* Sanity check */
4257                     if(pos < 0 || pos > 100) return 0;
4258                     vlc = get_vertical_line_count(es);
4259                     new_y = pos * (es->line_count - vlc) / 100;
4260                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4261                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4262                             es->line_count, es->y_offset, pos, dy);
4263                 }
4264                 break;
4265         case SB_THUMBPOSITION:
4266                 TRACE("SB_THUMBPOSITION %d\n", pos);
4267                 es->flags &= ~EF_VSCROLL_TRACK;
4268                 if(es->style & WS_VSCROLL)
4269                     dy = pos - es->y_offset;
4270                 else
4271                 {
4272                     /* Assume default scroll range 0-100 */
4273                     INT vlc, new_y;
4274                     /* Sanity check */
4275                     if(pos < 0 || pos > 100) return 0;
4276                     vlc = get_vertical_line_count(es);
4277                     new_y = pos * (es->line_count - vlc) / 100;
4278                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4279                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4280                             es->line_count, es->y_offset, pos, dy);
4281                 }
4282                 if (!dy)
4283                 {
4284                         /* force scroll info update */
4285                         EDIT_UpdateScrollInfo(es);
4286                         EDIT_NOTIFY_PARENT(es, EN_VSCROLL);
4287                 }
4288                 break;
4289         case SB_ENDSCROLL:
4290                 TRACE("SB_ENDSCROLL\n");
4291                 break;
4292         /*
4293          *      FIXME : the next two are undocumented !
4294          *      Are we doing the right thing ?
4295          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
4296          *      although it's also a regular control message.
4297          */
4298         case EM_GETTHUMB: /* this one is used by NT notepad */
4299         case EM_GETTHUMB16:
4300         {
4301                 LRESULT ret;
4302                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_VSCROLL)
4303                     ret = GetScrollPos(es->hwndSelf, SB_VERT);
4304                 else
4305                 {
4306                     /* Assume default scroll range 0-100 */
4307                     INT vlc = get_vertical_line_count(es);
4308                     ret = es->line_count ? es->y_offset * 100 / (es->line_count - vlc) : 0;
4309                 }
4310                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
4311                 return ret;
4312         }
4313         case EM_LINESCROLL16:
4314                 TRACE("EM_LINESCROLL16 %d\n", pos);
4315                 dy = pos;
4316                 break;
4317
4318         default:
4319                 ERR("undocumented WM_VSCROLL action %d (0x%04x), please report\n",
4320                     action, action);
4321                 return 0;
4322         }
4323         if (dy)
4324                 EDIT_EM_LineScroll(es, 0, dy);
4325         return 0;
4326 }
4327
4328 /*********************************************************************
4329  *
4330  *      EM_GETTHUMB
4331  *
4332  *      FIXME: is this right ?  (or should it be only VSCROLL)
4333  *      (and maybe only for edit controls that really have their
4334  *      own scrollbars) (and maybe only for multiline controls ?)
4335  *      All in all: very poorly documented
4336  *
4337  */
4338 static LRESULT EDIT_EM_GetThumb(EDITSTATE *es)
4339 {
4340         return MAKELONG(EDIT_WM_VScroll(es, EM_GETTHUMB16, 0),
4341                 EDIT_WM_HScroll(es, EM_GETTHUMB16, 0));
4342 }
4343
4344
4345 /********************************************************************
4346  * 
4347  * The Following code is to handle inline editing from IMEs
4348  */
4349
4350 static void EDIT_GetCompositionStr(HIMC hIMC, LPARAM CompFlag, EDITSTATE *es)
4351 {
4352     LONG buflen;
4353     LPWSTR lpCompStr = NULL;
4354     LPSTR lpCompStrAttr = NULL;
4355     DWORD dwBufLenAttr;
4356
4357     buflen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4358
4359     if (buflen < 0)
4360     {
4361         return;
4362     }
4363
4364     lpCompStr = HeapAlloc(GetProcessHeap(),0,buflen + sizeof(WCHAR));
4365     if (!lpCompStr)
4366     {
4367         ERR("Unable to allocate IME CompositionString\n");
4368         return;
4369     }
4370
4371     if (buflen)
4372         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, buflen);
4373     lpCompStr[buflen/sizeof(WCHAR)] = 0;
4374
4375     if (CompFlag & GCS_COMPATTR)
4376     {
4377         /* 
4378          * We do not use the attributes yet. it would tell us what characters
4379          * are in transition and which are converted or decided upon
4380          */
4381         dwBufLenAttr = ImmGetCompositionStringW(hIMC, GCS_COMPATTR, NULL, 0);
4382         if (dwBufLenAttr)
4383         {
4384             dwBufLenAttr ++;
4385             lpCompStrAttr = HeapAlloc(GetProcessHeap(),0,dwBufLenAttr+1);
4386             if (!lpCompStrAttr)
4387             {
4388                 ERR("Unable to allocate IME Attribute String\n");
4389                 HeapFree(GetProcessHeap(),0,lpCompStr);
4390                 return;
4391             }
4392             ImmGetCompositionStringW(hIMC,GCS_COMPATTR, lpCompStrAttr, 
4393                     dwBufLenAttr);
4394             lpCompStrAttr[dwBufLenAttr] = 0;
4395         }
4396         else
4397             lpCompStrAttr = NULL;
4398     }
4399
4400     /* check for change in composition start */
4401     if (es->selection_end < es->composition_start)
4402         es->composition_start = es->selection_end;
4403     
4404     /* replace existing selection string */
4405     es->selection_start = es->composition_start;
4406
4407     if (es->composition_len > 0)
4408         es->selection_end = es->composition_start + es->composition_len;
4409     else
4410         es->selection_end = es->selection_start;
4411
4412     EDIT_EM_ReplaceSel(es, FALSE, lpCompStr, TRUE, TRUE);
4413     es->composition_len = abs(es->composition_start - es->selection_end);
4414
4415     es->selection_start = es->composition_start;
4416     es->selection_end = es->selection_start + es->composition_len;
4417
4418     HeapFree(GetProcessHeap(),0,lpCompStrAttr);
4419     HeapFree(GetProcessHeap(),0,lpCompStr);
4420 }
4421
4422 static void EDIT_GetResultStr(HIMC hIMC, EDITSTATE *es)
4423 {
4424     LONG buflen;
4425     LPWSTR lpResultStr;
4426
4427     buflen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
4428     if (buflen <= 0)
4429     {
4430         return;
4431     }
4432
4433     lpResultStr = HeapAlloc(GetProcessHeap(),0, buflen+sizeof(WCHAR));
4434     if (!lpResultStr)
4435     {
4436         ERR("Unable to alloc buffer for IME string\n");
4437         return;
4438     }
4439
4440     ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpResultStr, buflen);
4441     lpResultStr[buflen/sizeof(WCHAR)] = 0;
4442
4443     /* check for change in composition start */
4444     if (es->selection_end < es->composition_start)
4445         es->composition_start = es->selection_end;
4446
4447     es->selection_start = es->composition_start;
4448     es->selection_end = es->composition_start + es->composition_len;
4449     EDIT_EM_ReplaceSel(es, TRUE, lpResultStr, TRUE, TRUE);
4450     es->composition_start = es->selection_end;
4451     es->composition_len = 0;
4452
4453     HeapFree(GetProcessHeap(),0,lpResultStr);
4454 }
4455
4456 static void EDIT_ImeComposition(HWND hwnd, LPARAM CompFlag, EDITSTATE *es)
4457 {
4458     HIMC hIMC;
4459     int cursor;
4460
4461     if (es->composition_len == 0 && es->selection_start != es->selection_end)
4462     {
4463         static const WCHAR empty_stringW[] = {0};
4464         EDIT_EM_ReplaceSel(es, TRUE, empty_stringW, TRUE, TRUE);
4465         es->composition_start = es->selection_end;
4466     }
4467
4468     hIMC = ImmGetContext(hwnd);
4469     if (!hIMC)
4470         return;
4471
4472     if (CompFlag & GCS_RESULTSTR)
4473         EDIT_GetResultStr(hIMC, es);
4474     if (CompFlag & GCS_COMPSTR)
4475         EDIT_GetCompositionStr(hIMC, CompFlag, es);
4476     cursor = ImmGetCompositionStringW(hIMC, GCS_CURSORPOS, 0, 0);
4477     ImmReleaseContext(hwnd, hIMC);
4478     EDIT_SetCaretPos(es, es->selection_start + cursor, es->flags & EF_AFTER_WRAP);
4479 }
4480
4481
4482 /*********************************************************************
4483  *
4484  *      WM_NCCREATE
4485  *
4486  * See also EDIT_WM_StyleChanged
4487  */
4488 static LRESULT EDIT_WM_NCCreate(HWND hwnd, LPCREATESTRUCTW lpcs, BOOL unicode)
4489 {
4490         EDITSTATE *es;
4491         UINT alloc_size;
4492
4493         TRACE("Creating %s edit control, style = %08x\n",
4494                 unicode ? "Unicode" : "ANSI", lpcs->style);
4495
4496         if (!(es = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*es))))
4497                 return FALSE;
4498         SetWindowLongPtrW( hwnd, 0, (LONG_PTR)es );
4499
4500        /*
4501         *      Note: since the EDITSTATE has not been fully initialized yet,
4502         *            we can't use any API calls that may send
4503         *            WM_XXX messages before WM_NCCREATE is completed.
4504         */
4505
4506         es->is_unicode = unicode;
4507         es->style = lpcs->style;
4508
4509         es->bEnableState = !(es->style & WS_DISABLED);
4510
4511         es->hwndSelf = hwnd;
4512         /* Save parent, which will be notified by EN_* messages */
4513         es->hwndParent = lpcs->hwndParent;
4514
4515         if (es->style & ES_COMBO)
4516            es->hwndListBox = GetDlgItem(es->hwndParent, ID_CB_LISTBOX);
4517
4518         /* FIXME: should we handle changes to WS_EX_RIGHT style after creation? */
4519         if (lpcs->dwExStyle & WS_EX_RIGHT) es->style |= ES_RIGHT;
4520
4521         /* Number overrides lowercase overrides uppercase (at least it
4522          * does in Win95).  However I'll bet that ES_NUMBER would be
4523          * invalid under Win 3.1.
4524          */
4525         if (es->style & ES_NUMBER) {
4526                 ; /* do not override the ES_NUMBER */
4527         }  else if (es->style & ES_LOWERCASE) {
4528                 es->style &= ~ES_UPPERCASE;
4529         }
4530         if (es->style & ES_MULTILINE) {
4531                 es->buffer_limit = BUFLIMIT_INITIAL;
4532                 if (es->style & WS_VSCROLL)
4533                         es->style |= ES_AUTOVSCROLL;
4534                 if (es->style & WS_HSCROLL)
4535                         es->style |= ES_AUTOHSCROLL;
4536                 es->style &= ~ES_PASSWORD;
4537                 if ((es->style & ES_CENTER) || (es->style & ES_RIGHT)) {
4538                         /* Confirmed - RIGHT overrides CENTER */
4539                         if (es->style & ES_RIGHT)
4540                                 es->style &= ~ES_CENTER;
4541                         es->style &= ~WS_HSCROLL;
4542                         es->style &= ~ES_AUTOHSCROLL;
4543                 }
4544         } else {
4545                 es->buffer_limit = BUFLIMIT_INITIAL;
4546                 if ((es->style & ES_RIGHT) && (es->style & ES_CENTER))
4547                         es->style &= ~ES_CENTER;
4548                 es->style &= ~WS_HSCROLL;
4549                 es->style &= ~WS_VSCROLL;
4550                 if (es->style & ES_PASSWORD)
4551                         es->password_char = '*';
4552         }
4553
4554         alloc_size = ROUND_TO_GROW((es->buffer_size + 1) * sizeof(WCHAR));
4555         if(!(es->hloc32W = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
4556             goto cleanup;
4557         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
4558
4559         if (!(es->undo_text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (es->buffer_size + 1) * sizeof(WCHAR))))
4560                 goto cleanup;
4561         es->undo_buffer_size = es->buffer_size;
4562
4563         if (es->style & ES_MULTILINE)
4564                 if (!(es->first_line_def = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LINEDEF))))
4565                         goto cleanup;
4566         es->line_count = 1;
4567
4568         /*
4569          * In Win95 look and feel, the WS_BORDER style is replaced by the
4570          * WS_EX_CLIENTEDGE style for the edit control. This gives the edit
4571          * control a nonclient area so we don't need to draw the border.
4572          * If WS_BORDER without WS_EX_CLIENTEDGE is specified we shouldn't have
4573          * a nonclient area and we should handle painting the border ourselves.
4574          *
4575          * When making modifications please ensure that the code still works
4576          * for edit controls created directly with style 0x50800000, exStyle 0
4577          * (which should have a single pixel border)
4578          */
4579         if (lpcs->dwExStyle & WS_EX_CLIENTEDGE)
4580                 es->style &= ~WS_BORDER;
4581         else if (es->style & WS_BORDER)
4582                 SetWindowLongW(hwnd, GWL_STYLE, es->style & ~WS_BORDER);
4583
4584         return TRUE;
4585
4586 cleanup:
4587         SetWindowLongPtrW(es->hwndSelf, 0, 0);
4588         HeapFree(GetProcessHeap(), 0, es->first_line_def);
4589         HeapFree(GetProcessHeap(), 0, es->undo_text);
4590         if (es->hloc32W) LocalFree(es->hloc32W);
4591         HeapFree(GetProcessHeap(), 0, es);
4592         return FALSE;
4593 }
4594
4595
4596 /*********************************************************************
4597  *
4598  *      WM_CREATE
4599  *
4600  */
4601 static LRESULT EDIT_WM_Create(EDITSTATE *es, LPCWSTR name)
4602 {
4603         RECT clientRect;
4604
4605         TRACE("%s\n", debugstr_w(name));
4606        /*
4607         *       To initialize some final structure members, we call some helper
4608         *       functions.  However, since the EDITSTATE is not consistent (i.e.
4609         *       not fully initialized), we should be very careful which
4610         *       functions can be called, and in what order.
4611         */
4612         EDIT_WM_SetFont(es, 0, FALSE);
4613         EDIT_EM_EmptyUndoBuffer(es);
4614
4615         /* We need to calculate the format rect
4616            (applications may send EM_SETMARGINS before the control gets visible) */
4617         GetClientRect(es->hwndSelf, &clientRect);
4618         EDIT_SetRectNP(es, &clientRect);
4619
4620        if (name && *name) {
4621            EDIT_EM_ReplaceSel(es, FALSE, name, FALSE, FALSE);
4622            /* if we insert text to the editline, the text scrolls out
4623             * of the window, as the caret is placed after the insert
4624             * pos normally; thus we reset es->selection... to 0 and
4625             * update caret
4626             */
4627            es->selection_start = es->selection_end = 0;
4628            /* Adobe Photoshop does NOT like this. and MSDN says that EN_CHANGE
4629             * Messages are only to be sent when the USER does something to
4630             * change the contents. So I am removing this EN_CHANGE
4631             *
4632             * EDIT_NOTIFY_PARENT(es, EN_CHANGE);
4633             */
4634            EDIT_EM_ScrollCaret(es);
4635        }
4636        /* force scroll info update */
4637        EDIT_UpdateScrollInfo(es);
4638        /* The rule seems to return 1 here for success */
4639        /* Power Builder masked edit controls will crash  */
4640        /* if not. */
4641        /* FIXME: is that in all cases so ? */
4642        return 1;
4643 }
4644
4645
4646 /*********************************************************************
4647  *
4648  *      WM_NCDESTROY
4649  *
4650  */
4651 static LRESULT EDIT_WM_NCDestroy(EDITSTATE *es)
4652 {
4653         LINEDEF *pc, *pp;
4654         HLOCAL16 hloc16 = GetWindowWord( es->hwndSelf, GWW_HANDLE16 );
4655
4656         if (es->hloc32W) {
4657                 LocalFree(es->hloc32W);
4658         }
4659         if (es->hloc32A) {
4660                 LocalFree(es->hloc32A);
4661         }
4662         if (hloc16) {
4663                 STACK16FRAME* stack16 = MapSL(PtrToUlong(NtCurrentTeb()->WOW32Reserved));
4664                 HANDLE16 oldDS = stack16->ds;
4665
4666                 stack16->ds = GetWindowLongPtrW( es->hwndSelf, GWLP_HINSTANCE );
4667                 while (LocalUnlock16(hloc16)) ;
4668                 LocalFree16(hloc16);
4669                 stack16->ds = oldDS;
4670                 SetWindowWord( es->hwndSelf, GWW_HANDLE16, 0 );
4671         }
4672
4673         pc = es->first_line_def;
4674         while (pc)
4675         {
4676                 pp = pc->next;
4677                 HeapFree(GetProcessHeap(), 0, pc);
4678                 pc = pp;
4679         }
4680
4681         SetWindowLongPtrW( es->hwndSelf, 0, 0 );
4682         HeapFree(GetProcessHeap(), 0, es->undo_text);
4683         HeapFree(GetProcessHeap(), 0, es);
4684
4685         return 0;
4686 }
4687
4688
4689 static inline LRESULT DefWindowProcT(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, BOOL unicode)
4690 {
4691         if(unicode)
4692                 return DefWindowProcW(hwnd, msg, wParam, lParam);
4693         else
4694                 return DefWindowProcA(hwnd, msg, wParam, lParam);
4695 }
4696
4697 /*********************************************************************
4698  *
4699  *      EditWndProc_common
4700  *
4701  *      The messages are in the order of the actual integer values
4702  *      (which can be found in include/windows.h)
4703  */
4704 static LRESULT EditWndProc_common( HWND hwnd, UINT msg,
4705                                    WPARAM wParam, LPARAM lParam, BOOL unicode )
4706 {
4707         EDITSTATE *es = (EDITSTATE *)GetWindowLongPtrW( hwnd, 0 );
4708         LRESULT result = 0;
4709
4710         TRACE("hwnd=%p msg=%x (%s) wparam=%lx lparam=%lx\n", hwnd, msg, SPY_GetMsgName(msg, hwnd), wParam, lParam);
4711
4712         if (!es && msg != WM_NCCREATE)
4713                 return DefWindowProcT(hwnd, msg, wParam, lParam, unicode);
4714
4715         if (es && (msg != WM_NCDESTROY)) EDIT_LockBuffer(es);
4716
4717         switch (msg) {
4718         case EM_GETSEL:
4719                 result = EDIT_EM_GetSel(es, (PUINT)wParam, (PUINT)lParam);
4720                 break;
4721
4722         case EM_SETSEL:
4723                 EDIT_EM_SetSel(es, wParam, lParam, FALSE);
4724                 EDIT_EM_ScrollCaret(es);
4725                 result = 1;
4726                 break;
4727
4728         case EM_GETRECT:
4729                 if (lParam)
4730                         CopyRect((LPRECT)lParam, &es->format_rect);
4731                 break;
4732
4733         case EM_SETRECT:
4734                 if ((es->style & ES_MULTILINE) && lParam) {
4735                         EDIT_SetRectNP(es, (LPRECT)lParam);
4736                         EDIT_UpdateText(es, NULL, TRUE);
4737                 }
4738                 break;
4739
4740         case EM_SETRECTNP:
4741                 if ((es->style & ES_MULTILINE) && lParam)
4742                         EDIT_SetRectNP(es, (LPRECT)lParam);
4743                 break;
4744
4745         case EM_SCROLL:
4746                 result = EDIT_EM_Scroll(es, (INT)wParam);
4747                 break;
4748
4749         case EM_LINESCROLL:
4750                 result = (LRESULT)EDIT_EM_LineScroll(es, (INT)wParam, (INT)lParam);
4751                 break;
4752
4753         case EM_SCROLLCARET:
4754                 EDIT_EM_ScrollCaret(es);
4755                 result = 1;
4756                 break;
4757
4758         case EM_GETMODIFY:
4759                 result = ((es->flags & EF_MODIFIED) != 0);
4760                 break;
4761
4762         case EM_SETMODIFY:
4763                 if (wParam)
4764                         es->flags |= EF_MODIFIED;
4765                 else
4766                         es->flags &= ~(EF_MODIFIED | EF_UPDATE);  /* reset pending updates */
4767                 break;
4768
4769         case EM_GETLINECOUNT:
4770                 result = (es->style & ES_MULTILINE) ? es->line_count : 1;
4771                 break;
4772
4773         case EM_LINEINDEX:
4774                 result = (LRESULT)EDIT_EM_LineIndex(es, (INT)wParam);
4775                 break;
4776
4777         case EM_SETHANDLE:
4778                 EDIT_EM_SetHandle(es, (HLOCAL)wParam);
4779                 break;
4780
4781         case EM_GETHANDLE:
4782                 result = (LRESULT)EDIT_EM_GetHandle(es);
4783                 break;
4784
4785         case EM_GETTHUMB:
4786                 result = EDIT_EM_GetThumb(es);
4787                 break;
4788
4789         /* these messages missing from specs */
4790         case 0x00bf:
4791         case 0x00c0:
4792         case 0x00c3:
4793         case 0x00ca:
4794                 FIXME("undocumented message 0x%x, please report\n", msg);
4795                 result = DefWindowProcW(hwnd, msg, wParam, lParam);
4796                 break;
4797
4798         case EM_LINELENGTH:
4799                 result = (LRESULT)EDIT_EM_LineLength(es, (INT)wParam);
4800                 break;
4801
4802         case EM_REPLACESEL:
4803         {
4804                 LPWSTR textW;
4805
4806                 if(unicode)
4807                     textW = (LPWSTR)lParam;
4808                 else
4809                 {
4810                     LPSTR textA = (LPSTR)lParam;
4811                     INT countW = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
4812                     if((textW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
4813                         MultiByteToWideChar(CP_ACP, 0, textA, -1, textW, countW);
4814                 }
4815
4816                 EDIT_EM_ReplaceSel(es, (BOOL)wParam, textW, TRUE, TRUE);
4817                 result = 1;
4818
4819                 if(!unicode)
4820                     HeapFree(GetProcessHeap(), 0, textW);
4821                 break;
4822         }
4823
4824         case EM_GETLINE:
4825                 result = (LRESULT)EDIT_EM_GetLine(es, (INT)wParam, (LPWSTR)lParam, unicode);
4826                 break;
4827
4828         case EM_SETLIMITTEXT:
4829                 EDIT_EM_SetLimitText(es, wParam);
4830                 break;
4831
4832         case EM_CANUNDO:
4833                 result = (LRESULT)EDIT_EM_CanUndo(es);
4834                 break;
4835
4836         case EM_UNDO:
4837         case WM_UNDO:
4838                 result = (LRESULT)EDIT_EM_Undo(es);
4839                 break;
4840
4841         case EM_FMTLINES:
4842                 result = (LRESULT)EDIT_EM_FmtLines(es, (BOOL)wParam);
4843                 break;
4844
4845         case EM_LINEFROMCHAR:
4846                 result = (LRESULT)EDIT_EM_LineFromChar(es, (INT)wParam);
4847                 break;
4848
4849         case EM_SETTABSTOPS:
4850                 result = (LRESULT)EDIT_EM_SetTabStops(es, (INT)wParam, (LPINT)lParam);
4851                 break;
4852
4853         case EM_SETPASSWORDCHAR:
4854         {
4855                 WCHAR charW = 0;
4856
4857                 if(unicode)
4858                     charW = (WCHAR)wParam;
4859                 else
4860                 {
4861                     CHAR charA = wParam;
4862                     MultiByteToWideChar(CP_ACP, 0, &charA, 1, &charW, 1);
4863                 }
4864
4865                 EDIT_EM_SetPasswordChar(es, charW);
4866                 break;
4867         }
4868
4869         case EM_EMPTYUNDOBUFFER:
4870                 EDIT_EM_EmptyUndoBuffer(es);
4871                 break;
4872
4873         case EM_GETFIRSTVISIBLELINE:
4874                 result = (es->style & ES_MULTILINE) ? es->y_offset : es->x_offset;
4875                 break;
4876
4877         case EM_SETREADONLY:
4878         {
4879                 DWORD old_style = es->style;
4880
4881                 if (wParam) {
4882                     SetWindowLongW( hwnd, GWL_STYLE,
4883                                     GetWindowLongW( hwnd, GWL_STYLE ) | ES_READONLY );
4884                     es->style |= ES_READONLY;
4885                 } else {
4886                     SetWindowLongW( hwnd, GWL_STYLE,
4887                                     GetWindowLongW( hwnd, GWL_STYLE ) & ~ES_READONLY );
4888                     es->style &= ~ES_READONLY;
4889                 }
4890
4891                 if (old_style ^ es->style)
4892                     InvalidateRect(es->hwndSelf, NULL, TRUE);
4893
4894                 result = 1;
4895                 break;
4896         }
4897
4898         case EM_SETWORDBREAKPROC:
4899                 EDIT_EM_SetWordBreakProc(es, (void *)lParam);
4900                 break;
4901
4902         case EM_GETWORDBREAKPROC:
4903                 result = (LRESULT)es->word_break_proc;
4904                 break;
4905
4906         case EM_GETPASSWORDCHAR:
4907         {
4908                 if(unicode)
4909                     result = es->password_char;
4910                 else
4911                 {
4912                     WCHAR charW = es->password_char;
4913                     CHAR charA = 0;
4914                     WideCharToMultiByte(CP_ACP, 0, &charW, 1, &charA, 1, NULL, NULL);
4915                     result = charA;
4916                 }
4917                 break;
4918         }
4919
4920         case EM_SETMARGINS:
4921                 EDIT_EM_SetMargins(es, (INT)wParam, LOWORD(lParam), HIWORD(lParam), TRUE);
4922                 break;
4923
4924         case EM_GETMARGINS:
4925                 result = MAKELONG(es->left_margin, es->right_margin);
4926                 break;
4927
4928         case EM_GETLIMITTEXT:
4929                 result = es->buffer_limit;
4930                 break;
4931
4932         case EM_POSFROMCHAR:
4933                 if ((INT)wParam >= get_text_length(es)) result = -1;
4934                 else result = EDIT_EM_PosFromChar(es, (INT)wParam, FALSE);
4935                 break;
4936
4937         case EM_CHARFROMPOS:
4938                 result = EDIT_EM_CharFromPos(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
4939                 break;
4940
4941         /* End of the EM_ messages which were in numerical order; what order
4942          * are these in?  vaguely alphabetical?
4943          */
4944
4945         case WM_NCCREATE:
4946                 result = EDIT_WM_NCCreate(hwnd, (LPCREATESTRUCTW)lParam, unicode);
4947                 break;
4948
4949         case WM_NCDESTROY:
4950                 result = EDIT_WM_NCDestroy(es);
4951                 es = NULL;
4952                 break;
4953
4954         case WM_GETDLGCODE:
4955                 result = DLGC_HASSETSEL | DLGC_WANTCHARS | DLGC_WANTARROWS;
4956
4957                 if (es->style & ES_MULTILINE)
4958                    result |= DLGC_WANTALLKEYS;
4959
4960                 if (lParam)
4961                 {
4962                     es->flags|=EF_DIALOGMODE;
4963
4964                     if (((LPMSG)lParam)->message == WM_KEYDOWN)
4965                     {
4966                         int vk = (int)((LPMSG)lParam)->wParam;
4967
4968                         if (es->hwndListBox)
4969                         {
4970                             if (vk == VK_RETURN || vk == VK_ESCAPE)
4971                                 if (SendMessageW(GetParent(hwnd), CB_GETDROPPEDSTATE, 0, 0))
4972                                     result |= DLGC_WANTMESSAGE;
4973                         }
4974                   }
4975                 }
4976                 break;
4977
4978         case WM_IME_CHAR:
4979             if (!unicode)
4980             {
4981                 WCHAR charW;
4982                 CHAR  strng[2];
4983
4984                 strng[0] = wParam >> 8;
4985                 strng[1] = wParam & 0xff;
4986                 if (strng[0]) MultiByteToWideChar(CP_ACP, 0, strng, 2, &charW, 1);
4987                 else MultiByteToWideChar(CP_ACP, 0, &strng[1], 1, &charW, 1);
4988                 result = EDIT_WM_Char(es, charW);
4989                 break;
4990             }
4991             /* fall through */
4992         case WM_CHAR:
4993         {
4994                 WCHAR charW;
4995
4996                 if(unicode)
4997                     charW = wParam;
4998                 else
4999                 {
5000                     CHAR charA = wParam;
5001                     MultiByteToWideChar(CP_ACP, 0, &charA, 1, &charW, 1);
5002                 }
5003
5004                 if (es->hwndListBox)
5005                 {
5006                     if (charW == VK_RETURN || charW == VK_ESCAPE)
5007                     {
5008                         if (SendMessageW(GetParent(hwnd), CB_GETDROPPEDSTATE, 0, 0))
5009                             SendMessageW(GetParent(hwnd), WM_KEYDOWN, charW, 0);
5010                         break;
5011                     }
5012                 }
5013                 result = EDIT_WM_Char(es, charW);
5014                 break;
5015         }
5016
5017         case WM_UNICHAR:
5018                 if (unicode)
5019                 {
5020                     if (wParam == UNICODE_NOCHAR) return TRUE;
5021                     if (wParam <= 0x000fffff)
5022                     {
5023                         if(wParam > 0xffff) /* convert to surrogates */
5024                         {
5025                             wParam -= 0x10000;
5026                             EDIT_WM_Char(es, (wParam >> 10) + 0xd800);
5027                             EDIT_WM_Char(es, (wParam & 0x03ff) + 0xdc00);
5028                         }
5029                         else EDIT_WM_Char(es, wParam);
5030                     }
5031                     return 0;
5032                 }
5033                 break;
5034
5035         case WM_CLEAR:
5036                 EDIT_WM_Clear(es);
5037                 break;
5038
5039         case WM_COMMAND:
5040                 EDIT_WM_Command(es, HIWORD(wParam), LOWORD(wParam), (HWND)lParam);
5041                 break;
5042
5043         case WM_CONTEXTMENU:
5044                 EDIT_WM_ContextMenu(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
5045                 break;
5046
5047         case WM_COPY:
5048                 EDIT_WM_Copy(es);
5049                 break;
5050
5051         case WM_CREATE:
5052                 if(unicode)
5053                     result = EDIT_WM_Create(es, ((LPCREATESTRUCTW)lParam)->lpszName);
5054                 else
5055                 {
5056                     LPCSTR nameA = ((LPCREATESTRUCTA)lParam)->lpszName;
5057                     LPWSTR nameW = NULL;
5058                     if(nameA)
5059                     {
5060                         INT countW = MultiByteToWideChar(CP_ACP, 0, nameA, -1, NULL, 0);
5061                         if((nameW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
5062                             MultiByteToWideChar(CP_ACP, 0, nameA, -1, nameW, countW);
5063                     }
5064                     result = EDIT_WM_Create(es, nameW);
5065                     HeapFree(GetProcessHeap(), 0, nameW);
5066                 }
5067                 break;
5068
5069         case WM_CUT:
5070                 EDIT_WM_Cut(es);
5071                 break;
5072
5073         case WM_ENABLE:
5074                 es->bEnableState = (BOOL) wParam;
5075                 EDIT_UpdateText(es, NULL, TRUE);
5076                 break;
5077
5078         case WM_ERASEBKGND:
5079                 /* we do the proper erase in EDIT_WM_Paint */
5080                 result = 1;
5081                 break;
5082
5083         case WM_GETFONT:
5084                 result = (LRESULT)es->font;
5085                 break;
5086
5087         case WM_GETTEXT:
5088                 result = (LRESULT)EDIT_WM_GetText(es, (INT)wParam, (LPWSTR)lParam, unicode);
5089                 break;
5090
5091         case WM_GETTEXTLENGTH:
5092                 if (unicode) result = get_text_length(es);
5093                 else result = WideCharToMultiByte( CP_ACP, 0, es->text, get_text_length(es),
5094                                                    NULL, 0, NULL, NULL );
5095                 break;
5096
5097         case WM_HSCROLL:
5098                 result = EDIT_WM_HScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
5099                 break;
5100
5101         case WM_KEYDOWN:
5102                 result = EDIT_WM_KeyDown(es, (INT)wParam);
5103                 break;
5104
5105         case WM_KILLFOCUS:
5106                 result = EDIT_WM_KillFocus(es);
5107                 break;
5108
5109         case WM_LBUTTONDBLCLK:
5110                 result = EDIT_WM_LButtonDblClk(es);
5111                 break;
5112
5113         case WM_LBUTTONDOWN:
5114                 result = EDIT_WM_LButtonDown(es, wParam, (short)LOWORD(lParam), (short)HIWORD(lParam));
5115                 break;
5116
5117         case WM_LBUTTONUP:
5118                 result = EDIT_WM_LButtonUp(es);
5119                 break;
5120
5121         case WM_MBUTTONDOWN:
5122                 result = EDIT_WM_MButtonDown(es);
5123                 break;
5124
5125         case WM_MOUSEMOVE:
5126                 result = EDIT_WM_MouseMove(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
5127                 break;
5128
5129         case WM_PRINTCLIENT:
5130         case WM_PAINT:
5131                 EDIT_WM_Paint(es, (HDC)wParam);
5132                 break;
5133
5134         case WM_PASTE:
5135                 EDIT_WM_Paste(es);
5136                 break;
5137
5138         case WM_SETFOCUS:
5139                 EDIT_WM_SetFocus(es);
5140                 break;
5141
5142         case WM_SETFONT:
5143                 EDIT_WM_SetFont(es, (HFONT)wParam, LOWORD(lParam) != 0);
5144                 break;
5145
5146         case WM_SETREDRAW:
5147                 /* FIXME: actually set an internal flag and behave accordingly */
5148                 break;
5149
5150         case WM_SETTEXT:
5151                 EDIT_WM_SetText(es, (LPCWSTR)lParam, unicode);
5152                 result = TRUE;
5153                 break;
5154
5155         case WM_SIZE:
5156                 EDIT_WM_Size(es, (UINT)wParam, LOWORD(lParam), HIWORD(lParam));
5157                 break;
5158
5159         case WM_STYLECHANGED:
5160                 result = EDIT_WM_StyleChanged(es, wParam, (const STYLESTRUCT *)lParam);
5161                 break;
5162
5163         case WM_STYLECHANGING:
5164                 result = 0; /* See EDIT_WM_StyleChanged */
5165                 break;
5166
5167         case WM_SYSKEYDOWN:
5168                 result = EDIT_WM_SysKeyDown(es, (INT)wParam, (DWORD)lParam);
5169                 break;
5170
5171         case WM_TIMER:
5172                 EDIT_WM_Timer(es);
5173                 break;
5174
5175         case WM_VSCROLL:
5176                 result = EDIT_WM_VScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
5177                 break;
5178
5179         case WM_MOUSEWHEEL:
5180                 {
5181                     int gcWheelDelta = 0;
5182                     UINT pulScrollLines = 3;
5183                     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
5184
5185                     if (wParam & (MK_SHIFT | MK_CONTROL)) {
5186                         result = DefWindowProcW(hwnd, msg, wParam, lParam);
5187                         break;
5188                     }
5189                     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
5190                     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
5191                     {
5192                         int cLineScroll= (int) min((UINT) es->line_count, pulScrollLines);
5193                         cLineScroll *= (gcWheelDelta / WHEEL_DELTA);
5194                         result = EDIT_EM_LineScroll(es, 0, cLineScroll);
5195                     }
5196                 }
5197                 break;
5198
5199
5200         /* IME messages to make the edit control IME aware */
5201         case WM_IME_SETCONTEXT:
5202                 break;
5203
5204         case WM_IME_STARTCOMPOSITION:
5205                 es->composition_start = es->selection_end;
5206                 es->composition_len = 0;
5207                 break;
5208
5209         case WM_IME_COMPOSITION:
5210                 EDIT_ImeComposition(hwnd, lParam, es);
5211                 break;
5212
5213         case WM_IME_ENDCOMPOSITION:
5214                 if (es->composition_len > 0)
5215                 {
5216                         static const WCHAR empty_stringW[] = {0};
5217                         EDIT_EM_ReplaceSel(es, TRUE, empty_stringW, TRUE, TRUE);
5218                         es->selection_end = es->selection_start;
5219                         es->composition_len= 0;
5220                 }
5221                 break;
5222
5223         case WM_IME_COMPOSITIONFULL:
5224                 break;
5225
5226         case WM_IME_SELECT:
5227                 break;
5228
5229         case WM_IME_CONTROL:
5230                 break;
5231
5232         default:
5233                 result = DefWindowProcT(hwnd, msg, wParam, lParam, unicode);
5234                 break;
5235         }
5236
5237         if (IsWindow(hwnd) && es) EDIT_UnlockBuffer(es, FALSE);
5238
5239         TRACE("hwnd=%p msg=%x (%s) -- 0x%08lx\n", hwnd, msg, SPY_GetMsgName(msg, hwnd), result);
5240
5241         return result;
5242 }
5243
5244
5245 /*********************************************************************
5246  *      EditWndProc_wrapper16
5247  */
5248 static LRESULT EditWndProc_wrapper16( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, BOOL unicode )
5249 {
5250     static const UINT msg16_offset = EM_GETSEL16 - EM_GETSEL;
5251     LRESULT result;
5252
5253     switch (msg)
5254     {
5255     case EM_SCROLL16:
5256     case EM_SCROLLCARET16:
5257     case EM_GETMODIFY16:
5258     case EM_SETMODIFY16:
5259     case EM_GETLINECOUNT16:
5260     case EM_GETTHUMB16:
5261     case EM_LINELENGTH16:
5262     case EM_LIMITTEXT16:
5263     case EM_CANUNDO16:
5264     case EM_UNDO16:
5265     case EM_FMTLINES16:
5266     case EM_LINEFROMCHAR16:
5267     case EM_SETPASSWORDCHAR16:
5268     case EM_EMPTYUNDOBUFFER16:
5269     case EM_SETREADONLY16:
5270     case EM_GETPASSWORDCHAR16:
5271         /* these messages missing from specs */
5272     case WM_USER+15:
5273     case WM_USER+16:
5274     case WM_USER+19:
5275     case WM_USER+26:
5276         msg -= msg16_offset;
5277         break;
5278     case EM_GETSEL16:
5279         wParam = 0;
5280         lParam = 0;
5281         msg -= msg16_offset;
5282         break;
5283     case EM_REPLACESEL16:
5284     case EM_GETLINE16:
5285         lParam = (LPARAM)MapSL(lParam);
5286         msg -= msg16_offset;
5287         break;
5288     case EM_LINESCROLL16:
5289         wParam = (INT)(SHORT)HIWORD(lParam);
5290         lParam = (INT)(SHORT)LOWORD(lParam);
5291         msg -= msg16_offset;
5292         break;
5293     case EM_LINEINDEX16:
5294         if ((INT16)wParam == -1) wParam = (WPARAM)-1;
5295         msg -= msg16_offset;
5296         break;
5297     case EM_SETSEL16:
5298         if ((short)LOWORD(lParam) == -1)
5299         {
5300             wParam = -1;
5301             lParam = 0;
5302         }
5303         else
5304         {
5305             wParam = LOWORD(lParam);
5306             lParam = HIWORD(lParam);
5307         }
5308         msg -= msg16_offset;
5309         break;
5310     case EM_GETRECT16:
5311         if (lParam)
5312         {
5313             RECT rect;
5314             RECT16 *r16 = MapSL(lParam);
5315             EditWndProc_common( hwnd, msg - msg16_offset, wParam, (LPARAM)&rect, FALSE );
5316             r16->left   = rect.left;
5317             r16->top    = rect.top;
5318             r16->right  = rect.right;
5319             r16->bottom = rect.bottom;
5320         }
5321         return 0;
5322     case EM_SETRECT16:
5323     case EM_SETRECTNP16:
5324         if (lParam)
5325         {
5326             RECT rect;
5327             RECT16 *r16 = MapSL(lParam);
5328             rect.left   = r16->left;
5329             rect.top    = r16->top;
5330             rect.right  = r16->right;
5331             rect.bottom = r16->bottom;
5332             EditWndProc_common( hwnd, msg - msg16_offset, wParam, (LPARAM)&rect, FALSE );
5333         }
5334         return 0;
5335     case EM_SETHANDLE16:
5336         EDIT_EM_SetHandle16( hwnd, (HLOCAL16)wParam );
5337         break;
5338     case EM_GETHANDLE16:
5339         result = EDIT_EM_GetHandle16( hwnd );
5340         break;
5341     case EM_SETTABSTOPS16:
5342     {
5343         INT16 *tabs16 = MapSL(lParam);
5344         INT i, count = wParam, *tabs = NULL;
5345         if (count > 0)
5346         {
5347             if (!(tabs = HeapAlloc( GetProcessHeap(), 0, count * sizeof(*tabs) ))) return 0;
5348             for (i = 0; i < count; i++) tabs[i] = tabs16[i];
5349         }
5350         result = EditWndProc_common( hwnd, msg - msg16_offset, count, (LPARAM)tabs, FALSE );
5351         HeapFree( GetProcessHeap(), 0, tabs );
5352         return result;
5353     }
5354     case EM_GETFIRSTVISIBLELINE16:
5355         if (!(GetWindowLongW( hwnd, GWL_STYLE ) & ES_MULTILINE)) return 0;
5356         msg -= msg16_offset;
5357         break;
5358     case EM_SETWORDBREAKPROC16:
5359     {
5360         struct word_break_thunk *thunk = add_word_break_thunk( (EDITWORDBREAKPROC16)lParam );
5361         return EditWndProc_common( hwnd, EM_SETWORDBREAKPROC, wParam, (LPARAM)thunk, FALSE );
5362     }
5363     case EM_GETWORDBREAKPROC16:
5364         result = EditWndProc_common( hwnd, EM_GETWORDBREAKPROC, wParam, lParam, FALSE );
5365         return (LRESULT)get_word_break_thunk( (EDITWORDBREAKPROCA)result );
5366     default:
5367         return EditWndProc_common( hwnd, msg, wParam, lParam, unicode );
5368     }
5369     return EditWndProc_common( hwnd, msg, wParam, lParam, FALSE );
5370 }
5371
5372 /*********************************************************************
5373  *
5374  *      EditWndProc   (USER32.@)
5375  */
5376 LRESULT WINAPI EditWndProcA(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
5377 {
5378     return EditWndProc_wrapper16(hWnd, uMsg, wParam, lParam, FALSE);
5379 }
5380
5381 /*********************************************************************
5382  *
5383  *      EditWndProcW
5384  */
5385 static LRESULT WINAPI EditWndProcW(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
5386 {
5387     return EditWndProc_wrapper16(hWnd, uMsg, wParam, lParam, TRUE);
5388 }
5389
5390 /*********************************************************************
5391  * edit class descriptor
5392  */
5393 static const WCHAR editW[] = {'E','d','i','t',0};
5394 const struct builtin_class_descr EDIT_builtin_class =
5395 {
5396     editW,                /* name */
5397     CS_DBLCLKS | CS_PARENTDC,   /* style */
5398     EditWndProcA,         /* procA */
5399     EditWndProcW,         /* procW */
5400 #ifdef __i386__
5401     sizeof(EDITSTATE *) + sizeof(HLOCAL16), /* extra */
5402 #else
5403     sizeof(EDITSTATE *),  /* extra */
5404 #endif
5405     IDC_IBEAM,            /* cursor */
5406     0                     /* brush */
5407 };