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