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