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