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