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