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