vbscript: Added IRegExp2_QueryInterface tests.
[wine/multimedia.git] / dlls / riched20 / editor.c
blob727b63219704309693c7161baedc5b7ab4c73bf5
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 *pText;
287 LRESULT total_bytes_read = 0;
288 BOOL is_read = FALSE;
289 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
291 TRACE("%08x %p\n", dwFormat, stream);
293 do {
294 LONG nWideChars = 0;
295 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
297 if (!stream->dwSize)
299 ME_StreamInFill(stream);
300 if (stream->editstream->dwError)
301 break;
302 if (!stream->dwSize)
303 break;
304 total_bytes_read += stream->dwSize;
307 if (!(dwFormat & SF_UNICODE))
309 char * buf = stream->buffer;
310 DWORD size = stream->dwSize;
311 DWORD cp = CP_ACP;
313 if (!is_read)
315 is_read = TRUE;
316 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
318 cp = CP_UTF8;
319 buf += 3;
320 size -= 3;
324 nWideChars = MultiByteToWideChar(cp, 0, buf, size, wszText, STREAMIN_BUFFER_SIZE);
325 pText = wszText;
327 else
329 nWideChars = stream->dwSize >> 1;
330 pText = (WCHAR *)stream->buffer;
333 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
334 if (stream->dwSize == 0)
335 break;
336 stream->dwSize = 0;
337 } while(1);
338 return total_bytes_read;
341 static void ME_ApplyBorderProperties(RTF_Info *info,
342 ME_BorderRect *borderRect,
343 RTFBorder *borderDef)
345 int i, colorNum;
346 ME_Border *pBorders[] = {&borderRect->top,
347 &borderRect->left,
348 &borderRect->bottom,
349 &borderRect->right};
350 for (i = 0; i < 4; i++)
352 RTFColor *colorDef = info->colorList;
353 pBorders[i]->width = borderDef[i].width;
354 colorNum = borderDef[i].color;
355 while (colorDef && colorDef->rtfCNum != colorNum)
356 colorDef = colorDef->rtfNextColor;
357 if (colorDef)
358 pBorders[i]->colorRef = RGB(
359 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
360 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
361 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
362 else
363 pBorders[i]->colorRef = RGB(0, 0, 0);
367 void ME_RTFCharAttrHook(RTF_Info *info)
369 CHARFORMAT2W fmt;
370 fmt.cbSize = sizeof(fmt);
371 fmt.dwMask = 0;
372 fmt.dwEffects = 0;
374 switch(info->rtfMinor)
376 case rtfPlain:
377 /* FIXME add more flags once they're implemented */
378 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
379 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
380 fmt.yHeight = 12*20; /* 12pt */
381 fmt.wWeight = FW_NORMAL;
382 fmt.bUnderlineType = CFU_UNDERLINENONE;
383 break;
384 case rtfBold:
385 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
386 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
387 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
388 break;
389 case rtfItalic:
390 fmt.dwMask = CFM_ITALIC;
391 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
392 break;
393 case rtfUnderline:
394 fmt.dwMask = CFM_UNDERLINETYPE;
395 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
396 break;
397 case rtfDotUnderline:
398 fmt.dwMask = CFM_UNDERLINETYPE;
399 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
400 break;
401 case rtfDbUnderline:
402 fmt.dwMask = CFM_UNDERLINETYPE;
403 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
404 break;
405 case rtfWordUnderline:
406 fmt.dwMask = CFM_UNDERLINETYPE;
407 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
408 break;
409 case rtfNoUnderline:
410 fmt.dwMask = CFM_UNDERLINETYPE;
411 fmt.bUnderlineType = CFU_UNDERLINENONE;
412 break;
413 case rtfStrikeThru:
414 fmt.dwMask = CFM_STRIKEOUT;
415 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
416 break;
417 case rtfSubScript:
418 case rtfSuperScript:
419 case rtfSubScrShrink:
420 case rtfSuperScrShrink:
421 case rtfNoSuperSub:
422 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
423 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
424 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
425 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
426 break;
427 case rtfInvisible:
428 fmt.dwMask = CFM_HIDDEN;
429 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
430 break;
431 case rtfBackColor:
432 fmt.dwMask = CFM_BACKCOLOR;
433 fmt.dwEffects = 0;
434 if (info->rtfParam == 0)
435 fmt.dwEffects = CFE_AUTOBACKCOLOR;
436 else if (info->rtfParam != rtfNoParam)
438 RTFColor *c = RTFGetColor(info, info->rtfParam);
439 if (c && c->rtfCBlue >= 0)
440 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
441 else
442 fmt.dwEffects = CFE_AUTOBACKCOLOR;
444 break;
445 case rtfForeColor:
446 fmt.dwMask = CFM_COLOR;
447 fmt.dwEffects = 0;
448 if (info->rtfParam == 0)
449 fmt.dwEffects = CFE_AUTOCOLOR;
450 else if (info->rtfParam != rtfNoParam)
452 RTFColor *c = RTFGetColor(info, info->rtfParam);
453 if (c && c->rtfCBlue >= 0)
454 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
455 else {
456 fmt.dwEffects = CFE_AUTOCOLOR;
459 break;
460 case rtfFontNum:
461 if (info->rtfParam != rtfNoParam)
463 RTFFont *f = RTFGetFont(info, info->rtfParam);
464 if (f)
466 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
467 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
468 fmt.bCharSet = f->rtfFCharSet;
469 fmt.dwMask = CFM_FACE | CFM_CHARSET;
470 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
473 break;
474 case rtfFontSize:
475 fmt.dwMask = CFM_SIZE;
476 if (info->rtfParam != rtfNoParam)
477 fmt.yHeight = info->rtfParam*10;
478 break;
480 if (fmt.dwMask) {
481 ME_Style *style2;
482 RTFFlushOutputBuffer(info);
483 /* FIXME too slow ? how come ? */
484 style2 = ME_ApplyStyle(info->style, &fmt);
485 ME_ReleaseStyle(info->style);
486 info->style = style2;
487 info->styleChanged = TRUE;
491 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
492 the same tags mean different things in different contexts */
493 void ME_RTFParAttrHook(RTF_Info *info)
495 PARAFORMAT2 fmt;
496 fmt.cbSize = sizeof(fmt);
497 fmt.dwMask = 0;
499 switch(info->rtfMinor)
501 case rtfParDef: /* restores default paragraph attributes */
502 if (!info->editor->bEmulateVersion10) /* v4.1 */
503 info->borderType = RTFBorderParaLeft;
504 else /* v1.0 - 3.0 */
505 info->borderType = RTFBorderParaTop;
506 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
507 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
508 PFM_STARTINDENT;
509 /* TODO: numbering, shading */
510 fmt.wAlignment = PFA_LEFT;
511 fmt.cTabCount = 0;
512 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
513 fmt.wBorderWidth = fmt.wBorders = 0;
514 fmt.wBorderSpace = 0;
515 fmt.bLineSpacingRule = 0;
516 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
517 fmt.dyLineSpacing = 0;
518 if (!info->editor->bEmulateVersion10) /* v4.1 */
520 if (info->tableDef && info->tableDef->tableRowStart &&
521 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
523 ME_Cursor cursor;
524 ME_DisplayItem *para;
525 /* We are just after a table row. */
526 RTFFlushOutputBuffer(info);
527 cursor = info->editor->pCursors[0];
528 para = cursor.pPara;
529 if (para == info->tableDef->tableRowStart->member.para.next_para
530 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
532 /* Since the table row end, no text has been inserted, and the \intbl
533 * control word has not be used. We can confirm that we are not in a
534 * table anymore.
536 info->tableDef->tableRowStart = NULL;
537 info->canInheritInTbl = FALSE;
540 } else { /* v1.0 - v3.0 */
541 fmt.dwMask |= PFM_TABLE;
542 fmt.wEffects &= ~PFE_TABLE;
544 break;
545 case rtfNestLevel:
546 if (!info->editor->bEmulateVersion10) /* v4.1 */
548 while (info->rtfParam > info->nestingLevel) {
549 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
550 ZeroMemory(tableDef, sizeof(RTFTable));
551 tableDef->parent = info->tableDef;
552 info->tableDef = tableDef;
554 RTFFlushOutputBuffer(info);
555 if (tableDef->tableRowStart &&
556 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
558 ME_DisplayItem *para = tableDef->tableRowStart;
559 para = para->member.para.next_para;
560 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
561 tableDef->tableRowStart = para;
562 } else {
563 ME_Cursor cursor;
564 WCHAR endl = '\r';
565 cursor = info->editor->pCursors[0];
566 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
567 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
568 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
571 info->nestingLevel++;
573 info->canInheritInTbl = FALSE;
575 break;
576 case rtfInTable:
578 if (!info->editor->bEmulateVersion10) /* v4.1 */
580 if (info->nestingLevel < 1)
582 RTFTable *tableDef;
583 if (!info->tableDef)
585 info->tableDef = ALLOC_OBJ(RTFTable);
586 ZeroMemory(info->tableDef, sizeof(RTFTable));
588 tableDef = info->tableDef;
589 RTFFlushOutputBuffer(info);
590 if (tableDef->tableRowStart &&
591 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
593 ME_DisplayItem *para = tableDef->tableRowStart;
594 para = para->member.para.next_para;
595 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
596 tableDef->tableRowStart = para;
597 } else {
598 ME_Cursor cursor;
599 WCHAR endl = '\r';
600 cursor = info->editor->pCursors[0];
601 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
602 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
603 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
605 info->nestingLevel = 1;
606 info->canInheritInTbl = TRUE;
608 return;
609 } else { /* v1.0 - v3.0 */
610 fmt.dwMask |= PFM_TABLE;
611 fmt.wEffects |= PFE_TABLE;
613 break;
615 case rtfFirstIndent:
616 ME_GetSelectionParaFormat(info->editor, &fmt);
617 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
618 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
619 fmt.dxOffset = -info->rtfParam;
620 break;
621 case rtfLeftIndent:
622 ME_GetSelectionParaFormat(info->editor, &fmt);
623 fmt.dwMask = PFM_STARTINDENT;
624 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
625 break;
626 case rtfRightIndent:
627 fmt.dwMask = PFM_RIGHTINDENT;
628 fmt.dxRightIndent = info->rtfParam;
629 break;
630 case rtfQuadLeft:
631 case rtfQuadJust:
632 fmt.dwMask = PFM_ALIGNMENT;
633 fmt.wAlignment = PFA_LEFT;
634 break;
635 case rtfQuadRight:
636 fmt.dwMask = PFM_ALIGNMENT;
637 fmt.wAlignment = PFA_RIGHT;
638 break;
639 case rtfQuadCenter:
640 fmt.dwMask = PFM_ALIGNMENT;
641 fmt.wAlignment = PFA_CENTER;
642 break;
643 case rtfTabPos:
644 ME_GetSelectionParaFormat(info->editor, &fmt);
645 if (!(fmt.dwMask & PFM_TABSTOPS))
647 fmt.cTabCount = 0;
649 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
650 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
651 fmt.dwMask = PFM_TABSTOPS;
652 break;
653 case rtfKeep:
654 fmt.dwMask = PFM_KEEP;
655 fmt.wEffects = PFE_KEEP;
656 break;
657 case rtfNoWidowControl:
658 fmt.dwMask = PFM_NOWIDOWCONTROL;
659 fmt.wEffects = PFE_NOWIDOWCONTROL;
660 break;
661 case rtfKeepNext:
662 fmt.dwMask = PFM_KEEPNEXT;
663 fmt.wEffects = PFE_KEEPNEXT;
664 break;
665 case rtfSpaceAfter:
666 fmt.dwMask = PFM_SPACEAFTER;
667 fmt.dySpaceAfter = info->rtfParam;
668 break;
669 case rtfSpaceBefore:
670 fmt.dwMask = PFM_SPACEBEFORE;
671 fmt.dySpaceBefore = info->rtfParam;
672 break;
673 case rtfSpaceBetween:
674 fmt.dwMask = PFM_LINESPACING;
675 if ((int)info->rtfParam > 0)
677 fmt.dyLineSpacing = info->rtfParam;
678 fmt.bLineSpacingRule = 3;
680 else
682 fmt.dyLineSpacing = info->rtfParam;
683 fmt.bLineSpacingRule = 4;
685 break;
686 case rtfSpaceMultiply:
687 fmt.dwMask = PFM_LINESPACING;
688 fmt.dyLineSpacing = info->rtfParam * 20;
689 fmt.bLineSpacingRule = 5;
690 break;
691 case rtfParBullet:
692 fmt.dwMask = PFM_NUMBERING;
693 fmt.wNumbering = PFN_BULLET;
694 break;
695 case rtfParSimple:
696 fmt.dwMask = PFM_NUMBERING;
697 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
698 break;
699 case rtfParNumDecimal:
700 fmt.dwMask = PFM_NUMBERING;
701 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
702 break;
703 case rtfParNumIndent:
704 fmt.dwMask = PFM_NUMBERINGTAB;
705 fmt.wNumberingTab = info->rtfParam;
706 break;
707 case rtfParNumStartAt:
708 fmt.dwMask = PFM_NUMBERINGSTART;
709 fmt.wNumberingStart = info->rtfParam;
710 break;
711 case rtfBorderLeft:
712 info->borderType = RTFBorderParaLeft;
713 ME_GetSelectionParaFormat(info->editor, &fmt);
714 if (!(fmt.dwMask & PFM_BORDER))
716 fmt.wBorderSpace = 0;
717 fmt.wBorderWidth = 1;
718 fmt.wBorders = 0;
720 fmt.wBorders |= 1;
721 fmt.dwMask = PFM_BORDER;
722 break;
723 case rtfBorderRight:
724 info->borderType = RTFBorderParaRight;
725 ME_GetSelectionParaFormat(info->editor, &fmt);
726 if (!(fmt.dwMask & PFM_BORDER))
728 fmt.wBorderSpace = 0;
729 fmt.wBorderWidth = 1;
730 fmt.wBorders = 0;
732 fmt.wBorders |= 2;
733 fmt.dwMask = PFM_BORDER;
734 break;
735 case rtfBorderTop:
736 info->borderType = RTFBorderParaTop;
737 ME_GetSelectionParaFormat(info->editor, &fmt);
738 if (!(fmt.dwMask & PFM_BORDER))
740 fmt.wBorderSpace = 0;
741 fmt.wBorderWidth = 1;
742 fmt.wBorders = 0;
744 fmt.wBorders |= 4;
745 fmt.dwMask = PFM_BORDER;
746 break;
747 case rtfBorderBottom:
748 info->borderType = RTFBorderParaBottom;
749 ME_GetSelectionParaFormat(info->editor, &fmt);
750 if (!(fmt.dwMask & PFM_BORDER))
752 fmt.wBorderSpace = 0;
753 fmt.wBorderWidth = 1;
754 fmt.wBorders = 0;
756 fmt.wBorders |= 8;
757 fmt.dwMask = PFM_BORDER;
758 break;
759 case rtfBorderSingle:
760 ME_GetSelectionParaFormat(info->editor, &fmt);
761 /* we assume that borders have been created before (RTF spec) */
762 fmt.wBorders &= ~0x700;
763 fmt.wBorders |= 1 << 8;
764 fmt.dwMask = PFM_BORDER;
765 break;
766 case rtfBorderThick:
767 ME_GetSelectionParaFormat(info->editor, &fmt);
768 /* we assume that borders have been created before (RTF spec) */
769 fmt.wBorders &= ~0x700;
770 fmt.wBorders |= 2 << 8;
771 fmt.dwMask = PFM_BORDER;
772 break;
773 case rtfBorderShadow:
774 ME_GetSelectionParaFormat(info->editor, &fmt);
775 /* we assume that borders have been created before (RTF spec) */
776 fmt.wBorders &= ~0x700;
777 fmt.wBorders |= 10 << 8;
778 fmt.dwMask = PFM_BORDER;
779 break;
780 case rtfBorderDouble:
781 ME_GetSelectionParaFormat(info->editor, &fmt);
782 /* we assume that borders have been created before (RTF spec) */
783 fmt.wBorders &= ~0x700;
784 fmt.wBorders |= 7 << 8;
785 fmt.dwMask = PFM_BORDER;
786 break;
787 case rtfBorderDot:
788 ME_GetSelectionParaFormat(info->editor, &fmt);
789 /* we assume that borders have been created before (RTF spec) */
790 fmt.wBorders &= ~0x700;
791 fmt.wBorders |= 11 << 8;
792 fmt.dwMask = PFM_BORDER;
793 break;
794 case rtfBorderWidth:
796 int borderSide = info->borderType & RTFBorderSideMask;
797 RTFTable *tableDef = info->tableDef;
798 ME_GetSelectionParaFormat(info->editor, &fmt);
799 /* we assume that borders have been created before (RTF spec) */
800 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
801 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
803 RTFBorder *border;
804 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
805 break;
806 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
807 border->width = info->rtfParam;
808 break;
810 fmt.dwMask = PFM_BORDER;
811 break;
813 case rtfBorderSpace:
814 ME_GetSelectionParaFormat(info->editor, &fmt);
815 /* we assume that borders have been created before (RTF spec) */
816 fmt.wBorderSpace = info->rtfParam;
817 fmt.dwMask = PFM_BORDER;
818 break;
819 case rtfBorderColor:
821 RTFTable *tableDef = info->tableDef;
822 int borderSide = info->borderType & RTFBorderSideMask;
823 int borderType = info->borderType & RTFBorderTypeMask;
824 switch(borderType)
826 case RTFBorderTypePara:
827 if (!info->editor->bEmulateVersion10) /* v4.1 */
828 break;
829 /* v1.0 - 3.0 treat paragraph and row borders the same. */
830 case RTFBorderTypeRow:
831 if (tableDef) {
832 tableDef->border[borderSide].color = info->rtfParam;
834 break;
835 case RTFBorderTypeCell:
836 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
837 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
839 break;
841 break;
844 if (fmt.dwMask) {
845 RTFFlushOutputBuffer(info);
846 /* FIXME too slow ? how come ?*/
847 ME_SetSelectionParaFormat(info->editor, &fmt);
851 void ME_RTFTblAttrHook(RTF_Info *info)
853 switch (info->rtfMinor)
855 case rtfRowDef:
857 if (!info->editor->bEmulateVersion10) /* v4.1 */
858 info->borderType = 0; /* Not sure */
859 else /* v1.0 - 3.0 */
860 info->borderType = RTFBorderRowTop;
861 if (!info->tableDef) {
862 info->tableDef = ME_MakeTableDef(info->editor);
863 } else {
864 ME_InitTableDef(info->editor, info->tableDef);
866 break;
868 case rtfCellPos:
870 int cellNum;
871 if (!info->tableDef)
873 info->tableDef = ME_MakeTableDef(info->editor);
875 cellNum = info->tableDef->numCellsDefined;
876 if (cellNum >= MAX_TABLE_CELLS)
877 break;
878 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
879 if (cellNum < MAX_TAB_STOPS) {
880 /* Tab stops were used to store cell positions before v4.1 but v4.1
881 * still seems to set the tabstops without using them. */
882 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
883 PARAFORMAT2 *pFmt = para->member.para.pFmt;
884 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
885 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
887 info->tableDef->numCellsDefined++;
888 break;
890 case rtfRowBordTop:
891 info->borderType = RTFBorderRowTop;
892 break;
893 case rtfRowBordLeft:
894 info->borderType = RTFBorderRowLeft;
895 break;
896 case rtfRowBordBottom:
897 info->borderType = RTFBorderRowBottom;
898 break;
899 case rtfRowBordRight:
900 info->borderType = RTFBorderRowRight;
901 break;
902 case rtfCellBordTop:
903 info->borderType = RTFBorderCellTop;
904 break;
905 case rtfCellBordLeft:
906 info->borderType = RTFBorderCellLeft;
907 break;
908 case rtfCellBordBottom:
909 info->borderType = RTFBorderCellBottom;
910 break;
911 case rtfCellBordRight:
912 info->borderType = RTFBorderCellRight;
913 break;
914 case rtfRowGapH:
915 if (info->tableDef)
916 info->tableDef->gapH = info->rtfParam;
917 break;
918 case rtfRowLeftEdge:
919 if (info->tableDef)
920 info->tableDef->leftEdge = info->rtfParam;
921 break;
925 void ME_RTFSpecialCharHook(RTF_Info *info)
927 RTFTable *tableDef = info->tableDef;
928 switch (info->rtfMinor)
930 case rtfNestCell:
931 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
932 break;
933 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
934 case rtfCell:
935 if (!tableDef)
936 break;
937 RTFFlushOutputBuffer(info);
938 if (!info->editor->bEmulateVersion10) { /* v4.1 */
939 if (tableDef->tableRowStart)
941 if (!info->nestingLevel &&
942 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
944 ME_DisplayItem *para = tableDef->tableRowStart;
945 para = para->member.para.next_para;
946 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
947 tableDef->tableRowStart = para;
948 info->nestingLevel = 1;
950 ME_InsertTableCellFromCursor(info->editor);
952 } else { /* v1.0 - v3.0 */
953 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
954 PARAFORMAT2 *pFmt = para->member.para.pFmt;
955 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
956 tableDef->numCellsInserted < tableDef->numCellsDefined)
958 WCHAR tab = '\t';
959 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
960 tableDef->numCellsInserted++;
963 break;
964 case rtfNestRow:
965 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
966 break;
967 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
968 case rtfRow:
970 ME_DisplayItem *para, *cell, *run;
971 int i;
973 if (!tableDef)
974 break;
975 RTFFlushOutputBuffer(info);
976 if (!info->editor->bEmulateVersion10) { /* v4.1 */
977 if (!tableDef->tableRowStart)
978 break;
979 if (!info->nestingLevel &&
980 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
982 para = tableDef->tableRowStart;
983 para = para->member.para.next_para;
984 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
985 tableDef->tableRowStart = para;
986 info->nestingLevel++;
988 para = tableDef->tableRowStart;
989 cell = ME_FindItemFwd(para, diCell);
990 assert(cell && !cell->member.cell.prev_cell);
991 if (tableDef->numCellsDefined < 1)
993 /* 2000 twips appears to be the cell size that native richedit uses
994 * when no cell sizes are specified. */
995 const int defaultCellSize = 2000;
996 int nRightBoundary = defaultCellSize;
997 cell->member.cell.nRightBoundary = nRightBoundary;
998 while (cell->member.cell.next_cell) {
999 cell = cell->member.cell.next_cell;
1000 nRightBoundary += defaultCellSize;
1001 cell->member.cell.nRightBoundary = nRightBoundary;
1003 para = ME_InsertTableCellFromCursor(info->editor);
1004 cell = para->member.para.pCell;
1005 cell->member.cell.nRightBoundary = nRightBoundary;
1006 } else {
1007 for (i = 0; i < tableDef->numCellsDefined; i++)
1009 RTFCell *cellDef = &tableDef->cells[i];
1010 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1011 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1012 cellDef->border);
1013 cell = cell->member.cell.next_cell;
1014 if (!cell)
1016 para = ME_InsertTableCellFromCursor(info->editor);
1017 cell = para->member.para.pCell;
1020 /* Cell for table row delimiter is empty */
1021 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1024 run = ME_FindItemFwd(cell, diRun);
1025 if (info->editor->pCursors[0].pRun != run ||
1026 info->editor->pCursors[0].nOffset)
1028 int nOfs, nChars;
1029 /* Delete inserted cells that aren't defined. */
1030 info->editor->pCursors[1].pRun = run;
1031 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1032 info->editor->pCursors[1].nOffset = 0;
1033 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1034 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1035 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1036 nChars, TRUE);
1039 para = ME_InsertTableRowEndFromCursor(info->editor);
1040 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1041 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1042 ME_ApplyBorderProperties(info, &para->member.para.border,
1043 tableDef->border);
1044 info->nestingLevel--;
1045 if (!info->nestingLevel)
1047 if (info->canInheritInTbl) {
1048 tableDef->tableRowStart = para;
1049 } else {
1050 while (info->tableDef) {
1051 tableDef = info->tableDef;
1052 info->tableDef = tableDef->parent;
1053 heap_free(tableDef);
1056 } else {
1057 info->tableDef = tableDef->parent;
1058 heap_free(tableDef);
1060 } else { /* v1.0 - v3.0 */
1061 WCHAR endl = '\r';
1062 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1063 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1064 pFmt->dxOffset = info->tableDef->gapH;
1065 pFmt->dxStartIndent = info->tableDef->leftEdge;
1067 ME_ApplyBorderProperties(info, &para->member.para.border,
1068 tableDef->border);
1069 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1071 WCHAR tab = '\t';
1072 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1073 tableDef->numCellsInserted++;
1075 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1076 if (!tableDef->numCellsDefined)
1077 pFmt->wEffects &= ~PFE_TABLE;
1078 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1079 tableDef->numCellsInserted = 0;
1081 break;
1083 case rtfTab:
1084 case rtfPar:
1085 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1086 ME_DisplayItem *para;
1087 PARAFORMAT2 *pFmt;
1088 RTFFlushOutputBuffer(info);
1089 para = info->editor->pCursors[0].pPara;
1090 pFmt = para->member.para.pFmt;
1091 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1093 /* rtfPar is treated like a space within a table. */
1094 info->rtfClass = rtfText;
1095 info->rtfMajor = ' ';
1097 else if (info->rtfMinor == rtfPar && tableDef)
1098 tableDef->numCellsInserted = 0;
1100 break;
1104 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1105 const SIZEL* sz)
1107 LPOLEOBJECT lpObject = NULL;
1108 LPSTORAGE lpStorage = NULL;
1109 LPOLECLIENTSITE lpClientSite = NULL;
1110 LPDATAOBJECT lpDataObject = NULL;
1111 LPOLECACHE lpOleCache = NULL;
1112 STGMEDIUM stgm;
1113 FORMATETC fm;
1114 CLSID clsid;
1115 BOOL ret = FALSE;
1116 DWORD conn;
1118 if (hemf)
1120 stgm.tymed = TYMED_ENHMF;
1121 stgm.u.hEnhMetaFile = hemf;
1122 fm.cfFormat = CF_ENHMETAFILE;
1124 else if (hbmp)
1126 stgm.tymed = TYMED_GDI;
1127 stgm.u.hBitmap = hbmp;
1128 fm.cfFormat = CF_BITMAP;
1130 stgm.pUnkForRelease = NULL;
1132 fm.ptd = NULL;
1133 fm.dwAspect = DVASPECT_CONTENT;
1134 fm.lindex = -1;
1135 fm.tymed = stgm.tymed;
1137 if (!info->lpRichEditOle)
1139 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1142 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1143 #if 0
1144 /* FIXME: enable it when rich-edit properly implements this method */
1145 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1146 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1147 #endif
1148 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1149 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1150 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1151 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1152 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1154 REOBJECT reobject;
1156 reobject.cbStruct = sizeof(reobject);
1157 reobject.cp = REO_CP_SELECTION;
1158 reobject.clsid = clsid;
1159 reobject.poleobj = lpObject;
1160 reobject.pstg = lpStorage;
1161 reobject.polesite = lpClientSite;
1162 /* convert from twips to .01 mm */
1163 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1164 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1165 reobject.dvaspect = DVASPECT_CONTENT;
1166 reobject.dwFlags = 0; /* FIXME */
1167 reobject.dwUser = 0;
1169 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1170 ret = TRUE;
1173 if (lpObject) IOleObject_Release(lpObject);
1174 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1175 if (lpStorage) IStorage_Release(lpStorage);
1176 if (lpDataObject) IDataObject_Release(lpDataObject);
1177 if (lpOleCache) IOleCache_Release(lpOleCache);
1179 return ret;
1182 static void ME_RTFReadPictGroup(RTF_Info *info)
1184 SIZEL sz;
1185 BYTE* buffer = NULL;
1186 unsigned bufsz, bufidx;
1187 BOOL flip;
1188 BYTE val;
1189 METAFILEPICT mfp;
1190 HENHMETAFILE hemf;
1191 HBITMAP hbmp;
1192 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1194 RTFGetToken (info);
1195 if (info->rtfClass == rtfEOF)
1196 return;
1197 mfp.mm = MM_TEXT;
1198 /* fetch picture type */
1199 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1201 mfp.mm = info->rtfParam;
1202 gfx = gfx_metafile;
1204 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1206 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1207 gfx = gfx_dib;
1209 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1211 gfx = gfx_enhmetafile;
1213 else
1215 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1216 goto skip_group;
1218 sz.cx = sz.cy = 0;
1219 /* fetch picture attributes */
1220 for (;;)
1222 RTFGetToken (info);
1223 if (info->rtfClass == rtfEOF)
1224 return;
1225 if (info->rtfClass == rtfText)
1226 break;
1227 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1229 ERR("Expected picture attribute (%d %d)\n",
1230 info->rtfClass, info->rtfMajor);
1231 goto skip_group;
1233 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1235 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1237 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1239 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1241 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1242 sz.cx = info->rtfParam;
1243 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1244 sz.cy = info->rtfParam;
1245 else
1246 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1248 /* fetch picture data */
1249 bufsz = 1024;
1250 bufidx = 0;
1251 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1252 val = info->rtfMajor;
1253 for (flip = TRUE;; flip = !flip)
1255 RTFGetToken (info);
1256 if (info->rtfClass == rtfEOF)
1258 HeapFree(GetProcessHeap(), 0, buffer);
1259 return; /* Warn ?? */
1261 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1262 break;
1263 if (info->rtfClass != rtfText) goto skip_group;
1264 if (flip)
1266 if (bufidx >= bufsz &&
1267 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1268 goto skip_group;
1269 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1271 else
1272 val = info->rtfMajor;
1274 if (flip) FIXME("wrong hex string\n");
1276 switch (gfx)
1278 case gfx_enhmetafile:
1279 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1280 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1281 break;
1282 case gfx_metafile:
1283 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1284 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1285 break;
1286 case gfx_dib:
1288 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1289 HDC hdc = GetDC(0);
1290 unsigned nc = bi->bmiHeader.biClrUsed;
1292 /* not quite right, especially for bitfields type of compression */
1293 if (!nc && bi->bmiHeader.biBitCount <= 8)
1294 nc = 1 << bi->bmiHeader.biBitCount;
1295 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1296 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1297 bi, DIB_RGB_COLORS)))
1298 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1299 ReleaseDC(0, hdc);
1301 break;
1302 default:
1303 break;
1305 HeapFree(GetProcessHeap(), 0, buffer);
1306 RTFRouteToken (info); /* feed "}" back to router */
1307 return;
1308 skip_group:
1309 HeapFree(GetProcessHeap(), 0, buffer);
1310 RTFSkipGroup(info);
1311 RTFRouteToken(info); /* feed "}" back to router */
1314 /* for now, lookup the \result part and use it, whatever the object */
1315 static void ME_RTFReadObjectGroup(RTF_Info *info)
1317 for (;;)
1319 RTFGetToken (info);
1320 if (info->rtfClass == rtfEOF)
1321 return;
1322 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1323 break;
1324 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1326 RTFGetToken (info);
1327 if (info->rtfClass == rtfEOF)
1328 return;
1329 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1331 int level = 1;
1333 while (RTFGetToken (info) != rtfEOF)
1335 if (info->rtfClass == rtfGroup)
1337 if (info->rtfMajor == rtfBeginGroup) level++;
1338 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1340 RTFRouteToken(info);
1343 else RTFSkipGroup(info);
1344 continue;
1346 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1348 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1349 return;
1352 RTFRouteToken(info); /* feed "}" back to router */
1355 static void ME_RTFReadHook(RTF_Info *info)
1357 switch(info->rtfClass)
1359 case rtfGroup:
1360 switch(info->rtfMajor)
1362 case rtfBeginGroup:
1363 if (info->stackTop < maxStack) {
1364 info->stack[info->stackTop].style = info->style;
1365 ME_AddRefStyle(info->style);
1366 info->stack[info->stackTop].codePage = info->codePage;
1367 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1369 info->stackTop++;
1370 info->styleChanged = FALSE;
1371 break;
1372 case rtfEndGroup:
1374 RTFFlushOutputBuffer(info);
1375 info->stackTop--;
1376 if (info->stackTop <= 0)
1377 info->rtfClass = rtfEOF;
1378 if (info->stackTop < 0)
1379 return;
1381 ME_ReleaseStyle(info->style);
1382 info->style = info->stack[info->stackTop].style;
1383 info->codePage = info->stack[info->stackTop].codePage;
1384 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1385 break;
1388 break;
1392 void
1393 ME_StreamInFill(ME_InStream *stream)
1395 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1396 (BYTE *)stream->buffer,
1397 sizeof(stream->buffer),
1398 (LONG *)&stream->dwSize);
1399 stream->dwUsed = 0;
1402 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1404 RTF_Info parser;
1405 ME_Style *style;
1406 int from, to, nUndoMode;
1407 int nEventMask = editor->nEventMask;
1408 ME_InStream inStream;
1409 BOOL invalidRTF = FALSE;
1410 ME_Cursor *selStart, *selEnd;
1411 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1413 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1414 editor->nEventMask = 0;
1416 ME_GetSelectionOfs(editor, &from, &to);
1417 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1419 ME_GetSelection(editor, &selStart, &selEnd);
1420 style = ME_GetSelectionInsertStyle(editor);
1422 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1424 /* Don't insert text at the end of the table row */
1425 if (!editor->bEmulateVersion10) { /* v4.1 */
1426 ME_DisplayItem *para = editor->pCursors->pPara;
1427 if (para->member.para.nFlags & MEPF_ROWEND)
1429 para = para->member.para.next_para;
1430 editor->pCursors[0].pPara = para;
1431 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1432 editor->pCursors[0].nOffset = 0;
1434 if (para->member.para.nFlags & MEPF_ROWSTART)
1436 para = para->member.para.next_para;
1437 editor->pCursors[0].pPara = para;
1438 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1439 editor->pCursors[0].nOffset = 0;
1441 editor->pCursors[1] = editor->pCursors[0];
1442 } else { /* v1.0 - 3.0 */
1443 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1444 ME_IsInTable(editor->pCursors[0].pRun))
1445 return 0;
1447 } else {
1448 style = editor->pBuffer->pDefaultStyle;
1449 ME_AddRefStyle(style);
1450 ME_SetSelection(editor, 0, 0);
1451 ME_InternalDeleteText(editor, &editor->pCursors[1],
1452 ME_GetTextLength(editor), FALSE);
1453 from = to = 0;
1454 ME_ClearTempStyle(editor);
1455 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1459 /* Back up undo mode to a local variable */
1460 nUndoMode = editor->nUndoMode;
1462 /* Only create an undo if SFF_SELECTION is set */
1463 if (!(format & SFF_SELECTION))
1464 editor->nUndoMode = umIgnore;
1466 inStream.editstream = stream;
1467 inStream.editstream->dwError = 0;
1468 inStream.dwSize = 0;
1469 inStream.dwUsed = 0;
1471 if (format & SF_RTF)
1473 /* Check if it's really RTF, and if it is not, use plain text */
1474 ME_StreamInFill(&inStream);
1475 if (!inStream.editstream->dwError)
1477 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1478 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1480 invalidRTF = TRUE;
1481 inStream.editstream->dwError = -16;
1486 if (!invalidRTF && !inStream.editstream->dwError)
1488 if (format & SF_RTF) {
1489 from = ME_GetCursorOfs(&editor->pCursors[0]);
1491 /* setup the RTF parser */
1492 memset(&parser, 0, sizeof parser);
1493 RTFSetEditStream(&parser, &inStream);
1494 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1495 parser.editor = editor;
1496 parser.style = style;
1497 WriterInit(&parser);
1498 RTFInit(&parser);
1499 RTFSetReadHook(&parser, ME_RTFReadHook);
1500 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1501 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1502 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1504 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1505 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1507 BeginFile(&parser);
1509 /* do the parsing */
1510 RTFRead(&parser);
1511 RTFFlushOutputBuffer(&parser);
1512 if (!editor->bEmulateVersion10) { /* v4.1 */
1513 if (parser.tableDef && parser.tableDef->tableRowStart &&
1514 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1516 /* Delete any incomplete table row at the end of the rich text. */
1517 int nOfs, nChars;
1518 ME_DisplayItem *para;
1520 parser.rtfMinor = rtfRow;
1521 /* Complete the table row before deleting it.
1522 * By doing it this way we will have the current paragraph format set
1523 * properly to reflect that is not in the complete table, and undo items
1524 * will be added for this change to the current paragraph format. */
1525 if (parser.nestingLevel > 0)
1527 while (parser.nestingLevel > 1)
1528 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1529 para = parser.tableDef->tableRowStart;
1530 ME_RTFSpecialCharHook(&parser);
1531 } else {
1532 para = parser.tableDef->tableRowStart;
1533 ME_RTFSpecialCharHook(&parser);
1534 assert(para->member.para.nFlags & MEPF_ROWEND);
1535 para = para->member.para.next_para;
1538 editor->pCursors[1].pPara = para;
1539 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1540 editor->pCursors[1].nOffset = 0;
1541 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1542 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1543 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1544 if (parser.tableDef)
1545 parser.tableDef->tableRowStart = NULL;
1548 ME_CheckTablesForCorruption(editor);
1549 RTFDestroy(&parser);
1550 if (parser.lpRichEditOle)
1551 IRichEditOle_Release(parser.lpRichEditOle);
1553 if (parser.stackTop > 0)
1555 while (--parser.stackTop >= 0)
1557 ME_ReleaseStyle(parser.style);
1558 parser.style = parser.stack[parser.stackTop].style;
1560 if (!inStream.editstream->dwError)
1561 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1564 /* Remove last line break, as mandated by tests. This is not affected by
1565 CR/LF counters, since RTF streaming presents only \para tokens, which
1566 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1568 if (stripLastCR) {
1569 int newto;
1570 ME_GetSelection(editor, &selStart, &selEnd);
1571 newto = ME_GetCursorOfs(selEnd);
1572 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1573 WCHAR lastchar[3] = {'\0', '\0'};
1574 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1575 ME_Cursor linebreakCursor = *selEnd;
1577 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1578 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1579 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1580 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1584 to = ME_GetCursorOfs(&editor->pCursors[0]);
1585 num_read = to - from;
1587 style = parser.style;
1589 else if (format & SF_TEXT)
1590 num_read = ME_StreamInText(editor, format, &inStream, style);
1591 else
1592 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1593 /* put the cursor at the top */
1594 if (!(format & SFF_SELECTION))
1595 ME_SetSelection(editor, 0, 0);
1598 /* Restore saved undo mode */
1599 editor->nUndoMode = nUndoMode;
1601 /* even if we didn't add an undo, we need to commit anything on the stack */
1602 ME_CommitUndo(editor);
1604 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1605 if (!(format & SFF_SELECTION))
1606 ME_EmptyUndoStack(editor);
1608 ME_ReleaseStyle(style);
1609 editor->nEventMask = nEventMask;
1610 ME_UpdateRepaint(editor, FALSE);
1611 if (!(format & SFF_SELECTION)) {
1612 ME_ClearTempStyle(editor);
1614 ITextHost_TxShowCaret(editor->texthost, FALSE);
1615 ME_MoveCaret(editor);
1616 ITextHost_TxShowCaret(editor->texthost, TRUE);
1617 ME_SendSelChange(editor);
1618 ME_SendRequestResize(editor, FALSE);
1620 return num_read;
1624 typedef struct tagME_RTFStringStreamStruct
1626 char *string;
1627 int pos;
1628 int length;
1629 } ME_RTFStringStreamStruct;
1631 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1633 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1634 int count;
1636 count = min(cb, pStruct->length - pStruct->pos);
1637 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1638 pStruct->pos += count;
1639 *pcb = count;
1640 return 0;
1643 static void
1644 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1646 EDITSTREAM es;
1647 ME_RTFStringStreamStruct data;
1649 data.string = string;
1650 data.length = strlen(string);
1651 data.pos = 0;
1652 es.dwCookie = (DWORD_PTR)&data;
1653 es.pfnCallback = ME_ReadFromRTFString;
1654 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1658 static int
1659 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1661 const int nLen = lstrlenW(text);
1662 const int nTextLen = ME_GetTextLength(editor);
1663 int nMin, nMax;
1664 ME_Cursor cursor;
1665 WCHAR wLastChar = ' ';
1667 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1668 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1670 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1671 FIXME("Flags 0x%08x not implemented\n",
1672 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1674 nMin = chrg->cpMin;
1675 if (chrg->cpMax == -1)
1676 nMax = nTextLen;
1677 else
1678 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1680 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1681 if (editor->bEmulateVersion10 && nMax == nTextLen)
1683 flags |= FR_DOWN;
1686 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1687 if (editor->bEmulateVersion10 && nMax < nMin)
1689 if (chrgText)
1691 chrgText->cpMin = -1;
1692 chrgText->cpMax = -1;
1694 return -1;
1697 /* when searching up, if cpMin < cpMax, then instead of searching
1698 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1699 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1700 * case, it is always bigger than cpMin.
1702 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1704 int nSwap = nMax;
1706 nMax = nMin > nTextLen ? nTextLen : nMin;
1707 if (nMin < nSwap || chrg->cpMax == -1)
1708 nMin = 0;
1709 else
1710 nMin = nSwap;
1713 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1715 if (chrgText)
1716 chrgText->cpMin = chrgText->cpMax = -1;
1717 return -1;
1720 if (flags & FR_DOWN) /* Forward search */
1722 /* If possible, find the character before where the search starts */
1723 if ((flags & FR_WHOLEWORD) && nMin)
1725 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1726 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1727 ME_MoveCursorChars(editor, &cursor, 1);
1728 } else {
1729 ME_CursorFromCharOfs(editor, nMin, &cursor);
1732 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1734 ME_DisplayItem *pCurItem = cursor.pRun;
1735 int nCurStart = cursor.nOffset;
1736 int nMatched = 0;
1738 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1740 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1741 break;
1743 nMatched++;
1744 if (nMatched == nLen)
1746 ME_DisplayItem *pNextItem = pCurItem;
1747 int nNextStart = nCurStart;
1748 WCHAR wNextChar;
1750 /* Check to see if next character is a whitespace */
1751 if (flags & FR_WHOLEWORD)
1753 if (nCurStart + nMatched == pCurItem->member.run.len)
1755 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1756 nNextStart = -nMatched;
1759 if (pNextItem)
1760 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1761 else
1762 wNextChar = ' ';
1764 if (isalnumW(wNextChar))
1765 break;
1768 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1769 if (chrgText)
1771 chrgText->cpMin = cursor.nOffset;
1772 chrgText->cpMax = cursor.nOffset + nLen;
1774 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1775 return cursor.nOffset;
1777 if (nCurStart + nMatched == pCurItem->member.run.len)
1779 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1780 nCurStart = -nMatched;
1783 if (pCurItem)
1784 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1785 else
1786 wLastChar = ' ';
1788 cursor.nOffset++;
1789 if (cursor.nOffset == cursor.pRun->member.run.len)
1791 ME_NextRun(&cursor.pPara, &cursor.pRun);
1792 cursor.nOffset = 0;
1796 else /* Backward search */
1798 /* If possible, find the character after where the search ends */
1799 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1801 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1802 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1803 ME_MoveCursorChars(editor, &cursor, -1);
1804 } else {
1805 ME_CursorFromCharOfs(editor, nMax, &cursor);
1808 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1810 ME_DisplayItem *pCurItem = cursor.pRun;
1811 ME_DisplayItem *pCurPara = cursor.pPara;
1812 int nCurEnd = cursor.nOffset;
1813 int nMatched = 0;
1815 if (nCurEnd == 0)
1817 ME_PrevRun(&pCurPara, &pCurItem);
1818 nCurEnd = pCurItem->member.run.len + nMatched;
1821 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1822 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1824 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1825 break;
1827 nMatched++;
1828 if (nMatched == nLen)
1830 ME_DisplayItem *pPrevItem = pCurItem;
1831 int nPrevEnd = nCurEnd;
1832 WCHAR wPrevChar;
1833 int nStart;
1835 /* Check to see if previous character is a whitespace */
1836 if (flags & FR_WHOLEWORD)
1838 if (nPrevEnd - nMatched == 0)
1840 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1841 if (pPrevItem)
1842 nPrevEnd = pPrevItem->member.run.len + nMatched;
1845 if (pPrevItem)
1846 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1847 else
1848 wPrevChar = ' ';
1850 if (isalnumW(wPrevChar))
1851 break;
1854 nStart = pCurPara->member.para.nCharOfs
1855 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1856 if (chrgText)
1858 chrgText->cpMin = nStart;
1859 chrgText->cpMax = nStart + nLen;
1861 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1862 return nStart;
1864 if (nCurEnd - nMatched == 0)
1866 ME_PrevRun(&pCurPara, &pCurItem);
1867 /* Don't care about pCurItem becoming NULL here; it's already taken
1868 * care of in the exterior loop condition */
1869 nCurEnd = pCurItem->member.run.len + nMatched;
1872 if (pCurItem)
1873 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1874 else
1875 wLastChar = ' ';
1877 cursor.nOffset--;
1878 if (cursor.nOffset < 0)
1880 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1881 cursor.nOffset = cursor.pRun->member.run.len;
1885 TRACE("not found\n");
1886 if (chrgText)
1887 chrgText->cpMin = chrgText->cpMax = -1;
1888 return -1;
1891 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1893 int nChars;
1894 ME_Cursor start;
1896 if (!ex->cb || !pText) return 0;
1898 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1899 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1901 if (ex->flags & GT_SELECTION)
1903 int from, to;
1904 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1905 start = editor->pCursors[nStartCur];
1906 nChars = to - from;
1908 else
1910 ME_SetCursorToStart(editor, &start);
1911 nChars = INT_MAX;
1913 if (ex->codepage == 1200)
1915 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1916 &start, nChars, ex->flags & GT_USECRLF);
1918 else
1920 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1921 we can just take a bigger buffer? :)
1922 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1923 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1925 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1926 DWORD buflen;
1927 LPWSTR buffer;
1928 LRESULT rc;
1930 buflen = min(crlfmul * nChars, ex->cb - 1);
1931 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1933 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1934 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1935 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1936 if (rc) rc--; /* do not count 0 terminator */
1938 heap_free(buffer);
1939 return rc;
1943 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1944 const ME_Cursor *start, int nLen, BOOL unicode)
1946 if (!strText) return 0;
1947 if (unicode) {
1948 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1949 } else {
1950 int nChars;
1951 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1952 if (!p) return 0;
1953 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1954 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1955 nLen+1, NULL, NULL);
1956 FREE_OBJ(p);
1957 return nChars;
1961 typedef struct tagME_GlobalDestStruct
1963 HGLOBAL hData;
1964 int nLength;
1965 } ME_GlobalDestStruct;
1967 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1969 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1970 int i;
1971 WORD *pSrc, *pDest;
1973 cb = cb >> 1;
1974 pDest = (WORD *)lpBuff;
1975 pSrc = GlobalLock(pData->hData);
1976 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1977 pDest[i] = pSrc[pData->nLength+i];
1979 pData->nLength += i;
1980 *pcb = 2*i;
1981 GlobalUnlock(pData->hData);
1982 return 0;
1985 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1987 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1988 int i;
1989 BYTE *pSrc, *pDest;
1991 pDest = lpBuff;
1992 pSrc = GlobalLock(pData->hData);
1993 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1994 pDest[i] = pSrc[pData->nLength+i];
1996 pData->nLength += i;
1997 *pcb = i;
1998 GlobalUnlock(pData->hData);
1999 return 0;
2002 static BOOL ME_Paste(ME_TextEditor *editor)
2004 DWORD dwFormat = 0;
2005 EDITSTREAM es;
2006 ME_GlobalDestStruct gds;
2007 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2008 UINT cf = 0;
2010 if (IsClipboardFormatAvailable(nRTFFormat))
2011 cf = nRTFFormat, dwFormat = SF_RTF;
2012 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2013 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2014 else
2015 return FALSE;
2017 if (!OpenClipboard(editor->hWnd))
2018 return FALSE;
2019 gds.hData = GetClipboardData(cf);
2020 gds.nLength = 0;
2021 es.dwCookie = (DWORD_PTR)&gds;
2022 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2023 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2025 CloseClipboard();
2026 return TRUE;
2029 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2031 LPDATAOBJECT dataObj = NULL;
2032 HRESULT hr = S_OK;
2034 if (editor->cPasswordMask)
2035 return FALSE; /* Copying or Cutting masked text isn't allowed */
2037 if(editor->lpOleCallback)
2039 CHARRANGE range;
2040 range.cpMin = ME_GetCursorOfs(start);
2041 range.cpMax = range.cpMin + nChars;
2042 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2044 if(FAILED(hr) || !dataObj)
2045 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2046 if(SUCCEEDED(hr)) {
2047 hr = OleSetClipboard(dataObj);
2048 IDataObject_Release(dataObj);
2050 return SUCCEEDED(hr) != 0;
2053 /* helper to send a msg filter notification */
2054 static BOOL
2055 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2057 MSGFILTER msgf;
2059 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2060 msgf.nmhdr.hwndFrom = editor->hWnd;
2061 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2062 msgf.nmhdr.code = EN_MSGFILTER;
2063 msgf.msg = msg;
2064 msgf.wParam = *wParam;
2065 msgf.lParam = *lParam;
2066 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2067 return FALSE;
2068 *wParam = msgf.wParam;
2069 *lParam = msgf.lParam;
2070 msgf.wParam = *wParam;
2072 return TRUE;
2075 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2077 ME_DisplayItem *startPara, *endPara;
2078 ME_DisplayItem *prev_para;
2079 ME_Cursor *from, *to;
2080 ME_Cursor start;
2081 int nChars;
2083 if (!editor->AutoURLDetect_bEnable) return;
2085 ME_GetSelection(editor, &from, &to);
2087 /* Find paragraph previous to the one that contains start cursor */
2088 startPara = from->pPara;
2089 prev_para = startPara->member.para.prev_para;
2090 if (prev_para->type == diParagraph) startPara = prev_para;
2092 /* Find paragraph that contains end cursor */
2093 endPara = to->pPara->member.para.next_para;
2095 start.pPara = startPara;
2096 start.pRun = ME_FindItemFwd(startPara, diRun);
2097 start.nOffset = 0;
2098 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2100 ME_UpdateLinkAttribute(editor, &start, nChars);
2103 static BOOL
2104 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2106 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2107 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2109 if (editor->bMouseCaptured)
2110 return FALSE;
2111 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2112 editor->nSelectionType = stPosition;
2114 switch (nKey)
2116 case VK_LEFT:
2117 case VK_RIGHT:
2118 case VK_HOME:
2119 case VK_END:
2120 editor->nUDArrowX = -1;
2121 /* fall through */
2122 case VK_UP:
2123 case VK_DOWN:
2124 case VK_PRIOR:
2125 case VK_NEXT:
2126 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2127 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2128 return TRUE;
2129 case VK_BACK:
2130 case VK_DELETE:
2131 editor->nUDArrowX = -1;
2132 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2133 if (editor->styleFlags & ES_READONLY)
2134 return FALSE;
2135 if (ME_IsSelection(editor))
2137 ME_DeleteSelection(editor);
2138 ME_CommitUndo(editor);
2140 else if (nKey == VK_DELETE)
2142 /* Delete stops group typing.
2143 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2144 ME_DeleteTextAtCursor(editor, 1, 1);
2145 ME_CommitUndo(editor);
2147 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2149 BOOL bDeletionSucceeded;
2150 /* Backspace can be grouped for a single undo */
2151 ME_ContinueCoalescingTransaction(editor);
2152 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2153 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2154 /* Deletion was prevented so the cursor is moved back to where it was.
2155 * (e.g. this happens when trying to delete cell boundaries)
2157 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2159 ME_CommitCoalescingUndo(editor);
2161 else
2162 return TRUE;
2163 ME_MoveCursorFromTableRowStartParagraph(editor);
2164 ME_UpdateSelectionLinkAttribute(editor);
2165 ME_UpdateRepaint(editor, FALSE);
2166 ME_SendRequestResize(editor, FALSE);
2167 return TRUE;
2168 case VK_RETURN:
2169 if (editor->bDialogMode)
2171 if (ctrl_is_down)
2172 return TRUE;
2174 if (!(editor->styleFlags & ES_WANTRETURN))
2176 if (editor->hwndParent)
2178 DWORD dw;
2179 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2180 if (HIWORD(dw) == DC_HASDEFID)
2182 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2183 if (hwDefCtrl)
2185 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2186 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2190 return TRUE;
2194 if (editor->styleFlags & ES_MULTILINE)
2196 ME_Cursor cursor = editor->pCursors[0];
2197 ME_DisplayItem *para = cursor.pPara;
2198 int from, to;
2199 const WCHAR endl = '\r';
2200 const WCHAR endlv10[] = {'\r','\n'};
2201 ME_Style *style;
2203 if (editor->styleFlags & ES_READONLY) {
2204 MessageBeep(MB_ICONERROR);
2205 return TRUE;
2208 ME_GetSelectionOfs(editor, &from, &to);
2209 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2211 if (!editor->bEmulateVersion10) { /* v4.1 */
2212 if (para->member.para.nFlags & MEPF_ROWEND) {
2213 /* Add a new table row after this row. */
2214 para = ME_AppendTableRow(editor, para);
2215 para = para->member.para.next_para;
2216 editor->pCursors[0].pPara = para;
2217 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2218 editor->pCursors[0].nOffset = 0;
2219 editor->pCursors[1] = editor->pCursors[0];
2220 ME_CommitUndo(editor);
2221 ME_CheckTablesForCorruption(editor);
2222 ME_UpdateRepaint(editor, FALSE);
2223 return TRUE;
2225 else if (para == editor->pCursors[1].pPara &&
2226 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2227 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2228 !para->member.para.prev_para->member.para.nCharOfs)
2230 /* Insert a newline before the table. */
2231 para = para->member.para.prev_para;
2232 para->member.para.nFlags &= ~MEPF_ROWSTART;
2233 editor->pCursors[0].pPara = para;
2234 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2235 editor->pCursors[1] = editor->pCursors[0];
2236 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2237 editor->pCursors[0].pRun->member.run.style);
2238 para = editor->pBuffer->pFirst->member.para.next_para;
2239 ME_SetDefaultParaFormat(para->member.para.pFmt);
2240 para->member.para.nFlags = MEPF_REWRAP;
2241 editor->pCursors[0].pPara = para;
2242 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2243 editor->pCursors[1] = editor->pCursors[0];
2244 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2245 ME_CommitCoalescingUndo(editor);
2246 ME_CheckTablesForCorruption(editor);
2247 ME_UpdateRepaint(editor, FALSE);
2248 return TRUE;
2250 } else { /* v1.0 - 3.0 */
2251 ME_DisplayItem *para = cursor.pPara;
2252 if (ME_IsInTable(para))
2254 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2256 if (from == to) {
2257 ME_ContinueCoalescingTransaction(editor);
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];
2263 ME_CommitCoalescingUndo(editor);
2264 ME_UpdateRepaint(editor, FALSE);
2265 return TRUE;
2267 } else {
2268 ME_ContinueCoalescingTransaction(editor);
2269 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2270 !ME_IsInTable(para->member.para.prev_para))
2272 /* Insert newline before table */
2273 cursor.pRun = ME_FindItemBack(para, diRun);
2274 if (cursor.pRun) {
2275 editor->pCursors[0].pRun = cursor.pRun;
2276 editor->pCursors[0].pPara = para->member.para.prev_para;
2278 editor->pCursors[0].nOffset = 0;
2279 editor->pCursors[1] = editor->pCursors[0];
2280 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2281 editor->pCursors[0].pRun->member.run.style);
2282 } else {
2283 editor->pCursors[1] = editor->pCursors[0];
2284 para = ME_AppendTableRow(editor, para);
2285 editor->pCursors[0].pPara = para;
2286 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2287 editor->pCursors[0].nOffset = 0;
2288 editor->pCursors[1] = editor->pCursors[0];
2290 ME_CommitCoalescingUndo(editor);
2291 ME_UpdateRepaint(editor, FALSE);
2292 return TRUE;
2297 style = ME_GetInsertStyle(editor, 0);
2298 ME_SaveTempStyle(editor);
2299 ME_ContinueCoalescingTransaction(editor);
2300 if (shift_is_down)
2301 ME_InsertEndRowFromCursor(editor, 0);
2302 else
2303 if (!editor->bEmulateVersion10)
2304 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2305 else
2306 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2307 ME_ReleaseStyle(style);
2308 ME_CommitCoalescingUndo(editor);
2309 SetCursor(NULL);
2311 ME_UpdateSelectionLinkAttribute(editor);
2312 ME_UpdateRepaint(editor, FALSE);
2314 return TRUE;
2316 break;
2317 case VK_ESCAPE:
2318 if (editor->bDialogMode && editor->hwndParent)
2319 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2320 return TRUE;
2321 case VK_TAB:
2322 if (editor->bDialogMode && editor->hwndParent)
2323 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2324 return TRUE;
2325 case 'A':
2326 if (ctrl_is_down)
2328 ME_SetSelection(editor, 0, -1);
2329 return TRUE;
2331 break;
2332 case 'V':
2333 if (ctrl_is_down)
2334 return ME_Paste(editor);
2335 break;
2336 case 'C':
2337 case 'X':
2338 if (ctrl_is_down)
2340 BOOL result;
2341 int nOfs, nChars;
2342 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2343 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2345 nChars -= nOfs;
2346 result = ME_Copy(editor, selStart, nChars);
2347 if (result && nKey == 'X')
2349 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2350 ME_CommitUndo(editor);
2351 ME_UpdateRepaint(editor, TRUE);
2353 return result;
2355 break;
2356 case 'Z':
2357 if (ctrl_is_down)
2359 ME_Undo(editor);
2360 return TRUE;
2362 break;
2363 case 'Y':
2364 if (ctrl_is_down)
2366 ME_Redo(editor);
2367 return TRUE;
2369 break;
2371 default:
2372 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2373 editor->nUDArrowX = -1;
2374 if (ctrl_is_down)
2376 if (nKey == 'W')
2378 CHARFORMAT2W chf;
2379 char buf[2048];
2380 chf.cbSize = sizeof(chf);
2382 ME_GetSelectionCharFormat(editor, &chf);
2383 ME_DumpStyleToBuf(&chf, buf);
2384 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2386 if (nKey == 'Q')
2388 ME_CheckCharOffsets(editor);
2392 return FALSE;
2395 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2396 LPARAM flags, BOOL unicode)
2398 WCHAR wstr;
2400 if (editor->bMouseCaptured)
2401 return 0;
2403 if (unicode)
2404 wstr = (WCHAR)charCode;
2405 else
2407 CHAR charA = charCode;
2408 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2411 if (editor->styleFlags & ES_READONLY) {
2412 MessageBeep(MB_ICONERROR);
2413 return 0; /* FIXME really 0 ? */
2416 if ((unsigned)wstr >= ' ' || wstr == '\t')
2418 ME_Cursor cursor = editor->pCursors[0];
2419 ME_DisplayItem *para = cursor.pPara;
2420 int from, to;
2421 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2422 ME_GetSelectionOfs(editor, &from, &to);
2423 if (wstr == '\t' &&
2424 /* v4.1 allows tabs to be inserted with ctrl key down */
2425 !(ctrl_is_down && !editor->bEmulateVersion10))
2427 ME_DisplayItem *para;
2428 BOOL bSelectedRow = FALSE;
2430 para = cursor.pPara;
2431 if (ME_IsSelection(editor) &&
2432 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2433 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2434 para->member.para.prev_para->type == diParagraph)
2436 para = para->member.para.prev_para;
2437 bSelectedRow = TRUE;
2439 if (ME_IsInTable(para))
2441 ME_TabPressedInTable(editor, bSelectedRow);
2442 ME_CommitUndo(editor);
2443 return 0;
2445 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2446 if (para->member.para.nFlags & MEPF_ROWEND) {
2447 if (from == to) {
2448 para = para->member.para.next_para;
2449 if (para->member.para.nFlags & MEPF_ROWSTART)
2450 para = para->member.para.next_para;
2451 editor->pCursors[0].pPara = para;
2452 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2453 editor->pCursors[0].nOffset = 0;
2454 editor->pCursors[1] = editor->pCursors[0];
2457 } else { /* v1.0 - 3.0 */
2458 if (ME_IsInTable(cursor.pRun) &&
2459 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2460 from == to)
2462 /* Text should not be inserted at the end of the table. */
2463 MessageBeep(-1);
2464 return 0;
2467 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2468 /* WM_CHAR is restricted to nTextLimit */
2469 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2471 ME_Style *style = ME_GetInsertStyle(editor, 0);
2472 ME_SaveTempStyle(editor);
2473 ME_ContinueCoalescingTransaction(editor);
2474 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2475 ME_ReleaseStyle(style);
2476 ME_CommitCoalescingUndo(editor);
2477 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2480 ME_UpdateSelectionLinkAttribute(editor);
2481 ME_UpdateRepaint(editor, FALSE);
2483 return 0;
2486 /* Process the message and calculate the new click count.
2488 * returns: The click count if it is mouse down event, else returns 0. */
2489 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2490 LPARAM lParam)
2492 static int clickNum = 0;
2493 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2494 return 0;
2496 if ((msg == WM_LBUTTONDBLCLK) ||
2497 (msg == WM_RBUTTONDBLCLK) ||
2498 (msg == WM_MBUTTONDBLCLK) ||
2499 (msg == WM_XBUTTONDBLCLK))
2501 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2504 if ((msg == WM_LBUTTONDOWN) ||
2505 (msg == WM_RBUTTONDOWN) ||
2506 (msg == WM_MBUTTONDOWN) ||
2507 (msg == WM_XBUTTONDOWN))
2509 static MSG prevClickMsg;
2510 MSG clickMsg;
2511 /* Compare the editor instead of the hwnd so that the this
2512 * can still be done for windowless richedit controls. */
2513 clickMsg.hwnd = (HWND)editor;
2514 clickMsg.message = msg;
2515 clickMsg.wParam = wParam;
2516 clickMsg.lParam = lParam;
2517 clickMsg.time = GetMessageTime();
2518 clickMsg.pt.x = (short)LOWORD(lParam);
2519 clickMsg.pt.y = (short)HIWORD(lParam);
2520 if ((clickNum != 0) &&
2521 (clickMsg.message == prevClickMsg.message) &&
2522 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2523 (clickMsg.wParam == prevClickMsg.wParam) &&
2524 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2525 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2526 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2528 clickNum++;
2529 } else {
2530 clickNum = 1;
2532 prevClickMsg = clickMsg;
2533 } else {
2534 return 0;
2536 return clickNum;
2539 static BOOL ME_SetCursor(ME_TextEditor *editor)
2541 ME_Cursor cursor;
2542 POINT pt;
2543 BOOL isExact;
2544 SCROLLBARINFO sbi;
2545 DWORD messagePos = GetMessagePos();
2546 pt.x = (short)LOWORD(messagePos);
2547 pt.y = (short)HIWORD(messagePos);
2549 if (editor->hWnd)
2551 sbi.cbSize = sizeof(sbi);
2552 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2553 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2554 PtInRect(&sbi.rcScrollBar, pt))
2556 ITextHost_TxSetCursor(editor->texthost,
2557 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2558 return TRUE;
2560 sbi.cbSize = sizeof(sbi);
2561 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2562 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2563 PtInRect(&sbi.rcScrollBar, pt))
2565 ITextHost_TxSetCursor(editor->texthost,
2566 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2567 return TRUE;
2570 ITextHost_TxScreenToClient(editor->texthost, &pt);
2572 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2573 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2574 return TRUE;
2576 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2577 pt.y < editor->rcFormat.top &&
2578 pt.x < editor->rcFormat.left)
2580 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2581 return TRUE;
2583 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2585 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2586 ITextHost_TxSetCursor(editor->texthost,
2587 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2588 else /* v4.1 */
2589 ITextHost_TxSetCursor(editor->texthost,
2590 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2591 return TRUE;
2593 if (pt.x < editor->rcFormat.left)
2595 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2596 return TRUE;
2598 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2599 if (isExact)
2601 ME_Run *run;
2603 run = &cursor.pRun->member.run;
2604 if (run->style->fmt.dwMask & CFM_LINK &&
2605 run->style->fmt.dwEffects & CFE_LINK)
2607 ITextHost_TxSetCursor(editor->texthost,
2608 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2609 FALSE);
2610 return TRUE;
2613 if (ME_IsSelection(editor))
2615 int selStart, selEnd;
2616 int offset = ME_GetCursorOfs(&cursor);
2618 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2619 if (selStart <= offset && selEnd >= offset) {
2620 ITextHost_TxSetCursor(editor->texthost,
2621 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2622 FALSE);
2623 return TRUE;
2627 ITextHost_TxSetCursor(editor->texthost,
2628 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2629 return TRUE;
2632 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2634 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2635 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2636 editor->rcFormat.left += 1 + editor->selofs;
2637 editor->rcFormat.right -= 1;
2640 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2642 CHARRANGE selrange;
2643 HMENU menu;
2644 int seltype = 0;
2645 if(!editor->lpOleCallback || !editor->hWnd)
2646 return FALSE;
2647 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2648 if(selrange.cpMin == selrange.cpMax)
2649 seltype |= SEL_EMPTY;
2650 else
2652 /* FIXME: Handle objects */
2653 seltype |= SEL_TEXT;
2654 if(selrange.cpMax-selrange.cpMin > 1)
2655 seltype |= SEL_MULTICHAR;
2657 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2659 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2660 DestroyMenu(menu);
2662 return TRUE;
2665 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2667 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2668 int i;
2669 DWORD props;
2670 LONG selbarwidth;
2672 ed->hWnd = NULL;
2673 ed->hwndParent = NULL;
2674 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2675 ed->texthost = texthost;
2676 ed->bEmulateVersion10 = bEmulateVersion10;
2677 ed->styleFlags = 0;
2678 ITextHost_TxGetPropertyBits(texthost,
2679 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2680 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2681 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2682 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2683 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2684 &props);
2685 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2686 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2687 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2688 ed->pBuffer = ME_MakeText();
2689 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2690 ed->nAvailWidth = 0; /* wrap to client area */
2691 ME_MakeFirstParagraph(ed);
2692 /* The four cursors are for:
2693 * 0 - The position where the caret is shown
2694 * 1 - The anchored end of the selection (for normal selection)
2695 * 2 & 3 - The anchored start and end respectively for word, line,
2696 * or paragraph selection.
2698 ed->nCursors = 4;
2699 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2700 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2701 ed->pCursors[1] = ed->pCursors[0];
2702 ed->pCursors[2] = ed->pCursors[0];
2703 ed->pCursors[3] = ed->pCursors[1];
2704 ed->nLastTotalLength = ed->nTotalLength = 0;
2705 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2706 ed->nUDArrowX = -1;
2707 ed->rgbBackColor = -1;
2708 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2709 ed->bCaretAtEnd = FALSE;
2710 ed->nEventMask = 0;
2711 ed->nModifyStep = 0;
2712 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2713 list_init( &ed->undo_stack );
2714 list_init( &ed->redo_stack );
2715 ed->nUndoStackSize = 0;
2716 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2717 ed->nUndoMode = umAddToUndo;
2718 ed->nParagraphs = 1;
2719 ed->nLastSelStart = ed->nLastSelEnd = 0;
2720 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2721 ed->bHideSelection = FALSE;
2722 ed->pfnWordBreak = NULL;
2723 ed->lpOleCallback = NULL;
2724 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2725 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2726 ed->AutoURLDetect_bEnable = FALSE;
2727 ed->bHaveFocus = FALSE;
2728 ed->bDialogMode = FALSE;
2729 ed->bMouseCaptured = FALSE;
2730 for (i=0; i<HFONT_CACHE_SIZE; i++)
2732 ed->pFontCache[i].nRefs = 0;
2733 ed->pFontCache[i].nAge = 0;
2734 ed->pFontCache[i].hFont = NULL;
2737 ME_CheckCharOffsets(ed);
2738 ed->bDefaultFormatRect = TRUE;
2739 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2740 if (selbarwidth) {
2741 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2742 ed->selofs = SELECTIONBAR_WIDTH;
2743 ed->styleFlags |= ES_SELECTIONBAR;
2744 } else {
2745 ed->selofs = 0;
2747 ed->nSelectionType = stPosition;
2749 ed->cPasswordMask = 0;
2750 if (props & TXTBIT_USEPASSWORD)
2751 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2753 if (props & TXTBIT_AUTOWORDSEL)
2754 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2755 if (props & TXTBIT_MULTILINE) {
2756 ed->styleFlags |= ES_MULTILINE;
2757 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2758 } else {
2759 ed->bWordWrap = FALSE;
2761 if (props & TXTBIT_READONLY)
2762 ed->styleFlags |= ES_READONLY;
2763 if (!(props & TXTBIT_HIDESELECTION))
2764 ed->styleFlags |= ES_NOHIDESEL;
2765 if (props & TXTBIT_SAVESELECTION)
2766 ed->styleFlags |= ES_SAVESEL;
2767 if (props & TXTBIT_VERTICAL)
2768 ed->styleFlags |= ES_VERTICAL;
2769 if (props & TXTBIT_DISABLEDRAG)
2770 ed->styleFlags |= ES_NOOLEDRAGDROP;
2772 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2774 /* Default scrollbar information */
2775 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2776 ed->vert_si.nMin = 0;
2777 ed->vert_si.nMax = 0;
2778 ed->vert_si.nPage = 0;
2779 ed->vert_si.nPos = 0;
2781 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2782 ed->horz_si.nMin = 0;
2783 ed->horz_si.nMax = 0;
2784 ed->horz_si.nPage = 0;
2785 ed->horz_si.nPos = 0;
2787 OleInitialize(NULL);
2789 return ed;
2792 static void ME_DestroyEditor(ME_TextEditor *editor)
2794 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2795 ME_DisplayItem *p = pFirst, *pNext = NULL;
2796 int i;
2798 ME_ClearTempStyle(editor);
2799 ME_EmptyUndoStack(editor);
2800 while(p) {
2801 pNext = p->next;
2802 ME_DestroyDisplayItem(p);
2803 p = pNext;
2805 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2806 for (i=0; i<HFONT_CACHE_SIZE; i++)
2808 if (editor->pFontCache[i].hFont)
2809 DeleteObject(editor->pFontCache[i].hFont);
2811 if (editor->rgbBackColor != -1)
2812 DeleteObject(editor->hbrBackground);
2813 if(editor->lpOleCallback)
2814 IRichEditOleCallback_Release(editor->lpOleCallback);
2815 ITextHost_Release(editor->texthost);
2816 OleUninitialize();
2818 FREE_OBJ(editor->pBuffer);
2819 FREE_OBJ(editor->pCursors);
2821 FREE_OBJ(editor);
2824 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2826 TRACE("\n");
2827 switch (fdwReason)
2829 case DLL_PROCESS_ATTACH:
2830 DisableThreadLibraryCalls(hinstDLL);
2831 me_heap = HeapCreate (0, 0x10000, 0);
2832 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2833 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2834 LookupInit();
2835 break;
2837 case DLL_PROCESS_DETACH:
2838 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2839 UnregisterClassW(MSFTEDIT_CLASS, 0);
2840 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2841 UnregisterClassA("RichEdit50A", 0);
2842 if (ME_ListBoxRegistered)
2843 UnregisterClassW(REListBox20W, 0);
2844 if (ME_ComboBoxRegistered)
2845 UnregisterClassW(REComboBox20W, 0);
2846 LookupCleanup();
2847 HeapDestroy (me_heap);
2848 me_heap = NULL;
2849 break;
2851 return TRUE;
2855 static const char * const edit_messages[] = {
2856 "EM_GETSEL",
2857 "EM_SETSEL",
2858 "EM_GETRECT",
2859 "EM_SETRECT",
2860 "EM_SETRECTNP",
2861 "EM_SCROLL",
2862 "EM_LINESCROLL",
2863 "EM_SCROLLCARET",
2864 "EM_GETMODIFY",
2865 "EM_SETMODIFY",
2866 "EM_GETLINECOUNT",
2867 "EM_LINEINDEX",
2868 "EM_SETHANDLE",
2869 "EM_GETHANDLE",
2870 "EM_GETTHUMB",
2871 "EM_UNKNOWN_BF",
2872 "EM_UNKNOWN_C0",
2873 "EM_LINELENGTH",
2874 "EM_REPLACESEL",
2875 "EM_UNKNOWN_C3",
2876 "EM_GETLINE",
2877 "EM_LIMITTEXT",
2878 "EM_CANUNDO",
2879 "EM_UNDO",
2880 "EM_FMTLINES",
2881 "EM_LINEFROMCHAR",
2882 "EM_UNKNOWN_CA",
2883 "EM_SETTABSTOPS",
2884 "EM_SETPASSWORDCHAR",
2885 "EM_EMPTYUNDOBUFFER",
2886 "EM_GETFIRSTVISIBLELINE",
2887 "EM_SETREADONLY",
2888 "EM_SETWORDBREAKPROC",
2889 "EM_GETWORDBREAKPROC",
2890 "EM_GETPASSWORDCHAR",
2891 "EM_SETMARGINS",
2892 "EM_GETMARGINS",
2893 "EM_GETLIMITTEXT",
2894 "EM_POSFROMCHAR",
2895 "EM_CHARFROMPOS",
2896 "EM_SETIMESTATUS",
2897 "EM_GETIMESTATUS"
2900 static const char * const richedit_messages[] = {
2901 "EM_CANPASTE",
2902 "EM_DISPLAYBAND",
2903 "EM_EXGETSEL",
2904 "EM_EXLIMITTEXT",
2905 "EM_EXLINEFROMCHAR",
2906 "EM_EXSETSEL",
2907 "EM_FINDTEXT",
2908 "EM_FORMATRANGE",
2909 "EM_GETCHARFORMAT",
2910 "EM_GETEVENTMASK",
2911 "EM_GETOLEINTERFACE",
2912 "EM_GETPARAFORMAT",
2913 "EM_GETSELTEXT",
2914 "EM_HIDESELECTION",
2915 "EM_PASTESPECIAL",
2916 "EM_REQUESTRESIZE",
2917 "EM_SELECTIONTYPE",
2918 "EM_SETBKGNDCOLOR",
2919 "EM_SETCHARFORMAT",
2920 "EM_SETEVENTMASK",
2921 "EM_SETOLECALLBACK",
2922 "EM_SETPARAFORMAT",
2923 "EM_SETTARGETDEVICE",
2924 "EM_STREAMIN",
2925 "EM_STREAMOUT",
2926 "EM_GETTEXTRANGE",
2927 "EM_FINDWORDBREAK",
2928 "EM_SETOPTIONS",
2929 "EM_GETOPTIONS",
2930 "EM_FINDTEXTEX",
2931 "EM_GETWORDBREAKPROCEX",
2932 "EM_SETWORDBREAKPROCEX",
2933 "EM_SETUNDOLIMIT",
2934 "EM_UNKNOWN_USER_83",
2935 "EM_REDO",
2936 "EM_CANREDO",
2937 "EM_GETUNDONAME",
2938 "EM_GETREDONAME",
2939 "EM_STOPGROUPTYPING",
2940 "EM_SETTEXTMODE",
2941 "EM_GETTEXTMODE",
2942 "EM_AUTOURLDETECT",
2943 "EM_GETAUTOURLDETECT",
2944 "EM_SETPALETTE",
2945 "EM_GETTEXTEX",
2946 "EM_GETTEXTLENGTHEX",
2947 "EM_SHOWSCROLLBAR",
2948 "EM_SETTEXTEX",
2949 "EM_UNKNOWN_USER_98",
2950 "EM_UNKNOWN_USER_99",
2951 "EM_SETPUNCTUATION",
2952 "EM_GETPUNCTUATION",
2953 "EM_SETWORDWRAPMODE",
2954 "EM_GETWORDWRAPMODE",
2955 "EM_SETIMECOLOR",
2956 "EM_GETIMECOLOR",
2957 "EM_SETIMEOPTIONS",
2958 "EM_GETIMEOPTIONS",
2959 "EM_CONVPOSITION",
2960 "EM_UNKNOWN_USER_109",
2961 "EM_UNKNOWN_USER_110",
2962 "EM_UNKNOWN_USER_111",
2963 "EM_UNKNOWN_USER_112",
2964 "EM_UNKNOWN_USER_113",
2965 "EM_UNKNOWN_USER_114",
2966 "EM_UNKNOWN_USER_115",
2967 "EM_UNKNOWN_USER_116",
2968 "EM_UNKNOWN_USER_117",
2969 "EM_UNKNOWN_USER_118",
2970 "EM_UNKNOWN_USER_119",
2971 "EM_SETLANGOPTIONS",
2972 "EM_GETLANGOPTIONS",
2973 "EM_GETIMECOMPMODE",
2974 "EM_FINDTEXTW",
2975 "EM_FINDTEXTEXW",
2976 "EM_RECONVERSION",
2977 "EM_SETIMEMODEBIAS",
2978 "EM_GETIMEMODEBIAS"
2981 static const char *
2982 get_msg_name(UINT msg)
2984 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2985 return edit_messages[msg - EM_GETSEL];
2986 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2987 return richedit_messages[msg - EM_CANPASTE];
2988 return "";
2991 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2993 int x,y;
2994 BOOL isExact;
2995 ME_Cursor cursor; /* The start of the clicked text. */
2997 ENLINK info;
2998 x = (short)LOWORD(lParam);
2999 y = (short)HIWORD(lParam);
3000 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3001 if (!isExact) return;
3003 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3004 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3005 { /* The clicked run has CFE_LINK set */
3006 info.nmhdr.hwndFrom = NULL;
3007 info.nmhdr.idFrom = 0;
3008 info.nmhdr.code = EN_LINK;
3009 info.msg = msg;
3010 info.wParam = wParam;
3011 info.lParam = lParam;
3012 cursor.nOffset = 0;
3013 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3014 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3015 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3019 #define UNSUPPORTED_MSG(e) \
3020 case e: \
3021 FIXME(#e ": stub\n"); \
3022 *phresult = S_FALSE; \
3023 return 0;
3025 /* Handle messages for windowless and windoweded richedit controls.
3027 * The LRESULT that is returned is a return value for window procs,
3028 * and the phresult parameter is the COM return code needed by the
3029 * text services interface. */
3030 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3031 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3033 *phresult = S_OK;
3035 switch(msg) {
3037 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3038 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3039 UNSUPPORTED_MSG(EM_FMTLINES)
3040 UNSUPPORTED_MSG(EM_FORMATRANGE)
3041 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3042 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3043 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3044 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3045 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3046 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3047 UNSUPPORTED_MSG(EM_GETREDONAME)
3048 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3049 UNSUPPORTED_MSG(EM_GETUNDONAME)
3050 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3051 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3052 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3053 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3054 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3055 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3056 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3057 UNSUPPORTED_MSG(EM_SETMARGINS)
3058 UNSUPPORTED_MSG(EM_SETPALETTE)
3059 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3060 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3061 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3063 /* Messages specific to Richedit controls */
3065 case EM_STREAMIN:
3066 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3067 case EM_STREAMOUT:
3068 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3069 case WM_GETDLGCODE:
3071 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3072 if (lParam)
3073 editor->bDialogMode = TRUE;
3074 if (editor->styleFlags & ES_MULTILINE)
3075 code |= DLGC_WANTMESSAGE;
3076 return code;
3078 case EM_EMPTYUNDOBUFFER:
3079 ME_EmptyUndoStack(editor);
3080 return 0;
3081 case EM_GETSEL:
3083 /* Note: wParam/lParam can be NULL */
3084 UINT from, to;
3085 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3086 PUINT pto = lParam ? (PUINT)lParam : &to;
3087 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3088 if ((*pfrom|*pto) & 0xFFFF0000)
3089 return -1;
3090 return MAKELONG(*pfrom,*pto);
3092 case EM_EXGETSEL:
3094 CHARRANGE *pRange = (CHARRANGE *)lParam;
3095 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3096 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3097 return 0;
3099 case EM_SETUNDOLIMIT:
3101 if ((int)wParam < 0)
3102 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3103 else
3104 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3105 /* Setting a max stack size keeps wine from getting killed
3106 for hogging memory. Windows allocates all this memory at once, so
3107 no program would realistically set a value above our maximum. */
3108 return editor->nUndoLimit;
3110 case EM_CANUNDO:
3111 return !list_empty( &editor->undo_stack );
3112 case EM_CANREDO:
3113 return !list_empty( &editor->redo_stack );
3114 case WM_UNDO: /* FIXME: actually not the same */
3115 case EM_UNDO:
3116 return ME_Undo(editor);
3117 case EM_REDO:
3118 return ME_Redo(editor);
3119 case EM_GETOPTIONS:
3121 /* these flags are equivalent to the ES_* counterparts */
3122 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3123 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3124 DWORD settings = editor->styleFlags & mask;
3126 return settings;
3128 case EM_SETOPTIONS:
3130 /* these flags are equivalent to ES_* counterparts, except for
3131 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3132 * but is still stored in editor->styleFlags. */
3133 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3134 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3135 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3136 DWORD settings = mask & editor->styleFlags;
3137 DWORD oldSettings = settings;
3138 DWORD changedSettings;
3140 switch(wParam)
3142 case ECOOP_SET:
3143 settings = lParam;
3144 break;
3145 case ECOOP_OR:
3146 settings |= lParam;
3147 break;
3148 case ECOOP_AND:
3149 settings &= lParam;
3150 break;
3151 case ECOOP_XOR:
3152 settings ^= lParam;
3154 changedSettings = oldSettings ^ settings;
3156 if (changedSettings) {
3157 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3159 if (changedSettings & ECO_SELECTIONBAR)
3161 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3162 if (settings & ECO_SELECTIONBAR) {
3163 assert(!editor->selofs);
3164 editor->selofs = SELECTIONBAR_WIDTH;
3165 editor->rcFormat.left += editor->selofs;
3166 } else {
3167 editor->rcFormat.left -= editor->selofs;
3168 editor->selofs = 0;
3170 ME_RewrapRepaint(editor);
3173 if (changedSettings & settings & ECO_VERTICAL)
3174 FIXME("ECO_VERTICAL not implemented yet!\n");
3175 if (changedSettings & settings & ECO_AUTOHSCROLL)
3176 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3177 if (changedSettings & settings & ECO_AUTOVSCROLL)
3178 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3179 if (changedSettings & settings & ECO_NOHIDESEL)
3180 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3181 if (changedSettings & settings & ECO_WANTRETURN)
3182 FIXME("ECO_WANTRETURN not implemented yet!\n");
3183 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3184 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3187 return settings;
3189 case EM_SETSEL:
3191 ME_InvalidateSelection(editor);
3192 ME_SetSelection(editor, wParam, lParam);
3193 ME_InvalidateSelection(editor);
3194 ITextHost_TxShowCaret(editor->texthost, FALSE);
3195 ME_ShowCaret(editor);
3196 ME_SendSelChange(editor);
3197 return 0;
3199 case EM_SETSCROLLPOS:
3201 POINT *point = (POINT *)lParam;
3202 ME_ScrollAbs(editor, point->x, point->y);
3203 return 0;
3205 case EM_AUTOURLDETECT:
3207 if (wParam==1 || wParam ==0)
3209 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3210 return 0;
3212 return E_INVALIDARG;
3214 case EM_GETAUTOURLDETECT:
3216 return editor->AutoURLDetect_bEnable;
3218 case EM_EXSETSEL:
3220 int end;
3221 CHARRANGE range = *(CHARRANGE *)lParam;
3223 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3225 ME_InvalidateSelection(editor);
3226 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3227 ME_InvalidateSelection(editor);
3228 ITextHost_TxShowCaret(editor->texthost, FALSE);
3229 ME_ShowCaret(editor);
3230 ME_SendSelChange(editor);
3232 return end;
3234 case EM_SHOWSCROLLBAR:
3236 DWORD flags;
3238 switch (wParam)
3240 case SB_HORZ:
3241 flags = WS_HSCROLL;
3242 break;
3243 case SB_VERT:
3244 flags = WS_VSCROLL;
3245 break;
3246 case SB_BOTH:
3247 flags = WS_HSCROLL|WS_VSCROLL;
3248 break;
3249 default:
3250 return 0;
3253 if (lParam) {
3254 editor->styleFlags |= flags;
3255 if (flags & WS_HSCROLL)
3256 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3257 editor->nTotalWidth > editor->sizeWindow.cx);
3258 if (flags & WS_VSCROLL)
3259 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3260 editor->nTotalLength > editor->sizeWindow.cy);
3261 } else {
3262 editor->styleFlags &= ~flags;
3263 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3265 return 0;
3267 case EM_SETTEXTEX:
3269 LPWSTR wszText;
3270 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3271 size_t len = 0;
3272 int from, to;
3273 ME_Style *style;
3274 BOOL bRtf, bUnicode, bSelection;
3275 int oldModify = editor->nModifyStep;
3277 if (!pStruct) return 0;
3279 /* If we detect ascii rtf at the start of the string,
3280 * we know it isn't unicode. */
3281 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3282 !strncmp((char *)lParam, "{\\urtf", 6)));
3283 bUnicode = !bRtf && pStruct->codepage == 1200;
3285 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3286 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3287 pStruct->flags, pStruct->codepage);
3289 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3290 if (bSelection) {
3291 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3292 style = ME_GetSelectionInsertStyle(editor);
3293 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3294 } else {
3295 ME_Cursor start;
3296 ME_SetCursorToStart(editor, &start);
3297 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3298 style = editor->pBuffer->pDefaultStyle;
3301 if (bRtf) {
3302 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3303 if (bSelection) {
3304 /* FIXME: The length returned doesn't include the rtf control
3305 * characters, only the actual text. */
3306 len = lParam ? strlen((char *)lParam) : 0;
3308 } else {
3309 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3310 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3311 len = wszText ? lstrlenW(wszText) : 0;
3312 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3313 ME_EndToUnicode(bUnicode, wszText);
3316 if (bSelection) {
3317 ME_ReleaseStyle(style);
3318 ME_UpdateSelectionLinkAttribute(editor);
3319 } else {
3320 ME_Cursor cursor;
3321 len = 1;
3322 ME_SetCursorToStart(editor, &cursor);
3323 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3325 ME_CommitUndo(editor);
3326 if (!(pStruct->flags & ST_KEEPUNDO))
3328 editor->nModifyStep = oldModify;
3329 ME_EmptyUndoStack(editor);
3331 ME_UpdateRepaint(editor, FALSE);
3332 return len;
3334 case EM_SETBKGNDCOLOR:
3336 LRESULT lColor;
3337 if (editor->rgbBackColor != -1) {
3338 DeleteObject(editor->hbrBackground);
3339 lColor = editor->rgbBackColor;
3341 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3343 if (wParam)
3345 editor->rgbBackColor = -1;
3346 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3348 else
3350 editor->rgbBackColor = lParam;
3351 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3353 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3354 ITextHost_TxViewChange(editor->texthost, TRUE);
3355 return lColor;
3357 case EM_GETMODIFY:
3358 return editor->nModifyStep == 0 ? 0 : -1;
3359 case EM_SETMODIFY:
3361 if (wParam)
3362 editor->nModifyStep = 1;
3363 else
3364 editor->nModifyStep = 0;
3366 return 0;
3368 case EM_SETREADONLY:
3370 if (wParam)
3371 editor->styleFlags |= ES_READONLY;
3372 else
3373 editor->styleFlags &= ~ES_READONLY;
3374 return 0;
3376 case EM_SETEVENTMASK:
3378 DWORD nOldMask = editor->nEventMask;
3380 editor->nEventMask = lParam;
3381 return nOldMask;
3383 case EM_GETEVENTMASK:
3384 return editor->nEventMask;
3385 case EM_SETCHARFORMAT:
3387 CHARFORMAT2W buf, *p;
3388 BOOL bRepaint = TRUE;
3389 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3390 if (p == NULL) return 0;
3391 if (wParam & SCF_ALL) {
3392 if (editor->mode & TM_PLAINTEXT) {
3393 ME_SetDefaultCharFormat(editor, p);
3394 } else {
3395 ME_Cursor start;
3396 ME_SetCursorToStart(editor, &start);
3397 ME_SetCharFormat(editor, &start, NULL, p);
3398 editor->nModifyStep = 1;
3400 } else if (wParam & SCF_SELECTION) {
3401 if (editor->mode & TM_PLAINTEXT)
3402 return 0;
3403 if (wParam & SCF_WORD) {
3404 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3405 return 0;
3407 bRepaint = ME_IsSelection(editor);
3408 ME_SetSelectionCharFormat(editor, p);
3409 if (bRepaint) editor->nModifyStep = 1;
3410 } else { /* SCF_DEFAULT */
3411 ME_SetDefaultCharFormat(editor, p);
3413 ME_CommitUndo(editor);
3414 if (bRepaint)
3416 ME_WrapMarkedParagraphs(editor);
3417 ME_UpdateScrollBar(editor);
3418 ME_Repaint(editor);
3420 return 1;
3422 case EM_GETCHARFORMAT:
3424 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3425 if (dst->cbSize != sizeof(CHARFORMATA) &&
3426 dst->cbSize != sizeof(CHARFORMATW) &&
3427 dst->cbSize != sizeof(CHARFORMAT2A) &&
3428 dst->cbSize != sizeof(CHARFORMAT2W))
3429 return 0;
3430 tmp.cbSize = sizeof(tmp);
3431 if (!wParam)
3432 ME_GetDefaultCharFormat(editor, &tmp);
3433 else
3434 ME_GetSelectionCharFormat(editor, &tmp);
3435 ME_CopyToCFAny(dst, &tmp);
3436 return tmp.dwMask;
3438 case EM_SETPARAFORMAT:
3440 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3441 ME_WrapMarkedParagraphs(editor);
3442 ME_UpdateScrollBar(editor);
3443 ME_Repaint(editor);
3444 ME_CommitUndo(editor);
3445 return result;
3447 case EM_GETPARAFORMAT:
3448 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3449 return ((PARAFORMAT2 *)lParam)->dwMask;
3450 case EM_GETFIRSTVISIBLELINE:
3452 ME_DisplayItem *p = editor->pBuffer->pFirst;
3453 int y = editor->vert_si.nPos;
3454 int ypara = 0;
3455 int count = 0;
3456 int ystart, yend;
3457 while(p) {
3458 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3459 if (p->type == diTextEnd)
3460 break;
3461 if (p->type == diParagraph) {
3462 ypara = p->member.para.pt.y;
3463 continue;
3465 ystart = ypara + p->member.row.pt.y;
3466 yend = ystart + p->member.row.nHeight;
3467 if (y < yend) {
3468 break;
3470 count++;
3472 return count;
3474 case EM_HIDESELECTION:
3476 editor->bHideSelection = (wParam != 0);
3477 ME_InvalidateSelection(editor);
3478 return 0;
3480 case EM_LINESCROLL:
3482 if (!(editor->styleFlags & ES_MULTILINE))
3483 return FALSE;
3484 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3485 return TRUE;
3487 case WM_CLEAR:
3489 int from, to;
3490 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3491 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3492 ME_CommitUndo(editor);
3493 ME_UpdateRepaint(editor, TRUE);
3494 return 0;
3496 case EM_REPLACESEL:
3498 int from, to, nStartCursor;
3499 ME_Style *style;
3500 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3501 size_t len = wszText ? lstrlenW(wszText) : 0;
3502 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3504 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3505 style = ME_GetSelectionInsertStyle(editor);
3506 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3507 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3508 ME_ReleaseStyle(style);
3509 /* drop temporary style if line end */
3511 * FIXME question: does abc\n mean: put abc,
3512 * clear temp style, put \n? (would require a change)
3514 if (len>0 && wszText[len-1] == '\n')
3515 ME_ClearTempStyle(editor);
3516 ME_EndToUnicode(unicode, wszText);
3517 ME_CommitUndo(editor);
3518 ME_UpdateSelectionLinkAttribute(editor);
3519 if (!wParam)
3520 ME_EmptyUndoStack(editor);
3521 ME_UpdateRepaint(editor, FALSE);
3522 return len;
3524 case EM_SCROLLCARET:
3525 ME_EnsureVisible(editor, &editor->pCursors[0]);
3526 return 0;
3527 case WM_SETFONT:
3529 LOGFONTW lf;
3530 CHARFORMAT2W fmt;
3531 HDC hDC;
3532 BOOL bRepaint = LOWORD(lParam);
3534 if (!wParam)
3535 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3536 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3537 hDC = ITextHost_TxGetDC(editor->texthost);
3538 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3539 ITextHost_TxReleaseDC(editor->texthost, hDC);
3540 if (editor->mode & TM_RICHTEXT) {
3541 ME_Cursor start;
3542 ME_SetCursorToStart(editor, &start);
3543 ME_SetCharFormat(editor, &start, NULL, &fmt);
3545 ME_SetDefaultCharFormat(editor, &fmt);
3547 ME_CommitUndo(editor);
3548 ME_MarkAllForWrapping(editor);
3549 ME_WrapMarkedParagraphs(editor);
3550 ME_UpdateScrollBar(editor);
3551 if (bRepaint)
3552 ME_Repaint(editor);
3553 return 0;
3555 case WM_SETTEXT:
3557 ME_Cursor cursor;
3558 ME_SetCursorToStart(editor, &cursor);
3559 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3560 if (lParam)
3562 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3563 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3564 !strncmp((char *)lParam, "{\\urtf", 6))
3566 /* Undocumented: WM_SETTEXT supports RTF text */
3567 ME_StreamInRTFString(editor, 0, (char *)lParam);
3569 else
3571 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3572 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3573 if (lstrlenW(wszText) > 0)
3575 int len = -1;
3577 /* uses default style! */
3578 if (!(editor->styleFlags & ES_MULTILINE))
3580 WCHAR * p;
3582 p = wszText;
3583 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3584 len = p - wszText;
3586 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3588 ME_EndToUnicode(unicode, wszText);
3591 else
3592 TRACE("WM_SETTEXT - NULL\n");
3593 ME_SetCursorToStart(editor, &cursor);
3594 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3595 ME_SetSelection(editor, 0, 0);
3596 editor->nModifyStep = 0;
3597 ME_CommitUndo(editor);
3598 ME_EmptyUndoStack(editor);
3599 ME_UpdateRepaint(editor, FALSE);
3600 return 1;
3602 case EM_CANPASTE:
3604 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3605 if (IsClipboardFormatAvailable(nRTFFormat))
3606 return TRUE;
3607 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3608 return TRUE;
3609 return FALSE;
3611 case WM_PASTE:
3612 case WM_MBUTTONDOWN:
3613 ME_Paste(editor);
3614 return 0;
3615 case WM_CUT:
3616 case WM_COPY:
3618 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3619 int nChars = nTo - nFrom;
3620 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3622 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3624 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3625 ME_CommitUndo(editor);
3626 ME_UpdateRepaint(editor, TRUE);
3628 return 0;
3630 case WM_GETTEXTLENGTH:
3632 GETTEXTLENGTHEX how;
3634 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3635 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3636 how.codepage = unicode ? 1200 : CP_ACP;
3637 return ME_GetTextLengthEx(editor, &how);
3639 case EM_GETTEXTLENGTHEX:
3640 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3641 case WM_GETTEXT:
3643 GETTEXTEX ex;
3644 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3645 ex.flags = GT_USECRLF;
3646 ex.codepage = unicode ? 1200 : CP_ACP;
3647 ex.lpDefaultChar = NULL;
3648 ex.lpUsedDefChar = NULL;
3649 return ME_GetTextEx(editor, &ex, lParam);
3651 case EM_GETTEXTEX:
3652 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3653 case EM_GETSELTEXT:
3655 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3656 ME_Cursor *from = &editor->pCursors[nStartCur];
3657 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3658 nTo - nFrom, unicode);
3660 case EM_GETSCROLLPOS:
3662 POINT *point = (POINT *)lParam;
3663 point->x = editor->horz_si.nPos;
3664 point->y = editor->vert_si.nPos;
3665 /* 16-bit scaled value is returned as stored in scrollinfo */
3666 if (editor->horz_si.nMax > 0xffff)
3667 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3668 if (editor->vert_si.nMax > 0xffff)
3669 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3670 return 1;
3672 case EM_GETTEXTRANGE:
3674 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3675 ME_Cursor start;
3676 int nStart = rng->chrg.cpMin;
3677 int nEnd = rng->chrg.cpMax;
3678 int textlength = ME_GetTextLength(editor);
3680 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3681 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3682 if (nStart < 0) return 0;
3683 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3684 nEnd = textlength;
3685 if (nStart >= nEnd) return 0;
3687 ME_CursorFromCharOfs(editor, nStart, &start);
3688 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3690 case EM_GETLINE:
3692 ME_DisplayItem *run;
3693 const unsigned int nMaxChars = *(WORD *) lParam;
3694 unsigned int nCharsLeft = nMaxChars;
3695 char *dest = (char *) lParam;
3696 BOOL wroteNull = FALSE;
3698 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3699 unicode ? "Unicode" : "Ansi");
3701 run = ME_FindRowWithNumber(editor, wParam);
3702 if (run == NULL)
3703 return 0;
3705 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3706 && run->type == diRun)
3708 WCHAR *str = get_text( &run->member.run, 0 );
3709 unsigned int nCopy;
3711 nCopy = min(nCharsLeft, run->member.run.len);
3713 if (unicode)
3714 memcpy(dest, str, nCopy * sizeof(WCHAR));
3715 else
3716 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3717 nCharsLeft, NULL, NULL);
3718 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3719 nCharsLeft -= nCopy;
3722 /* append line termination, space allowing */
3723 if (nCharsLeft > 0)
3725 if (unicode)
3726 *((WCHAR *)dest) = '\0';
3727 else
3728 *dest = '\0';
3729 nCharsLeft--;
3730 wroteNull = TRUE;
3733 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3734 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3736 case EM_GETLINECOUNT:
3738 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3739 int nRows = 0;
3741 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3743 while (item != editor->pBuffer->pLast)
3745 assert(item->type == diParagraph);
3746 prev_para = ME_FindItemBack(item, diRun);
3747 if (prev_para) {
3748 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3750 nRows += item->member.para.nRows;
3751 item = item->member.para.next_para;
3753 last_para = ME_FindItemBack(item, diRun);
3754 assert(last_para);
3755 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3756 if (editor->bEmulateVersion10 && prev_para &&
3757 last_para->member.run.nCharOfs == 0 &&
3758 prev_para->member.run.len == 1 &&
3759 *get_text( &prev_para->member.run, 0 ) == '\r')
3761 /* In 1.0 emulation, the last solitary \r at the very end of the text
3762 (if one exists) is NOT a line break.
3763 FIXME: this is an ugly hack. This should have a more regular model. */
3764 nRows--;
3767 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3768 return max(1, nRows);
3770 case EM_LINEFROMCHAR:
3772 if (wParam == -1)
3773 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3774 else
3775 return ME_RowNumberFromCharOfs(editor, wParam);
3777 case EM_EXLINEFROMCHAR:
3779 if (lParam == -1)
3780 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3781 else
3782 return ME_RowNumberFromCharOfs(editor, lParam);
3784 case EM_LINEINDEX:
3786 ME_DisplayItem *item, *para;
3787 int nCharOfs;
3789 if (wParam == -1)
3790 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3791 else
3792 item = ME_FindRowWithNumber(editor, wParam);
3793 if (!item)
3794 return -1;
3795 para = ME_GetParagraph(item);
3796 item = ME_FindItemFwd(item, diRun);
3797 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3798 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3799 return nCharOfs;
3801 case EM_LINELENGTH:
3803 ME_DisplayItem *item, *item_end;
3804 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3805 ME_DisplayItem *para, *run;
3807 if (wParam > ME_GetTextLength(editor))
3808 return 0;
3809 if (wParam == -1)
3811 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3812 return 0;
3814 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3815 item = ME_RowStart(run);
3816 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3817 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3818 if (item_end->type == diStartRow) {
3819 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3820 } else {
3821 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3822 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3823 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3825 nChars = nNextLineOfs - nThisLineOfs;
3826 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3827 return nChars;
3829 case EM_EXLIMITTEXT:
3831 if ((int)lParam < 0)
3832 return 0;
3833 if (lParam == 0)
3834 editor->nTextLimit = 65536;
3835 else
3836 editor->nTextLimit = (int) lParam;
3837 return 0;
3839 case EM_LIMITTEXT:
3841 if (wParam == 0)
3842 editor->nTextLimit = 65536;
3843 else
3844 editor->nTextLimit = (int) wParam;
3845 return 0;
3847 case EM_GETLIMITTEXT:
3849 return editor->nTextLimit;
3851 case EM_FINDTEXT:
3853 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3854 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3855 WCHAR *tmp;
3856 LRESULT r;
3858 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3859 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3860 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3861 FREE_OBJ( tmp );
3862 return r;
3864 case EM_FINDTEXTEX:
3866 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3867 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3868 WCHAR *tmp;
3869 LRESULT r;
3871 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3872 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3873 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3874 FREE_OBJ( tmp );
3875 return r;
3877 case EM_FINDTEXTW:
3879 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3880 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3882 case EM_FINDTEXTEXW:
3884 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3885 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3887 case EM_GETZOOM:
3888 if (!wParam || !lParam)
3889 return FALSE;
3890 *(int *)wParam = editor->nZoomNumerator;
3891 *(int *)lParam = editor->nZoomDenominator;
3892 return TRUE;
3893 case EM_SETZOOM:
3894 return ME_SetZoom(editor, wParam, lParam);
3895 case EM_CHARFROMPOS:
3897 ME_Cursor cursor;
3898 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3899 &cursor, NULL))
3900 return ME_GetCursorOfs(&cursor);
3901 else
3902 return -1;
3904 case EM_POSFROMCHAR:
3906 ME_DisplayItem *pPara, *pRun;
3907 int nCharOfs, nOffset, nLength;
3908 POINTL pt = {0,0};
3910 nCharOfs = wParam;
3911 /* detect which API version we're dealing with */
3912 if (wParam >= 0x40000)
3913 nCharOfs = lParam;
3914 nLength = ME_GetTextLength(editor);
3915 nCharOfs = min(nCharOfs, nLength);
3916 nCharOfs = max(nCharOfs, 0);
3918 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3919 assert(pRun->type == diRun);
3920 pt.y = pRun->member.run.pt.y;
3921 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3922 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3923 pt.x += editor->rcFormat.left;
3925 pt.x -= editor->horz_si.nPos;
3926 pt.y -= editor->vert_si.nPos;
3928 if (wParam >= 0x40000) {
3929 *(POINTL *)wParam = pt;
3931 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3933 case WM_CREATE:
3935 INT max;
3937 ME_SetDefaultFormatRect(editor);
3939 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3940 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3941 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3943 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3944 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3946 if (editor->styleFlags & ES_DISABLENOSCROLL)
3948 if (editor->styleFlags & WS_VSCROLL)
3950 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3951 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3953 if (editor->styleFlags & WS_HSCROLL)
3955 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3956 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3960 ME_CommitUndo(editor);
3961 ME_WrapMarkedParagraphs(editor);
3962 ME_MoveCaret(editor);
3963 return 0;
3965 case WM_DESTROY:
3966 ME_DestroyEditor(editor);
3967 return 0;
3968 case WM_SETCURSOR:
3970 return ME_SetCursor(editor);
3972 case WM_LBUTTONDBLCLK:
3973 case WM_LBUTTONDOWN:
3975 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3976 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3977 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3978 return 0;
3979 ITextHost_TxSetFocus(editor->texthost);
3980 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3981 ME_CalculateClickCount(editor, msg, wParam, lParam));
3982 ITextHost_TxSetCapture(editor->texthost, TRUE);
3983 editor->bMouseCaptured = TRUE;
3984 ME_LinkNotify(editor,msg,wParam,lParam);
3985 if (!ME_SetCursor(editor)) goto do_default;
3986 break;
3988 case WM_MOUSEMOVE:
3989 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3990 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3991 return 0;
3992 if (editor->bMouseCaptured)
3993 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3994 ME_LinkNotify(editor,msg,wParam,lParam);
3995 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3996 if (editor->bMouseCaptured)
3997 ME_SetCursor(editor);
3998 break;
3999 case WM_LBUTTONUP:
4000 if (editor->bMouseCaptured) {
4001 ITextHost_TxSetCapture(editor->texthost, FALSE);
4002 editor->bMouseCaptured = FALSE;
4004 if (editor->nSelectionType == stDocument)
4005 editor->nSelectionType = stPosition;
4006 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4007 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4008 return 0;
4009 else
4011 ME_SetCursor(editor);
4012 ME_LinkNotify(editor,msg,wParam,lParam);
4014 break;
4015 case WM_RBUTTONUP:
4016 case WM_RBUTTONDOWN:
4017 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4018 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4019 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4020 return 0;
4021 goto do_default;
4022 case WM_CONTEXTMENU:
4023 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4024 goto do_default;
4025 break;
4026 case WM_SETFOCUS:
4027 editor->bHaveFocus = TRUE;
4028 ME_ShowCaret(editor);
4029 ME_SendOldNotify(editor, EN_SETFOCUS);
4030 return 0;
4031 case WM_KILLFOCUS:
4032 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4033 editor->bHaveFocus = FALSE;
4034 ME_HideCaret(editor);
4035 ME_SendOldNotify(editor, EN_KILLFOCUS);
4036 return 0;
4037 case WM_COMMAND:
4038 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4039 return 0;
4040 case WM_KEYUP:
4041 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4042 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4043 return 0;
4044 goto do_default;
4045 case WM_KEYDOWN:
4046 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4047 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4048 return 0;
4049 if (ME_KeyDown(editor, LOWORD(wParam)))
4050 return 0;
4051 goto do_default;
4052 case WM_CHAR:
4053 return ME_Char(editor, wParam, lParam, unicode);
4054 case WM_UNICHAR:
4055 if (unicode)
4057 if(wParam == UNICODE_NOCHAR) return TRUE;
4058 if(wParam <= 0x000fffff)
4060 if(wParam > 0xffff) /* convert to surrogates */
4062 wParam -= 0x10000;
4063 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4064 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4065 } else {
4066 ME_Char(editor, wParam, 0, TRUE);
4069 return 0;
4071 break;
4072 case EM_STOPGROUPTYPING:
4073 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4074 return 0;
4075 case WM_HSCROLL:
4077 const int scrollUnit = 7;
4079 switch(LOWORD(wParam))
4081 case SB_LEFT:
4082 ME_ScrollAbs(editor, 0, 0);
4083 break;
4084 case SB_RIGHT:
4085 ME_ScrollAbs(editor,
4086 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4087 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4088 break;
4089 case SB_LINELEFT:
4090 ME_ScrollLeft(editor, scrollUnit);
4091 break;
4092 case SB_LINERIGHT:
4093 ME_ScrollRight(editor, scrollUnit);
4094 break;
4095 case SB_PAGELEFT:
4096 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4097 break;
4098 case SB_PAGERIGHT:
4099 ME_ScrollRight(editor, editor->sizeWindow.cx);
4100 break;
4101 case SB_THUMBTRACK:
4102 case SB_THUMBPOSITION:
4104 int pos = HIWORD(wParam);
4105 if (editor->horz_si.nMax > 0xffff)
4106 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4107 ME_HScrollAbs(editor, pos);
4108 break;
4111 break;
4113 case EM_SCROLL: /* fall through */
4114 case WM_VSCROLL:
4116 int origNPos;
4117 int lineHeight;
4119 origNPos = editor->vert_si.nPos;
4120 lineHeight = 24;
4122 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4123 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4124 if (lineHeight <= 0) lineHeight = 24;
4126 switch(LOWORD(wParam))
4128 case SB_TOP:
4129 ME_ScrollAbs(editor, 0, 0);
4130 break;
4131 case SB_BOTTOM:
4132 ME_ScrollAbs(editor,
4133 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4134 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4135 break;
4136 case SB_LINEUP:
4137 ME_ScrollUp(editor,lineHeight);
4138 break;
4139 case SB_LINEDOWN:
4140 ME_ScrollDown(editor,lineHeight);
4141 break;
4142 case SB_PAGEUP:
4143 ME_ScrollUp(editor,editor->sizeWindow.cy);
4144 break;
4145 case SB_PAGEDOWN:
4146 ME_ScrollDown(editor,editor->sizeWindow.cy);
4147 break;
4148 case SB_THUMBTRACK:
4149 case SB_THUMBPOSITION:
4151 int pos = HIWORD(wParam);
4152 if (editor->vert_si.nMax > 0xffff)
4153 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4154 ME_VScrollAbs(editor, pos);
4155 break;
4158 if (msg == EM_SCROLL)
4159 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4160 break;
4162 case WM_MOUSEWHEEL:
4164 int gcWheelDelta;
4165 UINT pulScrollLines;
4166 BOOL ctrl_is_down;
4168 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4169 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4170 return 0;
4172 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4174 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4176 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4178 if (ctrl_is_down) {
4179 int numerator;
4180 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4182 numerator = 100;
4183 } else {
4184 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4186 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4187 if (numerator >= 10 && numerator <= 500)
4188 ME_SetZoom(editor, numerator, 100);
4189 } else {
4190 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4191 /* FIXME follow the original */
4192 if (pulScrollLines)
4193 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4196 break;
4198 case EM_GETRECT:
4200 *((RECT *)lParam) = editor->rcFormat;
4201 if (editor->bDefaultFormatRect)
4202 ((RECT *)lParam)->left -= editor->selofs;
4203 return 0;
4205 case EM_SETRECT:
4206 case EM_SETRECTNP:
4208 if (lParam)
4210 int border = 0;
4211 RECT clientRect;
4212 RECT *rc = (RECT *)lParam;
4214 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4215 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4216 if (wParam == 0)
4218 editor->rcFormat.top = max(0, rc->top - border);
4219 editor->rcFormat.left = max(0, rc->left - border);
4220 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4221 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4222 } else if (wParam == 1) {
4223 /* MSDN incorrectly says a wParam value of 1 causes the
4224 * lParam rect to be used as a relative offset,
4225 * however, the tests show it just prevents min/max bound
4226 * checking. */
4227 editor->rcFormat.top = rc->top - border;
4228 editor->rcFormat.left = rc->left - border;
4229 editor->rcFormat.bottom = rc->bottom;
4230 editor->rcFormat.right = rc->right + border;
4231 } else {
4232 return 0;
4234 editor->bDefaultFormatRect = FALSE;
4236 else
4238 ME_SetDefaultFormatRect(editor);
4239 editor->bDefaultFormatRect = TRUE;
4241 ME_MarkAllForWrapping(editor);
4242 ME_WrapMarkedParagraphs(editor);
4243 ME_UpdateScrollBar(editor);
4244 if (msg != EM_SETRECTNP)
4245 ME_Repaint(editor);
4246 return 0;
4248 case EM_REQUESTRESIZE:
4249 ME_SendRequestResize(editor, TRUE);
4250 return 0;
4251 case WM_SETREDRAW:
4252 goto do_default;
4253 case WM_SIZE:
4255 RECT clientRect;
4257 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4258 if (editor->bDefaultFormatRect) {
4259 ME_SetDefaultFormatRect(editor);
4260 } else {
4261 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4262 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4264 editor->prevClientRect = clientRect;
4265 ME_RewrapRepaint(editor);
4266 goto do_default;
4268 /* IME messages to make richedit controls IME aware */
4269 case WM_IME_SETCONTEXT:
4270 case WM_IME_CONTROL:
4271 case WM_IME_SELECT:
4272 case WM_IME_COMPOSITIONFULL:
4273 return 0;
4274 case WM_IME_STARTCOMPOSITION:
4276 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4277 ME_DeleteSelection(editor);
4278 ME_CommitUndo(editor);
4279 ME_UpdateRepaint(editor, FALSE);
4280 return 0;
4282 case WM_IME_COMPOSITION:
4284 HIMC hIMC;
4286 ME_Style *style = ME_GetInsertStyle(editor, 0);
4287 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4288 ME_DeleteSelection(editor);
4289 ME_SaveTempStyle(editor);
4290 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4292 LPWSTR lpCompStr = NULL;
4293 DWORD dwBufLen;
4294 DWORD dwIndex = lParam & GCS_RESULTSTR;
4295 if (!dwIndex)
4296 dwIndex = GCS_COMPSTR;
4298 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4299 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4300 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4301 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4302 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4303 HeapFree(GetProcessHeap(), 0, lpCompStr);
4305 if (dwIndex == GCS_COMPSTR)
4306 ME_SetSelection(editor,editor->imeStartIndex,
4307 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4309 ME_ReleaseStyle(style);
4310 ME_CommitUndo(editor);
4311 ME_UpdateRepaint(editor, FALSE);
4312 return 0;
4314 case WM_IME_ENDCOMPOSITION:
4316 ME_DeleteSelection(editor);
4317 editor->imeStartIndex=-1;
4318 return 0;
4320 case EM_GETOLEINTERFACE:
4322 LPVOID *ppvObj = (LPVOID*) lParam;
4323 return CreateIRichEditOle(editor, ppvObj);
4325 case EM_GETPASSWORDCHAR:
4327 return editor->cPasswordMask;
4329 case EM_SETOLECALLBACK:
4330 if(editor->lpOleCallback)
4331 IRichEditOleCallback_Release(editor->lpOleCallback);
4332 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4333 if(editor->lpOleCallback)
4334 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4335 return TRUE;
4336 case EM_GETWORDBREAKPROC:
4337 return (LRESULT)editor->pfnWordBreak;
4338 case EM_SETWORDBREAKPROC:
4340 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4342 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4343 return (LRESULT)pfnOld;
4345 case EM_GETTEXTMODE:
4346 return editor->mode;
4347 case EM_SETTEXTMODE:
4349 int mask = 0;
4350 int changes = 0;
4352 if (ME_GetTextLength(editor) ||
4353 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4354 return E_UNEXPECTED;
4356 /* Check for mutually exclusive flags in adjacent bits of wParam */
4357 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4358 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4359 return E_INVALIDARG;
4361 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4363 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4364 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4365 if (wParam & TM_PLAINTEXT) {
4366 /* Clear selection since it should be possible to select the
4367 * end of text run for rich text */
4368 ME_InvalidateSelection(editor);
4369 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4370 editor->pCursors[1] = editor->pCursors[0];
4371 /* plain text can only have the default style. */
4372 ME_ClearTempStyle(editor);
4373 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4374 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4375 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4378 /* FIXME: Currently no support for undo level and code page options */
4379 editor->mode = (editor->mode & ~mask) | changes;
4380 return 0;
4382 case EM_SETPASSWORDCHAR:
4384 editor->cPasswordMask = wParam;
4385 ME_RewrapRepaint(editor);
4386 return 0;
4388 case EM_SETTARGETDEVICE:
4389 if (wParam == 0)
4391 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4392 if (editor->nAvailWidth || editor->bWordWrap != new)
4394 editor->bWordWrap = new;
4395 editor->nAvailWidth = 0; /* wrap to client area */
4396 ME_RewrapRepaint(editor);
4398 } else {
4399 int width = max(0, lParam);
4400 if ((editor->styleFlags & ES_MULTILINE) &&
4401 (!editor->bWordWrap || editor->nAvailWidth != width))
4403 editor->nAvailWidth = width;
4404 editor->bWordWrap = TRUE;
4405 ME_RewrapRepaint(editor);
4407 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4409 return TRUE;
4410 default:
4411 do_default:
4412 *phresult = S_FALSE;
4413 break;
4415 return 0L;
4418 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4419 LPARAM lParam, BOOL unicode)
4421 ME_TextEditor *editor;
4422 HRESULT hresult;
4423 LRESULT lresult = 0;
4425 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4426 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4428 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4429 if (!editor)
4431 if (msg == WM_NCCREATE)
4433 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4434 ITextHost *texthost;
4436 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4437 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4438 return texthost != NULL;
4440 else
4442 return DefWindowProcW(hWnd, msg, wParam, lParam);
4446 switch (msg)
4448 case WM_PAINT:
4450 HDC hDC;
4451 RECT rc;
4452 PAINTSTRUCT ps;
4454 hDC = BeginPaint(editor->hWnd, &ps);
4455 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4456 ME_SendOldNotify(editor, EN_UPDATE);
4457 /* Erase area outside of the formatting rectangle */
4458 if (ps.rcPaint.top < editor->rcFormat.top)
4460 rc = ps.rcPaint;
4461 rc.bottom = editor->rcFormat.top;
4462 FillRect(hDC, &rc, editor->hbrBackground);
4463 ps.rcPaint.top = editor->rcFormat.top;
4465 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4466 rc = ps.rcPaint;
4467 rc.top = editor->rcFormat.bottom;
4468 FillRect(hDC, &rc, editor->hbrBackground);
4469 ps.rcPaint.bottom = editor->rcFormat.bottom;
4471 if (ps.rcPaint.left < editor->rcFormat.left) {
4472 rc = ps.rcPaint;
4473 rc.right = editor->rcFormat.left;
4474 FillRect(hDC, &rc, editor->hbrBackground);
4475 ps.rcPaint.left = editor->rcFormat.left;
4477 if (ps.rcPaint.right > editor->rcFormat.right) {
4478 rc = ps.rcPaint;
4479 rc.left = editor->rcFormat.right;
4480 FillRect(hDC, &rc, editor->hbrBackground);
4481 ps.rcPaint.right = editor->rcFormat.right;
4484 ME_PaintContent(editor, hDC, &ps.rcPaint);
4485 EndPaint(editor->hWnd, &ps);
4486 return 0;
4488 case WM_ERASEBKGND:
4490 HDC hDC = (HDC)wParam;
4491 RECT rc;
4493 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4494 FillRect(hDC, &rc, editor->hbrBackground);
4495 return 1;
4497 case EM_SETOPTIONS:
4499 DWORD dwStyle;
4500 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4501 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4502 ECO_SELECTIONBAR;
4503 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4504 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4505 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4506 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4507 return lresult;
4509 case EM_SETREADONLY:
4511 DWORD dwStyle;
4512 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4513 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4514 dwStyle &= ~ES_READONLY;
4515 if (wParam)
4516 dwStyle |= ES_READONLY;
4517 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4518 return lresult;
4520 default:
4521 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4524 if (hresult == S_FALSE)
4525 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4527 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4528 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4530 return lresult;
4533 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4535 BOOL unicode = TRUE;
4537 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4538 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4539 unicode = FALSE;
4541 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4544 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4546 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4549 /******************************************************************
4550 * RichEditANSIWndProc (RICHED20.10)
4552 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4554 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4557 /******************************************************************
4558 * RichEdit10ANSIWndProc (RICHED20.9)
4560 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4562 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4564 ITextHost *texthost;
4565 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4567 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4568 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4569 return texthost != NULL;
4571 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4574 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4576 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4579 /* Fill buffer with srcChars unicode characters from the start cursor.
4581 * buffer: destination buffer
4582 * buflen: length of buffer in characters excluding the NULL terminator.
4583 * start: start of editor text to copy into buffer.
4584 * srcChars: Number of characters to use from the editor text.
4585 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4587 * returns the number of characters written excluding the NULL terminator.
4589 * The written text is always NULL terminated.
4591 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4592 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4594 ME_DisplayItem *pRun, *pNextRun;
4595 const WCHAR *pStart = buffer;
4596 const WCHAR cr_lf[] = {'\r', '\n', 0};
4597 const WCHAR *str;
4598 int nLen;
4600 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4601 if (editor->bEmulateVersion10) bCRLF = 0;
4603 pRun = start->pRun;
4604 assert(pRun);
4605 pNextRun = ME_FindItemFwd(pRun, diRun);
4607 nLen = pRun->member.run.len - start->nOffset;
4608 str = get_text( &pRun->member.run, start->nOffset );
4610 /* No '\r' is appended to the last paragraph. */
4611 while (srcChars && buflen && pNextRun)
4613 int nFlags = pRun->member.run.nFlags;
4615 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4617 if (buflen == 1) break;
4618 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4619 * EM_GETTEXTEX, however, this is done for copying text which
4620 * also uses this function. */
4621 srcChars -= min(nLen, srcChars);
4622 nLen = 2;
4623 str = cr_lf;
4624 } else {
4625 nLen = min(nLen, srcChars);
4626 srcChars -= nLen;
4629 nLen = min(nLen, buflen);
4630 buflen -= nLen;
4632 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4634 buffer += nLen;
4636 pRun = pNextRun;
4637 pNextRun = ME_FindItemFwd(pRun, diRun);
4639 nLen = pRun->member.run.len;
4640 str = get_text( &pRun->member.run, 0 );
4642 *buffer = 0;
4643 return buffer - pStart;
4646 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4648 WNDCLASSW wcW;
4649 WNDCLASSA wcA;
4651 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4652 wcW.lpfnWndProc = RichEditWndProcW;
4653 wcW.cbClsExtra = 0;
4654 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4655 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4656 wcW.hIcon = NULL;
4657 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4658 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4659 wcW.lpszMenuName = NULL;
4661 if (is_version_nt())
4663 wcW.lpszClassName = RICHEDIT_CLASS20W;
4664 if (!RegisterClassW(&wcW)) return FALSE;
4665 wcW.lpszClassName = MSFTEDIT_CLASS;
4666 if (!RegisterClassW(&wcW)) return FALSE;
4668 else
4670 /* WNDCLASSA/W have the same layout */
4671 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4672 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4673 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4674 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4677 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4678 wcA.lpfnWndProc = RichEditWndProcA;
4679 wcA.cbClsExtra = 0;
4680 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4681 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4682 wcA.hIcon = NULL;
4683 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4684 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4685 wcA.lpszMenuName = NULL;
4686 wcA.lpszClassName = RICHEDIT_CLASS20A;
4687 if (!RegisterClassA(&wcA)) return FALSE;
4688 wcA.lpszClassName = "RichEdit50A";
4689 if (!RegisterClassA(&wcA)) return FALSE;
4691 return TRUE;
4694 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4695 /* FIXME: Not implemented */
4696 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4697 hWnd, msg, get_msg_name(msg), wParam, lParam);
4698 return DefWindowProcW(hWnd, msg, wParam, lParam);
4701 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4702 /* FIXME: Not implemented */
4703 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4704 hWnd, msg, get_msg_name(msg), wParam, lParam);
4705 return DefWindowProcW(hWnd, msg, wParam, lParam);
4708 /******************************************************************
4709 * REExtendedRegisterClass (RICHED20.8)
4711 * FIXME undocumented
4712 * Need to check for errors and implement controls and callbacks
4714 LRESULT WINAPI REExtendedRegisterClass(void)
4716 WNDCLASSW wcW;
4717 UINT result;
4719 FIXME("semi stub\n");
4721 wcW.cbClsExtra = 0;
4722 wcW.cbWndExtra = 4;
4723 wcW.hInstance = NULL;
4724 wcW.hIcon = NULL;
4725 wcW.hCursor = NULL;
4726 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4727 wcW.lpszMenuName = NULL;
4729 if (!ME_ListBoxRegistered)
4731 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4732 wcW.lpfnWndProc = REListWndProc;
4733 wcW.lpszClassName = REListBox20W;
4734 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4737 if (!ME_ComboBoxRegistered)
4739 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4740 wcW.lpfnWndProc = REComboWndProc;
4741 wcW.lpszClassName = REComboBox20W;
4742 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4745 result = 0;
4746 if (ME_ListBoxRegistered)
4747 result += 1;
4748 if (ME_ComboBoxRegistered)
4749 result += 2;
4751 return result;
4754 static BOOL isurlspecial(WCHAR c)
4756 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4757 return strchrW( special_chars, c ) != NULL;
4761 * This proc takes a selection, and scans it forward in order to select the span
4762 * of a possible URL candidate. A possible URL candidate must start with isalnum
4763 * or one of the following special characters: *|/\+%#@ and must consist entirely
4764 * of the characters allowed to start the URL, plus : (colon) which may occur
4765 * at most once, and not at either end.
4767 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4768 const ME_Cursor *start,
4769 int nChars,
4770 ME_Cursor *candidate_min,
4771 ME_Cursor *candidate_max)
4773 ME_Cursor cursor = *start;
4774 BOOL foundColon = FALSE;
4775 BOOL candidateStarted = FALSE;
4776 WCHAR lastAcceptedChar = '\0';
4778 while (nChars > 0)
4780 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4781 WCHAR *str = strStart + cursor.nOffset;
4782 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4783 nChars -= nLen;
4785 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4787 /* Find start of candidate */
4788 if (!candidateStarted)
4790 while (nLen)
4792 nLen--;
4793 if (isalnumW(*str) || isurlspecial(*str))
4795 cursor.nOffset = str - strStart;
4796 *candidate_min = cursor;
4797 candidateStarted = TRUE;
4798 lastAcceptedChar = *str++;
4799 break;
4801 str++;
4805 /* Find end of candidate */
4806 if (candidateStarted) {
4807 while (nLen)
4809 nLen--;
4810 if (*str == ':' && !foundColon) {
4811 foundColon = TRUE;
4812 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4813 cursor.nOffset = str - strStart;
4814 if (lastAcceptedChar == ':')
4815 ME_MoveCursorChars(editor, &cursor, -1);
4816 *candidate_max = cursor;
4817 return TRUE;
4819 lastAcceptedChar = *str++;
4822 } else {
4823 /* End of paragraph: skip it if before candidate span, or terminates
4824 current active span */
4825 if (candidateStarted) {
4826 if (lastAcceptedChar == ':')
4827 ME_MoveCursorChars(editor, &cursor, -1);
4828 *candidate_max = cursor;
4829 return TRUE;
4833 /* Reaching this point means no span was found, so get next span */
4834 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4835 if (candidateStarted) {
4836 /* There are no further runs, so take end of text as end of candidate */
4837 cursor.nOffset = str - strStart;
4838 if (lastAcceptedChar == ':')
4839 ME_MoveCursorChars(editor, &cursor, -1);
4840 *candidate_max = cursor;
4841 return TRUE;
4843 *candidate_max = *candidate_min = cursor;
4844 return FALSE;
4846 cursor.nOffset = 0;
4849 if (candidateStarted) {
4850 /* There are no further runs, so take end of text as end of candidate */
4851 if (lastAcceptedChar == ':')
4852 ME_MoveCursorChars(editor, &cursor, -1);
4853 *candidate_max = cursor;
4854 return TRUE;
4856 *candidate_max = *candidate_min = cursor;
4857 return FALSE;
4861 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4863 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4865 #define MAX_PREFIX_LEN 9
4866 struct prefix_s {
4867 const WCHAR text[MAX_PREFIX_LEN];
4868 int length;
4869 }prefixes[] = {
4870 {{'p','r','o','s','p','e','r','o',':'}, 9},
4871 {{'t','e','l','n','e','t',':'}, 7},
4872 {{'g','o','p','h','e','r',':'}, 7},
4873 {{'m','a','i','l','t','o',':'}, 7},
4874 {{'h','t','t','p','s',':'}, 6},
4875 {{'f','i','l','e',':'}, 5},
4876 {{'n','e','w','s',':'}, 5},
4877 {{'w','a','i','s',':'}, 5},
4878 {{'n','n','t','p',':'}, 5},
4879 {{'h','t','t','p',':'}, 5},
4880 {{'w','w','w','.'}, 4},
4881 {{'f','t','p',':'}, 4},
4883 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4884 unsigned int i;
4886 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4887 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4889 if (nChars < prefixes[i].length) continue;
4890 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4891 return TRUE;
4893 return FALSE;
4894 #undef MAX_PREFIX_LEN
4898 * This proc walks through the indicated selection and evaluates whether each
4899 * section identified by ME_FindNextURLCandidate and in-between sections have
4900 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4901 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4903 * Since this function can cause runs to be split, do not depend on the value
4904 * of the start cursor at the end of the function.
4906 * nChars may be set to INT_MAX to update to the end of the text.
4908 * Returns TRUE if at least one section was modified.
4910 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4912 BOOL modified = FALSE;
4913 ME_Cursor startCur = *start;
4915 if (!editor->AutoURLDetect_bEnable) return FALSE;
4919 CHARFORMAT2W link;
4920 ME_Cursor candidateStart, candidateEnd;
4922 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4923 &candidateStart, &candidateEnd))
4925 /* Section before candidate is not an URL */
4926 int cMin = ME_GetCursorOfs(&candidateStart);
4927 int cMax = ME_GetCursorOfs(&candidateEnd);
4929 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4930 candidateStart = candidateEnd;
4931 nChars -= cMax - ME_GetCursorOfs(&startCur);
4933 else
4935 /* No more candidates until end of selection */
4936 nChars = 0;
4939 if (startCur.pRun != candidateStart.pRun ||
4940 startCur.nOffset != candidateStart.nOffset)
4942 /* CFE_LINK effect should be consistently unset */
4943 link.cbSize = sizeof(link);
4944 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4945 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4947 /* CFE_LINK must be unset from this range */
4948 memset(&link, 0, sizeof(CHARFORMAT2W));
4949 link.cbSize = sizeof(link);
4950 link.dwMask = CFM_LINK;
4951 link.dwEffects = 0;
4952 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4953 /* Update candidateEnd since setting character formats may split
4954 * runs, which can cause a cursor to be at an invalid offset within
4955 * a split run. */
4956 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
4958 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
4959 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4961 modified = TRUE;
4964 if (candidateStart.pRun != candidateEnd.pRun ||
4965 candidateStart.nOffset != candidateEnd.nOffset)
4967 /* CFE_LINK effect should be consistently set */
4968 link.cbSize = sizeof(link);
4969 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4970 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4972 /* CFE_LINK must be set on this range */
4973 memset(&link, 0, sizeof(CHARFORMAT2W));
4974 link.cbSize = sizeof(link);
4975 link.dwMask = CFM_LINK;
4976 link.dwEffects = CFE_LINK;
4977 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4978 modified = TRUE;
4981 startCur = candidateEnd;
4982 } while (nChars > 0);
4983 return modified;