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