- strip support for darwin
[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);
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)) {
1129                    if (current_line->width > fw) {
1130                         INT next = 0;
1131                         INT prev;
1132                         do {
1133                                 prev = next;
1134                                 next = EDIT_CallWordBreakProc(es, current_position - es->text,
1135                                                 prev + 1, current_line->net_length, WB_RIGHT);
1136                                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1137                                                         current_position, next, es->tabs_count, es->tabs));
1138                         } while (current_line->width <= fw);
1139                         if (!prev) { /* Didn't find a line break so force a break */
1140                                 next = 0;
1141                                 do {
1142                                         prev = next;
1143                                         next++;
1144                                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1145                                                                 current_position, next, es->tabs_count, es->tabs));
1146                                 } while (current_line->width <= fw);
1147                                 if (!prev)
1148                                         prev = 1;
1149                         }
1150
1151                         /* If the first line we are calculating, wrapped before istart, we must
1152                          * adjust istart in order for this to be reflected in the update region. */
1153                         if (current_line->index == nstart_index && istart > current_line->index + prev)
1154                                 istart = current_line->index + prev;
1155                         /* else if we are updating the previous line before the first line we
1156                          * are re-calculating and it expanded */
1157                         else if (current_line == start_line &&
1158                                         current_line->index != nstart_index && orig_net_length < prev)
1159                         {
1160                           /* Line expanded due to an upwards line wrap so we must partially include
1161                            * previous line in update region */
1162                                 nstart_line = line_index;
1163                                 nstart_index = current_line->index;
1164                                 istart = current_line->index + orig_net_length;
1165                         }
1166
1167                         current_line->net_length = prev;
1168                         current_line->ending = END_WRAP;
1169                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc, current_position,
1170                                         current_line->net_length, es->tabs_count, es->tabs));
1171                     }
1172                     else if (orig_net_length <  current_line->net_length  &&
1173                         current_line == start_line &&
1174                         current_line->index != nstart_index) {
1175                         /* The previous line expanded but it's still not as wide as the client rect */
1176                         /* The expansion is due to an upwards line wrap so we must partially include
1177                            it in the update region */
1178                         nstart_line = line_index;
1179                         nstart_index = current_line->index;
1180                         istart = current_line->index + orig_net_length;
1181                     }
1182                 }
1183
1184
1185                 /* Adjust length to include line termination */
1186                 switch (current_line->ending) {
1187                 case END_SOFT:
1188                         current_line->length = current_line->net_length + 3;
1189                         break;
1190                 case END_RICH:
1191                         current_line->length = current_line->net_length + 1;
1192                         break;
1193                 case END_HARD:
1194                         current_line->length = current_line->net_length + 2;
1195                         break;
1196                 case END_WRAP:
1197                 case END_0:
1198                         current_line->length = current_line->net_length;
1199                         break;
1200                 }
1201                 es->text_width = max(es->text_width, current_line->width);
1202                 current_position += current_line->length;
1203                 previous_line = current_line;
1204                 current_line = current_line->next;
1205                 line_index++;
1206         } while (previous_line->ending != END_0);
1207
1208         /* Finish adjusting line indexes by delta or remove hanging lines */
1209         if (previous_line->ending == END_0)
1210         {
1211                 LINEDEF *pnext = NULL;
1212
1213                 previous_line->next = NULL;
1214                 while (current_line)
1215                 {
1216                         pnext = current_line->next;
1217                         HeapFree(GetProcessHeap(), 0, current_line);
1218                         current_line = pnext;
1219                         es->line_count--;
1220                 }
1221         }
1222         else
1223         {
1224                 while (current_line)
1225                 {
1226                         current_line->index += delta;
1227                         current_line = current_line->next;
1228                 }
1229         }
1230
1231         /* Calculate rest of modification rectangle */
1232         if (hrgn)
1233         {
1234                 HRGN tmphrgn;
1235            /*
1236                 * We calculate two rectangles. One for the first line which may have
1237                 * an indent with respect to the format rect. The other is a format-width
1238                 * rectangle that spans the rest of the lines that changed or moved.
1239                 */
1240                 rc.top = es->format_rect.top + nstart_line * es->line_height -
1241                         (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1242                 rc.bottom = rc.top + es->line_height;
1243                 rc.left = es->format_rect.left + (INT)LOWORD(GetTabbedTextExtentW(dc,
1244                                         es->text + nstart_index, istart - nstart_index,
1245                                         es->tabs_count, es->tabs)) - es->x_offset; /* Adjust for horz scroll */
1246                 rc.right = es->format_rect.right;
1247                 SetRectRgn(hrgn, rc.left, rc.top, rc.right, rc.bottom);
1248
1249                 rc.top = rc.bottom;
1250                 rc.left = es->format_rect.left;
1251                 rc.right = es->format_rect.right;
1252            /*
1253                 * If lines were added or removed we must re-paint the remainder of the
1254             * lines since the remaining lines were either shifted up or down.
1255                 */
1256                 if (line_count < es->line_count) /* We added lines */
1257                         rc.bottom = es->line_count * es->line_height;
1258                 else if (line_count > es->line_count) /* We removed lines */
1259                         rc.bottom = line_count * es->line_height;
1260                 else
1261                         rc.bottom = line_index * es->line_height;
1262                 rc.bottom -= (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1263                 tmphrgn = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
1264                 CombineRgn(hrgn, hrgn, tmphrgn, RGN_OR);
1265                 DeleteObject(tmphrgn);
1266         }
1267
1268         if (es->font)
1269                 SelectObject(dc, old_font);
1270
1271         ReleaseDC(es->hwndSelf, dc);
1272 }
1273
1274 /*********************************************************************
1275  *
1276  *      EDIT_CalcLineWidth_SL
1277  *
1278  */
1279 static void EDIT_CalcLineWidth_SL(EDITSTATE *es)
1280 {
1281     es->text_width = (short)LOWORD(EDIT_EM_PosFromChar(es, strlenW(es->text), FALSE));
1282 }
1283
1284 /*********************************************************************
1285  *
1286  *      EDIT_CallWordBreakProc
1287  *
1288  *      Call appropriate WordBreakProc (internal or external).
1289  *
1290  *      Note: The "start" argument should always be an index referring
1291  *              to es->text.  The actual wordbreak proc might be
1292  *              16 bit, so we can't always pass any 32 bit LPSTR.
1293  *              Hence we assume that es->text is the buffer that holds
1294  *              the string under examination (we can decide this for ourselves).
1295  *
1296  */
1297 static INT EDIT_CallWordBreakProc(EDITSTATE *es, INT start, INT index, INT count, INT action)
1298 {
1299     INT ret, iWndsLocks;
1300
1301     /* To avoid any deadlocks, all the locks on the window structures
1302        must be suspended before the control is passed to the application */
1303     iWndsLocks = WIN_SuspendWndsLock();
1304
1305         if (es->word_break_proc16) {
1306             HGLOBAL16 hglob16;
1307             SEGPTR segptr;
1308             INT countA;
1309             WORD args[5];
1310             DWORD result;
1311
1312             countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1313             hglob16 = GlobalAlloc16(GMEM_MOVEABLE | GMEM_ZEROINIT, countA);
1314             segptr = K32WOWGlobalLock16(hglob16);
1315             WideCharToMultiByte(CP_ACP, 0, es->text + start, count, MapSL(segptr), countA, NULL, NULL);
1316             args[4] = SELECTOROF(segptr);
1317             args[3] = OFFSETOF(segptr);
1318             args[2] = index;
1319             args[1] = countA;
1320             args[0] = action;
1321             WOWCallback16Ex((DWORD)es->word_break_proc16, WCB16_PASCAL, sizeof(args), args, &result);
1322             ret = LOWORD(result);
1323             GlobalUnlock16(hglob16);
1324             GlobalFree16(hglob16);
1325         }
1326         else if (es->word_break_proc)
1327         {
1328             if(es->is_unicode)
1329             {
1330                 EDITWORDBREAKPROCW wbpW = (EDITWORDBREAKPROCW)es->word_break_proc;
1331
1332                 TRACE_(relay)("(UNICODE wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1333                         es->word_break_proc, debugstr_wn(es->text + start, count), index, count, action);
1334                 ret = wbpW(es->text + start, index, count, action);
1335             }
1336             else
1337             {
1338                 EDITWORDBREAKPROCA wbpA = (EDITWORDBREAKPROCA)es->word_break_proc;
1339                 INT countA;
1340                 CHAR *textA;
1341
1342                 countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1343                 textA = HeapAlloc(GetProcessHeap(), 0, countA);
1344                 WideCharToMultiByte(CP_ACP, 0, es->text + start, count, textA, countA, NULL, NULL);
1345                 TRACE_(relay)("(ANSI wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1346                         es->word_break_proc, debugstr_an(textA, countA), index, countA, action);
1347                 ret = wbpA(textA, index, countA, action);
1348                 HeapFree(GetProcessHeap(), 0, textA);
1349             }
1350         }
1351         else
1352             ret = EDIT_WordBreakProc(es->text + start, index, count, action);
1353
1354     WIN_RestoreWndsLock(iWndsLocks);
1355     return ret;
1356 }
1357
1358
1359 /*********************************************************************
1360  *
1361  *      EDIT_CharFromPos
1362  *
1363  *      Beware: This is not the function called on EM_CHARFROMPOS
1364  *              The position _can_ be outside the formatting / client
1365  *              rectangle
1366  *              The return value is only the character index
1367  *
1368  */
1369 static INT EDIT_CharFromPos(EDITSTATE *es, INT x, INT y, LPBOOL after_wrap)
1370 {
1371         INT index;
1372         HDC dc;
1373         HFONT old_font = 0;
1374
1375         if (es->style & ES_MULTILINE) {
1376                 INT line = (y - es->format_rect.top) / es->line_height + es->y_offset;
1377                 INT line_index = 0;
1378                 LINEDEF *line_def = es->first_line_def;
1379                 INT low, high;
1380                 while ((line > 0) && line_def->next) {
1381                         line_index += line_def->length;
1382                         line_def = line_def->next;
1383                         line--;
1384                 }
1385                 x += es->x_offset - es->format_rect.left;
1386                 if (x >= line_def->width) {
1387                         if (after_wrap)
1388                                 *after_wrap = (line_def->ending == END_WRAP);
1389                         return line_index + line_def->net_length;
1390                 }
1391                 if (x <= 0) {
1392                         if (after_wrap)
1393                                 *after_wrap = FALSE;
1394                         return line_index;
1395                 }
1396                 dc = GetDC(es->hwndSelf);
1397                 if (es->font)
1398                         old_font = SelectObject(dc, es->font);
1399                     low = line_index + 1;
1400                     high = line_index + line_def->net_length + 1;
1401                     while (low < high - 1)
1402                     {
1403                         INT mid = (low + high) / 2;
1404                         if (LOWORD(GetTabbedTextExtentW(dc, es->text + line_index,mid - line_index, es->tabs_count, es->tabs)) > x) high = mid;
1405                         else low = mid;
1406                     }
1407                     index = low;
1408
1409                 if (after_wrap)
1410                         *after_wrap = ((index == line_index + line_def->net_length) &&
1411                                                         (line_def->ending == END_WRAP));
1412         } else {
1413                 LPWSTR text;
1414                 SIZE size;
1415                 if (after_wrap)
1416                         *after_wrap = FALSE;
1417                 x -= es->format_rect.left;
1418                 if (!x)
1419                         return es->x_offset;
1420                 text = EDIT_GetPasswordPointer_SL(es);
1421                 dc = GetDC(es->hwndSelf);
1422                 if (es->font)
1423                         old_font = SelectObject(dc, es->font);
1424                 if (x < 0)
1425                 {
1426                     INT low = 0;
1427                     INT high = es->x_offset;
1428                     while (low < high - 1)
1429                     {
1430                         INT mid = (low + high) / 2;
1431                         GetTextExtentPoint32W( dc, text + mid,
1432                                                es->x_offset - mid, &size );
1433                         if (size.cx > -x) low = mid;
1434                         else high = mid;
1435                     }
1436                     index = low;
1437                 }
1438                 else
1439                 {
1440                     INT low = es->x_offset;
1441                     INT high = strlenW(es->text) + 1;
1442                     while (low < high - 1)
1443                     {
1444                         INT mid = (low + high) / 2;
1445                         GetTextExtentPoint32W( dc, text + es->x_offset,
1446                                                mid - es->x_offset, &size );
1447                         if (size.cx > x) high = mid;
1448                         else low = mid;
1449                     }
1450                     index = low;
1451                 }
1452                 if (es->style & ES_PASSWORD)
1453                         HeapFree(GetProcessHeap(), 0, text);
1454         }
1455         if (es->font)
1456                 SelectObject(dc, old_font);
1457         ReleaseDC(es->hwndSelf, dc);
1458         return index;
1459 }
1460
1461
1462 /*********************************************************************
1463  *
1464  *      EDIT_ConfinePoint
1465  *
1466  *      adjusts the point to be within the formatting rectangle
1467  *      (so CharFromPos returns the nearest _visible_ character)
1468  *
1469  */
1470 static void EDIT_ConfinePoint(EDITSTATE *es, LPINT x, LPINT y)
1471 {
1472         *x = min(max(*x, es->format_rect.left), es->format_rect.right - 1);
1473         *y = min(max(*y, es->format_rect.top), es->format_rect.bottom - 1);
1474 }
1475
1476
1477 /*********************************************************************
1478  *
1479  *      EDIT_GetLineRect
1480  *
1481  *      Calculates the bounding rectangle for a line from a starting
1482  *      column to an ending column.
1483  *
1484  */
1485 static void EDIT_GetLineRect(EDITSTATE *es, INT line, INT scol, INT ecol, LPRECT rc)
1486 {
1487         INT line_index =  EDIT_EM_LineIndex(es, line);
1488
1489         if (es->style & ES_MULTILINE)
1490                 rc->top = es->format_rect.top + (line - es->y_offset) * es->line_height;
1491         else
1492                 rc->top = es->format_rect.top;
1493         rc->bottom = rc->top + es->line_height;
1494         rc->left = (scol == 0) ? es->format_rect.left : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + scol, TRUE));
1495         rc->right = (ecol == -1) ? es->format_rect.right : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + ecol, TRUE));
1496 }
1497
1498
1499 /*********************************************************************
1500  *
1501  *      EDIT_GetPasswordPointer_SL
1502  *
1503  *      note: caller should free the (optionally) allocated buffer
1504  *
1505  */
1506 static LPWSTR EDIT_GetPasswordPointer_SL(EDITSTATE *es)
1507 {
1508         if (es->style & ES_PASSWORD) {
1509                 INT len = strlenW(es->text);
1510                 LPWSTR text = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1511                 text[len] = '\0';
1512                 while(len) text[--len] = es->password_char;
1513                 return text;
1514         } else
1515                 return es->text;
1516 }
1517
1518
1519 /*********************************************************************
1520  *
1521  *      EDIT_LockBuffer
1522  *
1523  *      This acts as a LOCAL_Lock(), but it locks only once.  This way
1524  *      you can call it whenever you like, without unlocking.
1525  *
1526  *      Initially the edit control allocates a HLOCAL32 buffer 
1527  *      (32 bit linear memory handler).  However, 16 bit application
1528  *      might send a EM_GETHANDLE message and expect a HLOCAL16 (16 bit SEG:OFF
1529  *      handler).  From that moment on we have to keep using this 16 bit memory
1530  *      handler, because it is supposed to be valid at all times after EM_GETHANDLE.
1531  *      What we do is create a HLOCAL16 buffer, copy the text, and do pointer
1532  *      conversion.
1533  *
1534  */
1535 static void EDIT_LockBuffer(EDITSTATE *es)
1536 {
1537         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
1538         if (!es->text) {
1539             CHAR *textA = NULL;
1540             UINT countA = 0;
1541             BOOL _16bit = FALSE;
1542
1543             if(es->hloc32W)
1544             {
1545                 if(es->hloc32A)
1546                 {
1547                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
1548                     textA = LocalLock(es->hloc32A);
1549                     countA = strlen(textA) + 1;
1550                 }
1551                 else if(es->hloc16)
1552                 {
1553                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
1554                     textA = LOCAL_Lock(hInstance, es->hloc16);
1555                     countA = strlen(textA) + 1;
1556                     _16bit = TRUE;
1557                 }
1558             }
1559             else {
1560                 ERR("no buffer ... please report\n");
1561                 return;
1562             }
1563
1564             if(textA)
1565             {
1566                 HLOCAL hloc32W_new;
1567                 UINT countW_new = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
1568                 TRACE("%d bytes translated to %d WCHARs\n", countA, countW_new);
1569                 if(countW_new > es->buffer_size + 1)
1570                 {
1571                     UINT alloc_size = ROUND_TO_GROW(countW_new * sizeof(WCHAR));
1572                     TRACE("Resizing 32-bit UNICODE buffer from %d+1 to %d WCHARs\n", es->buffer_size, countW_new);
1573                     hloc32W_new = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
1574                     if(hloc32W_new)
1575                     {
1576                         es->hloc32W = hloc32W_new;
1577                         es->buffer_size = LocalSize(hloc32W_new)/sizeof(WCHAR) - 1;
1578                         TRACE("Real new size %d+1 WCHARs\n", es->buffer_size);
1579                     }
1580                     else
1581                         WARN("FAILED! Will synchronize partially\n");
1582                 }
1583             }
1584
1585             /*TRACE("Locking 32-bit UNICODE buffer\n");*/
1586             es->text = LocalLock(es->hloc32W);
1587
1588             if(textA)
1589             {
1590                 MultiByteToWideChar(CP_ACP, 0, textA, countA, es->text, es->buffer_size + 1);
1591                 if(_16bit)
1592                     LOCAL_Unlock(hInstance, es->hloc16);
1593                 else
1594                     LocalUnlock(es->hloc32A);
1595             }
1596         }
1597         es->lock_count++;
1598 }
1599
1600
1601 /*********************************************************************
1602  *
1603  *      EDIT_SL_InvalidateText
1604  *
1605  *      Called from EDIT_InvalidateText().
1606  *      Does the job for single-line controls only.
1607  *
1608  */
1609 static void EDIT_SL_InvalidateText(EDITSTATE *es, INT start, INT end)
1610 {
1611         RECT line_rect;
1612         RECT rc;
1613
1614         EDIT_GetLineRect(es, 0, start, end, &line_rect);
1615         if (IntersectRect(&rc, &line_rect, &es->format_rect))
1616                 EDIT_UpdateText(es, &rc, TRUE);
1617 }
1618
1619
1620 /*********************************************************************
1621  *
1622  *      EDIT_ML_InvalidateText
1623  *
1624  *      Called from EDIT_InvalidateText().
1625  *      Does the job for multi-line controls only.
1626  *
1627  */
1628 static void EDIT_ML_InvalidateText(EDITSTATE *es, INT start, INT end)
1629 {
1630         INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1631         INT sl = EDIT_EM_LineFromChar(es, start);
1632         INT el = EDIT_EM_LineFromChar(es, end);
1633         INT sc;
1634         INT ec;
1635         RECT rc1;
1636         RECT rcWnd;
1637         RECT rcLine;
1638         RECT rcUpdate;
1639         INT l;
1640
1641         if ((el < es->y_offset) || (sl > es->y_offset + vlc))
1642                 return;
1643
1644         sc = start - EDIT_EM_LineIndex(es, sl);
1645         ec = end - EDIT_EM_LineIndex(es, el);
1646         if (sl < es->y_offset) {
1647                 sl = es->y_offset;
1648                 sc = 0;
1649         }
1650         if (el > es->y_offset + vlc) {
1651                 el = es->y_offset + vlc;
1652                 ec = EDIT_EM_LineLength(es, EDIT_EM_LineIndex(es, el));
1653         }
1654         GetClientRect(es->hwndSelf, &rc1);
1655         IntersectRect(&rcWnd, &rc1, &es->format_rect);
1656         if (sl == el) {
1657                 EDIT_GetLineRect(es, sl, sc, ec, &rcLine);
1658                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1659                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1660         } else {
1661                 EDIT_GetLineRect(es, sl, sc,
1662                                 EDIT_EM_LineLength(es,
1663                                         EDIT_EM_LineIndex(es, sl)),
1664                                 &rcLine);
1665                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1666                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1667                 for (l = sl + 1 ; l < el ; l++) {
1668                         EDIT_GetLineRect(es, l, 0,
1669                                 EDIT_EM_LineLength(es,
1670                                         EDIT_EM_LineIndex(es, l)),
1671                                 &rcLine);
1672                         if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1673                                 EDIT_UpdateText(es, &rcUpdate, TRUE);
1674                 }
1675                 EDIT_GetLineRect(es, el, 0, ec, &rcLine);
1676                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1677                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1678         }
1679 }
1680
1681
1682 /*********************************************************************
1683  *
1684  *      EDIT_InvalidateText
1685  *
1686  *      Invalidate the text from offset start upto, but not including,
1687  *      offset end.  Useful for (re)painting the selection.
1688  *      Regions outside the linewidth are not invalidated.
1689  *      end == -1 means end == TextLength.
1690  *      start and end need not be ordered.
1691  *
1692  */
1693 static void EDIT_InvalidateText(EDITSTATE *es, INT start, INT end)
1694 {
1695         if (end == start)
1696                 return;
1697
1698         if (end == -1)
1699                 end = strlenW(es->text);
1700
1701         if (end < start) {
1702             INT tmp = start;
1703             start = end;
1704             end = tmp;
1705         }
1706
1707         if (es->style & ES_MULTILINE)
1708                 EDIT_ML_InvalidateText(es, start, end);
1709         else
1710                 EDIT_SL_InvalidateText(es, start, end);
1711 }
1712
1713
1714 /*********************************************************************
1715  *
1716  *      EDIT_MakeFit
1717  *
1718  * Try to fit size + 1 characters in the buffer.
1719  */
1720 static BOOL EDIT_MakeFit(EDITSTATE *es, UINT size)
1721 {
1722         HLOCAL hNew32W;
1723
1724         if (size <= es->buffer_size)
1725                 return TRUE;
1726
1727         TRACE("trying to ReAlloc to %d+1 characters\n", size);
1728
1729         /* Force edit to unlock it's buffer. es->text now NULL */
1730         EDIT_UnlockBuffer(es, TRUE);
1731
1732         if (es->hloc32W) {
1733             UINT alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1734             if ((hNew32W = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT))) {
1735                 TRACE("Old 32 bit handle %p, new handle %p\n", es->hloc32W, hNew32W);
1736                 es->hloc32W = hNew32W;
1737                 es->buffer_size = LocalSize(hNew32W)/sizeof(WCHAR) - 1;
1738             }
1739         }
1740
1741         EDIT_LockBuffer(es);
1742
1743         if (es->buffer_size < size) {
1744                 WARN("FAILED !  We now have %d+1\n", es->buffer_size);
1745                 EDIT_NOTIFY_PARENT(es, EN_ERRSPACE, "EN_ERRSPACE");
1746                 return FALSE;
1747         } else {
1748                 TRACE("We now have %d+1\n", es->buffer_size);
1749                 return TRUE;
1750         }
1751 }
1752
1753
1754 /*********************************************************************
1755  *
1756  *      EDIT_MakeUndoFit
1757  *
1758  *      Try to fit size + 1 bytes in the undo buffer.
1759  *
1760  */
1761 static BOOL EDIT_MakeUndoFit(EDITSTATE *es, UINT size)
1762 {
1763         UINT alloc_size;
1764
1765         if (size <= es->undo_buffer_size)
1766                 return TRUE;
1767
1768         TRACE("trying to ReAlloc to %d+1\n", size);
1769
1770         alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1771         if ((es->undo_text = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, es->undo_text, alloc_size))) {
1772                 es->undo_buffer_size = alloc_size/sizeof(WCHAR) - 1;
1773                 return TRUE;
1774         }
1775         else
1776         {
1777                 WARN("FAILED !  We now have %d+1\n", es->undo_buffer_size);
1778                 return FALSE;
1779         }
1780 }
1781
1782
1783 /*********************************************************************
1784  *
1785  *      EDIT_MoveBackward
1786  *
1787  */
1788 static void EDIT_MoveBackward(EDITSTATE *es, BOOL extend)
1789 {
1790         INT e = es->selection_end;
1791
1792         if (e) {
1793                 e--;
1794                 if ((es->style & ES_MULTILINE) && e &&
1795                                 (es->text[e - 1] == '\r') && (es->text[e] == '\n')) {
1796                         e--;
1797                         if (e && (es->text[e - 1] == '\r'))
1798                                 e--;
1799                 }
1800         }
1801         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1802         EDIT_EM_ScrollCaret(es);
1803 }
1804
1805
1806 /*********************************************************************
1807  *
1808  *      EDIT_MoveDown_ML
1809  *
1810  *      Only for multi line controls
1811  *      Move the caret one line down, on a column with the nearest
1812  *      x coordinate on the screen (might be a different column).
1813  *
1814  */
1815 static void EDIT_MoveDown_ML(EDITSTATE *es, BOOL extend)
1816 {
1817         INT s = es->selection_start;
1818         INT e = es->selection_end;
1819         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1820         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1821         INT x = (short)LOWORD(pos);
1822         INT y = (short)HIWORD(pos);
1823
1824         e = EDIT_CharFromPos(es, x, y + es->line_height, &after_wrap);
1825         if (!extend)
1826                 s = e;
1827         EDIT_EM_SetSel(es, s, e, after_wrap);
1828         EDIT_EM_ScrollCaret(es);
1829 }
1830
1831
1832 /*********************************************************************
1833  *
1834  *      EDIT_MoveEnd
1835  *
1836  */
1837 static void EDIT_MoveEnd(EDITSTATE *es, BOOL extend)
1838 {
1839         BOOL after_wrap = FALSE;
1840         INT e;
1841
1842         /* Pass a high value in x to make sure of receiving the end of the line */
1843         if (es->style & ES_MULTILINE)
1844                 e = EDIT_CharFromPos(es, 0x3fffffff,
1845                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), &after_wrap);
1846         else
1847                 e = strlenW(es->text);
1848         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, after_wrap);
1849         EDIT_EM_ScrollCaret(es);
1850 }
1851
1852
1853 /*********************************************************************
1854  *
1855  *      EDIT_MoveForward
1856  *
1857  */
1858 static void EDIT_MoveForward(EDITSTATE *es, BOOL extend)
1859 {
1860         INT e = es->selection_end;
1861
1862         if (es->text[e]) {
1863                 e++;
1864                 if ((es->style & ES_MULTILINE) && (es->text[e - 1] == '\r')) {
1865                         if (es->text[e] == '\n')
1866                                 e++;
1867                         else if ((es->text[e] == '\r') && (es->text[e + 1] == '\n'))
1868                                 e += 2;
1869                 }
1870         }
1871         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1872         EDIT_EM_ScrollCaret(es);
1873 }
1874
1875
1876 /*********************************************************************
1877  *
1878  *      EDIT_MoveHome
1879  *
1880  *      Home key: move to beginning of line.
1881  *
1882  */
1883 static void EDIT_MoveHome(EDITSTATE *es, BOOL extend)
1884 {
1885         INT e;
1886
1887         /* Pass the x_offset in x to make sure of receiving the first position of the line */
1888         if (es->style & ES_MULTILINE)
1889                 e = EDIT_CharFromPos(es, -es->x_offset,
1890                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), NULL);
1891         else
1892                 e = 0;
1893         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1894         EDIT_EM_ScrollCaret(es);
1895 }
1896
1897
1898 /*********************************************************************
1899  *
1900  *      EDIT_MovePageDown_ML
1901  *
1902  *      Only for multi line controls
1903  *      Move the caret one page down, on a column with the nearest
1904  *      x coordinate on the screen (might be a different column).
1905  *
1906  */
1907 static void EDIT_MovePageDown_ML(EDITSTATE *es, BOOL extend)
1908 {
1909         INT s = es->selection_start;
1910         INT e = es->selection_end;
1911         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1912         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1913         INT x = (short)LOWORD(pos);
1914         INT y = (short)HIWORD(pos);
1915
1916         e = EDIT_CharFromPos(es, x,
1917                 y + (es->format_rect.bottom - es->format_rect.top),
1918                 &after_wrap);
1919         if (!extend)
1920                 s = e;
1921         EDIT_EM_SetSel(es, s, e, after_wrap);
1922         EDIT_EM_ScrollCaret(es);
1923 }
1924
1925
1926 /*********************************************************************
1927  *
1928  *      EDIT_MovePageUp_ML
1929  *
1930  *      Only for multi line controls
1931  *      Move the caret one page up, on a column with the nearest
1932  *      x coordinate on the screen (might be a different column).
1933  *
1934  */
1935 static void EDIT_MovePageUp_ML(EDITSTATE *es, BOOL extend)
1936 {
1937         INT s = es->selection_start;
1938         INT e = es->selection_end;
1939         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1940         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1941         INT x = (short)LOWORD(pos);
1942         INT y = (short)HIWORD(pos);
1943
1944         e = EDIT_CharFromPos(es, x,
1945                 y - (es->format_rect.bottom - es->format_rect.top),
1946                 &after_wrap);
1947         if (!extend)
1948                 s = e;
1949         EDIT_EM_SetSel(es, s, e, after_wrap);
1950         EDIT_EM_ScrollCaret(es);
1951 }
1952
1953
1954 /*********************************************************************
1955  *
1956  *      EDIT_MoveUp_ML
1957  *
1958  *      Only for multi line controls
1959  *      Move the caret one line up, on a column with the nearest
1960  *      x coordinate on the screen (might be a different column).
1961  *
1962  */
1963 static void EDIT_MoveUp_ML(EDITSTATE *es, BOOL extend)
1964 {
1965         INT s = es->selection_start;
1966         INT e = es->selection_end;
1967         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1968         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1969         INT x = (short)LOWORD(pos);
1970         INT y = (short)HIWORD(pos);
1971
1972         e = EDIT_CharFromPos(es, x, y - es->line_height, &after_wrap);
1973         if (!extend)
1974                 s = e;
1975         EDIT_EM_SetSel(es, s, e, after_wrap);
1976         EDIT_EM_ScrollCaret(es);
1977 }
1978
1979
1980 /*********************************************************************
1981  *
1982  *      EDIT_MoveWordBackward
1983  *
1984  */
1985 static void EDIT_MoveWordBackward(EDITSTATE *es, BOOL extend)
1986 {
1987         INT s = es->selection_start;
1988         INT e = es->selection_end;
1989         INT l;
1990         INT ll;
1991         INT li;
1992
1993         l = EDIT_EM_LineFromChar(es, e);
1994         ll = EDIT_EM_LineLength(es, e);
1995         li = EDIT_EM_LineIndex(es, l);
1996         if (e - li == 0) {
1997                 if (l) {
1998                         li = EDIT_EM_LineIndex(es, l - 1);
1999                         e = li + EDIT_EM_LineLength(es, li);
2000                 }
2001         } else {
2002                 e = li + (INT)EDIT_CallWordBreakProc(es,
2003                                 li, e - li, ll, WB_LEFT);
2004         }
2005         if (!extend)
2006                 s = e;
2007         EDIT_EM_SetSel(es, s, e, FALSE);
2008         EDIT_EM_ScrollCaret(es);
2009 }
2010
2011
2012 /*********************************************************************
2013  *
2014  *      EDIT_MoveWordForward
2015  *
2016  */
2017 static void EDIT_MoveWordForward(EDITSTATE *es, BOOL extend)
2018 {
2019         INT s = es->selection_start;
2020         INT e = es->selection_end;
2021         INT l;
2022         INT ll;
2023         INT li;
2024
2025         l = EDIT_EM_LineFromChar(es, e);
2026         ll = EDIT_EM_LineLength(es, e);
2027         li = EDIT_EM_LineIndex(es, l);
2028         if (e - li == ll) {
2029                 if ((es->style & ES_MULTILINE) && (l != es->line_count - 1))
2030                         e = EDIT_EM_LineIndex(es, l + 1);
2031         } else {
2032                 e = li + EDIT_CallWordBreakProc(es,
2033                                 li, e - li + 1, ll, WB_RIGHT);
2034         }
2035         if (!extend)
2036                 s = e;
2037         EDIT_EM_SetSel(es, s, e, FALSE);
2038         EDIT_EM_ScrollCaret(es);
2039 }
2040
2041
2042 /*********************************************************************
2043  *
2044  *      EDIT_PaintLine
2045  *
2046  */
2047 static void EDIT_PaintLine(EDITSTATE *es, HDC dc, INT line, BOOL rev)
2048 {
2049         INT s = es->selection_start;
2050         INT e = es->selection_end;
2051         INT li;
2052         INT ll;
2053         INT x;
2054         INT y;
2055         LRESULT pos;
2056
2057         if (es->style & ES_MULTILINE) {
2058                 INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2059                 if ((line < es->y_offset) || (line > es->y_offset + vlc) || (line >= es->line_count))
2060                         return;
2061         } else if (line)
2062                 return;
2063
2064         TRACE("line=%d\n", line);
2065
2066         pos = EDIT_EM_PosFromChar(es, EDIT_EM_LineIndex(es, line), FALSE);
2067         x = (short)LOWORD(pos);
2068         y = (short)HIWORD(pos);
2069         li = EDIT_EM_LineIndex(es, line);
2070         ll = EDIT_EM_LineLength(es, li);
2071         s = min(es->selection_start, es->selection_end);
2072         e = max(es->selection_start, es->selection_end);
2073         s = min(li + ll, max(li, s));
2074         e = min(li + ll, max(li, e));
2075         if (rev && (s != e) &&
2076                         ((es->flags & EF_FOCUSED) || (es->style & ES_NOHIDESEL))) {
2077                 x += EDIT_PaintText(es, dc, x, y, line, 0, s - li, FALSE);
2078                 x += EDIT_PaintText(es, dc, x, y, line, s - li, e - s, TRUE);
2079                 x += EDIT_PaintText(es, dc, x, y, line, e - li, li + ll - e, FALSE);
2080         } else
2081                 x += EDIT_PaintText(es, dc, x, y, line, 0, ll, FALSE);
2082 }
2083
2084
2085 /*********************************************************************
2086  *
2087  *      EDIT_PaintText
2088  *
2089  */
2090 static INT EDIT_PaintText(EDITSTATE *es, HDC dc, INT x, INT y, INT line, INT col, INT count, BOOL rev)
2091 {
2092         COLORREF BkColor;
2093         COLORREF TextColor;
2094         INT ret;
2095         INT li;
2096         INT BkMode;
2097         SIZE size;
2098
2099         if (!count)
2100                 return 0;
2101         BkMode = GetBkMode(dc);
2102         BkColor = GetBkColor(dc);
2103         TextColor = GetTextColor(dc);
2104         if (rev) {
2105                 SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT));
2106                 SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2107                 SetBkMode( dc, OPAQUE);
2108         }
2109         li = EDIT_EM_LineIndex(es, line);
2110         if (es->style & ES_MULTILINE) {
2111                 ret = (INT)LOWORD(TabbedTextOutW(dc, x, y, es->text + li + col, count,
2112                                         es->tabs_count, es->tabs, es->format_rect.left - es->x_offset));
2113         } else {
2114                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2115                 TextOutW(dc, x, y, text + li + col, count);
2116                 GetTextExtentPoint32W(dc, text + li + col, count, &size);
2117                 ret = size.cx;
2118                 if (es->style & ES_PASSWORD)
2119                         HeapFree(GetProcessHeap(), 0, text);
2120         }
2121         if (rev) {
2122                 SetBkColor(dc, BkColor);
2123                 SetTextColor(dc, TextColor);
2124                 SetBkMode( dc, BkMode);
2125         }
2126         return ret;
2127 }
2128
2129
2130 /*********************************************************************
2131  *
2132  *      EDIT_SetCaretPos
2133  *
2134  */
2135 static void EDIT_SetCaretPos(EDITSTATE *es, INT pos,
2136                              BOOL after_wrap)
2137 {
2138         LRESULT res = EDIT_EM_PosFromChar(es, pos, after_wrap);
2139         TRACE("%d - %dx%d\n", pos, (short)LOWORD(res), (short)HIWORD(res));
2140         SetCaretPos((short)LOWORD(res), (short)HIWORD(res));
2141 }
2142
2143
2144 /*********************************************************************
2145  *
2146  *      EDIT_SetRectNP
2147  *
2148  *      note:   this is not (exactly) the handler called on EM_SETRECTNP
2149  *              it is also used to set the rect of a single line control
2150  *
2151  */
2152 static void EDIT_SetRectNP(EDITSTATE *es, LPRECT rc)
2153 {
2154         CopyRect(&es->format_rect, rc);
2155         if (es->style & WS_BORDER) {
2156                 INT bw = GetSystemMetrics(SM_CXBORDER) + 1;
2157                 es->format_rect.left += bw;
2158                 es->format_rect.top += bw;
2159                 es->format_rect.right -= bw;
2160                 es->format_rect.bottom -= bw;
2161         }
2162         es->format_rect.left += es->left_margin;
2163         es->format_rect.right -= es->right_margin;
2164         es->format_rect.right = max(es->format_rect.right, es->format_rect.left + es->char_width);
2165         if (es->style & ES_MULTILINE)
2166         {
2167             INT fw, vlc, max_x_offset, max_y_offset;
2168
2169             vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2170             es->format_rect.bottom = es->format_rect.top + max(1, vlc) * es->line_height;
2171
2172             /* correct es->x_offset */
2173             fw = es->format_rect.right - es->format_rect.left;
2174             max_x_offset = es->text_width - fw;
2175             if(max_x_offset < 0) max_x_offset = 0;
2176             if(es->x_offset > max_x_offset)
2177                 es->x_offset = max_x_offset;
2178
2179             /* correct es->y_offset */
2180             max_y_offset = es->line_count - vlc;
2181             if(max_y_offset < 0) max_y_offset = 0;
2182             if(es->y_offset > max_y_offset)
2183                 es->y_offset = max_y_offset;
2184
2185             /* force scroll info update */
2186             EDIT_UpdateScrollInfo(es);
2187         }
2188         else
2189         /* Windows doesn't care to fix text placement for SL controls */
2190                 es->format_rect.bottom = es->format_rect.top + es->line_height;
2191
2192         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL))
2193                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
2194 }
2195
2196
2197 /*********************************************************************
2198  *
2199  *      EDIT_UnlockBuffer
2200  *
2201  */
2202 static void EDIT_UnlockBuffer(EDITSTATE *es, BOOL force)
2203 {
2204         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
2205
2206         /* Edit window might be already destroyed */
2207         if(!IsWindow(es->hwndSelf))
2208         {
2209             WARN("edit hwnd %p already destroyed\n", es->hwndSelf);
2210             return;
2211         }
2212
2213         if (!es->lock_count) {
2214                 ERR("lock_count == 0 ... please report\n");
2215                 return;
2216         }
2217         if (!es->text) {
2218                 ERR("es->text == 0 ... please report\n");
2219                 return;
2220         }
2221
2222         if (force || (es->lock_count == 1)) {
2223             if (es->hloc32W) {
2224                 CHAR *textA = NULL;
2225                 BOOL _16bit = FALSE;
2226                 UINT countA = 0;
2227                 UINT countW = strlenW(es->text) + 1;
2228
2229                 if(es->hloc32A)
2230                 {
2231                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2232                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
2233                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2234                     countA = LocalSize(es->hloc32A);
2235                     if(countA_new > countA)
2236                     {
2237                         HLOCAL hloc32A_new;
2238                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2239                         TRACE("Resizing 32-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2240                         hloc32A_new = LocalReAlloc(es->hloc32A, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2241                         if(hloc32A_new)
2242                         {
2243                             es->hloc32A = hloc32A_new;
2244                             countA = LocalSize(hloc32A_new);
2245                             TRACE("Real new size %d bytes\n", countA);
2246                         }
2247                         else
2248                             WARN("FAILED! Will synchronize partially\n");
2249                     }
2250                     textA = LocalLock(es->hloc32A);
2251                 }
2252                 else if(es->hloc16)
2253                 {
2254                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2255                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
2256                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2257                     countA = LOCAL_Size(hInstance, es->hloc16);
2258                     if(countA_new > countA)
2259                     {
2260                         HLOCAL16 hloc16_new;
2261                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2262                         TRACE("Resizing 16-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2263                         hloc16_new = LOCAL_ReAlloc(hInstance, es->hloc16, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2264                         if(hloc16_new)
2265                         {
2266                             es->hloc16 = hloc16_new;
2267                             countA = LOCAL_Size(hInstance, hloc16_new);
2268                             TRACE("Real new size %d bytes\n", countA);
2269                         }
2270                         else
2271                             WARN("FAILED! Will synchronize partially\n");
2272                     }
2273                     textA = LOCAL_Lock(hInstance, es->hloc16);
2274                     _16bit = TRUE;
2275                 }
2276
2277                 if(textA)
2278                 {
2279                     WideCharToMultiByte(CP_ACP, 0, es->text, countW, textA, countA, NULL, NULL);
2280                     if(_16bit)
2281                         LOCAL_Unlock(hInstance, es->hloc16);
2282                     else
2283                         LocalUnlock(es->hloc32A);
2284                 }
2285
2286                 LocalUnlock(es->hloc32W);
2287                 es->text = NULL;
2288             }
2289             else {
2290                 ERR("no buffer ... please report\n");
2291                 return;
2292             }
2293         }
2294         es->lock_count--;
2295 }
2296
2297
2298 /*********************************************************************
2299  *
2300  *      EDIT_UpdateScrollInfo
2301  *
2302  */
2303 static void EDIT_UpdateScrollInfo(EDITSTATE *es)
2304 {
2305     if ((es->style & WS_VSCROLL) && !(es->flags & EF_VSCROLL_TRACK))
2306     {
2307         SCROLLINFO si;
2308         si.cbSize       = sizeof(SCROLLINFO);
2309         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2310         si.nMin         = 0;
2311         si.nMax         = es->line_count - 1;
2312         si.nPage        = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2313         si.nPos         = es->y_offset;
2314         TRACE("SB_VERT, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2315                 si.nMin, si.nMax, si.nPage, si.nPos);
2316         SetScrollInfo(es->hwndSelf, SB_VERT, &si, TRUE);
2317     }
2318
2319     if ((es->style & WS_HSCROLL) && !(es->flags & EF_HSCROLL_TRACK))
2320     {
2321         SCROLLINFO si;
2322         si.cbSize       = sizeof(SCROLLINFO);
2323         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2324         si.nMin         = 0;
2325         si.nMax         = es->text_width - 1;
2326         si.nPage        = es->format_rect.right - es->format_rect.left;
2327         si.nPos         = es->x_offset;
2328         TRACE("SB_HORZ, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2329                 si.nMin, si.nMax, si.nPage, si.nPos);
2330         SetScrollInfo(es->hwndSelf, SB_HORZ, &si, TRUE);
2331     }
2332 }
2333
2334 /*********************************************************************
2335  *
2336  *      EDIT_WordBreakProc
2337  *
2338  *      Find the beginning of words.
2339  *      Note:   unlike the specs for a WordBreakProc, this function only
2340  *              allows to be called without linebreaks between s[0] upto
2341  *              s[count - 1].  Remember it is only called
2342  *              internally, so we can decide this for ourselves.
2343  *
2344  */
2345 static INT CALLBACK EDIT_WordBreakProc(LPWSTR s, INT index, INT count, INT action)
2346 {
2347         INT ret = 0;
2348
2349         TRACE("s=%p, index=%d, count=%d, action=%d\n", s, index, count, action);
2350
2351         if(!s) return 0;
2352
2353         switch (action) {
2354         case WB_LEFT:
2355                 if (!count)
2356                         break;
2357                 if (index)
2358                         index--;
2359                 if (s[index] == ' ') {
2360                         while (index && (s[index] == ' '))
2361                                 index--;
2362                         if (index) {
2363                                 while (index && (s[index] != ' '))
2364                                         index--;
2365                                 if (s[index] == ' ')
2366                                         index++;
2367                         }
2368                 } else {
2369                         while (index && (s[index] != ' '))
2370                                 index--;
2371                         if (s[index] == ' ')
2372                                 index++;
2373                 }
2374                 ret = index;
2375                 break;
2376         case WB_RIGHT:
2377                 if (!count)
2378                         break;
2379                 if (index)
2380                         index--;
2381                 if (s[index] == ' ')
2382                         while ((index < count) && (s[index] == ' ')) index++;
2383                 else {
2384                         while (s[index] && (s[index] != ' ') && (index < count))
2385                                 index++;
2386                         while ((s[index] == ' ') && (index < count)) index++;
2387                 }
2388                 ret = index;
2389                 break;
2390         case WB_ISDELIMITER:
2391                 ret = (s[index] == ' ');
2392                 break;
2393         default:
2394                 ERR("unknown action code, please report !\n");
2395                 break;
2396         }
2397         return ret;
2398 }
2399
2400
2401 /*********************************************************************
2402  *
2403  *      EM_CHARFROMPOS
2404  *
2405  *      returns line number (not index) in high-order word of result.
2406  *      NB : Q137805 is unclear about this. POINT * pointer in lParam apply
2407  *      to Richedit, not to the edit control. Original documentation is valid.
2408  *      FIXME: do the specs mean to return -1 if outside client area or
2409  *              if outside formatting rectangle ???
2410  *
2411  */
2412 static LRESULT EDIT_EM_CharFromPos(EDITSTATE *es, INT x, INT y)
2413 {
2414         POINT pt;
2415         RECT rc;
2416         INT index;
2417
2418         pt.x = x;
2419         pt.y = y;
2420         GetClientRect(es->hwndSelf, &rc);
2421         if (!PtInRect(&rc, pt))
2422                 return -1;
2423
2424         index = EDIT_CharFromPos(es, x, y, NULL);
2425         return MAKELONG(index, EDIT_EM_LineFromChar(es, index));
2426 }
2427
2428
2429 /*********************************************************************
2430  *
2431  *      EM_FMTLINES
2432  *
2433  * Enable or disable soft breaks.
2434  * 
2435  * This means: insert or remove the soft linebreak character (\r\r\n).
2436  * Take care to check if the text still fits the buffer after insertion.
2437  * If not, notify with EN_ERRSPACE.
2438  * 
2439  */
2440 static BOOL EDIT_EM_FmtLines(EDITSTATE *es, BOOL add_eol)
2441 {
2442         es->flags &= ~EF_USE_SOFTBRK;
2443         if (add_eol) {
2444                 es->flags |= EF_USE_SOFTBRK;
2445                 FIXME("soft break enabled, not implemented\n");
2446         }
2447         return add_eol;
2448 }
2449
2450
2451 /*********************************************************************
2452  *
2453  *      EM_GETHANDLE
2454  *
2455  *      Hopefully this won't fire back at us.
2456  *      We always start with a fixed buffer in the local heap.
2457  *      Despite of the documentation says that the local heap is used
2458  *      only if DS_LOCALEDIT flag is set, NT and 2000 always allocate
2459  *      buffer on the local heap.
2460  *
2461  */
2462 static HLOCAL EDIT_EM_GetHandle(EDITSTATE *es)
2463 {
2464         HLOCAL hLocal;
2465
2466         if (!(es->style & ES_MULTILINE))
2467                 return 0;
2468
2469         if(es->is_unicode)
2470             hLocal = es->hloc32W;
2471         else
2472         {
2473             if(!es->hloc32A)
2474             {
2475                 CHAR *textA;
2476                 UINT countA, alloc_size;
2477                 TRACE("Allocating 32-bit ANSI alias buffer\n");
2478                 countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2479                 alloc_size = ROUND_TO_GROW(countA);
2480                 if(!(es->hloc32A = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
2481                 {
2482                     ERR("Could not allocate %d bytes for 32-bit ANSI alias buffer\n", alloc_size);
2483                     return 0;
2484                 }
2485                 textA = LocalLock(es->hloc32A);
2486                 WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2487                 LocalUnlock(es->hloc32A);
2488             }
2489             hLocal = es->hloc32A;
2490         }
2491
2492         TRACE("Returning %p, LocalSize() = %ld\n", hLocal, LocalSize(hLocal));
2493         return hLocal;
2494 }
2495
2496
2497 /*********************************************************************
2498  *
2499  *      EM_GETHANDLE16
2500  *
2501  *      Hopefully this won't fire back at us.
2502  *      We always start with a buffer in 32 bit linear memory.
2503  *      However, with this message a 16 bit application requests
2504  *      a handle of 16 bit local heap memory, where it expects to find
2505  *      the text.
2506  *      It's a pitty that from this moment on we have to use this
2507  *      local heap, because applications may rely on the handle
2508  *      in the future.
2509  *
2510  *      In this function we'll try to switch to local heap.
2511  */
2512 static HLOCAL16 EDIT_EM_GetHandle16(EDITSTATE *es)
2513 {
2514         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
2515         CHAR *textA;
2516         UINT countA, alloc_size;
2517
2518         if (!(es->style & ES_MULTILINE))
2519                 return 0;
2520
2521         if (es->hloc16)
2522                 return es->hloc16;
2523
2524         if (!LOCAL_HeapSize(hInstance)) {
2525                 if (!LocalInit16(hInstance, 0,
2526                                 GlobalSize16(hInstance))) {
2527                         ERR("could not initialize local heap\n");
2528                         return 0;
2529                 }
2530                 TRACE("local heap initialized\n");
2531         }
2532
2533         countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2534         alloc_size = ROUND_TO_GROW(countA);
2535
2536         TRACE("Allocating 16-bit ANSI alias buffer\n");
2537         if (!(es->hloc16 = LOCAL_Alloc(hInstance, LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size))) {
2538                 ERR("could not allocate new 16 bit buffer\n");
2539                 return 0;
2540         }
2541
2542         if (!(textA = (LPSTR)LOCAL_Lock(hInstance, es->hloc16))) {
2543                 ERR("could not lock new 16 bit buffer\n");
2544                 LOCAL_Free(hInstance, es->hloc16);
2545                 es->hloc16 = 0;
2546                 return 0;
2547         }
2548
2549         WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2550         LOCAL_Unlock(hInstance, es->hloc16);
2551
2552         TRACE("Returning %04X, LocalSize() = %d\n", es->hloc16, LOCAL_Size(hInstance, es->hloc16));
2553         return es->hloc16;
2554 }
2555
2556
2557 /*********************************************************************
2558  *
2559  *      EM_GETLINE
2560  *
2561  */
2562 static INT EDIT_EM_GetLine(EDITSTATE *es, INT line, LPARAM lParam, BOOL unicode)
2563 {
2564         LPWSTR src;
2565         INT line_len, dst_len;
2566         INT i;
2567
2568         if (es->style & ES_MULTILINE) {
2569                 if (line >= es->line_count)
2570                         return 0;
2571         } else
2572                 line = 0;
2573         i = EDIT_EM_LineIndex(es, line);
2574         src = es->text + i;
2575         line_len = EDIT_EM_LineLength(es, i);
2576         dst_len = *(WORD *)lParam;
2577         if(unicode)
2578         {
2579             LPWSTR dst = (LPWSTR)lParam;
2580             if(dst_len <= line_len)
2581             {
2582                 memcpy(dst, src, dst_len * sizeof(WCHAR));
2583                 return dst_len;
2584             }
2585             else /* Append 0 if enough space */
2586             {
2587                 memcpy(dst, src, line_len * sizeof(WCHAR));
2588                 dst[line_len] = 0;
2589                 return line_len;
2590             }
2591         }
2592         else
2593         {
2594             LPSTR dst = (LPSTR)lParam;
2595             INT ret;
2596             ret = WideCharToMultiByte(CP_ACP, 0, src, line_len, dst, dst_len, NULL, NULL);
2597             if(!ret) /* Insufficient buffer size */
2598                 return dst_len;
2599             if(ret < dst_len) /* Append 0 if enough space */
2600                 dst[ret] = 0;
2601             return ret;
2602         }
2603 }
2604
2605
2606 /*********************************************************************
2607  *
2608  *      EM_GETSEL
2609  *
2610  */
2611 static LRESULT EDIT_EM_GetSel(EDITSTATE *es, PUINT start, PUINT end)
2612 {
2613         UINT s = es->selection_start;
2614         UINT e = es->selection_end;
2615
2616         ORDER_UINT(s, e);
2617         if (start)
2618                 *start = s;
2619         if (end)
2620                 *end = e;
2621         return MAKELONG(s, e);
2622 }
2623
2624
2625 /*********************************************************************
2626  *
2627  *      EM_GETTHUMB
2628  *
2629  *      FIXME: is this right ?  (or should it be only VSCROLL)
2630  *      (and maybe only for edit controls that really have their
2631  *      own scrollbars) (and maybe only for multiline controls ?)
2632  *      All in all: very poorly documented
2633  *
2634  */
2635 static LRESULT EDIT_EM_GetThumb(EDITSTATE *es)
2636 {
2637         return MAKELONG(EDIT_WM_VScroll(es, EM_GETTHUMB16, 0),
2638                 EDIT_WM_HScroll(es, EM_GETTHUMB16, 0));
2639 }
2640
2641
2642 /*********************************************************************
2643  *
2644  *      EM_LINEFROMCHAR
2645  *
2646  */
2647 static INT EDIT_EM_LineFromChar(EDITSTATE *es, INT index)
2648 {
2649         INT line;
2650         LINEDEF *line_def;
2651
2652         if (!(es->style & ES_MULTILINE))
2653                 return 0;
2654         if (index > (INT)strlenW(es->text))
2655                 return es->line_count - 1;
2656         if (index == -1)
2657                 index = min(es->selection_start, es->selection_end);
2658
2659         line = 0;
2660         line_def = es->first_line_def;
2661         index -= line_def->length;
2662         while ((index >= 0) && line_def->next) {
2663                 line++;
2664                 line_def = line_def->next;
2665                 index -= line_def->length;
2666         }
2667         return line;
2668 }
2669
2670
2671 /*********************************************************************
2672  *
2673  *      EM_LINEINDEX
2674  *
2675  */
2676 static INT EDIT_EM_LineIndex(EDITSTATE *es, INT line)
2677 {
2678         INT line_index;
2679         LINEDEF *line_def;
2680
2681         if (!(es->style & ES_MULTILINE))
2682                 return 0;
2683         if (line >= es->line_count)
2684                 return -1;
2685
2686         line_index = 0;
2687         line_def = es->first_line_def;
2688         if (line == -1) {
2689                 INT index = es->selection_end - line_def->length;
2690                 while ((index >= 0) && line_def->next) {
2691                         line_index += line_def->length;
2692                         line_def = line_def->next;
2693                         index -= line_def->length;
2694                 }
2695         } else {
2696                 while (line > 0) {
2697                         line_index += line_def->length;
2698                         line_def = line_def->next;
2699                         line--;
2700                 }
2701         }
2702         return line_index;
2703 }
2704
2705
2706 /*********************************************************************
2707  *
2708  *      EM_LINELENGTH
2709  *
2710  */
2711 static INT EDIT_EM_LineLength(EDITSTATE *es, INT index)
2712 {
2713         LINEDEF *line_def;
2714
2715         if (!(es->style & ES_MULTILINE))
2716                 return strlenW(es->text);
2717
2718         if (index == -1) {
2719                 /* get the number of remaining non-selected chars of selected lines */
2720                 INT32 l; /* line number */
2721                 INT32 li; /* index of first char in line */
2722                 INT32 count;
2723                 l = EDIT_EM_LineFromChar(es, es->selection_start);
2724                 /* # chars before start of selection area */
2725                 count = es->selection_start - EDIT_EM_LineIndex(es, l);
2726                 l = EDIT_EM_LineFromChar(es, es->selection_end);
2727                 /* # chars after end of selection */
2728                 li = EDIT_EM_LineIndex(es, l);
2729                 count += li + EDIT_EM_LineLength(es, li) - es->selection_end;
2730                 return count;
2731         }
2732         line_def = es->first_line_def;
2733         index -= line_def->length;
2734         while ((index >= 0) && line_def->next) {
2735                 line_def = line_def->next;
2736                 index -= line_def->length;
2737         }
2738         return line_def->net_length;
2739 }
2740
2741
2742 /*********************************************************************
2743  *
2744  *      EM_LINESCROLL
2745  *
2746  *      NOTE: dx is in average character widths, dy - in lines;
2747  *
2748  */
2749 static BOOL EDIT_EM_LineScroll(EDITSTATE *es, INT dx, INT dy)
2750 {
2751         if (!(es->style & ES_MULTILINE))
2752                 return FALSE;
2753
2754         dx *= es->char_width;
2755         return EDIT_EM_LineScroll_internal(es, dx, dy);
2756 }
2757
2758 /*********************************************************************
2759  *
2760  *      EDIT_EM_LineScroll_internal
2761  *
2762  *      Version of EDIT_EM_LineScroll for internal use.
2763  *      It doesn't refuse if ES_MULTILINE is set and assumes that
2764  *      dx is in pixels, dy - in lines.
2765  *
2766  */
2767 static BOOL EDIT_EM_LineScroll_internal(EDITSTATE *es, INT dx, INT dy)
2768 {
2769         INT nyoff;
2770         INT x_offset_in_pixels;
2771
2772         if (es->style & ES_MULTILINE)
2773         {
2774             x_offset_in_pixels = es->x_offset;
2775         }
2776         else
2777         {
2778             dy = 0;
2779             x_offset_in_pixels = (short)LOWORD(EDIT_EM_PosFromChar(es, es->x_offset, FALSE));
2780         }
2781
2782         if (-dx > x_offset_in_pixels)
2783                 dx = -x_offset_in_pixels;
2784         if (dx > es->text_width - x_offset_in_pixels)
2785                 dx = es->text_width - x_offset_in_pixels;
2786         nyoff = max(0, es->y_offset + dy);
2787         if (nyoff >= es->line_count)
2788                 nyoff = es->line_count - 1;
2789         dy = (es->y_offset - nyoff) * es->line_height;
2790         if (dx || dy) {
2791                 RECT rc1;
2792                 RECT rc;
2793
2794                 es->y_offset = nyoff;
2795                 if(es->style & ES_MULTILINE)
2796                     es->x_offset += dx;
2797                 else
2798                     es->x_offset += dx / es->char_width;
2799
2800                 GetClientRect(es->hwndSelf, &rc1);
2801                 IntersectRect(&rc, &rc1, &es->format_rect);
2802                 ScrollWindowEx(es->hwndSelf, -dx, dy,
2803                                 NULL, &rc, NULL, NULL, SW_INVALIDATE);
2804                 /* force scroll info update */
2805                 EDIT_UpdateScrollInfo(es);
2806         }
2807         if (dx && !(es->flags & EF_HSCROLL_TRACK))
2808                 EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
2809         if (dy && !(es->flags & EF_VSCROLL_TRACK))
2810                 EDIT_NOTIFY_PARENT(es, EN_VSCROLL, "EN_VSCROLL");
2811         return TRUE;
2812 }
2813
2814
2815 /*********************************************************************
2816  *
2817  *      EM_POSFROMCHAR
2818  *
2819  */
2820 static LRESULT EDIT_EM_PosFromChar(EDITSTATE *es, INT index, BOOL after_wrap)
2821 {
2822         INT len = strlenW(es->text);
2823         INT l;
2824         INT li;
2825         INT x;
2826         INT y = 0;
2827         HDC dc;
2828         HFONT old_font = 0;
2829         SIZE size;
2830
2831         index = min(index, len);
2832         dc = GetDC(es->hwndSelf);
2833         if (es->font)
2834                 old_font = SelectObject(dc, es->font);
2835         if (es->style & ES_MULTILINE) {
2836                 l = EDIT_EM_LineFromChar(es, index);
2837                 y = (l - es->y_offset) * es->line_height;
2838                 li = EDIT_EM_LineIndex(es, l);
2839                 if (after_wrap && (li == index) && l) {
2840                         INT l2 = l - 1;
2841                         LINEDEF *line_def = es->first_line_def;
2842                         while (l2) {
2843                                 line_def = line_def->next;
2844                                 l2--;
2845                         }
2846                         if (line_def->ending == END_WRAP) {
2847                                 l--;
2848                                 y -= es->line_height;
2849                                 li = EDIT_EM_LineIndex(es, l);
2850                         }
2851                 }
2852                 x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
2853                                 es->tabs_count, es->tabs)) - es->x_offset;
2854         } else {
2855                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2856                 if (index < es->x_offset) {
2857                         GetTextExtentPoint32W(dc, text + index,
2858                                         es->x_offset - index, &size);
2859                         x = -size.cx;
2860                 } else {
2861                         GetTextExtentPoint32W(dc, text + es->x_offset,
2862                                         index - es->x_offset, &size);
2863                          x = size.cx;
2864                 }
2865                 y = 0;
2866                 if (es->style & ES_PASSWORD)
2867                         HeapFree(GetProcessHeap(), 0, text);
2868         }
2869         x += es->format_rect.left;
2870         y += es->format_rect.top;
2871         if (es->font)
2872                 SelectObject(dc, old_font);
2873         ReleaseDC(es->hwndSelf, dc);
2874         return MAKELONG((INT16)x, (INT16)y);
2875 }
2876
2877
2878 /*********************************************************************
2879  *
2880  *      EM_REPLACESEL
2881  *
2882  *      FIXME: handle ES_NUMBER and ES_OEMCONVERT here
2883  *
2884  */
2885 static void EDIT_EM_ReplaceSel(EDITSTATE *es, BOOL can_undo, LPCWSTR lpsz_replace, BOOL send_update, BOOL honor_limit)
2886 {
2887         UINT strl = strlenW(lpsz_replace);
2888         UINT tl = strlenW(es->text);
2889         UINT utl;
2890         UINT s;
2891         UINT e;
2892         UINT i;
2893         UINT size;
2894         LPWSTR p;
2895         HRGN hrgn = 0;
2896
2897         TRACE("%s, can_undo %d, send_update %d\n",
2898             debugstr_w(lpsz_replace), can_undo, send_update);
2899
2900         s = es->selection_start;
2901         e = es->selection_end;
2902
2903         if ((s == e) && !strl)
2904                 return;
2905
2906         ORDER_UINT(s, e);
2907
2908         /* Issue the EN_MAXTEXT notification and continue with replacing text
2909          * such that buffer limit is honored. */
2910         size = tl - (e - s) + strl;
2911         if ((honor_limit) && (es->buffer_limit > 0) && (size > es->buffer_limit)) {
2912                 EDIT_NOTIFY_PARENT(es, EN_MAXTEXT, "EN_MAXTEXT");
2913                 strl = es->buffer_limit - (tl - (e-s));
2914         }
2915
2916         if (!EDIT_MakeFit(es, tl - (e - s) + strl))
2917                 return;
2918
2919         if (e != s) {
2920                 /* there is something to be deleted */
2921                 TRACE("deleting stuff.\n");
2922                 if (can_undo) {
2923                         utl = strlenW(es->undo_text);
2924                         if (!es->undo_insert_count && (*es->undo_text && (s == es->undo_position))) {
2925                                 /* undo-buffer is extended to the right */
2926                                 EDIT_MakeUndoFit(es, utl + e - s);
2927                                 strncpyW(es->undo_text + utl, es->text + s, e - s + 1);
2928                                 (es->undo_text + utl)[e - s] = 0; /* ensure 0 termination */
2929                         } else if (!es->undo_insert_count && (*es->undo_text && (e == es->undo_position))) {
2930                                 /* undo-buffer is extended to the left */
2931                                 EDIT_MakeUndoFit(es, utl + e - s);
2932                                 for (p = es->undo_text + utl ; p >= es->undo_text ; p--)
2933                                         p[e - s] = p[0];
2934                                 for (i = 0 , p = es->undo_text ; i < e - s ; i++)
2935                                         p[i] = (es->text + s)[i];
2936                                 es->undo_position = s;
2937                         } else {
2938                                 /* new undo-buffer */
2939                                 EDIT_MakeUndoFit(es, e - s);
2940                                 strncpyW(es->undo_text, es->text + s, e - s + 1);
2941                                 es->undo_text[e - s] = 0; /* ensure 0 termination */
2942                                 es->undo_position = s;
2943                         }
2944                         /* any deletion makes the old insertion-undo invalid */
2945                         es->undo_insert_count = 0;
2946                 } else
2947                         EDIT_EM_EmptyUndoBuffer(es);
2948
2949                 /* now delete */
2950                 strcpyW(es->text + s, es->text + e);
2951         }
2952         if (strl) {
2953                 /* there is an insertion */
2954                 if (can_undo) {
2955                         if ((s == es->undo_position) ||
2956                                         ((es->undo_insert_count) &&
2957                                         (s == es->undo_position + es->undo_insert_count)))
2958                                 /*
2959                                  * insertion is new and at delete position or
2960                                  * an extension to either left or right
2961                                  */
2962                                 es->undo_insert_count += strl;
2963                         else {
2964                                 /* new insertion undo */
2965                                 es->undo_position = s;
2966                                 es->undo_insert_count = strl;
2967                                 /* new insertion makes old delete-buffer invalid */
2968                                 *es->undo_text = '\0';
2969                         }
2970                 } else
2971                         EDIT_EM_EmptyUndoBuffer(es);
2972
2973                 /* now insert */
2974                 tl = strlenW(es->text);
2975                 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));
2976                 for (p = es->text + tl ; p >= es->text + s ; p--)
2977                         p[strl] = p[0];
2978                 for (i = 0 , p = es->text + s ; i < strl ; i++)
2979                         p[i] = lpsz_replace[i];
2980                 if(es->style & ES_UPPERCASE)
2981                         CharUpperBuffW(p, strl);
2982                 else if(es->style & ES_LOWERCASE)
2983                         CharLowerBuffW(p, strl);
2984                 s += strl;
2985         }
2986         if (es->style & ES_MULTILINE)
2987         {
2988                 INT s = min(es->selection_start, es->selection_end);
2989
2990                 hrgn = CreateRectRgn(0, 0, 0, 0);
2991                 EDIT_BuildLineDefs_ML(es, s, s + strl,
2992                                 strl - abs(es->selection_end - es->selection_start), hrgn);
2993         }
2994         else
2995             EDIT_CalcLineWidth_SL(es);
2996
2997         EDIT_EM_SetSel(es, s, s, FALSE);
2998         es->flags |= EF_MODIFIED;
2999         if (send_update) es->flags |= EF_UPDATE;
3000         if (hrgn)
3001         {
3002                 EDIT_UpdateTextRegion(es, hrgn, TRUE);
3003                 DeleteObject(hrgn);
3004         }
3005         else
3006             EDIT_UpdateText(es, NULL, TRUE);
3007
3008         EDIT_EM_ScrollCaret(es);
3009
3010         /* force scroll info update */
3011         EDIT_UpdateScrollInfo(es);
3012
3013
3014         if(es->flags & EF_UPDATE)
3015         {
3016             es->flags &= ~EF_UPDATE;
3017             EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3018         }
3019 }
3020
3021
3022 /*********************************************************************
3023  *
3024  *      EM_SCROLL
3025  *
3026  */
3027 static LRESULT EDIT_EM_Scroll(EDITSTATE *es, INT action)
3028 {
3029         INT dy;
3030
3031         if (!(es->style & ES_MULTILINE))
3032                 return (LRESULT)FALSE;
3033
3034         dy = 0;
3035
3036         switch (action) {
3037         case SB_LINEUP:
3038                 if (es->y_offset)
3039                         dy = -1;
3040                 break;
3041         case SB_LINEDOWN:
3042                 if (es->y_offset < es->line_count - 1)
3043                         dy = 1;
3044                 break;
3045         case SB_PAGEUP:
3046                 if (es->y_offset)
3047                         dy = -(es->format_rect.bottom - es->format_rect.top) / es->line_height;
3048                 break;
3049         case SB_PAGEDOWN:
3050                 if (es->y_offset < es->line_count - 1)
3051                         dy = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3052                 break;
3053         default:
3054                 return (LRESULT)FALSE;
3055         }
3056         if (dy) {
3057             INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3058             /* check if we are going to move too far */
3059             if(es->y_offset + dy > es->line_count - vlc)
3060                 dy = es->line_count - vlc - es->y_offset;
3061
3062             /* Notification is done in EDIT_EM_LineScroll */
3063             if(dy)
3064                 EDIT_EM_LineScroll(es, 0, dy);
3065         }
3066         return MAKELONG((INT16)dy, (BOOL16)TRUE);
3067 }
3068
3069
3070 /*********************************************************************
3071  *
3072  *      EM_SCROLLCARET
3073  *
3074  */
3075 static void EDIT_EM_ScrollCaret(EDITSTATE *es)
3076 {
3077         if (es->style & ES_MULTILINE) {
3078                 INT l;
3079                 INT li;
3080                 INT vlc;
3081                 INT ww;
3082                 INT cw = es->char_width;
3083                 INT x;
3084                 INT dy = 0;
3085                 INT dx = 0;
3086
3087                 l = EDIT_EM_LineFromChar(es, es->selection_end);
3088                 li = EDIT_EM_LineIndex(es, l);
3089                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP));
3090                 vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3091                 if (l >= es->y_offset + vlc)
3092                         dy = l - vlc + 1 - es->y_offset;
3093                 if (l < es->y_offset)
3094                         dy = l - es->y_offset;
3095                 ww = es->format_rect.right - es->format_rect.left;
3096                 if (x < es->format_rect.left)
3097                         dx = x - es->format_rect.left - ww / HSCROLL_FRACTION / cw * cw;
3098                 if (x > es->format_rect.right)
3099                         dx = x - es->format_rect.left - (HSCROLL_FRACTION - 1) * ww / HSCROLL_FRACTION / cw * cw;
3100                 if (dy || dx)
3101                 {
3102                     /* check if we are going to move too far */
3103                     if(es->x_offset + dx + ww > es->text_width)
3104                         dx = es->text_width - ww - es->x_offset;
3105                     if(dx || dy)
3106                         EDIT_EM_LineScroll_internal(es, dx, dy);
3107                 }
3108         } else {
3109                 INT x;
3110                 INT goal;
3111                 INT format_width;
3112
3113                 if (!(es->style & ES_AUTOHSCROLL))
3114                         return;
3115
3116                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3117                 format_width = es->format_rect.right - es->format_rect.left;
3118                 if (x < es->format_rect.left) {
3119                         goal = es->format_rect.left + format_width / HSCROLL_FRACTION;
3120                         do {
3121                                 es->x_offset--;
3122                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3123                         } while ((x < goal) && es->x_offset);
3124                         /* FIXME: use ScrollWindow() somehow to improve performance */
3125                         EDIT_UpdateText(es, NULL, TRUE);
3126                 } else if (x > es->format_rect.right) {
3127                         INT x_last;
3128                         INT len = strlenW(es->text);
3129                         goal = es->format_rect.right - format_width / HSCROLL_FRACTION;
3130                         do {
3131                                 es->x_offset++;
3132                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3133                                 x_last = (short)LOWORD(EDIT_EM_PosFromChar(es, len, FALSE));
3134                         } while ((x > goal) && (x_last > es->format_rect.right));
3135                         /* FIXME: use ScrollWindow() somehow to improve performance */
3136                         EDIT_UpdateText(es, NULL, TRUE);
3137                 }
3138         }
3139
3140     if(es->flags & EF_FOCUSED)
3141         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
3142 }
3143
3144
3145 /*********************************************************************
3146  *
3147  *      EM_SETHANDLE
3148  *
3149  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3150  *
3151  */
3152 static void EDIT_EM_SetHandle(EDITSTATE *es, HLOCAL hloc)
3153 {
3154         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
3155
3156         if (!(es->style & ES_MULTILINE))
3157                 return;
3158
3159         if (!hloc) {
3160                 WARN("called with NULL handle\n");
3161                 return;
3162         }
3163
3164         EDIT_UnlockBuffer(es, TRUE);
3165
3166         if(es->hloc16)
3167         {
3168             LOCAL_Free(hInstance, es->hloc16);
3169             es->hloc16 = (HLOCAL16)NULL;
3170         }
3171
3172         if(es->is_unicode)
3173         {
3174             if(es->hloc32A)
3175             {
3176                 LocalFree(es->hloc32A);
3177                 es->hloc32A = NULL;
3178             }
3179             es->hloc32W = hloc;
3180         }
3181         else
3182         {
3183             INT countW, countA;
3184             HLOCAL hloc32W_new;
3185             WCHAR *textW;
3186             CHAR *textA;
3187
3188             countA = LocalSize(hloc);
3189             textA = LocalLock(hloc);
3190             countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3191             if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3192             {
3193                 ERR("Could not allocate new unicode buffer\n");
3194                 return;
3195             }
3196             textW = LocalLock(hloc32W_new);
3197             MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3198             LocalUnlock(hloc32W_new);
3199             LocalUnlock(hloc);
3200
3201             if(es->hloc32W)
3202                 LocalFree(es->hloc32W);
3203
3204             es->hloc32W = hloc32W_new;
3205             es->hloc32A = hloc;
3206         }
3207
3208         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3209
3210         EDIT_LockBuffer(es);
3211
3212         es->x_offset = es->y_offset = 0;
3213         es->selection_start = es->selection_end = 0;
3214         EDIT_EM_EmptyUndoBuffer(es);
3215         es->flags &= ~EF_MODIFIED;
3216         es->flags &= ~EF_UPDATE;
3217         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3218         EDIT_UpdateText(es, NULL, TRUE);
3219         EDIT_EM_ScrollCaret(es);
3220         /* force scroll info update */
3221         EDIT_UpdateScrollInfo(es);
3222 }
3223
3224
3225 /*********************************************************************
3226  *
3227  *      EM_SETHANDLE16
3228  *
3229  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3230  *
3231  */
3232 static void EDIT_EM_SetHandle16(EDITSTATE *es, HLOCAL16 hloc)
3233 {
3234         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
3235         INT countW, countA;
3236         HLOCAL hloc32W_new;
3237         WCHAR *textW;
3238         CHAR *textA;
3239
3240         if (!(es->style & ES_MULTILINE))
3241                 return;
3242
3243         if (!hloc) {
3244                 WARN("called with NULL handle\n");
3245                 return;
3246         }
3247
3248         EDIT_UnlockBuffer(es, TRUE);
3249
3250         if(es->hloc32A)
3251         {
3252             LocalFree(es->hloc32A);
3253             es->hloc32A = NULL;
3254         }
3255
3256         countA = LOCAL_Size(hInstance, hloc);
3257         textA = LOCAL_Lock(hInstance, hloc);
3258         countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3259         if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3260         {
3261             ERR("Could not allocate new unicode buffer\n");
3262             return;
3263         }
3264         textW = LocalLock(hloc32W_new);
3265         MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3266         LocalUnlock(hloc32W_new);
3267         LOCAL_Unlock(hInstance, hloc);
3268
3269         if(es->hloc32W)
3270             LocalFree(es->hloc32W);
3271
3272         es->hloc32W = hloc32W_new;
3273         es->hloc16 = hloc;
3274
3275         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3276
3277         EDIT_LockBuffer(es);
3278
3279         es->x_offset = es->y_offset = 0;
3280         es->selection_start = es->selection_end = 0;
3281         EDIT_EM_EmptyUndoBuffer(es);
3282         es->flags &= ~EF_MODIFIED;
3283         es->flags &= ~EF_UPDATE;
3284         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3285         EDIT_UpdateText(es, NULL, TRUE);
3286         EDIT_EM_ScrollCaret(es);
3287         /* force scroll info update */
3288         EDIT_UpdateScrollInfo(es);
3289 }
3290
3291
3292 /*********************************************************************
3293  *
3294  *      EM_SETLIMITTEXT
3295  *
3296  *      FIXME: in WinNT maxsize is 0x7FFFFFFF / 0xFFFFFFFF
3297  *      However, the windows version is not complied to yet in all of edit.c
3298  *
3299  *  Additionally as the wrapper for RichEdit controls we need larger buffers
3300  *  at present -1 will represent nolimit
3301  */
3302 static void EDIT_EM_SetLimitText(EDITSTATE *es, INT limit)
3303 {
3304     if (limit == 0xFFFFFFFF)
3305         es->buffer_limit = -1;
3306     else if (es->style & ES_MULTILINE) {
3307                 if (limit)
3308                         es->buffer_limit = min(limit, BUFLIMIT_MULTI);
3309                 else
3310                         es->buffer_limit = BUFLIMIT_MULTI;
3311         } else {
3312                 if (limit)
3313                         es->buffer_limit = min(limit, BUFLIMIT_SINGLE);
3314                 else
3315                         es->buffer_limit = BUFLIMIT_SINGLE;
3316         }
3317 }
3318
3319
3320 /*********************************************************************
3321  *
3322  *      EM_SETMARGINS
3323  *
3324  * EC_USEFONTINFO is used as a left or right value i.e. lParam and not as an
3325  * action wParam despite what the docs say. EC_USEFONTINFO calculates the
3326  * margin according to the textmetrics of the current font.
3327  *
3328  * FIXME - With TrueType or vector fonts EC_USEFONTINFO currently sets one third
3329  * of the char's width as the margin, but this is not how Windows handles this.
3330  * For all other fonts Windows sets the margins to zero.
3331  *
3332  */
3333 static void EDIT_EM_SetMargins(EDITSTATE *es, INT action,
3334                                INT left, INT right)
3335 {
3336         TEXTMETRICW tm;
3337         INT default_left_margin  = 0; /* in pixels */
3338         INT default_right_margin = 0; /* in pixels */
3339
3340         /* Set the default margins depending on the font */
3341         if (es->font && (left == EC_USEFONTINFO || right == EC_USEFONTINFO)) {
3342             HDC dc = GetDC(es->hwndSelf);
3343             HFONT old_font = SelectObject(dc, es->font);
3344             GetTextMetricsW(dc, &tm);
3345             /* The default margins are only non zero for TrueType or Vector fonts */
3346             if (tm.tmPitchAndFamily & ( TMPF_VECTOR | TMPF_TRUETYPE )) {
3347                 /* This must be calculated more exactly! But how? */
3348                 default_left_margin = tm.tmAveCharWidth / 3;
3349                 default_right_margin = tm.tmAveCharWidth / 3;
3350             }
3351             SelectObject(dc, old_font);
3352             ReleaseDC(es->hwndSelf, dc);
3353         }
3354
3355         if (action & EC_LEFTMARGIN) {
3356                 if (left != EC_USEFONTINFO)
3357                         es->left_margin = left;
3358                 else
3359                         es->left_margin = default_left_margin;
3360         }
3361
3362         if (action & EC_RIGHTMARGIN) {
3363                 if (right != EC_USEFONTINFO)
3364                         es->right_margin = right;
3365                 else
3366                         es->right_margin = default_right_margin;
3367         }
3368         TRACE("left=%d, right=%d\n", es->left_margin, es->right_margin);
3369 }
3370
3371
3372 /*********************************************************************
3373  *
3374  *      EM_SETPASSWORDCHAR
3375  *
3376  */
3377 static void EDIT_EM_SetPasswordChar(EDITSTATE *es, WCHAR c)
3378 {
3379         LONG style;
3380
3381         if (es->style & ES_MULTILINE)
3382                 return;
3383
3384         if (es->password_char == c)
3385                 return;
3386
3387         style = GetWindowLongW( es->hwndSelf, GWL_STYLE );
3388         es->password_char = c;
3389         if (c) {
3390             SetWindowLongW( es->hwndSelf, GWL_STYLE, style | ES_PASSWORD );
3391             es->style |= ES_PASSWORD;
3392         } else {
3393             SetWindowLongW( es->hwndSelf, GWL_STYLE, style & ~ES_PASSWORD );
3394             es->style &= ~ES_PASSWORD;
3395         }
3396         EDIT_UpdateText(es, NULL, TRUE);
3397 }
3398
3399
3400 /*********************************************************************
3401  *
3402  *      EDIT_EM_SetSel
3403  *
3404  *      note:   unlike the specs say: the order of start and end
3405  *              _is_ preserved in Windows.  (i.e. start can be > end)
3406  *              In other words: this handler is OK
3407  *
3408  */
3409 static void EDIT_EM_SetSel(EDITSTATE *es, UINT start, UINT end, BOOL after_wrap)
3410 {
3411         UINT old_start = es->selection_start;
3412         UINT old_end = es->selection_end;
3413         UINT len = strlenW(es->text);
3414
3415         if (start == (UINT)-1) {
3416                 start = es->selection_end;
3417                 end = es->selection_end;
3418         } else {
3419                 start = min(start, len);
3420                 end = min(end, len);
3421         }
3422         es->selection_start = start;
3423         es->selection_end = end;
3424         if (after_wrap)
3425                 es->flags |= EF_AFTER_WRAP;
3426         else
3427                 es->flags &= ~EF_AFTER_WRAP;
3428 /* This is a little bit more efficient than before, not sure if it can be improved. FIXME? */
3429         ORDER_UINT(start, end);
3430         ORDER_UINT(end, old_end);
3431         ORDER_UINT(start, old_start);
3432         ORDER_UINT(old_start, old_end);
3433         if (end != old_start)
3434         {
3435 /*
3436  * One can also do
3437  *          ORDER_UINT32(end, old_start);
3438  *          EDIT_InvalidateText(es, start, end);
3439  *          EDIT_InvalidateText(es, old_start, old_end);
3440  * in place of the following if statement.
3441  */
3442             if (old_start > end )
3443             {
3444                 EDIT_InvalidateText(es, start, end);
3445                 EDIT_InvalidateText(es, old_start, old_end);
3446             }
3447             else
3448             {
3449                 EDIT_InvalidateText(es, start, old_start);
3450                 EDIT_InvalidateText(es, end, old_end);
3451             }
3452         }
3453         else EDIT_InvalidateText(es, start, old_end);
3454 }
3455
3456
3457 /*********************************************************************
3458  *
3459  *      EM_SETTABSTOPS
3460  *
3461  */
3462 static BOOL EDIT_EM_SetTabStops(EDITSTATE *es, INT count, LPINT tabs)
3463 {
3464         if (!(es->style & ES_MULTILINE))
3465                 return FALSE;
3466         if (es->tabs)
3467                 HeapFree(GetProcessHeap(), 0, es->tabs);
3468         es->tabs_count = count;
3469         if (!count)
3470                 es->tabs = NULL;
3471         else {
3472                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3473                 memcpy(es->tabs, tabs, count * sizeof(INT));
3474         }
3475         return TRUE;
3476 }
3477
3478
3479 /*********************************************************************
3480  *
3481  *      EM_SETTABSTOPS16
3482  *
3483  */
3484 static BOOL EDIT_EM_SetTabStops16(EDITSTATE *es, INT count, LPINT16 tabs)
3485 {
3486         if (!(es->style & ES_MULTILINE))
3487                 return FALSE;
3488         if (es->tabs)
3489                 HeapFree(GetProcessHeap(), 0, es->tabs);
3490         es->tabs_count = count;
3491         if (!count)
3492                 es->tabs = NULL;
3493         else {
3494                 INT i;
3495                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3496                 for (i = 0 ; i < count ; i++)
3497                         es->tabs[i] = *tabs++;
3498         }
3499         return TRUE;
3500 }
3501
3502
3503 /*********************************************************************
3504  *
3505  *      EM_SETWORDBREAKPROC
3506  *
3507  */
3508 static void EDIT_EM_SetWordBreakProc(EDITSTATE *es, LPARAM lParam)
3509 {
3510         if (es->word_break_proc == (void *)lParam)
3511                 return;
3512
3513         es->word_break_proc = (void *)lParam;
3514         es->word_break_proc16 = NULL;
3515
3516         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3517                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3518                 EDIT_UpdateText(es, NULL, TRUE);
3519         }
3520 }
3521
3522
3523 /*********************************************************************
3524  *
3525  *      EM_SETWORDBREAKPROC16
3526  *
3527  */
3528 static void EDIT_EM_SetWordBreakProc16(EDITSTATE *es, EDITWORDBREAKPROC16 wbp)
3529 {
3530         if (es->word_break_proc16 == wbp)
3531                 return;
3532
3533         es->word_break_proc = NULL;
3534         es->word_break_proc16 = wbp;
3535         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3536                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3537                 EDIT_UpdateText(es, NULL, TRUE);
3538         }
3539 }
3540
3541
3542 /*********************************************************************
3543  *
3544  *      EM_UNDO / WM_UNDO
3545  *
3546  */
3547 static BOOL EDIT_EM_Undo(EDITSTATE *es)
3548 {
3549         INT ulength;
3550         LPWSTR utext;
3551
3552         /* As per MSDN spec, for a single-line edit control,
3553            the return value is always TRUE */
3554         if( es->style & ES_READONLY )
3555             return !(es->style & ES_MULTILINE);
3556
3557         ulength = strlenW(es->undo_text);
3558         if( ulength == 0 )
3559             return !(es->style & ES_MULTILINE);
3560
3561         utext = HeapAlloc(GetProcessHeap(), 0, (ulength + 1) * sizeof(WCHAR));
3562
3563         strcpyW(utext, es->undo_text);
3564
3565         TRACE("before UNDO:insertion length = %d, deletion buffer = %s\n",
3566                      es->undo_insert_count, debugstr_w(utext));
3567
3568         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3569         EDIT_EM_EmptyUndoBuffer(es);
3570         EDIT_EM_ReplaceSel(es, TRUE, utext, FALSE, TRUE);
3571         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3572         /* send the notification after the selection start and end are set */
3573         EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3574         EDIT_EM_ScrollCaret(es);
3575         HeapFree(GetProcessHeap(), 0, utext);
3576
3577         TRACE("after UNDO:insertion length = %d, deletion buffer = %s\n",
3578                         es->undo_insert_count, debugstr_w(es->undo_text));
3579         return TRUE;
3580 }
3581
3582
3583 /*********************************************************************
3584  *
3585  *      WM_CHAR
3586  *
3587  */
3588 static void EDIT_WM_Char(EDITSTATE *es, WCHAR c)
3589 {
3590         BOOL control;
3591
3592         /* Protect read-only edit control from modification */
3593         if(es->style & ES_READONLY)
3594             return;
3595
3596         control = GetKeyState(VK_CONTROL) & 0x8000;
3597
3598         switch (c) {
3599         case '\r':
3600             /* If the edit doesn't want the return and it's not a multiline edit, do nothing */
3601             if(!(es->style & ES_MULTILINE) && !(es->style & ES_WANTRETURN))
3602                 break;
3603         case '\n':
3604                 if (es->style & ES_MULTILINE) {
3605                         if (es->style & ES_READONLY) {
3606                                 EDIT_MoveHome(es, FALSE);
3607                                 EDIT_MoveDown_ML(es, FALSE);
3608                         } else {
3609                                 static const WCHAR cr_lfW[] = {'\r','\n',0};
3610                                 EDIT_EM_ReplaceSel(es, TRUE, cr_lfW, TRUE, TRUE);
3611                         }
3612                 }
3613                 break;
3614         case '\t':
3615                 if ((es->style & ES_MULTILINE) && !(es->style & ES_READONLY))
3616                 {
3617                         static const WCHAR tabW[] = {'\t',0};
3618                         EDIT_EM_ReplaceSel(es, TRUE, tabW, TRUE, TRUE);
3619                 }
3620                 break;
3621         case VK_BACK:
3622                 if (!(es->style & ES_READONLY) && !control) {
3623                         if (es->selection_start != es->selection_end)
3624                                 EDIT_WM_Clear(es);
3625                         else {
3626                                 /* delete character left of caret */
3627                                 EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3628                                 EDIT_MoveBackward(es, TRUE);
3629                                 EDIT_WM_Clear(es);
3630                         }
3631                 }
3632                 break;
3633         case 0x03: /* ^C */
3634                 SendMessageW(es->hwndSelf, WM_COPY, 0, 0);
3635                 break;
3636         case 0x16: /* ^V */
3637                 SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3638                 break;
3639         case 0x18: /* ^X */
3640                 SendMessageW(es->hwndSelf, WM_CUT, 0, 0);
3641                 break;
3642
3643         default:
3644                 if (!(es->style & ES_READONLY) && (c >= ' ') && (c != 127)) {
3645                         WCHAR str[2];
3646                         str[0] = c;
3647                         str[1] = '\0';
3648                         EDIT_EM_ReplaceSel(es, TRUE, str, TRUE, TRUE);
3649                 }
3650                 break;
3651         }
3652 }
3653
3654
3655 /*********************************************************************
3656  *
3657  *      WM_COMMAND
3658  *
3659  */
3660 static void EDIT_WM_Command(EDITSTATE *es, INT code, INT id, HWND control)
3661 {
3662         if (code || control)
3663                 return;
3664
3665         switch (id) {
3666                 case EM_UNDO:
3667                         EDIT_EM_Undo(es);
3668                         break;
3669                 case WM_CUT:
3670                         EDIT_WM_Cut(es);
3671                         break;
3672                 case WM_COPY:
3673                         EDIT_WM_Copy(es);
3674                         break;
3675                 case WM_PASTE:
3676                         EDIT_WM_Paste(es);
3677                         break;
3678                 case WM_CLEAR:
3679                         EDIT_WM_Clear(es);
3680                         break;
3681                 case EM_SETSEL:
3682                         EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
3683                         EDIT_EM_ScrollCaret(es);
3684                         break;
3685                 default:
3686                         ERR("unknown menu item, please report\n");
3687                         break;
3688         }
3689 }
3690
3691
3692 /*********************************************************************
3693  *
3694  *      WM_CONTEXTMENU
3695  *
3696  *      Note: the resource files resource/sysres_??.rc cannot define a
3697  *              single popup menu.  Hence we use a (dummy) menubar
3698  *              containing the single popup menu as its first item.
3699  *
3700  *      FIXME: the message identifiers have been chosen arbitrarily,
3701  *              hence we use MF_BYPOSITION.
3702  *              We might as well use the "real" values (anybody knows ?)
3703  *              The menu definition is in resources/sysres_??.rc.
3704  *              Once these are OK, we better use MF_BYCOMMAND here
3705  *              (as we do in EDIT_WM_Command()).
3706  *
3707  */
3708 static void EDIT_WM_ContextMenu(EDITSTATE *es, INT x, INT y)
3709 {
3710         HMENU menu = LoadMenuA(user32_module, "EDITMENU");
3711         HMENU popup = GetSubMenu(menu, 0);
3712         UINT start = es->selection_start;
3713         UINT end = es->selection_end;
3714
3715         ORDER_UINT(start, end);
3716
3717         /* undo */
3718         EnableMenuItem(popup, 0, MF_BYPOSITION | (EDIT_EM_CanUndo(es) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3719         /* cut */
3720         EnableMenuItem(popup, 2, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3721         /* copy */
3722         EnableMenuItem(popup, 3, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) ? MF_ENABLED : MF_GRAYED));
3723         /* paste */
3724         EnableMenuItem(popup, 4, MF_BYPOSITION | (IsClipboardFormatAvailable(CF_UNICODETEXT) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3725         /* delete */
3726         EnableMenuItem(popup, 5, MF_BYPOSITION | ((end - start) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3727         /* select all */
3728         EnableMenuItem(popup, 7, MF_BYPOSITION | (start || (end != strlenW(es->text)) ? MF_ENABLED : MF_GRAYED));
3729
3730         TrackPopupMenu(popup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, es->hwndSelf, NULL);
3731         DestroyMenu(menu);
3732 }
3733
3734
3735 /*********************************************************************
3736  *
3737  *      WM_COPY
3738  *
3739  */
3740 static void EDIT_WM_Copy(EDITSTATE *es)
3741 {
3742         INT s = min(es->selection_start, es->selection_end);
3743         INT e = max(es->selection_start, es->selection_end);
3744         HGLOBAL hdst;
3745         LPWSTR dst;
3746
3747         if (e == s) return;
3748
3749         hdst = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (DWORD)(e - s + 1) * sizeof(WCHAR));
3750         dst = GlobalLock(hdst);
3751         strncpyW(dst, es->text + s, e - s);
3752         dst[e - s] = 0; /* ensure 0 termination */
3753         TRACE("%s\n", debugstr_w(dst));
3754         GlobalUnlock(hdst);
3755         OpenClipboard(es->hwndSelf);
3756         EmptyClipboard();
3757         SetClipboardData(CF_UNICODETEXT, hdst);
3758         CloseClipboard();
3759 }
3760
3761
3762 /*********************************************************************
3763  *
3764  *      WM_CREATE
3765  *
3766  */
3767 static LRESULT EDIT_WM_Create(EDITSTATE *es, LPCWSTR name)
3768 {
3769         TRACE("%s\n", debugstr_w(name));
3770        /*
3771         *       To initialize some final structure members, we call some helper
3772         *       functions.  However, since the EDITSTATE is not consistent (i.e.
3773         *       not fully initialized), we should be very careful which
3774         *       functions can be called, and in what order.
3775         */
3776         EDIT_WM_SetFont(es, 0, FALSE);
3777         EDIT_EM_EmptyUndoBuffer(es);
3778
3779        if (name && *name) {
3780            EDIT_EM_ReplaceSel(es, FALSE, name, FALSE, TRUE);
3781            /* if we insert text to the editline, the text scrolls out
3782             * of the window, as the caret is placed after the insert
3783             * pos normally; thus we reset es->selection... to 0 and
3784             * update caret
3785             */
3786            es->selection_start = es->selection_end = 0;
3787            /* Adobe Photoshop does NOT like this. and MSDN says that EN_CHANGE
3788             * Messages are only to be sent when the USER does something to
3789             * change the contents. So I am removing this EN_CHANGE
3790             *
3791             * EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3792             */
3793            EDIT_EM_ScrollCaret(es);
3794        }
3795        /* force scroll info update */
3796        EDIT_UpdateScrollInfo(es);
3797        /* The rule seems to return 1 here for success */
3798        /* Power Builder masked edit controls will crash  */
3799        /* if not. */
3800        /* FIXME: is that in all cases so ? */
3801        return 1;
3802 }
3803
3804
3805 /*********************************************************************
3806  *
3807  *      WM_DESTROY
3808  *
3809  */
3810 static LRESULT EDIT_WM_Destroy(EDITSTATE *es)
3811 {
3812         LINEDEF *pc, *pp;
3813
3814         if (es->hloc32W) {
3815                 while (LocalUnlock(es->hloc32W)) ;
3816                 LocalFree(es->hloc32W);
3817         }
3818         if (es->hloc32A) {
3819                 while (LocalUnlock(es->hloc32A)) ;
3820                 LocalFree(es->hloc32A);
3821         }
3822         if (es->hloc16) {
3823                 HINSTANCE16 hInstance = GetWindowWord( es->hwndSelf, GWL_HINSTANCE );
3824                 while (LOCAL_Unlock(hInstance, es->hloc16)) ;
3825                 LOCAL_Free(hInstance, es->hloc16);
3826         }
3827
3828         pc = es->first_line_def;
3829         while (pc)
3830         {
3831                 pp = pc->next;
3832                 HeapFree(GetProcessHeap(), 0, pc);
3833                 pc = pp;
3834         }
3835
3836         SetWindowLongW( es->hwndSelf, 0, 0 );
3837         HeapFree(GetProcessHeap(), 0, es);
3838
3839         return 0;
3840 }
3841
3842
3843 /*********************************************************************
3844  *
3845  *      WM_ERASEBKGND
3846  *
3847  */
3848 static LRESULT EDIT_WM_EraseBkGnd(EDITSTATE *es, HDC dc)
3849 {
3850         HBRUSH brush;
3851         RECT rc;
3852
3853         if (!(brush = EDIT_NotifyCtlColor(es, dc)))
3854                 brush = (HBRUSH)GetStockObject(WHITE_BRUSH);
3855
3856         GetClientRect(es->hwndSelf, &rc);
3857         IntersectClipRect(dc, rc.left, rc.top, rc.right, rc.bottom);
3858         GetClipBox(dc, &rc);
3859         /*
3860          *      FIXME:  specs say that we should UnrealizeObject() the brush,
3861          *              but the specs of UnrealizeObject() say that we shouldn't
3862          *              unrealize a stock object.  The default brush that
3863          *              DefWndProc() returns is ... a stock object.
3864          */
3865         FillRect(dc, &rc, brush);
3866         return -1;
3867 }
3868
3869
3870 /*********************************************************************
3871  *
3872  *      WM_GETTEXT
3873  *
3874  */
3875 static INT EDIT_WM_GetText(EDITSTATE *es, INT count, LPARAM lParam, BOOL unicode)
3876 {
3877     if(!count) return 0;
3878
3879     if(unicode)
3880     {
3881         LPWSTR textW = (LPWSTR)lParam;
3882         lstrcpynW(textW, es->text, count);
3883         return strlenW(textW);
3884     }
3885     else
3886     {
3887         LPSTR textA = (LPSTR)lParam;
3888         if (!WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, count, NULL, NULL))
3889             textA[count - 1] = 0; /* ensure 0 termination */
3890         return strlen(textA);
3891     }
3892 }
3893
3894 /*********************************************************************
3895  *
3896  *      WM_HSCROLL
3897  *
3898  */
3899 static LRESULT EDIT_WM_HScroll(EDITSTATE *es, INT action, INT pos)
3900 {
3901         INT dx;
3902         INT fw;
3903
3904         if (!(es->style & ES_MULTILINE))
3905                 return 0;
3906
3907         if (!(es->style & ES_AUTOHSCROLL))
3908                 return 0;
3909
3910         dx = 0;
3911         fw = es->format_rect.right - es->format_rect.left;
3912         switch (action) {
3913         case SB_LINELEFT:
3914                 TRACE("SB_LINELEFT\n");
3915                 if (es->x_offset)
3916                         dx = -es->char_width;
3917                 break;
3918         case SB_LINERIGHT:
3919                 TRACE("SB_LINERIGHT\n");
3920                 if (es->x_offset < es->text_width)
3921                         dx = es->char_width;
3922                 break;
3923         case SB_PAGELEFT:
3924                 TRACE("SB_PAGELEFT\n");
3925                 if (es->x_offset)
3926                         dx = -fw / HSCROLL_FRACTION / es->char_width * es->char_width;
3927                 break;
3928         case SB_PAGERIGHT:
3929                 TRACE("SB_PAGERIGHT\n");
3930                 if (es->x_offset < es->text_width)
3931                         dx = fw / HSCROLL_FRACTION / es->char_width * es->char_width;
3932                 break;
3933         case SB_LEFT:
3934                 TRACE("SB_LEFT\n");
3935                 if (es->x_offset)
3936                         dx = -es->x_offset;
3937                 break;
3938         case SB_RIGHT:
3939                 TRACE("SB_RIGHT\n");
3940                 if (es->x_offset < es->text_width)
3941                         dx = es->text_width - es->x_offset;
3942                 break;
3943         case SB_THUMBTRACK:
3944                 TRACE("SB_THUMBTRACK %d\n", pos);
3945                 es->flags |= EF_HSCROLL_TRACK;
3946                 if(es->style & WS_HSCROLL)
3947                     dx = pos - es->x_offset;
3948                 else
3949                 {
3950                     INT fw, new_x;
3951                     /* Sanity check */
3952                     if(pos < 0 || pos > 100) return 0;
3953                     /* Assume default scroll range 0-100 */
3954                     fw = es->format_rect.right - es->format_rect.left;
3955                     new_x = pos * (es->text_width - fw) / 100;
3956                     dx = es->text_width ? (new_x - es->x_offset) : 0;
3957                 }
3958                 break;
3959         case SB_THUMBPOSITION:
3960                 TRACE("SB_THUMBPOSITION %d\n", pos);
3961                 es->flags &= ~EF_HSCROLL_TRACK;
3962                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
3963                     dx = pos - es->x_offset;
3964                 else
3965                 {
3966                     INT fw, new_x;
3967                     /* Sanity check */
3968                     if(pos < 0 || pos > 100) return 0;
3969                     /* Assume default scroll range 0-100 */
3970                     fw = es->format_rect.right - es->format_rect.left;
3971                     new_x = pos * (es->text_width - fw) / 100;
3972                     dx = es->text_width ? (new_x - es->x_offset) : 0;
3973                 }
3974                 if (!dx) {
3975                         /* force scroll info update */
3976                         EDIT_UpdateScrollInfo(es);
3977                         EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
3978                 }
3979                 break;
3980         case SB_ENDSCROLL:
3981                 TRACE("SB_ENDSCROLL\n");
3982                 break;
3983         /*
3984          *      FIXME : the next two are undocumented !
3985          *      Are we doing the right thing ?
3986          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
3987          *      although it's also a regular control message.
3988          */
3989         case EM_GETTHUMB: /* this one is used by NT notepad */
3990         case EM_GETTHUMB16:
3991         {
3992                 LRESULT ret;
3993                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
3994                     ret = GetScrollPos(es->hwndSelf, SB_HORZ);
3995                 else
3996                 {
3997                     /* Assume default scroll range 0-100 */
3998                     INT fw = es->format_rect.right - es->format_rect.left;
3999                     ret = es->text_width ? es->x_offset * 100 / (es->text_width - fw) : 0;
4000                 }
4001                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
4002                 return ret;
4003         }
4004         case EM_LINESCROLL16:
4005                 TRACE("EM_LINESCROLL16\n");
4006                 dx = pos;
4007                 break;
4008
4009         default:
4010                 ERR("undocumented WM_HSCROLL action %d (0x%04x), please report\n",
4011                     action, action);
4012                 return 0;
4013         }
4014         if (dx)
4015         {
4016             INT fw = es->format_rect.right - es->format_rect.left;
4017             /* check if we are going to move too far */
4018             if(es->x_offset + dx + fw > es->text_width)
4019                 dx = es->text_width - fw - es->x_offset;
4020             if(dx)
4021                 EDIT_EM_LineScroll_internal(es, dx, 0);
4022         }
4023         return 0;
4024 }
4025
4026
4027 /*********************************************************************
4028  *
4029  *      EDIT_CheckCombo
4030  *
4031  */
4032 static BOOL EDIT_CheckCombo(EDITSTATE *es, UINT msg, INT key)
4033 {
4034    HWND hLBox = es->hwndListBox;
4035    HWND hCombo;
4036    BOOL bDropped;
4037    int  nEUI;
4038
4039    if (!hLBox)
4040       return FALSE;
4041
4042    hCombo   = GetParent(es->hwndSelf);
4043    bDropped = TRUE;
4044    nEUI     = 0;
4045
4046    TRACE_(combo)("[%p]: handling msg %x (%x)\n", es->hwndSelf, msg, key);
4047
4048    if (key == VK_UP || key == VK_DOWN)
4049    {
4050       if (SendMessageW(hCombo, CB_GETEXTENDEDUI, 0, 0))
4051          nEUI = 1;
4052
4053       if (msg == WM_KEYDOWN || nEUI)
4054           bDropped = (BOOL)SendMessageW(hCombo, CB_GETDROPPEDSTATE, 0, 0);
4055    }
4056
4057    switch (msg)
4058    {
4059       case WM_KEYDOWN:
4060          if (!bDropped && nEUI && (key == VK_UP || key == VK_DOWN))
4061          {
4062             /* make sure ComboLBox pops up */
4063             SendMessageW(hCombo, CB_SETEXTENDEDUI, FALSE, 0);
4064             key = VK_F4;
4065             nEUI = 2;
4066          }
4067
4068          SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)key, 0);
4069          break;
4070
4071       case WM_SYSKEYDOWN: /* Handle Alt+up/down arrows */
4072          if (nEUI)
4073             SendMessageW(hCombo, CB_SHOWDROPDOWN, bDropped ? FALSE : TRUE, 0);
4074          else
4075             SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)VK_F4, 0);
4076          break;
4077    }
4078
4079    if(nEUI == 2)
4080       SendMessageW(hCombo, CB_SETEXTENDEDUI, TRUE, 0);
4081
4082    return TRUE;
4083 }
4084
4085
4086 /*********************************************************************
4087  *
4088  *      WM_KEYDOWN
4089  *
4090  *      Handling of special keys that don't produce a WM_CHAR
4091  *      (i.e. non-printable keys) & Backspace & Delete
4092  *
4093  */
4094 static LRESULT EDIT_WM_KeyDown(EDITSTATE *es, INT key)
4095 {
4096         BOOL shift;
4097         BOOL control;
4098
4099         if (GetKeyState(VK_MENU) & 0x8000)
4100                 return 0;
4101
4102         shift = GetKeyState(VK_SHIFT) & 0x8000;
4103         control = GetKeyState(VK_CONTROL) & 0x8000;
4104
4105         switch (key) {
4106         case VK_F4:
4107         case VK_UP:
4108                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key) || key == VK_F4)
4109                         break;
4110
4111                 /* fall through */
4112         case VK_LEFT:
4113                 if ((es->style & ES_MULTILINE) && (key == VK_UP))
4114                         EDIT_MoveUp_ML(es, shift);
4115                 else
4116                         if (control)
4117                                 EDIT_MoveWordBackward(es, shift);
4118                         else
4119                                 EDIT_MoveBackward(es, shift);
4120                 break;
4121         case VK_DOWN:
4122                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key))
4123                         break;
4124                 /* fall through */
4125         case VK_RIGHT:
4126                 if ((es->style & ES_MULTILINE) && (key == VK_DOWN))
4127                         EDIT_MoveDown_ML(es, shift);
4128                 else if (control)
4129                         EDIT_MoveWordForward(es, shift);
4130                 else
4131                         EDIT_MoveForward(es, shift);
4132                 break;
4133         case VK_HOME:
4134                 EDIT_MoveHome(es, shift);
4135                 break;
4136         case VK_END:
4137                 EDIT_MoveEnd(es, shift);
4138                 break;
4139         case VK_PRIOR:
4140                 if (es->style & ES_MULTILINE)
4141                         EDIT_MovePageUp_ML(es, shift);
4142                 else
4143                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4144                 break;
4145         case VK_NEXT:
4146                 if (es->style & ES_MULTILINE)
4147                         EDIT_MovePageDown_ML(es, shift);
4148                 else
4149                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4150                 break;
4151         case VK_DELETE:
4152                 if (!(es->style & ES_READONLY) && !(shift && control)) {
4153                         if (es->selection_start != es->selection_end) {
4154                                 if (shift)
4155                                         EDIT_WM_Cut(es);
4156                                 else
4157                                         EDIT_WM_Clear(es);
4158                         } else {
4159                                 if (shift) {
4160                                         /* delete character left of caret */
4161                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4162                                         EDIT_MoveBackward(es, TRUE);
4163                                         EDIT_WM_Clear(es);
4164                                 } else if (control) {
4165                                         /* delete to end of line */
4166                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4167                                         EDIT_MoveEnd(es, TRUE);
4168                                         EDIT_WM_Clear(es);
4169                                 } else {
4170                                         /* delete character right of caret */
4171                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4172                                         EDIT_MoveForward(es, TRUE);
4173                                         EDIT_WM_Clear(es);
4174                                 }
4175                         }
4176                 }
4177                 break;
4178         case VK_INSERT:
4179                 if (shift) {
4180                         if (!(es->style & ES_READONLY))
4181                                 EDIT_WM_Paste(es);
4182                 } else if (control)
4183                         EDIT_WM_Copy(es);
4184                 break;
4185         case VK_RETURN:
4186             /* If the edit doesn't want the return send a message to the default object */
4187             if(!(es->style & ES_WANTRETURN))
4188             {
4189                 HWND hwndParent = GetParent(es->hwndSelf);
4190                 DWORD dw = SendMessageW( hwndParent, DM_GETDEFID, 0, 0 );
4191                 if (HIWORD(dw) == DC_HASDEFID)
4192                 {
4193                     SendMessageW( hwndParent, WM_COMMAND,
4194                                   MAKEWPARAM( LOWORD(dw), BN_CLICKED ),
4195                               (LPARAM)GetDlgItem( hwndParent, LOWORD(dw) ) );
4196                 }
4197             }
4198             break;
4199         }
4200         return 0;
4201 }
4202
4203
4204 /*********************************************************************
4205  *
4206  *      WM_KILLFOCUS
4207  *
4208  */
4209 static LRESULT EDIT_WM_KillFocus(EDITSTATE *es)
4210 {
4211         es->flags &= ~EF_FOCUSED;
4212         DestroyCaret();
4213         if(!(es->style & ES_NOHIDESEL))
4214                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
4215         EDIT_NOTIFY_PARENT(es, EN_KILLFOCUS, "EN_KILLFOCUS");
4216         return 0;
4217 }
4218
4219
4220 /*********************************************************************
4221  *
4222  *      WM_LBUTTONDBLCLK
4223  *
4224  *      The caret position has been set on the WM_LBUTTONDOWN message
4225  *
4226  */
4227 static LRESULT EDIT_WM_LButtonDblClk(EDITSTATE *es)
4228 {
4229         INT s;
4230         INT e = es->selection_end;
4231         INT l;
4232         INT li;
4233         INT ll;
4234
4235         if (!(es->flags & EF_FOCUSED))
4236                 return 0;
4237
4238         l = EDIT_EM_LineFromChar(es, e);
4239         li = EDIT_EM_LineIndex(es, l);
4240         ll = EDIT_EM_LineLength(es, e);
4241         s = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_LEFT);
4242         e = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_RIGHT);
4243         EDIT_EM_SetSel(es, s, e, FALSE);
4244         EDIT_EM_ScrollCaret(es);
4245         return 0;
4246 }
4247
4248
4249 /*********************************************************************
4250  *
4251  *      WM_LBUTTONDOWN
4252  *
4253  */
4254 static LRESULT EDIT_WM_LButtonDown(EDITSTATE *es, DWORD keys, INT x, INT y)
4255 {
4256         INT e;
4257         BOOL after_wrap;
4258
4259         SetFocus(es->hwndSelf);
4260         if (!(es->flags & EF_FOCUSED))
4261                 return 0;
4262
4263         es->bCaptureState = TRUE;
4264         SetCapture(es->hwndSelf);
4265         EDIT_ConfinePoint(es, &x, &y);
4266         e = EDIT_CharFromPos(es, x, y, &after_wrap);
4267         EDIT_EM_SetSel(es, (keys & MK_SHIFT) ? es->selection_start : e, e, after_wrap);
4268         EDIT_EM_ScrollCaret(es);
4269         es->region_posx = es->region_posy = 0;
4270         SetTimer(es->hwndSelf, 0, 100, NULL);
4271         return 0;
4272 }
4273
4274
4275 /*********************************************************************
4276  *
4277  *      WM_LBUTTONUP
4278  *
4279  */
4280 static LRESULT EDIT_WM_LButtonUp(EDITSTATE *es)
4281 {
4282         if (es->bCaptureState) {
4283                 KillTimer(es->hwndSelf, 0);
4284                 if (GetCapture() == es->hwndSelf) ReleaseCapture();
4285         }
4286         es->bCaptureState = FALSE;
4287         return 0;
4288 }
4289
4290
4291 /*********************************************************************
4292  *
4293  *      WM_MBUTTONDOWN
4294  *
4295  */
4296 static LRESULT EDIT_WM_MButtonDown(EDITSTATE *es)
4297 {
4298     SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
4299     return 0;
4300 }
4301
4302
4303 /*********************************************************************
4304  *
4305  *      WM_MOUSEMOVE
4306  *
4307  */
4308 static LRESULT EDIT_WM_MouseMove(EDITSTATE *es, INT x, INT y)
4309 {
4310         INT e;
4311         BOOL after_wrap;
4312         INT prex, prey;
4313
4314         if (GetCapture() != es->hwndSelf)
4315                 return 0;
4316
4317         /*
4318          *      FIXME: gotta do some scrolling if outside client
4319          *              area.  Maybe reset the timer ?
4320          */
4321         prex = x; prey = y;
4322         EDIT_ConfinePoint(es, &x, &y);
4323         es->region_posx = (prex < x) ? -1 : ((prex > x) ? 1 : 0);
4324         es->region_posy = (prey < y) ? -1 : ((prey > y) ? 1 : 0);
4325         e = EDIT_CharFromPos(es, x, y, &after_wrap);
4326         EDIT_EM_SetSel(es, es->selection_start, e, after_wrap);
4327         EDIT_SetCaretPos(es,es->selection_end,es->flags & EF_AFTER_WRAP);
4328         return 0;
4329 }
4330
4331
4332 /*********************************************************************
4333  *
4334  *      WM_NCCREATE
4335  *
4336  * See also EDIT_WM_StyleChanged
4337  */
4338 static LRESULT EDIT_WM_NCCreate(HWND hwnd, LPCREATESTRUCTW lpcs, BOOL unicode)
4339 {
4340         EDITSTATE *es;
4341         UINT alloc_size;
4342
4343         TRACE("Creating %s edit control, style = %08lx\n",
4344                 unicode ? "Unicode" : "ANSI", lpcs->style);
4345
4346         if (!(es = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*es))))
4347                 return FALSE;
4348         SetWindowLongW( hwnd, 0, (LONG)es );
4349
4350        /*
4351         *      Note: since the EDITSTATE has not been fully initialized yet,
4352         *            we can't use any API calls that may send
4353         *            WM_XXX messages before WM_NCCREATE is completed.
4354         */
4355
4356         es->is_unicode = unicode;
4357         es->style = lpcs->style;
4358
4359         es->bEnableState = !(es->style & WS_DISABLED);
4360
4361         es->hwndSelf = hwnd;
4362         /* Save parent, which will be notified by EN_* messages */
4363         es->hwndParent = lpcs->hwndParent;
4364
4365         if (es->style & ES_COMBO)
4366            es->hwndListBox = GetDlgItem(es->hwndParent, ID_CB_LISTBOX);
4367
4368         /* Number overrides lowercase overrides uppercase (at least it
4369          * does in Win95).  However I'll bet that ES_NUMBER would be
4370          * invalid under Win 3.1.
4371          */
4372         if (es->style & ES_NUMBER) {
4373                 ; /* do not override the ES_NUMBER */
4374         }  else if (es->style & ES_LOWERCASE) {
4375                 es->style &= ~ES_UPPERCASE;
4376         }
4377         if (es->style & ES_MULTILINE) {
4378                 es->buffer_limit = BUFLIMIT_MULTI;
4379                 if (es->style & WS_VSCROLL)
4380                         es->style |= ES_AUTOVSCROLL;
4381                 if (es->style & WS_HSCROLL)
4382                         es->style |= ES_AUTOHSCROLL;
4383                 es->style &= ~ES_PASSWORD;
4384                 if ((es->style & ES_CENTER) || (es->style & ES_RIGHT)) {
4385                         /* Confirmed - RIGHT overrides CENTER */
4386                         if (es->style & ES_RIGHT)
4387                                 es->style &= ~ES_CENTER;
4388                         es->style &= ~WS_HSCROLL;
4389                         es->style &= ~ES_AUTOHSCROLL;
4390                 }
4391
4392                 /* FIXME: for now, all multi line controls are AUTOVSCROLL */
4393                 es->style |= ES_AUTOVSCROLL;
4394         } else {
4395                 es->buffer_limit = BUFLIMIT_SINGLE;
4396                 es->style &= ~ES_CENTER;
4397                 es->style &= ~ES_RIGHT;
4398                 es->style &= ~WS_HSCROLL;
4399                 es->style &= ~WS_VSCROLL;
4400                 es->style &= ~ES_AUTOVSCROLL;
4401                 es->style &= ~ES_WANTRETURN;
4402                 if (es->style & ES_PASSWORD)
4403                         es->password_char = '*';
4404
4405                 /* FIXME: for now, all single line controls are AUTOHSCROLL */
4406                 es->style |= ES_AUTOHSCROLL;
4407         }
4408
4409         alloc_size = ROUND_TO_GROW((es->buffer_size + 1) * sizeof(WCHAR));
4410         if(!(es->hloc32W = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
4411             return FALSE;
4412         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
4413
4414         if (!(es->undo_text = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (es->buffer_size + 1) * sizeof(WCHAR))))
4415                 return FALSE;
4416         es->undo_buffer_size = es->buffer_size;
4417
4418         if (es->style & ES_MULTILINE)
4419                 if (!(es->first_line_def = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(LINEDEF))))
4420                         return FALSE;
4421         es->line_count = 1;
4422
4423         /*
4424          * In Win95 look and feel, the WS_BORDER style is replaced by the
4425          * WS_EX_CLIENTEDGE style for the edit control. This gives the edit
4426          * control a non client area.  Not always.  This coordinates in some
4427          * way with the window creation code in dialog.c  When making
4428          * modifications please ensure that the code still works for edit
4429          * controls created directly with style 0x50800000, exStyle 0 (
4430          * which should have a single pixel border)
4431          */
4432         es->style      &= ~WS_BORDER;
4433
4434         return TRUE;
4435 }
4436
4437 /*********************************************************************
4438  *
4439  *      WM_PAINT
4440  *
4441  */
4442 static void EDIT_WM_Paint(EDITSTATE *es, WPARAM wParam)
4443 {
4444         PAINTSTRUCT ps;
4445         INT i;
4446         HDC dc;
4447         HFONT old_font = 0;
4448         RECT rc;
4449         RECT rcLine;
4450         RECT rcRgn;
4451         BOOL rev = es->bEnableState &&
4452                                 ((es->flags & EF_FOCUSED) ||
4453                                         (es->style & ES_NOHIDESEL));
4454         if (!wParam)
4455             dc = BeginPaint(es->hwndSelf, &ps);
4456         else
4457             dc = (HDC) wParam;
4458         if(es->style & WS_BORDER) {
4459                 GetClientRect(es->hwndSelf, &rc);
4460                 if(es->style & ES_MULTILINE) {
4461                         if(es->style & WS_HSCROLL) rc.bottom++;
4462                         if(es->style & WS_VSCROLL) rc.right++;
4463                 }
4464                 Rectangle(dc, rc.left, rc.top, rc.right, rc.bottom);
4465         }
4466         IntersectClipRect(dc, es->format_rect.left,
4467                                 es->format_rect.top,
4468                                 es->format_rect.right,
4469                                 es->format_rect.bottom);
4470         if (es->style & ES_MULTILINE) {
4471                 GetClientRect(es->hwndSelf, &rc);
4472                 IntersectClipRect(dc, rc.left, rc.top, rc.right, rc.bottom);
4473         }
4474         if (es->font)
4475                 old_font = SelectObject(dc, es->font);
4476         EDIT_NotifyCtlColor(es, dc);
4477
4478         if (!es->bEnableState)
4479                 SetTextColor(dc, GetSysColor(COLOR_GRAYTEXT));
4480         GetClipBox(dc, &rcRgn);
4481         if (es->style & ES_MULTILINE) {
4482                 INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4483                 for (i = es->y_offset ; i <= min(es->y_offset + vlc, es->y_offset + es->line_count - 1) ; i++) {
4484                         EDIT_GetLineRect(es, i, 0, -1, &rcLine);
4485                         if (IntersectRect(&rc, &rcRgn, &rcLine))
4486                                 EDIT_PaintLine(es, dc, i, rev);
4487                 }
4488         } else {
4489                 EDIT_GetLineRect(es, 0, 0, -1, &rcLine);
4490                 if (IntersectRect(&rc, &rcRgn, &rcLine))
4491                         EDIT_PaintLine(es, dc, 0, rev);
4492         }
4493         if (es->font)
4494                 SelectObject(dc, old_font);
4495
4496         if (!wParam)
4497             EndPaint(es->hwndSelf, &ps);
4498 }
4499
4500
4501 /*********************************************************************
4502  *
4503  *      WM_PASTE
4504  *
4505  */
4506 static void EDIT_WM_Paste(EDITSTATE *es)
4507 {
4508         HGLOBAL hsrc;
4509         LPWSTR src;
4510
4511         /* Protect read-only edit control from modification */
4512         if(es->style & ES_READONLY)
4513             return;
4514
4515         OpenClipboard(es->hwndSelf);
4516         if ((hsrc = GetClipboardData(CF_UNICODETEXT))) {
4517                 src = (LPWSTR)GlobalLock(hsrc);
4518                 EDIT_EM_ReplaceSel(es, TRUE, src, TRUE, TRUE);
4519                 GlobalUnlock(hsrc);
4520         }
4521         CloseClipboard();
4522 }
4523
4524
4525 /*********************************************************************
4526  *
4527  *      WM_SETFOCUS
4528  *
4529  */
4530 static void EDIT_WM_SetFocus(EDITSTATE *es)
4531 {
4532         es->flags |= EF_FOCUSED;
4533         CreateCaret(es->hwndSelf, 0, 2, es->line_height);
4534         EDIT_SetCaretPos(es, es->selection_end,
4535                          es->flags & EF_AFTER_WRAP);
4536         if(!(es->style & ES_NOHIDESEL))
4537                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
4538         ShowCaret(es->hwndSelf);
4539         EDIT_NOTIFY_PARENT(es, EN_SETFOCUS, "EN_SETFOCUS");
4540 }
4541
4542
4543 /*********************************************************************
4544  *
4545  *      WM_SETFONT
4546  *
4547  * With Win95 look the margins are set to default font value unless
4548  * the system font (font == 0) is being set, in which case they are left
4549  * unchanged.
4550  *
4551  */
4552 static void EDIT_WM_SetFont(EDITSTATE *es, HFONT font, BOOL redraw)
4553 {
4554         TEXTMETRICW tm;
4555         HDC dc;
4556         HFONT old_font = 0;
4557         RECT r;
4558
4559         es->font = font;
4560         dc = GetDC(es->hwndSelf);
4561         if (font)
4562                 old_font = SelectObject(dc, font);
4563         GetTextMetricsW(dc, &tm);
4564         es->line_height = tm.tmHeight;
4565         es->char_width = tm.tmAveCharWidth;
4566         if (font)
4567                 SelectObject(dc, old_font);
4568         ReleaseDC(es->hwndSelf, dc);
4569         EDIT_EM_SetMargins(es, EC_LEFTMARGIN | EC_RIGHTMARGIN,
4570                            EC_USEFONTINFO, EC_USEFONTINFO);
4571
4572         /* Force the recalculation of the format rect for each font change */
4573         GetClientRect(es->hwndSelf, &r);
4574         EDIT_SetRectNP(es, &r);
4575
4576         if (es->style & ES_MULTILINE)
4577                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
4578         else
4579             EDIT_CalcLineWidth_SL(es);
4580
4581         if (redraw)
4582                 EDIT_UpdateText(es, NULL, TRUE);
4583         if (es->flags & EF_FOCUSED) {
4584                 DestroyCaret();
4585                 CreateCaret(es->hwndSelf, 0, 2, es->line_height);
4586                 EDIT_SetCaretPos(es, es->selection_end,
4587                                  es->flags & EF_AFTER_WRAP);
4588                 ShowCaret(es->hwndSelf);
4589         }
4590 }
4591
4592
4593 /*********************************************************************
4594  *
4595  *      WM_SETTEXT
4596  *
4597  * NOTES
4598  *  For multiline controls (ES_MULTILINE), reception of WM_SETTEXT triggers:
4599  *  The modified flag is reset. No notifications are sent.
4600  *
4601  *  For single-line controls, reception of WM_SETTEXT triggers:
4602  *  The modified flag is reset. EN_UPDATE and EN_CHANGE notifications are sent.
4603  *
4604  */
4605 static void EDIT_WM_SetText(EDITSTATE *es, LPARAM lParam, BOOL unicode)
4606 {
4607     LPWSTR text = NULL;
4608
4609     if(unicode)
4610         text = (LPWSTR)lParam;
4611     else if (lParam)
4612     {
4613         LPCSTR textA = (LPCSTR)lParam;
4614         INT countW = MultiByteToWideChar(CP_ACP, 0, textA, -1, NULL, 0);
4615         if((text = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
4616             MultiByteToWideChar(CP_ACP, 0, textA, -1, text, countW);
4617     }
4618
4619         EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
4620         if (text) {
4621                 TRACE("%s\n", debugstr_w(text));
4622                 EDIT_EM_ReplaceSel(es, FALSE, text, FALSE, FALSE);
4623                 if(!unicode)
4624                     HeapFree(GetProcessHeap(), 0, text);
4625         } else {
4626                 static const WCHAR empty_stringW[] = {0};
4627                 TRACE("<NULL>\n");
4628                 EDIT_EM_ReplaceSel(es, FALSE, empty_stringW, FALSE, FALSE);
4629         }
4630         es->x_offset = 0;
4631         es->flags &= ~EF_MODIFIED;
4632         EDIT_EM_SetSel(es, 0, 0, FALSE);
4633         /* Send the notification after the selection start and end have been set
4634          * edit control doesn't send notification on WM_SETTEXT
4635          * if it is multiline, or it is part of combobox
4636          */
4637         if( !((es->style & ES_MULTILINE) || es->hwndListBox))
4638        {
4639             EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
4640            EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
4641        }
4642         EDIT_EM_ScrollCaret(es);
4643 }
4644
4645
4646 /*********************************************************************
4647  *
4648  *      WM_SIZE
4649  *
4650  */
4651 static void EDIT_WM_Size(EDITSTATE *es, UINT action, INT width, INT height)
4652 {
4653         if ((action == SIZE_MAXIMIZED) || (action == SIZE_RESTORED)) {
4654                 RECT rc;
4655                 TRACE("width = %d, height = %d\n", width, height);
4656                 SetRect(&rc, 0, 0, width, height);
4657                 EDIT_SetRectNP(es, &rc);
4658                 EDIT_UpdateText(es, NULL, TRUE);
4659         }
4660 }
4661
4662
4663 /*********************************************************************
4664  *
4665  *      WM_STYLECHANGED
4666  *
4667  * This message is sent by SetWindowLong on having changed either the Style
4668  * or the extended style.
4669  *
4670  * We ensure that the window's version of the styles and the EDITSTATE's agree.
4671  *
4672  * See also EDIT_WM_NCCreate
4673  *
4674  * It appears that the Windows version of the edit control allows the style
4675  * (as retrieved by GetWindowLong) to be any value and maintains an internal
4676  * style variable which will generally be different.  In this function we
4677  * update the internal style based on what changed in the externally visible
4678  * style.
4679  *
4680  * Much of this content as based upon the MSDN, especially:
4681  *  Platform SDK Documentation -> User Interface Services ->
4682  *      Windows User Interface -> Edit Controls -> Edit Control Reference ->
4683  *      Edit Control Styles
4684  */
4685 static LRESULT  EDIT_WM_StyleChanged ( EDITSTATE *es, WPARAM which, const STYLESTRUCT *style)
4686 {
4687         if (GWL_STYLE == which) {
4688                 DWORD style_change_mask;
4689                 DWORD new_style;
4690                 /* Only a subset of changes can be applied after the control
4691                  * has been created.
4692                  */
4693                 style_change_mask = ES_UPPERCASE | ES_LOWERCASE |
4694                                     ES_NUMBER;
4695                 if (es->style & ES_MULTILINE)
4696                         style_change_mask |= ES_WANTRETURN;
4697
4698                 new_style = style->styleNew & style_change_mask;
4699
4700                 /* Number overrides lowercase overrides uppercase (at least it
4701                  * does in Win95).  However I'll bet that ES_NUMBER would be
4702                  * invalid under Win 3.1.
4703                  */
4704                 if (new_style & ES_NUMBER) {
4705                         ; /* do not override the ES_NUMBER */
4706                 }  else if (new_style & ES_LOWERCASE) {
4707                         new_style &= ~ES_UPPERCASE;
4708                 }
4709
4710                 es->style = (es->style & ~style_change_mask) | new_style;
4711         } else if (GWL_EXSTYLE == which) {
4712                 ; /* FIXME - what is needed here */
4713         } else {
4714                 WARN ("Invalid style change %d\n",which);
4715         }
4716
4717         return 0;
4718 }
4719
4720 /*********************************************************************
4721  *
4722  *      WM_SYSKEYDOWN
4723  *
4724  */
4725 static LRESULT EDIT_WM_SysKeyDown(EDITSTATE *es, INT key, DWORD key_data)
4726 {
4727         if ((key == VK_BACK) && (key_data & 0x2000)) {
4728                 if (EDIT_EM_CanUndo(es))
4729                         EDIT_EM_Undo(es);
4730                 return 0;
4731         } else if (key == VK_UP || key == VK_DOWN) {
4732                 if (EDIT_CheckCombo(es, WM_SYSKEYDOWN, key))
4733                         return 0;
4734         }
4735         return DefWindowProcW(es->hwndSelf, WM_SYSKEYDOWN, (WPARAM)key, (LPARAM)key_data);
4736 }
4737
4738
4739 /*********************************************************************
4740  *
4741  *      WM_TIMER
4742  *
4743  */
4744 static void EDIT_WM_Timer(EDITSTATE *es)
4745 {
4746         if (es->region_posx < 0) {
4747                 EDIT_MoveBackward(es, TRUE);
4748         } else if (es->region_posx > 0) {
4749                 EDIT_MoveForward(es, TRUE);
4750         }
4751 /*
4752  *      FIXME: gotta do some vertical scrolling here, like
4753  *              EDIT_EM_LineScroll(hwnd, 0, 1);
4754  */
4755 }
4756
4757 /*********************************************************************
4758  *
4759  *      WM_VSCROLL
4760  *
4761  */
4762 static LRESULT EDIT_WM_VScroll(EDITSTATE *es, INT action, INT pos)
4763 {
4764         INT dy;
4765
4766         if (!(es->style & ES_MULTILINE))
4767                 return 0;
4768
4769         if (!(es->style & ES_AUTOVSCROLL))
4770                 return 0;
4771
4772         dy = 0;
4773         switch (action) {
4774         case SB_LINEUP:
4775         case SB_LINEDOWN:
4776         case SB_PAGEUP:
4777         case SB_PAGEDOWN:
4778                 TRACE("action %d (%s)\n", action, (action == SB_LINEUP ? "SB_LINEUP" :
4779                                                    (action == SB_LINEDOWN ? "SB_LINEDOWN" :
4780                                                     (action == SB_PAGEUP ? "SB_PAGEUP" :
4781                                                      "SB_PAGEDOWN"))));
4782                 EDIT_EM_Scroll(es, action);
4783                 return 0;
4784         case SB_TOP:
4785                 TRACE("SB_TOP\n");
4786                 dy = -es->y_offset;
4787                 break;
4788         case SB_BOTTOM:
4789                 TRACE("SB_BOTTOM\n");
4790                 dy = es->line_count - 1 - es->y_offset;
4791                 break;
4792         case SB_THUMBTRACK:
4793                 TRACE("SB_THUMBTRACK %d\n", pos);
4794                 es->flags |= EF_VSCROLL_TRACK;
4795                 if(es->style & WS_VSCROLL)
4796                     dy = pos - es->y_offset;
4797                 else
4798                 {
4799                     /* Assume default scroll range 0-100 */
4800                     INT vlc, new_y;
4801                     /* Sanity check */
4802                     if(pos < 0 || pos > 100) return 0;
4803                     vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4804                     new_y = pos * (es->line_count - vlc) / 100;
4805                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4806                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4807                             es->line_count, es->y_offset, pos, dy);
4808                 }
4809                 break;
4810         case SB_THUMBPOSITION:
4811                 TRACE("SB_THUMBPOSITION %d\n", pos);
4812                 es->flags &= ~EF_VSCROLL_TRACK;
4813                 if(es->style & WS_VSCROLL)
4814                     dy = pos - es->y_offset;
4815                 else
4816                 {
4817                     /* Assume default scroll range 0-100 */
4818                     INT vlc, new_y;
4819                     /* Sanity check */
4820                     if(pos < 0 || pos > 100) return 0;
4821                     vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4822                     new_y = pos * (es->line_count - vlc) / 100;
4823                     dy = es->line_count ? (new_y - es->y_offset) : 0;
4824                     TRACE("line_count=%d, y_offset=%d, pos=%d, dy = %d\n",
4825                             es->line_count, es->y_offset, pos, dy);
4826                 }
4827                 if (!dy)
4828                 {
4829                         /* force scroll info update */
4830                         EDIT_UpdateScrollInfo(es);
4831                         EDIT_NOTIFY_PARENT(es, EN_VSCROLL, "EN_VSCROLL");
4832                 }
4833                 break;
4834         case SB_ENDSCROLL:
4835                 TRACE("SB_ENDSCROLL\n");
4836                 break;
4837         /*
4838          *      FIXME : the next two are undocumented !
4839          *      Are we doing the right thing ?
4840          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
4841          *      although it's also a regular control message.
4842          */
4843         case EM_GETTHUMB: /* this one is used by NT notepad */
4844         case EM_GETTHUMB16:
4845         {
4846                 LRESULT ret;
4847                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_VSCROLL)
4848                     ret = GetScrollPos(es->hwndSelf, SB_VERT);
4849                 else
4850                 {
4851                     /* Assume default scroll range 0-100 */
4852                     INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
4853                     ret = es->line_count ? es->y_offset * 100 / (es->line_count - vlc) : 0;
4854                 }
4855                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
4856                 return ret;
4857         }
4858         case EM_LINESCROLL16:
4859                 TRACE("EM_LINESCROLL16 %d\n", pos);
4860                 dy = pos;
4861                 break;
4862
4863         default:
4864                 ERR("undocumented WM_VSCROLL action %d (0x%04x), please report\n",
4865                     action, action);
4866                 return 0;
4867         }
4868         if (dy)
4869                 EDIT_EM_LineScroll(es, 0, dy);
4870         return 0;
4871 }
4872
4873 /*********************************************************************
4874  *
4875  *      EDIT_UpdateText
4876  *
4877  */
4878 static void EDIT_UpdateTextRegion(EDITSTATE *es, HRGN hrgn, BOOL bErase)
4879 {
4880     if (es->flags & EF_UPDATE) EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
4881     InvalidateRgn(es->hwndSelf, hrgn, bErase);
4882 }
4883
4884
4885 /*********************************************************************
4886  *
4887  *      EDIT_UpdateText
4888  *
4889  */
4890 static void EDIT_UpdateText(EDITSTATE *es, LPRECT rc, BOOL bErase)
4891 {
4892     if (es->flags & EF_UPDATE) EDIT_NOTIFY_PARENT(es, EN_UPDATE, "EN_UPDATE");
4893     InvalidateRect(es->hwndSelf, rc, bErase);
4894 }