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