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