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