We need to set the new text even if the old text string was NULL.
[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_DBLCLKS | CS_PARENTDC,   /* style */
289     EditWndProcA,         /* procA */
290     EditWndProcW,         /* procW */
291     sizeof(EDITSTATE *),  /* extra */
292     IDC_IBEAM,            /* 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 ((short)LOWORD(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)(SHORT)HIWORD(lParam);
504                 lParam = (LPARAM)(INT)(SHORT)LOWORD(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, (short)LOWORD(lParam), (short)HIWORD(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, (short)LOWORD(lParam), (short)HIWORD(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                 if (strng[0]) MultiByteToWideChar(CP_ACP, 0, strng, 2, &charW, 1);
776                 else MultiByteToWideChar(CP_ACP, 0, &strng[1], 1, &charW, 1);
777                 EDIT_WM_Char(es, charW);
778                 break;
779             }
780             /* fall through */
781         case WM_CHAR:
782         {
783                 WCHAR charW;
784
785                 if(unicode)
786                     charW = wParam;
787                 else
788                 {
789                     CHAR charA = wParam;
790                     MultiByteToWideChar(CP_ACP, 0, &charA, 1, &charW, 1);
791                 }
792
793                 if ((charW == VK_RETURN || charW == VK_ESCAPE) && es->hwndListBox)
794                 {
795                    if (SendMessageW(GetParent(hwnd), CB_GETDROPPEDSTATE, 0, 0))
796                       SendMessageW(GetParent(hwnd), WM_KEYDOWN, charW, 0);
797                    break;
798                 }
799                 EDIT_WM_Char(es, charW);
800                 break;
801         }
802
803         case WM_CLEAR:
804                 EDIT_WM_Clear(es);
805                 break;
806
807         case WM_COMMAND:
808                 EDIT_WM_Command(es, HIWORD(wParam), LOWORD(wParam), (HWND)lParam);
809                 break;
810
811         case WM_CONTEXTMENU:
812                 EDIT_WM_ContextMenu(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
813                 break;
814
815         case WM_COPY:
816                 EDIT_WM_Copy(es);
817                 break;
818
819         case WM_CREATE:
820                 if(unicode)
821                     result = EDIT_WM_Create(es, ((LPCREATESTRUCTW)lParam)->lpszName);
822                 else
823                 {
824                     LPCSTR nameA = ((LPCREATESTRUCTA)lParam)->lpszName;
825                     LPWSTR nameW = NULL;
826                     if(nameA)
827                     {
828                         INT countW = MultiByteToWideChar(CP_ACP, 0, nameA, -1, NULL, 0);
829                         if((nameW = HeapAlloc(GetProcessHeap(), 0, countW * sizeof(WCHAR))))
830                             MultiByteToWideChar(CP_ACP, 0, nameA, -1, nameW, countW);
831                     }
832                     result = EDIT_WM_Create(es, nameW);
833                     if(nameW)
834                         HeapFree(GetProcessHeap(), 0, nameW);
835                 }
836                 break;
837
838         case WM_CUT:
839                 EDIT_WM_Cut(es);
840                 break;
841
842         case WM_ENABLE:
843                 es->bEnableState = (BOOL) wParam;
844                 EDIT_UpdateText(es, NULL, TRUE);
845                 break;
846
847         case WM_ERASEBKGND:
848                 result = EDIT_WM_EraseBkGnd(es, (HDC)wParam);
849                 break;
850
851         case WM_GETFONT:
852                 result = (LRESULT)es->font;
853                 break;
854
855         case WM_GETTEXT:
856                 result = (LRESULT)EDIT_WM_GetText(es, (INT)wParam, lParam, unicode);
857                 break;
858
859         case WM_GETTEXTLENGTH:
860                 if (unicode) result = strlenW(es->text);
861                 else result = WideCharToMultiByte( CP_ACP, 0, es->text, strlenW(es->text),
862                                                    NULL, 0, NULL, NULL );
863                 break;
864
865         case WM_HSCROLL:
866                 result = EDIT_WM_HScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
867                 break;
868
869         case WM_KEYDOWN:
870                 result = EDIT_WM_KeyDown(es, (INT)wParam);
871                 break;
872
873         case WM_KILLFOCUS:
874                 result = EDIT_WM_KillFocus(es);
875                 break;
876
877         case WM_LBUTTONDBLCLK:
878                 result = EDIT_WM_LButtonDblClk(es);
879                 break;
880
881         case WM_LBUTTONDOWN:
882                 result = EDIT_WM_LButtonDown(es, wParam, (short)LOWORD(lParam), (short)HIWORD(lParam));
883                 break;
884
885         case WM_LBUTTONUP:
886                 result = EDIT_WM_LButtonUp(es);
887                 break;
888
889         case WM_MBUTTONDOWN:
890                 result = EDIT_WM_MButtonDown(es);
891                 break;
892
893         case WM_MOUSEACTIVATE:
894                 result = MA_ACTIVATE;
895                 break;
896
897         case WM_MOUSEMOVE:
898                 result = EDIT_WM_MouseMove(es, (short)LOWORD(lParam), (short)HIWORD(lParam));
899                 break;
900
901         case WM_PAINT:
902                 EDIT_WM_Paint(es, wParam);
903                 break;
904
905         case WM_PASTE:
906                 EDIT_WM_Paste(es);
907                 break;
908
909         case WM_SETFOCUS:
910                 EDIT_WM_SetFocus(es);
911                 break;
912
913         case WM_SETFONT:
914                 EDIT_WM_SetFont(es, (HFONT)wParam, LOWORD(lParam) != 0);
915                 break;
916
917         case WM_SETREDRAW:
918                 /* FIXME: actually set an internal flag and behave accordingly */
919                 break;
920
921         case WM_SETTEXT:
922                 EDIT_WM_SetText(es, lParam, unicode);
923                 result = TRUE;
924                 break;
925
926         case WM_SIZE:
927                 EDIT_WM_Size(es, (UINT)wParam, LOWORD(lParam), HIWORD(lParam));
928                 break;
929
930         case WM_STYLECHANGED:
931                 result = EDIT_WM_StyleChanged(es, wParam, (const STYLESTRUCT *)lParam);
932                 break;
933
934         case WM_STYLECHANGING:
935                 result = 0; /* See EDIT_WM_StyleChanged */
936                 break;
937
938         case WM_SYSKEYDOWN:
939                 result = EDIT_WM_SysKeyDown(es, (INT)wParam, (DWORD)lParam);
940                 break;
941
942         case WM_TIMER:
943                 EDIT_WM_Timer(es);
944                 break;
945
946         case WM_VSCROLL:
947                 result = EDIT_WM_VScroll(es, LOWORD(wParam), (short)HIWORD(wParam));
948                 break;
949
950         case WM_MOUSEWHEEL:
951                 {
952                     int gcWheelDelta = 0;
953                     UINT pulScrollLines = 3;
954                     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
955
956                     if (wParam & (MK_SHIFT | MK_CONTROL)) {
957                         result = DefWindowProcW(hwnd, msg, wParam, lParam);
958                         break;
959                     }
960                     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
961                     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
962                     {
963                         int cLineScroll= (int) min((UINT) es->line_count, pulScrollLines);
964                         cLineScroll *= (gcWheelDelta / WHEEL_DELTA);
965                         result = EDIT_EM_LineScroll(es, 0, cLineScroll);
966                     }
967                 }
968                 break;
969         default:
970                 result = DefWindowProcT(hwnd, msg, wParam, lParam, unicode);
971                 break;
972         }
973         
974         if (es) EDIT_UnlockBuffer(es, FALSE);
975         
976         return result;
977 }
978
979 /*********************************************************************
980  *
981  *      EditWndProcW   (USER32.@)
982  */
983 LRESULT WINAPI EditWndProcW(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
984 {
985     return EditWndProc_common(hWnd, uMsg, wParam, lParam, TRUE);
986 }
987
988 /*********************************************************************
989  *
990  *      EditWndProc   (USER32.@)
991  */
992 LRESULT WINAPI EditWndProcA(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
993 {
994     return EditWndProc_common(hWnd, uMsg, wParam, lParam, FALSE);
995 }
996
997 /*********************************************************************
998  *
999  *      EDIT_BuildLineDefs_ML
1000  *
1001  *      Build linked list of text lines.
1002  *      Lines can end with '\0' (last line), a character (if it is wrapped),
1003  *      a soft return '\r\r\n' or a hard return '\r\n'
1004  *
1005  */
1006 static void EDIT_BuildLineDefs_ML(EDITSTATE *es, INT istart, INT iend, INT delta, HRGN hrgn)
1007 {
1008         HDC dc;
1009         HFONT old_font = 0;
1010         LPWSTR current_position, cp;
1011         INT fw;
1012         LINEDEF *current_line;
1013         LINEDEF *previous_line;
1014         LINEDEF *start_line;
1015         INT line_index = 0, nstart_line = 0, nstart_index = 0;
1016         INT line_count = es->line_count;
1017         INT orig_net_length;
1018         RECT rc;
1019
1020         if (istart == iend && delta == 0)
1021                 return;
1022
1023         dc = GetDC(es->hwndSelf);
1024         if (es->font)
1025                 old_font = SelectObject(dc, es->font);
1026
1027         previous_line = NULL;
1028         current_line = es->first_line_def;
1029
1030         /* Find starting line. istart must lie inside an existing line or
1031          * at the end of buffer */
1032         do {
1033                 if (istart < current_line->index + current_line->length ||
1034                                 current_line->ending == END_0)
1035                         break;
1036
1037                 previous_line = current_line;
1038                 current_line = current_line->next;
1039                 line_index++;
1040         } while (current_line);
1041
1042         if (!current_line) /* Error occurred start is not inside previous buffer */
1043         {
1044                 FIXME(" modification occurred outside buffer\n");
1045                 ReleaseDC(es->hwndSelf, dc);
1046                 return;
1047         }
1048
1049         /* Remember start of modifications in order to calculate update region */
1050         nstart_line = line_index;
1051         nstart_index = current_line->index;
1052
1053         /* We must start to reformat from the previous line since the modifications
1054          * may have caused the line to wrap upwards. */
1055         if (!(es->style & ES_AUTOHSCROLL) && line_index > 0)
1056         {
1057                 line_index--;
1058                 current_line = previous_line;
1059         }
1060         start_line = current_line;
1061
1062         fw = es->format_rect.right - es->format_rect.left;
1063         current_position = es->text + current_line->index;
1064         do {
1065                 if (current_line != start_line)
1066                 {
1067                         if (!current_line || current_line->index + delta > current_position - es->text)
1068                         {
1069                                 /* The buffer has been expanded, create a new line and
1070                                    insert it into the link list */
1071                                 LINEDEF *new_line = HeapAlloc(GetProcessHeap(), 0, sizeof(LINEDEF));
1072                                 new_line->next = previous_line->next;
1073                                 previous_line->next = new_line;
1074                                 current_line = new_line;
1075                                 es->line_count++;
1076                         }
1077                         else if (current_line->index + delta < current_position - es->text)
1078                         {
1079                                 /* The previous line merged with this line so we delete this extra entry */
1080                                 previous_line->next = current_line->next;
1081                                 HeapFree(GetProcessHeap(), 0, current_line);
1082                                 current_line = previous_line->next;
1083                                 es->line_count--;
1084                                 continue;
1085                         }
1086                         else /* current_line->index + delta == current_position */
1087                         {
1088                                 if (current_position - es->text > iend)
1089                                         break; /* We reached end of line modifications */
1090                                 /* else recalulate this line */
1091                         }
1092                 }
1093
1094                 current_line->index = current_position - es->text;
1095                 orig_net_length = current_line->net_length;
1096
1097                 /* Find end of line */
1098                 cp = current_position;
1099                 while (*cp) {
1100                     if (*cp == '\n') break;
1101                         if ((*cp == '\r') && (*(cp + 1) == '\n'))
1102                                 break;
1103                         cp++;
1104                 }
1105
1106                 /* Mark type of line termination */
1107                 if (!(*cp)) {
1108                         current_line->ending = END_0;
1109                         current_line->net_length = strlenW(current_position);
1110                 } else if ((cp > current_position) && (*(cp - 1) == '\r')) {
1111                         current_line->ending = END_SOFT;
1112                         current_line->net_length = cp - current_position - 1;
1113                 } else if (*cp == '\n') {
1114                         current_line->ending = END_RICH;
1115                         current_line->net_length = cp - current_position;
1116                 } else {
1117                         current_line->ending = END_HARD;
1118                         current_line->net_length = cp - current_position;
1119                 }
1120
1121                 /* Calculate line width */
1122                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1123                                         current_position, current_line->net_length,
1124                                         es->tabs_count, es->tabs));
1125
1126                 /* FIXME: check here for lines that are too wide even in AUTOHSCROLL (> 32767 ???) */
1127                 if ((!(es->style & ES_AUTOHSCROLL)) && (current_line->width > fw)) {
1128                         INT next = 0;
1129                         INT prev;
1130                         do {
1131                                 prev = next;
1132                                 next = EDIT_CallWordBreakProc(es, current_position - es->text,
1133                                                 prev + 1, current_line->net_length, WB_RIGHT);
1134                                 current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1135                                                         current_position, next, es->tabs_count, es->tabs));
1136                         } while (current_line->width <= fw);
1137                         if (!prev) { /* Didn't find a line break so force a break */
1138                                 next = 0;
1139                                 do {
1140                                         prev = next;
1141                                         next++;
1142                                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc,
1143                                                                 current_position, next, es->tabs_count, es->tabs));
1144                                 } while (current_line->width <= fw);
1145                                 if (!prev)
1146                                         prev = 1;
1147                         }
1148
1149                         /* If the first line we are calculating, wrapped before istart, we must
1150                          * adjust istart in order for this to be reflected in the update region. */
1151                         if (current_line->index == nstart_index && istart > current_line->index + prev)
1152                                 istart = current_line->index + prev;
1153                         /* else if we are updating the previous line before the first line we
1154                          * are re-calculating and it expanded */
1155                         else if (current_line == start_line &&
1156                                         current_line->index != nstart_index && orig_net_length < prev)
1157                         {
1158                           /* Line expanded due to an upwards line wrap so we must partially include
1159                            * previous line in update region */
1160                                 nstart_line = line_index;
1161                                 nstart_index = current_line->index;
1162                                 istart = current_line->index + orig_net_length;
1163                         }
1164
1165                         current_line->net_length = prev;
1166                         current_line->ending = END_WRAP;
1167                         current_line->width = (INT)LOWORD(GetTabbedTextExtentW(dc, current_position,
1168                                         current_line->net_length, es->tabs_count, es->tabs));
1169                 }
1170
1171
1172                 /* Adjust length to include line termination */
1173                 switch (current_line->ending) {
1174                 case END_SOFT:
1175                         current_line->length = current_line->net_length + 3;
1176                         break;
1177                 case END_RICH:
1178                         current_line->length = current_line->net_length + 1;
1179                         break;
1180                 case END_HARD:
1181                         current_line->length = current_line->net_length + 2;
1182                         break;
1183                 case END_WRAP:
1184                 case END_0:
1185                         current_line->length = current_line->net_length;
1186                         break;
1187                 }
1188                 es->text_width = max(es->text_width, current_line->width);
1189                 current_position += current_line->length;
1190                 previous_line = current_line;
1191                 current_line = current_line->next;
1192                 line_index++;
1193         } while (previous_line->ending != END_0);
1194
1195         /* Finish adjusting line indexes by delta or remove hanging lines */
1196         if (previous_line->ending == END_0)
1197         {
1198                 LINEDEF *pnext = NULL;
1199
1200                 previous_line->next = NULL;
1201                 while (current_line)
1202                 {
1203                         pnext = current_line->next;
1204                         HeapFree(GetProcessHeap(), 0, current_line);
1205                         current_line = pnext;
1206                         es->line_count--;
1207                 }
1208         }
1209         else
1210         {
1211                 while (current_line)
1212                 {
1213                         current_line->index += delta;
1214                         current_line = current_line->next;
1215                 }
1216         }
1217
1218         /* Calculate rest of modification rectangle */
1219         if (hrgn)
1220         {
1221                 HRGN tmphrgn;
1222            /*
1223                 * We calculate two rectangles. One for the first line which may have
1224                 * an indent with respect to the format rect. The other is a format-width
1225                 * rectangle that spans the rest of the lines that changed or moved.
1226                 */
1227                 rc.top = es->format_rect.top + nstart_line * es->line_height -
1228                         (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1229                 rc.bottom = rc.top + es->line_height;
1230                 rc.left = es->format_rect.left + (INT)LOWORD(GetTabbedTextExtentW(dc,
1231                                         es->text + nstart_index, istart - nstart_index,
1232                                         es->tabs_count, es->tabs)) - es->x_offset; /* Adjust for horz scroll */
1233                 rc.right = es->format_rect.right;
1234                 SetRectRgn(hrgn, rc.left, rc.top, rc.right, rc.bottom);
1235
1236                 rc.top = rc.bottom;
1237                 rc.left = es->format_rect.left;
1238                 rc.right = es->format_rect.right;
1239            /*
1240                 * If lines were added or removed we must re-paint the remainder of the
1241             * lines since the remaining lines were either shifted up or down.
1242                 */
1243                 if (line_count < es->line_count) /* We added lines */
1244                         rc.bottom = es->line_count * es->line_height;
1245                 else if (line_count > es->line_count) /* We removed lines */
1246                         rc.bottom = line_count * es->line_height;
1247                 else
1248                         rc.bottom = line_index * es->line_height;
1249                 rc.bottom -= (es->y_offset * es->line_height); /* Adjust for vertical scrollbar */
1250                 tmphrgn = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
1251                 CombineRgn(hrgn, hrgn, tmphrgn, RGN_OR);
1252                 DeleteObject(tmphrgn);
1253         }
1254
1255         if (es->font)
1256                 SelectObject(dc, old_font);
1257
1258         ReleaseDC(es->hwndSelf, dc);
1259 }
1260
1261 /*********************************************************************
1262  *
1263  *      EDIT_CalcLineWidth_SL
1264  *
1265  */
1266 static void EDIT_CalcLineWidth_SL(EDITSTATE *es)
1267 {
1268     es->text_width = (short)LOWORD(EDIT_EM_PosFromChar(es, strlenW(es->text), FALSE));
1269 }
1270
1271 /*********************************************************************
1272  *
1273  *      EDIT_CallWordBreakProc
1274  *
1275  *      Call appropriate WordBreakProc (internal or external).
1276  *
1277  *      Note: The "start" argument should always be an index referring
1278  *              to es->text.  The actual wordbreak proc might be
1279  *              16 bit, so we can't always pass any 32 bit LPSTR.
1280  *              Hence we assume that es->text is the buffer that holds
1281  *              the string under examination (we can decide this for ourselves).
1282  *
1283  */
1284 static INT EDIT_CallWordBreakProc(EDITSTATE *es, INT start, INT index, INT count, INT action)
1285 {
1286     INT ret, iWndsLocks;
1287
1288     /* To avoid any deadlocks, all the locks on the window structures
1289        must be suspended before the control is passed to the application */
1290     iWndsLocks = WIN_SuspendWndsLock();
1291
1292         if (es->word_break_proc16) {
1293             HGLOBAL16 hglob16;
1294             SEGPTR segptr;
1295             INT countA;
1296             WORD args[5];
1297             DWORD result;
1298
1299             countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1300             hglob16 = GlobalAlloc16(GMEM_MOVEABLE | GMEM_ZEROINIT, countA);
1301             segptr = K32WOWGlobalLock16(hglob16);
1302             WideCharToMultiByte(CP_ACP, 0, es->text + start, count, MapSL(segptr), countA, NULL, NULL);
1303             args[4] = SELECTOROF(segptr);
1304             args[3] = OFFSETOF(segptr);
1305             args[2] = index;
1306             args[1] = countA;
1307             args[0] = action;
1308             WOWCallback16Ex((DWORD)es->word_break_proc16, WCB16_PASCAL, sizeof(args), args, &result);
1309             ret = LOWORD(result);
1310             GlobalUnlock16(hglob16);
1311             GlobalFree16(hglob16);
1312         }
1313         else if (es->word_break_proc)
1314         {
1315             if(es->is_unicode)
1316             {
1317                 EDITWORDBREAKPROCW wbpW = (EDITWORDBREAKPROCW)es->word_break_proc;
1318
1319                 TRACE_(relay)("(UNICODE wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1320                         es->word_break_proc, debugstr_wn(es->text + start, count), index, count, action);
1321                 ret = wbpW(es->text + start, index, count, action);
1322             }
1323             else
1324             {
1325                 EDITWORDBREAKPROCA wbpA = (EDITWORDBREAKPROCA)es->word_break_proc;
1326                 INT countA;
1327                 CHAR *textA;
1328
1329                 countA = WideCharToMultiByte(CP_ACP, 0, es->text + start, count, NULL, 0, NULL, NULL);
1330                 textA = HeapAlloc(GetProcessHeap(), 0, countA);
1331                 WideCharToMultiByte(CP_ACP, 0, es->text + start, count, textA, countA, NULL, NULL);
1332                 TRACE_(relay)("(ANSI wordbrk=%p,str=%s,idx=%d,cnt=%d,act=%d)\n",
1333                         es->word_break_proc, debugstr_an(textA, countA), index, countA, action);
1334                 ret = wbpA(textA, index, countA, action);
1335                 HeapFree(GetProcessHeap(), 0, textA);
1336             }
1337         }
1338         else
1339             ret = EDIT_WordBreakProc(es->text + start, index, count, action);
1340
1341     WIN_RestoreWndsLock(iWndsLocks);
1342     return ret;
1343 }
1344
1345
1346 /*********************************************************************
1347  *
1348  *      EDIT_CharFromPos
1349  *
1350  *      Beware: This is not the function called on EM_CHARFROMPOS
1351  *              The position _can_ be outside the formatting / client
1352  *              rectangle
1353  *              The return value is only the character index
1354  *
1355  */
1356 static INT EDIT_CharFromPos(EDITSTATE *es, INT x, INT y, LPBOOL after_wrap)
1357 {
1358         INT index;
1359         HDC dc;
1360         HFONT old_font = 0;
1361
1362         if (es->style & ES_MULTILINE) {
1363                 INT line = (y - es->format_rect.top) / es->line_height + es->y_offset;
1364                 INT line_index = 0;
1365                 LINEDEF *line_def = es->first_line_def;
1366                 INT low, high;
1367                 while ((line > 0) && line_def->next) {
1368                         line_index += line_def->length;
1369                         line_def = line_def->next;
1370                         line--;
1371                 }
1372                 x += es->x_offset - es->format_rect.left;
1373                 if (x >= line_def->width) {
1374                         if (after_wrap)
1375                                 *after_wrap = (line_def->ending == END_WRAP);
1376                         return line_index + line_def->net_length;
1377                 }
1378                 if (x <= 0) {
1379                         if (after_wrap)
1380                                 *after_wrap = FALSE;
1381                         return line_index;
1382                 }
1383                 dc = GetDC(es->hwndSelf);
1384                 if (es->font)
1385                         old_font = SelectObject(dc, es->font);
1386                     low = line_index + 1;
1387                     high = line_index + line_def->net_length + 1;
1388                     while (low < high - 1)
1389                     {
1390                         INT mid = (low + high) / 2;
1391                         if (LOWORD(GetTabbedTextExtentW(dc, es->text + line_index,mid - line_index, es->tabs_count, es->tabs)) > x) high = mid;
1392                         else low = mid;
1393                     }
1394                     index = low;
1395
1396                 if (after_wrap)
1397                         *after_wrap = ((index == line_index + line_def->net_length) &&
1398                                                         (line_def->ending == END_WRAP));
1399         } else {
1400                 LPWSTR text;
1401                 SIZE size;
1402                 if (after_wrap)
1403                         *after_wrap = FALSE;
1404                 x -= es->format_rect.left;
1405                 if (!x)
1406                         return es->x_offset;
1407                 text = EDIT_GetPasswordPointer_SL(es);
1408                 dc = GetDC(es->hwndSelf);
1409                 if (es->font)
1410                         old_font = SelectObject(dc, es->font);
1411                 if (x < 0)
1412                 {
1413                     INT low = 0;
1414                     INT high = es->x_offset;
1415                     while (low < high - 1)
1416                     {
1417                         INT mid = (low + high) / 2;
1418                         GetTextExtentPoint32W( dc, text + mid,
1419                                                es->x_offset - mid, &size );
1420                         if (size.cx > -x) low = mid;
1421                         else high = mid;
1422                     }
1423                     index = low;
1424                 }
1425                 else
1426                 {
1427                     INT low = es->x_offset;
1428                     INT high = strlenW(es->text) + 1;
1429                     while (low < high - 1)
1430                     {
1431                         INT mid = (low + high) / 2;
1432                         GetTextExtentPoint32W( dc, text + es->x_offset,
1433                                                mid - es->x_offset, &size );
1434                         if (size.cx > x) high = mid;
1435                         else low = mid;
1436                     }
1437                     index = low;
1438                 }
1439                 if (es->style & ES_PASSWORD)
1440                         HeapFree(GetProcessHeap(), 0, text);
1441         }
1442         if (es->font)
1443                 SelectObject(dc, old_font);
1444         ReleaseDC(es->hwndSelf, dc);
1445         return index;
1446 }
1447
1448
1449 /*********************************************************************
1450  *
1451  *      EDIT_ConfinePoint
1452  *
1453  *      adjusts the point to be within the formatting rectangle
1454  *      (so CharFromPos returns the nearest _visible_ character)
1455  *
1456  */
1457 static void EDIT_ConfinePoint(EDITSTATE *es, LPINT x, LPINT y)
1458 {
1459         *x = min(max(*x, es->format_rect.left), es->format_rect.right - 1);
1460         *y = min(max(*y, es->format_rect.top), es->format_rect.bottom - 1);
1461 }
1462
1463
1464 /*********************************************************************
1465  *
1466  *      EDIT_GetLineRect
1467  *
1468  *      Calculates the bounding rectangle for a line from a starting
1469  *      column to an ending column.
1470  *
1471  */
1472 static void EDIT_GetLineRect(EDITSTATE *es, INT line, INT scol, INT ecol, LPRECT rc)
1473 {
1474         INT line_index =  EDIT_EM_LineIndex(es, line);
1475
1476         if (es->style & ES_MULTILINE)
1477                 rc->top = es->format_rect.top + (line - es->y_offset) * es->line_height;
1478         else
1479                 rc->top = es->format_rect.top;
1480         rc->bottom = rc->top + es->line_height;
1481         rc->left = (scol == 0) ? es->format_rect.left : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + scol, TRUE));
1482         rc->right = (ecol == -1) ? es->format_rect.right : (short)LOWORD(EDIT_EM_PosFromChar(es, line_index + ecol, TRUE));
1483 }
1484
1485
1486 /*********************************************************************
1487  *
1488  *      EDIT_GetPasswordPointer_SL
1489  *
1490  *      note: caller should free the (optionally) allocated buffer
1491  *
1492  */
1493 static LPWSTR EDIT_GetPasswordPointer_SL(EDITSTATE *es)
1494 {
1495         if (es->style & ES_PASSWORD) {
1496                 INT len = strlenW(es->text);
1497                 LPWSTR text = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR));
1498                 text[len] = '\0';
1499                 while(len) text[--len] = es->password_char;
1500                 return text;
1501         } else
1502                 return es->text;
1503 }
1504
1505
1506 /*********************************************************************
1507  *
1508  *      EDIT_LockBuffer
1509  *
1510  *      This acts as a LOCAL_Lock(), but it locks only once.  This way
1511  *      you can call it whenever you like, without unlocking.
1512  *
1513  *      Initially the edit control allocates a HLOCAL32 buffer 
1514  *      (32 bit linear memory handler).  However, 16 bit application
1515  *      might send a EM_GETHANDLE message and expect a HLOCAL16 (16 bit SEG:OFF
1516  *      handler).  From that moment on we have to keep using this 16 bit memory
1517  *      handler, because it is supposed to be valid at all times after EM_GETHANDLE.
1518  *      What we do is create a HLOCAL16 buffer, copy the text, and do pointer
1519  *      conversion.
1520  *
1521  */
1522 static void EDIT_LockBuffer(EDITSTATE *es)
1523 {
1524         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
1525         if (!es->text) {
1526             CHAR *textA = NULL;
1527             UINT countA = 0;
1528             BOOL _16bit = FALSE;
1529
1530             if(es->hloc32W)
1531             {
1532                 if(es->hloc32A)
1533                 {
1534                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
1535                     textA = LocalLock(es->hloc32A);
1536                     countA = strlen(textA) + 1;
1537                 }
1538                 else if(es->hloc16)
1539                 {
1540                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
1541                     textA = LOCAL_Lock(hInstance, es->hloc16);
1542                     countA = strlen(textA) + 1;
1543                     _16bit = TRUE;
1544                 }
1545             }
1546             else {
1547                 ERR("no buffer ... please report\n");
1548                 return;
1549             }
1550
1551             if(textA)
1552             {
1553                 HLOCAL hloc32W_new;
1554                 UINT countW_new = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
1555                 TRACE("%d bytes translated to %d WCHARs\n", countA, countW_new);
1556                 if(countW_new > es->buffer_size + 1)
1557                 {
1558                     UINT alloc_size = ROUND_TO_GROW(countW_new * sizeof(WCHAR));
1559                     TRACE("Resizing 32-bit UNICODE buffer from %d+1 to %d WCHARs\n", es->buffer_size, countW_new);
1560                     hloc32W_new = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
1561                     if(hloc32W_new)
1562                     {
1563                         es->hloc32W = hloc32W_new;
1564                         es->buffer_size = LocalSize(hloc32W_new)/sizeof(WCHAR) - 1;
1565                         TRACE("Real new size %d+1 WCHARs\n", es->buffer_size);
1566                     }
1567                     else
1568                         WARN("FAILED! Will synchronize partially\n");
1569                 }
1570             }
1571
1572             /*TRACE("Locking 32-bit UNICODE buffer\n");*/
1573             es->text = LocalLock(es->hloc32W);
1574
1575             if(textA)
1576             {
1577                 MultiByteToWideChar(CP_ACP, 0, textA, countA, es->text, es->buffer_size + 1);
1578                 if(_16bit)
1579                     LOCAL_Unlock(hInstance, es->hloc16);
1580                 else
1581                     LocalUnlock(es->hloc32A);
1582             }
1583         }
1584         es->lock_count++;
1585 }
1586
1587
1588 /*********************************************************************
1589  *
1590  *      EDIT_SL_InvalidateText
1591  *
1592  *      Called from EDIT_InvalidateText().
1593  *      Does the job for single-line controls only.
1594  *
1595  */
1596 static void EDIT_SL_InvalidateText(EDITSTATE *es, INT start, INT end)
1597 {
1598         RECT line_rect;
1599         RECT rc;
1600
1601         EDIT_GetLineRect(es, 0, start, end, &line_rect);
1602         if (IntersectRect(&rc, &line_rect, &es->format_rect))
1603                 EDIT_UpdateText(es, &rc, TRUE);
1604 }
1605
1606
1607 /*********************************************************************
1608  *
1609  *      EDIT_ML_InvalidateText
1610  *
1611  *      Called from EDIT_InvalidateText().
1612  *      Does the job for multi-line controls only.
1613  *
1614  */
1615 static void EDIT_ML_InvalidateText(EDITSTATE *es, INT start, INT end)
1616 {
1617         INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
1618         INT sl = EDIT_EM_LineFromChar(es, start);
1619         INT el = EDIT_EM_LineFromChar(es, end);
1620         INT sc;
1621         INT ec;
1622         RECT rc1;
1623         RECT rcWnd;
1624         RECT rcLine;
1625         RECT rcUpdate;
1626         INT l;
1627
1628         if ((el < es->y_offset) || (sl > es->y_offset + vlc))
1629                 return;
1630
1631         sc = start - EDIT_EM_LineIndex(es, sl);
1632         ec = end - EDIT_EM_LineIndex(es, el);
1633         if (sl < es->y_offset) {
1634                 sl = es->y_offset;
1635                 sc = 0;
1636         }
1637         if (el > es->y_offset + vlc) {
1638                 el = es->y_offset + vlc;
1639                 ec = EDIT_EM_LineLength(es, EDIT_EM_LineIndex(es, el));
1640         }
1641         GetClientRect(es->hwndSelf, &rc1);
1642         IntersectRect(&rcWnd, &rc1, &es->format_rect);
1643         if (sl == el) {
1644                 EDIT_GetLineRect(es, sl, sc, ec, &rcLine);
1645                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1646                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1647         } else {
1648                 EDIT_GetLineRect(es, sl, sc,
1649                                 EDIT_EM_LineLength(es,
1650                                         EDIT_EM_LineIndex(es, sl)),
1651                                 &rcLine);
1652                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1653                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1654                 for (l = sl + 1 ; l < el ; l++) {
1655                         EDIT_GetLineRect(es, l, 0,
1656                                 EDIT_EM_LineLength(es,
1657                                         EDIT_EM_LineIndex(es, l)),
1658                                 &rcLine);
1659                         if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1660                                 EDIT_UpdateText(es, &rcUpdate, TRUE);
1661                 }
1662                 EDIT_GetLineRect(es, el, 0, ec, &rcLine);
1663                 if (IntersectRect(&rcUpdate, &rcWnd, &rcLine))
1664                         EDIT_UpdateText(es, &rcUpdate, TRUE);
1665         }
1666 }
1667
1668
1669 /*********************************************************************
1670  *
1671  *      EDIT_InvalidateText
1672  *
1673  *      Invalidate the text from offset start upto, but not including,
1674  *      offset end.  Useful for (re)painting the selection.
1675  *      Regions outside the linewidth are not invalidated.
1676  *      end == -1 means end == TextLength.
1677  *      start and end need not be ordered.
1678  *
1679  */
1680 static void EDIT_InvalidateText(EDITSTATE *es, INT start, INT end)
1681 {
1682         if (end == start)
1683                 return;
1684
1685         if (end == -1)
1686                 end = strlenW(es->text);
1687
1688         if (end < start) {
1689             INT tmp = start;
1690             start = end;
1691             end = tmp;
1692         }
1693
1694         if (es->style & ES_MULTILINE)
1695                 EDIT_ML_InvalidateText(es, start, end);
1696         else
1697                 EDIT_SL_InvalidateText(es, start, end);
1698 }
1699
1700
1701 /*********************************************************************
1702  *
1703  *      EDIT_MakeFit
1704  *
1705  * Try to fit size + 1 characters in the buffer.
1706  * Constrain to limits if honor_limit is TRUE.
1707  */
1708 static BOOL EDIT_MakeFit(EDITSTATE *es, UINT size, BOOL honor_limit)
1709 {
1710         HLOCAL hNew32W;
1711
1712         if ((honor_limit) && (es->buffer_limit > 0) && (size > es->buffer_limit)) {
1713                 EDIT_NOTIFY_PARENT(es, EN_MAXTEXT, "EN_MAXTEXT");
1714                 return FALSE;
1715         }
1716
1717         if (size <= es->buffer_size)
1718                 return TRUE;
1719
1720         TRACE("trying to ReAlloc to %d+1 characters\n", size);
1721
1722         /* Force edit to unlock it's buffer. es->text now NULL */
1723         EDIT_UnlockBuffer(es, TRUE);
1724
1725         if (es->hloc32W) {
1726             UINT alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1727             if ((hNew32W = LocalReAlloc(es->hloc32W, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT))) {
1728                 TRACE("Old 32 bit handle %p, new handle %p\n", es->hloc32W, hNew32W);
1729                 es->hloc32W = hNew32W;
1730                 es->buffer_size = LocalSize(hNew32W)/sizeof(WCHAR) - 1;
1731             }
1732         }
1733
1734         EDIT_LockBuffer(es);
1735
1736         if (es->buffer_size < size) {
1737                 WARN("FAILED !  We now have %d+1\n", es->buffer_size);
1738                 EDIT_NOTIFY_PARENT(es, EN_ERRSPACE, "EN_ERRSPACE");
1739                 return FALSE;
1740         } else {
1741                 TRACE("We now have %d+1\n", es->buffer_size);
1742                 return TRUE;
1743         }
1744 }
1745
1746
1747 /*********************************************************************
1748  *
1749  *      EDIT_MakeUndoFit
1750  *
1751  *      Try to fit size + 1 bytes in the undo buffer.
1752  *
1753  */
1754 static BOOL EDIT_MakeUndoFit(EDITSTATE *es, UINT size)
1755 {
1756         UINT alloc_size;
1757
1758         if (size <= es->undo_buffer_size)
1759                 return TRUE;
1760
1761         TRACE("trying to ReAlloc to %d+1\n", size);
1762
1763         alloc_size = ROUND_TO_GROW((size + 1) * sizeof(WCHAR));
1764         if ((es->undo_text = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, es->undo_text, alloc_size))) {
1765                 es->undo_buffer_size = alloc_size/sizeof(WCHAR) - 1;
1766                 return TRUE;
1767         }
1768         else
1769         {
1770                 WARN("FAILED !  We now have %d+1\n", es->undo_buffer_size);
1771                 return FALSE;
1772         }
1773 }
1774
1775
1776 /*********************************************************************
1777  *
1778  *      EDIT_MoveBackward
1779  *
1780  */
1781 static void EDIT_MoveBackward(EDITSTATE *es, BOOL extend)
1782 {
1783         INT e = es->selection_end;
1784
1785         if (e) {
1786                 e--;
1787                 if ((es->style & ES_MULTILINE) && e &&
1788                                 (es->text[e - 1] == '\r') && (es->text[e] == '\n')) {
1789                         e--;
1790                         if (e && (es->text[e - 1] == '\r'))
1791                                 e--;
1792                 }
1793         }
1794         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1795         EDIT_EM_ScrollCaret(es);
1796 }
1797
1798
1799 /*********************************************************************
1800  *
1801  *      EDIT_MoveDown_ML
1802  *
1803  *      Only for multi line controls
1804  *      Move the caret one line down, on a column with the nearest
1805  *      x coordinate on the screen (might be a different column).
1806  *
1807  */
1808 static void EDIT_MoveDown_ML(EDITSTATE *es, BOOL extend)
1809 {
1810         INT s = es->selection_start;
1811         INT e = es->selection_end;
1812         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1813         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1814         INT x = (short)LOWORD(pos);
1815         INT y = (short)HIWORD(pos);
1816
1817         e = EDIT_CharFromPos(es, x, y + es->line_height, &after_wrap);
1818         if (!extend)
1819                 s = e;
1820         EDIT_EM_SetSel(es, s, e, after_wrap);
1821         EDIT_EM_ScrollCaret(es);
1822 }
1823
1824
1825 /*********************************************************************
1826  *
1827  *      EDIT_MoveEnd
1828  *
1829  */
1830 static void EDIT_MoveEnd(EDITSTATE *es, BOOL extend)
1831 {
1832         BOOL after_wrap = FALSE;
1833         INT e;
1834
1835         /* Pass a high value in x to make sure of receiving the end of the line */
1836         if (es->style & ES_MULTILINE)
1837                 e = EDIT_CharFromPos(es, 0x3fffffff,
1838                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), &after_wrap);
1839         else
1840                 e = strlenW(es->text);
1841         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, after_wrap);
1842         EDIT_EM_ScrollCaret(es);
1843 }
1844
1845
1846 /*********************************************************************
1847  *
1848  *      EDIT_MoveForward
1849  *
1850  */
1851 static void EDIT_MoveForward(EDITSTATE *es, BOOL extend)
1852 {
1853         INT e = es->selection_end;
1854
1855         if (es->text[e]) {
1856                 e++;
1857                 if ((es->style & ES_MULTILINE) && (es->text[e - 1] == '\r')) {
1858                         if (es->text[e] == '\n')
1859                                 e++;
1860                         else if ((es->text[e] == '\r') && (es->text[e + 1] == '\n'))
1861                                 e += 2;
1862                 }
1863         }
1864         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1865         EDIT_EM_ScrollCaret(es);
1866 }
1867
1868
1869 /*********************************************************************
1870  *
1871  *      EDIT_MoveHome
1872  *
1873  *      Home key: move to beginning of line.
1874  *
1875  */
1876 static void EDIT_MoveHome(EDITSTATE *es, BOOL extend)
1877 {
1878         INT e;
1879
1880         /* Pass the x_offset in x to make sure of receiving the first position of the line */
1881         if (es->style & ES_MULTILINE)
1882                 e = EDIT_CharFromPos(es, -es->x_offset,
1883                         HIWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP)), NULL);
1884         else
1885                 e = 0;
1886         EDIT_EM_SetSel(es, extend ? es->selection_start : e, e, FALSE);
1887         EDIT_EM_ScrollCaret(es);
1888 }
1889
1890
1891 /*********************************************************************
1892  *
1893  *      EDIT_MovePageDown_ML
1894  *
1895  *      Only for multi line controls
1896  *      Move the caret one page down, on a column with the nearest
1897  *      x coordinate on the screen (might be a different column).
1898  *
1899  */
1900 static void EDIT_MovePageDown_ML(EDITSTATE *es, BOOL extend)
1901 {
1902         INT s = es->selection_start;
1903         INT e = es->selection_end;
1904         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1905         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1906         INT x = (short)LOWORD(pos);
1907         INT y = (short)HIWORD(pos);
1908
1909         e = EDIT_CharFromPos(es, x,
1910                 y + (es->format_rect.bottom - es->format_rect.top),
1911                 &after_wrap);
1912         if (!extend)
1913                 s = e;
1914         EDIT_EM_SetSel(es, s, e, after_wrap);
1915         EDIT_EM_ScrollCaret(es);
1916 }
1917
1918
1919 /*********************************************************************
1920  *
1921  *      EDIT_MovePageUp_ML
1922  *
1923  *      Only for multi line controls
1924  *      Move the caret one page up, on a column with the nearest
1925  *      x coordinate on the screen (might be a different column).
1926  *
1927  */
1928 static void EDIT_MovePageUp_ML(EDITSTATE *es, BOOL extend)
1929 {
1930         INT s = es->selection_start;
1931         INT e = es->selection_end;
1932         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1933         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1934         INT x = (short)LOWORD(pos);
1935         INT y = (short)HIWORD(pos);
1936
1937         e = EDIT_CharFromPos(es, x,
1938                 y - (es->format_rect.bottom - es->format_rect.top),
1939                 &after_wrap);
1940         if (!extend)
1941                 s = e;
1942         EDIT_EM_SetSel(es, s, e, after_wrap);
1943         EDIT_EM_ScrollCaret(es);
1944 }
1945
1946
1947 /*********************************************************************
1948  *
1949  *      EDIT_MoveUp_ML
1950  *
1951  *      Only for multi line controls
1952  *      Move the caret one line up, on a column with the nearest
1953  *      x coordinate on the screen (might be a different column).
1954  *
1955  */
1956 static void EDIT_MoveUp_ML(EDITSTATE *es, BOOL extend)
1957 {
1958         INT s = es->selection_start;
1959         INT e = es->selection_end;
1960         BOOL after_wrap = (es->flags & EF_AFTER_WRAP);
1961         LRESULT pos = EDIT_EM_PosFromChar(es, e, after_wrap);
1962         INT x = (short)LOWORD(pos);
1963         INT y = (short)HIWORD(pos);
1964
1965         e = EDIT_CharFromPos(es, x, y - es->line_height, &after_wrap);
1966         if (!extend)
1967                 s = e;
1968         EDIT_EM_SetSel(es, s, e, after_wrap);
1969         EDIT_EM_ScrollCaret(es);
1970 }
1971
1972
1973 /*********************************************************************
1974  *
1975  *      EDIT_MoveWordBackward
1976  *
1977  */
1978 static void EDIT_MoveWordBackward(EDITSTATE *es, BOOL extend)
1979 {
1980         INT s = es->selection_start;
1981         INT e = es->selection_end;
1982         INT l;
1983         INT ll;
1984         INT li;
1985
1986         l = EDIT_EM_LineFromChar(es, e);
1987         ll = EDIT_EM_LineLength(es, e);
1988         li = EDIT_EM_LineIndex(es, l);
1989         if (e - li == 0) {
1990                 if (l) {
1991                         li = EDIT_EM_LineIndex(es, l - 1);
1992                         e = li + EDIT_EM_LineLength(es, li);
1993                 }
1994         } else {
1995                 e = li + (INT)EDIT_CallWordBreakProc(es,
1996                                 li, e - li, ll, WB_LEFT);
1997         }
1998         if (!extend)
1999                 s = e;
2000         EDIT_EM_SetSel(es, s, e, FALSE);
2001         EDIT_EM_ScrollCaret(es);
2002 }
2003
2004
2005 /*********************************************************************
2006  *
2007  *      EDIT_MoveWordForward
2008  *
2009  */
2010 static void EDIT_MoveWordForward(EDITSTATE *es, BOOL extend)
2011 {
2012         INT s = es->selection_start;
2013         INT e = es->selection_end;
2014         INT l;
2015         INT ll;
2016         INT li;
2017
2018         l = EDIT_EM_LineFromChar(es, e);
2019         ll = EDIT_EM_LineLength(es, e);
2020         li = EDIT_EM_LineIndex(es, l);
2021         if (e - li == ll) {
2022                 if ((es->style & ES_MULTILINE) && (l != es->line_count - 1))
2023                         e = EDIT_EM_LineIndex(es, l + 1);
2024         } else {
2025                 e = li + EDIT_CallWordBreakProc(es,
2026                                 li, e - li + 1, ll, WB_RIGHT);
2027         }
2028         if (!extend)
2029                 s = e;
2030         EDIT_EM_SetSel(es, s, e, FALSE);
2031         EDIT_EM_ScrollCaret(es);
2032 }
2033
2034
2035 /*********************************************************************
2036  *
2037  *      EDIT_PaintLine
2038  *
2039  */
2040 static void EDIT_PaintLine(EDITSTATE *es, HDC dc, INT line, BOOL rev)
2041 {
2042         INT s = es->selection_start;
2043         INT e = es->selection_end;
2044         INT li;
2045         INT ll;
2046         INT x;
2047         INT y;
2048         LRESULT pos;
2049
2050         if (es->style & ES_MULTILINE) {
2051                 INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2052                 if ((line < es->y_offset) || (line > es->y_offset + vlc) || (line >= es->line_count))
2053                         return;
2054         } else if (line)
2055                 return;
2056
2057         TRACE("line=%d\n", line);
2058
2059         pos = EDIT_EM_PosFromChar(es, EDIT_EM_LineIndex(es, line), FALSE);
2060         x = (short)LOWORD(pos);
2061         y = (short)HIWORD(pos);
2062         li = EDIT_EM_LineIndex(es, line);
2063         ll = EDIT_EM_LineLength(es, li);
2064         s = min(es->selection_start, es->selection_end);
2065         e = max(es->selection_start, es->selection_end);
2066         s = min(li + ll, max(li, s));
2067         e = min(li + ll, max(li, e));
2068         if (rev && (s != e) &&
2069                         ((es->flags & EF_FOCUSED) || (es->style & ES_NOHIDESEL))) {
2070                 x += EDIT_PaintText(es, dc, x, y, line, 0, s - li, FALSE);
2071                 x += EDIT_PaintText(es, dc, x, y, line, s - li, e - s, TRUE);
2072                 x += EDIT_PaintText(es, dc, x, y, line, e - li, li + ll - e, FALSE);
2073         } else
2074                 x += EDIT_PaintText(es, dc, x, y, line, 0, ll, FALSE);
2075 }
2076
2077
2078 /*********************************************************************
2079  *
2080  *      EDIT_PaintText
2081  *
2082  */
2083 static INT EDIT_PaintText(EDITSTATE *es, HDC dc, INT x, INT y, INT line, INT col, INT count, BOOL rev)
2084 {
2085         COLORREF BkColor;
2086         COLORREF TextColor;
2087         INT ret;
2088         INT li;
2089         INT BkMode;
2090         SIZE size;
2091
2092         if (!count)
2093                 return 0;
2094         BkMode = GetBkMode(dc);
2095         BkColor = GetBkColor(dc);
2096         TextColor = GetTextColor(dc);
2097         if (rev) {
2098                 SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT));
2099                 SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT));
2100                 SetBkMode( dc, OPAQUE);
2101         }
2102         li = EDIT_EM_LineIndex(es, line);
2103         if (es->style & ES_MULTILINE) {
2104                 ret = (INT)LOWORD(TabbedTextOutW(dc, x, y, es->text + li + col, count,
2105                                         es->tabs_count, es->tabs, es->format_rect.left - es->x_offset));
2106         } else {
2107                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2108                 TextOutW(dc, x, y, text + li + col, count);
2109                 GetTextExtentPoint32W(dc, text + li + col, count, &size);
2110                 ret = size.cx;
2111                 if (es->style & ES_PASSWORD)
2112                         HeapFree(GetProcessHeap(), 0, text);
2113         }
2114         if (rev) {
2115                 SetBkColor(dc, BkColor);
2116                 SetTextColor(dc, TextColor);
2117                 SetBkMode( dc, BkMode);
2118         }
2119         return ret;
2120 }
2121
2122
2123 /*********************************************************************
2124  *
2125  *      EDIT_SetCaretPos
2126  *
2127  */
2128 static void EDIT_SetCaretPos(EDITSTATE *es, INT pos,
2129                              BOOL after_wrap)
2130 {
2131         LRESULT res = EDIT_EM_PosFromChar(es, pos, after_wrap);
2132         SetCaretPos((short)LOWORD(res), (short)HIWORD(res));
2133 }
2134
2135
2136 /*********************************************************************
2137  *
2138  *      EDIT_SetRectNP
2139  *
2140  *      note:   this is not (exactly) the handler called on EM_SETRECTNP
2141  *              it is also used to set the rect of a single line control
2142  *
2143  */
2144 static void EDIT_SetRectNP(EDITSTATE *es, LPRECT rc)
2145 {
2146         CopyRect(&es->format_rect, rc);
2147         if (es->style & WS_BORDER) {
2148                 INT bw = GetSystemMetrics(SM_CXBORDER) + 1;
2149                 if(TWEAK_WineLook == WIN31_LOOK)
2150                         bw += 2;
2151                 es->format_rect.left += bw;
2152                 es->format_rect.top += bw;
2153                 es->format_rect.right -= bw;
2154                 es->format_rect.bottom -= bw;
2155         }
2156         es->format_rect.left += es->left_margin;
2157         es->format_rect.right -= es->right_margin;
2158         es->format_rect.right = max(es->format_rect.right, es->format_rect.left + es->char_width);
2159         if (es->style & ES_MULTILINE)
2160         {
2161             INT fw, vlc, max_x_offset, max_y_offset;
2162
2163             vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2164             es->format_rect.bottom = es->format_rect.top + max(1, vlc) * es->line_height;
2165
2166             /* correct es->x_offset */
2167             fw = es->format_rect.right - es->format_rect.left;
2168             max_x_offset = es->text_width - fw;
2169             if(max_x_offset < 0) max_x_offset = 0;
2170             if(es->x_offset > max_x_offset)
2171                 es->x_offset = max_x_offset;
2172
2173             /* correct es->y_offset */
2174             max_y_offset = es->line_count - vlc;
2175             if(max_y_offset < 0) max_y_offset = 0;
2176             if(es->y_offset > max_y_offset)
2177                 es->y_offset = max_y_offset;
2178
2179             /* force scroll info update */
2180             EDIT_UpdateScrollInfo(es);
2181         }
2182         else
2183         /* Windows doesn't care to fix text placement for SL controls */
2184                 es->format_rect.bottom = es->format_rect.top + es->line_height;
2185
2186         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL))
2187                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
2188 }
2189
2190
2191 /*********************************************************************
2192  *
2193  *      EDIT_UnlockBuffer
2194  *
2195  */
2196 static void EDIT_UnlockBuffer(EDITSTATE *es, BOOL force)
2197 {
2198         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
2199
2200         /* Edit window might be already destroyed */
2201         if(!IsWindow(es->hwndSelf))
2202         {
2203             WARN("edit hwnd %p already destroyed\n", es->hwndSelf);
2204             return;
2205         }
2206
2207         if (!es->lock_count) {
2208                 ERR("lock_count == 0 ... please report\n");
2209                 return;
2210         }
2211         if (!es->text) {
2212                 ERR("es->text == 0 ... please report\n");
2213                 return;
2214         }
2215
2216         if (force || (es->lock_count == 1)) {
2217             if (es->hloc32W) {
2218                 CHAR *textA = NULL;
2219                 BOOL _16bit = FALSE;
2220                 UINT countA = 0;
2221                 UINT countW = strlenW(es->text) + 1;
2222
2223                 if(es->hloc32A)
2224                 {
2225                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2226                     TRACE("Synchronizing with 32-bit ANSI buffer\n");
2227                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2228                     countA = LocalSize(es->hloc32A);
2229                     if(countA_new > countA)
2230                     {
2231                         HLOCAL hloc32A_new;
2232                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2233                         TRACE("Resizing 32-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2234                         hloc32A_new = LocalReAlloc(es->hloc32A, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2235                         if(hloc32A_new)
2236                         {
2237                             es->hloc32A = hloc32A_new;
2238                             countA = LocalSize(hloc32A_new);
2239                             TRACE("Real new size %d bytes\n", countA);
2240                         }
2241                         else
2242                             WARN("FAILED! Will synchronize partially\n");
2243                     }
2244                     textA = LocalLock(es->hloc32A);
2245                 }
2246                 else if(es->hloc16)
2247                 {
2248                     UINT countA_new = WideCharToMultiByte(CP_ACP, 0, es->text, countW, NULL, 0, NULL, NULL);
2249                     TRACE("Synchronizing with 16-bit ANSI buffer\n");
2250                     TRACE("%d WCHARs translated to %d bytes\n", countW, countA_new);
2251                     countA = LOCAL_Size(hInstance, es->hloc16);
2252                     if(countA_new > countA)
2253                     {
2254                         HLOCAL16 hloc16_new;
2255                         UINT alloc_size = ROUND_TO_GROW(countA_new);
2256                         TRACE("Resizing 16-bit ANSI buffer from %d to %d bytes\n", countA, alloc_size);
2257                         hloc16_new = LOCAL_ReAlloc(hInstance, es->hloc16, alloc_size, LMEM_MOVEABLE | LMEM_ZEROINIT);
2258                         if(hloc16_new)
2259                         {
2260                             es->hloc16 = hloc16_new;
2261                             countA = LOCAL_Size(hInstance, hloc16_new);
2262                             TRACE("Real new size %d bytes\n", countA);
2263                         }
2264                         else
2265                             WARN("FAILED! Will synchronize partially\n");
2266                     }
2267                     textA = LOCAL_Lock(hInstance, es->hloc16);
2268                     _16bit = TRUE;
2269                 }
2270
2271                 if(textA)
2272                 {
2273                     WideCharToMultiByte(CP_ACP, 0, es->text, countW, textA, countA, NULL, NULL);
2274                     if(_16bit)
2275                         LOCAL_Unlock(hInstance, es->hloc16);
2276                     else
2277                         LocalUnlock(es->hloc32A);
2278                 }
2279
2280                 LocalUnlock(es->hloc32W);
2281                 es->text = NULL;
2282             }
2283             else {
2284                 ERR("no buffer ... please report\n");
2285                 return;
2286             }
2287         }
2288         es->lock_count--;
2289 }
2290
2291
2292 /*********************************************************************
2293  *
2294  *      EDIT_UpdateScrollInfo
2295  *
2296  */
2297 static void EDIT_UpdateScrollInfo(EDITSTATE *es)
2298 {
2299     if ((es->style & WS_VSCROLL) && !(es->flags & EF_VSCROLL_TRACK))
2300     {
2301         SCROLLINFO si;
2302         si.cbSize       = sizeof(SCROLLINFO);
2303         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2304         si.nMin         = 0;
2305         si.nMax         = es->line_count - 1;
2306         si.nPage        = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
2307         si.nPos         = es->y_offset;
2308         TRACE("SB_VERT, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2309                 si.nMin, si.nMax, si.nPage, si.nPos);
2310         SetScrollInfo(es->hwndSelf, SB_VERT, &si, TRUE);
2311     }
2312
2313     if ((es->style & WS_HSCROLL) && !(es->flags & EF_HSCROLL_TRACK))
2314     {
2315         SCROLLINFO si;
2316         si.cbSize       = sizeof(SCROLLINFO);
2317         si.fMask        = SIF_PAGE | SIF_POS | SIF_RANGE | SIF_DISABLENOSCROLL;
2318         si.nMin         = 0;
2319         si.nMax         = es->text_width - 1;
2320         si.nPage        = es->format_rect.right - es->format_rect.left;
2321         si.nPos         = es->x_offset;
2322         TRACE("SB_HORZ, nMin=%d, nMax=%d, nPage=%d, nPos=%d\n",
2323                 si.nMin, si.nMax, si.nPage, si.nPos);
2324         SetScrollInfo(es->hwndSelf, SB_HORZ, &si, TRUE);
2325     }
2326 }
2327
2328 /*********************************************************************
2329  *
2330  *      EDIT_WordBreakProc
2331  *
2332  *      Find the beginning of words.
2333  *      Note:   unlike the specs for a WordBreakProc, this function only
2334  *              allows to be called without linebreaks between s[0] upto
2335  *              s[count - 1].  Remember it is only called
2336  *              internally, so we can decide this for ourselves.
2337  *
2338  */
2339 static INT CALLBACK EDIT_WordBreakProc(LPWSTR s, INT index, INT count, INT action)
2340 {
2341         INT ret = 0;
2342
2343         TRACE("s=%p, index=%d, count=%d, action=%d\n", s, index, count, action);
2344
2345         if(!s) return 0;
2346
2347         switch (action) {
2348         case WB_LEFT:
2349                 if (!count)
2350                         break;
2351                 if (index)
2352                         index--;
2353                 if (s[index] == ' ') {
2354                         while (index && (s[index] == ' '))
2355                                 index--;
2356                         if (index) {
2357                                 while (index && (s[index] != ' '))
2358                                         index--;
2359                                 if (s[index] == ' ')
2360                                         index++;
2361                         }
2362                 } else {
2363                         while (index && (s[index] != ' '))
2364                                 index--;
2365                         if (s[index] == ' ')
2366                                 index++;
2367                 }
2368                 ret = index;
2369                 break;
2370         case WB_RIGHT:
2371                 if (!count)
2372                         break;
2373                 if (index)
2374                         index--;
2375                 if (s[index] == ' ')
2376                         while ((index < count) && (s[index] == ' ')) index++;
2377                 else {
2378                         while (s[index] && (s[index] != ' ') && (index < count))
2379                                 index++;
2380                         while ((s[index] == ' ') && (index < count)) index++;
2381                 }
2382                 ret = index;
2383                 break;
2384         case WB_ISDELIMITER:
2385                 ret = (s[index] == ' ');
2386                 break;
2387         default:
2388                 ERR("unknown action code, please report !\n");
2389                 break;
2390         }
2391         return ret;
2392 }
2393
2394
2395 /*********************************************************************
2396  *
2397  *      EM_CHARFROMPOS
2398  *
2399  *      returns line number (not index) in high-order word of result.
2400  *      NB : Q137805 is unclear about this. POINT * pointer in lParam apply
2401  *      to Richedit, not to the edit control. Original documentation is valid.
2402  *      FIXME: do the specs mean to return -1 if outside client area or
2403  *              if outside formatting rectangle ???
2404  *
2405  */
2406 static LRESULT EDIT_EM_CharFromPos(EDITSTATE *es, INT x, INT y)
2407 {
2408         POINT pt;
2409         RECT rc;
2410         INT index;
2411
2412         pt.x = x;
2413         pt.y = y;
2414         GetClientRect(es->hwndSelf, &rc);
2415         if (!PtInRect(&rc, pt))
2416                 return -1;
2417
2418         index = EDIT_CharFromPos(es, x, y, NULL);
2419         return MAKELONG(index, EDIT_EM_LineFromChar(es, index));
2420 }
2421
2422
2423 /*********************************************************************
2424  *
2425  *      EM_FMTLINES
2426  *
2427  * Enable or disable soft breaks.
2428  * 
2429  * This means: insert or remove the soft linebreak character (\r\r\n).
2430  * Take care to check if the text still fits the buffer after insertion.
2431  * If not, notify with EN_ERRSPACE.
2432  * 
2433  */
2434 static BOOL EDIT_EM_FmtLines(EDITSTATE *es, BOOL add_eol)
2435 {
2436         es->flags &= ~EF_USE_SOFTBRK;
2437         if (add_eol) {
2438                 es->flags |= EF_USE_SOFTBRK;
2439                 FIXME("soft break enabled, not implemented\n");
2440         }
2441         return add_eol;
2442 }
2443
2444
2445 /*********************************************************************
2446  *
2447  *      EM_GETHANDLE
2448  *
2449  *      Hopefully this won't fire back at us.
2450  *      We always start with a fixed buffer in the local heap.
2451  *      Despite of the documentation says that the local heap is used
2452  *      only if DS_LOCALEDIT flag is set, NT and 2000 always allocate
2453  *      buffer on the local heap.
2454  *
2455  */
2456 static HLOCAL EDIT_EM_GetHandle(EDITSTATE *es)
2457 {
2458         HLOCAL hLocal;
2459
2460         if (!(es->style & ES_MULTILINE))
2461                 return 0;
2462
2463         if(es->is_unicode)
2464             hLocal = es->hloc32W;
2465         else
2466         {
2467             if(!es->hloc32A)
2468             {
2469                 CHAR *textA;
2470                 UINT countA, alloc_size;
2471                 TRACE("Allocating 32-bit ANSI alias buffer\n");
2472                 countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2473                 alloc_size = ROUND_TO_GROW(countA);
2474                 if(!(es->hloc32A = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size)))
2475                 {
2476                     ERR("Could not allocate %d bytes for 32-bit ANSI alias buffer\n", alloc_size);
2477                     return 0;
2478                 }
2479                 textA = LocalLock(es->hloc32A);
2480                 WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2481                 LocalUnlock(es->hloc32A);
2482             }
2483             hLocal = es->hloc32A;
2484         }
2485
2486         TRACE("Returning %p, LocalSize() = %ld\n", hLocal, LocalSize(hLocal));
2487         return hLocal;
2488 }
2489
2490
2491 /*********************************************************************
2492  *
2493  *      EM_GETHANDLE16
2494  *
2495  *      Hopefully this won't fire back at us.
2496  *      We always start with a buffer in 32 bit linear memory.
2497  *      However, with this message a 16 bit application requests
2498  *      a handle of 16 bit local heap memory, where it expects to find
2499  *      the text.
2500  *      It's a pitty that from this moment on we have to use this
2501  *      local heap, because applications may rely on the handle
2502  *      in the future.
2503  *
2504  *      In this function we'll try to switch to local heap.
2505  */
2506 static HLOCAL16 EDIT_EM_GetHandle16(EDITSTATE *es)
2507 {
2508         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
2509         CHAR *textA;
2510         UINT countA, alloc_size;
2511
2512         if (!(es->style & ES_MULTILINE))
2513                 return 0;
2514
2515         if (es->hloc16)
2516                 return es->hloc16;
2517
2518         if (!LOCAL_HeapSize(hInstance)) {
2519                 if (!LocalInit16(hInstance, 0,
2520                                 GlobalSize16(hInstance))) {
2521                         ERR("could not initialize local heap\n");
2522                         return 0;
2523                 }
2524                 TRACE("local heap initialized\n");
2525         }
2526
2527         countA = WideCharToMultiByte(CP_ACP, 0, es->text, -1, NULL, 0, NULL, NULL);
2528         alloc_size = ROUND_TO_GROW(countA);
2529
2530         TRACE("Allocating 16-bit ANSI alias buffer\n");
2531         if (!(es->hloc16 = LOCAL_Alloc(hInstance, LMEM_MOVEABLE | LMEM_ZEROINIT, alloc_size))) {
2532                 ERR("could not allocate new 16 bit buffer\n");
2533                 return 0;
2534         }
2535
2536         if (!(textA = (LPSTR)LOCAL_Lock(hInstance, es->hloc16))) {
2537                 ERR("could not lock new 16 bit buffer\n");
2538                 LOCAL_Free(hInstance, es->hloc16);
2539                 es->hloc16 = 0;
2540                 return 0;
2541         }
2542
2543         WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, countA, NULL, NULL);
2544         LOCAL_Unlock(hInstance, es->hloc16);
2545
2546         TRACE("Returning %04X, LocalSize() = %d\n", es->hloc16, LOCAL_Size(hInstance, es->hloc16));
2547         return es->hloc16;
2548 }
2549
2550
2551 /*********************************************************************
2552  *
2553  *      EM_GETLINE
2554  *
2555  */
2556 static INT EDIT_EM_GetLine(EDITSTATE *es, INT line, LPARAM lParam, BOOL unicode)
2557 {
2558         LPWSTR src;
2559         INT line_len, dst_len;
2560         INT i;
2561
2562         if (es->style & ES_MULTILINE) {
2563                 if (line >= es->line_count)
2564                         return 0;
2565         } else
2566                 line = 0;
2567         i = EDIT_EM_LineIndex(es, line);
2568         src = es->text + i;
2569         line_len = EDIT_EM_LineLength(es, i);
2570         dst_len = *(WORD *)lParam;
2571         if(unicode)
2572         {
2573             LPWSTR dst = (LPWSTR)lParam;
2574             if(dst_len <= line_len)
2575             {
2576                 memcpy(dst, src, dst_len * sizeof(WCHAR));
2577                 return dst_len;
2578             }
2579             else /* Append 0 if enough space */
2580             {
2581                 memcpy(dst, src, line_len * sizeof(WCHAR));
2582                 dst[line_len] = 0;
2583                 return line_len;
2584             }
2585         }
2586         else
2587         {
2588             LPSTR dst = (LPSTR)lParam;
2589             INT ret;
2590             ret = WideCharToMultiByte(CP_ACP, 0, src, line_len, dst, dst_len, NULL, NULL);
2591             if(!ret) /* Insufficient buffer size */
2592                 return dst_len;
2593             if(ret < dst_len) /* Append 0 if enough space */
2594                 dst[ret] = 0;
2595             return ret;
2596         }
2597 }
2598
2599
2600 /*********************************************************************
2601  *
2602  *      EM_GETSEL
2603  *
2604  */
2605 static LRESULT EDIT_EM_GetSel(EDITSTATE *es, PUINT start, PUINT end)
2606 {
2607         UINT s = es->selection_start;
2608         UINT e = es->selection_end;
2609
2610         ORDER_UINT(s, e);
2611         if (start)
2612                 *start = s;
2613         if (end)
2614                 *end = e;
2615         return MAKELONG(s, e);
2616 }
2617
2618
2619 /*********************************************************************
2620  *
2621  *      EM_GETTHUMB
2622  *
2623  *      FIXME: is this right ?  (or should it be only VSCROLL)
2624  *      (and maybe only for edit controls that really have their
2625  *      own scrollbars) (and maybe only for multiline controls ?)
2626  *      All in all: very poorly documented
2627  *
2628  */
2629 static LRESULT EDIT_EM_GetThumb(EDITSTATE *es)
2630 {
2631         return MAKELONG(EDIT_WM_VScroll(es, EM_GETTHUMB16, 0),
2632                 EDIT_WM_HScroll(es, EM_GETTHUMB16, 0));
2633 }
2634
2635
2636 /*********************************************************************
2637  *
2638  *      EM_LINEFROMCHAR
2639  *
2640  */
2641 static INT EDIT_EM_LineFromChar(EDITSTATE *es, INT index)
2642 {
2643         INT line;
2644         LINEDEF *line_def;
2645
2646         if (!(es->style & ES_MULTILINE))
2647                 return 0;
2648         if (index > (INT)strlenW(es->text))
2649                 return es->line_count - 1;
2650         if (index == -1)
2651                 index = min(es->selection_start, es->selection_end);
2652
2653         line = 0;
2654         line_def = es->first_line_def;
2655         index -= line_def->length;
2656         while ((index >= 0) && line_def->next) {
2657                 line++;
2658                 line_def = line_def->next;
2659                 index -= line_def->length;
2660         }
2661         return line;
2662 }
2663
2664
2665 /*********************************************************************
2666  *
2667  *      EM_LINEINDEX
2668  *
2669  */
2670 static INT EDIT_EM_LineIndex(EDITSTATE *es, INT line)
2671 {
2672         INT line_index;
2673         LINEDEF *line_def;
2674
2675         if (!(es->style & ES_MULTILINE))
2676                 return 0;
2677         if (line >= es->line_count)
2678                 return -1;
2679
2680         line_index = 0;
2681         line_def = es->first_line_def;
2682         if (line == -1) {
2683                 INT index = es->selection_end - line_def->length;
2684                 while ((index >= 0) && line_def->next) {
2685                         line_index += line_def->length;
2686                         line_def = line_def->next;
2687                         index -= line_def->length;
2688                 }
2689         } else {
2690                 while (line > 0) {
2691                         line_index += line_def->length;
2692                         line_def = line_def->next;
2693                         line--;
2694                 }
2695         }
2696         return line_index;
2697 }
2698
2699
2700 /*********************************************************************
2701  *
2702  *      EM_LINELENGTH
2703  *
2704  */
2705 static INT EDIT_EM_LineLength(EDITSTATE *es, INT index)
2706 {
2707         LINEDEF *line_def;
2708
2709         if (!(es->style & ES_MULTILINE))
2710                 return strlenW(es->text);
2711
2712         if (index == -1) {
2713                 /* get the number of remaining non-selected chars of selected lines */
2714                 INT32 l; /* line number */
2715                 INT32 li; /* index of first char in line */
2716                 INT32 count;
2717                 l = EDIT_EM_LineFromChar(es, es->selection_start);
2718                 /* # chars before start of selection area */
2719                 count = es->selection_start - EDIT_EM_LineIndex(es, l);
2720                 l = EDIT_EM_LineFromChar(es, es->selection_end);
2721                 /* # chars after end of selection */
2722                 li = EDIT_EM_LineIndex(es, l);
2723                 count += li + EDIT_EM_LineLength(es, li) - es->selection_end;
2724                 return count;
2725         }
2726         line_def = es->first_line_def;
2727         index -= line_def->length;
2728         while ((index >= 0) && line_def->next) {
2729                 line_def = line_def->next;
2730                 index -= line_def->length;
2731         }
2732         return line_def->net_length;
2733 }
2734
2735
2736 /*********************************************************************
2737  *
2738  *      EM_LINESCROLL
2739  *
2740  *      NOTE: dx is in average character widths, dy - in lines;
2741  *
2742  */
2743 static BOOL EDIT_EM_LineScroll(EDITSTATE *es, INT dx, INT dy)
2744 {
2745         if (!(es->style & ES_MULTILINE))
2746                 return FALSE;
2747
2748         dx *= es->char_width;
2749         return EDIT_EM_LineScroll_internal(es, dx, dy);
2750 }
2751
2752 /*********************************************************************
2753  *
2754  *      EDIT_EM_LineScroll_internal
2755  *
2756  *      Version of EDIT_EM_LineScroll for internal use.
2757  *      It doesn't refuse if ES_MULTILINE is set and assumes that
2758  *      dx is in pixels, dy - in lines.
2759  *
2760  */
2761 static BOOL EDIT_EM_LineScroll_internal(EDITSTATE *es, INT dx, INT dy)
2762 {
2763         INT nyoff;
2764         INT x_offset_in_pixels;
2765
2766         if (es->style & ES_MULTILINE)
2767         {
2768             x_offset_in_pixels = es->x_offset;
2769         }
2770         else
2771         {
2772             dy = 0;
2773             x_offset_in_pixels = (short)LOWORD(EDIT_EM_PosFromChar(es, es->x_offset, FALSE));
2774         }
2775
2776         if (-dx > x_offset_in_pixels)
2777                 dx = -x_offset_in_pixels;
2778         if (dx > es->text_width - x_offset_in_pixels)
2779                 dx = es->text_width - x_offset_in_pixels;
2780         nyoff = max(0, es->y_offset + dy);
2781         if (nyoff >= es->line_count)
2782                 nyoff = es->line_count - 1;
2783         dy = (es->y_offset - nyoff) * es->line_height;
2784         if (dx || dy) {
2785                 RECT rc1;
2786                 RECT rc;
2787
2788                 es->y_offset = nyoff;
2789                 if(es->style & ES_MULTILINE)
2790                     es->x_offset += dx;
2791                 else
2792                     es->x_offset += dx / es->char_width;
2793
2794                 GetClientRect(es->hwndSelf, &rc1);
2795                 IntersectRect(&rc, &rc1, &es->format_rect);
2796                 ScrollWindowEx(es->hwndSelf, -dx, dy,
2797                                 NULL, &rc, NULL, NULL, SW_INVALIDATE);
2798                 /* force scroll info update */
2799                 EDIT_UpdateScrollInfo(es);
2800         }
2801         if (dx && !(es->flags & EF_HSCROLL_TRACK))
2802                 EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
2803         if (dy && !(es->flags & EF_VSCROLL_TRACK))
2804                 EDIT_NOTIFY_PARENT(es, EN_VSCROLL, "EN_VSCROLL");
2805         return TRUE;
2806 }
2807
2808
2809 /*********************************************************************
2810  *
2811  *      EM_POSFROMCHAR
2812  *
2813  */
2814 static LRESULT EDIT_EM_PosFromChar(EDITSTATE *es, INT index, BOOL after_wrap)
2815 {
2816         INT len = strlenW(es->text);
2817         INT l;
2818         INT li;
2819         INT x;
2820         INT y = 0;
2821         HDC dc;
2822         HFONT old_font = 0;
2823         SIZE size;
2824
2825         index = min(index, len);
2826         dc = GetDC(es->hwndSelf);
2827         if (es->font)
2828                 old_font = SelectObject(dc, es->font);
2829         if (es->style & ES_MULTILINE) {
2830                 l = EDIT_EM_LineFromChar(es, index);
2831                 y = (l - es->y_offset) * es->line_height;
2832                 li = EDIT_EM_LineIndex(es, l);
2833                 if (after_wrap && (li == index) && l) {
2834                         INT l2 = l - 1;
2835                         LINEDEF *line_def = es->first_line_def;
2836                         while (l2) {
2837                                 line_def = line_def->next;
2838                                 l2--;
2839                         }
2840                         if (line_def->ending == END_WRAP) {
2841                                 l--;
2842                                 y -= es->line_height;
2843                                 li = EDIT_EM_LineIndex(es, l);
2844                         }
2845                 }
2846                 x = LOWORD(GetTabbedTextExtentW(dc, es->text + li, index - li,
2847                                 es->tabs_count, es->tabs)) - es->x_offset;
2848         } else {
2849                 LPWSTR text = EDIT_GetPasswordPointer_SL(es);
2850                 if (index < es->x_offset) {
2851                         GetTextExtentPoint32W(dc, text + index,
2852                                         es->x_offset - index, &size);
2853                         x = -size.cx;
2854                 } else {
2855                         GetTextExtentPoint32W(dc, text + es->x_offset,
2856                                         index - es->x_offset, &size);
2857                          x = size.cx;
2858                 }
2859                 y = 0;
2860                 if (es->style & ES_PASSWORD)
2861                         HeapFree(GetProcessHeap(), 0, text);
2862         }
2863         x += es->format_rect.left;
2864         y += es->format_rect.top;
2865         if (es->font)
2866                 SelectObject(dc, old_font);
2867         ReleaseDC(es->hwndSelf, dc);
2868         return MAKELONG((INT16)x, (INT16)y);
2869 }
2870
2871
2872 /*********************************************************************
2873  *
2874  *      EM_REPLACESEL
2875  *
2876  *      FIXME: handle ES_NUMBER and ES_OEMCONVERT here
2877  *
2878  */
2879 static void EDIT_EM_ReplaceSel(EDITSTATE *es, BOOL can_undo, LPCWSTR lpsz_replace, BOOL send_update, BOOL honor_limit)
2880 {
2881         UINT strl = strlenW(lpsz_replace);
2882         UINT tl = strlenW(es->text);
2883         UINT utl;
2884         UINT s;
2885         UINT e;
2886         UINT i;
2887         LPWSTR p;
2888         HRGN hrgn = 0;
2889
2890         TRACE("%s, can_undo %d, send_update %d\n",
2891             debugstr_w(lpsz_replace), can_undo, send_update);
2892
2893         s = es->selection_start;
2894         e = es->selection_end;
2895
2896         if ((s == e) && !strl)
2897                 return;
2898
2899         ORDER_UINT(s, e);
2900
2901         if (!EDIT_MakeFit(es, tl - (e - s) + strl, honor_limit))
2902                 return;
2903
2904         if (e != s) {
2905                 /* there is something to be deleted */
2906                 TRACE("deleting stuff.\n");
2907                 if (can_undo) {
2908                         utl = strlenW(es->undo_text);
2909                         if (!es->undo_insert_count && (*es->undo_text && (s == es->undo_position))) {
2910                                 /* undo-buffer is extended to the right */
2911                                 EDIT_MakeUndoFit(es, utl + e - s);
2912                                 strncpyW(es->undo_text + utl, es->text + s, e - s + 1);
2913                                 (es->undo_text + utl)[e - s] = 0; /* ensure 0 termination */
2914                         } else if (!es->undo_insert_count && (*es->undo_text && (e == es->undo_position))) {
2915                                 /* undo-buffer is extended to the left */
2916                                 EDIT_MakeUndoFit(es, utl + e - s);
2917                                 for (p = es->undo_text + utl ; p >= es->undo_text ; p--)
2918                                         p[e - s] = p[0];
2919                                 for (i = 0 , p = es->undo_text ; i < e - s ; i++)
2920                                         p[i] = (es->text + s)[i];
2921                                 es->undo_position = s;
2922                         } else {
2923                                 /* new undo-buffer */
2924                                 EDIT_MakeUndoFit(es, e - s);
2925                                 strncpyW(es->undo_text, es->text + s, e - s + 1);
2926                                 es->undo_text[e - s] = 0; /* ensure 0 termination */
2927                                 es->undo_position = s;
2928                         }
2929                         /* any deletion makes the old insertion-undo invalid */
2930                         es->undo_insert_count = 0;
2931                 } else
2932                         EDIT_EM_EmptyUndoBuffer(es);
2933
2934                 /* now delete */
2935                 strcpyW(es->text + s, es->text + e);
2936         }
2937         if (strl) {
2938                 /* there is an insertion */
2939                 if (can_undo) {
2940                         if ((s == es->undo_position) ||
2941                                         ((es->undo_insert_count) &&
2942                                         (s == es->undo_position + es->undo_insert_count)))
2943                                 /*
2944                                  * insertion is new and at delete position or
2945                                  * an extension to either left or right
2946                                  */
2947                                 es->undo_insert_count += strl;
2948                         else {
2949                                 /* new insertion undo */
2950                                 es->undo_position = s;
2951                                 es->undo_insert_count = strl;
2952                                 /* new insertion makes old delete-buffer invalid */
2953                                 *es->undo_text = '\0';
2954                         }
2955                 } else
2956                         EDIT_EM_EmptyUndoBuffer(es);
2957
2958                 /* now insert */
2959                 tl = strlenW(es->text);
2960                 TRACE("inserting stuff (tl %d, strl %d, selstart %d ('%s'), text '%s')\n", tl, strl, s, debugstr_w(es->text + s), debugstr_w(es->text));
2961                 for (p = es->text + tl ; p >= es->text + s ; p--)
2962                         p[strl] = p[0];
2963                 for (i = 0 , p = es->text + s ; i < strl ; i++)
2964                         p[i] = lpsz_replace[i];
2965                 if(es->style & ES_UPPERCASE)
2966                         CharUpperBuffW(p, strl);
2967                 else if(es->style & ES_LOWERCASE)
2968                         CharLowerBuffW(p, strl);
2969                 s += strl;
2970         }
2971         if (es->style & ES_MULTILINE)
2972         {
2973                 INT s = min(es->selection_start, es->selection_end);
2974
2975                 hrgn = CreateRectRgn(0, 0, 0, 0);
2976                 EDIT_BuildLineDefs_ML(es, s, s + strl,
2977                                 strl - abs(es->selection_end - es->selection_start), hrgn);
2978         }
2979         else
2980             EDIT_CalcLineWidth_SL(es);
2981
2982         EDIT_EM_SetSel(es, s, s, FALSE);
2983         es->flags |= EF_MODIFIED;
2984         if (send_update) es->flags |= EF_UPDATE;
2985         if (hrgn)
2986         {
2987                 EDIT_UpdateTextRegion(es, hrgn, TRUE);
2988                 DeleteObject(hrgn);
2989         }
2990         else
2991             EDIT_UpdateText(es, NULL, TRUE);
2992
2993         EDIT_EM_ScrollCaret(es);
2994
2995         /* force scroll info update */
2996         EDIT_UpdateScrollInfo(es);
2997
2998
2999         if(es->flags & EF_UPDATE)
3000         {
3001             es->flags &= ~EF_UPDATE;
3002             EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3003         }
3004 }
3005
3006
3007 /*********************************************************************
3008  *
3009  *      EM_SCROLL
3010  *
3011  */
3012 static LRESULT EDIT_EM_Scroll(EDITSTATE *es, INT action)
3013 {
3014         INT dy;
3015
3016         if (!(es->style & ES_MULTILINE))
3017                 return (LRESULT)FALSE;
3018
3019         dy = 0;
3020
3021         switch (action) {
3022         case SB_LINEUP:
3023                 if (es->y_offset)
3024                         dy = -1;
3025                 break;
3026         case SB_LINEDOWN:
3027                 if (es->y_offset < es->line_count - 1)
3028                         dy = 1;
3029                 break;
3030         case SB_PAGEUP:
3031                 if (es->y_offset)
3032                         dy = -(es->format_rect.bottom - es->format_rect.top) / es->line_height;
3033                 break;
3034         case SB_PAGEDOWN:
3035                 if (es->y_offset < es->line_count - 1)
3036                         dy = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3037                 break;
3038         default:
3039                 return (LRESULT)FALSE;
3040         }
3041         if (dy) {
3042             INT vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3043             /* check if we are going to move too far */
3044             if(es->y_offset + dy > es->line_count - vlc)
3045                 dy = es->line_count - vlc - es->y_offset;
3046
3047             /* Notification is done in EDIT_EM_LineScroll */
3048             if(dy)
3049                 EDIT_EM_LineScroll(es, 0, dy);
3050         }
3051         return MAKELONG((INT16)dy, (BOOL16)TRUE);
3052 }
3053
3054
3055 /*********************************************************************
3056  *
3057  *      EM_SCROLLCARET
3058  *
3059  */
3060 static void EDIT_EM_ScrollCaret(EDITSTATE *es)
3061 {
3062         if (es->style & ES_MULTILINE) {
3063                 INT l;
3064                 INT li;
3065                 INT vlc;
3066                 INT ww;
3067                 INT cw = es->char_width;
3068                 INT x;
3069                 INT dy = 0;
3070                 INT dx = 0;
3071
3072                 l = EDIT_EM_LineFromChar(es, es->selection_end);
3073                 li = EDIT_EM_LineIndex(es, l);
3074                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, es->flags & EF_AFTER_WRAP));
3075                 vlc = (es->format_rect.bottom - es->format_rect.top) / es->line_height;
3076                 if (l >= es->y_offset + vlc)
3077                         dy = l - vlc + 1 - es->y_offset;
3078                 if (l < es->y_offset)
3079                         dy = l - es->y_offset;
3080                 ww = es->format_rect.right - es->format_rect.left;
3081                 if (x < es->format_rect.left)
3082                         dx = x - es->format_rect.left - ww / HSCROLL_FRACTION / cw * cw;
3083                 if (x > es->format_rect.right)
3084                         dx = x - es->format_rect.left - (HSCROLL_FRACTION - 1) * ww / HSCROLL_FRACTION / cw * cw;
3085                 if (dy || dx)
3086                 {
3087                     /* check if we are going to move too far */
3088                     if(es->x_offset + dx + ww > es->text_width)
3089                         dx = es->text_width - ww - es->x_offset;
3090                     if(dx || dy)
3091                         EDIT_EM_LineScroll_internal(es, dx, dy);
3092                 }
3093         } else {
3094                 INT x;
3095                 INT goal;
3096                 INT format_width;
3097
3098                 if (!(es->style & ES_AUTOHSCROLL))
3099                         return;
3100
3101                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3102                 format_width = es->format_rect.right - es->format_rect.left;
3103                 if (x < es->format_rect.left) {
3104                         goal = es->format_rect.left + format_width / HSCROLL_FRACTION;
3105                         do {
3106                                 es->x_offset--;
3107                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3108                         } while ((x < goal) && es->x_offset);
3109                         /* FIXME: use ScrollWindow() somehow to improve performance */
3110                         EDIT_UpdateText(es, NULL, TRUE);
3111                 } else if (x > es->format_rect.right) {
3112                         INT x_last;
3113                         INT len = strlenW(es->text);
3114                         goal = es->format_rect.right - format_width / HSCROLL_FRACTION;
3115                         do {
3116                                 es->x_offset++;
3117                                 x = (short)LOWORD(EDIT_EM_PosFromChar(es, es->selection_end, FALSE));
3118                                 x_last = (short)LOWORD(EDIT_EM_PosFromChar(es, len, FALSE));
3119                         } while ((x > goal) && (x_last > es->format_rect.right));
3120                         /* FIXME: use ScrollWindow() somehow to improve performance */
3121                         EDIT_UpdateText(es, NULL, TRUE);
3122                 }
3123         }
3124
3125     if(es->flags & EF_FOCUSED)
3126         EDIT_SetCaretPos(es, es->selection_end, es->flags & EF_AFTER_WRAP);
3127 }
3128
3129
3130 /*********************************************************************
3131  *
3132  *      EM_SETHANDLE
3133  *
3134  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3135  *
3136  */
3137 static void EDIT_EM_SetHandle(EDITSTATE *es, HLOCAL hloc)
3138 {
3139         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
3140
3141         if (!(es->style & ES_MULTILINE))
3142                 return;
3143
3144         if (!hloc) {
3145                 WARN("called with NULL handle\n");
3146                 return;
3147         }
3148
3149         EDIT_UnlockBuffer(es, TRUE);
3150
3151         if(es->hloc16)
3152         {
3153             LOCAL_Free(hInstance, es->hloc16);
3154             es->hloc16 = (HLOCAL16)NULL;
3155         }
3156
3157         if(es->is_unicode)
3158         {
3159             if(es->hloc32A)
3160             {
3161                 LocalFree(es->hloc32A);
3162                 es->hloc32A = NULL;
3163             }
3164             es->hloc32W = hloc;
3165         }
3166         else
3167         {
3168             INT countW, countA;
3169             HLOCAL hloc32W_new;
3170             WCHAR *textW;
3171             CHAR *textA;
3172
3173             countA = LocalSize(hloc);
3174             textA = LocalLock(hloc);
3175             countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3176             if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3177             {
3178                 ERR("Could not allocate new unicode buffer\n");
3179                 return;
3180             }
3181             textW = LocalLock(hloc32W_new);
3182             MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3183             LocalUnlock(hloc32W_new);
3184             LocalUnlock(hloc);
3185
3186             if(es->hloc32W)
3187                 LocalFree(es->hloc32W);
3188
3189             es->hloc32W = hloc32W_new;
3190             es->hloc32A = hloc;
3191         }
3192
3193         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3194
3195         EDIT_LockBuffer(es);
3196
3197         es->x_offset = es->y_offset = 0;
3198         es->selection_start = es->selection_end = 0;
3199         EDIT_EM_EmptyUndoBuffer(es);
3200         es->flags &= ~EF_MODIFIED;
3201         es->flags &= ~EF_UPDATE;
3202         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3203         EDIT_UpdateText(es, NULL, TRUE);
3204         EDIT_EM_ScrollCaret(es);
3205         /* force scroll info update */
3206         EDIT_UpdateScrollInfo(es);
3207 }
3208
3209
3210 /*********************************************************************
3211  *
3212  *      EM_SETHANDLE16
3213  *
3214  *      FIXME:  ES_LOWERCASE, ES_UPPERCASE, ES_OEMCONVERT, ES_NUMBER ???
3215  *
3216  */
3217 static void EDIT_EM_SetHandle16(EDITSTATE *es, HLOCAL16 hloc)
3218 {
3219         HINSTANCE16 hInstance = GetWindowLongW( es->hwndSelf, GWL_HINSTANCE );
3220         INT countW, countA;
3221         HLOCAL hloc32W_new;
3222         WCHAR *textW;
3223         CHAR *textA;
3224
3225         if (!(es->style & ES_MULTILINE))
3226                 return;
3227
3228         if (!hloc) {
3229                 WARN("called with NULL handle\n");
3230                 return;
3231         }
3232
3233         EDIT_UnlockBuffer(es, TRUE);
3234
3235         if(es->hloc32A)
3236         {
3237             LocalFree(es->hloc32A);
3238             es->hloc32A = NULL;
3239         }
3240
3241         countA = LOCAL_Size(hInstance, hloc);
3242         textA = LOCAL_Lock(hInstance, hloc);
3243         countW = MultiByteToWideChar(CP_ACP, 0, textA, countA, NULL, 0);
3244         if(!(hloc32W_new = LocalAlloc(LMEM_MOVEABLE | LMEM_ZEROINIT, countW * sizeof(WCHAR))))
3245         {
3246             ERR("Could not allocate new unicode buffer\n");
3247             return;
3248         }
3249         textW = LocalLock(hloc32W_new);
3250         MultiByteToWideChar(CP_ACP, 0, textA, countA, textW, countW);
3251         LocalUnlock(hloc32W_new);
3252         LOCAL_Unlock(hInstance, hloc);
3253
3254         if(es->hloc32W)
3255             LocalFree(es->hloc32W);
3256
3257         es->hloc32W = hloc32W_new;
3258         es->hloc16 = hloc;
3259
3260         es->buffer_size = LocalSize(es->hloc32W)/sizeof(WCHAR) - 1;
3261
3262         EDIT_LockBuffer(es);
3263
3264         es->x_offset = es->y_offset = 0;
3265         es->selection_start = es->selection_end = 0;
3266         EDIT_EM_EmptyUndoBuffer(es);
3267         es->flags &= ~EF_MODIFIED;
3268         es->flags &= ~EF_UPDATE;
3269         EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3270         EDIT_UpdateText(es, NULL, TRUE);
3271         EDIT_EM_ScrollCaret(es);
3272         /* force scroll info update */
3273         EDIT_UpdateScrollInfo(es);
3274 }
3275
3276
3277 /*********************************************************************
3278  *
3279  *      EM_SETLIMITTEXT
3280  *
3281  *      FIXME: in WinNT maxsize is 0x7FFFFFFF / 0xFFFFFFFF
3282  *      However, the windows version is not complied to yet in all of edit.c
3283  *
3284  *  Additionally as the wrapper for RichEdit controls we need larger buffers
3285  *  at present -1 will represent nolimit
3286  */
3287 static void EDIT_EM_SetLimitText(EDITSTATE *es, INT limit)
3288 {
3289     if (limit == 0xFFFFFFFF)
3290         es->buffer_limit = -1;
3291     else if (es->style & ES_MULTILINE) {
3292                 if (limit)
3293                         es->buffer_limit = min(limit, BUFLIMIT_MULTI);
3294                 else
3295                         es->buffer_limit = BUFLIMIT_MULTI;
3296         } else {
3297                 if (limit)
3298                         es->buffer_limit = min(limit, BUFLIMIT_SINGLE);
3299                 else
3300                         es->buffer_limit = BUFLIMIT_SINGLE;
3301         }
3302 }
3303
3304
3305 /*********************************************************************
3306  *
3307  *      EM_SETMARGINS
3308  *
3309  * EC_USEFONTINFO is used as a left or right value i.e. lParam and not as an
3310  * action wParam despite what the docs say. EC_USEFONTINFO calculates the
3311  * margin according to the textmetrics of the current font.
3312  *
3313  * FIXME - With TrueType or vector fonts EC_USEFONTINFO currently sets one third
3314  * of the char's width as the margin, but this is not how Windows handles this.
3315  * For all other fonts Windows sets the margins to zero.
3316  *
3317  */
3318 static void EDIT_EM_SetMargins(EDITSTATE *es, INT action,
3319                                INT left, INT right)
3320 {
3321         TEXTMETRICW tm;
3322         INT default_left_margin  = 0; /* in pixels */
3323         INT default_right_margin = 0; /* in pixels */
3324
3325         /* Set the default margins depending on the font */
3326         if (es->font && (left == EC_USEFONTINFO || right == EC_USEFONTINFO)) {
3327             HDC dc = GetDC(es->hwndSelf);
3328             HFONT old_font = SelectObject(dc, es->font);
3329             GetTextMetricsW(dc, &tm);
3330             /* The default margins are only non zero for TrueType or Vector fonts */
3331             if (tm.tmPitchAndFamily & ( TMPF_VECTOR | TMPF_TRUETYPE )) {
3332                 /* This must be calculated more exactly! But how? */
3333                 default_left_margin = tm.tmAveCharWidth / 3;
3334                 default_right_margin = tm.tmAveCharWidth / 3;
3335             }
3336             SelectObject(dc, old_font);
3337             ReleaseDC(es->hwndSelf, dc);
3338         }
3339
3340         if (action & EC_LEFTMARGIN) {
3341                 if (left != EC_USEFONTINFO)
3342                         es->left_margin = left;
3343                 else
3344                         es->left_margin = default_left_margin;
3345         }
3346
3347         if (action & EC_RIGHTMARGIN) {
3348                 if (right != EC_USEFONTINFO)
3349                         es->right_margin = right;
3350                 else
3351                         es->right_margin = default_right_margin;
3352         }
3353         TRACE("left=%d, right=%d\n", es->left_margin, es->right_margin);
3354 }
3355
3356
3357 /*********************************************************************
3358  *
3359  *      EM_SETPASSWORDCHAR
3360  *
3361  */
3362 static void EDIT_EM_SetPasswordChar(EDITSTATE *es, WCHAR c)
3363 {
3364         LONG style;
3365
3366         if (es->style & ES_MULTILINE)
3367                 return;
3368
3369         if (es->password_char == c)
3370                 return;
3371
3372         style = GetWindowLongW( es->hwndSelf, GWL_STYLE );
3373         es->password_char = c;
3374         if (c) {
3375             SetWindowLongW( es->hwndSelf, GWL_STYLE, style | ES_PASSWORD );
3376             es->style |= ES_PASSWORD;
3377         } else {
3378             SetWindowLongW( es->hwndSelf, GWL_STYLE, style & ~ES_PASSWORD );
3379             es->style &= ~ES_PASSWORD;
3380         }
3381         EDIT_UpdateText(es, NULL, TRUE);
3382 }
3383
3384
3385 /*********************************************************************
3386  *
3387  *      EDIT_EM_SetSel
3388  *
3389  *      note:   unlike the specs say: the order of start and end
3390  *              _is_ preserved in Windows.  (i.e. start can be > end)
3391  *              In other words: this handler is OK
3392  *
3393  */
3394 static void EDIT_EM_SetSel(EDITSTATE *es, UINT start, UINT end, BOOL after_wrap)
3395 {
3396         UINT old_start = es->selection_start;
3397         UINT old_end = es->selection_end;
3398         UINT len = strlenW(es->text);
3399
3400         if (start == (UINT)-1) {
3401                 start = es->selection_end;
3402                 end = es->selection_end;
3403         } else {
3404                 start = min(start, len);
3405                 end = min(end, len);
3406         }
3407         es->selection_start = start;
3408         es->selection_end = end;
3409         if (after_wrap)
3410                 es->flags |= EF_AFTER_WRAP;
3411         else
3412                 es->flags &= ~EF_AFTER_WRAP;
3413 /* This is a little bit more efficient than before, not sure if it can be improved. FIXME? */
3414         ORDER_UINT(start, end);
3415         ORDER_UINT(end, old_end);
3416         ORDER_UINT(start, old_start);
3417         ORDER_UINT(old_start, old_end);
3418         if (end != old_start)
3419         {
3420 /*
3421  * One can also do
3422  *          ORDER_UINT32(end, old_start);
3423  *          EDIT_InvalidateText(es, start, end);
3424  *          EDIT_InvalidateText(es, old_start, old_end);
3425  * in place of the following if statement.
3426  */
3427             if (old_start > end )
3428             {
3429                 EDIT_InvalidateText(es, start, end);
3430                 EDIT_InvalidateText(es, old_start, old_end);
3431             }
3432             else
3433             {
3434                 EDIT_InvalidateText(es, start, old_start);
3435                 EDIT_InvalidateText(es, end, old_end);
3436             }
3437         }
3438         else EDIT_InvalidateText(es, start, old_end);
3439 }
3440
3441
3442 /*********************************************************************
3443  *
3444  *      EM_SETTABSTOPS
3445  *
3446  */
3447 static BOOL EDIT_EM_SetTabStops(EDITSTATE *es, INT count, LPINT tabs)
3448 {
3449         if (!(es->style & ES_MULTILINE))
3450                 return FALSE;
3451         if (es->tabs)
3452                 HeapFree(GetProcessHeap(), 0, es->tabs);
3453         es->tabs_count = count;
3454         if (!count)
3455                 es->tabs = NULL;
3456         else {
3457                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3458                 memcpy(es->tabs, tabs, count * sizeof(INT));
3459         }
3460         return TRUE;
3461 }
3462
3463
3464 /*********************************************************************
3465  *
3466  *      EM_SETTABSTOPS16
3467  *
3468  */
3469 static BOOL EDIT_EM_SetTabStops16(EDITSTATE *es, INT count, LPINT16 tabs)
3470 {
3471         if (!(es->style & ES_MULTILINE))
3472                 return FALSE;
3473         if (es->tabs)
3474                 HeapFree(GetProcessHeap(), 0, es->tabs);
3475         es->tabs_count = count;
3476         if (!count)
3477                 es->tabs = NULL;
3478         else {
3479                 INT i;
3480                 es->tabs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(INT));
3481                 for (i = 0 ; i < count ; i++)
3482                         es->tabs[i] = *tabs++;
3483         }
3484         return TRUE;
3485 }
3486
3487
3488 /*********************************************************************
3489  *
3490  *      EM_SETWORDBREAKPROC
3491  *
3492  */
3493 static void EDIT_EM_SetWordBreakProc(EDITSTATE *es, LPARAM lParam)
3494 {
3495         if (es->word_break_proc == (void *)lParam)
3496                 return;
3497
3498         es->word_break_proc = (void *)lParam;
3499         es->word_break_proc16 = NULL;
3500
3501         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3502                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3503                 EDIT_UpdateText(es, NULL, TRUE);
3504         }
3505 }
3506
3507
3508 /*********************************************************************
3509  *
3510  *      EM_SETWORDBREAKPROC16
3511  *
3512  */
3513 static void EDIT_EM_SetWordBreakProc16(EDITSTATE *es, EDITWORDBREAKPROC16 wbp)
3514 {
3515         if (es->word_break_proc16 == wbp)
3516                 return;
3517
3518         es->word_break_proc = NULL;
3519         es->word_break_proc16 = wbp;
3520         if ((es->style & ES_MULTILINE) && !(es->style & ES_AUTOHSCROLL)) {
3521                 EDIT_BuildLineDefs_ML(es, 0, strlenW(es->text), 0, NULL);
3522                 EDIT_UpdateText(es, NULL, TRUE);
3523         }
3524 }
3525
3526
3527 /*********************************************************************
3528  *
3529  *      EM_UNDO / WM_UNDO
3530  *
3531  */
3532 static BOOL EDIT_EM_Undo(EDITSTATE *es)
3533 {
3534         INT ulength;
3535         LPWSTR utext;
3536
3537         /* Protect read-only edit control from modification */
3538         if(es->style & ES_READONLY)
3539             return FALSE;
3540
3541         ulength = strlenW(es->undo_text);
3542         utext = HeapAlloc(GetProcessHeap(), 0, (ulength + 1) * sizeof(WCHAR));
3543
3544         strcpyW(utext, es->undo_text);
3545
3546         TRACE("before UNDO:insertion length = %d, deletion buffer = %s\n",
3547                      es->undo_insert_count, debugstr_w(utext));
3548
3549         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3550         EDIT_EM_EmptyUndoBuffer(es);
3551         EDIT_EM_ReplaceSel(es, TRUE, utext, FALSE, TRUE);
3552         EDIT_EM_SetSel(es, es->undo_position, es->undo_position + es->undo_insert_count, FALSE);
3553         /* send the notification after the selection start and end are set */
3554         EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3555         EDIT_EM_ScrollCaret(es);
3556         HeapFree(GetProcessHeap(), 0, utext);
3557
3558         TRACE("after UNDO:insertion length = %d, deletion buffer = %s\n",
3559                         es->undo_insert_count, debugstr_w(es->undo_text));
3560         return TRUE;
3561 }
3562
3563
3564 /*********************************************************************
3565  *
3566  *      WM_CHAR
3567  *
3568  */
3569 static void EDIT_WM_Char(EDITSTATE *es, WCHAR c)
3570 {
3571         BOOL control;
3572
3573         /* Protect read-only edit control from modification */
3574         if(es->style & ES_READONLY)
3575             return;
3576
3577         control = GetKeyState(VK_CONTROL) & 0x8000;
3578
3579         switch (c) {
3580         case '\r':
3581             /* If the edit doesn't want the return and it's not a multiline edit, do nothing */
3582             if(!(es->style & ES_MULTILINE) && !(es->style & ES_WANTRETURN))
3583                 break;
3584         case '\n':
3585                 if (es->style & ES_MULTILINE) {
3586                         if (es->style & ES_READONLY) {
3587                                 EDIT_MoveHome(es, FALSE);
3588                                 EDIT_MoveDown_ML(es, FALSE);
3589                         } else {
3590                                 static const WCHAR cr_lfW[] = {'\r','\n',0};
3591                                 EDIT_EM_ReplaceSel(es, TRUE, cr_lfW, TRUE, TRUE);
3592                         }
3593                 }
3594                 break;
3595         case '\t':
3596                 if ((es->style & ES_MULTILINE) && !(es->style & ES_READONLY))
3597                 {
3598                         static const WCHAR tabW[] = {'\t',0};
3599                         EDIT_EM_ReplaceSel(es, TRUE, tabW, TRUE, TRUE);
3600                 }
3601                 break;
3602         case VK_BACK:
3603                 if (!(es->style & ES_READONLY) && !control) {
3604                         if (es->selection_start != es->selection_end)
3605                                 EDIT_WM_Clear(es);
3606                         else {
3607                                 /* delete character left of caret */
3608                                 EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
3609                                 EDIT_MoveBackward(es, TRUE);
3610                                 EDIT_WM_Clear(es);
3611                         }
3612                 }
3613                 break;
3614         case 0x03: /* ^C */
3615                 SendMessageW(es->hwndSelf, WM_COPY, 0, 0);
3616                 break;
3617         case 0x16: /* ^V */
3618                 SendMessageW(es->hwndSelf, WM_PASTE, 0, 0);
3619                 break;
3620         case 0x18: /* ^X */
3621                 SendMessageW(es->hwndSelf, WM_CUT, 0, 0);
3622                 break;
3623
3624         default:
3625                 if (!(es->style & ES_READONLY) && (c >= ' ') && (c != 127)) {
3626                         WCHAR str[2];
3627                         str[0] = c;
3628                         str[1] = '\0';
3629                         EDIT_EM_ReplaceSel(es, TRUE, str, TRUE, TRUE);
3630                 }
3631                 break;
3632         }
3633 }
3634
3635
3636 /*********************************************************************
3637  *
3638  *      WM_COMMAND
3639  *
3640  */
3641 static void EDIT_WM_Command(EDITSTATE *es, INT code, INT id, HWND control)
3642 {
3643         if (code || control)
3644                 return;
3645
3646         switch (id) {
3647                 case EM_UNDO:
3648                         EDIT_EM_Undo(es);
3649                         break;
3650                 case WM_CUT:
3651                         EDIT_WM_Cut(es);
3652                         break;
3653                 case WM_COPY:
3654                         EDIT_WM_Copy(es);
3655                         break;
3656                 case WM_PASTE:
3657                         EDIT_WM_Paste(es);
3658                         break;
3659                 case WM_CLEAR:
3660                         EDIT_WM_Clear(es);
3661                         break;
3662                 case EM_SETSEL:
3663                         EDIT_EM_SetSel(es, 0, (UINT)-1, FALSE);
3664                         EDIT_EM_ScrollCaret(es);
3665                         break;
3666                 default:
3667                         ERR("unknown menu item, please report\n");
3668                         break;
3669         }
3670 }
3671
3672
3673 /*********************************************************************
3674  *
3675  *      WM_CONTEXTMENU
3676  *
3677  *      Note: the resource files resource/sysres_??.rc cannot define a
3678  *              single popup menu.  Hence we use a (dummy) menubar
3679  *              containing the single popup menu as its first item.
3680  *
3681  *      FIXME: the message identifiers have been chosen arbitrarily,
3682  *              hence we use MF_BYPOSITION.
3683  *              We might as well use the "real" values (anybody knows ?)
3684  *              The menu definition is in resources/sysres_??.rc.
3685  *              Once these are OK, we better use MF_BYCOMMAND here
3686  *              (as we do in EDIT_WM_Command()).
3687  *
3688  */
3689 static void EDIT_WM_ContextMenu(EDITSTATE *es, INT x, INT y)
3690 {
3691         HMENU menu = LoadMenuA(user32_module, "EDITMENU");
3692         HMENU popup = GetSubMenu(menu, 0);
3693         UINT start = es->selection_start;
3694         UINT end = es->selection_end;
3695
3696         ORDER_UINT(start, end);
3697
3698         /* undo */
3699         EnableMenuItem(popup, 0, MF_BYPOSITION | (EDIT_EM_CanUndo(es) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3700         /* cut */
3701         EnableMenuItem(popup, 2, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3702         /* copy */
3703         EnableMenuItem(popup, 3, MF_BYPOSITION | ((end - start) && !(es->style & ES_PASSWORD) ? MF_ENABLED : MF_GRAYED));
3704         /* paste */
3705         EnableMenuItem(popup, 4, MF_BYPOSITION | (IsClipboardFormatAvailable(CF_UNICODETEXT) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3706         /* delete */
3707         EnableMenuItem(popup, 5, MF_BYPOSITION | ((end - start) && !(es->style & ES_READONLY) ? MF_ENABLED : MF_GRAYED));
3708         /* select all */
3709         EnableMenuItem(popup, 7, MF_BYPOSITION | (start || (end != strlenW(es->text)) ? MF_ENABLED : MF_GRAYED));
3710
3711         TrackPopupMenu(popup, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, es->hwndSelf, NULL);
3712         DestroyMenu(menu);
3713 }
3714
3715
3716 /*********************************************************************
3717  *
3718  *      WM_COPY
3719  *
3720  */
3721 static void EDIT_WM_Copy(EDITSTATE *es)
3722 {
3723         INT s = min(es->selection_start, es->selection_end);
3724         INT e = max(es->selection_start, es->selection_end);
3725         HGLOBAL hdst;
3726         LPWSTR dst;
3727
3728         if (e == s) return;
3729
3730         hdst = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, (DWORD)(e - s + 1) * sizeof(WCHAR));
3731         dst = GlobalLock(hdst);
3732         strncpyW(dst, es->text + s, e - s);
3733         dst[e - s] = 0; /* ensure 0 termination */
3734         TRACE("%s\n", debugstr_w(dst));
3735         GlobalUnlock(hdst);
3736         OpenClipboard(es->hwndSelf);
3737         EmptyClipboard();
3738         SetClipboardData(CF_UNICODETEXT, hdst);
3739         CloseClipboard();
3740 }
3741
3742
3743 /*********************************************************************
3744  *
3745  *      WM_CREATE
3746  *
3747  */
3748 static LRESULT EDIT_WM_Create(EDITSTATE *es, LPCWSTR name)
3749 {
3750         TRACE("%s\n", debugstr_w(name));
3751        /*
3752         *       To initialize some final structure members, we call some helper
3753         *       functions.  However, since the EDITSTATE is not consistent (i.e.
3754         *       not fully initialized), we should be very careful which
3755         *       functions can be called, and in what order.
3756         */
3757         EDIT_WM_SetFont(es, 0, FALSE);
3758         EDIT_EM_EmptyUndoBuffer(es);
3759
3760        if (name && *name) {
3761            EDIT_EM_ReplaceSel(es, FALSE, name, FALSE, TRUE);
3762            /* if we insert text to the editline, the text scrolls out
3763             * of the window, as the caret is placed after the insert
3764             * pos normally; thus we reset es->selection... to 0 and
3765             * update caret
3766             */
3767            es->selection_start = es->selection_end = 0;
3768            /* Adobe Photoshop does NOT like this. and MSDN says that EN_CHANGE
3769             * Messages are only to be sent when the USER does something to
3770             * change the contents. So I am removing this EN_CHANGE
3771             *
3772             * EDIT_NOTIFY_PARENT(es, EN_CHANGE, "EN_CHANGE");
3773             */
3774            EDIT_EM_ScrollCaret(es);
3775        }
3776        /* force scroll info update */
3777        EDIT_UpdateScrollInfo(es);
3778        /* The rule seems to return 1 here for success */
3779        /* Power Builder masked edit controls will crash  */
3780        /* if not. */
3781        /* FIXME: is that in all cases so ? */
3782        return 1;
3783 }
3784
3785
3786 /*********************************************************************
3787  *
3788  *      WM_DESTROY
3789  *
3790  */
3791 static LRESULT EDIT_WM_Destroy(EDITSTATE *es)
3792 {
3793         LINEDEF *pc, *pp;
3794
3795         if (es->hloc32W) {
3796                 while (LocalUnlock(es->hloc32W)) ;
3797                 LocalFree(es->hloc32W);
3798         }
3799         if (es->hloc32A) {
3800                 while (LocalUnlock(es->hloc32A)) ;
3801                 LocalFree(es->hloc32A);
3802         }
3803         if (es->hloc16) {
3804                 HINSTANCE16 hInstance = GetWindowWord( es->hwndSelf, GWL_HINSTANCE );
3805                 while (LOCAL_Unlock(hInstance, es->hloc16)) ;
3806                 LOCAL_Free(hInstance, es->hloc16);
3807         }
3808
3809         pc = es->first_line_def;
3810         while (pc)
3811         {
3812                 pp = pc->next;
3813                 HeapFree(GetProcessHeap(), 0, pc);
3814                 pc = pp;
3815         }
3816
3817         SetWindowLongW( es->hwndSelf, 0, 0 );
3818         HeapFree(GetProcessHeap(), 0, es);
3819
3820         return 0;
3821 }
3822
3823
3824 /*********************************************************************
3825  *
3826  *      WM_ERASEBKGND
3827  *
3828  */
3829 static LRESULT EDIT_WM_EraseBkGnd(EDITSTATE *es, HDC dc)
3830 {
3831         HBRUSH brush;
3832         RECT rc;
3833
3834         if (!(brush = EDIT_NotifyCtlColor(es, dc)))
3835                 brush = (HBRUSH)GetStockObject(WHITE_BRUSH);
3836
3837         GetClientRect(es->hwndSelf, &rc);
3838         IntersectClipRect(dc, rc.left, rc.top, rc.right, rc.bottom);
3839         GetClipBox(dc, &rc);
3840         /*
3841          *      FIXME:  specs say that we should UnrealizeObject() the brush,
3842          *              but the specs of UnrealizeObject() say that we shouldn't
3843          *              unrealize a stock object.  The default brush that
3844          *              DefWndProc() returns is ... a stock object.
3845          */
3846         FillRect(dc, &rc, brush);
3847         return -1;
3848 }
3849
3850
3851 /*********************************************************************
3852  *
3853  *      WM_GETTEXT
3854  *
3855  */
3856 static INT EDIT_WM_GetText(EDITSTATE *es, INT count, LPARAM lParam, BOOL unicode)
3857 {
3858     if(!count) return 0;
3859
3860     if(unicode)
3861     {
3862         LPWSTR textW = (LPWSTR)lParam;
3863         lstrcpynW(textW, es->text, count);
3864         return strlenW(textW);
3865     }
3866     else
3867     {
3868         LPSTR textA = (LPSTR)lParam;
3869         if (!WideCharToMultiByte(CP_ACP, 0, es->text, -1, textA, count, NULL, NULL))
3870             textA[count - 1] = 0; /* ensure 0 termination */
3871         return strlen(textA);
3872     }
3873 }
3874
3875 /*********************************************************************
3876  *
3877  *      WM_HSCROLL
3878  *
3879  */
3880 static LRESULT EDIT_WM_HScroll(EDITSTATE *es, INT action, INT pos)
3881 {
3882         INT dx;
3883         INT fw;
3884
3885         if (!(es->style & ES_MULTILINE))
3886                 return 0;
3887
3888         if (!(es->style & ES_AUTOHSCROLL))
3889                 return 0;
3890
3891         dx = 0;
3892         fw = es->format_rect.right - es->format_rect.left;
3893         switch (action) {
3894         case SB_LINELEFT:
3895                 TRACE("SB_LINELEFT\n");
3896                 if (es->x_offset)
3897                         dx = -es->char_width;
3898                 break;
3899         case SB_LINERIGHT:
3900                 TRACE("SB_LINERIGHT\n");
3901                 if (es->x_offset < es->text_width)
3902                         dx = es->char_width;
3903                 break;
3904         case SB_PAGELEFT:
3905                 TRACE("SB_PAGELEFT\n");
3906                 if (es->x_offset)
3907                         dx = -fw / HSCROLL_FRACTION / es->char_width * es->char_width;
3908                 break;
3909         case SB_PAGERIGHT:
3910                 TRACE("SB_PAGERIGHT\n");
3911                 if (es->x_offset < es->text_width)
3912                         dx = fw / HSCROLL_FRACTION / es->char_width * es->char_width;
3913                 break;
3914         case SB_LEFT:
3915                 TRACE("SB_LEFT\n");
3916                 if (es->x_offset)
3917                         dx = -es->x_offset;
3918                 break;
3919         case SB_RIGHT:
3920                 TRACE("SB_RIGHT\n");
3921                 if (es->x_offset < es->text_width)
3922                         dx = es->text_width - es->x_offset;
3923                 break;
3924         case SB_THUMBTRACK:
3925                 TRACE("SB_THUMBTRACK %d\n", pos);
3926                 es->flags |= EF_HSCROLL_TRACK;
3927                 if(es->style & WS_HSCROLL)
3928                     dx = pos - es->x_offset;
3929                 else
3930                 {
3931                     INT fw, new_x;
3932                     /* Sanity check */
3933                     if(pos < 0 || pos > 100) return 0;
3934                     /* Assume default scroll range 0-100 */
3935                     fw = es->format_rect.right - es->format_rect.left;
3936                     new_x = pos * (es->text_width - fw) / 100;
3937                     dx = es->text_width ? (new_x - es->x_offset) : 0;
3938                 }
3939                 break;
3940         case SB_THUMBPOSITION:
3941                 TRACE("SB_THUMBPOSITION %d\n", pos);
3942                 es->flags &= ~EF_HSCROLL_TRACK;
3943                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
3944                     dx = pos - es->x_offset;
3945                 else
3946                 {
3947                     INT fw, new_x;
3948                     /* Sanity check */
3949                     if(pos < 0 || pos > 100) return 0;
3950                     /* Assume default scroll range 0-100 */
3951                     fw = es->format_rect.right - es->format_rect.left;
3952                     new_x = pos * (es->text_width - fw) / 100;
3953                     dx = es->text_width ? (new_x - es->x_offset) : 0;
3954                 }
3955                 if (!dx) {
3956                         /* force scroll info update */
3957                         EDIT_UpdateScrollInfo(es);
3958                         EDIT_NOTIFY_PARENT(es, EN_HSCROLL, "EN_HSCROLL");
3959                 }
3960                 break;
3961         case SB_ENDSCROLL:
3962                 TRACE("SB_ENDSCROLL\n");
3963                 break;
3964         /*
3965          *      FIXME : the next two are undocumented !
3966          *      Are we doing the right thing ?
3967          *      At least Win 3.1 Notepad makes use of EM_GETTHUMB this way,
3968          *      although it's also a regular control message.
3969          */
3970         case EM_GETTHUMB: /* this one is used by NT notepad */
3971         case EM_GETTHUMB16:
3972         {
3973                 LRESULT ret;
3974                 if(GetWindowLongW( es->hwndSelf, GWL_STYLE ) & WS_HSCROLL)
3975                     ret = GetScrollPos(es->hwndSelf, SB_HORZ);
3976                 else
3977                 {
3978                     /* Assume default scroll range 0-100 */
3979                     INT fw = es->format_rect.right - es->format_rect.left;
3980                     ret = es->text_width ? es->x_offset * 100 / (es->text_width - fw) : 0;
3981                 }
3982                 TRACE("EM_GETTHUMB: returning %ld\n", ret);
3983                 return ret;
3984         }
3985         case EM_LINESCROLL16:
3986                 TRACE("EM_LINESCROLL16\n");
3987                 dx = pos;
3988                 break;
3989
3990         default:
3991                 ERR("undocumented WM_HSCROLL action %d (0x%04x), please report\n",
3992                     action, action);
3993                 return 0;
3994         }
3995         if (dx)
3996         {
3997             INT fw = es->format_rect.right - es->format_rect.left;
3998             /* check if we are going to move too far */
3999             if(es->x_offset + dx + fw > es->text_width)
4000                 dx = es->text_width - fw - es->x_offset;
4001             if(dx)
4002                 EDIT_EM_LineScroll_internal(es, dx, 0);
4003         }
4004         return 0;
4005 }
4006
4007
4008 /*********************************************************************
4009  *
4010  *      EDIT_CheckCombo
4011  *
4012  */
4013 static BOOL EDIT_CheckCombo(EDITSTATE *es, UINT msg, INT key)
4014 {
4015    HWND hLBox = es->hwndListBox;
4016    HWND hCombo;
4017    BOOL bDropped;
4018    int  nEUI;
4019
4020    if (!hLBox)
4021       return FALSE;
4022
4023    hCombo   = GetParent(es->hwndSelf);
4024    bDropped = TRUE;
4025    nEUI     = 0;
4026
4027    TRACE_(combo)("[%p]: handling msg %x (%x)\n", es->hwndSelf, msg, key);
4028
4029    if (key == VK_UP || key == VK_DOWN)
4030    {
4031       if (SendMessageW(hCombo, CB_GETEXTENDEDUI, 0, 0))
4032          nEUI = 1;
4033
4034       if (msg == WM_KEYDOWN || nEUI)
4035           bDropped = (BOOL)SendMessageW(hCombo, CB_GETDROPPEDSTATE, 0, 0);
4036    }
4037
4038    switch (msg)
4039    {
4040       case WM_KEYDOWN:
4041          if (!bDropped && nEUI && (key == VK_UP || key == VK_DOWN))
4042          {
4043             /* make sure ComboLBox pops up */
4044             SendMessageW(hCombo, CB_SETEXTENDEDUI, FALSE, 0);
4045             key = VK_F4;
4046             nEUI = 2;
4047          }
4048
4049          SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)key, 0);
4050          break;
4051
4052       case WM_SYSKEYDOWN: /* Handle Alt+up/down arrows */
4053          if (nEUI)
4054             SendMessageW(hCombo, CB_SHOWDROPDOWN, bDropped ? FALSE : TRUE, 0);
4055          else
4056             SendMessageW(hLBox, WM_KEYDOWN, (WPARAM)VK_F4, 0);
4057          break;
4058    }
4059
4060    if(nEUI == 2)
4061       SendMessageW(hCombo, CB_SETEXTENDEDUI, TRUE, 0);
4062
4063    return TRUE;
4064 }
4065
4066
4067 /*********************************************************************
4068  *
4069  *      WM_KEYDOWN
4070  *
4071  *      Handling of special keys that don't produce a WM_CHAR
4072  *      (i.e. non-printable keys) & Backspace & Delete
4073  *
4074  */
4075 static LRESULT EDIT_WM_KeyDown(EDITSTATE *es, INT key)
4076 {
4077         BOOL shift;
4078         BOOL control;
4079
4080         if (GetKeyState(VK_MENU) & 0x8000)
4081                 return 0;
4082
4083         shift = GetKeyState(VK_SHIFT) & 0x8000;
4084         control = GetKeyState(VK_CONTROL) & 0x8000;
4085
4086         switch (key) {
4087         case VK_F4:
4088         case VK_UP:
4089                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key) || key == VK_F4)
4090                         break;
4091
4092                 /* fall through */
4093         case VK_LEFT:
4094                 if ((es->style & ES_MULTILINE) && (key == VK_UP))
4095                         EDIT_MoveUp_ML(es, shift);
4096                 else
4097                         if (control)
4098                                 EDIT_MoveWordBackward(es, shift);
4099                         else
4100                                 EDIT_MoveBackward(es, shift);
4101                 break;
4102         case VK_DOWN:
4103                 if (EDIT_CheckCombo(es, WM_KEYDOWN, key))
4104                         break;
4105                 /* fall through */
4106         case VK_RIGHT:
4107                 if ((es->style & ES_MULTILINE) && (key == VK_DOWN))
4108                         EDIT_MoveDown_ML(es, shift);
4109                 else if (control)
4110                         EDIT_MoveWordForward(es, shift);
4111                 else
4112                         EDIT_MoveForward(es, shift);
4113                 break;
4114         case VK_HOME:
4115                 EDIT_MoveHome(es, shift);
4116                 break;
4117         case VK_END:
4118                 EDIT_MoveEnd(es, shift);
4119                 break;
4120         case VK_PRIOR:
4121                 if (es->style & ES_MULTILINE)
4122                         EDIT_MovePageUp_ML(es, shift);
4123                 else
4124                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4125                 break;
4126         case VK_NEXT:
4127                 if (es->style & ES_MULTILINE)
4128                         EDIT_MovePageDown_ML(es, shift);
4129                 else
4130                         EDIT_CheckCombo(es, WM_KEYDOWN, key);
4131                 break;
4132         case VK_DELETE:
4133                 if (!(es->style & ES_READONLY) && !(shift && control)) {
4134                         if (es->selection_start != es->selection_end) {
4135                                 if (shift)
4136                                         EDIT_WM_Cut(es);
4137                                 else
4138                                         EDIT_WM_Clear(es);
4139                         } else {
4140                                 if (shift) {
4141                                         /* delete character left of caret */
4142                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4143                                         EDIT_MoveBackward(es, TRUE);
4144                                         EDIT_WM_Clear(es);
4145                                 } else if (control) {
4146                                         /* delete to end of line */
4147                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4148                                         EDIT_MoveEnd(es, TRUE);
4149                                         EDIT_WM_Clear(es);
4150                                 } else {
4151                                         /* delete character right of caret */
4152                                         EDIT_EM_SetSel(es, (UINT)-1, 0, FALSE);
4153                                         EDIT_MoveForward(es, TRUE);
4154                                         EDIT_WM_Clear(es);
4155                                 }
4156                         }
4157                 }
4158                 break;
4159         case VK_INSERT:
4160                 if (shift) {
4161                         if (!(es->style & ES_READONLY))
4162                                 EDIT_WM_Paste(es);
4163                 } else if (control)
4164                         EDIT_WM_Copy(es);
4165                 break;
4166         case VK_RETURN:
4167             /* If the edit doesn't want the return send a message to the default object */
4168             if(!(es->style & ES_WANTRETURN))
4169             {
4170                 HWND hwndParent = GetParent(es->hwndSelf);
4171                 DWORD dw = SendMessageW( hwndParent, DM_GETDEFID, 0, 0 );
4172                 if (HIWORD(dw) == DC_HASDEFID)
4173                 {
4174                     SendMessageW( hwndParent, WM_COMMAND,
4175                                   MAKEWPARAM( LOWORD(dw), BN_CLICKED ),
4176                               (LPARAM)GetDlgItem( hwndParent, LOWORD(dw) ) );
4177                 }
4178             }
4179             break;
4180         }
4181         return 0;
4182 }
4183
4184
4185 /*********************************************************************
4186  *
4187  *      WM_KILLFOCUS
4188  *
4189  */
4190 static LRESULT EDIT_WM_KillFocus(EDITSTATE *es)
4191 {
4192         es->flags &= ~EF_FOCUSED;
4193         DestroyCaret();
4194         if(!(es->style & ES_NOHIDESEL))
4195                 EDIT_InvalidateText(es, es->selection_start, es->selection_end);
4196         EDIT_NOTIFY_PARENT(es, EN_KILLFOCUS, "EN_KILLFOCUS");
4197         return 0;
4198 }
4199
4200
4201 /*********************************************************************
4202  *
4203  *      WM_LBUTTONDBLCLK
4204  *
4205  *      The caret position has been set on the WM_LBUTTONDOWN message
4206  *
4207  */
4208 static LRESULT EDIT_WM_LButtonDblClk(EDITSTATE *es)
4209 {
4210         INT s;
4211         INT e = es->selection_end;
4212         INT l;
4213         INT li;
4214         INT ll;
4215
4216         if (!(es->flags & EF_FOCUSED))
4217                 return 0;
4218
4219         l = EDIT_EM_LineFromChar(es, e);
4220         li = EDIT_EM_LineIndex(es, l);
4221         ll = EDIT_EM_LineLength(es, e);
4222         s = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_LEFT);
4223         e = li + EDIT_CallWordBreakProc(es, li, e - li, ll, WB_RIGHT);
4224         EDIT_EM_SetSel(es, s, e, FALSE);
4225         EDIT_EM_ScrollCaret(es);
4226         return 0;
4227 }
4228
4229
4230 /*********************************************************************
4231  *
4232  *      WM_LBUTTONDOWN
4233  *
4234  */
4235 static LRESULT EDIT_WM_LButtonDown(EDITSTATE *es, DWORD keys, INT x, INT y)
4236 {
4237         INT e;
4238         BOOL after_wrap;
4239
4240         SetFocus(es->hwndSelf);
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 }