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