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