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