richedit: Don't change text mode with undo or redo stack.
[wine.git] / dlls / riched20 / editor.c
blob842b15919a3ba595776e274edb901a53e1bb5179
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 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
236 #define STACK_SIZE_DEFAULT 100
237 #define STACK_SIZE_MAX 1000
239 #define TEXT_LIMIT_DEFAULT 32767
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
250 int me_debug = 0;
251 HANDLE me_heap = NULL;
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
256 static inline int is_version_nt(void)
258 return !(GetVersion() & 0x80000000);
261 static ME_TextBuffer *ME_MakeText(void) {
263 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
265 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
268 p1->prev = NULL;
269 p1->next = p2;
270 p2->prev = p1;
271 p2->next = NULL;
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
276 buf->pFirst = p1;
277 buf->pLast = p2;
278 buf->pCharStyle = NULL;
280 return buf;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
287 WCHAR *pText;
289 TRACE("%08x %p\n", dwFormat, stream);
291 do {
292 LONG nWideChars = 0;
294 if (!stream->dwSize)
296 ME_StreamInFill(stream);
297 if (stream->editstream->dwError)
298 break;
299 if (!stream->dwSize)
300 break;
303 if (!(dwFormat & SF_UNICODE))
305 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
306 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
307 pText = wszText;
309 else
311 nWideChars = stream->dwSize >> 1;
312 pText = (WCHAR *)stream->buffer;
315 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
316 if (stream->dwSize == 0)
317 break;
318 stream->dwSize = 0;
319 } while(1);
320 return 0;
323 static void ME_ApplyBorderProperties(RTF_Info *info,
324 ME_BorderRect *borderRect,
325 RTFBorder *borderDef)
327 int i, colorNum;
328 ME_Border *pBorders[] = {&borderRect->top,
329 &borderRect->left,
330 &borderRect->bottom,
331 &borderRect->right};
332 for (i = 0; i < 4; i++)
334 RTFColor *colorDef = info->colorList;
335 pBorders[i]->width = borderDef[i].width;
336 colorNum = borderDef[i].color;
337 while (colorDef && colorDef->rtfCNum != colorNum)
338 colorDef = colorDef->rtfNextColor;
339 if (colorDef)
340 pBorders[i]->colorRef = RGB(
341 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
342 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
343 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
344 else
345 pBorders[i]->colorRef = RGB(0, 0, 0);
349 void ME_RTFCharAttrHook(RTF_Info *info)
351 CHARFORMAT2W fmt;
352 fmt.cbSize = sizeof(fmt);
353 fmt.dwMask = 0;
354 fmt.dwEffects = 0;
356 switch(info->rtfMinor)
358 case rtfPlain:
359 /* FIXME add more flags once they're implemented */
360 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
361 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
362 fmt.yHeight = 12*20; /* 12pt */
363 fmt.wWeight = FW_NORMAL;
364 fmt.bUnderlineType = CFU_UNDERLINENONE;
365 break;
366 case rtfBold:
367 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
368 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
369 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
370 break;
371 case rtfItalic:
372 fmt.dwMask = CFM_ITALIC;
373 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
374 break;
375 case rtfUnderline:
376 fmt.dwMask = CFM_UNDERLINETYPE;
377 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
378 break;
379 case rtfDotUnderline:
380 fmt.dwMask = CFM_UNDERLINETYPE;
381 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
382 break;
383 case rtfDbUnderline:
384 fmt.dwMask = CFM_UNDERLINETYPE;
385 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
386 break;
387 case rtfWordUnderline:
388 fmt.dwMask = CFM_UNDERLINETYPE;
389 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
390 break;
391 case rtfNoUnderline:
392 fmt.dwMask = CFM_UNDERLINETYPE;
393 fmt.bUnderlineType = CFU_UNDERLINENONE;
394 break;
395 case rtfStrikeThru:
396 fmt.dwMask = CFM_STRIKEOUT;
397 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
398 break;
399 case rtfSubScript:
400 case rtfSuperScript:
401 case rtfSubScrShrink:
402 case rtfSuperScrShrink:
403 case rtfNoSuperSub:
404 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
405 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
406 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
407 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
408 break;
409 case rtfInvisible:
410 fmt.dwMask = CFM_HIDDEN;
411 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
412 break;
413 case rtfBackColor:
414 fmt.dwMask = CFM_BACKCOLOR;
415 fmt.dwEffects = 0;
416 if (info->rtfParam == 0)
417 fmt.dwEffects = CFE_AUTOBACKCOLOR;
418 else if (info->rtfParam != rtfNoParam)
420 RTFColor *c = RTFGetColor(info, info->rtfParam);
421 if (c && c->rtfCBlue >= 0)
422 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
423 else
424 fmt.dwEffects = CFE_AUTOBACKCOLOR;
426 break;
427 case rtfForeColor:
428 fmt.dwMask = CFM_COLOR;
429 fmt.dwEffects = 0;
430 if (info->rtfParam == 0)
431 fmt.dwEffects = CFE_AUTOCOLOR;
432 else if (info->rtfParam != rtfNoParam)
434 RTFColor *c = RTFGetColor(info, info->rtfParam);
435 if (c && c->rtfCBlue >= 0)
436 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
437 else {
438 fmt.dwEffects = CFE_AUTOCOLOR;
441 break;
442 case rtfFontNum:
443 if (info->rtfParam != rtfNoParam)
445 RTFFont *f = RTFGetFont(info, info->rtfParam);
446 if (f)
448 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
449 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
450 fmt.bCharSet = f->rtfFCharSet;
451 fmt.dwMask = CFM_FACE | CFM_CHARSET;
452 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
455 break;
456 case rtfFontSize:
457 fmt.dwMask = CFM_SIZE;
458 if (info->rtfParam != rtfNoParam)
459 fmt.yHeight = info->rtfParam*10;
460 break;
462 if (fmt.dwMask) {
463 ME_Style *style2;
464 RTFFlushOutputBuffer(info);
465 /* FIXME too slow ? how come ? */
466 style2 = ME_ApplyStyle(info->style, &fmt);
467 ME_ReleaseStyle(info->style);
468 info->style = style2;
469 info->styleChanged = TRUE;
473 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
474 the same tags mean different things in different contexts */
475 void ME_RTFParAttrHook(RTF_Info *info)
477 PARAFORMAT2 fmt;
478 fmt.cbSize = sizeof(fmt);
479 fmt.dwMask = 0;
481 switch(info->rtfMinor)
483 case rtfParDef: /* restores default paragraph attributes */
484 if (!info->editor->bEmulateVersion10) /* v4.1 */
485 info->borderType = RTFBorderParaLeft;
486 else /* v1.0 - 3.0 */
487 info->borderType = RTFBorderParaTop;
488 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
489 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
490 PFM_STARTINDENT;
491 /* TODO: numbering, shading */
492 fmt.wAlignment = PFA_LEFT;
493 fmt.cTabCount = 0;
494 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
495 fmt.wBorderWidth = fmt.wBorders = 0;
496 fmt.wBorderSpace = 0;
497 fmt.bLineSpacingRule = 0;
498 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
499 fmt.dyLineSpacing = 0;
500 if (!info->editor->bEmulateVersion10) /* v4.1 */
502 if (info->tableDef && info->tableDef->tableRowStart &&
503 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
505 ME_Cursor cursor;
506 ME_DisplayItem *para;
507 /* We are just after a table row. */
508 RTFFlushOutputBuffer(info);
509 cursor = info->editor->pCursors[0];
510 para = cursor.pPara;
511 if (para == info->tableDef->tableRowStart->member.para.next_para
512 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
514 /* Since the table row end, no text has been inserted, and the \intbl
515 * control word has not be used. We can confirm that we are not in a
516 * table anymore.
518 info->tableDef->tableRowStart = NULL;
519 info->canInheritInTbl = FALSE;
522 } else { /* v1.0 - v3.0 */
523 fmt.dwMask |= PFM_TABLE;
524 fmt.wEffects &= ~PFE_TABLE;
526 break;
527 case rtfNestLevel:
528 if (!info->editor->bEmulateVersion10) /* v4.1 */
530 while (info->rtfParam > info->nestingLevel) {
531 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
532 ZeroMemory(tableDef, sizeof(RTFTable));
533 tableDef->parent = info->tableDef;
534 info->tableDef = tableDef;
536 RTFFlushOutputBuffer(info);
537 if (tableDef->tableRowStart &&
538 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
540 ME_DisplayItem *para = tableDef->tableRowStart;
541 para = para->member.para.next_para;
542 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
543 tableDef->tableRowStart = para;
544 } else {
545 ME_Cursor cursor;
546 WCHAR endl = '\r';
547 cursor = info->editor->pCursors[0];
548 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
549 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
550 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
553 info->nestingLevel++;
555 info->canInheritInTbl = FALSE;
557 break;
558 case rtfInTable:
560 if (!info->editor->bEmulateVersion10) /* v4.1 */
562 if (info->nestingLevel < 1)
564 RTFTable *tableDef;
565 if (!info->tableDef)
567 info->tableDef = ALLOC_OBJ(RTFTable);
568 ZeroMemory(info->tableDef, sizeof(RTFTable));
570 tableDef = info->tableDef;
571 RTFFlushOutputBuffer(info);
572 if (tableDef->tableRowStart &&
573 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
575 ME_DisplayItem *para = tableDef->tableRowStart;
576 para = para->member.para.next_para;
577 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
578 tableDef->tableRowStart = para;
579 } else {
580 ME_Cursor cursor;
581 WCHAR endl = '\r';
582 cursor = info->editor->pCursors[0];
583 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
584 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
585 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
587 info->nestingLevel = 1;
588 info->canInheritInTbl = TRUE;
590 return;
591 } else { /* v1.0 - v3.0 */
592 fmt.dwMask |= PFM_TABLE;
593 fmt.wEffects |= PFE_TABLE;
595 break;
597 case rtfFirstIndent:
598 ME_GetSelectionParaFormat(info->editor, &fmt);
599 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
600 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
601 fmt.dxOffset = -info->rtfParam;
602 break;
603 case rtfLeftIndent:
604 ME_GetSelectionParaFormat(info->editor, &fmt);
605 fmt.dwMask = PFM_STARTINDENT;
606 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
607 break;
608 case rtfRightIndent:
609 fmt.dwMask = PFM_RIGHTINDENT;
610 fmt.dxRightIndent = info->rtfParam;
611 break;
612 case rtfQuadLeft:
613 case rtfQuadJust:
614 fmt.dwMask = PFM_ALIGNMENT;
615 fmt.wAlignment = PFA_LEFT;
616 break;
617 case rtfQuadRight:
618 fmt.dwMask = PFM_ALIGNMENT;
619 fmt.wAlignment = PFA_RIGHT;
620 break;
621 case rtfQuadCenter:
622 fmt.dwMask = PFM_ALIGNMENT;
623 fmt.wAlignment = PFA_CENTER;
624 break;
625 case rtfTabPos:
626 ME_GetSelectionParaFormat(info->editor, &fmt);
627 if (!(fmt.dwMask & PFM_TABSTOPS))
629 fmt.cTabCount = 0;
631 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
632 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
633 fmt.dwMask = PFM_TABSTOPS;
634 break;
635 case rtfKeep:
636 fmt.dwMask = PFM_KEEP;
637 fmt.wEffects = PFE_KEEP;
638 break;
639 case rtfNoWidowControl:
640 fmt.dwMask = PFM_NOWIDOWCONTROL;
641 fmt.wEffects = PFE_NOWIDOWCONTROL;
642 break;
643 case rtfKeepNext:
644 fmt.dwMask = PFM_KEEPNEXT;
645 fmt.wEffects = PFE_KEEPNEXT;
646 break;
647 case rtfSpaceAfter:
648 fmt.dwMask = PFM_SPACEAFTER;
649 fmt.dySpaceAfter = info->rtfParam;
650 break;
651 case rtfSpaceBefore:
652 fmt.dwMask = PFM_SPACEBEFORE;
653 fmt.dySpaceBefore = info->rtfParam;
654 break;
655 case rtfSpaceBetween:
656 fmt.dwMask = PFM_LINESPACING;
657 if ((int)info->rtfParam > 0)
659 fmt.dyLineSpacing = info->rtfParam;
660 fmt.bLineSpacingRule = 3;
662 else
664 fmt.dyLineSpacing = info->rtfParam;
665 fmt.bLineSpacingRule = 4;
667 case rtfSpaceMultiply:
668 fmt.dwMask = PFM_LINESPACING;
669 fmt.dyLineSpacing = info->rtfParam * 20;
670 fmt.bLineSpacingRule = 5;
671 break;
672 case rtfParBullet:
673 fmt.dwMask = PFM_NUMBERING;
674 fmt.wNumbering = PFN_BULLET;
675 break;
676 case rtfParSimple:
677 fmt.dwMask = PFM_NUMBERING;
678 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
679 break;
680 case rtfParNumDecimal:
681 fmt.dwMask = PFM_NUMBERING;
682 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
683 break;
684 case rtfParNumIndent:
685 fmt.dwMask = PFM_NUMBERINGTAB;
686 fmt.wNumberingTab = info->rtfParam;
687 break;
688 case rtfParNumStartAt:
689 fmt.dwMask = PFM_NUMBERINGSTART;
690 fmt.wNumberingStart = info->rtfParam;
691 break;
692 case rtfBorderLeft:
693 info->borderType = RTFBorderParaLeft;
694 ME_GetSelectionParaFormat(info->editor, &fmt);
695 if (!(fmt.dwMask & PFM_BORDER))
697 fmt.wBorderSpace = 0;
698 fmt.wBorderWidth = 1;
699 fmt.wBorders = 0;
701 fmt.wBorders |= 1;
702 fmt.dwMask = PFM_BORDER;
703 break;
704 case rtfBorderRight:
705 info->borderType = RTFBorderParaRight;
706 ME_GetSelectionParaFormat(info->editor, &fmt);
707 if (!(fmt.dwMask & PFM_BORDER))
709 fmt.wBorderSpace = 0;
710 fmt.wBorderWidth = 1;
711 fmt.wBorders = 0;
713 fmt.wBorders |= 2;
714 fmt.dwMask = PFM_BORDER;
715 break;
716 case rtfBorderTop:
717 info->borderType = RTFBorderParaTop;
718 ME_GetSelectionParaFormat(info->editor, &fmt);
719 if (!(fmt.dwMask & PFM_BORDER))
721 fmt.wBorderSpace = 0;
722 fmt.wBorderWidth = 1;
723 fmt.wBorders = 0;
725 fmt.wBorders |= 4;
726 fmt.dwMask = PFM_BORDER;
727 break;
728 case rtfBorderBottom:
729 info->borderType = RTFBorderParaBottom;
730 ME_GetSelectionParaFormat(info->editor, &fmt);
731 if (!(fmt.dwMask & PFM_BORDER))
733 fmt.wBorderSpace = 0;
734 fmt.wBorderWidth = 1;
735 fmt.wBorders = 0;
737 fmt.wBorders |= 8;
738 fmt.dwMask = PFM_BORDER;
739 break;
740 case rtfBorderSingle:
741 ME_GetSelectionParaFormat(info->editor, &fmt);
742 /* we assume that borders have been created before (RTF spec) */
743 fmt.wBorders &= ~0x700;
744 fmt.wBorders |= 1 << 8;
745 fmt.dwMask = PFM_BORDER;
746 break;
747 case rtfBorderThick:
748 ME_GetSelectionParaFormat(info->editor, &fmt);
749 /* we assume that borders have been created before (RTF spec) */
750 fmt.wBorders &= ~0x700;
751 fmt.wBorders |= 2 << 8;
752 fmt.dwMask = PFM_BORDER;
753 break;
754 case rtfBorderShadow:
755 ME_GetSelectionParaFormat(info->editor, &fmt);
756 /* we assume that borders have been created before (RTF spec) */
757 fmt.wBorders &= ~0x700;
758 fmt.wBorders |= 10 << 8;
759 fmt.dwMask = PFM_BORDER;
760 break;
761 case rtfBorderDouble:
762 ME_GetSelectionParaFormat(info->editor, &fmt);
763 /* we assume that borders have been created before (RTF spec) */
764 fmt.wBorders &= ~0x700;
765 fmt.wBorders |= 7 << 8;
766 fmt.dwMask = PFM_BORDER;
767 break;
768 case rtfBorderDot:
769 ME_GetSelectionParaFormat(info->editor, &fmt);
770 /* we assume that borders have been created before (RTF spec) */
771 fmt.wBorders &= ~0x700;
772 fmt.wBorders |= 11 << 8;
773 fmt.dwMask = PFM_BORDER;
774 break;
775 case rtfBorderWidth:
777 int borderSide = info->borderType & RTFBorderSideMask;
778 RTFTable *tableDef = info->tableDef;
779 ME_GetSelectionParaFormat(info->editor, &fmt);
780 /* we assume that borders have been created before (RTF spec) */
781 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
782 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
784 RTFBorder *border;
785 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
786 break;
787 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
788 border->width = info->rtfParam;
789 break;
791 fmt.dwMask = PFM_BORDER;
792 break;
794 case rtfBorderSpace:
795 ME_GetSelectionParaFormat(info->editor, &fmt);
796 /* we assume that borders have been created before (RTF spec) */
797 fmt.wBorderSpace = info->rtfParam;
798 fmt.dwMask = PFM_BORDER;
799 break;
800 case rtfBorderColor:
802 RTFTable *tableDef = info->tableDef;
803 int borderSide = info->borderType & RTFBorderSideMask;
804 int borderType = info->borderType & RTFBorderTypeMask;
805 switch(borderType)
807 case RTFBorderTypePara:
808 if (!info->editor->bEmulateVersion10) /* v4.1 */
809 break;
810 /* v1.0 - 3.0 treat paragraph and row borders the same. */
811 case RTFBorderTypeRow:
812 if (tableDef) {
813 tableDef->border[borderSide].color = info->rtfParam;
815 break;
816 case RTFBorderTypeCell:
817 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
818 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
820 break;
822 break;
825 if (fmt.dwMask) {
826 RTFFlushOutputBuffer(info);
827 /* FIXME too slow ? how come ?*/
828 ME_SetSelectionParaFormat(info->editor, &fmt);
832 void ME_RTFTblAttrHook(RTF_Info *info)
834 switch (info->rtfMinor)
836 case rtfRowDef:
838 if (!info->editor->bEmulateVersion10) /* v4.1 */
839 info->borderType = 0; /* Not sure */
840 else /* v1.0 - 3.0 */
841 info->borderType = RTFBorderRowTop;
842 if (!info->tableDef) {
843 info->tableDef = ME_MakeTableDef(info->editor);
844 } else {
845 ME_InitTableDef(info->editor, info->tableDef);
847 break;
849 case rtfCellPos:
851 int cellNum;
852 if (!info->tableDef)
854 info->tableDef = ME_MakeTableDef(info->editor);
856 cellNum = info->tableDef->numCellsDefined;
857 if (cellNum >= MAX_TABLE_CELLS)
858 break;
859 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
860 if (cellNum < MAX_TAB_STOPS) {
861 /* Tab stops were used to store cell positions before v4.1 but v4.1
862 * still seems to set the tabstops without using them. */
863 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
864 PARAFORMAT2 *pFmt = para->member.para.pFmt;
865 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
866 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
868 info->tableDef->numCellsDefined++;
869 break;
871 case rtfRowBordTop:
872 info->borderType = RTFBorderRowTop;
873 break;
874 case rtfRowBordLeft:
875 info->borderType = RTFBorderRowLeft;
876 break;
877 case rtfRowBordBottom:
878 info->borderType = RTFBorderRowBottom;
879 break;
880 case rtfRowBordRight:
881 info->borderType = RTFBorderRowRight;
882 break;
883 case rtfCellBordTop:
884 info->borderType = RTFBorderCellTop;
885 break;
886 case rtfCellBordLeft:
887 info->borderType = RTFBorderCellLeft;
888 break;
889 case rtfCellBordBottom:
890 info->borderType = RTFBorderCellBottom;
891 break;
892 case rtfCellBordRight:
893 info->borderType = RTFBorderCellRight;
894 break;
895 case rtfRowGapH:
896 if (info->tableDef)
897 info->tableDef->gapH = info->rtfParam;
898 break;
899 case rtfRowLeftEdge:
900 if (info->tableDef)
901 info->tableDef->leftEdge = info->rtfParam;
902 break;
906 void ME_RTFSpecialCharHook(RTF_Info *info)
908 RTFTable *tableDef = info->tableDef;
909 switch (info->rtfMinor)
911 case rtfNestCell:
912 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
913 break;
914 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
915 case rtfCell:
916 if (!tableDef)
917 break;
918 RTFFlushOutputBuffer(info);
919 if (!info->editor->bEmulateVersion10) { /* v4.1 */
920 if (tableDef->tableRowStart)
922 if (!info->nestingLevel &&
923 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
925 ME_DisplayItem *para = tableDef->tableRowStart;
926 para = para->member.para.next_para;
927 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
928 tableDef->tableRowStart = para;
929 info->nestingLevel = 1;
931 ME_InsertTableCellFromCursor(info->editor);
933 } else { /* v1.0 - v3.0 */
934 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
935 PARAFORMAT2 *pFmt = para->member.para.pFmt;
936 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
937 tableDef->numCellsInserted < tableDef->numCellsDefined)
939 WCHAR tab = '\t';
940 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
941 tableDef->numCellsInserted++;
944 break;
945 case rtfNestRow:
946 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
947 break;
948 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
949 case rtfRow:
951 ME_DisplayItem *para, *cell, *run;
952 int i;
954 if (!tableDef)
955 break;
956 RTFFlushOutputBuffer(info);
957 if (!info->editor->bEmulateVersion10) { /* v4.1 */
958 if (!tableDef->tableRowStart)
959 break;
960 if (!info->nestingLevel &&
961 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
963 para = tableDef->tableRowStart;
964 para = para->member.para.next_para;
965 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
966 tableDef->tableRowStart = para;
967 info->nestingLevel++;
969 para = tableDef->tableRowStart;
970 cell = ME_FindItemFwd(para, diCell);
971 assert(cell && !cell->member.cell.prev_cell);
972 if (tableDef->numCellsDefined < 1)
974 /* 2000 twips appears to be the cell size that native richedit uses
975 * when no cell sizes are specified. */
976 const int defaultCellSize = 2000;
977 int nRightBoundary = defaultCellSize;
978 cell->member.cell.nRightBoundary = nRightBoundary;
979 while (cell->member.cell.next_cell) {
980 cell = cell->member.cell.next_cell;
981 nRightBoundary += defaultCellSize;
982 cell->member.cell.nRightBoundary = nRightBoundary;
984 para = ME_InsertTableCellFromCursor(info->editor);
985 cell = para->member.para.pCell;
986 cell->member.cell.nRightBoundary = nRightBoundary;
987 } else {
988 for (i = 0; i < tableDef->numCellsDefined; i++)
990 RTFCell *cellDef = &tableDef->cells[i];
991 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
992 ME_ApplyBorderProperties(info, &cell->member.cell.border,
993 cellDef->border);
994 cell = cell->member.cell.next_cell;
995 if (!cell)
997 para = ME_InsertTableCellFromCursor(info->editor);
998 cell = para->member.para.pCell;
1001 /* Cell for table row delimiter is empty */
1002 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1005 run = ME_FindItemFwd(cell, diRun);
1006 if (info->editor->pCursors[0].pRun != run ||
1007 info->editor->pCursors[0].nOffset)
1009 int nOfs, nChars;
1010 /* Delete inserted cells that aren't defined. */
1011 info->editor->pCursors[1].pRun = run;
1012 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1013 info->editor->pCursors[1].nOffset = 0;
1014 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1015 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1016 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1017 nChars, TRUE);
1020 para = ME_InsertTableRowEndFromCursor(info->editor);
1021 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1022 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1023 ME_ApplyBorderProperties(info, &para->member.para.border,
1024 tableDef->border);
1025 info->nestingLevel--;
1026 if (!info->nestingLevel)
1028 if (info->canInheritInTbl) {
1029 tableDef->tableRowStart = para;
1030 } else {
1031 while (info->tableDef) {
1032 tableDef = info->tableDef;
1033 info->tableDef = tableDef->parent;
1034 heap_free(tableDef);
1037 } else {
1038 info->tableDef = tableDef->parent;
1039 heap_free(tableDef);
1041 } else { /* v1.0 - v3.0 */
1042 WCHAR endl = '\r';
1043 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1044 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1045 pFmt->dxOffset = info->tableDef->gapH;
1046 pFmt->dxStartIndent = info->tableDef->leftEdge;
1048 ME_ApplyBorderProperties(info, &para->member.para.border,
1049 tableDef->border);
1050 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1052 WCHAR tab = '\t';
1053 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1054 tableDef->numCellsInserted++;
1056 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1057 if (!tableDef->numCellsDefined)
1058 pFmt->wEffects &= ~PFE_TABLE;
1059 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1060 tableDef->numCellsInserted = 0;
1062 break;
1064 case rtfTab:
1065 case rtfPar:
1066 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1067 ME_DisplayItem *para;
1068 PARAFORMAT2 *pFmt;
1069 RTFFlushOutputBuffer(info);
1070 para = info->editor->pCursors[0].pPara;
1071 pFmt = para->member.para.pFmt;
1072 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1074 /* rtfPar is treated like a space within a table. */
1075 info->rtfClass = rtfText;
1076 info->rtfMajor = ' ';
1078 else if (info->rtfMinor == rtfPar && tableDef)
1079 tableDef->numCellsInserted = 0;
1081 break;
1085 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1086 const SIZEL* sz)
1088 LPOLEOBJECT lpObject = NULL;
1089 LPSTORAGE lpStorage = NULL;
1090 LPOLECLIENTSITE lpClientSite = NULL;
1091 LPDATAOBJECT lpDataObject = NULL;
1092 LPOLECACHE lpOleCache = NULL;
1093 STGMEDIUM stgm;
1094 FORMATETC fm;
1095 CLSID clsid;
1096 BOOL ret = FALSE;
1097 DWORD conn;
1099 if (hemf)
1101 stgm.tymed = TYMED_ENHMF;
1102 stgm.u.hEnhMetaFile = hemf;
1103 fm.cfFormat = CF_ENHMETAFILE;
1105 else if (hbmp)
1107 stgm.tymed = TYMED_GDI;
1108 stgm.u.hBitmap = hbmp;
1109 fm.cfFormat = CF_BITMAP;
1111 stgm.pUnkForRelease = NULL;
1113 fm.ptd = NULL;
1114 fm.dwAspect = DVASPECT_CONTENT;
1115 fm.lindex = -1;
1116 fm.tymed = stgm.tymed;
1118 if (!info->lpRichEditOle)
1120 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1123 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1124 #if 0
1125 /* FIXME: enable it when rich-edit properly implements this method */
1126 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1127 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1128 #endif
1129 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1130 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1131 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1132 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1133 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1135 REOBJECT reobject;
1137 reobject.cbStruct = sizeof(reobject);
1138 reobject.cp = REO_CP_SELECTION;
1139 reobject.clsid = clsid;
1140 reobject.poleobj = lpObject;
1141 reobject.pstg = lpStorage;
1142 reobject.polesite = lpClientSite;
1143 /* convert from twips to .01 mm */
1144 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1145 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1146 reobject.dvaspect = DVASPECT_CONTENT;
1147 reobject.dwFlags = 0; /* FIXME */
1148 reobject.dwUser = 0;
1150 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1151 ret = TRUE;
1154 if (lpObject) IOleObject_Release(lpObject);
1155 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1156 if (lpStorage) IStorage_Release(lpStorage);
1157 if (lpDataObject) IDataObject_Release(lpDataObject);
1158 if (lpOleCache) IOleCache_Release(lpOleCache);
1160 return ret;
1163 static void ME_RTFReadPictGroup(RTF_Info *info)
1165 SIZEL sz;
1166 BYTE* buffer = NULL;
1167 unsigned bufsz, bufidx;
1168 BOOL flip;
1169 BYTE val;
1170 METAFILEPICT mfp;
1171 HENHMETAFILE hemf;
1172 HBITMAP hbmp;
1173 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1175 RTFGetToken (info);
1176 if (info->rtfClass == rtfEOF)
1177 return;
1178 mfp.mm = MM_TEXT;
1179 /* fetch picture type */
1180 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1182 mfp.mm = info->rtfParam;
1183 gfx = gfx_metafile;
1185 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1187 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1188 gfx = gfx_dib;
1190 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1192 gfx = gfx_enhmetafile;
1194 else
1196 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1197 goto skip_group;
1199 sz.cx = sz.cy = 0;
1200 /* fetch picture attributes */
1201 for (;;)
1203 RTFGetToken (info);
1204 if (info->rtfClass == rtfEOF)
1205 return;
1206 if (info->rtfClass == rtfText)
1207 break;
1208 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1210 ERR("Expected picture attribute (%d %d)\n",
1211 info->rtfClass, info->rtfMajor);
1212 goto skip_group;
1214 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1216 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1218 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1220 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1222 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1223 sz.cx = info->rtfParam;
1224 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1225 sz.cy = info->rtfParam;
1226 else
1227 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1229 /* fetch picture data */
1230 bufsz = 1024;
1231 bufidx = 0;
1232 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1233 val = info->rtfMajor;
1234 for (flip = TRUE;; flip = !flip)
1236 RTFGetToken (info);
1237 if (info->rtfClass == rtfEOF)
1239 HeapFree(GetProcessHeap(), 0, buffer);
1240 return; /* Warn ?? */
1242 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1243 break;
1244 if (info->rtfClass != rtfText) goto skip_group;
1245 if (flip)
1247 if (bufidx >= bufsz &&
1248 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1249 goto skip_group;
1250 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1252 else
1253 val = info->rtfMajor;
1255 if (flip) FIXME("wrong hex string\n");
1257 switch (gfx)
1259 case gfx_enhmetafile:
1260 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1261 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1262 break;
1263 case gfx_metafile:
1264 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1265 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1266 break;
1267 case gfx_dib:
1269 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1270 HDC hdc = GetDC(0);
1271 unsigned nc = bi->bmiHeader.biClrUsed;
1273 /* not quite right, especially for bitfields type of compression */
1274 if (!nc && bi->bmiHeader.biBitCount <= 8)
1275 nc = 1 << bi->bmiHeader.biBitCount;
1276 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1277 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1278 bi, DIB_RGB_COLORS)))
1279 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1280 ReleaseDC(0, hdc);
1282 break;
1283 default:
1284 break;
1286 HeapFree(GetProcessHeap(), 0, buffer);
1287 RTFRouteToken (info); /* feed "}" back to router */
1288 return;
1289 skip_group:
1290 HeapFree(GetProcessHeap(), 0, buffer);
1291 RTFSkipGroup(info);
1292 RTFRouteToken(info); /* feed "}" back to router */
1295 /* for now, lookup the \result part and use it, whatever the object */
1296 static void ME_RTFReadObjectGroup(RTF_Info *info)
1298 for (;;)
1300 RTFGetToken (info);
1301 if (info->rtfClass == rtfEOF)
1302 return;
1303 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1304 break;
1305 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1307 RTFGetToken (info);
1308 if (info->rtfClass == rtfEOF)
1309 return;
1310 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1312 int level = 1;
1314 while (RTFGetToken (info) != rtfEOF)
1316 if (info->rtfClass == rtfGroup)
1318 if (info->rtfMajor == rtfBeginGroup) level++;
1319 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1321 RTFRouteToken(info);
1324 else RTFSkipGroup(info);
1325 continue;
1327 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1329 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1330 return;
1333 RTFRouteToken(info); /* feed "}" back to router */
1336 static void ME_RTFReadHook(RTF_Info *info)
1338 switch(info->rtfClass)
1340 case rtfGroup:
1341 switch(info->rtfMajor)
1343 case rtfBeginGroup:
1344 if (info->stackTop < maxStack) {
1345 info->stack[info->stackTop].style = info->style;
1346 ME_AddRefStyle(info->style);
1347 info->stack[info->stackTop].codePage = info->codePage;
1348 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1350 info->stackTop++;
1351 info->styleChanged = FALSE;
1352 break;
1353 case rtfEndGroup:
1355 RTFFlushOutputBuffer(info);
1356 info->stackTop--;
1357 if (info->stackTop <= 0)
1358 info->rtfClass = rtfEOF;
1359 if (info->stackTop < 0)
1360 return;
1362 ME_ReleaseStyle(info->style);
1363 info->style = info->stack[info->stackTop].style;
1364 info->codePage = info->stack[info->stackTop].codePage;
1365 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1366 break;
1369 break;
1373 void
1374 ME_StreamInFill(ME_InStream *stream)
1376 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1377 (BYTE *)stream->buffer,
1378 sizeof(stream->buffer),
1379 (LONG *)&stream->dwSize);
1380 stream->dwUsed = 0;
1383 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1385 RTF_Info parser;
1386 ME_Style *style;
1387 int from, to, nUndoMode;
1388 int nEventMask = editor->nEventMask;
1389 ME_InStream inStream;
1390 BOOL invalidRTF = FALSE;
1391 ME_Cursor *selStart, *selEnd;
1393 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1394 editor->nEventMask = 0;
1396 ME_GetSelectionOfs(editor, &from, &to);
1397 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1399 ME_GetSelection(editor, &selStart, &selEnd);
1400 style = ME_GetSelectionInsertStyle(editor);
1402 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1404 /* Don't insert text at the end of the table row */
1405 if (!editor->bEmulateVersion10) { /* v4.1 */
1406 ME_DisplayItem *para = editor->pCursors->pPara;
1407 if (para->member.para.nFlags & MEPF_ROWEND)
1409 para = para->member.para.next_para;
1410 editor->pCursors[0].pPara = para;
1411 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1412 editor->pCursors[0].nOffset = 0;
1414 if (para->member.para.nFlags & MEPF_ROWSTART)
1416 para = para->member.para.next_para;
1417 editor->pCursors[0].pPara = para;
1418 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1419 editor->pCursors[0].nOffset = 0;
1421 editor->pCursors[1] = editor->pCursors[0];
1422 } else { /* v1.0 - 3.0 */
1423 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1424 ME_IsInTable(editor->pCursors[0].pRun))
1425 return 0;
1427 } else {
1428 style = editor->pBuffer->pDefaultStyle;
1429 ME_AddRefStyle(style);
1430 ME_SetSelection(editor, 0, 0);
1431 ME_InternalDeleteText(editor, &editor->pCursors[1],
1432 ME_GetTextLength(editor), FALSE);
1433 from = to = 0;
1434 ME_ClearTempStyle(editor);
1435 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1439 /* Back up undo mode to a local variable */
1440 nUndoMode = editor->nUndoMode;
1442 /* Only create an undo if SFF_SELECTION is set */
1443 if (!(format & SFF_SELECTION))
1444 editor->nUndoMode = umIgnore;
1446 inStream.editstream = stream;
1447 inStream.editstream->dwError = 0;
1448 inStream.dwSize = 0;
1449 inStream.dwUsed = 0;
1451 if (format & SF_RTF)
1453 /* Check if it's really RTF, and if it is not, use plain text */
1454 ME_StreamInFill(&inStream);
1455 if (!inStream.editstream->dwError)
1457 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1458 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1460 invalidRTF = TRUE;
1461 inStream.editstream->dwError = -16;
1466 if (!invalidRTF && !inStream.editstream->dwError)
1468 if (format & SF_RTF) {
1469 /* setup the RTF parser */
1470 memset(&parser, 0, sizeof parser);
1471 RTFSetEditStream(&parser, &inStream);
1472 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1473 parser.editor = editor;
1474 parser.style = style;
1475 WriterInit(&parser);
1476 RTFInit(&parser);
1477 RTFSetReadHook(&parser, ME_RTFReadHook);
1478 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1479 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1480 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1482 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1483 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1485 BeginFile(&parser);
1487 /* do the parsing */
1488 RTFRead(&parser);
1489 RTFFlushOutputBuffer(&parser);
1490 if (!editor->bEmulateVersion10) { /* v4.1 */
1491 if (parser.tableDef && parser.tableDef->tableRowStart &&
1492 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1494 /* Delete any incomplete table row at the end of the rich text. */
1495 int nOfs, nChars;
1496 ME_DisplayItem *para;
1498 parser.rtfMinor = rtfRow;
1499 /* Complete the table row before deleting it.
1500 * By doing it this way we will have the current paragraph format set
1501 * properly to reflect that is not in the complete table, and undo items
1502 * will be added for this change to the current paragraph format. */
1503 if (parser.nestingLevel > 0)
1505 while (parser.nestingLevel > 1)
1506 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1507 para = parser.tableDef->tableRowStart;
1508 ME_RTFSpecialCharHook(&parser);
1509 } else {
1510 para = parser.tableDef->tableRowStart;
1511 ME_RTFSpecialCharHook(&parser);
1512 assert(para->member.para.nFlags & MEPF_ROWEND);
1513 para = para->member.para.next_para;
1516 editor->pCursors[1].pPara = para;
1517 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1518 editor->pCursors[1].nOffset = 0;
1519 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1520 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1521 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1522 if (parser.tableDef)
1523 parser.tableDef->tableRowStart = NULL;
1526 ME_CheckTablesForCorruption(editor);
1527 RTFDestroy(&parser);
1528 if (parser.lpRichEditOle)
1529 IRichEditOle_Release(parser.lpRichEditOle);
1531 if (parser.stackTop > 0)
1533 while (--parser.stackTop >= 0)
1535 ME_ReleaseStyle(parser.style);
1536 parser.style = parser.stack[parser.stackTop].style;
1538 if (!inStream.editstream->dwError)
1539 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1542 /* Remove last line break, as mandated by tests. This is not affected by
1543 CR/LF counters, since RTF streaming presents only \para tokens, which
1544 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1546 if (stripLastCR) {
1547 int newto;
1548 ME_GetSelection(editor, &selStart, &selEnd);
1549 newto = ME_GetCursorOfs(selEnd);
1550 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1551 WCHAR lastchar[3] = {'\0', '\0'};
1552 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1553 ME_Cursor linebreakCursor = *selEnd;
1555 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1556 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1557 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1558 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1563 style = parser.style;
1565 else if (format & SF_TEXT)
1566 ME_StreamInText(editor, format, &inStream, style);
1567 else
1568 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1569 /* put the cursor at the top */
1570 if (!(format & SFF_SELECTION))
1571 ME_SetSelection(editor, 0, 0);
1574 /* Restore saved undo mode */
1575 editor->nUndoMode = nUndoMode;
1577 /* even if we didn't add an undo, we need to commit anything on the stack */
1578 ME_CommitUndo(editor);
1580 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1581 if (!(format & SFF_SELECTION))
1582 ME_EmptyUndoStack(editor);
1584 ME_ReleaseStyle(style);
1585 editor->nEventMask = nEventMask;
1586 ME_UpdateRepaint(editor, FALSE);
1587 if (!(format & SFF_SELECTION)) {
1588 ME_ClearTempStyle(editor);
1590 ITextHost_TxShowCaret(editor->texthost, FALSE);
1591 ME_MoveCaret(editor);
1592 ITextHost_TxShowCaret(editor->texthost, TRUE);
1593 ME_SendSelChange(editor);
1594 ME_SendRequestResize(editor, FALSE);
1596 return 0;
1600 typedef struct tagME_RTFStringStreamStruct
1602 char *string;
1603 int pos;
1604 int length;
1605 } ME_RTFStringStreamStruct;
1607 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1609 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1610 int count;
1612 count = min(cb, pStruct->length - pStruct->pos);
1613 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1614 pStruct->pos += count;
1615 *pcb = count;
1616 return 0;
1619 static void
1620 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1622 EDITSTREAM es;
1623 ME_RTFStringStreamStruct data;
1625 data.string = string;
1626 data.length = strlen(string);
1627 data.pos = 0;
1628 es.dwCookie = (DWORD_PTR)&data;
1629 es.pfnCallback = ME_ReadFromRTFString;
1630 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1634 static int
1635 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1637 const int nLen = lstrlenW(text);
1638 const int nTextLen = ME_GetTextLength(editor);
1639 int nMin, nMax;
1640 ME_Cursor cursor;
1641 WCHAR wLastChar = ' ';
1643 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1644 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1646 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1647 FIXME("Flags 0x%08x not implemented\n",
1648 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1650 nMin = chrg->cpMin;
1651 if (chrg->cpMax == -1)
1652 nMax = nTextLen;
1653 else
1654 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1656 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1657 if (editor->bEmulateVersion10 && nMax == nTextLen)
1659 flags |= FR_DOWN;
1662 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1663 if (editor->bEmulateVersion10 && nMax < nMin)
1665 if (chrgText)
1667 chrgText->cpMin = -1;
1668 chrgText->cpMax = -1;
1670 return -1;
1673 /* when searching up, if cpMin < cpMax, then instead of searching
1674 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1675 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1676 * case, it is always bigger than cpMin.
1678 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1680 int nSwap = nMax;
1682 nMax = nMin > nTextLen ? nTextLen : nMin;
1683 if (nMin < nSwap || chrg->cpMax == -1)
1684 nMin = 0;
1685 else
1686 nMin = nSwap;
1689 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1691 if (chrgText)
1692 chrgText->cpMin = chrgText->cpMax = -1;
1693 return -1;
1696 if (flags & FR_DOWN) /* Forward search */
1698 /* If possible, find the character before where the search starts */
1699 if ((flags & FR_WHOLEWORD) && nMin)
1701 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1702 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1703 ME_MoveCursorChars(editor, &cursor, 1);
1704 } else {
1705 ME_CursorFromCharOfs(editor, nMin, &cursor);
1708 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1710 ME_DisplayItem *pCurItem = cursor.pRun;
1711 int nCurStart = cursor.nOffset;
1712 int nMatched = 0;
1714 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1716 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1717 break;
1719 nMatched++;
1720 if (nMatched == nLen)
1722 ME_DisplayItem *pNextItem = pCurItem;
1723 int nNextStart = nCurStart;
1724 WCHAR wNextChar;
1726 /* Check to see if next character is a whitespace */
1727 if (flags & FR_WHOLEWORD)
1729 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1731 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1732 nNextStart = -nMatched;
1735 if (pNextItem)
1736 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1737 else
1738 wNextChar = ' ';
1740 if (isalnumW(wNextChar))
1741 break;
1744 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1745 if (chrgText)
1747 chrgText->cpMin = cursor.nOffset;
1748 chrgText->cpMax = cursor.nOffset + nLen;
1750 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1751 return cursor.nOffset;
1753 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1755 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1756 nCurStart = -nMatched;
1759 if (pCurItem)
1760 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1761 else
1762 wLastChar = ' ';
1764 cursor.nOffset++;
1765 if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1767 ME_NextRun(&cursor.pPara, &cursor.pRun);
1768 cursor.nOffset = 0;
1772 else /* Backward search */
1774 /* If possible, find the character after where the search ends */
1775 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1777 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1778 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1779 ME_MoveCursorChars(editor, &cursor, -1);
1780 } else {
1781 ME_CursorFromCharOfs(editor, nMax, &cursor);
1784 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1786 ME_DisplayItem *pCurItem = cursor.pRun;
1787 ME_DisplayItem *pCurPara = cursor.pPara;
1788 int nCurEnd = cursor.nOffset;
1789 int nMatched = 0;
1791 if (nCurEnd == 0)
1793 ME_PrevRun(&pCurPara, &pCurItem);
1794 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1797 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1799 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1800 break;
1802 nMatched++;
1803 if (nMatched == nLen)
1805 ME_DisplayItem *pPrevItem = pCurItem;
1806 int nPrevEnd = nCurEnd;
1807 WCHAR wPrevChar;
1808 int nStart;
1810 /* Check to see if previous character is a whitespace */
1811 if (flags & FR_WHOLEWORD)
1813 if (nPrevEnd - nMatched == 0)
1815 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1816 if (pPrevItem)
1817 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1820 if (pPrevItem)
1821 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1822 else
1823 wPrevChar = ' ';
1825 if (isalnumW(wPrevChar))
1826 break;
1829 nStart = pCurPara->member.para.nCharOfs
1830 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1831 if (chrgText)
1833 chrgText->cpMin = nStart;
1834 chrgText->cpMax = nStart + nLen;
1836 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1837 return nStart;
1839 if (nCurEnd - nMatched == 0)
1841 ME_PrevRun(&pCurPara, &pCurItem);
1842 /* Don't care about pCurItem becoming NULL here; it's already taken
1843 * care of in the exterior loop condition */
1844 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1847 if (pCurItem)
1848 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1849 else
1850 wLastChar = ' ';
1852 cursor.nOffset--;
1853 if (cursor.nOffset < 0)
1855 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1856 cursor.nOffset = cursor.pRun->member.run.strText->nLen;
1860 TRACE("not found\n");
1861 if (chrgText)
1862 chrgText->cpMin = chrgText->cpMax = -1;
1863 return -1;
1866 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1868 int nChars;
1869 ME_Cursor start;
1871 if (!ex->cb || !pText) return 0;
1873 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1874 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1876 if (ex->flags & GT_SELECTION)
1878 int from, to;
1879 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1880 start = editor->pCursors[nStartCur];
1881 nChars = to - from;
1883 else
1885 ME_SetCursorToStart(editor, &start);
1886 nChars = INT_MAX;
1888 if (ex->codepage == 1200)
1890 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1891 &start, nChars, ex->flags & GT_USECRLF);
1893 else
1895 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1896 we can just take a bigger buffer? :)
1897 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1898 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1900 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1901 DWORD buflen;
1902 LPWSTR buffer;
1903 LRESULT rc;
1905 buflen = min(crlfmul * nChars, ex->cb - 1);
1906 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1908 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1909 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1910 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1911 if (rc) rc--; /* do not count 0 terminator */
1913 heap_free(buffer);
1914 return rc;
1918 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1919 const ME_Cursor *start, int nLen, BOOL unicode)
1921 if (!strText) return 0;
1922 if (unicode) {
1923 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1924 } else {
1925 int nChars;
1926 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1927 if (!p) return 0;
1928 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1929 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1930 nLen+1, NULL, NULL);
1931 FREE_OBJ(p);
1932 return nChars;
1936 typedef struct tagME_GlobalDestStruct
1938 HGLOBAL hData;
1939 int nLength;
1940 } ME_GlobalDestStruct;
1942 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1944 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1945 int i;
1946 WORD *pSrc, *pDest;
1948 cb = cb >> 1;
1949 pDest = (WORD *)lpBuff;
1950 pSrc = GlobalLock(pData->hData);
1951 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1952 pDest[i] = pSrc[pData->nLength+i];
1954 pData->nLength += i;
1955 *pcb = 2*i;
1956 GlobalUnlock(pData->hData);
1957 return 0;
1960 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1962 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1963 int i;
1964 BYTE *pSrc, *pDest;
1966 pDest = lpBuff;
1967 pSrc = GlobalLock(pData->hData);
1968 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1969 pDest[i] = pSrc[pData->nLength+i];
1971 pData->nLength += i;
1972 *pcb = i;
1973 GlobalUnlock(pData->hData);
1974 return 0;
1977 static BOOL ME_Paste(ME_TextEditor *editor)
1979 DWORD dwFormat = 0;
1980 EDITSTREAM es;
1981 ME_GlobalDestStruct gds;
1982 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1983 UINT cf = 0;
1985 if (IsClipboardFormatAvailable(nRTFFormat))
1986 cf = nRTFFormat, dwFormat = SF_RTF;
1987 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1988 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1989 else
1990 return FALSE;
1992 if (!OpenClipboard(editor->hWnd))
1993 return FALSE;
1994 gds.hData = GetClipboardData(cf);
1995 gds.nLength = 0;
1996 es.dwCookie = (DWORD_PTR)&gds;
1997 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1998 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2000 CloseClipboard();
2001 return TRUE;
2004 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2006 LPDATAOBJECT dataObj = NULL;
2007 HRESULT hr = S_OK;
2009 if (editor->cPasswordMask)
2010 return FALSE; /* Copying or Cutting masked text isn't allowed */
2012 if(editor->lpOleCallback)
2014 CHARRANGE range;
2015 range.cpMin = ME_GetCursorOfs(start);
2016 range.cpMax = range.cpMin + nChars;
2017 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2019 if(FAILED(hr) || !dataObj)
2020 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2021 if(SUCCEEDED(hr)) {
2022 hr = OleSetClipboard(dataObj);
2023 IDataObject_Release(dataObj);
2025 return SUCCEEDED(hr) != 0;
2028 /* helper to send a msg filter notification */
2029 static BOOL
2030 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2032 MSGFILTER msgf;
2034 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2035 msgf.nmhdr.hwndFrom = editor->hWnd;
2036 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2037 msgf.nmhdr.code = EN_MSGFILTER;
2038 msgf.msg = msg;
2039 msgf.wParam = *wParam;
2040 msgf.lParam = *lParam;
2041 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2042 return FALSE;
2043 *wParam = msgf.wParam;
2044 *lParam = msgf.lParam;
2045 msgf.wParam = *wParam;
2047 return TRUE;
2050 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2052 ME_DisplayItem *startPara, *endPara;
2053 ME_DisplayItem *prev_para;
2054 ME_Cursor *from, *to;
2055 ME_Cursor start;
2056 int nChars;
2058 if (!editor->AutoURLDetect_bEnable) return;
2060 ME_GetSelection(editor, &from, &to);
2062 /* Find paragraph previous to the one that contains start cursor */
2063 startPara = from->pPara;
2064 prev_para = startPara->member.para.prev_para;
2065 if (prev_para->type == diParagraph) startPara = prev_para;
2067 /* Find paragraph that contains end cursor */
2068 endPara = to->pPara->member.para.next_para;
2070 start.pPara = startPara;
2071 start.pRun = ME_FindItemFwd(startPara, diRun);
2072 start.nOffset = 0;
2073 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2075 ME_UpdateLinkAttribute(editor, &start, nChars);
2078 static BOOL
2079 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2081 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2082 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2084 if (editor->bMouseCaptured)
2085 return FALSE;
2086 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2087 editor->nSelectionType = stPosition;
2089 switch (nKey)
2091 case VK_LEFT:
2092 case VK_RIGHT:
2093 case VK_HOME:
2094 case VK_END:
2095 editor->nUDArrowX = -1;
2096 /* fall through */
2097 case VK_UP:
2098 case VK_DOWN:
2099 case VK_PRIOR:
2100 case VK_NEXT:
2101 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2102 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2103 return TRUE;
2104 case VK_BACK:
2105 case VK_DELETE:
2106 editor->nUDArrowX = -1;
2107 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2108 if (editor->styleFlags & ES_READONLY)
2109 return FALSE;
2110 if (ME_IsSelection(editor))
2112 ME_DeleteSelection(editor);
2113 ME_CommitUndo(editor);
2115 else if (nKey == VK_DELETE)
2117 /* Delete stops group typing.
2118 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2119 ME_DeleteTextAtCursor(editor, 1, 1);
2120 ME_CommitUndo(editor);
2122 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2124 BOOL bDeletionSucceeded;
2125 /* Backspace can be grouped for a single undo */
2126 ME_ContinueCoalescingTransaction(editor);
2127 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2128 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2129 /* Deletion was prevented so the cursor is moved back to where it was.
2130 * (e.g. this happens when trying to delete cell boundaries)
2132 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2134 ME_CommitCoalescingUndo(editor);
2136 else
2137 return TRUE;
2138 ME_MoveCursorFromTableRowStartParagraph(editor);
2139 ME_UpdateSelectionLinkAttribute(editor);
2140 ME_UpdateRepaint(editor, FALSE);
2141 ME_SendRequestResize(editor, FALSE);
2142 return TRUE;
2143 case VK_RETURN:
2144 if (editor->bDialogMode)
2146 if (ctrl_is_down)
2147 return TRUE;
2149 if (!(editor->styleFlags & ES_WANTRETURN))
2151 if (editor->hwndParent)
2153 DWORD dw;
2154 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2155 if (HIWORD(dw) == DC_HASDEFID)
2157 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2158 if (hwDefCtrl)
2160 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2161 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2165 return TRUE;
2169 if (editor->styleFlags & ES_MULTILINE)
2171 ME_Cursor cursor = editor->pCursors[0];
2172 ME_DisplayItem *para = cursor.pPara;
2173 int from, to;
2174 const WCHAR endl = '\r';
2175 ME_Style *style;
2177 if (editor->styleFlags & ES_READONLY) {
2178 MessageBeep(MB_ICONERROR);
2179 return TRUE;
2182 ME_GetSelectionOfs(editor, &from, &to);
2183 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2185 if (!editor->bEmulateVersion10) { /* v4.1 */
2186 if (para->member.para.nFlags & MEPF_ROWEND) {
2187 /* Add a new table row after this row. */
2188 para = ME_AppendTableRow(editor, para);
2189 para = para->member.para.next_para;
2190 editor->pCursors[0].pPara = para;
2191 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2192 editor->pCursors[0].nOffset = 0;
2193 editor->pCursors[1] = editor->pCursors[0];
2194 ME_CommitUndo(editor);
2195 ME_CheckTablesForCorruption(editor);
2196 ME_UpdateRepaint(editor, FALSE);
2197 return TRUE;
2199 else if (para == editor->pCursors[1].pPara &&
2200 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2201 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2202 !para->member.para.prev_para->member.para.nCharOfs)
2204 /* Insert a newline before the table. */
2205 para = para->member.para.prev_para;
2206 para->member.para.nFlags &= ~MEPF_ROWSTART;
2207 editor->pCursors[0].pPara = para;
2208 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2209 editor->pCursors[1] = editor->pCursors[0];
2210 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2211 editor->pCursors[0].pRun->member.run.style);
2212 para = editor->pBuffer->pFirst->member.para.next_para;
2213 ME_SetDefaultParaFormat(para->member.para.pFmt);
2214 para->member.para.nFlags = MEPF_REWRAP;
2215 editor->pCursors[0].pPara = para;
2216 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2217 editor->pCursors[1] = editor->pCursors[0];
2218 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2219 ME_CommitCoalescingUndo(editor);
2220 ME_CheckTablesForCorruption(editor);
2221 ME_UpdateRepaint(editor, FALSE);
2222 return TRUE;
2224 } else { /* v1.0 - 3.0 */
2225 ME_DisplayItem *para = cursor.pPara;
2226 if (ME_IsInTable(para))
2228 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2230 if (from == to) {
2231 ME_ContinueCoalescingTransaction(editor);
2232 para = ME_AppendTableRow(editor, para);
2233 editor->pCursors[0].pPara = para;
2234 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2235 editor->pCursors[0].nOffset = 0;
2236 editor->pCursors[1] = editor->pCursors[0];
2237 ME_CommitCoalescingUndo(editor);
2238 ME_UpdateRepaint(editor, FALSE);
2239 return TRUE;
2241 } else {
2242 ME_ContinueCoalescingTransaction(editor);
2243 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2244 !ME_IsInTable(para->member.para.prev_para))
2246 /* Insert newline before table */
2247 cursor.pRun = ME_FindItemBack(para, diRun);
2248 if (cursor.pRun) {
2249 editor->pCursors[0].pRun = cursor.pRun;
2250 editor->pCursors[0].pPara = para->member.para.prev_para;
2252 editor->pCursors[0].nOffset = 0;
2253 editor->pCursors[1] = editor->pCursors[0];
2254 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2255 editor->pCursors[0].pRun->member.run.style);
2256 } else {
2257 editor->pCursors[1] = editor->pCursors[0];
2258 para = ME_AppendTableRow(editor, para);
2259 editor->pCursors[0].pPara = para;
2260 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2261 editor->pCursors[0].nOffset = 0;
2262 editor->pCursors[1] = editor->pCursors[0];
2264 ME_CommitCoalescingUndo(editor);
2265 ME_UpdateRepaint(editor, FALSE);
2266 return TRUE;
2271 style = ME_GetInsertStyle(editor, 0);
2272 ME_SaveTempStyle(editor);
2273 ME_ContinueCoalescingTransaction(editor);
2274 if (shift_is_down)
2275 ME_InsertEndRowFromCursor(editor, 0);
2276 else
2277 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2278 ME_ReleaseStyle(style);
2279 ME_CommitCoalescingUndo(editor);
2280 SetCursor(NULL);
2282 ME_UpdateSelectionLinkAttribute(editor);
2283 ME_UpdateRepaint(editor, FALSE);
2285 return TRUE;
2287 break;
2288 case VK_ESCAPE:
2289 if (editor->bDialogMode && editor->hwndParent)
2290 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2291 return TRUE;
2292 case VK_TAB:
2293 if (editor->bDialogMode && editor->hwndParent)
2294 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2295 return TRUE;
2296 case 'A':
2297 if (ctrl_is_down)
2299 ME_SetSelection(editor, 0, -1);
2300 return TRUE;
2302 break;
2303 case 'V':
2304 if (ctrl_is_down)
2305 return ME_Paste(editor);
2306 break;
2307 case 'C':
2308 case 'X':
2309 if (ctrl_is_down)
2311 BOOL result;
2312 int nOfs, nChars;
2313 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2314 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2316 nChars -= nOfs;
2317 result = ME_Copy(editor, selStart, nChars);
2318 if (result && nKey == 'X')
2320 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2321 ME_CommitUndo(editor);
2322 ME_UpdateRepaint(editor, TRUE);
2324 return result;
2326 break;
2327 case 'Z':
2328 if (ctrl_is_down)
2330 ME_Undo(editor);
2331 return TRUE;
2333 break;
2334 case 'Y':
2335 if (ctrl_is_down)
2337 ME_Redo(editor);
2338 return TRUE;
2340 break;
2342 default:
2343 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2344 editor->nUDArrowX = -1;
2345 if (ctrl_is_down)
2347 if (nKey == 'W')
2349 CHARFORMAT2W chf;
2350 char buf[2048];
2351 chf.cbSize = sizeof(chf);
2353 ME_GetSelectionCharFormat(editor, &chf);
2354 ME_DumpStyleToBuf(&chf, buf);
2355 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2357 if (nKey == 'Q')
2359 ME_CheckCharOffsets(editor);
2363 return FALSE;
2366 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2367 LPARAM flags, BOOL unicode)
2369 WCHAR wstr;
2371 if (editor->bMouseCaptured)
2372 return 0;
2374 if (unicode)
2375 wstr = (WCHAR)charCode;
2376 else
2378 CHAR charA = charCode;
2379 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2382 if (editor->styleFlags & ES_READONLY) {
2383 MessageBeep(MB_ICONERROR);
2384 return 0; /* FIXME really 0 ? */
2387 if ((unsigned)wstr >= ' ' || wstr == '\t')
2389 ME_Cursor cursor = editor->pCursors[0];
2390 ME_DisplayItem *para = cursor.pPara;
2391 int from, to;
2392 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2393 ME_GetSelectionOfs(editor, &from, &to);
2394 if (wstr == '\t' &&
2395 /* v4.1 allows tabs to be inserted with ctrl key down */
2396 !(ctrl_is_down && !editor->bEmulateVersion10))
2398 ME_DisplayItem *para;
2399 BOOL bSelectedRow = FALSE;
2401 para = cursor.pPara;
2402 if (ME_IsSelection(editor) &&
2403 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2404 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2405 para->member.para.prev_para->type == diParagraph)
2407 para = para->member.para.prev_para;
2408 bSelectedRow = TRUE;
2410 if (ME_IsInTable(para))
2412 ME_TabPressedInTable(editor, bSelectedRow);
2413 ME_CommitUndo(editor);
2414 return 0;
2416 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2417 if (para->member.para.nFlags & MEPF_ROWEND) {
2418 if (from == to) {
2419 para = para->member.para.next_para;
2420 if (para->member.para.nFlags & MEPF_ROWSTART)
2421 para = para->member.para.next_para;
2422 editor->pCursors[0].pPara = para;
2423 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2424 editor->pCursors[0].nOffset = 0;
2425 editor->pCursors[1] = editor->pCursors[0];
2428 } else { /* v1.0 - 3.0 */
2429 if (ME_IsInTable(cursor.pRun) &&
2430 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2431 from == to)
2433 /* Text should not be inserted at the end of the table. */
2434 MessageBeep(-1);
2435 return 0;
2438 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2439 /* WM_CHAR is restricted to nTextLimit */
2440 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2442 ME_Style *style = ME_GetInsertStyle(editor, 0);
2443 ME_SaveTempStyle(editor);
2444 ME_ContinueCoalescingTransaction(editor);
2445 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2446 ME_ReleaseStyle(style);
2447 ME_CommitCoalescingUndo(editor);
2448 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2451 ME_UpdateSelectionLinkAttribute(editor);
2452 ME_UpdateRepaint(editor, FALSE);
2454 return 0;
2457 /* Process the message and calculate the new click count.
2459 * returns: The click count if it is mouse down event, else returns 0. */
2460 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2461 LPARAM lParam)
2463 static int clickNum = 0;
2464 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2465 return 0;
2467 if ((msg == WM_LBUTTONDBLCLK) ||
2468 (msg == WM_RBUTTONDBLCLK) ||
2469 (msg == WM_MBUTTONDBLCLK) ||
2470 (msg == WM_XBUTTONDBLCLK))
2472 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2475 if ((msg == WM_LBUTTONDOWN) ||
2476 (msg == WM_RBUTTONDOWN) ||
2477 (msg == WM_MBUTTONDOWN) ||
2478 (msg == WM_XBUTTONDOWN))
2480 static MSG prevClickMsg;
2481 MSG clickMsg;
2482 /* Compare the editor instead of the hwnd so that the this
2483 * can still be done for windowless richedit controls. */
2484 clickMsg.hwnd = (HWND)editor;
2485 clickMsg.message = msg;
2486 clickMsg.wParam = wParam;
2487 clickMsg.lParam = lParam;
2488 clickMsg.time = GetMessageTime();
2489 clickMsg.pt.x = (short)LOWORD(lParam);
2490 clickMsg.pt.y = (short)HIWORD(lParam);
2491 if ((clickNum != 0) &&
2492 (clickMsg.message == prevClickMsg.message) &&
2493 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2494 (clickMsg.wParam == prevClickMsg.wParam) &&
2495 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2496 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2497 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2499 clickNum++;
2500 } else {
2501 clickNum = 1;
2503 prevClickMsg = clickMsg;
2504 } else {
2505 return 0;
2507 return clickNum;
2510 static BOOL ME_SetCursor(ME_TextEditor *editor)
2512 ME_Cursor cursor;
2513 POINT pt;
2514 BOOL isExact;
2515 SCROLLBARINFO sbi;
2516 DWORD messagePos = GetMessagePos();
2517 pt.x = (short)LOWORD(messagePos);
2518 pt.y = (short)HIWORD(messagePos);
2520 if (editor->hWnd)
2522 sbi.cbSize = sizeof(sbi);
2523 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2524 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2525 PtInRect(&sbi.rcScrollBar, pt))
2527 ITextHost_TxSetCursor(editor->texthost,
2528 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2529 return TRUE;
2531 sbi.cbSize = sizeof(sbi);
2532 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2533 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2534 PtInRect(&sbi.rcScrollBar, pt))
2536 ITextHost_TxSetCursor(editor->texthost,
2537 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2538 return TRUE;
2541 ITextHost_TxScreenToClient(editor->texthost, &pt);
2543 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2544 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2545 return TRUE;
2547 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2548 pt.y < editor->rcFormat.top &&
2549 pt.x < editor->rcFormat.left)
2551 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2552 return TRUE;
2554 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2556 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2557 ITextHost_TxSetCursor(editor->texthost,
2558 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2559 else /* v4.1 */
2560 ITextHost_TxSetCursor(editor->texthost,
2561 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2562 return TRUE;
2564 if (pt.x < editor->rcFormat.left)
2566 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2567 return TRUE;
2569 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2570 if (isExact)
2572 ME_Run *run;
2574 run = &cursor.pRun->member.run;
2575 if (run->style->fmt.dwMask & CFM_LINK &&
2576 run->style->fmt.dwEffects & CFE_LINK)
2578 ITextHost_TxSetCursor(editor->texthost,
2579 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2580 FALSE);
2581 return TRUE;
2584 if (ME_IsSelection(editor))
2586 int selStart, selEnd;
2587 int offset = ME_GetCursorOfs(&cursor);
2589 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2590 if (selStart <= offset && selEnd >= offset) {
2591 ITextHost_TxSetCursor(editor->texthost,
2592 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2593 FALSE);
2594 return TRUE;
2598 ITextHost_TxSetCursor(editor->texthost,
2599 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2600 return TRUE;
2603 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2605 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2606 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2607 editor->rcFormat.left += 1 + editor->selofs;
2608 editor->rcFormat.right -= 1;
2611 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2613 CHARRANGE selrange;
2614 HMENU menu;
2615 int seltype = 0;
2616 if(!editor->lpOleCallback || !editor->hWnd)
2617 return FALSE;
2618 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2619 if(selrange.cpMin == selrange.cpMax)
2620 seltype |= SEL_EMPTY;
2621 else
2623 /* FIXME: Handle objects */
2624 seltype |= SEL_TEXT;
2625 if(selrange.cpMax-selrange.cpMin > 1)
2626 seltype |= SEL_MULTICHAR;
2628 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2630 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2631 DestroyMenu(menu);
2633 return TRUE;
2636 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2638 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2639 int i;
2640 DWORD props;
2641 LONG selbarwidth;
2643 ed->hWnd = NULL;
2644 ed->hwndParent = NULL;
2645 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2646 ed->texthost = texthost;
2647 ed->bEmulateVersion10 = bEmulateVersion10;
2648 ed->styleFlags = 0;
2649 ITextHost_TxGetPropertyBits(texthost,
2650 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2651 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2652 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2653 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2654 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2655 &props);
2656 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2657 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2658 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2659 ed->pBuffer = ME_MakeText();
2660 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2661 ed->nAvailWidth = 0; /* wrap to client area */
2662 ME_MakeFirstParagraph(ed);
2663 /* The four cursors are for:
2664 * 0 - The position where the caret is shown
2665 * 1 - The anchored end of the selection (for normal selection)
2666 * 2 & 3 - The anchored start and end respectively for word, line,
2667 * or paragraph selection.
2669 ed->nCursors = 4;
2670 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2671 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2672 ed->pCursors[1] = ed->pCursors[0];
2673 ed->pCursors[2] = ed->pCursors[0];
2674 ed->pCursors[3] = ed->pCursors[1];
2675 ed->nLastTotalLength = ed->nTotalLength = 0;
2676 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2677 ed->nUDArrowX = -1;
2678 ed->nSequence = 0;
2679 ed->rgbBackColor = -1;
2680 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2681 ed->bCaretAtEnd = FALSE;
2682 ed->nEventMask = 0;
2683 ed->nModifyStep = 0;
2684 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2685 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2686 ed->nUndoStackSize = 0;
2687 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2688 ed->nUndoMode = umAddToUndo;
2689 ed->nParagraphs = 1;
2690 ed->nLastSelStart = ed->nLastSelEnd = 0;
2691 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2692 ed->bHideSelection = FALSE;
2693 ed->pfnWordBreak = NULL;
2694 ed->lpOleCallback = NULL;
2695 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2696 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2697 ed->AutoURLDetect_bEnable = FALSE;
2698 ed->bHaveFocus = FALSE;
2699 ed->bDialogMode = FALSE;
2700 ed->bMouseCaptured = FALSE;
2701 for (i=0; i<HFONT_CACHE_SIZE; i++)
2703 ed->pFontCache[i].nRefs = 0;
2704 ed->pFontCache[i].nAge = 0;
2705 ed->pFontCache[i].hFont = NULL;
2708 ME_CheckCharOffsets(ed);
2709 ed->bDefaultFormatRect = TRUE;
2710 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2711 if (selbarwidth) {
2712 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2713 ed->selofs = SELECTIONBAR_WIDTH;
2714 ed->styleFlags |= ES_SELECTIONBAR;
2715 } else {
2716 ed->selofs = 0;
2718 ed->nSelectionType = stPosition;
2720 ed->cPasswordMask = 0;
2721 if (props & TXTBIT_USEPASSWORD)
2722 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2724 if (props & TXTBIT_AUTOWORDSEL)
2725 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2726 if (props & TXTBIT_MULTILINE) {
2727 ed->styleFlags |= ES_MULTILINE;
2728 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2729 } else {
2730 ed->bWordWrap = FALSE;
2732 if (props & TXTBIT_READONLY)
2733 ed->styleFlags |= ES_READONLY;
2734 if (!(props & TXTBIT_HIDESELECTION))
2735 ed->styleFlags |= ES_NOHIDESEL;
2736 if (props & TXTBIT_SAVESELECTION)
2737 ed->styleFlags |= ES_SAVESEL;
2738 if (props & TXTBIT_VERTICAL)
2739 ed->styleFlags |= ES_VERTICAL;
2740 if (props & TXTBIT_DISABLEDRAG)
2741 ed->styleFlags |= ES_NOOLEDRAGDROP;
2743 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2745 /* Default scrollbar information */
2746 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2747 ed->vert_si.nMin = 0;
2748 ed->vert_si.nMax = 0;
2749 ed->vert_si.nPage = 0;
2750 ed->vert_si.nPos = 0;
2752 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2753 ed->horz_si.nMin = 0;
2754 ed->horz_si.nMax = 0;
2755 ed->horz_si.nPage = 0;
2756 ed->horz_si.nPos = 0;
2758 OleInitialize(NULL);
2760 return ed;
2763 static void ME_DestroyEditor(ME_TextEditor *editor)
2765 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2766 ME_DisplayItem *p = pFirst, *pNext = NULL;
2767 int i;
2769 ME_ClearTempStyle(editor);
2770 ME_EmptyUndoStack(editor);
2771 while(p) {
2772 pNext = p->next;
2773 ME_DestroyDisplayItem(p);
2774 p = pNext;
2776 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2777 for (i=0; i<HFONT_CACHE_SIZE; i++)
2779 if (editor->pFontCache[i].hFont)
2780 DeleteObject(editor->pFontCache[i].hFont);
2782 if (editor->rgbBackColor != -1)
2783 DeleteObject(editor->hbrBackground);
2784 if(editor->lpOleCallback)
2785 IUnknown_Release(editor->lpOleCallback);
2786 IUnknown_Release(editor->texthost);
2787 OleUninitialize();
2789 FREE_OBJ(editor->pBuffer);
2790 FREE_OBJ(editor->pCursors);
2792 FREE_OBJ(editor);
2795 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2797 TRACE("\n");
2798 switch (fdwReason)
2800 case DLL_PROCESS_ATTACH:
2801 DisableThreadLibraryCalls(hinstDLL);
2802 me_heap = HeapCreate (0, 0x10000, 0);
2803 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2804 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2805 LookupInit();
2806 break;
2808 case DLL_PROCESS_DETACH:
2809 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2810 UnregisterClassW(MSFTEDIT_CLASS, 0);
2811 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2812 UnregisterClassA("RichEdit50A", 0);
2813 if (ME_ListBoxRegistered)
2814 UnregisterClassW(REListBox20W, 0);
2815 if (ME_ComboBoxRegistered)
2816 UnregisterClassW(REComboBox20W, 0);
2817 LookupCleanup();
2818 HeapDestroy (me_heap);
2819 me_heap = NULL;
2820 break;
2822 return TRUE;
2826 static const char * const edit_messages[] = {
2827 "EM_GETSEL",
2828 "EM_SETSEL",
2829 "EM_GETRECT",
2830 "EM_SETRECT",
2831 "EM_SETRECTNP",
2832 "EM_SCROLL",
2833 "EM_LINESCROLL",
2834 "EM_SCROLLCARET",
2835 "EM_GETMODIFY",
2836 "EM_SETMODIFY",
2837 "EM_GETLINECOUNT",
2838 "EM_LINEINDEX",
2839 "EM_SETHANDLE",
2840 "EM_GETHANDLE",
2841 "EM_GETTHUMB",
2842 "EM_UNKNOWN_BF",
2843 "EM_UNKNOWN_C0",
2844 "EM_LINELENGTH",
2845 "EM_REPLACESEL",
2846 "EM_UNKNOWN_C3",
2847 "EM_GETLINE",
2848 "EM_LIMITTEXT",
2849 "EM_CANUNDO",
2850 "EM_UNDO",
2851 "EM_FMTLINES",
2852 "EM_LINEFROMCHAR",
2853 "EM_UNKNOWN_CA",
2854 "EM_SETTABSTOPS",
2855 "EM_SETPASSWORDCHAR",
2856 "EM_EMPTYUNDOBUFFER",
2857 "EM_GETFIRSTVISIBLELINE",
2858 "EM_SETREADONLY",
2859 "EM_SETWORDBREAKPROC",
2860 "EM_GETWORDBREAKPROC",
2861 "EM_GETPASSWORDCHAR",
2862 "EM_SETMARGINS",
2863 "EM_GETMARGINS",
2864 "EM_GETLIMITTEXT",
2865 "EM_POSFROMCHAR",
2866 "EM_CHARFROMPOS",
2867 "EM_SETIMESTATUS",
2868 "EM_GETIMESTATUS"
2871 static const char * const richedit_messages[] = {
2872 "EM_CANPASTE",
2873 "EM_DISPLAYBAND",
2874 "EM_EXGETSEL",
2875 "EM_EXLIMITTEXT",
2876 "EM_EXLINEFROMCHAR",
2877 "EM_EXSETSEL",
2878 "EM_FINDTEXT",
2879 "EM_FORMATRANGE",
2880 "EM_GETCHARFORMAT",
2881 "EM_GETEVENTMASK",
2882 "EM_GETOLEINTERFACE",
2883 "EM_GETPARAFORMAT",
2884 "EM_GETSELTEXT",
2885 "EM_HIDESELECTION",
2886 "EM_PASTESPECIAL",
2887 "EM_REQUESTRESIZE",
2888 "EM_SELECTIONTYPE",
2889 "EM_SETBKGNDCOLOR",
2890 "EM_SETCHARFORMAT",
2891 "EM_SETEVENTMASK",
2892 "EM_SETOLECALLBACK",
2893 "EM_SETPARAFORMAT",
2894 "EM_SETTARGETDEVICE",
2895 "EM_STREAMIN",
2896 "EM_STREAMOUT",
2897 "EM_GETTEXTRANGE",
2898 "EM_FINDWORDBREAK",
2899 "EM_SETOPTIONS",
2900 "EM_GETOPTIONS",
2901 "EM_FINDTEXTEX",
2902 "EM_GETWORDBREAKPROCEX",
2903 "EM_SETWORDBREAKPROCEX",
2904 "EM_SETUNDOLIMIT",
2905 "EM_UNKNOWN_USER_83",
2906 "EM_REDO",
2907 "EM_CANREDO",
2908 "EM_GETUNDONAME",
2909 "EM_GETREDONAME",
2910 "EM_STOPGROUPTYPING",
2911 "EM_SETTEXTMODE",
2912 "EM_GETTEXTMODE",
2913 "EM_AUTOURLDETECT",
2914 "EM_GETAUTOURLDETECT",
2915 "EM_SETPALETTE",
2916 "EM_GETTEXTEX",
2917 "EM_GETTEXTLENGTHEX",
2918 "EM_SHOWSCROLLBAR",
2919 "EM_SETTEXTEX",
2920 "EM_UNKNOWN_USER_98",
2921 "EM_UNKNOWN_USER_99",
2922 "EM_SETPUNCTUATION",
2923 "EM_GETPUNCTUATION",
2924 "EM_SETWORDWRAPMODE",
2925 "EM_GETWORDWRAPMODE",
2926 "EM_SETIMECOLOR",
2927 "EM_GETIMECOLOR",
2928 "EM_SETIMEOPTIONS",
2929 "EM_GETIMEOPTIONS",
2930 "EM_CONVPOSITION",
2931 "EM_UNKNOWN_USER_109",
2932 "EM_UNKNOWN_USER_110",
2933 "EM_UNKNOWN_USER_111",
2934 "EM_UNKNOWN_USER_112",
2935 "EM_UNKNOWN_USER_113",
2936 "EM_UNKNOWN_USER_114",
2937 "EM_UNKNOWN_USER_115",
2938 "EM_UNKNOWN_USER_116",
2939 "EM_UNKNOWN_USER_117",
2940 "EM_UNKNOWN_USER_118",
2941 "EM_UNKNOWN_USER_119",
2942 "EM_SETLANGOPTIONS",
2943 "EM_GETLANGOPTIONS",
2944 "EM_GETIMECOMPMODE",
2945 "EM_FINDTEXTW",
2946 "EM_FINDTEXTEXW",
2947 "EM_RECONVERSION",
2948 "EM_SETIMEMODEBIAS",
2949 "EM_GETIMEMODEBIAS"
2952 static const char *
2953 get_msg_name(UINT msg)
2955 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2956 return edit_messages[msg - EM_GETSEL];
2957 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2958 return richedit_messages[msg - EM_CANPASTE];
2959 return "";
2962 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2964 int x,y;
2965 BOOL isExact;
2966 ME_Cursor cursor; /* The start of the clicked text. */
2968 ENLINK info;
2969 x = (short)LOWORD(lParam);
2970 y = (short)HIWORD(lParam);
2971 ME_CharFromPos(editor, x, y, &cursor, &isExact);
2972 if (!isExact) return;
2974 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
2975 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
2976 { /* The clicked run has CFE_LINK set */
2977 info.nmhdr.hwndFrom = NULL;
2978 info.nmhdr.idFrom = 0;
2979 info.nmhdr.code = EN_LINK;
2980 info.msg = msg;
2981 info.wParam = wParam;
2982 info.lParam = lParam;
2983 cursor.nOffset = 0;
2984 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
2985 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
2986 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
2990 #define UNSUPPORTED_MSG(e) \
2991 case e: \
2992 FIXME(#e ": stub\n"); \
2993 *phresult = S_FALSE; \
2994 return 0;
2996 /* Handle messages for windowless and windoweded richedit controls.
2998 * The LRESULT that is returned is a return value for window procs,
2999 * and the phresult parameter is the COM return code needed by the
3000 * text services interface. */
3001 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3002 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3004 *phresult = S_OK;
3006 switch(msg) {
3008 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3009 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3010 UNSUPPORTED_MSG(EM_FMTLINES)
3011 UNSUPPORTED_MSG(EM_FORMATRANGE)
3012 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3013 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3014 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3015 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3016 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3017 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3018 UNSUPPORTED_MSG(EM_GETREDONAME)
3019 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3020 UNSUPPORTED_MSG(EM_GETUNDONAME)
3021 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3022 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3023 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3024 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3025 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3026 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3027 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3028 UNSUPPORTED_MSG(EM_SETMARGINS)
3029 UNSUPPORTED_MSG(EM_SETPALETTE)
3030 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3031 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3032 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3034 /* Messages specific to Richedit controls */
3036 case EM_STREAMIN:
3037 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3038 case EM_STREAMOUT:
3039 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3040 case WM_GETDLGCODE:
3042 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3043 if (lParam)
3044 editor->bDialogMode = TRUE;
3045 if (editor->styleFlags & ES_MULTILINE)
3046 code |= DLGC_WANTMESSAGE;
3047 return code;
3049 case EM_EMPTYUNDOBUFFER:
3050 ME_EmptyUndoStack(editor);
3051 return 0;
3052 case EM_GETSEL:
3054 /* Note: wParam/lParam can be NULL */
3055 UINT from, to;
3056 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3057 PUINT pto = lParam ? (PUINT)lParam : &to;
3058 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3059 if ((*pfrom|*pto) & 0xFFFF0000)
3060 return -1;
3061 return MAKELONG(*pfrom,*pto);
3063 case EM_EXGETSEL:
3065 CHARRANGE *pRange = (CHARRANGE *)lParam;
3066 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3067 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3068 return 0;
3070 case EM_SETUNDOLIMIT:
3072 if ((int)wParam < 0)
3073 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3074 else
3075 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3076 /* Setting a max stack size keeps wine from getting killed
3077 for hogging memory. Windows allocates all this memory at once, so
3078 no program would realistically set a value above our maximum. */
3079 return editor->nUndoLimit;
3081 case EM_CANUNDO:
3082 return editor->pUndoStack != NULL;
3083 case EM_CANREDO:
3084 return editor->pRedoStack != NULL;
3085 case WM_UNDO: /* FIXME: actually not the same */
3086 case EM_UNDO:
3087 return ME_Undo(editor);
3088 case EM_REDO:
3089 return ME_Redo(editor);
3090 case EM_GETOPTIONS:
3092 /* these flags are equivalent to the ES_* counterparts */
3093 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3094 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3095 DWORD settings = editor->styleFlags & mask;
3097 return settings;
3099 case EM_SETOPTIONS:
3101 /* these flags are equivalent to ES_* counterparts, except for
3102 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3103 * but is still stored in editor->styleFlags. */
3104 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3105 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3106 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3107 DWORD settings = mask & editor->styleFlags;
3108 DWORD oldSettings = settings;
3109 DWORD changedSettings;
3111 switch(wParam)
3113 case ECOOP_SET:
3114 settings = lParam;
3115 break;
3116 case ECOOP_OR:
3117 settings |= lParam;
3118 break;
3119 case ECOOP_AND:
3120 settings &= lParam;
3121 break;
3122 case ECOOP_XOR:
3123 settings ^= lParam;
3125 changedSettings = oldSettings ^ settings;
3127 if (changedSettings) {
3128 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3130 if (changedSettings & ECO_SELECTIONBAR)
3132 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3133 if (settings & ECO_SELECTIONBAR) {
3134 assert(!editor->selofs);
3135 editor->selofs = SELECTIONBAR_WIDTH;
3136 editor->rcFormat.left += editor->selofs;
3137 } else {
3138 editor->rcFormat.left -= editor->selofs;
3139 editor->selofs = 0;
3141 ME_RewrapRepaint(editor);
3144 if (changedSettings & settings & ECO_VERTICAL)
3145 FIXME("ECO_VERTICAL not implemented yet!\n");
3146 if (changedSettings & settings & ECO_AUTOHSCROLL)
3147 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3148 if (changedSettings & settings & ECO_AUTOVSCROLL)
3149 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3150 if (changedSettings & settings & ECO_NOHIDESEL)
3151 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3152 if (changedSettings & settings & ECO_WANTRETURN)
3153 FIXME("ECO_WANTRETURN not implemented yet!\n");
3154 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3155 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3158 return settings;
3160 case EM_SETSEL:
3162 ME_InvalidateSelection(editor);
3163 ME_SetSelection(editor, wParam, lParam);
3164 ME_InvalidateSelection(editor);
3165 ITextHost_TxShowCaret(editor->texthost, FALSE);
3166 ME_ShowCaret(editor);
3167 ME_SendSelChange(editor);
3168 return 0;
3170 case EM_SETSCROLLPOS:
3172 POINT *point = (POINT *)lParam;
3173 ME_ScrollAbs(editor, point->x, point->y);
3174 return 0;
3176 case EM_AUTOURLDETECT:
3178 if (wParam==1 || wParam ==0)
3180 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3181 return 0;
3183 return E_INVALIDARG;
3185 case EM_GETAUTOURLDETECT:
3187 return editor->AutoURLDetect_bEnable;
3189 case EM_EXSETSEL:
3191 int end;
3192 CHARRANGE range = *(CHARRANGE *)lParam;
3194 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3196 ME_InvalidateSelection(editor);
3197 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3198 ME_InvalidateSelection(editor);
3199 ITextHost_TxShowCaret(editor->texthost, FALSE);
3200 ME_ShowCaret(editor);
3201 ME_SendSelChange(editor);
3203 return end;
3205 case EM_SHOWSCROLLBAR:
3207 DWORD flags;
3209 switch (wParam)
3211 case SB_HORZ:
3212 flags = WS_HSCROLL;
3213 break;
3214 case SB_VERT:
3215 flags = WS_VSCROLL;
3216 break;
3217 case SB_BOTH:
3218 flags = WS_HSCROLL|WS_VSCROLL;
3219 break;
3220 default:
3221 return 0;
3224 if (lParam) {
3225 editor->styleFlags |= flags;
3226 if (flags & WS_HSCROLL)
3227 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3228 editor->nTotalWidth > editor->sizeWindow.cx);
3229 if (flags & WS_VSCROLL)
3230 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3231 editor->nTotalLength > editor->sizeWindow.cy);
3232 } else {
3233 editor->styleFlags &= ~flags;
3234 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3236 return 0;
3238 case EM_SETTEXTEX:
3240 LPWSTR wszText;
3241 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3242 size_t len = 0;
3243 int from, to;
3244 ME_Style *style;
3245 BOOL bRtf, bUnicode, bSelection;
3246 int oldModify = editor->nModifyStep;
3248 if (!pStruct) return 0;
3250 /* If we detect ascii rtf at the start of the string,
3251 * we know it isn't unicode. */
3252 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3253 !strncmp((char *)lParam, "{\\urtf", 6)));
3254 bUnicode = !bRtf && pStruct->codepage == 1200;
3256 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3257 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3258 pStruct->flags, pStruct->codepage);
3260 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3261 if (bSelection) {
3262 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3263 style = ME_GetSelectionInsertStyle(editor);
3264 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3265 } else {
3266 ME_Cursor start;
3267 ME_SetCursorToStart(editor, &start);
3268 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3269 style = editor->pBuffer->pDefaultStyle;
3272 if (bRtf) {
3273 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3274 if (bSelection) {
3275 /* FIXME: The length returned doesn't include the rtf control
3276 * characters, only the actual text. */
3277 len = lParam ? strlen((char *)lParam) : 0;
3279 } else {
3280 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3281 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3282 len = wszText ? lstrlenW(wszText) : 0;
3283 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3284 ME_EndToUnicode(bUnicode, wszText);
3287 if (bSelection) {
3288 ME_ReleaseStyle(style);
3289 ME_UpdateSelectionLinkAttribute(editor);
3290 } else {
3291 ME_Cursor cursor;
3292 len = 1;
3293 ME_SetCursorToStart(editor, &cursor);
3294 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3296 ME_CommitUndo(editor);
3297 if (!(pStruct->flags & ST_KEEPUNDO))
3299 editor->nModifyStep = oldModify;
3300 ME_EmptyUndoStack(editor);
3302 ME_UpdateRepaint(editor, FALSE);
3303 return len;
3305 case EM_SETBKGNDCOLOR:
3307 LRESULT lColor;
3308 if (editor->rgbBackColor != -1) {
3309 DeleteObject(editor->hbrBackground);
3310 lColor = editor->rgbBackColor;
3312 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3314 if (wParam)
3316 editor->rgbBackColor = -1;
3317 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3319 else
3321 editor->rgbBackColor = lParam;
3322 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3324 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3325 ITextHost_TxViewChange(editor->texthost, TRUE);
3326 return lColor;
3328 case EM_GETMODIFY:
3329 return editor->nModifyStep == 0 ? 0 : -1;
3330 case EM_SETMODIFY:
3332 if (wParam)
3333 editor->nModifyStep = 1;
3334 else
3335 editor->nModifyStep = 0;
3337 return 0;
3339 case EM_SETREADONLY:
3341 if (wParam)
3342 editor->styleFlags |= ES_READONLY;
3343 else
3344 editor->styleFlags &= ~ES_READONLY;
3345 return 0;
3347 case EM_SETEVENTMASK:
3349 DWORD nOldMask = editor->nEventMask;
3351 editor->nEventMask = lParam;
3352 return nOldMask;
3354 case EM_GETEVENTMASK:
3355 return editor->nEventMask;
3356 case EM_SETCHARFORMAT:
3358 CHARFORMAT2W buf, *p;
3359 BOOL bRepaint = TRUE;
3360 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3361 if (p == NULL) return 0;
3362 if (!wParam)
3363 ME_SetDefaultCharFormat(editor, p);
3364 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
3365 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3366 return 0;
3367 } else if (wParam == SCF_ALL) {
3368 if (editor->mode & TM_PLAINTEXT)
3369 ME_SetDefaultCharFormat(editor, p);
3370 else {
3371 ME_Cursor start;
3372 ME_SetCursorToStart(editor, &start);
3373 ME_SetCharFormat(editor, &start, NULL, p);
3374 editor->nModifyStep = 1;
3376 } else if (editor->mode & TM_PLAINTEXT) {
3377 return 0;
3378 } else {
3379 bRepaint = ME_IsSelection(editor);
3380 ME_SetSelectionCharFormat(editor, p);
3381 if (bRepaint) editor->nModifyStep = 1;
3383 ME_CommitUndo(editor);
3384 if (bRepaint)
3386 ME_WrapMarkedParagraphs(editor);
3387 ME_UpdateScrollBar(editor);
3388 ME_Repaint(editor);
3390 return 1;
3392 case EM_GETCHARFORMAT:
3394 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3395 if (dst->cbSize != sizeof(CHARFORMATA) &&
3396 dst->cbSize != sizeof(CHARFORMATW) &&
3397 dst->cbSize != sizeof(CHARFORMAT2A) &&
3398 dst->cbSize != sizeof(CHARFORMAT2W))
3399 return 0;
3400 tmp.cbSize = sizeof(tmp);
3401 if (!wParam)
3402 ME_GetDefaultCharFormat(editor, &tmp);
3403 else
3404 ME_GetSelectionCharFormat(editor, &tmp);
3405 ME_CopyToCFAny(dst, &tmp);
3406 return tmp.dwMask;
3408 case EM_SETPARAFORMAT:
3410 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3411 ME_WrapMarkedParagraphs(editor);
3412 ME_UpdateScrollBar(editor);
3413 ME_Repaint(editor);
3414 ME_CommitUndo(editor);
3415 return result;
3417 case EM_GETPARAFORMAT:
3418 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3419 return ((PARAFORMAT2 *)lParam)->dwMask;
3420 case EM_GETFIRSTVISIBLELINE:
3422 ME_DisplayItem *p = editor->pBuffer->pFirst;
3423 int y = editor->vert_si.nPos;
3424 int ypara = 0;
3425 int count = 0;
3426 int ystart, yend;
3427 while(p) {
3428 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3429 if (p->type == diTextEnd)
3430 break;
3431 if (p->type == diParagraph) {
3432 ypara = p->member.para.pt.y;
3433 continue;
3435 ystart = ypara + p->member.row.pt.y;
3436 yend = ystart + p->member.row.nHeight;
3437 if (y < yend) {
3438 break;
3440 count++;
3442 return count;
3444 case EM_HIDESELECTION:
3446 editor->bHideSelection = (wParam != 0);
3447 ME_InvalidateSelection(editor);
3448 return 0;
3450 case EM_LINESCROLL:
3452 if (!(editor->styleFlags & ES_MULTILINE))
3453 return FALSE;
3454 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3455 return TRUE;
3457 case WM_CLEAR:
3459 int from, to;
3460 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3461 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3462 ME_CommitUndo(editor);
3463 ME_UpdateRepaint(editor, TRUE);
3464 return 0;
3466 case EM_REPLACESEL:
3468 int from, to, nStartCursor;
3469 ME_Style *style;
3470 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3471 size_t len = wszText ? lstrlenW(wszText) : 0;
3472 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3474 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3475 style = ME_GetSelectionInsertStyle(editor);
3476 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3477 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3478 ME_ReleaseStyle(style);
3479 /* drop temporary style if line end */
3481 * FIXME question: does abc\n mean: put abc,
3482 * clear temp style, put \n? (would require a change)
3484 if (len>0 && wszText[len-1] == '\n')
3485 ME_ClearTempStyle(editor);
3486 ME_EndToUnicode(unicode, wszText);
3487 ME_CommitUndo(editor);
3488 ME_UpdateSelectionLinkAttribute(editor);
3489 if (!wParam)
3490 ME_EmptyUndoStack(editor);
3491 ME_UpdateRepaint(editor, FALSE);
3492 return len;
3494 case EM_SCROLLCARET:
3495 ME_EnsureVisible(editor, &editor->pCursors[0]);
3496 return 0;
3497 case WM_SETFONT:
3499 LOGFONTW lf;
3500 CHARFORMAT2W fmt;
3501 HDC hDC;
3502 BOOL bRepaint = LOWORD(lParam);
3504 if (!wParam)
3505 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3506 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3507 hDC = ITextHost_TxGetDC(editor->texthost);
3508 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3509 ITextHost_TxReleaseDC(editor->texthost, hDC);
3510 if (editor->mode & TM_RICHTEXT) {
3511 ME_Cursor start;
3512 ME_SetCursorToStart(editor, &start);
3513 ME_SetCharFormat(editor, &start, NULL, &fmt);
3515 ME_SetDefaultCharFormat(editor, &fmt);
3517 ME_CommitUndo(editor);
3518 ME_MarkAllForWrapping(editor);
3519 ME_WrapMarkedParagraphs(editor);
3520 ME_UpdateScrollBar(editor);
3521 if (bRepaint)
3522 ME_Repaint(editor);
3523 return 0;
3525 case WM_SETTEXT:
3527 ME_Cursor cursor;
3528 ME_SetCursorToStart(editor, &cursor);
3529 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3530 if (lParam)
3532 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3533 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3534 !strncmp((char *)lParam, "{\\urtf", 6))
3536 /* Undocumented: WM_SETTEXT supports RTF text */
3537 ME_StreamInRTFString(editor, 0, (char *)lParam);
3539 else
3541 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3542 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3543 if (lstrlenW(wszText) > 0)
3545 int len = -1;
3547 /* uses default style! */
3548 if (!(editor->styleFlags & ES_MULTILINE))
3550 WCHAR * p;
3552 p = wszText;
3553 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3554 len = p - wszText;
3556 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3558 ME_EndToUnicode(unicode, wszText);
3561 else
3562 TRACE("WM_SETTEXT - NULL\n");
3563 ME_SetCursorToStart(editor, &cursor);
3564 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3565 ME_SetSelection(editor, 0, 0);
3566 editor->nModifyStep = 0;
3567 ME_CommitUndo(editor);
3568 ME_EmptyUndoStack(editor);
3569 ME_UpdateRepaint(editor, FALSE);
3570 return 1;
3572 case EM_CANPASTE:
3574 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3575 if (IsClipboardFormatAvailable(nRTFFormat))
3576 return TRUE;
3577 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3578 return TRUE;
3579 return FALSE;
3581 case WM_PASTE:
3582 ME_Paste(editor);
3583 return 0;
3584 case WM_CUT:
3585 case WM_COPY:
3587 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3588 int nChars = nTo - nFrom;
3589 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3591 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3593 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3594 ME_CommitUndo(editor);
3595 ME_UpdateRepaint(editor, TRUE);
3597 return 0;
3599 case WM_GETTEXTLENGTH:
3601 GETTEXTLENGTHEX how;
3603 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3604 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3605 how.codepage = unicode ? 1200 : CP_ACP;
3606 return ME_GetTextLengthEx(editor, &how);
3608 case EM_GETTEXTLENGTHEX:
3609 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3610 case WM_GETTEXT:
3612 GETTEXTEX ex;
3613 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3614 ex.flags = GT_USECRLF;
3615 ex.codepage = unicode ? 1200 : CP_ACP;
3616 ex.lpDefaultChar = NULL;
3617 ex.lpUsedDefChar = NULL;
3618 return ME_GetTextEx(editor, &ex, lParam);
3620 case EM_GETTEXTEX:
3621 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3622 case EM_GETSELTEXT:
3624 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3625 ME_Cursor *from = &editor->pCursors[nStartCur];
3626 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3627 nTo - nFrom, unicode);
3629 case EM_GETSCROLLPOS:
3631 POINT *point = (POINT *)lParam;
3632 point->x = editor->horz_si.nPos;
3633 point->y = editor->vert_si.nPos;
3634 /* 16-bit scaled value is returned as stored in scrollinfo */
3635 if (editor->horz_si.nMax > 0xffff)
3636 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3637 if (editor->vert_si.nMax > 0xffff)
3638 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3639 return 1;
3641 case EM_GETTEXTRANGE:
3643 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3644 ME_Cursor start;
3645 int nStart = rng->chrg.cpMin;
3646 int nEnd = rng->chrg.cpMax;
3647 int textlength = ME_GetTextLength(editor);
3649 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3650 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3651 if (nStart < 0) return 0;
3652 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3653 nEnd = textlength;
3654 if (nStart >= nEnd) return 0;
3656 ME_CursorFromCharOfs(editor, nStart, &start);
3657 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3659 case EM_GETLINE:
3661 ME_DisplayItem *run;
3662 const unsigned int nMaxChars = *(WORD *) lParam;
3663 unsigned int nCharsLeft = nMaxChars;
3664 char *dest = (char *) lParam;
3665 BOOL wroteNull = FALSE;
3667 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3668 unicode ? "Unicode" : "Ansi");
3670 run = ME_FindRowWithNumber(editor, wParam);
3671 if (run == NULL)
3672 return 0;
3674 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3675 && run->type == diRun)
3677 unsigned int nCopy;
3678 ME_String *strText;
3680 strText = run->member.run.strText;
3681 nCopy = min(nCharsLeft, strText->nLen);
3683 if (unicode)
3684 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3685 else
3686 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3687 nCharsLeft, NULL, NULL);
3688 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3689 nCharsLeft -= nCopy;
3692 /* append line termination, space allowing */
3693 if (nCharsLeft > 0)
3695 if (unicode)
3696 *((WCHAR *)dest) = '\0';
3697 else
3698 *dest = '\0';
3699 nCharsLeft--;
3700 wroteNull = TRUE;
3703 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3704 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3706 case EM_GETLINECOUNT:
3708 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3709 int nRows = 0;
3711 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3713 while (item != editor->pBuffer->pLast)
3715 assert(item->type == diParagraph);
3716 prev_para = ME_FindItemBack(item, diRun);
3717 if (prev_para) {
3718 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3720 nRows += item->member.para.nRows;
3721 item = item->member.para.next_para;
3723 last_para = ME_FindItemBack(item, diRun);
3724 assert(last_para);
3725 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3726 if (editor->bEmulateVersion10 && prev_para &&
3727 last_para->member.run.nCharOfs == 0 &&
3728 prev_para->member.run.strText->nLen == 1 &&
3729 prev_para->member.run.strText->szData[0] == '\r')
3731 /* In 1.0 emulation, the last solitary \r at the very end of the text
3732 (if one exists) is NOT a line break.
3733 FIXME: this is an ugly hack. This should have a more regular model. */
3734 nRows--;
3737 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3738 return max(1, nRows);
3740 case EM_LINEFROMCHAR:
3742 if (wParam == -1)
3743 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3744 else
3745 return ME_RowNumberFromCharOfs(editor, wParam);
3747 case EM_EXLINEFROMCHAR:
3749 if (lParam == -1)
3750 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3751 else
3752 return ME_RowNumberFromCharOfs(editor, lParam);
3754 case EM_LINEINDEX:
3756 ME_DisplayItem *item, *para;
3757 int nCharOfs;
3759 if (wParam == -1)
3760 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3761 else
3762 item = ME_FindRowWithNumber(editor, wParam);
3763 if (!item)
3764 return -1;
3765 para = ME_GetParagraph(item);
3766 item = ME_FindItemFwd(item, diRun);
3767 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3768 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3769 return nCharOfs;
3771 case EM_LINELENGTH:
3773 ME_DisplayItem *item, *item_end;
3774 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3775 ME_DisplayItem *para, *run;
3777 if (wParam > ME_GetTextLength(editor))
3778 return 0;
3779 if (wParam == -1)
3781 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3782 return 0;
3784 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3785 item = ME_RowStart(run);
3786 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3787 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3788 if (item_end->type == diStartRow) {
3789 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3790 } else {
3791 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3792 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3793 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3795 nChars = nNextLineOfs - nThisLineOfs;
3796 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3797 return nChars;
3799 case EM_EXLIMITTEXT:
3801 if ((int)lParam < 0)
3802 return 0;
3803 if (lParam == 0)
3804 editor->nTextLimit = 65536;
3805 else
3806 editor->nTextLimit = (int) lParam;
3807 return 0;
3809 case EM_LIMITTEXT:
3811 if (wParam == 0)
3812 editor->nTextLimit = 65536;
3813 else
3814 editor->nTextLimit = (int) wParam;
3815 return 0;
3817 case EM_GETLIMITTEXT:
3819 return editor->nTextLimit;
3821 case EM_FINDTEXT:
3823 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3824 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3825 WCHAR *tmp;
3826 LRESULT r;
3828 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3829 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3830 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3831 FREE_OBJ( tmp );
3832 return r;
3834 case EM_FINDTEXTEX:
3836 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3837 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3838 WCHAR *tmp;
3839 LRESULT r;
3841 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3842 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3843 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3844 FREE_OBJ( tmp );
3845 return r;
3847 case EM_FINDTEXTW:
3849 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3850 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3852 case EM_FINDTEXTEXW:
3854 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3855 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3857 case EM_GETZOOM:
3858 if (!wParam || !lParam)
3859 return FALSE;
3860 *(int *)wParam = editor->nZoomNumerator;
3861 *(int *)lParam = editor->nZoomDenominator;
3862 return TRUE;
3863 case EM_SETZOOM:
3864 return ME_SetZoom(editor, wParam, lParam);
3865 case EM_CHARFROMPOS:
3867 ME_Cursor cursor;
3868 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3869 &cursor, NULL))
3870 return ME_GetCursorOfs(&cursor);
3871 else
3872 return -1;
3874 case EM_POSFROMCHAR:
3876 ME_DisplayItem *pPara, *pRun;
3877 int nCharOfs, nOffset, nLength;
3878 POINTL pt = {0,0};
3880 nCharOfs = wParam;
3881 /* detect which API version we're dealing with */
3882 if (wParam >= 0x40000)
3883 nCharOfs = lParam;
3884 nLength = ME_GetTextLength(editor);
3885 nCharOfs = min(nCharOfs, nLength);
3886 nCharOfs = max(nCharOfs, 0);
3888 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3889 assert(pRun->type == diRun);
3890 pt.y = pRun->member.run.pt.y;
3891 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3892 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3893 pt.x += editor->rcFormat.left;
3895 pt.x -= editor->horz_si.nPos;
3896 pt.y -= editor->vert_si.nPos;
3898 if (wParam >= 0x40000) {
3899 *(POINTL *)wParam = pt;
3901 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3903 case WM_CREATE:
3905 INT max;
3907 ME_SetDefaultFormatRect(editor);
3909 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3910 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3911 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3913 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3914 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3916 if (editor->styleFlags & ES_DISABLENOSCROLL)
3918 if (editor->styleFlags & WS_VSCROLL)
3920 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3921 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3923 if (editor->styleFlags & WS_HSCROLL)
3925 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3926 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3930 ME_CommitUndo(editor);
3931 ME_WrapMarkedParagraphs(editor);
3932 ME_MoveCaret(editor);
3933 return 0;
3935 case WM_DESTROY:
3936 ME_DestroyEditor(editor);
3937 return 0;
3938 case WM_SETCURSOR:
3940 return ME_SetCursor(editor);
3942 case WM_LBUTTONDBLCLK:
3943 case WM_LBUTTONDOWN:
3945 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3946 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3947 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3948 return 0;
3949 ITextHost_TxSetFocus(editor->texthost);
3950 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3951 ME_CalculateClickCount(editor, msg, wParam, lParam));
3952 ITextHost_TxSetCapture(editor->texthost, TRUE);
3953 editor->bMouseCaptured = TRUE;
3954 ME_LinkNotify(editor,msg,wParam,lParam);
3955 if (!ME_SetCursor(editor)) goto do_default;
3956 break;
3958 case WM_MOUSEMOVE:
3959 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3960 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3961 return 0;
3962 if (editor->bMouseCaptured)
3963 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3964 ME_LinkNotify(editor,msg,wParam,lParam);
3965 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3966 if (editor->bMouseCaptured)
3967 ME_SetCursor(editor);
3968 break;
3969 case WM_LBUTTONUP:
3970 if (editor->bMouseCaptured) {
3971 ITextHost_TxSetCapture(editor->texthost, FALSE);
3972 editor->bMouseCaptured = FALSE;
3974 if (editor->nSelectionType == stDocument)
3975 editor->nSelectionType = stPosition;
3976 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3977 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3978 return 0;
3979 else
3981 ME_SetCursor(editor);
3982 ME_LinkNotify(editor,msg,wParam,lParam);
3984 break;
3985 case WM_RBUTTONUP:
3986 case WM_RBUTTONDOWN:
3987 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3988 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3989 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3990 return 0;
3991 goto do_default;
3992 case WM_CONTEXTMENU:
3993 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3994 goto do_default;
3995 break;
3996 case WM_SETFOCUS:
3997 editor->bHaveFocus = TRUE;
3998 ME_ShowCaret(editor);
3999 ME_SendOldNotify(editor, EN_SETFOCUS);
4000 return 0;
4001 case WM_KILLFOCUS:
4002 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4003 editor->bHaveFocus = FALSE;
4004 ME_HideCaret(editor);
4005 ME_SendOldNotify(editor, EN_KILLFOCUS);
4006 return 0;
4007 case WM_COMMAND:
4008 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4009 return 0;
4010 case WM_KEYUP:
4011 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4012 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4013 return 0;
4014 goto do_default;
4015 case WM_KEYDOWN:
4016 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4017 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4018 return 0;
4019 if (ME_KeyDown(editor, LOWORD(wParam)))
4020 return 0;
4021 goto do_default;
4022 case WM_CHAR:
4023 return ME_Char(editor, wParam, lParam, unicode);
4024 case WM_UNICHAR:
4025 if (unicode)
4027 if(wParam == UNICODE_NOCHAR) return TRUE;
4028 if(wParam <= 0x000fffff)
4030 if(wParam > 0xffff) /* convert to surrogates */
4032 wParam -= 0x10000;
4033 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4034 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4035 } else {
4036 ME_Char(editor, wParam, 0, TRUE);
4039 return 0;
4041 break;
4042 case EM_STOPGROUPTYPING:
4043 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4044 return 0;
4045 case WM_HSCROLL:
4047 const int scrollUnit = 7;
4049 switch(LOWORD(wParam))
4051 case SB_LEFT:
4052 ME_ScrollAbs(editor, 0, 0);
4053 break;
4054 case SB_RIGHT:
4055 ME_ScrollAbs(editor,
4056 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4057 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4058 break;
4059 case SB_LINELEFT:
4060 ME_ScrollLeft(editor, scrollUnit);
4061 break;
4062 case SB_LINERIGHT:
4063 ME_ScrollRight(editor, scrollUnit);
4064 break;
4065 case SB_PAGELEFT:
4066 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4067 break;
4068 case SB_PAGERIGHT:
4069 ME_ScrollRight(editor, editor->sizeWindow.cx);
4070 break;
4071 case SB_THUMBTRACK:
4072 case SB_THUMBPOSITION:
4074 int pos = HIWORD(wParam);
4075 if (editor->horz_si.nMax > 0xffff)
4076 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4077 ME_HScrollAbs(editor, pos);
4078 break;
4081 break;
4083 case EM_SCROLL: /* fall through */
4084 case WM_VSCROLL:
4086 int origNPos;
4087 int lineHeight;
4089 origNPos = editor->vert_si.nPos;
4090 lineHeight = 24;
4092 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4093 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4094 if (lineHeight <= 0) lineHeight = 24;
4096 switch(LOWORD(wParam))
4098 case SB_TOP:
4099 ME_ScrollAbs(editor, 0, 0);
4100 break;
4101 case SB_BOTTOM:
4102 ME_ScrollAbs(editor,
4103 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4104 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4105 break;
4106 case SB_LINEUP:
4107 ME_ScrollUp(editor,lineHeight);
4108 break;
4109 case SB_LINEDOWN:
4110 ME_ScrollDown(editor,lineHeight);
4111 break;
4112 case SB_PAGEUP:
4113 ME_ScrollUp(editor,editor->sizeWindow.cy);
4114 break;
4115 case SB_PAGEDOWN:
4116 ME_ScrollDown(editor,editor->sizeWindow.cy);
4117 break;
4118 case SB_THUMBTRACK:
4119 case SB_THUMBPOSITION:
4121 int pos = HIWORD(wParam);
4122 if (editor->vert_si.nMax > 0xffff)
4123 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4124 ME_VScrollAbs(editor, pos);
4125 break;
4128 if (msg == EM_SCROLL)
4129 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4130 break;
4132 case WM_MOUSEWHEEL:
4134 int gcWheelDelta;
4135 UINT pulScrollLines;
4136 BOOL ctrl_is_down;
4138 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4139 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4140 return 0;
4142 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4144 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4146 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4148 if (ctrl_is_down) {
4149 int numerator;
4150 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4152 numerator = 100;
4153 } else {
4154 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4156 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4157 if (numerator >= 10 && numerator <= 500)
4158 ME_SetZoom(editor, numerator, 100);
4159 } else {
4160 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4161 /* FIXME follow the original */
4162 if (pulScrollLines)
4163 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4166 break;
4168 case EM_GETRECT:
4170 *((RECT *)lParam) = editor->rcFormat;
4171 if (editor->bDefaultFormatRect)
4172 ((RECT *)lParam)->left -= editor->selofs;
4173 return 0;
4175 case EM_SETRECT:
4176 case EM_SETRECTNP:
4178 if (lParam)
4180 int border = 0;
4181 RECT clientRect;
4182 RECT *rc = (RECT *)lParam;
4184 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4185 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4186 if (wParam == 0)
4188 editor->rcFormat.top = max(0, rc->top - border);
4189 editor->rcFormat.left = max(0, rc->left - border);
4190 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4191 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4192 } else if (wParam == 1) {
4193 /* MSDN incorrectly says a wParam value of 1 causes the
4194 * lParam rect to be used as a relative offset,
4195 * however, the tests show it just prevents min/max bound
4196 * checking. */
4197 editor->rcFormat.top = rc->top - border;
4198 editor->rcFormat.left = rc->left - border;
4199 editor->rcFormat.bottom = rc->bottom;
4200 editor->rcFormat.right = rc->right + border;
4201 } else {
4202 return 0;
4204 editor->bDefaultFormatRect = FALSE;
4206 else
4208 ME_SetDefaultFormatRect(editor);
4209 editor->bDefaultFormatRect = TRUE;
4211 ME_MarkAllForWrapping(editor);
4212 ME_WrapMarkedParagraphs(editor);
4213 ME_UpdateScrollBar(editor);
4214 if (msg != EM_SETRECTNP)
4215 ME_Repaint(editor);
4216 return 0;
4218 case EM_REQUESTRESIZE:
4219 ME_SendRequestResize(editor, TRUE);
4220 return 0;
4221 case WM_SETREDRAW:
4222 goto do_default;
4223 case WM_SIZE:
4225 RECT clientRect;
4227 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4228 if (editor->bDefaultFormatRect) {
4229 ME_SetDefaultFormatRect(editor);
4230 } else {
4231 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4232 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4234 editor->prevClientRect = clientRect;
4235 ME_RewrapRepaint(editor);
4236 goto do_default;
4238 /* IME messages to make richedit controls IME aware */
4239 case WM_IME_SETCONTEXT:
4240 case WM_IME_CONTROL:
4241 case WM_IME_SELECT:
4242 case WM_IME_COMPOSITIONFULL:
4243 return 0;
4244 case WM_IME_STARTCOMPOSITION:
4246 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4247 ME_DeleteSelection(editor);
4248 ME_CommitUndo(editor);
4249 ME_UpdateRepaint(editor, FALSE);
4250 return 0;
4252 case WM_IME_COMPOSITION:
4254 HIMC hIMC;
4256 ME_Style *style = ME_GetInsertStyle(editor, 0);
4257 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4258 ME_DeleteSelection(editor);
4259 ME_SaveTempStyle(editor);
4260 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4262 LPWSTR lpCompStr = NULL;
4263 DWORD dwBufLen;
4264 DWORD dwIndex = lParam & GCS_RESULTSTR;
4265 if (!dwIndex)
4266 dwIndex = GCS_COMPSTR;
4268 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4269 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4270 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4271 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4272 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4273 HeapFree(GetProcessHeap(), 0, lpCompStr);
4275 if (dwIndex == GCS_COMPSTR)
4276 ME_SetSelection(editor,editor->imeStartIndex,
4277 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4279 ME_ReleaseStyle(style);
4280 ME_CommitUndo(editor);
4281 ME_UpdateRepaint(editor, FALSE);
4282 return 0;
4284 case WM_IME_ENDCOMPOSITION:
4286 ME_DeleteSelection(editor);
4287 editor->imeStartIndex=-1;
4288 return 0;
4290 case EM_GETOLEINTERFACE:
4292 LPVOID *ppvObj = (LPVOID*) lParam;
4293 return CreateIRichEditOle(editor, ppvObj);
4295 case EM_GETPASSWORDCHAR:
4297 return editor->cPasswordMask;
4299 case EM_SETOLECALLBACK:
4300 if(editor->lpOleCallback)
4301 IUnknown_Release(editor->lpOleCallback);
4302 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4303 if(editor->lpOleCallback)
4304 IUnknown_AddRef(editor->lpOleCallback);
4305 return TRUE;
4306 case EM_GETWORDBREAKPROC:
4307 return (LRESULT)editor->pfnWordBreak;
4308 case EM_SETWORDBREAKPROC:
4310 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4312 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4313 return (LRESULT)pfnOld;
4315 case EM_GETTEXTMODE:
4316 return editor->mode;
4317 case EM_SETTEXTMODE:
4319 int mask = 0;
4320 int changes = 0;
4322 if (ME_GetTextLength(editor) || editor->pUndoStack || editor->pRedoStack)
4323 return E_UNEXPECTED;
4325 /* Check for mutually exclusive flags in adjacent bits of wParam */
4326 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4327 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4328 return E_INVALIDARG;
4330 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4332 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4333 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4335 /* FIXME: Currently no support for undo level and code page options */
4336 editor->mode = (editor->mode & ~mask) | changes;
4337 return 0;
4339 case EM_SETPASSWORDCHAR:
4341 editor->cPasswordMask = wParam;
4342 ME_RewrapRepaint(editor);
4343 return 0;
4345 case EM_SETTARGETDEVICE:
4346 if (wParam == 0)
4348 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4349 if (editor->nAvailWidth || editor->bWordWrap != new)
4351 editor->bWordWrap = new;
4352 editor->nAvailWidth = 0; /* wrap to client area */
4353 ME_RewrapRepaint(editor);
4355 } else {
4356 int width = max(0, lParam);
4357 if ((editor->styleFlags & ES_MULTILINE) &&
4358 (!editor->bWordWrap || editor->nAvailWidth != width))
4360 editor->nAvailWidth = width;
4361 editor->bWordWrap = TRUE;
4362 ME_RewrapRepaint(editor);
4364 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4366 return TRUE;
4367 default:
4368 do_default:
4369 *phresult = S_FALSE;
4370 break;
4372 return 0L;
4375 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4376 LPARAM lParam, BOOL unicode)
4378 ME_TextEditor *editor;
4379 HRESULT hresult;
4380 LRESULT lresult = 0;
4382 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4383 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4385 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4386 if (!editor)
4388 if (msg == WM_NCCREATE)
4390 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4391 ITextHost *texthost;
4393 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4394 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4395 return texthost != NULL;
4397 else
4399 return DefWindowProcW(hWnd, msg, wParam, lParam);
4403 switch (msg)
4405 case WM_PAINT:
4407 HDC hDC;
4408 RECT rc;
4409 PAINTSTRUCT ps;
4411 hDC = BeginPaint(editor->hWnd, &ps);
4412 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4413 ME_SendOldNotify(editor, EN_UPDATE);
4414 /* Erase area outside of the formatting rectangle */
4415 if (ps.rcPaint.top < editor->rcFormat.top)
4417 rc = ps.rcPaint;
4418 rc.bottom = editor->rcFormat.top;
4419 FillRect(hDC, &rc, editor->hbrBackground);
4420 ps.rcPaint.top = editor->rcFormat.top;
4422 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4423 rc = ps.rcPaint;
4424 rc.top = editor->rcFormat.bottom;
4425 FillRect(hDC, &rc, editor->hbrBackground);
4426 ps.rcPaint.bottom = editor->rcFormat.bottom;
4428 if (ps.rcPaint.left < editor->rcFormat.left) {
4429 rc = ps.rcPaint;
4430 rc.right = editor->rcFormat.left;
4431 FillRect(hDC, &rc, editor->hbrBackground);
4432 ps.rcPaint.left = editor->rcFormat.left;
4434 if (ps.rcPaint.right > editor->rcFormat.right) {
4435 rc = ps.rcPaint;
4436 rc.left = editor->rcFormat.right;
4437 FillRect(hDC, &rc, editor->hbrBackground);
4438 ps.rcPaint.right = editor->rcFormat.right;
4441 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4442 EndPaint(editor->hWnd, &ps);
4443 return 0;
4445 case WM_ERASEBKGND:
4447 HDC hDC = (HDC)wParam;
4448 RECT rc;
4450 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4451 FillRect(hDC, &rc, editor->hbrBackground);
4452 return 1;
4454 case EM_SETOPTIONS:
4456 DWORD dwStyle;
4457 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4458 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4459 ECO_SELECTIONBAR;
4460 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4461 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4462 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4463 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4464 return lresult;
4466 case EM_SETREADONLY:
4468 DWORD dwStyle;
4469 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4470 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4471 dwStyle &= ~ES_READONLY;
4472 if (wParam)
4473 dwStyle |= ES_READONLY;
4474 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4475 return lresult;
4477 default:
4478 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4481 if (hresult == S_FALSE)
4482 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4484 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4485 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4487 return lresult;
4490 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4492 BOOL unicode = TRUE;
4494 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4495 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4496 unicode = FALSE;
4498 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4501 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4503 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4506 /******************************************************************
4507 * RichEditANSIWndProc (RICHED20.10)
4509 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4511 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4514 /******************************************************************
4515 * RichEdit10ANSIWndProc (RICHED20.9)
4517 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4519 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4521 ITextHost *texthost;
4522 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4524 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4525 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4526 return texthost != NULL;
4528 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4531 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4533 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4536 /* Fill buffer with srcChars unicode characters from the start cursor.
4538 * buffer: destination buffer
4539 * buflen: length of buffer in characters excluding the NULL terminator.
4540 * start: start of editor text to copy into buffer.
4541 * srcChars: Number of characters to use from the editor text.
4542 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4544 * returns the number of characters written excluding the NULL terminator.
4546 * The written text is always NULL terminated.
4548 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4549 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4551 ME_DisplayItem *pRun, *pNextRun;
4552 const WCHAR *pStart = buffer;
4553 const WCHAR cr_lf[] = {'\r', '\n', 0};
4554 const WCHAR *str;
4555 int nLen;
4557 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4558 if (editor->bEmulateVersion10) bCRLF = 0;
4560 pRun = start->pRun;
4561 assert(pRun);
4562 pNextRun = ME_FindItemFwd(pRun, diRun);
4564 nLen = pRun->member.run.strText->nLen - start->nOffset;
4565 str = pRun->member.run.strText->szData + start->nOffset;
4567 /* No '\r' is appended to the last paragraph. */
4568 while (srcChars && buflen && pNextRun)
4570 int nFlags = pRun->member.run.nFlags;
4572 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4574 if (buflen == 1) break;
4575 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4576 * EM_GETTEXTEX, however, this is done for copying text which
4577 * also uses this function. */
4578 srcChars -= min(nLen, srcChars);
4579 nLen = 2;
4580 str = cr_lf;
4581 } else {
4582 nLen = min(nLen, srcChars);
4583 srcChars -= nLen;
4586 nLen = min(nLen, buflen);
4587 buflen -= nLen;
4589 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4591 buffer += nLen;
4593 pRun = pNextRun;
4594 pNextRun = ME_FindItemFwd(pRun, diRun);
4596 nLen = pRun->member.run.strText->nLen;
4597 str = pRun->member.run.strText->szData;
4599 *buffer = 0;
4600 return buffer - pStart;
4603 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4605 WNDCLASSW wcW;
4606 WNDCLASSA wcA;
4608 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4609 wcW.lpfnWndProc = RichEditWndProcW;
4610 wcW.cbClsExtra = 0;
4611 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4612 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4613 wcW.hIcon = NULL;
4614 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4615 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4616 wcW.lpszMenuName = NULL;
4618 if (is_version_nt())
4620 wcW.lpszClassName = RICHEDIT_CLASS20W;
4621 if (!RegisterClassW(&wcW)) return FALSE;
4622 wcW.lpszClassName = MSFTEDIT_CLASS;
4623 if (!RegisterClassW(&wcW)) return FALSE;
4625 else
4627 /* WNDCLASSA/W have the same layout */
4628 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4629 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4630 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4631 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4634 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4635 wcA.lpfnWndProc = RichEditWndProcA;
4636 wcA.cbClsExtra = 0;
4637 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4638 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4639 wcA.hIcon = NULL;
4640 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4641 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4642 wcA.lpszMenuName = NULL;
4643 wcA.lpszClassName = RICHEDIT_CLASS20A;
4644 if (!RegisterClassA(&wcA)) return FALSE;
4645 wcA.lpszClassName = "RichEdit50A";
4646 if (!RegisterClassA(&wcA)) return FALSE;
4648 return TRUE;
4651 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4652 /* FIXME: Not implemented */
4653 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4654 hWnd, msg, get_msg_name(msg), wParam, lParam);
4655 return DefWindowProcW(hWnd, msg, wParam, lParam);
4658 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4659 /* FIXME: Not implemented */
4660 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4661 hWnd, msg, get_msg_name(msg), wParam, lParam);
4662 return DefWindowProcW(hWnd, msg, wParam, lParam);
4665 /******************************************************************
4666 * REExtendedRegisterClass (RICHED20.8)
4668 * FIXME undocumented
4669 * Need to check for errors and implement controls and callbacks
4671 LRESULT WINAPI REExtendedRegisterClass(void)
4673 WNDCLASSW wcW;
4674 UINT result;
4676 FIXME("semi stub\n");
4678 wcW.cbClsExtra = 0;
4679 wcW.cbWndExtra = 4;
4680 wcW.hInstance = NULL;
4681 wcW.hIcon = NULL;
4682 wcW.hCursor = NULL;
4683 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4684 wcW.lpszMenuName = NULL;
4686 if (!ME_ListBoxRegistered)
4688 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4689 wcW.lpfnWndProc = REListWndProc;
4690 wcW.lpszClassName = REListBox20W;
4691 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4694 if (!ME_ComboBoxRegistered)
4696 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4697 wcW.lpfnWndProc = REComboWndProc;
4698 wcW.lpszClassName = REComboBox20W;
4699 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4702 result = 0;
4703 if (ME_ListBoxRegistered)
4704 result += 1;
4705 if (ME_ComboBoxRegistered)
4706 result += 2;
4708 return result;
4711 static BOOL isurlspecial(WCHAR c)
4713 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4714 return strchrW( special_chars, c ) != NULL;
4718 * This proc takes a selection, and scans it forward in order to select the span
4719 * of a possible URL candidate. A possible URL candidate must start with isalnum
4720 * or one of the following special characters: *|/\+%#@ and must consist entirely
4721 * of the characters allowed to start the URL, plus : (colon) which may occur
4722 * at most once, and not at either end.
4724 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4725 const ME_Cursor *start,
4726 int nChars,
4727 ME_Cursor *candidate_min,
4728 ME_Cursor *candidate_max)
4730 ME_Cursor cursor = *start;
4731 BOOL foundColon = FALSE;
4732 BOOL candidateStarted = FALSE;
4733 WCHAR lastAcceptedChar = '\0';
4735 while (nChars > 0)
4737 WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4738 WCHAR *str = strStart + cursor.nOffset;
4739 int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4740 nChars -= nLen;
4742 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4744 /* Find start of candidate */
4745 if (!candidateStarted)
4747 while (nLen)
4749 nLen--;
4750 if (isalnumW(*str) || isurlspecial(*str))
4752 cursor.nOffset = str - strStart;
4753 *candidate_min = cursor;
4754 candidateStarted = TRUE;
4755 lastAcceptedChar = *str++;
4756 break;
4758 str++;
4762 /* Find end of candidate */
4763 if (candidateStarted) {
4764 while (nLen)
4766 nLen--;
4767 if (*str == ':' && !foundColon) {
4768 foundColon = TRUE;
4769 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4770 cursor.nOffset = str - strStart;
4771 if (lastAcceptedChar == ':')
4772 ME_MoveCursorChars(editor, &cursor, -1);
4773 *candidate_max = cursor;
4774 return TRUE;
4776 lastAcceptedChar = *str++;
4779 } else {
4780 /* End of paragraph: skip it if before candidate span, or terminates
4781 current active span */
4782 if (candidateStarted) {
4783 if (lastAcceptedChar == ':')
4784 ME_MoveCursorChars(editor, &cursor, -1);
4785 *candidate_max = cursor;
4786 return TRUE;
4790 /* Reaching this point means no span was found, so get next span */
4791 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4792 if (candidateStarted) {
4793 /* There are no further runs, so take end of text as end of candidate */
4794 cursor.nOffset = str - strStart;
4795 if (lastAcceptedChar == ':')
4796 ME_MoveCursorChars(editor, &cursor, -1);
4797 *candidate_max = cursor;
4798 return TRUE;
4800 *candidate_max = *candidate_min = cursor;
4801 return FALSE;
4803 cursor.nOffset = 0;
4806 if (candidateStarted) {
4807 /* There are no further runs, so take end of text as end of candidate */
4808 if (lastAcceptedChar == ':')
4809 ME_MoveCursorChars(editor, &cursor, -1);
4810 *candidate_max = cursor;
4811 return TRUE;
4813 *candidate_max = *candidate_min = cursor;
4814 return FALSE;
4818 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4820 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4822 #define MAX_PREFIX_LEN 9
4823 struct prefix_s {
4824 const WCHAR text[MAX_PREFIX_LEN];
4825 int length;
4826 }prefixes[] = {
4827 {{'p','r','o','s','p','e','r','o',':'}, 9},
4828 {{'t','e','l','n','e','t',':'}, 7},
4829 {{'g','o','p','h','e','r',':'}, 7},
4830 {{'m','a','i','l','t','o',':'}, 7},
4831 {{'h','t','t','p','s',':'}, 6},
4832 {{'f','i','l','e',':'}, 5},
4833 {{'n','e','w','s',':'}, 5},
4834 {{'w','a','i','s',':'}, 5},
4835 {{'n','n','t','p',':'}, 5},
4836 {{'h','t','t','p',':'}, 5},
4837 {{'w','w','w','.'}, 4},
4838 {{'f','t','p',':'}, 4},
4840 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4841 unsigned int i;
4843 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4844 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4846 if (nChars < prefixes[i].length) continue;
4847 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4848 return TRUE;
4850 return FALSE;
4851 #undef MAX_PREFIX_LEN
4855 * This proc walks through the indicated selection and evaluates whether each
4856 * section identified by ME_FindNextURLCandidate and in-between sections have
4857 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4858 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4860 * Since this function can cause runs to be split, do not depend on the value
4861 * of the start cursor at the end of the function.
4863 * nChars may be set to INT_MAX to update to the end of the text.
4865 * Returns TRUE if at least one section was modified.
4867 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4869 BOOL modified = FALSE;
4870 ME_Cursor startCur = *start;
4872 if (!editor->AutoURLDetect_bEnable) return FALSE;
4876 CHARFORMAT2W link;
4877 ME_Cursor candidateStart, candidateEnd;
4879 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4880 &candidateStart, &candidateEnd))
4882 /* Section before candidate is not an URL */
4883 int cMin = ME_GetCursorOfs(&candidateStart);
4884 int cMax = ME_GetCursorOfs(&candidateEnd);
4886 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4887 candidateStart = candidateEnd;
4888 nChars -= cMax - ME_GetCursorOfs(&startCur);
4890 else
4892 /* No more candidates until end of selection */
4893 nChars = 0;
4896 if (startCur.pRun != candidateStart.pRun ||
4897 startCur.nOffset != candidateStart.nOffset)
4899 /* CFE_LINK effect should be consistently unset */
4900 link.cbSize = sizeof(link);
4901 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4902 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4904 /* CFE_LINK must be unset from this range */
4905 memset(&link, 0, sizeof(CHARFORMAT2W));
4906 link.cbSize = sizeof(link);
4907 link.dwMask = CFM_LINK;
4908 link.dwEffects = 0;
4909 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4910 /* Update candidateEnd since setting character formats may split
4911 * runs, which can cause a cursor to be at an invalid offset within
4912 * a split run. */
4913 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4915 candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4916 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4918 modified = TRUE;
4921 if (candidateStart.pRun != candidateEnd.pRun ||
4922 candidateStart.nOffset != candidateEnd.nOffset)
4924 /* CFE_LINK effect should be consistently set */
4925 link.cbSize = sizeof(link);
4926 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4927 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4929 /* CFE_LINK must be set on this range */
4930 memset(&link, 0, sizeof(CHARFORMAT2W));
4931 link.cbSize = sizeof(link);
4932 link.dwMask = CFM_LINK;
4933 link.dwEffects = CFE_LINK;
4934 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4935 modified = TRUE;
4938 startCur = candidateEnd;
4939 } while (nChars > 0);
4940 return modified;