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