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