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