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