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