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