user32: Scale the button size with screen resolution.
[wine.git] / dlls / riched20 / editor.c
blob9c54623c5269ea4fe9743fe4b8f065906fecf2c8
1 /*
2 * RichEdit - functions dealing with editor object
4 * Copyright 2004 by Krzysztof Foltman
5 * Copyright 2005 by Cihan Altinay
6 * Copyright 2005 by Phil Krylov
7 * Copyright 2008 Eric Pouech
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.
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.
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
24 /*
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
29 + EM_CANPASTE
30 + EM_CANREDO 2.0
31 + EM_CANUNDO
32 + EM_CHARFROMPOS
33 - EM_DISPLAYBAND
34 + EM_EMPTYUNDOBUFFER
35 + EM_EXGETSEL
36 + EM_EXLIMITTEXT
37 + EM_EXLINEFROMCHAR
38 + EM_EXSETSEL
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41 - EM_FINDWORDBREAK
42 - EM_FMTLINES
43 - EM_FORMATRANGE
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
47 - EM_GETEDITSTYLE
48 + EM_GETEVENTMASK
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
53 - EM_GETIMESTATUS
54 - EM_GETLANGOPTIONS 2.0
55 + EM_GETLIMITTEXT
56 + EM_GETLINE
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
58 + EM_GETMODIFY
59 + EM_GETOLEINTERFACE
60 + EM_GETOPTIONS
61 + EM_GETPARAFORMAT
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
64 + EM_GETRECT
65 - EM_GETREDONAME 2.0
66 + EM_GETSEL
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0
69 ! - EM_GETTHUMB
70 + EM_GETTEXTEX 2.0
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72 + EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
75 - EM_GETUNDONAME
76 + EM_GETWORDBREAKPROC
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
79 + EM_GETZOOM 3.0
80 + EM_HIDESELECTION
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82 + EM_LINEFROMCHAR
83 + EM_LINEINDEX
84 + EM_LINELENGTH
85 + EM_LINESCROLL
86 - EM_PASTESPECIAL
87 + EM_POSFROMCHAR
88 + EM_REDO 2.0
89 + EM_REQUESTRESIZE
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
91 + EM_SCROLL
92 + EM_SCROLLCARET
93 - EM_SELECTIONTYPE
94 - EM_SETBIDIOPTIONS 3.0
95 + EM_SETBKGNDCOLOR
96 + EM_SETCHARFORMAT (partly done, no ANSI)
97 - EM_SETEDITSTYLE
98 + EM_SETEVENTMASK (few notifications supported)
99 + EM_SETFONTSIZE
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETIMESTATUS
103 - EM_SETLANGOPTIONS 2.0
104 - EM_SETLIMITTEXT
105 - EM_SETMARGINS
106 + EM_SETMODIFY (not sure if implementation is correct)
107 - EM_SETOLECALLBACK
108 + EM_SETOPTIONS (partially implemented)
109 - EM_SETPALETTE 2.0
110 + EM_SETPARAFORMAT
111 + EM_SETPASSWORDCHAR 2.0
112 - EM_SETPUNCTUATION 1.0asian
113 + EM_SETREADONLY no beep on modification attempt
114 + EM_SETRECT
115 + EM_SETRECTNP (EM_SETRECT without repainting)
116 + EM_SETSEL
117 + EM_SETSCROLLPOS 3.0
118 - EM_SETTABSTOPS 3.0
119 - EM_SETTARGETDEVICE (partial)
120 + EM_SETTEXTEX 3.0 (proper style?)
121 - EM_SETTEXTMODE 2.0
122 - EM_SETTYPOGRAPHYOPTIONS 3.0
123 + EM_SETUNDOLIMIT 2.0
124 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
125 - EM_SETWORDBREAKPROCEX
126 - EM_SETWORDWRAPMODE 1.0asian
127 + EM_SETZOOM 3.0
128 + EM_SHOWSCROLLBAR 2.0
129 + EM_STOPGROUPTYPING 2.0
130 + EM_STREAMIN
131 + EM_STREAMOUT
132 + EM_UNDO
133 + WM_CHAR
134 + WM_CLEAR
135 + WM_COPY
136 + WM_CUT
137 + WM_GETDLGCODE (the current implementation is incomplete)
138 + WM_GETTEXT (ANSI&Unicode)
139 + WM_GETTEXTLENGTH (ANSI version sucks)
140 + WM_HSCROLL
141 + WM_PASTE
142 + WM_SETFONT
143 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144 + WM_STYLECHANGING (seems to do nothing)
145 + WM_STYLECHANGED (seems to do nothing)
146 + WM_UNICHAR
147 + WM_VSCROLL
149 Notifications
151 * EN_CHANGE (sent from the wrong place)
152 - EN_CORRECTTEXT
153 - EN_DROPFILES
154 - EN_ERRSPACE
155 - EN_HSCROLL
156 - EN_IMECHANGE
157 + EN_KILLFOCUS
158 - EN_LINK
159 - EN_MAXTEXT
160 - EN_MSGFILTER
161 - EN_OLEOPFAILED
162 - EN_PROTECTED
163 + EN_REQUESTRESIZE
164 - EN_SAVECLIPBOARD
165 + EN_SELCHANGE
166 + EN_SETFOCUS
167 - EN_STOPNOUNDO
168 * EN_UPDATE (sent from the wrong place)
169 - EN_VSCROLL
171 Styles
173 - ES_AUTOHSCROLL
174 - ES_AUTOVSCROLL
175 + ES_CENTER
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
178 + ES_LEFT
179 - ES_MULTILINE (currently single line controls aren't supported)
180 - ES_NOIME
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182 + ES_RIGHT
183 - ES_SAVESEL
184 - ES_SELFIME
185 - ES_SUNKEN
186 - ES_VERTICAL
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188 - WS_SETFONT
189 + WS_HSCROLL
190 + WS_VSCROLL
194 * RICHED20 TODO (incomplete):
196 * - messages/styles/notifications listed above
197 * - add remaining CHARFORMAT/PARAFORMAT fields
198 * - right/center align should strip spaces from the beginning
199 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200 * - COM interface (looks like a major pain in the TODO list)
201 * - calculate heights of pictures (half-done)
202 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203 * - find/replace
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
206 * - IME
207 * - most notifications aren't sent at all (the most important ones are)
208 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211 * - full justification
212 * - hyphenation
213 * - tables
214 * - ListBox & ComboBox not implemented
216 * Bugs that are probably fixed, but not so easy to verify:
217 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220 * - caret shouldn't be displayed when selection isn't empty
221 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222 * - undo for setting default format (done, might be buggy)
223 * - styles might be not released properly (looks like they work like charm, but who knows?
227 #define NONAMELESSUNION
229 #include "editor.h"
230 #include "commdlg.h"
231 #include "winreg.h"
232 #define NO_SHLWAPI_STREAM
233 #include "shlwapi.h"
234 #include "rtf.h"
235 #include "imm.h"
236 #include "res.h"
238 #define STACK_SIZE_DEFAULT 100
239 #define STACK_SIZE_MAX 1000
241 #define TEXT_LIMIT_DEFAULT 32767
243 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
245 static BOOL ME_RegisterEditorClass(HINSTANCE);
246 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
248 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
249 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
250 static HCURSOR hLeft;
252 BOOL me_debug = FALSE;
253 HANDLE me_heap = NULL;
255 static BOOL ME_ListBoxRegistered = FALSE;
256 static BOOL ME_ComboBoxRegistered = FALSE;
258 static inline BOOL is_version_nt(void)
260 return !(GetVersion() & 0x80000000);
263 static ME_TextBuffer *ME_MakeText(void) {
265 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
267 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
268 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
270 p1->prev = NULL;
271 p1->next = p2;
272 p2->prev = p1;
273 p2->next = NULL;
274 p1->member.para.next_para = p2;
275 p2->member.para.prev_para = p1;
276 p2->member.para.nCharOfs = 0;
278 buf->pFirst = p1;
279 buf->pLast = p2;
280 buf->pCharStyle = NULL;
282 return buf;
286 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
288 WCHAR *pText;
289 LRESULT total_bytes_read = 0;
290 BOOL is_read = FALSE;
291 DWORD cp = CP_ACP, copy = 0;
292 char conv_buf[4 + STREAMIN_BUFFER_SIZE]; /* up to 4 additional UTF-8 bytes */
294 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
296 TRACE("%08x %p\n", dwFormat, stream);
298 do {
299 LONG nWideChars = 0;
300 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
302 if (!stream->dwSize)
304 ME_StreamInFill(stream);
305 if (stream->editstream->dwError)
306 break;
307 if (!stream->dwSize)
308 break;
309 total_bytes_read += stream->dwSize;
312 if (!(dwFormat & SF_UNICODE))
314 char * buf = stream->buffer;
315 DWORD size = stream->dwSize, end;
317 if (!is_read)
319 is_read = TRUE;
320 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
322 cp = CP_UTF8;
323 buf += 3;
324 size -= 3;
328 if (cp == CP_UTF8)
330 if (copy)
332 memcpy(conv_buf + copy, buf, size);
333 buf = conv_buf;
334 size += copy;
336 end = size;
337 while ((buf[end-1] & 0xC0) == 0x80)
339 --end;
340 --total_bytes_read; /* strange, but seems to match windows */
342 if (buf[end-1] & 0x80)
344 DWORD need = 0;
345 if ((buf[end-1] & 0xE0) == 0xC0)
346 need = 1;
347 if ((buf[end-1] & 0xF0) == 0xE0)
348 need = 2;
349 if ((buf[end-1] & 0xF8) == 0xF0)
350 need = 3;
352 if (size - end >= need)
354 /* we have enough bytes for this sequence */
355 end = size;
357 else
359 /* need more bytes, so don't transcode this sequence */
360 --end;
364 else
365 end = size;
367 nWideChars = MultiByteToWideChar(cp, 0, buf, end, wszText, STREAMIN_BUFFER_SIZE);
368 pText = wszText;
370 if (cp == CP_UTF8)
372 if (end != size)
374 memcpy(conv_buf, buf + end, size - end);
375 copy = size - end;
379 else
381 nWideChars = stream->dwSize >> 1;
382 pText = (WCHAR *)stream->buffer;
385 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
386 if (stream->dwSize == 0)
387 break;
388 stream->dwSize = 0;
389 } while(1);
390 return total_bytes_read;
393 static void ME_ApplyBorderProperties(RTF_Info *info,
394 ME_BorderRect *borderRect,
395 RTFBorder *borderDef)
397 int i, colorNum;
398 ME_Border *pBorders[] = {&borderRect->top,
399 &borderRect->left,
400 &borderRect->bottom,
401 &borderRect->right};
402 for (i = 0; i < 4; i++)
404 RTFColor *colorDef = info->colorList;
405 pBorders[i]->width = borderDef[i].width;
406 colorNum = borderDef[i].color;
407 while (colorDef && colorDef->rtfCNum != colorNum)
408 colorDef = colorDef->rtfNextColor;
409 if (colorDef)
410 pBorders[i]->colorRef = RGB(
411 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
412 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
413 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
414 else
415 pBorders[i]->colorRef = RGB(0, 0, 0);
419 void ME_RTFCharAttrHook(RTF_Info *info)
421 CHARFORMAT2W fmt;
422 fmt.cbSize = sizeof(fmt);
423 fmt.dwMask = 0;
424 fmt.dwEffects = 0;
426 switch(info->rtfMinor)
428 case rtfPlain:
429 /* FIXME add more flags once they're implemented */
430 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
431 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
432 fmt.yHeight = 12*20; /* 12pt */
433 fmt.wWeight = FW_NORMAL;
434 fmt.bUnderlineType = CFU_UNDERLINENONE;
435 break;
436 case rtfBold:
437 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
438 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
439 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
440 break;
441 case rtfItalic:
442 fmt.dwMask = CFM_ITALIC;
443 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
444 break;
445 case rtfUnderline:
446 fmt.dwMask = CFM_UNDERLINETYPE;
447 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
448 break;
449 case rtfDotUnderline:
450 fmt.dwMask = CFM_UNDERLINETYPE;
451 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
452 break;
453 case rtfDbUnderline:
454 fmt.dwMask = CFM_UNDERLINETYPE;
455 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
456 break;
457 case rtfWordUnderline:
458 fmt.dwMask = CFM_UNDERLINETYPE;
459 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
460 break;
461 case rtfNoUnderline:
462 fmt.dwMask = CFM_UNDERLINETYPE;
463 fmt.bUnderlineType = CFU_UNDERLINENONE;
464 break;
465 case rtfStrikeThru:
466 fmt.dwMask = CFM_STRIKEOUT;
467 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
468 break;
469 case rtfSubScript:
470 case rtfSuperScript:
471 case rtfSubScrShrink:
472 case rtfSuperScrShrink:
473 case rtfNoSuperSub:
474 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
475 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
476 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
477 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
478 break;
479 case rtfInvisible:
480 fmt.dwMask = CFM_HIDDEN;
481 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
482 break;
483 case rtfBackColor:
484 fmt.dwMask = CFM_BACKCOLOR;
485 fmt.dwEffects = 0;
486 if (info->rtfParam == 0)
487 fmt.dwEffects = CFE_AUTOBACKCOLOR;
488 else if (info->rtfParam != rtfNoParam)
490 RTFColor *c = RTFGetColor(info, info->rtfParam);
491 if (c && c->rtfCBlue >= 0)
492 fmt.crBackColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
493 else
494 fmt.dwEffects = CFE_AUTOBACKCOLOR;
496 break;
497 case rtfForeColor:
498 fmt.dwMask = CFM_COLOR;
499 fmt.dwEffects = 0;
500 if (info->rtfParam == 0)
501 fmt.dwEffects = CFE_AUTOCOLOR;
502 else if (info->rtfParam != rtfNoParam)
504 RTFColor *c = RTFGetColor(info, info->rtfParam);
505 if (c && c->rtfCBlue >= 0)
506 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
507 else {
508 fmt.dwEffects = CFE_AUTOCOLOR;
511 break;
512 case rtfFontNum:
513 if (info->rtfParam != rtfNoParam)
515 RTFFont *f = RTFGetFont(info, info->rtfParam);
516 if (f)
518 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
519 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
520 fmt.bCharSet = f->rtfFCharSet;
521 fmt.dwMask = CFM_FACE | CFM_CHARSET;
522 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
525 break;
526 case rtfFontSize:
527 fmt.dwMask = CFM_SIZE;
528 if (info->rtfParam != rtfNoParam)
529 fmt.yHeight = info->rtfParam*10;
530 break;
532 if (fmt.dwMask) {
533 ME_Style *style2;
534 RTFFlushOutputBuffer(info);
535 /* FIXME too slow ? how come ? */
536 style2 = ME_ApplyStyle(info->editor, info->style, &fmt);
537 ME_ReleaseStyle(info->style);
538 info->style = style2;
539 info->styleChanged = TRUE;
543 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
544 the same tags mean different things in different contexts */
545 void ME_RTFParAttrHook(RTF_Info *info)
547 switch(info->rtfMinor)
549 case rtfParDef: /* restores default paragraph attributes */
550 if (!info->editor->bEmulateVersion10) /* v4.1 */
551 info->borderType = RTFBorderParaLeft;
552 else /* v1.0 - 3.0 */
553 info->borderType = RTFBorderParaTop;
554 info->fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
555 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
556 PFM_STARTINDENT | PFM_RTLPARA;
557 /* TODO: numbering, shading */
558 info->fmt.wAlignment = PFA_LEFT;
559 info->fmt.cTabCount = 0;
560 info->fmt.dxOffset = info->fmt.dxStartIndent = info->fmt.dxRightIndent = 0;
561 info->fmt.wBorderWidth = info->fmt.wBorders = 0;
562 info->fmt.wBorderSpace = 0;
563 info->fmt.bLineSpacingRule = 0;
564 info->fmt.dySpaceBefore = info->fmt.dySpaceAfter = 0;
565 info->fmt.dyLineSpacing = 0;
566 info->fmt.wEffects &= ~PFE_RTLPARA;
567 if (!info->editor->bEmulateVersion10) /* v4.1 */
569 if (info->tableDef && info->tableDef->tableRowStart &&
570 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
572 ME_Cursor cursor;
573 ME_DisplayItem *para;
574 /* We are just after a table row. */
575 RTFFlushOutputBuffer(info);
576 cursor = info->editor->pCursors[0];
577 para = cursor.pPara;
578 if (para == info->tableDef->tableRowStart->member.para.next_para
579 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
581 /* Since the table row end, no text has been inserted, and the \intbl
582 * control word has not be used. We can confirm that we are not in a
583 * table anymore.
585 info->tableDef->tableRowStart = NULL;
586 info->canInheritInTbl = FALSE;
589 } else { /* v1.0 - v3.0 */
590 info->fmt.dwMask |= PFM_TABLE;
591 info->fmt.wEffects &= ~PFE_TABLE;
593 break;
594 case rtfNestLevel:
595 if (!info->editor->bEmulateVersion10) /* v4.1 */
597 while (info->rtfParam > info->nestingLevel) {
598 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
599 ZeroMemory(tableDef, sizeof(RTFTable));
600 tableDef->parent = info->tableDef;
601 info->tableDef = tableDef;
603 RTFFlushOutputBuffer(info);
604 if (tableDef->tableRowStart &&
605 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
607 ME_DisplayItem *para = tableDef->tableRowStart;
608 para = para->member.para.next_para;
609 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
610 tableDef->tableRowStart = para;
611 } else {
612 ME_Cursor cursor;
613 WCHAR endl = '\r';
614 cursor = info->editor->pCursors[0];
615 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
616 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
617 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
620 info->nestingLevel++;
622 info->canInheritInTbl = FALSE;
624 break;
625 case rtfInTable:
627 if (!info->editor->bEmulateVersion10) /* v4.1 */
629 if (info->nestingLevel < 1)
631 RTFTable *tableDef;
632 if (!info->tableDef)
634 info->tableDef = ALLOC_OBJ(RTFTable);
635 ZeroMemory(info->tableDef, sizeof(RTFTable));
637 tableDef = info->tableDef;
638 RTFFlushOutputBuffer(info);
639 if (tableDef->tableRowStart &&
640 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
642 ME_DisplayItem *para = tableDef->tableRowStart;
643 para = para->member.para.next_para;
644 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
645 tableDef->tableRowStart = para;
646 } else {
647 ME_Cursor cursor;
648 WCHAR endl = '\r';
649 cursor = info->editor->pCursors[0];
650 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
651 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
652 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
654 info->nestingLevel = 1;
655 info->canInheritInTbl = TRUE;
657 return;
658 } else { /* v1.0 - v3.0 */
659 info->fmt.dwMask |= PFM_TABLE;
660 info->fmt.wEffects |= PFE_TABLE;
662 break;
664 case rtfFirstIndent:
665 case rtfLeftIndent:
666 if ((info->fmt.dwMask & (PFM_STARTINDENT | PFM_OFFSET)) != (PFM_STARTINDENT | PFM_OFFSET))
668 PARAFORMAT2 fmt;
669 fmt.cbSize = sizeof(fmt);
670 ME_GetSelectionParaFormat(info->editor, &fmt);
671 info->fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
672 info->fmt.dxStartIndent = fmt.dxStartIndent;
673 info->fmt.dxOffset = fmt.dxOffset;
675 if (info->rtfMinor == rtfFirstIndent)
677 info->fmt.dxStartIndent += info->fmt.dxOffset + info->rtfParam;
678 info->fmt.dxOffset = -info->rtfParam;
680 else
681 info->fmt.dxStartIndent = info->rtfParam - info->fmt.dxOffset;
682 break;
683 case rtfRightIndent:
684 info->fmt.dwMask |= PFM_RIGHTINDENT;
685 info->fmt.dxRightIndent = info->rtfParam;
686 break;
687 case rtfQuadLeft:
688 case rtfQuadJust:
689 info->fmt.dwMask |= PFM_ALIGNMENT;
690 info->fmt.wAlignment = PFA_LEFT;
691 break;
692 case rtfQuadRight:
693 info->fmt.dwMask |= PFM_ALIGNMENT;
694 info->fmt.wAlignment = PFA_RIGHT;
695 break;
696 case rtfQuadCenter:
697 info->fmt.dwMask |= PFM_ALIGNMENT;
698 info->fmt.wAlignment = PFA_CENTER;
699 break;
700 case rtfTabPos:
701 if (!(info->fmt.dwMask & PFM_TABSTOPS))
703 PARAFORMAT2 fmt;
704 fmt.cbSize = sizeof(fmt);
705 ME_GetSelectionParaFormat(info->editor, &fmt);
706 memcpy(info->fmt.rgxTabs, fmt.rgxTabs,
707 fmt.cTabCount * sizeof(fmt.rgxTabs[0]));
708 info->fmt.cTabCount = fmt.cTabCount;
709 info->fmt.dwMask |= PFM_TABSTOPS;
711 if (info->fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
712 info->fmt.rgxTabs[info->fmt.cTabCount++] = info->rtfParam;
713 break;
714 case rtfKeep:
715 info->fmt.dwMask |= PFM_KEEP;
716 info->fmt.wEffects |= PFE_KEEP;
717 break;
718 case rtfNoWidowControl:
719 info->fmt.dwMask |= PFM_NOWIDOWCONTROL;
720 info->fmt.wEffects |= PFE_NOWIDOWCONTROL;
721 break;
722 case rtfKeepNext:
723 info->fmt.dwMask |= PFM_KEEPNEXT;
724 info->fmt.wEffects |= PFE_KEEPNEXT;
725 break;
726 case rtfSpaceAfter:
727 info->fmt.dwMask |= PFM_SPACEAFTER;
728 info->fmt.dySpaceAfter = info->rtfParam;
729 break;
730 case rtfSpaceBefore:
731 info->fmt.dwMask |= PFM_SPACEBEFORE;
732 info->fmt.dySpaceBefore = info->rtfParam;
733 break;
734 case rtfSpaceBetween:
735 info->fmt.dwMask |= PFM_LINESPACING;
736 if ((int)info->rtfParam > 0)
738 info->fmt.dyLineSpacing = info->rtfParam;
739 info->fmt.bLineSpacingRule = 3;
741 else
743 info->fmt.dyLineSpacing = info->rtfParam;
744 info->fmt.bLineSpacingRule = 4;
746 break;
747 case rtfSpaceMultiply:
748 info->fmt.dwMask |= PFM_LINESPACING;
749 info->fmt.dyLineSpacing = info->rtfParam * 20;
750 info->fmt.bLineSpacingRule = 5;
751 break;
752 case rtfParBullet:
753 info->fmt.dwMask |= PFM_NUMBERING;
754 info->fmt.wNumbering = PFN_BULLET;
755 break;
756 case rtfParSimple:
757 info->fmt.dwMask |= PFM_NUMBERING;
758 info->fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
759 break;
760 case rtfParNumDecimal:
761 info->fmt.dwMask |= PFM_NUMBERING;
762 info->fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
763 break;
764 case rtfParNumIndent:
765 info->fmt.dwMask |= PFM_NUMBERINGTAB;
766 info->fmt.wNumberingTab = info->rtfParam;
767 break;
768 case rtfParNumStartAt:
769 info->fmt.dwMask |= PFM_NUMBERINGSTART;
770 info->fmt.wNumberingStart = info->rtfParam;
771 break;
772 case rtfBorderLeft:
773 info->borderType = RTFBorderParaLeft;
774 info->fmt.wBorders |= 1;
775 info->fmt.dwMask |= PFM_BORDER;
776 break;
777 case rtfBorderRight:
778 info->borderType = RTFBorderParaRight;
779 info->fmt.wBorders |= 2;
780 info->fmt.dwMask |= PFM_BORDER;
781 break;
782 case rtfBorderTop:
783 info->borderType = RTFBorderParaTop;
784 info->fmt.wBorders |= 4;
785 info->fmt.dwMask |= PFM_BORDER;
786 break;
787 case rtfBorderBottom:
788 info->borderType = RTFBorderParaBottom;
789 info->fmt.wBorders |= 8;
790 info->fmt.dwMask |= PFM_BORDER;
791 break;
792 case rtfBorderSingle:
793 info->fmt.wBorders &= ~0x700;
794 info->fmt.wBorders |= 1 << 8;
795 info->fmt.dwMask |= PFM_BORDER;
796 break;
797 case rtfBorderThick:
798 info->fmt.wBorders &= ~0x700;
799 info->fmt.wBorders |= 2 << 8;
800 info->fmt.dwMask |= PFM_BORDER;
801 break;
802 case rtfBorderShadow:
803 info->fmt.wBorders &= ~0x700;
804 info->fmt.wBorders |= 10 << 8;
805 info->fmt.dwMask |= PFM_BORDER;
806 break;
807 case rtfBorderDouble:
808 info->fmt.wBorders &= ~0x700;
809 info->fmt.wBorders |= 7 << 8;
810 info->fmt.dwMask |= PFM_BORDER;
811 break;
812 case rtfBorderDot:
813 info->fmt.wBorders &= ~0x700;
814 info->fmt.wBorders |= 11 << 8;
815 info->fmt.dwMask |= PFM_BORDER;
816 break;
817 case rtfBorderWidth:
819 int borderSide = info->borderType & RTFBorderSideMask;
820 RTFTable *tableDef = info->tableDef;
821 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
823 RTFBorder *border;
824 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
825 break;
826 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
827 border->width = info->rtfParam;
828 break;
830 info->fmt.wBorderWidth = info->rtfParam;
831 info->fmt.dwMask |= PFM_BORDER;
832 break;
834 case rtfBorderSpace:
835 info->fmt.wBorderSpace = info->rtfParam;
836 info->fmt.dwMask |= PFM_BORDER;
837 break;
838 case rtfBorderColor:
840 RTFTable *tableDef = info->tableDef;
841 int borderSide = info->borderType & RTFBorderSideMask;
842 int borderType = info->borderType & RTFBorderTypeMask;
843 switch(borderType)
845 case RTFBorderTypePara:
846 if (!info->editor->bEmulateVersion10) /* v4.1 */
847 break;
848 /* v1.0 - 3.0 treat paragraph and row borders the same. */
849 case RTFBorderTypeRow:
850 if (tableDef) {
851 tableDef->border[borderSide].color = info->rtfParam;
853 break;
854 case RTFBorderTypeCell:
855 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
856 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
858 break;
860 break;
862 case rtfRTLPar:
863 info->fmt.dwMask |= PFM_RTLPARA;
864 info->fmt.wEffects |= PFE_RTLPARA;
865 break;
866 case rtfLTRPar:
867 info->fmt.dwMask = PFM_RTLPARA;
868 info->fmt.wEffects &= ~PFE_RTLPARA;
869 break;
873 void ME_RTFTblAttrHook(RTF_Info *info)
875 switch (info->rtfMinor)
877 case rtfRowDef:
879 if (!info->editor->bEmulateVersion10) /* v4.1 */
880 info->borderType = 0; /* Not sure */
881 else /* v1.0 - 3.0 */
882 info->borderType = RTFBorderRowTop;
883 if (!info->tableDef) {
884 info->tableDef = ME_MakeTableDef(info->editor);
885 } else {
886 ME_InitTableDef(info->editor, info->tableDef);
888 break;
890 case rtfCellPos:
892 int cellNum;
893 if (!info->tableDef)
895 info->tableDef = ME_MakeTableDef(info->editor);
897 cellNum = info->tableDef->numCellsDefined;
898 if (cellNum >= MAX_TABLE_CELLS)
899 break;
900 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
901 if (cellNum < MAX_TAB_STOPS) {
902 /* Tab stops were used to store cell positions before v4.1 but v4.1
903 * still seems to set the tabstops without using them. */
904 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
905 PARAFORMAT2 *pFmt = para->member.para.pFmt;
906 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
907 pFmt->rgxTabs[cellNum] |= 0x00FFFFFF & info->rtfParam;
909 info->tableDef->numCellsDefined++;
910 break;
912 case rtfRowBordTop:
913 info->borderType = RTFBorderRowTop;
914 break;
915 case rtfRowBordLeft:
916 info->borderType = RTFBorderRowLeft;
917 break;
918 case rtfRowBordBottom:
919 info->borderType = RTFBorderRowBottom;
920 break;
921 case rtfRowBordRight:
922 info->borderType = RTFBorderRowRight;
923 break;
924 case rtfCellBordTop:
925 info->borderType = RTFBorderCellTop;
926 break;
927 case rtfCellBordLeft:
928 info->borderType = RTFBorderCellLeft;
929 break;
930 case rtfCellBordBottom:
931 info->borderType = RTFBorderCellBottom;
932 break;
933 case rtfCellBordRight:
934 info->borderType = RTFBorderCellRight;
935 break;
936 case rtfRowGapH:
937 if (info->tableDef)
938 info->tableDef->gapH = info->rtfParam;
939 break;
940 case rtfRowLeftEdge:
941 if (info->tableDef)
942 info->tableDef->leftEdge = info->rtfParam;
943 break;
947 void ME_RTFSpecialCharHook(RTF_Info *info)
949 RTFTable *tableDef = info->tableDef;
950 switch (info->rtfMinor)
952 case rtfNestCell:
953 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
954 break;
955 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
956 case rtfCell:
957 if (!tableDef)
958 break;
959 RTFFlushOutputBuffer(info);
960 if (!info->editor->bEmulateVersion10) { /* v4.1 */
961 if (tableDef->tableRowStart)
963 if (!info->nestingLevel &&
964 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
966 ME_DisplayItem *para = tableDef->tableRowStart;
967 para = para->member.para.next_para;
968 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
969 tableDef->tableRowStart = para;
970 info->nestingLevel = 1;
972 ME_InsertTableCellFromCursor(info->editor);
974 } else { /* v1.0 - v3.0 */
975 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
976 PARAFORMAT2 *pFmt = para->member.para.pFmt;
977 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
978 tableDef->numCellsInserted < tableDef->numCellsDefined)
980 WCHAR tab = '\t';
981 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
982 tableDef->numCellsInserted++;
985 break;
986 case rtfNestRow:
987 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
988 break;
989 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
990 case rtfRow:
992 ME_DisplayItem *para, *cell, *run;
993 int i;
995 if (!tableDef)
996 break;
997 RTFFlushOutputBuffer(info);
998 if (!info->editor->bEmulateVersion10) { /* v4.1 */
999 if (!tableDef->tableRowStart)
1000 break;
1001 if (!info->nestingLevel &&
1002 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1004 para = tableDef->tableRowStart;
1005 para = para->member.para.next_para;
1006 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1007 tableDef->tableRowStart = para;
1008 info->nestingLevel++;
1010 para = tableDef->tableRowStart;
1011 cell = ME_FindItemFwd(para, diCell);
1012 assert(cell && !cell->member.cell.prev_cell);
1013 if (tableDef->numCellsDefined < 1)
1015 /* 2000 twips appears to be the cell size that native richedit uses
1016 * when no cell sizes are specified. */
1017 const int defaultCellSize = 2000;
1018 int nRightBoundary = defaultCellSize;
1019 cell->member.cell.nRightBoundary = nRightBoundary;
1020 while (cell->member.cell.next_cell) {
1021 cell = cell->member.cell.next_cell;
1022 nRightBoundary += defaultCellSize;
1023 cell->member.cell.nRightBoundary = nRightBoundary;
1025 para = ME_InsertTableCellFromCursor(info->editor);
1026 cell = para->member.para.pCell;
1027 cell->member.cell.nRightBoundary = nRightBoundary;
1028 } else {
1029 for (i = 0; i < tableDef->numCellsDefined; i++)
1031 RTFCell *cellDef = &tableDef->cells[i];
1032 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1033 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1034 cellDef->border);
1035 cell = cell->member.cell.next_cell;
1036 if (!cell)
1038 para = ME_InsertTableCellFromCursor(info->editor);
1039 cell = para->member.para.pCell;
1042 /* Cell for table row delimiter is empty */
1043 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1046 run = ME_FindItemFwd(cell, diRun);
1047 if (info->editor->pCursors[0].pRun != run ||
1048 info->editor->pCursors[0].nOffset)
1050 int nOfs, nChars;
1051 /* Delete inserted cells that aren't defined. */
1052 info->editor->pCursors[1].pRun = run;
1053 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1054 info->editor->pCursors[1].nOffset = 0;
1055 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1056 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1057 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1058 nChars, TRUE);
1061 para = ME_InsertTableRowEndFromCursor(info->editor);
1062 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1063 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1064 ME_ApplyBorderProperties(info, &para->member.para.border,
1065 tableDef->border);
1066 info->nestingLevel--;
1067 if (!info->nestingLevel)
1069 if (info->canInheritInTbl) {
1070 tableDef->tableRowStart = para;
1071 } else {
1072 while (info->tableDef) {
1073 tableDef = info->tableDef;
1074 info->tableDef = tableDef->parent;
1075 heap_free(tableDef);
1078 } else {
1079 info->tableDef = tableDef->parent;
1080 heap_free(tableDef);
1082 } else { /* v1.0 - v3.0 */
1083 WCHAR endl = '\r';
1084 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1085 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1086 pFmt->dxOffset = info->tableDef->gapH;
1087 pFmt->dxStartIndent = info->tableDef->leftEdge;
1089 ME_ApplyBorderProperties(info, &para->member.para.border,
1090 tableDef->border);
1091 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1093 WCHAR tab = '\t';
1094 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1095 tableDef->numCellsInserted++;
1097 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1098 if (!tableDef->numCellsDefined)
1099 pFmt->wEffects &= ~PFE_TABLE;
1100 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1101 tableDef->numCellsInserted = 0;
1103 break;
1105 case rtfTab:
1106 case rtfPar:
1107 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1108 ME_DisplayItem *para;
1109 PARAFORMAT2 *pFmt;
1110 RTFFlushOutputBuffer(info);
1111 para = info->editor->pCursors[0].pPara;
1112 pFmt = para->member.para.pFmt;
1113 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1115 /* rtfPar is treated like a space within a table. */
1116 info->rtfClass = rtfText;
1117 info->rtfMajor = ' ';
1119 else if (info->rtfMinor == rtfPar && tableDef)
1120 tableDef->numCellsInserted = 0;
1122 break;
1126 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1127 const SIZEL* sz)
1129 LPOLEOBJECT lpObject = NULL;
1130 LPSTORAGE lpStorage = NULL;
1131 LPOLECLIENTSITE lpClientSite = NULL;
1132 LPDATAOBJECT lpDataObject = NULL;
1133 LPOLECACHE lpOleCache = NULL;
1134 STGMEDIUM stgm;
1135 FORMATETC fm;
1136 CLSID clsid;
1137 BOOL ret = FALSE;
1138 DWORD conn;
1140 if (hemf)
1142 stgm.tymed = TYMED_ENHMF;
1143 stgm.u.hEnhMetaFile = hemf;
1144 fm.cfFormat = CF_ENHMETAFILE;
1146 else if (hbmp)
1148 stgm.tymed = TYMED_GDI;
1149 stgm.u.hBitmap = hbmp;
1150 fm.cfFormat = CF_BITMAP;
1152 stgm.pUnkForRelease = NULL;
1154 fm.ptd = NULL;
1155 fm.dwAspect = DVASPECT_CONTENT;
1156 fm.lindex = -1;
1157 fm.tymed = stgm.tymed;
1159 if (!info->lpRichEditOle)
1161 CreateIRichEditOle(NULL, info->editor, (VOID**)&info->lpRichEditOle);
1164 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1165 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1166 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1167 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1168 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1169 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1170 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1171 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1173 REOBJECT reobject;
1175 reobject.cbStruct = sizeof(reobject);
1176 reobject.cp = REO_CP_SELECTION;
1177 reobject.clsid = clsid;
1178 reobject.poleobj = lpObject;
1179 reobject.pstg = lpStorage;
1180 reobject.polesite = lpClientSite;
1181 /* convert from twips to .01 mm */
1182 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1183 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1184 reobject.dvaspect = DVASPECT_CONTENT;
1185 reobject.dwFlags = 0; /* FIXME */
1186 reobject.dwUser = 0;
1188 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1189 ret = TRUE;
1192 if (lpObject) IOleObject_Release(lpObject);
1193 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1194 if (lpStorage) IStorage_Release(lpStorage);
1195 if (lpDataObject) IDataObject_Release(lpDataObject);
1196 if (lpOleCache) IOleCache_Release(lpOleCache);
1198 return ret;
1201 static void ME_RTFReadShpPictGroup( RTF_Info *info )
1203 int level = 1;
1205 for (;;)
1207 RTFGetToken (info);
1209 if (info->rtfClass == rtfEOF) return;
1210 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1212 if (--level == 0) break;
1214 else if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1216 level++;
1218 else
1220 RTFRouteToken( info );
1221 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1222 level--;
1226 RTFRouteToken( info ); /* feed "}" back to router */
1227 return;
1230 static DWORD read_hex_data( RTF_Info *info, BYTE **out )
1232 DWORD read = 0, size = 1024;
1233 BYTE *buf, val;
1234 BOOL flip;
1236 *out = NULL;
1238 if (info->rtfClass != rtfText)
1240 ERR("Called with incorrect token\n");
1241 return 0;
1244 buf = HeapAlloc( GetProcessHeap(), 0, size );
1245 if (!buf) return 0;
1247 val = info->rtfMajor;
1248 for (flip = TRUE;; flip = !flip)
1250 RTFGetToken( info );
1251 if (info->rtfClass == rtfEOF)
1253 HeapFree( GetProcessHeap(), 0, buf );
1254 return 0;
1256 if (info->rtfClass != rtfText) break;
1257 if (flip)
1259 if (read >= size)
1261 size *= 2;
1262 buf = HeapReAlloc( GetProcessHeap(), 0, buf, size );
1263 if (!buf) return 0;
1265 buf[read++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1267 else
1268 val = info->rtfMajor;
1270 if (flip) FIXME("wrong hex string\n");
1272 *out = buf;
1273 return read;
1276 static void ME_RTFReadPictGroup(RTF_Info *info)
1278 SIZEL sz;
1279 BYTE *buffer = NULL;
1280 DWORD size = 0;
1281 METAFILEPICT mfp;
1282 HENHMETAFILE hemf;
1283 HBITMAP hbmp;
1284 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1285 int level = 1;
1287 mfp.mm = MM_TEXT;
1288 sz.cx = sz.cy = 0;
1290 for (;;)
1292 RTFGetToken( info );
1294 if (info->rtfClass == rtfText)
1296 if (level == 1)
1298 if (!buffer)
1299 size = read_hex_data( info, &buffer );
1301 else
1303 RTFSkipGroup( info );
1305 } /* We potentially have a new token so fall through. */
1307 if (info->rtfClass == rtfEOF) return;
1309 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1311 if (--level == 0) break;
1312 continue;
1314 if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1316 level++;
1317 continue;
1319 if (!RTFCheckCM( info, rtfControl, rtfPictAttr ))
1321 RTFRouteToken( info );
1322 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1323 level--;
1324 continue;
1327 if (RTFCheckMM( info, rtfPictAttr, rtfWinMetafile ))
1329 mfp.mm = info->rtfParam;
1330 gfx = gfx_metafile;
1332 else if (RTFCheckMM( info, rtfPictAttr, rtfDevIndBitmap ))
1334 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1335 gfx = gfx_dib;
1337 else if (RTFCheckMM( info, rtfPictAttr, rtfEmfBlip ))
1338 gfx = gfx_enhmetafile;
1339 else if (RTFCheckMM( info, rtfPictAttr, rtfPicWid ))
1340 mfp.xExt = info->rtfParam;
1341 else if (RTFCheckMM( info, rtfPictAttr, rtfPicHt ))
1342 mfp.yExt = info->rtfParam;
1343 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalWid ))
1344 sz.cx = info->rtfParam;
1345 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalHt ))
1346 sz.cy = info->rtfParam;
1347 else
1348 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1351 if (buffer)
1353 switch (gfx)
1355 case gfx_enhmetafile:
1356 if ((hemf = SetEnhMetaFileBits( size, buffer )))
1357 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1358 break;
1359 case gfx_metafile:
1360 if ((hemf = SetWinMetaFileBits( size, buffer, NULL, &mfp )))
1361 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1362 break;
1363 case gfx_dib:
1365 BITMAPINFO *bi = (BITMAPINFO*)buffer;
1366 HDC hdc = GetDC(0);
1367 unsigned nc = bi->bmiHeader.biClrUsed;
1369 /* not quite right, especially for bitfields type of compression */
1370 if (!nc && bi->bmiHeader.biBitCount <= 8)
1371 nc = 1 << bi->bmiHeader.biBitCount;
1372 if ((hbmp = CreateDIBitmap( hdc, &bi->bmiHeader,
1373 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1374 bi, DIB_RGB_COLORS)) )
1375 ME_RTFInsertOleObject( info, NULL, hbmp, &sz );
1376 ReleaseDC( 0, hdc );
1377 break;
1379 default:
1380 break;
1383 HeapFree( GetProcessHeap(), 0, buffer );
1384 RTFRouteToken( info ); /* feed "}" back to router */
1385 return;
1388 /* for now, lookup the \result part and use it, whatever the object */
1389 static void ME_RTFReadObjectGroup(RTF_Info *info)
1391 for (;;)
1393 RTFGetToken (info);
1394 if (info->rtfClass == rtfEOF)
1395 return;
1396 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1397 break;
1398 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1400 RTFGetToken (info);
1401 if (info->rtfClass == rtfEOF)
1402 return;
1403 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1405 int level = 1;
1407 while (RTFGetToken (info) != rtfEOF)
1409 if (info->rtfClass == rtfGroup)
1411 if (info->rtfMajor == rtfBeginGroup) level++;
1412 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1414 RTFRouteToken(info);
1417 else RTFSkipGroup(info);
1418 continue;
1420 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1422 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1423 return;
1426 RTFRouteToken(info); /* feed "}" back to router */
1429 static void ME_RTFReadHook(RTF_Info *info)
1431 switch(info->rtfClass)
1433 case rtfGroup:
1434 switch(info->rtfMajor)
1436 case rtfBeginGroup:
1437 if (info->stackTop < maxStack) {
1438 info->stack[info->stackTop].style = info->style;
1439 ME_AddRefStyle(info->style);
1440 info->stack[info->stackTop].codePage = info->codePage;
1441 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1443 info->stackTop++;
1444 info->styleChanged = FALSE;
1445 break;
1446 case rtfEndGroup:
1448 RTFFlushOutputBuffer(info);
1449 info->stackTop--;
1450 if (info->stackTop <= 0)
1451 info->rtfClass = rtfEOF;
1452 if (info->stackTop < 0)
1453 return;
1455 ME_ReleaseStyle(info->style);
1456 info->style = info->stack[info->stackTop].style;
1457 info->codePage = info->stack[info->stackTop].codePage;
1458 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1459 break;
1462 break;
1466 void
1467 ME_StreamInFill(ME_InStream *stream)
1469 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1470 (BYTE *)stream->buffer,
1471 sizeof(stream->buffer),
1472 (LONG *)&stream->dwSize);
1473 stream->dwUsed = 0;
1476 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1478 RTF_Info parser;
1479 ME_Style *style;
1480 int from, to, nUndoMode;
1481 int nEventMask = editor->nEventMask;
1482 ME_InStream inStream;
1483 BOOL invalidRTF = FALSE;
1484 ME_Cursor *selStart, *selEnd;
1485 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1487 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1488 editor->nEventMask = 0;
1490 ME_GetSelectionOfs(editor, &from, &to);
1491 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1493 ME_GetSelection(editor, &selStart, &selEnd);
1494 style = ME_GetSelectionInsertStyle(editor);
1496 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1498 /* Don't insert text at the end of the table row */
1499 if (!editor->bEmulateVersion10) { /* v4.1 */
1500 ME_DisplayItem *para = editor->pCursors->pPara;
1501 if (para->member.para.nFlags & MEPF_ROWEND)
1503 para = para->member.para.next_para;
1504 editor->pCursors[0].pPara = para;
1505 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1506 editor->pCursors[0].nOffset = 0;
1508 if (para->member.para.nFlags & MEPF_ROWSTART)
1510 para = para->member.para.next_para;
1511 editor->pCursors[0].pPara = para;
1512 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1513 editor->pCursors[0].nOffset = 0;
1515 editor->pCursors[1] = editor->pCursors[0];
1516 } else { /* v1.0 - 3.0 */
1517 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1518 ME_IsInTable(editor->pCursors[0].pRun))
1519 return 0;
1521 } else {
1522 style = editor->pBuffer->pDefaultStyle;
1523 ME_AddRefStyle(style);
1524 ME_SetSelection(editor, 0, 0);
1525 ME_InternalDeleteText(editor, &editor->pCursors[1],
1526 ME_GetTextLength(editor), FALSE);
1527 from = to = 0;
1528 ME_ClearTempStyle(editor);
1529 ME_SetDefaultParaFormat(editor, editor->pCursors[0].pPara->member.para.pFmt);
1533 /* Back up undo mode to a local variable */
1534 nUndoMode = editor->nUndoMode;
1536 /* Only create an undo if SFF_SELECTION is set */
1537 if (!(format & SFF_SELECTION))
1538 editor->nUndoMode = umIgnore;
1540 inStream.editstream = stream;
1541 inStream.editstream->dwError = 0;
1542 inStream.dwSize = 0;
1543 inStream.dwUsed = 0;
1545 if (format & SF_RTF)
1547 /* Check if it's really RTF, and if it is not, use plain text */
1548 ME_StreamInFill(&inStream);
1549 if (!inStream.editstream->dwError)
1551 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1552 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1554 invalidRTF = TRUE;
1555 inStream.editstream->dwError = -16;
1560 if (!invalidRTF && !inStream.editstream->dwError)
1562 ME_Cursor start;
1563 from = ME_GetCursorOfs(&editor->pCursors[0]);
1564 if (format & SF_RTF) {
1566 /* setup the RTF parser */
1567 memset(&parser, 0, sizeof parser);
1568 RTFSetEditStream(&parser, &inStream);
1569 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1570 parser.editor = editor;
1571 parser.style = style;
1572 WriterInit(&parser);
1573 RTFInit(&parser);
1574 RTFSetReadHook(&parser, ME_RTFReadHook);
1575 RTFSetDestinationCallback(&parser, rtfShpPict, ME_RTFReadShpPictGroup);
1576 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1577 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1578 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1580 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1581 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1583 BeginFile(&parser);
1585 /* do the parsing */
1586 RTFRead(&parser);
1587 RTFFlushOutputBuffer(&parser);
1588 if (!editor->bEmulateVersion10) { /* v4.1 */
1589 if (parser.tableDef && parser.tableDef->tableRowStart &&
1590 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1592 /* Delete any incomplete table row at the end of the rich text. */
1593 int nOfs, nChars;
1594 ME_DisplayItem *para;
1596 parser.rtfMinor = rtfRow;
1597 /* Complete the table row before deleting it.
1598 * By doing it this way we will have the current paragraph format set
1599 * properly to reflect that is not in the complete table, and undo items
1600 * will be added for this change to the current paragraph format. */
1601 if (parser.nestingLevel > 0)
1603 while (parser.nestingLevel > 1)
1604 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1605 para = parser.tableDef->tableRowStart;
1606 ME_RTFSpecialCharHook(&parser);
1607 } else {
1608 para = parser.tableDef->tableRowStart;
1609 ME_RTFSpecialCharHook(&parser);
1610 assert(para->member.para.nFlags & MEPF_ROWEND);
1611 para = para->member.para.next_para;
1614 editor->pCursors[1].pPara = para;
1615 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1616 editor->pCursors[1].nOffset = 0;
1617 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1618 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1619 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1620 if (parser.tableDef)
1621 parser.tableDef->tableRowStart = NULL;
1624 ME_CheckTablesForCorruption(editor);
1625 RTFDestroy(&parser);
1626 if (parser.lpRichEditOle)
1627 IRichEditOle_Release(parser.lpRichEditOle);
1629 if (parser.stackTop > 0)
1631 while (--parser.stackTop >= 0)
1633 ME_ReleaseStyle(parser.style);
1634 parser.style = parser.stack[parser.stackTop].style;
1636 if (!inStream.editstream->dwError)
1637 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1640 /* Remove last line break, as mandated by tests. This is not affected by
1641 CR/LF counters, since RTF streaming presents only \para tokens, which
1642 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1644 if (stripLastCR && !(format & SFF_SELECTION)) {
1645 int newto;
1646 ME_GetSelection(editor, &selStart, &selEnd);
1647 newto = ME_GetCursorOfs(selEnd);
1648 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1649 WCHAR lastchar[3] = {'\0', '\0'};
1650 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1651 ME_Cursor linebreakCursor = *selEnd;
1653 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1654 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE, FALSE);
1655 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1656 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1660 to = ME_GetCursorOfs(&editor->pCursors[0]);
1661 num_read = to - from;
1663 style = parser.style;
1665 else if (format & SF_TEXT)
1667 num_read = ME_StreamInText(editor, format, &inStream, style);
1668 to = ME_GetCursorOfs(&editor->pCursors[0]);
1670 else
1671 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1672 /* put the cursor at the top */
1673 if (!(format & SFF_SELECTION))
1674 ME_SetSelection(editor, 0, 0);
1675 ME_CursorFromCharOfs(editor, from, &start);
1676 ME_UpdateLinkAttribute(editor, &start, to - from);
1679 /* Restore saved undo mode */
1680 editor->nUndoMode = nUndoMode;
1682 /* even if we didn't add an undo, we need to commit anything on the stack */
1683 ME_CommitUndo(editor);
1685 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1686 if (!(format & SFF_SELECTION))
1687 ME_EmptyUndoStack(editor);
1689 ME_ReleaseStyle(style);
1690 editor->nEventMask = nEventMask;
1691 ME_UpdateRepaint(editor, FALSE);
1692 if (!(format & SFF_SELECTION)) {
1693 ME_ClearTempStyle(editor);
1695 ITextHost_TxShowCaret(editor->texthost, FALSE);
1696 ME_MoveCaret(editor);
1697 ITextHost_TxShowCaret(editor->texthost, TRUE);
1698 ME_SendSelChange(editor);
1699 ME_SendRequestResize(editor, FALSE);
1701 return num_read;
1705 typedef struct tagME_RTFStringStreamStruct
1707 char *string;
1708 int pos;
1709 int length;
1710 } ME_RTFStringStreamStruct;
1712 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1714 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1715 int count;
1717 count = min(cb, pStruct->length - pStruct->pos);
1718 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1719 pStruct->pos += count;
1720 *pcb = count;
1721 return 0;
1724 static void
1725 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1727 EDITSTREAM es;
1728 ME_RTFStringStreamStruct data;
1730 data.string = string;
1731 data.length = strlen(string);
1732 data.pos = 0;
1733 es.dwCookie = (DWORD_PTR)&data;
1734 es.pfnCallback = ME_ReadFromRTFString;
1735 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, TRUE);
1739 static int
1740 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1742 const int nLen = lstrlenW(text);
1743 const int nTextLen = ME_GetTextLength(editor);
1744 int nMin, nMax;
1745 ME_Cursor cursor;
1746 WCHAR wLastChar = ' ';
1748 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1749 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1751 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1752 FIXME("Flags 0x%08x not implemented\n",
1753 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1755 nMin = chrg->cpMin;
1756 if (chrg->cpMax == -1)
1757 nMax = nTextLen;
1758 else
1759 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1761 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1762 if (editor->bEmulateVersion10 && nMax == nTextLen)
1764 flags |= FR_DOWN;
1767 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1768 if (editor->bEmulateVersion10 && nMax < nMin)
1770 if (chrgText)
1772 chrgText->cpMin = -1;
1773 chrgText->cpMax = -1;
1775 return -1;
1778 /* when searching up, if cpMin < cpMax, then instead of searching
1779 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1780 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1781 * case, it is always bigger than cpMin.
1783 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1785 int nSwap = nMax;
1787 nMax = nMin > nTextLen ? nTextLen : nMin;
1788 if (nMin < nSwap || chrg->cpMax == -1)
1789 nMin = 0;
1790 else
1791 nMin = nSwap;
1794 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1796 if (chrgText)
1797 chrgText->cpMin = chrgText->cpMax = -1;
1798 return -1;
1801 if (flags & FR_DOWN) /* Forward search */
1803 /* If possible, find the character before where the search starts */
1804 if ((flags & FR_WHOLEWORD) && nMin)
1806 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1807 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1808 ME_MoveCursorChars(editor, &cursor, 1);
1809 } else {
1810 ME_CursorFromCharOfs(editor, nMin, &cursor);
1813 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1815 ME_DisplayItem *pCurItem = cursor.pRun;
1816 int nCurStart = cursor.nOffset;
1817 int nMatched = 0;
1819 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1821 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1822 break;
1824 nMatched++;
1825 if (nMatched == nLen)
1827 ME_DisplayItem *pNextItem = pCurItem;
1828 int nNextStart = nCurStart;
1829 WCHAR wNextChar;
1831 /* Check to see if next character is a whitespace */
1832 if (flags & FR_WHOLEWORD)
1834 if (nCurStart + nMatched == pCurItem->member.run.len)
1836 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1837 nNextStart = -nMatched;
1840 if (pNextItem)
1841 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1842 else
1843 wNextChar = ' ';
1845 if (isalnumW(wNextChar))
1846 break;
1849 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1850 if (chrgText)
1852 chrgText->cpMin = cursor.nOffset;
1853 chrgText->cpMax = cursor.nOffset + nLen;
1855 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1856 return cursor.nOffset;
1858 if (nCurStart + nMatched == pCurItem->member.run.len)
1860 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1861 nCurStart = -nMatched;
1864 if (pCurItem)
1865 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1866 else
1867 wLastChar = ' ';
1869 cursor.nOffset++;
1870 if (cursor.nOffset == cursor.pRun->member.run.len)
1872 ME_NextRun(&cursor.pPara, &cursor.pRun, TRUE);
1873 cursor.nOffset = 0;
1877 else /* Backward search */
1879 /* If possible, find the character after where the search ends */
1880 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1882 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1883 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1884 ME_MoveCursorChars(editor, &cursor, -1);
1885 } else {
1886 ME_CursorFromCharOfs(editor, nMax, &cursor);
1889 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1891 ME_DisplayItem *pCurItem = cursor.pRun;
1892 ME_DisplayItem *pCurPara = cursor.pPara;
1893 int nCurEnd = cursor.nOffset;
1894 int nMatched = 0;
1896 if (nCurEnd == 0)
1898 ME_PrevRun(&pCurPara, &pCurItem, TRUE);
1899 nCurEnd = pCurItem->member.run.len;
1902 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1903 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1905 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1906 break;
1908 nMatched++;
1909 if (nMatched == nLen)
1911 ME_DisplayItem *pPrevItem = pCurItem;
1912 int nPrevEnd = nCurEnd;
1913 WCHAR wPrevChar;
1914 int nStart;
1916 /* Check to see if previous character is a whitespace */
1917 if (flags & FR_WHOLEWORD)
1919 if (nPrevEnd - nMatched == 0)
1921 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1922 if (pPrevItem)
1923 nPrevEnd = pPrevItem->member.run.len + nMatched;
1926 if (pPrevItem)
1927 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1928 else
1929 wPrevChar = ' ';
1931 if (isalnumW(wPrevChar))
1932 break;
1935 nStart = pCurPara->member.para.nCharOfs
1936 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1937 if (chrgText)
1939 chrgText->cpMin = nStart;
1940 chrgText->cpMax = nStart + nLen;
1942 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1943 return nStart;
1945 if (nCurEnd - nMatched == 0)
1947 ME_PrevRun(&pCurPara, &pCurItem, TRUE);
1948 /* Don't care about pCurItem becoming NULL here; it's already taken
1949 * care of in the exterior loop condition */
1950 nCurEnd = pCurItem->member.run.len + nMatched;
1953 if (pCurItem)
1954 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1955 else
1956 wLastChar = ' ';
1958 cursor.nOffset--;
1959 if (cursor.nOffset < 0)
1961 ME_PrevRun(&cursor.pPara, &cursor.pRun, TRUE);
1962 cursor.nOffset = cursor.pRun->member.run.len;
1966 TRACE("not found\n");
1967 if (chrgText)
1968 chrgText->cpMin = chrgText->cpMax = -1;
1969 return -1;
1972 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1974 int nChars;
1975 ME_Cursor start;
1977 if (!ex->cb || !pText) return 0;
1979 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1980 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1982 if (ex->flags & GT_SELECTION)
1984 int from, to;
1985 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1986 start = editor->pCursors[nStartCur];
1987 nChars = to - from;
1989 else
1991 ME_SetCursorToStart(editor, &start);
1992 nChars = INT_MAX;
1994 if (ex->codepage == CP_UNICODE)
1996 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1997 &start, nChars, ex->flags & GT_USECRLF, FALSE);
1999 else
2001 /* potentially each char may be a CR, why calculate the exact value with O(N) when
2002 we can just take a bigger buffer? :)
2003 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2004 occurs only in richedit 2.0 mode, in which line breaks have only one CR
2006 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2007 DWORD buflen;
2008 LPWSTR buffer;
2009 LRESULT rc;
2011 buflen = min(crlfmul * nChars, ex->cb - 1);
2012 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
2014 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF, FALSE);
2015 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
2016 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2017 if (rc) rc--; /* do not count 0 terminator */
2019 heap_free(buffer);
2020 return rc;
2024 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2025 const ME_Cursor *start, int nLen, BOOL unicode)
2027 if (!strText) return 0;
2028 if (unicode) {
2029 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE, FALSE);
2030 } else {
2031 int nChars;
2032 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2033 if (!p) return 0;
2034 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE, FALSE);
2035 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2036 nLen+1, NULL, NULL);
2037 FREE_OBJ(p);
2038 return nChars;
2042 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2044 int end;
2046 TRACE("%d - %d\n", to, from );
2048 ME_InvalidateSelection( editor );
2049 end = ME_SetSelection( editor, to, from );
2050 ME_InvalidateSelection( editor );
2051 ITextHost_TxShowCaret( editor->texthost, FALSE );
2052 ME_ShowCaret( editor );
2053 ME_SendSelChange( editor );
2055 return end;
2058 typedef struct tagME_GlobalDestStruct
2060 HGLOBAL hData;
2061 int nLength;
2062 } ME_GlobalDestStruct;
2064 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2066 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2067 int i;
2068 WORD *pSrc, *pDest;
2070 cb = cb >> 1;
2071 pDest = (WORD *)lpBuff;
2072 pSrc = GlobalLock(pData->hData);
2073 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2074 pDest[i] = pSrc[pData->nLength+i];
2076 pData->nLength += i;
2077 *pcb = 2*i;
2078 GlobalUnlock(pData->hData);
2079 return 0;
2082 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2084 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2085 int i;
2086 BYTE *pSrc, *pDest;
2088 pDest = lpBuff;
2089 pSrc = GlobalLock(pData->hData);
2090 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2091 pDest[i] = pSrc[pData->nLength+i];
2093 pData->nLength += i;
2094 *pcb = i;
2095 GlobalUnlock(pData->hData);
2096 return 0;
2099 static BOOL ME_Paste(ME_TextEditor *editor)
2101 DWORD dwFormat = 0;
2102 EDITSTREAM es;
2103 ME_GlobalDestStruct gds;
2104 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2105 UINT cf = 0;
2107 if (IsClipboardFormatAvailable(nRTFFormat))
2108 cf = nRTFFormat, dwFormat = SF_RTF;
2109 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2110 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2111 else
2112 return FALSE;
2114 if (!OpenClipboard(editor->hWnd))
2115 return FALSE;
2116 gds.hData = GetClipboardData(cf);
2117 gds.nLength = 0;
2118 es.dwCookie = (DWORD_PTR)&gds;
2119 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2120 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2122 CloseClipboard();
2123 return TRUE;
2126 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2128 LPDATAOBJECT dataObj = NULL;
2129 HRESULT hr = S_OK;
2131 if (editor->cPasswordMask)
2132 return FALSE; /* Copying or Cutting masked text isn't allowed */
2134 if(editor->lpOleCallback)
2136 CHARRANGE range;
2137 range.cpMin = ME_GetCursorOfs(start);
2138 range.cpMax = range.cpMin + nChars;
2139 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2141 if(FAILED(hr) || !dataObj)
2142 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2143 if(SUCCEEDED(hr)) {
2144 hr = OleSetClipboard(dataObj);
2145 IDataObject_Release(dataObj);
2147 return SUCCEEDED(hr);
2150 /* helper to send a msg filter notification */
2151 static BOOL
2152 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2154 MSGFILTER msgf;
2156 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2157 msgf.nmhdr.hwndFrom = editor->hWnd;
2158 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2159 msgf.nmhdr.code = EN_MSGFILTER;
2160 msgf.msg = msg;
2161 msgf.wParam = *wParam;
2162 msgf.lParam = *lParam;
2163 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2164 return FALSE;
2165 *wParam = msgf.wParam;
2166 *lParam = msgf.lParam;
2167 msgf.wParam = *wParam;
2169 return TRUE;
2172 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2174 ME_DisplayItem *startPara, *endPara;
2175 ME_DisplayItem *prev_para;
2176 ME_Cursor *from, *to;
2177 ME_Cursor start;
2178 int nChars;
2180 if (!editor->AutoURLDetect_bEnable) return;
2182 ME_GetSelection(editor, &from, &to);
2184 /* Find paragraph previous to the one that contains start cursor */
2185 startPara = from->pPara;
2186 prev_para = startPara->member.para.prev_para;
2187 if (prev_para->type == diParagraph) startPara = prev_para;
2189 /* Find paragraph that contains end cursor */
2190 endPara = to->pPara->member.para.next_para;
2192 start.pPara = startPara;
2193 start.pRun = ME_FindItemFwd(startPara, diRun);
2194 start.nOffset = 0;
2195 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2197 ME_UpdateLinkAttribute(editor, &start, nChars);
2200 static BOOL
2201 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2203 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2204 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2206 if (editor->bMouseCaptured)
2207 return FALSE;
2208 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2209 editor->nSelectionType = stPosition;
2211 switch (nKey)
2213 case VK_LEFT:
2214 case VK_RIGHT:
2215 case VK_HOME:
2216 case VK_END:
2217 editor->nUDArrowX = -1;
2218 /* fall through */
2219 case VK_UP:
2220 case VK_DOWN:
2221 case VK_PRIOR:
2222 case VK_NEXT:
2223 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2224 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2225 return TRUE;
2226 case VK_BACK:
2227 case VK_DELETE:
2228 editor->nUDArrowX = -1;
2229 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2230 if (editor->styleFlags & ES_READONLY)
2231 return FALSE;
2232 if (ME_IsSelection(editor))
2234 ME_DeleteSelection(editor);
2235 ME_CommitUndo(editor);
2237 else if (nKey == VK_DELETE)
2239 /* Delete stops group typing.
2240 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2241 ME_DeleteTextAtCursor(editor, 1, 1);
2242 ME_CommitUndo(editor);
2244 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2246 BOOL bDeletionSucceeded;
2247 /* Backspace can be grouped for a single undo */
2248 ME_ContinueCoalescingTransaction(editor);
2249 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2250 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2251 /* Deletion was prevented so the cursor is moved back to where it was.
2252 * (e.g. this happens when trying to delete cell boundaries)
2254 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2256 ME_CommitCoalescingUndo(editor);
2258 else
2259 return TRUE;
2260 ME_MoveCursorFromTableRowStartParagraph(editor);
2261 ME_UpdateSelectionLinkAttribute(editor);
2262 ME_UpdateRepaint(editor, FALSE);
2263 ME_SendRequestResize(editor, FALSE);
2264 return TRUE;
2265 case VK_RETURN:
2266 if (editor->bDialogMode)
2268 if (ctrl_is_down)
2269 return TRUE;
2271 if (!(editor->styleFlags & ES_WANTRETURN))
2273 if (editor->hwndParent)
2275 DWORD dw;
2276 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2277 if (HIWORD(dw) == DC_HASDEFID)
2279 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2280 if (hwDefCtrl)
2282 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2283 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2287 return TRUE;
2291 if (editor->styleFlags & ES_MULTILINE)
2293 ME_Cursor cursor = editor->pCursors[0];
2294 ME_DisplayItem *para = cursor.pPara;
2295 int from, to;
2296 const WCHAR endl = '\r';
2297 const WCHAR endlv10[] = {'\r','\n'};
2298 ME_Style *style;
2300 if (editor->styleFlags & ES_READONLY) {
2301 MessageBeep(MB_ICONERROR);
2302 return TRUE;
2305 ME_GetSelectionOfs(editor, &from, &to);
2306 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2308 if (!editor->bEmulateVersion10) { /* v4.1 */
2309 if (para->member.para.nFlags & MEPF_ROWEND) {
2310 /* Add a new table row after this row. */
2311 para = ME_AppendTableRow(editor, para);
2312 para = para->member.para.next_para;
2313 editor->pCursors[0].pPara = para;
2314 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2315 editor->pCursors[0].nOffset = 0;
2316 editor->pCursors[1] = editor->pCursors[0];
2317 ME_CommitUndo(editor);
2318 ME_CheckTablesForCorruption(editor);
2319 ME_UpdateRepaint(editor, FALSE);
2320 return TRUE;
2322 else if (para == editor->pCursors[1].pPara &&
2323 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2324 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2325 !para->member.para.prev_para->member.para.nCharOfs)
2327 /* Insert a newline before the table. */
2328 para = para->member.para.prev_para;
2329 para->member.para.nFlags &= ~MEPF_ROWSTART;
2330 editor->pCursors[0].pPara = para;
2331 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2332 editor->pCursors[1] = editor->pCursors[0];
2333 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2334 editor->pCursors[0].pRun->member.run.style);
2335 para = editor->pBuffer->pFirst->member.para.next_para;
2336 ME_SetDefaultParaFormat(editor, para->member.para.pFmt);
2337 para->member.para.nFlags = MEPF_REWRAP;
2338 editor->pCursors[0].pPara = para;
2339 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2340 editor->pCursors[1] = editor->pCursors[0];
2341 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2342 ME_CommitCoalescingUndo(editor);
2343 ME_CheckTablesForCorruption(editor);
2344 ME_UpdateRepaint(editor, FALSE);
2345 return TRUE;
2347 } else { /* v1.0 - 3.0 */
2348 ME_DisplayItem *para = cursor.pPara;
2349 if (ME_IsInTable(para))
2351 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2353 if (from == to) {
2354 ME_ContinueCoalescingTransaction(editor);
2355 para = ME_AppendTableRow(editor, para);
2356 editor->pCursors[0].pPara = para;
2357 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2358 editor->pCursors[0].nOffset = 0;
2359 editor->pCursors[1] = editor->pCursors[0];
2360 ME_CommitCoalescingUndo(editor);
2361 ME_UpdateRepaint(editor, FALSE);
2362 return TRUE;
2364 } else {
2365 ME_ContinueCoalescingTransaction(editor);
2366 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2367 !ME_IsInTable(para->member.para.prev_para))
2369 /* Insert newline before table */
2370 cursor.pRun = ME_FindItemBack(para, diRun);
2371 if (cursor.pRun) {
2372 editor->pCursors[0].pRun = cursor.pRun;
2373 editor->pCursors[0].pPara = para->member.para.prev_para;
2375 editor->pCursors[0].nOffset = 0;
2376 editor->pCursors[1] = editor->pCursors[0];
2377 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2378 editor->pCursors[0].pRun->member.run.style);
2379 } else {
2380 editor->pCursors[1] = editor->pCursors[0];
2381 para = ME_AppendTableRow(editor, para);
2382 editor->pCursors[0].pPara = para;
2383 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2384 editor->pCursors[0].nOffset = 0;
2385 editor->pCursors[1] = editor->pCursors[0];
2387 ME_CommitCoalescingUndo(editor);
2388 ME_UpdateRepaint(editor, FALSE);
2389 return TRUE;
2394 style = ME_GetInsertStyle(editor, 0);
2395 ME_SaveTempStyle(editor);
2396 ME_ContinueCoalescingTransaction(editor);
2397 if (shift_is_down)
2398 ME_InsertEndRowFromCursor(editor, 0);
2399 else
2400 if (!editor->bEmulateVersion10)
2401 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2402 else
2403 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2404 ME_ReleaseStyle(style);
2405 ME_CommitCoalescingUndo(editor);
2406 SetCursor(NULL);
2408 ME_UpdateSelectionLinkAttribute(editor);
2409 ME_UpdateRepaint(editor, FALSE);
2411 return TRUE;
2413 break;
2414 case VK_ESCAPE:
2415 if (editor->bDialogMode && editor->hwndParent)
2416 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2417 return TRUE;
2418 case VK_TAB:
2419 if (editor->bDialogMode && editor->hwndParent)
2420 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2421 return TRUE;
2422 case 'A':
2423 if (ctrl_is_down)
2425 handle_EM_EXSETSEL( editor, 0, -1 );
2426 return TRUE;
2428 break;
2429 case 'V':
2430 if (ctrl_is_down)
2431 return ME_Paste(editor);
2432 break;
2433 case 'C':
2434 case 'X':
2435 if (ctrl_is_down)
2437 BOOL result;
2438 int nOfs, nChars;
2439 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2440 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2442 nChars -= nOfs;
2443 result = ME_Copy(editor, selStart, nChars);
2444 if (result && nKey == 'X')
2446 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2447 ME_CommitUndo(editor);
2448 ME_UpdateRepaint(editor, TRUE);
2450 return result;
2452 break;
2453 case 'Z':
2454 if (ctrl_is_down)
2456 ME_Undo(editor);
2457 return TRUE;
2459 break;
2460 case 'Y':
2461 if (ctrl_is_down)
2463 ME_Redo(editor);
2464 return TRUE;
2466 break;
2468 default:
2469 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2470 editor->nUDArrowX = -1;
2471 if (ctrl_is_down)
2473 if (nKey == 'W')
2475 CHARFORMAT2W chf;
2476 char buf[2048];
2477 chf.cbSize = sizeof(chf);
2479 ME_GetSelectionCharFormat(editor, &chf);
2480 ME_DumpStyleToBuf(&chf, buf);
2481 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2483 if (nKey == 'Q')
2485 ME_CheckCharOffsets(editor);
2489 return FALSE;
2492 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2493 LPARAM flags, BOOL unicode)
2495 WCHAR wstr;
2497 if (editor->bMouseCaptured)
2498 return 0;
2500 if (unicode)
2501 wstr = (WCHAR)charCode;
2502 else
2504 CHAR charA = charCode;
2505 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2508 if (editor->styleFlags & ES_READONLY) {
2509 MessageBeep(MB_ICONERROR);
2510 return 0; /* FIXME really 0 ? */
2513 if ((unsigned)wstr >= ' ' || wstr == '\t')
2515 ME_Cursor cursor = editor->pCursors[0];
2516 ME_DisplayItem *para = cursor.pPara;
2517 int from, to;
2518 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2519 ME_GetSelectionOfs(editor, &from, &to);
2520 if (wstr == '\t' &&
2521 /* v4.1 allows tabs to be inserted with ctrl key down */
2522 !(ctrl_is_down && !editor->bEmulateVersion10))
2524 ME_DisplayItem *para;
2525 BOOL bSelectedRow = FALSE;
2527 para = cursor.pPara;
2528 if (ME_IsSelection(editor) &&
2529 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2530 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2531 para->member.para.prev_para->type == diParagraph)
2533 para = para->member.para.prev_para;
2534 bSelectedRow = TRUE;
2536 if (ME_IsInTable(para))
2538 ME_TabPressedInTable(editor, bSelectedRow);
2539 ME_CommitUndo(editor);
2540 return 0;
2542 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2543 if (para->member.para.nFlags & MEPF_ROWEND) {
2544 if (from == to) {
2545 para = para->member.para.next_para;
2546 if (para->member.para.nFlags & MEPF_ROWSTART)
2547 para = para->member.para.next_para;
2548 editor->pCursors[0].pPara = para;
2549 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2550 editor->pCursors[0].nOffset = 0;
2551 editor->pCursors[1] = editor->pCursors[0];
2554 } else { /* v1.0 - 3.0 */
2555 if (ME_IsInTable(cursor.pRun) &&
2556 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2557 from == to)
2559 /* Text should not be inserted at the end of the table. */
2560 MessageBeep(-1);
2561 return 0;
2564 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2565 /* WM_CHAR is restricted to nTextLimit */
2566 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2568 ME_Style *style = ME_GetInsertStyle(editor, 0);
2569 ME_SaveTempStyle(editor);
2570 ME_ContinueCoalescingTransaction(editor);
2571 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2572 ME_ReleaseStyle(style);
2573 ME_CommitCoalescingUndo(editor);
2574 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2577 ME_UpdateSelectionLinkAttribute(editor);
2578 ME_UpdateRepaint(editor, FALSE);
2580 return 0;
2583 /* Process the message and calculate the new click count.
2585 * returns: The click count if it is mouse down event, else returns 0. */
2586 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2587 LPARAM lParam)
2589 static int clickNum = 0;
2590 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2591 return 0;
2593 if ((msg == WM_LBUTTONDBLCLK) ||
2594 (msg == WM_RBUTTONDBLCLK) ||
2595 (msg == WM_MBUTTONDBLCLK) ||
2596 (msg == WM_XBUTTONDBLCLK))
2598 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2601 if ((msg == WM_LBUTTONDOWN) ||
2602 (msg == WM_RBUTTONDOWN) ||
2603 (msg == WM_MBUTTONDOWN) ||
2604 (msg == WM_XBUTTONDOWN))
2606 static MSG prevClickMsg;
2607 MSG clickMsg;
2608 /* Compare the editor instead of the hwnd so that the this
2609 * can still be done for windowless richedit controls. */
2610 clickMsg.hwnd = (HWND)editor;
2611 clickMsg.message = msg;
2612 clickMsg.wParam = wParam;
2613 clickMsg.lParam = lParam;
2614 clickMsg.time = GetMessageTime();
2615 clickMsg.pt.x = (short)LOWORD(lParam);
2616 clickMsg.pt.y = (short)HIWORD(lParam);
2617 if ((clickNum != 0) &&
2618 (clickMsg.message == prevClickMsg.message) &&
2619 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2620 (clickMsg.wParam == prevClickMsg.wParam) &&
2621 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2622 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2623 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2625 clickNum++;
2626 } else {
2627 clickNum = 1;
2629 prevClickMsg = clickMsg;
2630 } else {
2631 return 0;
2633 return clickNum;
2636 static BOOL is_link( ME_Run *run )
2638 return (run->style->fmt.dwMask & CFM_LINK) && (run->style->fmt.dwEffects & CFE_LINK);
2641 static BOOL ME_SetCursor(ME_TextEditor *editor)
2643 ME_Cursor cursor;
2644 POINT pt;
2645 BOOL isExact;
2646 SCROLLBARINFO sbi;
2647 DWORD messagePos = GetMessagePos();
2648 pt.x = (short)LOWORD(messagePos);
2649 pt.y = (short)HIWORD(messagePos);
2651 if (editor->hWnd)
2653 sbi.cbSize = sizeof(sbi);
2654 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2655 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2656 PtInRect(&sbi.rcScrollBar, pt))
2658 ITextHost_TxSetCursor(editor->texthost,
2659 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2660 return TRUE;
2662 sbi.cbSize = sizeof(sbi);
2663 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2664 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2665 PtInRect(&sbi.rcScrollBar, pt))
2667 ITextHost_TxSetCursor(editor->texthost,
2668 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2669 return TRUE;
2672 ITextHost_TxScreenToClient(editor->texthost, &pt);
2674 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2675 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2676 return TRUE;
2678 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2679 pt.y < editor->rcFormat.top &&
2680 pt.x < editor->rcFormat.left)
2682 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2683 return TRUE;
2685 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2687 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2688 ITextHost_TxSetCursor(editor->texthost,
2689 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2690 else /* v4.1 */
2691 ITextHost_TxSetCursor(editor->texthost,
2692 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2693 return TRUE;
2695 if (pt.x < editor->rcFormat.left)
2697 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2698 return TRUE;
2700 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2701 if (isExact)
2703 ME_Run *run;
2705 run = &cursor.pRun->member.run;
2706 if (is_link( run ))
2708 ITextHost_TxSetCursor(editor->texthost,
2709 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2710 FALSE);
2711 return TRUE;
2714 if (ME_IsSelection(editor))
2716 int selStart, selEnd;
2717 int offset = ME_GetCursorOfs(&cursor);
2719 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2720 if (selStart <= offset && selEnd >= offset) {
2721 ITextHost_TxSetCursor(editor->texthost,
2722 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2723 FALSE);
2724 return TRUE;
2728 ITextHost_TxSetCursor(editor->texthost,
2729 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2730 return TRUE;
2733 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2735 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2736 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2737 editor->rcFormat.left += 1 + editor->selofs;
2738 editor->rcFormat.right -= 1;
2741 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2743 CHARRANGE selrange;
2744 HMENU menu;
2745 int seltype = 0;
2746 if(!editor->lpOleCallback || !editor->hWnd)
2747 return FALSE;
2748 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2749 if(selrange.cpMin == selrange.cpMax)
2750 seltype |= SEL_EMPTY;
2751 else
2753 /* FIXME: Handle objects */
2754 seltype |= SEL_TEXT;
2755 if(selrange.cpMax-selrange.cpMin > 1)
2756 seltype |= SEL_MULTICHAR;
2758 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2760 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2761 DestroyMenu(menu);
2763 return TRUE;
2766 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10, DWORD csStyle)
2768 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2769 int i;
2770 DWORD props;
2771 LONG selbarwidth;
2773 ed->hWnd = NULL;
2774 ed->hwndParent = NULL;
2775 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2776 ed->texthost = texthost;
2777 ed->reOle = NULL;
2778 ed->bEmulateVersion10 = bEmulateVersion10;
2779 ed->styleFlags = 0;
2780 ed->alignStyle = PFA_LEFT;
2781 if (csStyle & ES_RIGHT)
2782 ed->alignStyle = PFA_RIGHT;
2783 if (csStyle & ES_CENTER)
2784 ed->alignStyle = PFA_CENTER;
2785 ITextHost_TxGetPropertyBits(texthost,
2786 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2787 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2788 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2789 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2790 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2791 &props);
2792 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2793 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2794 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2795 ed->pBuffer = ME_MakeText();
2796 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2797 ed->nAvailWidth = 0; /* wrap to client area */
2798 ME_MakeFirstParagraph(ed);
2799 /* The four cursors are for:
2800 * 0 - The position where the caret is shown
2801 * 1 - The anchored end of the selection (for normal selection)
2802 * 2 & 3 - The anchored start and end respectively for word, line,
2803 * or paragraph selection.
2805 ed->nCursors = 4;
2806 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2807 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2808 ed->pCursors[1] = ed->pCursors[0];
2809 ed->pCursors[2] = ed->pCursors[0];
2810 ed->pCursors[3] = ed->pCursors[1];
2811 ed->nLastTotalLength = ed->nTotalLength = 0;
2812 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2813 ed->nUDArrowX = -1;
2814 ed->rgbBackColor = -1;
2815 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2816 ed->bCaretAtEnd = FALSE;
2817 ed->nEventMask = 0;
2818 ed->nModifyStep = 0;
2819 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2820 list_init( &ed->undo_stack );
2821 list_init( &ed->redo_stack );
2822 ed->nUndoStackSize = 0;
2823 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2824 ed->nUndoMode = umAddToUndo;
2825 ed->nParagraphs = 1;
2826 ed->nLastSelStart = ed->nLastSelEnd = 0;
2827 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2828 ed->bHideSelection = FALSE;
2829 ed->pfnWordBreak = NULL;
2830 ed->lpOleCallback = NULL;
2831 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2832 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2833 ed->AutoURLDetect_bEnable = FALSE;
2834 ed->bHaveFocus = FALSE;
2835 ed->bDialogMode = FALSE;
2836 ed->bMouseCaptured = FALSE;
2837 for (i=0; i<HFONT_CACHE_SIZE; i++)
2839 ed->pFontCache[i].nRefs = 0;
2840 ed->pFontCache[i].nAge = 0;
2841 ed->pFontCache[i].hFont = NULL;
2844 ME_CheckCharOffsets(ed);
2845 ed->bDefaultFormatRect = TRUE;
2846 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2847 if (selbarwidth) {
2848 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2849 ed->selofs = SELECTIONBAR_WIDTH;
2850 ed->styleFlags |= ES_SELECTIONBAR;
2851 } else {
2852 ed->selofs = 0;
2854 ed->nSelectionType = stPosition;
2856 ed->cPasswordMask = 0;
2857 if (props & TXTBIT_USEPASSWORD)
2858 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2860 if (props & TXTBIT_AUTOWORDSEL)
2861 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2862 if (props & TXTBIT_MULTILINE) {
2863 ed->styleFlags |= ES_MULTILINE;
2864 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2865 } else {
2866 ed->bWordWrap = FALSE;
2868 if (props & TXTBIT_READONLY)
2869 ed->styleFlags |= ES_READONLY;
2870 if (!(props & TXTBIT_HIDESELECTION))
2871 ed->styleFlags |= ES_NOHIDESEL;
2872 if (props & TXTBIT_SAVESELECTION)
2873 ed->styleFlags |= ES_SAVESEL;
2874 if (props & TXTBIT_VERTICAL)
2875 ed->styleFlags |= ES_VERTICAL;
2876 if (props & TXTBIT_DISABLEDRAG)
2877 ed->styleFlags |= ES_NOOLEDRAGDROP;
2879 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2881 /* Default scrollbar information */
2882 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2883 ed->vert_si.nMin = 0;
2884 ed->vert_si.nMax = 0;
2885 ed->vert_si.nPage = 0;
2886 ed->vert_si.nPos = 0;
2888 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2889 ed->horz_si.nMin = 0;
2890 ed->horz_si.nMax = 0;
2891 ed->horz_si.nPage = 0;
2892 ed->horz_si.nPos = 0;
2894 ed->wheel_remain = 0;
2896 list_init( &ed->style_list );
2897 OleInitialize(NULL);
2899 return ed;
2902 void ME_DestroyEditor(ME_TextEditor *editor)
2904 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2905 ME_DisplayItem *p = pFirst, *pNext = NULL;
2906 ME_Style *s, *cursor2;
2907 int i;
2909 ME_ClearTempStyle(editor);
2910 ME_EmptyUndoStack(editor);
2911 while(p) {
2912 pNext = p->next;
2913 ME_DestroyDisplayItem(p);
2914 p = pNext;
2917 LIST_FOR_EACH_ENTRY_SAFE( s, cursor2, &editor->style_list, ME_Style, entry )
2918 ME_DestroyStyle( s );
2920 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2921 for (i=0; i<HFONT_CACHE_SIZE; i++)
2923 if (editor->pFontCache[i].hFont)
2924 DeleteObject(editor->pFontCache[i].hFont);
2926 if (editor->rgbBackColor != -1)
2927 DeleteObject(editor->hbrBackground);
2928 if(editor->lpOleCallback)
2929 IRichEditOleCallback_Release(editor->lpOleCallback);
2930 ITextHost_Release(editor->texthost);
2931 if (editor->reOle)
2933 IRichEditOle_Release(editor->reOle);
2934 editor->reOle = NULL;
2936 OleUninitialize();
2938 FREE_OBJ(editor->pBuffer);
2939 FREE_OBJ(editor->pCursors);
2941 FREE_OBJ(editor);
2944 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2946 TRACE("\n");
2947 switch (fdwReason)
2949 case DLL_PROCESS_ATTACH:
2950 DisableThreadLibraryCalls(hinstDLL);
2951 me_heap = HeapCreate (0, 0x10000, 0);
2952 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2953 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2954 LookupInit();
2955 break;
2957 case DLL_PROCESS_DETACH:
2958 if (lpvReserved) break;
2959 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2960 UnregisterClassW(MSFTEDIT_CLASS, 0);
2961 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2962 UnregisterClassA("RichEdit50A", 0);
2963 if (ME_ListBoxRegistered)
2964 UnregisterClassW(REListBox20W, 0);
2965 if (ME_ComboBoxRegistered)
2966 UnregisterClassW(REComboBox20W, 0);
2967 LookupCleanup();
2968 HeapDestroy (me_heap);
2969 release_typelib();
2970 break;
2972 return TRUE;
2975 static inline int get_default_line_height( ME_TextEditor *editor )
2977 int height = 0;
2979 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2980 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2981 if (height <= 0) height = 24;
2983 return height;
2986 static inline int calc_wheel_change( int *remain, int amount_per_click )
2988 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2989 *remain -= WHEEL_DELTA * change / amount_per_click;
2990 return change;
2993 static const char * const edit_messages[] = {
2994 "EM_GETSEL",
2995 "EM_SETSEL",
2996 "EM_GETRECT",
2997 "EM_SETRECT",
2998 "EM_SETRECTNP",
2999 "EM_SCROLL",
3000 "EM_LINESCROLL",
3001 "EM_SCROLLCARET",
3002 "EM_GETMODIFY",
3003 "EM_SETMODIFY",
3004 "EM_GETLINECOUNT",
3005 "EM_LINEINDEX",
3006 "EM_SETHANDLE",
3007 "EM_GETHANDLE",
3008 "EM_GETTHUMB",
3009 "EM_UNKNOWN_BF",
3010 "EM_UNKNOWN_C0",
3011 "EM_LINELENGTH",
3012 "EM_REPLACESEL",
3013 "EM_UNKNOWN_C3",
3014 "EM_GETLINE",
3015 "EM_LIMITTEXT",
3016 "EM_CANUNDO",
3017 "EM_UNDO",
3018 "EM_FMTLINES",
3019 "EM_LINEFROMCHAR",
3020 "EM_UNKNOWN_CA",
3021 "EM_SETTABSTOPS",
3022 "EM_SETPASSWORDCHAR",
3023 "EM_EMPTYUNDOBUFFER",
3024 "EM_GETFIRSTVISIBLELINE",
3025 "EM_SETREADONLY",
3026 "EM_SETWORDBREAKPROC",
3027 "EM_GETWORDBREAKPROC",
3028 "EM_GETPASSWORDCHAR",
3029 "EM_SETMARGINS",
3030 "EM_GETMARGINS",
3031 "EM_GETLIMITTEXT",
3032 "EM_POSFROMCHAR",
3033 "EM_CHARFROMPOS",
3034 "EM_SETIMESTATUS",
3035 "EM_GETIMESTATUS"
3038 static const char * const richedit_messages[] = {
3039 "EM_CANPASTE",
3040 "EM_DISPLAYBAND",
3041 "EM_EXGETSEL",
3042 "EM_EXLIMITTEXT",
3043 "EM_EXLINEFROMCHAR",
3044 "EM_EXSETSEL",
3045 "EM_FINDTEXT",
3046 "EM_FORMATRANGE",
3047 "EM_GETCHARFORMAT",
3048 "EM_GETEVENTMASK",
3049 "EM_GETOLEINTERFACE",
3050 "EM_GETPARAFORMAT",
3051 "EM_GETSELTEXT",
3052 "EM_HIDESELECTION",
3053 "EM_PASTESPECIAL",
3054 "EM_REQUESTRESIZE",
3055 "EM_SELECTIONTYPE",
3056 "EM_SETBKGNDCOLOR",
3057 "EM_SETCHARFORMAT",
3058 "EM_SETEVENTMASK",
3059 "EM_SETOLECALLBACK",
3060 "EM_SETPARAFORMAT",
3061 "EM_SETTARGETDEVICE",
3062 "EM_STREAMIN",
3063 "EM_STREAMOUT",
3064 "EM_GETTEXTRANGE",
3065 "EM_FINDWORDBREAK",
3066 "EM_SETOPTIONS",
3067 "EM_GETOPTIONS",
3068 "EM_FINDTEXTEX",
3069 "EM_GETWORDBREAKPROCEX",
3070 "EM_SETWORDBREAKPROCEX",
3071 "EM_SETUNDOLIMIT",
3072 "EM_UNKNOWN_USER_83",
3073 "EM_REDO",
3074 "EM_CANREDO",
3075 "EM_GETUNDONAME",
3076 "EM_GETREDONAME",
3077 "EM_STOPGROUPTYPING",
3078 "EM_SETTEXTMODE",
3079 "EM_GETTEXTMODE",
3080 "EM_AUTOURLDETECT",
3081 "EM_GETAUTOURLDETECT",
3082 "EM_SETPALETTE",
3083 "EM_GETTEXTEX",
3084 "EM_GETTEXTLENGTHEX",
3085 "EM_SHOWSCROLLBAR",
3086 "EM_SETTEXTEX",
3087 "EM_UNKNOWN_USER_98",
3088 "EM_UNKNOWN_USER_99",
3089 "EM_SETPUNCTUATION",
3090 "EM_GETPUNCTUATION",
3091 "EM_SETWORDWRAPMODE",
3092 "EM_GETWORDWRAPMODE",
3093 "EM_SETIMECOLOR",
3094 "EM_GETIMECOLOR",
3095 "EM_SETIMEOPTIONS",
3096 "EM_GETIMEOPTIONS",
3097 "EM_CONVPOSITION",
3098 "EM_UNKNOWN_USER_109",
3099 "EM_UNKNOWN_USER_110",
3100 "EM_UNKNOWN_USER_111",
3101 "EM_UNKNOWN_USER_112",
3102 "EM_UNKNOWN_USER_113",
3103 "EM_UNKNOWN_USER_114",
3104 "EM_UNKNOWN_USER_115",
3105 "EM_UNKNOWN_USER_116",
3106 "EM_UNKNOWN_USER_117",
3107 "EM_UNKNOWN_USER_118",
3108 "EM_UNKNOWN_USER_119",
3109 "EM_SETLANGOPTIONS",
3110 "EM_GETLANGOPTIONS",
3111 "EM_GETIMECOMPMODE",
3112 "EM_FINDTEXTW",
3113 "EM_FINDTEXTEXW",
3114 "EM_RECONVERSION",
3115 "EM_SETIMEMODEBIAS",
3116 "EM_GETIMEMODEBIAS"
3119 static const char *
3120 get_msg_name(UINT msg)
3122 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3123 return edit_messages[msg - EM_GETSEL];
3124 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3125 return richedit_messages[msg - EM_CANPASTE];
3126 return "";
3129 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3131 int x,y;
3132 BOOL isExact;
3133 ME_Cursor cursor; /* The start of the clicked text. */
3135 ENLINK info;
3136 x = (short)LOWORD(lParam);
3137 y = (short)HIWORD(lParam);
3138 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3139 if (!isExact) return;
3141 if (is_link( &cursor.pRun->member.run ))
3142 { /* The clicked run has CFE_LINK set */
3143 ME_DisplayItem *di;
3145 info.nmhdr.hwndFrom = NULL;
3146 info.nmhdr.idFrom = 0;
3147 info.nmhdr.code = EN_LINK;
3148 info.msg = msg;
3149 info.wParam = wParam;
3150 info.lParam = lParam;
3151 cursor.nOffset = 0;
3153 /* find the first contiguous run with CFE_LINK set */
3154 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3155 di = cursor.pRun;
3156 while (ME_PrevRun( NULL, &di, FALSE ) && is_link( &di->member.run ))
3157 info.chrg.cpMin -= di->member.run.len;
3159 /* find the last contiguous run with CFE_LINK set */
3160 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3161 di = cursor.pRun;
3162 while (ME_NextRun( NULL, &di, FALSE ) && is_link( &di->member.run ))
3163 info.chrg.cpMax += di->member.run.len;
3165 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3169 void ME_ReplaceSel(ME_TextEditor *editor, BOOL can_undo, const WCHAR *str, int len)
3171 int from, to, nStartCursor;
3172 ME_Style *style;
3174 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3175 style = ME_GetSelectionInsertStyle(editor);
3176 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3177 ME_InsertTextFromCursor(editor, 0, str, len, style);
3178 ME_ReleaseStyle(style);
3179 /* drop temporary style if line end */
3181 * FIXME question: does abc\n mean: put abc,
3182 * clear temp style, put \n? (would require a change)
3184 if (len>0 && str[len-1] == '\n')
3185 ME_ClearTempStyle(editor);
3186 ME_CommitUndo(editor);
3187 ME_UpdateSelectionLinkAttribute(editor);
3188 if (!can_undo)
3189 ME_EmptyUndoStack(editor);
3190 ME_UpdateRepaint(editor, FALSE);
3193 static void ME_SetText(ME_TextEditor *editor, void *text, BOOL unicode)
3195 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3196 int textLen;
3198 LPWSTR wszText = ME_ToUnicode(codepage, text, &textLen);
3200 if (textLen > 0)
3202 int len = -1;
3204 /* uses default style! */
3205 if (!(editor->styleFlags & ES_MULTILINE))
3207 WCHAR *p = wszText;
3209 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3210 len = p - wszText;
3212 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3214 ME_EndToUnicode(codepage, wszText);
3217 static LRESULT ME_WmCreate(ME_TextEditor *editor, LPARAM lParam, BOOL unicode)
3219 CREATESTRUCTW *createW = (CREATESTRUCTW*)lParam;
3220 CREATESTRUCTA *createA = (CREATESTRUCTA*)lParam;
3221 void *text = NULL;
3222 INT max;
3224 if (lParam)
3225 text = unicode ? (void*)createW->lpszName : (void*)createA->lpszName;
3227 ME_SetDefaultFormatRect(editor);
3229 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3230 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3231 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3233 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3234 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3236 if (editor->styleFlags & ES_DISABLENOSCROLL)
3238 if (editor->styleFlags & WS_VSCROLL)
3240 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3241 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3243 if (editor->styleFlags & WS_HSCROLL)
3245 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3246 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3250 if (text)
3252 ME_SetText(editor, text, unicode);
3253 ME_SetCursorToStart(editor, &editor->pCursors[0]);
3254 ME_SetCursorToStart(editor, &editor->pCursors[1]);
3257 ME_CommitUndo(editor);
3258 ME_WrapMarkedParagraphs(editor);
3259 ME_MoveCaret(editor);
3260 return 0;
3264 #define UNSUPPORTED_MSG(e) \
3265 case e: \
3266 FIXME(#e ": stub\n"); \
3267 *phresult = S_FALSE; \
3268 return 0;
3270 /* Handle messages for windowless and windowed richedit controls.
3272 * The LRESULT that is returned is a return value for window procs,
3273 * and the phresult parameter is the COM return code needed by the
3274 * text services interface. */
3275 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3276 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3278 *phresult = S_OK;
3280 switch(msg) {
3282 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3283 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3284 UNSUPPORTED_MSG(EM_FMTLINES)
3285 UNSUPPORTED_MSG(EM_FORMATRANGE)
3286 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3287 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3288 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3289 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3290 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3291 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3292 UNSUPPORTED_MSG(EM_GETREDONAME)
3293 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3294 UNSUPPORTED_MSG(EM_GETUNDONAME)
3295 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3296 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3297 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3298 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3299 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3300 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3301 UNSUPPORTED_MSG(EM_SETMARGINS)
3302 UNSUPPORTED_MSG(EM_SETPALETTE)
3303 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3304 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3305 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3307 /* Messages specific to Richedit controls */
3309 case EM_STREAMIN:
3310 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3311 case EM_STREAMOUT:
3312 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3313 case WM_GETDLGCODE:
3315 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3317 if (lParam)
3318 editor->bDialogMode = TRUE;
3319 if (editor->styleFlags & ES_MULTILINE)
3320 code |= DLGC_WANTMESSAGE;
3321 if (!(editor->styleFlags & ES_SAVESEL))
3322 code |= DLGC_HASSETSEL;
3323 return code;
3325 case EM_EMPTYUNDOBUFFER:
3326 ME_EmptyUndoStack(editor);
3327 return 0;
3328 case EM_GETSEL:
3330 /* Note: wParam/lParam can be NULL */
3331 UINT from, to;
3332 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3333 PUINT pto = lParam ? (PUINT)lParam : &to;
3334 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3335 if ((*pfrom|*pto) & 0xFFFF0000)
3336 return -1;
3337 return MAKELONG(*pfrom,*pto);
3339 case EM_EXGETSEL:
3341 CHARRANGE *pRange = (CHARRANGE *)lParam;
3342 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3343 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3344 return 0;
3346 case EM_SETUNDOLIMIT:
3348 if ((int)wParam < 0)
3349 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3350 else
3351 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3352 /* Setting a max stack size keeps wine from getting killed
3353 for hogging memory. Windows allocates all this memory at once, so
3354 no program would realistically set a value above our maximum. */
3355 return editor->nUndoLimit;
3357 case EM_CANUNDO:
3358 return !list_empty( &editor->undo_stack );
3359 case EM_CANREDO:
3360 return !list_empty( &editor->redo_stack );
3361 case WM_UNDO: /* FIXME: actually not the same */
3362 case EM_UNDO:
3363 return ME_Undo(editor);
3364 case EM_REDO:
3365 return ME_Redo(editor);
3366 case EM_GETOPTIONS:
3368 /* these flags are equivalent to the ES_* counterparts */
3369 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3370 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3371 DWORD settings = editor->styleFlags & mask;
3373 return settings;
3375 case EM_SETFONTSIZE:
3377 CHARFORMAT2W cf;
3378 LONG tmp_size, size;
3379 BOOL is_increase = ((LONG)wParam > 0);
3381 if (editor->mode & TM_PLAINTEXT)
3382 return FALSE;
3384 cf.cbSize = sizeof(cf);
3385 cf.dwMask = CFM_SIZE;
3386 ME_GetSelectionCharFormat(editor, &cf);
3387 tmp_size = (cf.yHeight / 20) + wParam;
3389 if (tmp_size <= 1)
3390 size = 1;
3391 else if (tmp_size > 12 && tmp_size < 28 && tmp_size % 2)
3392 size = tmp_size + (is_increase ? 1 : -1);
3393 else if (tmp_size > 28 && tmp_size < 36)
3394 size = is_increase ? 36 : 28;
3395 else if (tmp_size > 36 && tmp_size < 48)
3396 size = is_increase ? 48 : 36;
3397 else if (tmp_size > 48 && tmp_size < 72)
3398 size = is_increase ? 72 : 48;
3399 else if (tmp_size > 72 && tmp_size < 80)
3400 size = is_increase ? 80 : 72;
3401 else if (tmp_size > 80 && tmp_size < 1638)
3402 size = 10 * (is_increase ? (tmp_size / 10 + 1) : (tmp_size / 10));
3403 else if (tmp_size >= 1638)
3404 size = 1638;
3405 else
3406 size = tmp_size;
3408 cf.yHeight = size * 20; /* convert twips to points */
3409 ME_SetSelectionCharFormat(editor, &cf);
3410 ME_CommitUndo(editor);
3411 ME_WrapMarkedParagraphs(editor);
3412 ME_UpdateScrollBar(editor);
3413 ME_Repaint(editor);
3415 return TRUE;
3417 case EM_SETOPTIONS:
3419 /* these flags are equivalent to ES_* counterparts, except for
3420 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3421 * but is still stored in editor->styleFlags. */
3422 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3423 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3424 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3425 DWORD settings = mask & editor->styleFlags;
3426 DWORD oldSettings = settings;
3427 DWORD changedSettings;
3429 switch(wParam)
3431 case ECOOP_SET:
3432 settings = lParam;
3433 break;
3434 case ECOOP_OR:
3435 settings |= lParam;
3436 break;
3437 case ECOOP_AND:
3438 settings &= lParam;
3439 break;
3440 case ECOOP_XOR:
3441 settings ^= lParam;
3443 changedSettings = oldSettings ^ settings;
3445 if (changedSettings) {
3446 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3448 if (changedSettings & ECO_SELECTIONBAR)
3450 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3451 if (settings & ECO_SELECTIONBAR) {
3452 assert(!editor->selofs);
3453 editor->selofs = SELECTIONBAR_WIDTH;
3454 editor->rcFormat.left += editor->selofs;
3455 } else {
3456 editor->rcFormat.left -= editor->selofs;
3457 editor->selofs = 0;
3459 ME_RewrapRepaint(editor);
3462 if ((changedSettings & settings & ES_NOHIDESEL) && !editor->bHaveFocus)
3463 ME_InvalidateSelection( editor );
3465 if (changedSettings & settings & ECO_VERTICAL)
3466 FIXME("ECO_VERTICAL not implemented yet!\n");
3467 if (changedSettings & settings & ECO_AUTOHSCROLL)
3468 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3469 if (changedSettings & settings & ECO_AUTOVSCROLL)
3470 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3471 if (changedSettings & settings & ECO_WANTRETURN)
3472 FIXME("ECO_WANTRETURN not implemented yet!\n");
3473 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3474 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3477 return settings;
3479 case EM_SETSEL:
3481 return handle_EM_EXSETSEL( editor, wParam, lParam );
3483 case EM_SETSCROLLPOS:
3485 POINT *point = (POINT *)lParam;
3486 ME_ScrollAbs(editor, point->x, point->y);
3487 return 0;
3489 case EM_AUTOURLDETECT:
3491 if (wParam==1 || wParam ==0)
3493 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3494 return 0;
3496 return E_INVALIDARG;
3498 case EM_GETAUTOURLDETECT:
3500 return editor->AutoURLDetect_bEnable;
3502 case EM_EXSETSEL:
3504 CHARRANGE range = *(CHARRANGE *)lParam;
3506 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3508 case EM_SHOWSCROLLBAR:
3510 DWORD flags;
3512 switch (wParam)
3514 case SB_HORZ:
3515 flags = WS_HSCROLL;
3516 break;
3517 case SB_VERT:
3518 flags = WS_VSCROLL;
3519 break;
3520 case SB_BOTH:
3521 flags = WS_HSCROLL|WS_VSCROLL;
3522 break;
3523 default:
3524 return 0;
3527 if (lParam) {
3528 editor->styleFlags |= flags;
3529 if (flags & WS_HSCROLL)
3530 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3531 editor->nTotalWidth > editor->sizeWindow.cx);
3532 if (flags & WS_VSCROLL)
3533 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3534 editor->nTotalLength > editor->sizeWindow.cy);
3535 } else {
3536 editor->styleFlags &= ~flags;
3537 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3539 return 0;
3541 case EM_SETTEXTEX:
3543 LPWSTR wszText;
3544 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3545 int from, to, len;
3546 ME_Style *style;
3547 BOOL bRtf, bUnicode, bSelection, bUTF8;
3548 int oldModify = editor->nModifyStep;
3549 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3551 if (!pStruct) return 0;
3553 /* If we detect ascii rtf at the start of the string,
3554 * we know it isn't unicode. */
3555 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3556 !strncmp((char *)lParam, "{\\urtf", 6)));
3557 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3558 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3560 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3561 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3562 pStruct->flags, pStruct->codepage);
3564 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3565 if (bSelection) {
3566 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3567 style = ME_GetSelectionInsertStyle(editor);
3568 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3569 } else {
3570 ME_Cursor start;
3571 ME_SetCursorToStart(editor, &start);
3572 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3573 style = editor->pBuffer->pDefaultStyle;
3576 if (bRtf) {
3577 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3578 if (bSelection) {
3579 /* FIXME: The length returned doesn't include the rtf control
3580 * characters, only the actual text. */
3581 len = lParam ? strlen((char *)lParam) : 0;
3583 } else {
3584 if (bUTF8 && !bUnicode) {
3585 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3586 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3587 ME_EndToUnicode(CP_UTF8, wszText);
3588 } else {
3589 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3590 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3591 ME_EndToUnicode(pStruct->codepage, wszText);
3595 if (bSelection) {
3596 ME_ReleaseStyle(style);
3597 ME_UpdateSelectionLinkAttribute(editor);
3598 } else {
3599 ME_Cursor cursor;
3600 len = 1;
3601 ME_SetCursorToStart(editor, &cursor);
3602 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3604 ME_CommitUndo(editor);
3605 if (!(pStruct->flags & ST_KEEPUNDO))
3607 editor->nModifyStep = oldModify;
3608 ME_EmptyUndoStack(editor);
3610 ME_UpdateRepaint(editor, FALSE);
3611 return len;
3613 case EM_SETBKGNDCOLOR:
3615 LRESULT lColor;
3616 if (editor->rgbBackColor != -1) {
3617 DeleteObject(editor->hbrBackground);
3618 lColor = editor->rgbBackColor;
3620 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3622 if (wParam)
3624 editor->rgbBackColor = -1;
3625 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3627 else
3629 editor->rgbBackColor = lParam;
3630 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3632 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3633 return lColor;
3635 case EM_GETMODIFY:
3636 return editor->nModifyStep == 0 ? 0 : -1;
3637 case EM_SETMODIFY:
3639 if (wParam)
3640 editor->nModifyStep = 1;
3641 else
3642 editor->nModifyStep = 0;
3644 return 0;
3646 case EM_SETREADONLY:
3648 if (wParam)
3649 editor->styleFlags |= ES_READONLY;
3650 else
3651 editor->styleFlags &= ~ES_READONLY;
3652 return 1;
3654 case EM_SETEVENTMASK:
3656 DWORD nOldMask = editor->nEventMask;
3658 editor->nEventMask = lParam;
3659 return nOldMask;
3661 case EM_GETEVENTMASK:
3662 return editor->nEventMask;
3663 case EM_SETCHARFORMAT:
3665 CHARFORMAT2W buf, *p;
3666 BOOL bRepaint = TRUE;
3667 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3668 if (p == NULL) return 0;
3669 if (wParam & SCF_ALL) {
3670 if (editor->mode & TM_PLAINTEXT) {
3671 ME_SetDefaultCharFormat(editor, p);
3672 } else {
3673 ME_Cursor start;
3674 ME_SetCursorToStart(editor, &start);
3675 ME_SetCharFormat(editor, &start, NULL, p);
3676 editor->nModifyStep = 1;
3678 } else if (wParam & SCF_SELECTION) {
3679 if (editor->mode & TM_PLAINTEXT)
3680 return 0;
3681 if (wParam & SCF_WORD) {
3682 ME_Cursor start;
3683 ME_Cursor end = editor->pCursors[0];
3684 ME_MoveCursorWords(editor, &end, +1);
3685 start = end;
3686 ME_MoveCursorWords(editor, &start, -1);
3687 ME_SetCharFormat(editor, &start, &end, p);
3689 bRepaint = ME_IsSelection(editor);
3690 ME_SetSelectionCharFormat(editor, p);
3691 if (bRepaint) editor->nModifyStep = 1;
3692 } else { /* SCF_DEFAULT */
3693 ME_SetDefaultCharFormat(editor, p);
3695 ME_CommitUndo(editor);
3696 if (bRepaint)
3698 ME_WrapMarkedParagraphs(editor);
3699 ME_UpdateScrollBar(editor);
3700 ME_Repaint(editor);
3702 return 1;
3704 case EM_GETCHARFORMAT:
3706 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3707 if (dst->cbSize != sizeof(CHARFORMATA) &&
3708 dst->cbSize != sizeof(CHARFORMATW) &&
3709 dst->cbSize != sizeof(CHARFORMAT2A) &&
3710 dst->cbSize != sizeof(CHARFORMAT2W))
3711 return 0;
3712 tmp.cbSize = sizeof(tmp);
3713 if (!wParam)
3714 ME_GetDefaultCharFormat(editor, &tmp);
3715 else
3716 ME_GetSelectionCharFormat(editor, &tmp);
3717 ME_CopyToCFAny(dst, &tmp);
3718 return tmp.dwMask;
3720 case EM_SETPARAFORMAT:
3722 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3723 ME_WrapMarkedParagraphs(editor);
3724 ME_UpdateScrollBar(editor);
3725 ME_Repaint(editor);
3726 ME_CommitUndo(editor);
3727 return result;
3729 case EM_GETPARAFORMAT:
3730 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3731 return ((PARAFORMAT2 *)lParam)->dwMask;
3732 case EM_GETFIRSTVISIBLELINE:
3734 ME_DisplayItem *p = editor->pBuffer->pFirst;
3735 int y = editor->vert_si.nPos;
3736 int ypara = 0;
3737 int count = 0;
3738 int ystart, yend;
3739 while(p) {
3740 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3741 if (p->type == diTextEnd)
3742 break;
3743 if (p->type == diParagraph) {
3744 ypara = p->member.para.pt.y;
3745 continue;
3747 ystart = ypara + p->member.row.pt.y;
3748 yend = ystart + p->member.row.nHeight;
3749 if (y < yend) {
3750 break;
3752 count++;
3754 return count;
3756 case EM_HIDESELECTION:
3758 editor->bHideSelection = (wParam != 0);
3759 ME_InvalidateSelection(editor);
3760 return 0;
3762 case EM_LINESCROLL:
3764 if (!(editor->styleFlags & ES_MULTILINE))
3765 return FALSE;
3766 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3767 return TRUE;
3769 case WM_CLEAR:
3771 int from, to;
3772 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3773 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3774 ME_CommitUndo(editor);
3775 ME_UpdateRepaint(editor, TRUE);
3776 return 0;
3778 case EM_REPLACESEL:
3780 int len = 0;
3781 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3782 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3784 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3786 ME_ReplaceSel(editor, !!wParam, wszText, len);
3787 ME_EndToUnicode(codepage, wszText);
3788 return len;
3790 case EM_SCROLLCARET:
3791 ME_EnsureVisible(editor, &editor->pCursors[0]);
3792 return 0;
3793 case WM_SETFONT:
3795 LOGFONTW lf;
3796 CHARFORMAT2W fmt;
3797 HDC hDC;
3798 BOOL bRepaint = LOWORD(lParam);
3800 if (!wParam)
3801 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3803 if (!GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf))
3804 return 0;
3806 hDC = ITextHost_TxGetDC(editor->texthost);
3807 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3808 ITextHost_TxReleaseDC(editor->texthost, hDC);
3809 if (editor->mode & TM_RICHTEXT) {
3810 ME_Cursor start;
3811 ME_SetCursorToStart(editor, &start);
3812 ME_SetCharFormat(editor, &start, NULL, &fmt);
3814 ME_SetDefaultCharFormat(editor, &fmt);
3816 ME_CommitUndo(editor);
3817 ME_MarkAllForWrapping(editor);
3818 ME_WrapMarkedParagraphs(editor);
3819 ME_UpdateScrollBar(editor);
3820 if (bRepaint)
3821 ME_Repaint(editor);
3822 return 0;
3824 case WM_SETTEXT:
3826 ME_Cursor cursor;
3827 ME_SetCursorToStart(editor, &cursor);
3828 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3829 if (lParam)
3831 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3832 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3833 !strncmp((char *)lParam, "{\\urtf", 6))
3835 /* Undocumented: WM_SETTEXT supports RTF text */
3836 ME_StreamInRTFString(editor, 0, (char *)lParam);
3838 else
3839 ME_SetText(editor, (void*)lParam, unicode);
3841 else
3842 TRACE("WM_SETTEXT - NULL\n");
3843 ME_SetCursorToStart(editor, &cursor);
3844 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3845 ME_SetSelection(editor, 0, 0);
3846 editor->nModifyStep = 0;
3847 ME_CommitUndo(editor);
3848 ME_EmptyUndoStack(editor);
3849 ME_UpdateRepaint(editor, FALSE);
3850 return 1;
3852 case EM_CANPASTE:
3854 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3855 if (IsClipboardFormatAvailable(nRTFFormat))
3856 return TRUE;
3857 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3858 return TRUE;
3859 return FALSE;
3861 case WM_PASTE:
3862 case WM_MBUTTONDOWN:
3863 ME_Paste(editor);
3864 return 0;
3865 case WM_CUT:
3866 case WM_COPY:
3868 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3869 int nChars = nTo - nFrom;
3870 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3872 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3874 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3875 ME_CommitUndo(editor);
3876 ME_UpdateRepaint(editor, TRUE);
3878 return 0;
3880 case WM_GETTEXTLENGTH:
3882 GETTEXTLENGTHEX how;
3884 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3885 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3886 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3887 return ME_GetTextLengthEx(editor, &how);
3889 case EM_GETTEXTLENGTHEX:
3890 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3891 case WM_GETTEXT:
3893 GETTEXTEX ex;
3894 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3895 ex.flags = GT_USECRLF;
3896 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3897 ex.lpDefaultChar = NULL;
3898 ex.lpUsedDefChar = NULL;
3899 return ME_GetTextEx(editor, &ex, lParam);
3901 case EM_GETTEXTEX:
3902 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3903 case EM_GETSELTEXT:
3905 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3906 ME_Cursor *from = &editor->pCursors[nStartCur];
3907 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3908 nTo - nFrom, unicode);
3910 case EM_GETSCROLLPOS:
3912 POINT *point = (POINT *)lParam;
3913 point->x = editor->horz_si.nPos;
3914 point->y = editor->vert_si.nPos;
3915 /* 16-bit scaled value is returned as stored in scrollinfo */
3916 if (editor->horz_si.nMax > 0xffff)
3917 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3918 if (editor->vert_si.nMax > 0xffff)
3919 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3920 return 1;
3922 case EM_GETTEXTRANGE:
3924 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3925 ME_Cursor start;
3926 int nStart = rng->chrg.cpMin;
3927 int nEnd = rng->chrg.cpMax;
3928 int textlength = ME_GetTextLength(editor);
3930 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3931 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3932 if (nStart < 0) return 0;
3933 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3934 nEnd = textlength;
3935 if (nStart >= nEnd) return 0;
3937 ME_CursorFromCharOfs(editor, nStart, &start);
3938 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3940 case EM_GETLINE:
3942 ME_DisplayItem *run;
3943 const unsigned int nMaxChars = *(WORD *) lParam;
3944 unsigned int nCharsLeft = nMaxChars;
3945 char *dest = (char *) lParam;
3946 BOOL wroteNull = FALSE;
3948 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3949 unicode ? "Unicode" : "Ansi");
3951 run = ME_FindRowWithNumber(editor, wParam);
3952 if (run == NULL)
3953 return 0;
3955 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3956 && run->type == diRun)
3958 WCHAR *str = get_text( &run->member.run, 0 );
3959 unsigned int nCopy;
3961 nCopy = min(nCharsLeft, run->member.run.len);
3963 if (unicode)
3964 memcpy(dest, str, nCopy * sizeof(WCHAR));
3965 else
3966 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3967 nCharsLeft, NULL, NULL);
3968 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3969 nCharsLeft -= nCopy;
3972 /* append line termination, space allowing */
3973 if (nCharsLeft > 0)
3975 if (unicode)
3976 *((WCHAR *)dest) = '\0';
3977 else
3978 *dest = '\0';
3979 nCharsLeft--;
3980 wroteNull = TRUE;
3983 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3984 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3986 case EM_GETLINECOUNT:
3988 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3989 int nRows = 0;
3991 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3993 while (item != editor->pBuffer->pLast)
3995 assert(item->type == diParagraph);
3996 prev_para = ME_FindItemBack(item, diRun);
3997 if (prev_para) {
3998 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
4000 nRows += item->member.para.nRows;
4001 item = item->member.para.next_para;
4003 last_para = ME_FindItemBack(item, diRun);
4004 assert(last_para);
4005 assert(last_para->member.run.nFlags & MERF_ENDPARA);
4006 if (editor->bEmulateVersion10 && prev_para &&
4007 last_para->member.run.nCharOfs == 0 &&
4008 prev_para->member.run.len == 1 &&
4009 *get_text( &prev_para->member.run, 0 ) == '\r')
4011 /* In 1.0 emulation, the last solitary \r at the very end of the text
4012 (if one exists) is NOT a line break.
4013 FIXME: this is an ugly hack. This should have a more regular model. */
4014 nRows--;
4017 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
4018 return max(1, nRows);
4020 case EM_LINEFROMCHAR:
4022 if (wParam == -1)
4023 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4024 else
4025 return ME_RowNumberFromCharOfs(editor, wParam);
4027 case EM_EXLINEFROMCHAR:
4029 if (lParam == -1)
4030 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4031 else
4032 return ME_RowNumberFromCharOfs(editor, lParam);
4034 case EM_LINEINDEX:
4036 ME_DisplayItem *item, *para;
4037 int nCharOfs;
4039 if (wParam == -1)
4040 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
4041 else
4042 item = ME_FindRowWithNumber(editor, wParam);
4043 if (!item)
4044 return -1;
4045 para = ME_GetParagraph(item);
4046 item = ME_FindItemFwd(item, diRun);
4047 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
4048 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
4049 return nCharOfs;
4051 case EM_LINELENGTH:
4053 ME_DisplayItem *item, *item_end;
4054 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
4055 ME_DisplayItem *para, *run;
4057 if (wParam > ME_GetTextLength(editor))
4058 return 0;
4059 if (wParam == -1)
4061 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
4062 return 0;
4064 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
4065 item = ME_RowStart(run);
4066 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
4067 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
4068 if (item_end->type == diStartRow) {
4069 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
4070 } else {
4071 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
4072 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
4073 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
4075 nChars = nNextLineOfs - nThisLineOfs;
4076 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
4077 return nChars;
4079 case EM_EXLIMITTEXT:
4081 if ((int)lParam < 0)
4082 return 0;
4083 if (lParam == 0)
4084 editor->nTextLimit = 65536;
4085 else
4086 editor->nTextLimit = (int) lParam;
4087 return 0;
4089 case EM_LIMITTEXT:
4091 if (wParam == 0)
4092 editor->nTextLimit = 65536;
4093 else
4094 editor->nTextLimit = (int) wParam;
4095 return 0;
4097 case EM_GETLIMITTEXT:
4099 return editor->nTextLimit;
4101 case EM_FINDTEXT:
4103 LRESULT r;
4104 if(!unicode){
4105 FINDTEXTA *ft = (FINDTEXTA *)lParam;
4106 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
4107 WCHAR *tmp;
4109 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4110 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
4111 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
4112 FREE_OBJ( tmp );
4113 }else{
4114 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4115 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4117 return r;
4119 case EM_FINDTEXTEX:
4121 LRESULT r;
4122 if(!unicode){
4123 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
4124 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
4125 WCHAR *tmp;
4127 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4128 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
4129 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
4130 FREE_OBJ( tmp );
4131 }else{
4132 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4133 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4135 return r;
4137 case EM_FINDTEXTW:
4139 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4140 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4142 case EM_FINDTEXTEXW:
4144 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4145 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4147 case EM_GETZOOM:
4148 if (!wParam || !lParam)
4149 return FALSE;
4150 *(int *)wParam = editor->nZoomNumerator;
4151 *(int *)lParam = editor->nZoomDenominator;
4152 return TRUE;
4153 case EM_SETZOOM:
4154 return ME_SetZoom(editor, wParam, lParam);
4155 case EM_CHARFROMPOS:
4157 ME_Cursor cursor;
4158 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4159 &cursor, NULL))
4160 return ME_GetCursorOfs(&cursor);
4161 else
4162 return -1;
4164 case EM_POSFROMCHAR:
4166 ME_DisplayItem *pPara, *pRun;
4167 int nCharOfs, nOffset, nLength;
4168 POINTL pt = {0,0};
4170 nCharOfs = wParam;
4171 /* detect which API version we're dealing with */
4172 if (wParam >= 0x40000)
4173 nCharOfs = lParam;
4174 nLength = ME_GetTextLength(editor);
4175 nCharOfs = min(nCharOfs, nLength);
4176 nCharOfs = max(nCharOfs, 0);
4178 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4179 assert(pRun->type == diRun);
4180 pt.y = pRun->member.run.pt.y;
4181 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4182 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4183 pt.x += editor->rcFormat.left;
4185 pt.x -= editor->horz_si.nPos;
4186 pt.y -= editor->vert_si.nPos;
4188 if (wParam >= 0x40000) {
4189 *(POINTL *)wParam = pt;
4191 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4193 case WM_CREATE:
4194 return ME_WmCreate(editor, lParam, unicode);
4195 case WM_DESTROY:
4196 ME_DestroyEditor(editor);
4197 return 0;
4198 case WM_SETCURSOR:
4200 POINT cursor_pos;
4201 if (wParam == (WPARAM)editor->hWnd && GetCursorPos(&cursor_pos) &&
4202 ScreenToClient(editor->hWnd, &cursor_pos))
4203 ME_LinkNotify(editor, msg, 0, MAKELPARAM(cursor_pos.x, cursor_pos.y));
4204 return ME_SetCursor(editor);
4206 case WM_LBUTTONDBLCLK:
4207 case WM_LBUTTONDOWN:
4209 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4210 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4211 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4212 return 0;
4213 ITextHost_TxSetFocus(editor->texthost);
4214 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4215 ME_CalculateClickCount(editor, msg, wParam, lParam));
4216 ITextHost_TxSetCapture(editor->texthost, TRUE);
4217 editor->bMouseCaptured = TRUE;
4218 ME_LinkNotify(editor, msg, wParam, lParam);
4219 if (!ME_SetCursor(editor)) goto do_default;
4220 break;
4222 case WM_MOUSEMOVE:
4223 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4224 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4225 return 0;
4226 if (editor->bMouseCaptured)
4227 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4228 else
4229 ME_LinkNotify(editor, msg, wParam, lParam);
4230 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4231 if (editor->bMouseCaptured)
4232 ME_SetCursor(editor);
4233 break;
4234 case WM_LBUTTONUP:
4235 if (editor->bMouseCaptured) {
4236 ITextHost_TxSetCapture(editor->texthost, FALSE);
4237 editor->bMouseCaptured = FALSE;
4239 if (editor->nSelectionType == stDocument)
4240 editor->nSelectionType = stPosition;
4241 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4242 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4243 return 0;
4244 else
4246 ME_SetCursor(editor);
4247 ME_LinkNotify(editor, msg, wParam, lParam);
4249 break;
4250 case WM_RBUTTONUP:
4251 case WM_RBUTTONDOWN:
4252 case WM_RBUTTONDBLCLK:
4253 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4254 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4255 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4256 return 0;
4257 ME_LinkNotify(editor, msg, wParam, lParam);
4258 goto do_default;
4259 case WM_CONTEXTMENU:
4260 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4261 goto do_default;
4262 break;
4263 case WM_SETFOCUS:
4264 editor->bHaveFocus = TRUE;
4265 ME_ShowCaret(editor);
4266 ME_SendOldNotify(editor, EN_SETFOCUS);
4267 if (!editor->bHideSelection && !(editor->styleFlags & ES_NOHIDESEL))
4268 ME_InvalidateSelection( editor );
4269 return 0;
4270 case WM_KILLFOCUS:
4271 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4272 editor->bHaveFocus = FALSE;
4273 editor->wheel_remain = 0;
4274 ME_HideCaret(editor);
4275 ME_SendOldNotify(editor, EN_KILLFOCUS);
4276 if (!editor->bHideSelection && !(editor->styleFlags & ES_NOHIDESEL))
4277 ME_InvalidateSelection( editor );
4278 return 0;
4279 case WM_COMMAND:
4280 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4281 return 0;
4282 case WM_KEYUP:
4283 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4284 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4285 return 0;
4286 goto do_default;
4287 case WM_KEYDOWN:
4288 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4289 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4290 return 0;
4291 if (ME_KeyDown(editor, LOWORD(wParam)))
4292 return 0;
4293 goto do_default;
4294 case WM_CHAR:
4295 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4296 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4297 return 0;
4298 return ME_Char(editor, wParam, lParam, unicode);
4299 case WM_UNICHAR:
4300 if (unicode)
4302 if(wParam == UNICODE_NOCHAR) return TRUE;
4303 if(wParam <= 0x000fffff)
4305 if(wParam > 0xffff) /* convert to surrogates */
4307 wParam -= 0x10000;
4308 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4309 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4310 } else {
4311 ME_Char(editor, wParam, 0, TRUE);
4314 return 0;
4316 break;
4317 case EM_STOPGROUPTYPING:
4318 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4319 return 0;
4320 case WM_HSCROLL:
4322 const int scrollUnit = 7;
4324 switch(LOWORD(wParam))
4326 case SB_LEFT:
4327 ME_ScrollAbs(editor, 0, 0);
4328 break;
4329 case SB_RIGHT:
4330 ME_ScrollAbs(editor,
4331 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4332 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4333 break;
4334 case SB_LINELEFT:
4335 ME_ScrollLeft(editor, scrollUnit);
4336 break;
4337 case SB_LINERIGHT:
4338 ME_ScrollRight(editor, scrollUnit);
4339 break;
4340 case SB_PAGELEFT:
4341 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4342 break;
4343 case SB_PAGERIGHT:
4344 ME_ScrollRight(editor, editor->sizeWindow.cx);
4345 break;
4346 case SB_THUMBTRACK:
4347 case SB_THUMBPOSITION:
4349 int pos = HIWORD(wParam);
4350 if (editor->horz_si.nMax > 0xffff)
4351 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4352 ME_HScrollAbs(editor, pos);
4353 break;
4356 break;
4358 case EM_SCROLL: /* fall through */
4359 case WM_VSCROLL:
4361 int origNPos;
4362 int lineHeight = get_default_line_height( editor );
4364 origNPos = editor->vert_si.nPos;
4366 switch(LOWORD(wParam))
4368 case SB_TOP:
4369 ME_ScrollAbs(editor, 0, 0);
4370 break;
4371 case SB_BOTTOM:
4372 ME_ScrollAbs(editor,
4373 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4374 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4375 break;
4376 case SB_LINEUP:
4377 ME_ScrollUp(editor,lineHeight);
4378 break;
4379 case SB_LINEDOWN:
4380 ME_ScrollDown(editor,lineHeight);
4381 break;
4382 case SB_PAGEUP:
4383 ME_ScrollUp(editor,editor->sizeWindow.cy);
4384 break;
4385 case SB_PAGEDOWN:
4386 ME_ScrollDown(editor,editor->sizeWindow.cy);
4387 break;
4388 case SB_THUMBTRACK:
4389 case SB_THUMBPOSITION:
4391 int pos = HIWORD(wParam);
4392 if (editor->vert_si.nMax > 0xffff)
4393 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4394 ME_VScrollAbs(editor, pos);
4395 break;
4398 if (msg == EM_SCROLL)
4399 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4400 break;
4402 case WM_MOUSEWHEEL:
4404 int delta;
4405 BOOL ctrl_is_down;
4407 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4408 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4409 return 0;
4411 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4413 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4415 /* if scrolling changes direction, ignore left overs */
4416 if ((delta < 0 && editor->wheel_remain < 0) ||
4417 (delta > 0 && editor->wheel_remain > 0))
4418 editor->wheel_remain += delta;
4419 else
4420 editor->wheel_remain = delta;
4422 if (editor->wheel_remain)
4424 if (ctrl_is_down) {
4425 int numerator;
4426 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4428 numerator = 100;
4429 } else {
4430 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4432 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4433 if (numerator >= 10 && numerator <= 500)
4434 ME_SetZoom(editor, numerator, 100);
4435 } else {
4436 UINT max_lines = 3;
4437 int lines = 0;
4439 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4440 if (max_lines)
4441 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4442 if (lines)
4443 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4446 break;
4448 case EM_GETRECT:
4450 *((RECT *)lParam) = editor->rcFormat;
4451 if (editor->bDefaultFormatRect)
4452 ((RECT *)lParam)->left -= editor->selofs;
4453 return 0;
4455 case EM_SETRECT:
4456 case EM_SETRECTNP:
4458 if (lParam)
4460 int border = 0;
4461 RECT clientRect;
4462 RECT *rc = (RECT *)lParam;
4464 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4465 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4466 if (wParam == 0)
4468 editor->rcFormat.top = max(0, rc->top - border);
4469 editor->rcFormat.left = max(0, rc->left - border);
4470 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4471 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4472 } else if (wParam == 1) {
4473 /* MSDN incorrectly says a wParam value of 1 causes the
4474 * lParam rect to be used as a relative offset,
4475 * however, the tests show it just prevents min/max bound
4476 * checking. */
4477 editor->rcFormat.top = rc->top - border;
4478 editor->rcFormat.left = rc->left - border;
4479 editor->rcFormat.bottom = rc->bottom;
4480 editor->rcFormat.right = rc->right + border;
4481 } else {
4482 return 0;
4484 editor->bDefaultFormatRect = FALSE;
4486 else
4488 ME_SetDefaultFormatRect(editor);
4489 editor->bDefaultFormatRect = TRUE;
4491 ME_MarkAllForWrapping(editor);
4492 ME_WrapMarkedParagraphs(editor);
4493 ME_UpdateScrollBar(editor);
4494 if (msg != EM_SETRECTNP)
4495 ME_Repaint(editor);
4496 return 0;
4498 case EM_REQUESTRESIZE:
4499 ME_SendRequestResize(editor, TRUE);
4500 return 0;
4501 case WM_SETREDRAW:
4502 goto do_default;
4503 case WM_WINDOWPOSCHANGED:
4505 RECT clientRect;
4506 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4508 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4509 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4510 if (editor->bDefaultFormatRect) {
4511 ME_SetDefaultFormatRect(editor);
4512 } else {
4513 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4514 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4516 editor->prevClientRect = clientRect;
4517 ME_RewrapRepaint(editor);
4518 goto do_default;
4520 /* IME messages to make richedit controls IME aware */
4521 case WM_IME_SETCONTEXT:
4522 case WM_IME_CONTROL:
4523 case WM_IME_SELECT:
4524 case WM_IME_COMPOSITIONFULL:
4525 return 0;
4526 case WM_IME_STARTCOMPOSITION:
4528 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4529 ME_DeleteSelection(editor);
4530 ME_CommitUndo(editor);
4531 ME_UpdateRepaint(editor, FALSE);
4532 return 0;
4534 case WM_IME_COMPOSITION:
4536 HIMC hIMC;
4538 ME_Style *style = ME_GetInsertStyle(editor, 0);
4539 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4540 ME_DeleteSelection(editor);
4541 ME_SaveTempStyle(editor);
4542 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4544 LPWSTR lpCompStr = NULL;
4545 DWORD dwBufLen;
4546 DWORD dwIndex = lParam & GCS_RESULTSTR;
4547 if (!dwIndex)
4548 dwIndex = GCS_COMPSTR;
4550 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4551 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4552 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4553 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4554 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4555 HeapFree(GetProcessHeap(), 0, lpCompStr);
4557 if (dwIndex == GCS_COMPSTR)
4558 ME_SetSelection(editor,editor->imeStartIndex,
4559 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4561 ME_ReleaseStyle(style);
4562 ME_CommitUndo(editor);
4563 ME_UpdateRepaint(editor, FALSE);
4564 return 0;
4566 case WM_IME_ENDCOMPOSITION:
4568 ME_DeleteSelection(editor);
4569 editor->imeStartIndex=-1;
4570 return 0;
4572 case EM_GETOLEINTERFACE:
4574 if (!editor->reOle)
4575 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4576 return 0;
4577 *(LPVOID *)lParam = editor->reOle;
4578 IRichEditOle_AddRef(editor->reOle);
4579 return 1;
4581 case EM_GETPASSWORDCHAR:
4583 return editor->cPasswordMask;
4585 case EM_SETOLECALLBACK:
4586 if(editor->lpOleCallback)
4587 IRichEditOleCallback_Release(editor->lpOleCallback);
4588 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4589 if(editor->lpOleCallback)
4590 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4591 return TRUE;
4592 case EM_GETWORDBREAKPROC:
4593 return (LRESULT)editor->pfnWordBreak;
4594 case EM_SETWORDBREAKPROC:
4596 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4598 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4599 return (LRESULT)pfnOld;
4601 case EM_GETTEXTMODE:
4602 return editor->mode;
4603 case EM_SETTEXTMODE:
4605 int mask = 0;
4606 int changes = 0;
4608 if (ME_GetTextLength(editor) ||
4609 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4610 return E_UNEXPECTED;
4612 /* Check for mutually exclusive flags in adjacent bits of wParam */
4613 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4614 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4615 return E_INVALIDARG;
4617 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4619 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4620 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4621 if (wParam & TM_PLAINTEXT) {
4622 /* Clear selection since it should be possible to select the
4623 * end of text run for rich text */
4624 ME_InvalidateSelection(editor);
4625 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4626 editor->pCursors[1] = editor->pCursors[0];
4627 /* plain text can only have the default style. */
4628 ME_ClearTempStyle(editor);
4629 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4630 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4631 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4634 /* FIXME: Currently no support for undo level and code page options */
4635 editor->mode = (editor->mode & ~mask) | changes;
4636 return 0;
4638 case EM_SETPASSWORDCHAR:
4640 editor->cPasswordMask = wParam;
4641 ME_RewrapRepaint(editor);
4642 return 0;
4644 case EM_SETTARGETDEVICE:
4645 if (wParam == 0)
4647 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4648 if (editor->nAvailWidth || editor->bWordWrap != new)
4650 editor->bWordWrap = new;
4651 editor->nAvailWidth = 0; /* wrap to client area */
4652 ME_RewrapRepaint(editor);
4654 } else {
4655 int width = max(0, lParam);
4656 if ((editor->styleFlags & ES_MULTILINE) &&
4657 (!editor->bWordWrap || editor->nAvailWidth != width))
4659 editor->nAvailWidth = width;
4660 editor->bWordWrap = TRUE;
4661 ME_RewrapRepaint(editor);
4663 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4665 return TRUE;
4666 default:
4667 do_default:
4668 *phresult = S_FALSE;
4669 break;
4671 return 0L;
4674 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4675 LPARAM lParam, BOOL unicode)
4677 ME_TextEditor *editor;
4678 HRESULT hresult;
4679 LRESULT lresult = 0;
4681 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4682 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4684 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4685 if (!editor)
4687 if (msg == WM_NCCREATE)
4689 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4690 ITextHost *texthost;
4692 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4693 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4694 return texthost != NULL;
4696 else
4698 return DefWindowProcW(hWnd, msg, wParam, lParam);
4702 switch (msg)
4704 case WM_PAINT:
4706 HDC hDC;
4707 RECT rc;
4708 PAINTSTRUCT ps;
4710 hDC = BeginPaint(editor->hWnd, &ps);
4711 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4712 ME_SendOldNotify(editor, EN_UPDATE);
4713 /* Erase area outside of the formatting rectangle */
4714 if (ps.rcPaint.top < editor->rcFormat.top)
4716 rc = ps.rcPaint;
4717 rc.bottom = editor->rcFormat.top;
4718 FillRect(hDC, &rc, editor->hbrBackground);
4719 ps.rcPaint.top = editor->rcFormat.top;
4721 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4722 rc = ps.rcPaint;
4723 rc.top = editor->rcFormat.bottom;
4724 FillRect(hDC, &rc, editor->hbrBackground);
4725 ps.rcPaint.bottom = editor->rcFormat.bottom;
4727 if (ps.rcPaint.left < editor->rcFormat.left) {
4728 rc = ps.rcPaint;
4729 rc.right = editor->rcFormat.left;
4730 FillRect(hDC, &rc, editor->hbrBackground);
4731 ps.rcPaint.left = editor->rcFormat.left;
4733 if (ps.rcPaint.right > editor->rcFormat.right) {
4734 rc = ps.rcPaint;
4735 rc.left = editor->rcFormat.right;
4736 FillRect(hDC, &rc, editor->hbrBackground);
4737 ps.rcPaint.right = editor->rcFormat.right;
4740 ME_PaintContent(editor, hDC, &ps.rcPaint);
4741 EndPaint(editor->hWnd, &ps);
4742 return 0;
4744 case WM_ERASEBKGND:
4746 HDC hDC = (HDC)wParam;
4747 RECT rc;
4749 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4750 FillRect(hDC, &rc, editor->hbrBackground);
4751 return 1;
4753 case EM_SETOPTIONS:
4755 DWORD dwStyle;
4756 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4757 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4758 ECO_SELECTIONBAR;
4759 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4760 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4761 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4762 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4763 return lresult;
4765 case EM_SETREADONLY:
4767 DWORD dwStyle;
4768 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4769 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4770 dwStyle &= ~ES_READONLY;
4771 if (wParam)
4772 dwStyle |= ES_READONLY;
4773 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4774 return lresult;
4776 default:
4777 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4780 if (hresult == S_FALSE)
4781 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4783 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4784 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4786 return lresult;
4789 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4791 BOOL unicode = TRUE;
4793 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4794 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4795 unicode = FALSE;
4797 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4800 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4802 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4805 /******************************************************************
4806 * RichEditANSIWndProc (RICHED20.10)
4808 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4810 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4813 /******************************************************************
4814 * RichEdit10ANSIWndProc (RICHED20.9)
4816 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4818 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4820 ITextHost *texthost;
4821 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4823 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4824 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4825 return texthost != NULL;
4827 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4830 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4832 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4835 /* Fill buffer with srcChars unicode characters from the start cursor.
4837 * buffer: destination buffer
4838 * buflen: length of buffer in characters excluding the NULL terminator.
4839 * start: start of editor text to copy into buffer.
4840 * srcChars: Number of characters to use from the editor text.
4841 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4843 * returns the number of characters written excluding the NULL terminator.
4845 * The written text is always NULL terminated.
4847 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4848 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4849 BOOL bEOP)
4851 ME_DisplayItem *pRun, *pNextRun;
4852 const WCHAR *pStart = buffer;
4853 const WCHAR cr_lf[] = {'\r', '\n', 0};
4854 const WCHAR *str;
4855 int nLen;
4857 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4858 if (editor->bEmulateVersion10) bCRLF = FALSE;
4860 pRun = start->pRun;
4861 assert(pRun);
4862 pNextRun = ME_FindItemFwd(pRun, diRun);
4864 nLen = pRun->member.run.len - start->nOffset;
4865 str = get_text( &pRun->member.run, start->nOffset );
4867 while (srcChars && buflen && pNextRun)
4869 int nFlags = pRun->member.run.nFlags;
4871 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4873 if (buflen == 1) break;
4874 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4875 * EM_GETTEXTEX, however, this is done for copying text which
4876 * also uses this function. */
4877 srcChars -= min(nLen, srcChars);
4878 nLen = 2;
4879 str = cr_lf;
4880 } else {
4881 nLen = min(nLen, srcChars);
4882 srcChars -= nLen;
4885 nLen = min(nLen, buflen);
4886 buflen -= nLen;
4888 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4890 buffer += nLen;
4892 pRun = pNextRun;
4893 pNextRun = ME_FindItemFwd(pRun, diRun);
4895 nLen = pRun->member.run.len;
4896 str = get_text( &pRun->member.run, 0 );
4898 /* append '\r' to the last paragraph. */
4899 if (pRun->next->type == diTextEnd && bEOP)
4901 *buffer = '\r';
4902 buffer ++;
4904 *buffer = 0;
4905 return buffer - pStart;
4908 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4910 WNDCLASSW wcW;
4911 WNDCLASSA wcA;
4913 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4914 wcW.lpfnWndProc = RichEditWndProcW;
4915 wcW.cbClsExtra = 0;
4916 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4917 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4918 wcW.hIcon = NULL;
4919 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4920 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4921 wcW.lpszMenuName = NULL;
4923 if (is_version_nt())
4925 wcW.lpszClassName = RICHEDIT_CLASS20W;
4926 if (!RegisterClassW(&wcW)) return FALSE;
4927 wcW.lpszClassName = MSFTEDIT_CLASS;
4928 if (!RegisterClassW(&wcW)) return FALSE;
4930 else
4932 /* WNDCLASSA/W have the same layout */
4933 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4934 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4935 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4936 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4939 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4940 wcA.lpfnWndProc = RichEditWndProcA;
4941 wcA.cbClsExtra = 0;
4942 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4943 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4944 wcA.hIcon = NULL;
4945 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4946 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4947 wcA.lpszMenuName = NULL;
4948 wcA.lpszClassName = RICHEDIT_CLASS20A;
4949 if (!RegisterClassA(&wcA)) return FALSE;
4950 wcA.lpszClassName = "RichEdit50A";
4951 if (!RegisterClassA(&wcA)) return FALSE;
4953 return TRUE;
4956 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4957 /* FIXME: Not implemented */
4958 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4959 hWnd, msg, get_msg_name(msg), wParam, lParam);
4960 return DefWindowProcW(hWnd, msg, wParam, lParam);
4963 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4964 /* FIXME: Not implemented */
4965 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4966 hWnd, msg, get_msg_name(msg), wParam, lParam);
4967 return DefWindowProcW(hWnd, msg, wParam, lParam);
4970 /******************************************************************
4971 * REExtendedRegisterClass (RICHED20.8)
4973 * FIXME undocumented
4974 * Need to check for errors and implement controls and callbacks
4976 LRESULT WINAPI REExtendedRegisterClass(void)
4978 WNDCLASSW wcW;
4979 UINT result;
4981 FIXME("semi stub\n");
4983 wcW.cbClsExtra = 0;
4984 wcW.cbWndExtra = 4;
4985 wcW.hInstance = NULL;
4986 wcW.hIcon = NULL;
4987 wcW.hCursor = NULL;
4988 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4989 wcW.lpszMenuName = NULL;
4991 if (!ME_ListBoxRegistered)
4993 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4994 wcW.lpfnWndProc = REListWndProc;
4995 wcW.lpszClassName = REListBox20W;
4996 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4999 if (!ME_ComboBoxRegistered)
5001 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
5002 wcW.lpfnWndProc = REComboWndProc;
5003 wcW.lpszClassName = REComboBox20W;
5004 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
5007 result = 0;
5008 if (ME_ListBoxRegistered)
5009 result += 1;
5010 if (ME_ComboBoxRegistered)
5011 result += 2;
5013 return result;
5016 static int wchar_comp( const void *key, const void *elem )
5018 return *(const WCHAR *)key - *(const WCHAR *)elem;
5021 /* neutral characters end the url if the next non-neutral character is a space character,
5022 otherwise they are included in the url. */
5023 static BOOL isurlneutral( WCHAR c )
5025 /* NB this list is sorted */
5026 static const WCHAR neutral_chars[] = {'!','\"','\'','(',')',',','-','.',':',';','<','>','?','[',']','{','}'};
5028 /* Some shortcuts */
5029 if (isalnum( c )) return FALSE;
5030 if (c > neutral_chars[sizeof(neutral_chars) / sizeof(neutral_chars[0]) - 1]) return FALSE;
5032 return !!bsearch( &c, neutral_chars, sizeof(neutral_chars) / sizeof(neutral_chars[0]),
5033 sizeof(c), wchar_comp );
5037 * This proc takes a selection, and scans it forward in order to select the span
5038 * of a possible URL candidate. A possible URL candidate must start with isalnum
5039 * or one of the following special characters: *|/\+%#@ and must consist entirely
5040 * of the characters allowed to start the URL, plus : (colon) which may occur
5041 * at most once, and not at either end.
5043 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
5044 const ME_Cursor *start,
5045 int nChars,
5046 ME_Cursor *candidate_min,
5047 ME_Cursor *candidate_max)
5049 ME_Cursor cursor = *start, neutral_end, space_end;
5050 BOOL candidateStarted = FALSE, quoted = FALSE;
5051 WCHAR c;
5053 while (nChars > 0)
5055 WCHAR *str = get_text( &cursor.pRun->member.run, 0 );
5056 int run_len = cursor.pRun->member.run.len;
5058 nChars -= run_len - cursor.nOffset;
5060 /* Find start of candidate */
5061 if (!candidateStarted)
5063 while (cursor.nOffset < run_len)
5065 c = str[cursor.nOffset];
5066 if (!isspaceW( c ) && !isurlneutral( c ))
5068 *candidate_min = cursor;
5069 candidateStarted = TRUE;
5070 neutral_end.pPara = NULL;
5071 space_end.pPara = NULL;
5072 cursor.nOffset++;
5073 break;
5075 quoted = (c == '<');
5076 cursor.nOffset++;
5080 /* Find end of candidate */
5081 if (candidateStarted)
5083 while (cursor.nOffset < run_len)
5085 c = str[cursor.nOffset];
5086 if (isspaceW( c ))
5088 if (quoted && c != '\r')
5090 if (!space_end.pPara)
5092 if (neutral_end.pPara)
5093 space_end = neutral_end;
5094 else
5095 space_end = cursor;
5098 else
5099 goto done;
5101 else if (isurlneutral( c ))
5103 if (quoted && c == '>')
5105 neutral_end.pPara = NULL;
5106 space_end.pPara = NULL;
5107 goto done;
5109 if (!neutral_end.pPara)
5110 neutral_end = cursor;
5112 else
5113 neutral_end.pPara = NULL;
5115 cursor.nOffset++;
5119 cursor.nOffset = 0;
5120 if (!ME_NextRun(&cursor.pPara, &cursor.pRun, TRUE))
5121 goto done;
5124 done:
5125 if (candidateStarted)
5127 if (space_end.pPara)
5128 *candidate_max = space_end;
5129 else if (neutral_end.pPara)
5130 *candidate_max = neutral_end;
5131 else
5132 *candidate_max = cursor;
5133 return TRUE;
5135 *candidate_max = *candidate_min = cursor;
5136 return FALSE;
5140 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5142 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5144 #define MAX_PREFIX_LEN 9
5145 struct prefix_s {
5146 const WCHAR text[MAX_PREFIX_LEN];
5147 int length;
5148 }prefixes[] = {
5149 {{'p','r','o','s','p','e','r','o',':'}, 9},
5150 {{'t','e','l','n','e','t',':'}, 7},
5151 {{'g','o','p','h','e','r',':'}, 7},
5152 {{'m','a','i','l','t','o',':'}, 7},
5153 {{'h','t','t','p','s',':'}, 6},
5154 {{'f','i','l','e',':'}, 5},
5155 {{'n','e','w','s',':'}, 5},
5156 {{'w','a','i','s',':'}, 5},
5157 {{'n','n','t','p',':'}, 5},
5158 {{'h','t','t','p',':'}, 5},
5159 {{'w','w','w','.'}, 4},
5160 {{'f','t','p',':'}, 4},
5162 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5163 unsigned int i;
5165 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5166 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5168 if (nChars < prefixes[i].length) continue;
5169 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5170 return TRUE;
5172 return FALSE;
5173 #undef MAX_PREFIX_LEN
5177 * This proc walks through the indicated selection and evaluates whether each
5178 * section identified by ME_FindNextURLCandidate and in-between sections have
5179 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5180 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5182 * Since this function can cause runs to be split, do not depend on the value
5183 * of the start cursor at the end of the function.
5185 * nChars may be set to INT_MAX to update to the end of the text.
5187 * Returns TRUE if at least one section was modified.
5189 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5191 BOOL modified = FALSE;
5192 ME_Cursor startCur = *start;
5194 if (!editor->AutoURLDetect_bEnable) return FALSE;
5198 CHARFORMAT2W link;
5199 ME_Cursor candidateStart, candidateEnd;
5201 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5202 &candidateStart, &candidateEnd))
5204 /* Section before candidate is not an URL */
5205 int cMin = ME_GetCursorOfs(&candidateStart);
5206 int cMax = ME_GetCursorOfs(&candidateEnd);
5208 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5209 candidateStart = candidateEnd;
5210 nChars -= cMax - ME_GetCursorOfs(&startCur);
5212 else
5214 /* No more candidates until end of selection */
5215 nChars = 0;
5218 if (startCur.pRun != candidateStart.pRun ||
5219 startCur.nOffset != candidateStart.nOffset)
5221 /* CFE_LINK effect should be consistently unset */
5222 link.cbSize = sizeof(link);
5223 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5224 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5226 /* CFE_LINK must be unset from this range */
5227 memset(&link, 0, sizeof(CHARFORMAT2W));
5228 link.cbSize = sizeof(link);
5229 link.dwMask = CFM_LINK;
5230 link.dwEffects = 0;
5231 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5232 /* Update candidateEnd since setting character formats may split
5233 * runs, which can cause a cursor to be at an invalid offset within
5234 * a split run. */
5235 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5237 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5238 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5240 modified = TRUE;
5243 if (candidateStart.pRun != candidateEnd.pRun ||
5244 candidateStart.nOffset != candidateEnd.nOffset)
5246 /* CFE_LINK effect should be consistently set */
5247 link.cbSize = sizeof(link);
5248 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5249 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5251 /* CFE_LINK must be set on this range */
5252 memset(&link, 0, sizeof(CHARFORMAT2W));
5253 link.cbSize = sizeof(link);
5254 link.dwMask = CFM_LINK;
5255 link.dwEffects = CFE_LINK;
5256 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5257 modified = TRUE;
5260 startCur = candidateEnd;
5261 } while (nChars > 0);
5262 return modified;