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