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