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