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