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