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