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