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