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