riched20: Use proper interface methods macros.
[wine/multimedia.git] / dlls / riched20 / editor.c
blob6e0fb3c1230ad931da1e30812cd74a666d0d7af1
1 /*
2 * RichEdit - functions dealing with editor object
4 * Copyright 2004 by Krzysztof Foltman
5 * Copyright 2005 by Cihan Altinay
6 * Copyright 2005 by Phil Krylov
7 * Copyright 2008 Eric Pouech
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 /*
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
29 + EM_CANPASTE
30 + EM_CANREDO 2.0
31 + EM_CANUNDO
32 + EM_CHARFROMPOS
33 - EM_DISPLAYBAND
34 + EM_EMPTYUNDOBUFFER
35 + EM_EXGETSEL
36 + EM_EXLIMITTEXT
37 + EM_EXLINEFROMCHAR
38 + EM_EXSETSEL
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41 - EM_FINDWORDBREAK
42 - EM_FMTLINES
43 - EM_FORMATRANGE
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
47 - EM_GETEDITSTYLE
48 + EM_GETEVENTMASK
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
53 - EM_GETIMESTATUS
54 - EM_GETLANGOPTIONS 2.0
55 + EM_GETLIMITTEXT
56 + EM_GETLINE
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
58 + EM_GETMODIFY
59 + EM_GETOLEINTERFACE
60 + EM_GETOPTIONS
61 + EM_GETPARAFORMAT
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
64 + EM_GETRECT
65 - EM_GETREDONAME 2.0
66 + EM_GETSEL
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0
69 ! - EM_GETTHUMB
70 + EM_GETTEXTEX 2.0
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72 + EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
75 - EM_GETUNDONAME
76 + EM_GETWORDBREAKPROC
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
79 + EM_GETZOOM 3.0
80 + EM_HIDESELECTION
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82 + EM_LINEFROMCHAR
83 + EM_LINEINDEX
84 + EM_LINELENGTH
85 + EM_LINESCROLL
86 - EM_PASTESPECIAL
87 + EM_POSFROMCHAR
88 + EM_REDO 2.0
89 + EM_REQUESTRESIZE
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
91 + EM_SCROLL
92 + EM_SCROLLCARET
93 - EM_SELECTIONTYPE
94 - EM_SETBIDIOPTIONS 3.0
95 + EM_SETBKGNDCOLOR
96 + EM_SETCHARFORMAT (partly done, no ANSI)
97 - EM_SETEDITSTYLE
98 + EM_SETEVENTMASK (few notifications supported)
99 - EM_SETFONTSIZE
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETIMESTATUS
103 - EM_SETLANGOPTIONS 2.0
104 - EM_SETLIMITTEXT
105 - EM_SETMARGINS
106 + EM_SETMODIFY (not sure if implementation is correct)
107 - EM_SETOLECALLBACK
108 + EM_SETOPTIONS (partially implemented)
109 - EM_SETPALETTE 2.0
110 + EM_SETPARAFORMAT
111 + EM_SETPASSWORDCHAR 2.0
112 - EM_SETPUNCTUATION 1.0asian
113 + EM_SETREADONLY no beep on modification attempt
114 + EM_SETRECT
115 + EM_SETRECTNP (EM_SETRECT without repainting)
116 + EM_SETSEL
117 + EM_SETSCROLLPOS 3.0
118 - EM_SETTABSTOPS 3.0
119 - EM_SETTARGETDEVICE (partial)
120 + EM_SETTEXTEX 3.0 (proper style?)
121 - EM_SETTEXTMODE 2.0
122 - EM_SETTYPOGRAPHYOPTIONS 3.0
123 + EM_SETUNDOLIMIT 2.0
124 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
125 - EM_SETWORDBREAKPROCEX
126 - EM_SETWORDWRAPMODE 1.0asian
127 + EM_SETZOOM 3.0
128 + EM_SHOWSCROLLBAR 2.0
129 + EM_STOPGROUPTYPING 2.0
130 + EM_STREAMIN
131 + EM_STREAMOUT
132 + EM_UNDO
133 + WM_CHAR
134 + WM_CLEAR
135 + WM_COPY
136 + WM_CUT
137 + WM_GETDLGCODE (the current implementation is incomplete)
138 + WM_GETTEXT (ANSI&Unicode)
139 + WM_GETTEXTLENGTH (ANSI version sucks)
140 + WM_HSCROLL
141 + WM_PASTE
142 + WM_SETFONT
143 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144 + WM_STYLECHANGING (seems to do nothing)
145 + WM_STYLECHANGED (seems to do nothing)
146 + WM_UNICHAR
147 + WM_VSCROLL
149 Notifications
151 * EN_CHANGE (sent from the wrong place)
152 - EN_CORRECTTEXT
153 - EN_DROPFILES
154 - EN_ERRSPACE
155 - EN_HSCROLL
156 - EN_IMECHANGE
157 + EN_KILLFOCUS
158 - EN_LINK
159 - EN_MAXTEXT
160 - EN_MSGFILTER
161 - EN_OLEOPFAILED
162 - EN_PROTECTED
163 + EN_REQUESTRESIZE
164 - EN_SAVECLIPBOARD
165 + EN_SELCHANGE
166 + EN_SETFOCUS
167 - EN_STOPNOUNDO
168 * EN_UPDATE (sent from the wrong place)
169 - EN_VSCROLL
171 Styles
173 - ES_AUTOHSCROLL
174 - ES_AUTOVSCROLL
175 - ES_CENTER
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
178 - ES_LEFT
179 - ES_MULTILINE (currently single line controls aren't supported)
180 - ES_NOIME
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182 - ES_RIGHT
183 - ES_SAVESEL
184 - ES_SELFIME
185 - ES_SUNKEN
186 - ES_VERTICAL
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188 - WS_SETFONT
189 + WS_HSCROLL
190 + WS_VSCROLL
194 * RICHED20 TODO (incomplete):
196 * - messages/styles/notifications listed above
197 * - add remaining CHARFORMAT/PARAFORMAT fields
198 * - right/center align should strip spaces from the beginning
199 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200 * - COM interface (looks like a major pain in the TODO list)
201 * - calculate heights of pictures (half-done)
202 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203 * - find/replace
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
206 * - IME
207 * - most notifications aren't sent at all (the most important ones are)
208 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211 * - full justification
212 * - hyphenation
213 * - tables
214 * - ListBox & ComboBox not implemented
216 * Bugs that are probably fixed, but not so easy to verify:
217 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220 * - caret shouldn't be displayed when selection isn't empty
221 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222 * - undo for setting default format (done, might be buggy)
223 * - styles might be not released properly (looks like they work like charm, but who knows?
227 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
236 #define STACK_SIZE_DEFAULT 100
237 #define STACK_SIZE_MAX 1000
239 #define TEXT_LIMIT_DEFAULT 32767
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
250 int me_debug = 0;
251 HANDLE me_heap = NULL;
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
256 static inline int is_version_nt(void)
258 return !(GetVersion() & 0x80000000);
261 static ME_TextBuffer *ME_MakeText(void) {
263 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
265 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
268 p1->prev = NULL;
269 p1->next = p2;
270 p2->prev = p1;
271 p2->next = NULL;
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
276 buf->pFirst = p1;
277 buf->pLast = p2;
278 buf->pCharStyle = NULL;
280 return buf;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
287 WCHAR *pText;
288 LRESULT total_bytes_read = 0;
290 TRACE("%08x %p\n", dwFormat, stream);
292 do {
293 LONG nWideChars = 0;
295 if (!stream->dwSize)
297 ME_StreamInFill(stream);
298 if (stream->editstream->dwError)
299 break;
300 if (!stream->dwSize)
301 break;
302 total_bytes_read += stream->dwSize;
305 if (!(dwFormat & SF_UNICODE))
307 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
308 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
309 pText = wszText;
311 else
313 nWideChars = stream->dwSize >> 1;
314 pText = (WCHAR *)stream->buffer;
317 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
318 if (stream->dwSize == 0)
319 break;
320 stream->dwSize = 0;
321 } while(1);
322 return total_bytes_read;
325 static void ME_ApplyBorderProperties(RTF_Info *info,
326 ME_BorderRect *borderRect,
327 RTFBorder *borderDef)
329 int i, colorNum;
330 ME_Border *pBorders[] = {&borderRect->top,
331 &borderRect->left,
332 &borderRect->bottom,
333 &borderRect->right};
334 for (i = 0; i < 4; i++)
336 RTFColor *colorDef = info->colorList;
337 pBorders[i]->width = borderDef[i].width;
338 colorNum = borderDef[i].color;
339 while (colorDef && colorDef->rtfCNum != colorNum)
340 colorDef = colorDef->rtfNextColor;
341 if (colorDef)
342 pBorders[i]->colorRef = RGB(
343 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
344 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
345 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
346 else
347 pBorders[i]->colorRef = RGB(0, 0, 0);
351 void ME_RTFCharAttrHook(RTF_Info *info)
353 CHARFORMAT2W fmt;
354 fmt.cbSize = sizeof(fmt);
355 fmt.dwMask = 0;
356 fmt.dwEffects = 0;
358 switch(info->rtfMinor)
360 case rtfPlain:
361 /* FIXME add more flags once they're implemented */
362 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
363 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
364 fmt.yHeight = 12*20; /* 12pt */
365 fmt.wWeight = FW_NORMAL;
366 fmt.bUnderlineType = CFU_UNDERLINENONE;
367 break;
368 case rtfBold:
369 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
370 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
371 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
372 break;
373 case rtfItalic:
374 fmt.dwMask = CFM_ITALIC;
375 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
376 break;
377 case rtfUnderline:
378 fmt.dwMask = CFM_UNDERLINETYPE;
379 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
380 break;
381 case rtfDotUnderline:
382 fmt.dwMask = CFM_UNDERLINETYPE;
383 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
384 break;
385 case rtfDbUnderline:
386 fmt.dwMask = CFM_UNDERLINETYPE;
387 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
388 break;
389 case rtfWordUnderline:
390 fmt.dwMask = CFM_UNDERLINETYPE;
391 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
392 break;
393 case rtfNoUnderline:
394 fmt.dwMask = CFM_UNDERLINETYPE;
395 fmt.bUnderlineType = CFU_UNDERLINENONE;
396 break;
397 case rtfStrikeThru:
398 fmt.dwMask = CFM_STRIKEOUT;
399 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
400 break;
401 case rtfSubScript:
402 case rtfSuperScript:
403 case rtfSubScrShrink:
404 case rtfSuperScrShrink:
405 case rtfNoSuperSub:
406 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
407 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
408 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
409 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
410 break;
411 case rtfInvisible:
412 fmt.dwMask = CFM_HIDDEN;
413 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
414 break;
415 case rtfBackColor:
416 fmt.dwMask = CFM_BACKCOLOR;
417 fmt.dwEffects = 0;
418 if (info->rtfParam == 0)
419 fmt.dwEffects = CFE_AUTOBACKCOLOR;
420 else if (info->rtfParam != rtfNoParam)
422 RTFColor *c = RTFGetColor(info, info->rtfParam);
423 if (c && c->rtfCBlue >= 0)
424 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
425 else
426 fmt.dwEffects = CFE_AUTOBACKCOLOR;
428 break;
429 case rtfForeColor:
430 fmt.dwMask = CFM_COLOR;
431 fmt.dwEffects = 0;
432 if (info->rtfParam == 0)
433 fmt.dwEffects = CFE_AUTOCOLOR;
434 else if (info->rtfParam != rtfNoParam)
436 RTFColor *c = RTFGetColor(info, info->rtfParam);
437 if (c && c->rtfCBlue >= 0)
438 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
439 else {
440 fmt.dwEffects = CFE_AUTOCOLOR;
443 break;
444 case rtfFontNum:
445 if (info->rtfParam != rtfNoParam)
447 RTFFont *f = RTFGetFont(info, info->rtfParam);
448 if (f)
450 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
451 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
452 fmt.bCharSet = f->rtfFCharSet;
453 fmt.dwMask = CFM_FACE | CFM_CHARSET;
454 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
457 break;
458 case rtfFontSize:
459 fmt.dwMask = CFM_SIZE;
460 if (info->rtfParam != rtfNoParam)
461 fmt.yHeight = info->rtfParam*10;
462 break;
464 if (fmt.dwMask) {
465 ME_Style *style2;
466 RTFFlushOutputBuffer(info);
467 /* FIXME too slow ? how come ? */
468 style2 = ME_ApplyStyle(info->style, &fmt);
469 ME_ReleaseStyle(info->style);
470 info->style = style2;
471 info->styleChanged = TRUE;
475 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
476 the same tags mean different things in different contexts */
477 void ME_RTFParAttrHook(RTF_Info *info)
479 PARAFORMAT2 fmt;
480 fmt.cbSize = sizeof(fmt);
481 fmt.dwMask = 0;
483 switch(info->rtfMinor)
485 case rtfParDef: /* restores default paragraph attributes */
486 if (!info->editor->bEmulateVersion10) /* v4.1 */
487 info->borderType = RTFBorderParaLeft;
488 else /* v1.0 - 3.0 */
489 info->borderType = RTFBorderParaTop;
490 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
491 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
492 PFM_STARTINDENT;
493 /* TODO: numbering, shading */
494 fmt.wAlignment = PFA_LEFT;
495 fmt.cTabCount = 0;
496 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
497 fmt.wBorderWidth = fmt.wBorders = 0;
498 fmt.wBorderSpace = 0;
499 fmt.bLineSpacingRule = 0;
500 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
501 fmt.dyLineSpacing = 0;
502 if (!info->editor->bEmulateVersion10) /* v4.1 */
504 if (info->tableDef && info->tableDef->tableRowStart &&
505 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
507 ME_Cursor cursor;
508 ME_DisplayItem *para;
509 /* We are just after a table row. */
510 RTFFlushOutputBuffer(info);
511 cursor = info->editor->pCursors[0];
512 para = cursor.pPara;
513 if (para == info->tableDef->tableRowStart->member.para.next_para
514 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
516 /* Since the table row end, no text has been inserted, and the \intbl
517 * control word has not be used. We can confirm that we are not in a
518 * table anymore.
520 info->tableDef->tableRowStart = NULL;
521 info->canInheritInTbl = FALSE;
524 } else { /* v1.0 - v3.0 */
525 fmt.dwMask |= PFM_TABLE;
526 fmt.wEffects &= ~PFE_TABLE;
528 break;
529 case rtfNestLevel:
530 if (!info->editor->bEmulateVersion10) /* v4.1 */
532 while (info->rtfParam > info->nestingLevel) {
533 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
534 ZeroMemory(tableDef, sizeof(RTFTable));
535 tableDef->parent = info->tableDef;
536 info->tableDef = tableDef;
538 RTFFlushOutputBuffer(info);
539 if (tableDef->tableRowStart &&
540 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
542 ME_DisplayItem *para = tableDef->tableRowStart;
543 para = para->member.para.next_para;
544 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
545 tableDef->tableRowStart = para;
546 } else {
547 ME_Cursor cursor;
548 WCHAR endl = '\r';
549 cursor = info->editor->pCursors[0];
550 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
551 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
552 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
555 info->nestingLevel++;
557 info->canInheritInTbl = FALSE;
559 break;
560 case rtfInTable:
562 if (!info->editor->bEmulateVersion10) /* v4.1 */
564 if (info->nestingLevel < 1)
566 RTFTable *tableDef;
567 if (!info->tableDef)
569 info->tableDef = ALLOC_OBJ(RTFTable);
570 ZeroMemory(info->tableDef, sizeof(RTFTable));
572 tableDef = info->tableDef;
573 RTFFlushOutputBuffer(info);
574 if (tableDef->tableRowStart &&
575 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
577 ME_DisplayItem *para = tableDef->tableRowStart;
578 para = para->member.para.next_para;
579 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
580 tableDef->tableRowStart = para;
581 } else {
582 ME_Cursor cursor;
583 WCHAR endl = '\r';
584 cursor = info->editor->pCursors[0];
585 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
586 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
587 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
589 info->nestingLevel = 1;
590 info->canInheritInTbl = TRUE;
592 return;
593 } else { /* v1.0 - v3.0 */
594 fmt.dwMask |= PFM_TABLE;
595 fmt.wEffects |= PFE_TABLE;
597 break;
599 case rtfFirstIndent:
600 ME_GetSelectionParaFormat(info->editor, &fmt);
601 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
602 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
603 fmt.dxOffset = -info->rtfParam;
604 break;
605 case rtfLeftIndent:
606 ME_GetSelectionParaFormat(info->editor, &fmt);
607 fmt.dwMask = PFM_STARTINDENT;
608 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
609 break;
610 case rtfRightIndent:
611 fmt.dwMask = PFM_RIGHTINDENT;
612 fmt.dxRightIndent = info->rtfParam;
613 break;
614 case rtfQuadLeft:
615 case rtfQuadJust:
616 fmt.dwMask = PFM_ALIGNMENT;
617 fmt.wAlignment = PFA_LEFT;
618 break;
619 case rtfQuadRight:
620 fmt.dwMask = PFM_ALIGNMENT;
621 fmt.wAlignment = PFA_RIGHT;
622 break;
623 case rtfQuadCenter:
624 fmt.dwMask = PFM_ALIGNMENT;
625 fmt.wAlignment = PFA_CENTER;
626 break;
627 case rtfTabPos:
628 ME_GetSelectionParaFormat(info->editor, &fmt);
629 if (!(fmt.dwMask & PFM_TABSTOPS))
631 fmt.cTabCount = 0;
633 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
634 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
635 fmt.dwMask = PFM_TABSTOPS;
636 break;
637 case rtfKeep:
638 fmt.dwMask = PFM_KEEP;
639 fmt.wEffects = PFE_KEEP;
640 break;
641 case rtfNoWidowControl:
642 fmt.dwMask = PFM_NOWIDOWCONTROL;
643 fmt.wEffects = PFE_NOWIDOWCONTROL;
644 break;
645 case rtfKeepNext:
646 fmt.dwMask = PFM_KEEPNEXT;
647 fmt.wEffects = PFE_KEEPNEXT;
648 break;
649 case rtfSpaceAfter:
650 fmt.dwMask = PFM_SPACEAFTER;
651 fmt.dySpaceAfter = info->rtfParam;
652 break;
653 case rtfSpaceBefore:
654 fmt.dwMask = PFM_SPACEBEFORE;
655 fmt.dySpaceBefore = info->rtfParam;
656 break;
657 case rtfSpaceBetween:
658 fmt.dwMask = PFM_LINESPACING;
659 if ((int)info->rtfParam > 0)
661 fmt.dyLineSpacing = info->rtfParam;
662 fmt.bLineSpacingRule = 3;
664 else
666 fmt.dyLineSpacing = info->rtfParam;
667 fmt.bLineSpacingRule = 4;
669 break;
670 case rtfSpaceMultiply:
671 fmt.dwMask = PFM_LINESPACING;
672 fmt.dyLineSpacing = info->rtfParam * 20;
673 fmt.bLineSpacingRule = 5;
674 break;
675 case rtfParBullet:
676 fmt.dwMask = PFM_NUMBERING;
677 fmt.wNumbering = PFN_BULLET;
678 break;
679 case rtfParSimple:
680 fmt.dwMask = PFM_NUMBERING;
681 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
682 break;
683 case rtfParNumDecimal:
684 fmt.dwMask = PFM_NUMBERING;
685 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
686 break;
687 case rtfParNumIndent:
688 fmt.dwMask = PFM_NUMBERINGTAB;
689 fmt.wNumberingTab = info->rtfParam;
690 break;
691 case rtfParNumStartAt:
692 fmt.dwMask = PFM_NUMBERINGSTART;
693 fmt.wNumberingStart = info->rtfParam;
694 break;
695 case rtfBorderLeft:
696 info->borderType = RTFBorderParaLeft;
697 ME_GetSelectionParaFormat(info->editor, &fmt);
698 if (!(fmt.dwMask & PFM_BORDER))
700 fmt.wBorderSpace = 0;
701 fmt.wBorderWidth = 1;
702 fmt.wBorders = 0;
704 fmt.wBorders |= 1;
705 fmt.dwMask = PFM_BORDER;
706 break;
707 case rtfBorderRight:
708 info->borderType = RTFBorderParaRight;
709 ME_GetSelectionParaFormat(info->editor, &fmt);
710 if (!(fmt.dwMask & PFM_BORDER))
712 fmt.wBorderSpace = 0;
713 fmt.wBorderWidth = 1;
714 fmt.wBorders = 0;
716 fmt.wBorders |= 2;
717 fmt.dwMask = PFM_BORDER;
718 break;
719 case rtfBorderTop:
720 info->borderType = RTFBorderParaTop;
721 ME_GetSelectionParaFormat(info->editor, &fmt);
722 if (!(fmt.dwMask & PFM_BORDER))
724 fmt.wBorderSpace = 0;
725 fmt.wBorderWidth = 1;
726 fmt.wBorders = 0;
728 fmt.wBorders |= 4;
729 fmt.dwMask = PFM_BORDER;
730 break;
731 case rtfBorderBottom:
732 info->borderType = RTFBorderParaBottom;
733 ME_GetSelectionParaFormat(info->editor, &fmt);
734 if (!(fmt.dwMask & PFM_BORDER))
736 fmt.wBorderSpace = 0;
737 fmt.wBorderWidth = 1;
738 fmt.wBorders = 0;
740 fmt.wBorders |= 8;
741 fmt.dwMask = PFM_BORDER;
742 break;
743 case rtfBorderSingle:
744 ME_GetSelectionParaFormat(info->editor, &fmt);
745 /* we assume that borders have been created before (RTF spec) */
746 fmt.wBorders &= ~0x700;
747 fmt.wBorders |= 1 << 8;
748 fmt.dwMask = PFM_BORDER;
749 break;
750 case rtfBorderThick:
751 ME_GetSelectionParaFormat(info->editor, &fmt);
752 /* we assume that borders have been created before (RTF spec) */
753 fmt.wBorders &= ~0x700;
754 fmt.wBorders |= 2 << 8;
755 fmt.dwMask = PFM_BORDER;
756 break;
757 case rtfBorderShadow:
758 ME_GetSelectionParaFormat(info->editor, &fmt);
759 /* we assume that borders have been created before (RTF spec) */
760 fmt.wBorders &= ~0x700;
761 fmt.wBorders |= 10 << 8;
762 fmt.dwMask = PFM_BORDER;
763 break;
764 case rtfBorderDouble:
765 ME_GetSelectionParaFormat(info->editor, &fmt);
766 /* we assume that borders have been created before (RTF spec) */
767 fmt.wBorders &= ~0x700;
768 fmt.wBorders |= 7 << 8;
769 fmt.dwMask = PFM_BORDER;
770 break;
771 case rtfBorderDot:
772 ME_GetSelectionParaFormat(info->editor, &fmt);
773 /* we assume that borders have been created before (RTF spec) */
774 fmt.wBorders &= ~0x700;
775 fmt.wBorders |= 11 << 8;
776 fmt.dwMask = PFM_BORDER;
777 break;
778 case rtfBorderWidth:
780 int borderSide = info->borderType & RTFBorderSideMask;
781 RTFTable *tableDef = info->tableDef;
782 ME_GetSelectionParaFormat(info->editor, &fmt);
783 /* we assume that borders have been created before (RTF spec) */
784 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
785 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
787 RTFBorder *border;
788 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
789 break;
790 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
791 border->width = info->rtfParam;
792 break;
794 fmt.dwMask = PFM_BORDER;
795 break;
797 case rtfBorderSpace:
798 ME_GetSelectionParaFormat(info->editor, &fmt);
799 /* we assume that borders have been created before (RTF spec) */
800 fmt.wBorderSpace = info->rtfParam;
801 fmt.dwMask = PFM_BORDER;
802 break;
803 case rtfBorderColor:
805 RTFTable *tableDef = info->tableDef;
806 int borderSide = info->borderType & RTFBorderSideMask;
807 int borderType = info->borderType & RTFBorderTypeMask;
808 switch(borderType)
810 case RTFBorderTypePara:
811 if (!info->editor->bEmulateVersion10) /* v4.1 */
812 break;
813 /* v1.0 - 3.0 treat paragraph and row borders the same. */
814 case RTFBorderTypeRow:
815 if (tableDef) {
816 tableDef->border[borderSide].color = info->rtfParam;
818 break;
819 case RTFBorderTypeCell:
820 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
821 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
823 break;
825 break;
828 if (fmt.dwMask) {
829 RTFFlushOutputBuffer(info);
830 /* FIXME too slow ? how come ?*/
831 ME_SetSelectionParaFormat(info->editor, &fmt);
835 void ME_RTFTblAttrHook(RTF_Info *info)
837 switch (info->rtfMinor)
839 case rtfRowDef:
841 if (!info->editor->bEmulateVersion10) /* v4.1 */
842 info->borderType = 0; /* Not sure */
843 else /* v1.0 - 3.0 */
844 info->borderType = RTFBorderRowTop;
845 if (!info->tableDef) {
846 info->tableDef = ME_MakeTableDef(info->editor);
847 } else {
848 ME_InitTableDef(info->editor, info->tableDef);
850 break;
852 case rtfCellPos:
854 int cellNum;
855 if (!info->tableDef)
857 info->tableDef = ME_MakeTableDef(info->editor);
859 cellNum = info->tableDef->numCellsDefined;
860 if (cellNum >= MAX_TABLE_CELLS)
861 break;
862 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
863 if (cellNum < MAX_TAB_STOPS) {
864 /* Tab stops were used to store cell positions before v4.1 but v4.1
865 * still seems to set the tabstops without using them. */
866 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
867 PARAFORMAT2 *pFmt = para->member.para.pFmt;
868 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
869 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
871 info->tableDef->numCellsDefined++;
872 break;
874 case rtfRowBordTop:
875 info->borderType = RTFBorderRowTop;
876 break;
877 case rtfRowBordLeft:
878 info->borderType = RTFBorderRowLeft;
879 break;
880 case rtfRowBordBottom:
881 info->borderType = RTFBorderRowBottom;
882 break;
883 case rtfRowBordRight:
884 info->borderType = RTFBorderRowRight;
885 break;
886 case rtfCellBordTop:
887 info->borderType = RTFBorderCellTop;
888 break;
889 case rtfCellBordLeft:
890 info->borderType = RTFBorderCellLeft;
891 break;
892 case rtfCellBordBottom:
893 info->borderType = RTFBorderCellBottom;
894 break;
895 case rtfCellBordRight:
896 info->borderType = RTFBorderCellRight;
897 break;
898 case rtfRowGapH:
899 if (info->tableDef)
900 info->tableDef->gapH = info->rtfParam;
901 break;
902 case rtfRowLeftEdge:
903 if (info->tableDef)
904 info->tableDef->leftEdge = info->rtfParam;
905 break;
909 void ME_RTFSpecialCharHook(RTF_Info *info)
911 RTFTable *tableDef = info->tableDef;
912 switch (info->rtfMinor)
914 case rtfNestCell:
915 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
916 break;
917 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
918 case rtfCell:
919 if (!tableDef)
920 break;
921 RTFFlushOutputBuffer(info);
922 if (!info->editor->bEmulateVersion10) { /* v4.1 */
923 if (tableDef->tableRowStart)
925 if (!info->nestingLevel &&
926 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
928 ME_DisplayItem *para = tableDef->tableRowStart;
929 para = para->member.para.next_para;
930 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
931 tableDef->tableRowStart = para;
932 info->nestingLevel = 1;
934 ME_InsertTableCellFromCursor(info->editor);
936 } else { /* v1.0 - v3.0 */
937 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
938 PARAFORMAT2 *pFmt = para->member.para.pFmt;
939 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
940 tableDef->numCellsInserted < tableDef->numCellsDefined)
942 WCHAR tab = '\t';
943 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
944 tableDef->numCellsInserted++;
947 break;
948 case rtfNestRow:
949 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
950 break;
951 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
952 case rtfRow:
954 ME_DisplayItem *para, *cell, *run;
955 int i;
957 if (!tableDef)
958 break;
959 RTFFlushOutputBuffer(info);
960 if (!info->editor->bEmulateVersion10) { /* v4.1 */
961 if (!tableDef->tableRowStart)
962 break;
963 if (!info->nestingLevel &&
964 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
966 para = tableDef->tableRowStart;
967 para = para->member.para.next_para;
968 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
969 tableDef->tableRowStart = para;
970 info->nestingLevel++;
972 para = tableDef->tableRowStart;
973 cell = ME_FindItemFwd(para, diCell);
974 assert(cell && !cell->member.cell.prev_cell);
975 if (tableDef->numCellsDefined < 1)
977 /* 2000 twips appears to be the cell size that native richedit uses
978 * when no cell sizes are specified. */
979 const int defaultCellSize = 2000;
980 int nRightBoundary = defaultCellSize;
981 cell->member.cell.nRightBoundary = nRightBoundary;
982 while (cell->member.cell.next_cell) {
983 cell = cell->member.cell.next_cell;
984 nRightBoundary += defaultCellSize;
985 cell->member.cell.nRightBoundary = nRightBoundary;
987 para = ME_InsertTableCellFromCursor(info->editor);
988 cell = para->member.para.pCell;
989 cell->member.cell.nRightBoundary = nRightBoundary;
990 } else {
991 for (i = 0; i < tableDef->numCellsDefined; i++)
993 RTFCell *cellDef = &tableDef->cells[i];
994 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
995 ME_ApplyBorderProperties(info, &cell->member.cell.border,
996 cellDef->border);
997 cell = cell->member.cell.next_cell;
998 if (!cell)
1000 para = ME_InsertTableCellFromCursor(info->editor);
1001 cell = para->member.para.pCell;
1004 /* Cell for table row delimiter is empty */
1005 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1008 run = ME_FindItemFwd(cell, diRun);
1009 if (info->editor->pCursors[0].pRun != run ||
1010 info->editor->pCursors[0].nOffset)
1012 int nOfs, nChars;
1013 /* Delete inserted cells that aren't defined. */
1014 info->editor->pCursors[1].pRun = run;
1015 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1016 info->editor->pCursors[1].nOffset = 0;
1017 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1018 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1019 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1020 nChars, TRUE);
1023 para = ME_InsertTableRowEndFromCursor(info->editor);
1024 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1025 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1026 ME_ApplyBorderProperties(info, &para->member.para.border,
1027 tableDef->border);
1028 info->nestingLevel--;
1029 if (!info->nestingLevel)
1031 if (info->canInheritInTbl) {
1032 tableDef->tableRowStart = para;
1033 } else {
1034 while (info->tableDef) {
1035 tableDef = info->tableDef;
1036 info->tableDef = tableDef->parent;
1037 heap_free(tableDef);
1040 } else {
1041 info->tableDef = tableDef->parent;
1042 heap_free(tableDef);
1044 } else { /* v1.0 - v3.0 */
1045 WCHAR endl = '\r';
1046 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1047 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1048 pFmt->dxOffset = info->tableDef->gapH;
1049 pFmt->dxStartIndent = info->tableDef->leftEdge;
1051 ME_ApplyBorderProperties(info, &para->member.para.border,
1052 tableDef->border);
1053 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1055 WCHAR tab = '\t';
1056 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1057 tableDef->numCellsInserted++;
1059 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1060 if (!tableDef->numCellsDefined)
1061 pFmt->wEffects &= ~PFE_TABLE;
1062 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1063 tableDef->numCellsInserted = 0;
1065 break;
1067 case rtfTab:
1068 case rtfPar:
1069 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1070 ME_DisplayItem *para;
1071 PARAFORMAT2 *pFmt;
1072 RTFFlushOutputBuffer(info);
1073 para = info->editor->pCursors[0].pPara;
1074 pFmt = para->member.para.pFmt;
1075 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1077 /* rtfPar is treated like a space within a table. */
1078 info->rtfClass = rtfText;
1079 info->rtfMajor = ' ';
1081 else if (info->rtfMinor == rtfPar && tableDef)
1082 tableDef->numCellsInserted = 0;
1084 break;
1088 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1089 const SIZEL* sz)
1091 LPOLEOBJECT lpObject = NULL;
1092 LPSTORAGE lpStorage = NULL;
1093 LPOLECLIENTSITE lpClientSite = NULL;
1094 LPDATAOBJECT lpDataObject = NULL;
1095 LPOLECACHE lpOleCache = NULL;
1096 STGMEDIUM stgm;
1097 FORMATETC fm;
1098 CLSID clsid;
1099 BOOL ret = FALSE;
1100 DWORD conn;
1102 if (hemf)
1104 stgm.tymed = TYMED_ENHMF;
1105 stgm.u.hEnhMetaFile = hemf;
1106 fm.cfFormat = CF_ENHMETAFILE;
1108 else if (hbmp)
1110 stgm.tymed = TYMED_GDI;
1111 stgm.u.hBitmap = hbmp;
1112 fm.cfFormat = CF_BITMAP;
1114 stgm.pUnkForRelease = NULL;
1116 fm.ptd = NULL;
1117 fm.dwAspect = DVASPECT_CONTENT;
1118 fm.lindex = -1;
1119 fm.tymed = stgm.tymed;
1121 if (!info->lpRichEditOle)
1123 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1126 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1127 #if 0
1128 /* FIXME: enable it when rich-edit properly implements this method */
1129 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1130 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1131 #endif
1132 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1133 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1134 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1135 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1136 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1138 REOBJECT reobject;
1140 reobject.cbStruct = sizeof(reobject);
1141 reobject.cp = REO_CP_SELECTION;
1142 reobject.clsid = clsid;
1143 reobject.poleobj = lpObject;
1144 reobject.pstg = lpStorage;
1145 reobject.polesite = lpClientSite;
1146 /* convert from twips to .01 mm */
1147 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1148 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1149 reobject.dvaspect = DVASPECT_CONTENT;
1150 reobject.dwFlags = 0; /* FIXME */
1151 reobject.dwUser = 0;
1153 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1154 ret = TRUE;
1157 if (lpObject) IOleObject_Release(lpObject);
1158 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1159 if (lpStorage) IStorage_Release(lpStorage);
1160 if (lpDataObject) IDataObject_Release(lpDataObject);
1161 if (lpOleCache) IOleCache_Release(lpOleCache);
1163 return ret;
1166 static void ME_RTFReadPictGroup(RTF_Info *info)
1168 SIZEL sz;
1169 BYTE* buffer = NULL;
1170 unsigned bufsz, bufidx;
1171 BOOL flip;
1172 BYTE val;
1173 METAFILEPICT mfp;
1174 HENHMETAFILE hemf;
1175 HBITMAP hbmp;
1176 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1178 RTFGetToken (info);
1179 if (info->rtfClass == rtfEOF)
1180 return;
1181 mfp.mm = MM_TEXT;
1182 /* fetch picture type */
1183 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1185 mfp.mm = info->rtfParam;
1186 gfx = gfx_metafile;
1188 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1190 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1191 gfx = gfx_dib;
1193 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1195 gfx = gfx_enhmetafile;
1197 else
1199 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1200 goto skip_group;
1202 sz.cx = sz.cy = 0;
1203 /* fetch picture attributes */
1204 for (;;)
1206 RTFGetToken (info);
1207 if (info->rtfClass == rtfEOF)
1208 return;
1209 if (info->rtfClass == rtfText)
1210 break;
1211 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1213 ERR("Expected picture attribute (%d %d)\n",
1214 info->rtfClass, info->rtfMajor);
1215 goto skip_group;
1217 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1219 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1221 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1223 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1225 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1226 sz.cx = info->rtfParam;
1227 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1228 sz.cy = info->rtfParam;
1229 else
1230 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1232 /* fetch picture data */
1233 bufsz = 1024;
1234 bufidx = 0;
1235 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1236 val = info->rtfMajor;
1237 for (flip = TRUE;; flip = !flip)
1239 RTFGetToken (info);
1240 if (info->rtfClass == rtfEOF)
1242 HeapFree(GetProcessHeap(), 0, buffer);
1243 return; /* Warn ?? */
1245 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1246 break;
1247 if (info->rtfClass != rtfText) goto skip_group;
1248 if (flip)
1250 if (bufidx >= bufsz &&
1251 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1252 goto skip_group;
1253 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1255 else
1256 val = info->rtfMajor;
1258 if (flip) FIXME("wrong hex string\n");
1260 switch (gfx)
1262 case gfx_enhmetafile:
1263 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1264 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1265 break;
1266 case gfx_metafile:
1267 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1268 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1269 break;
1270 case gfx_dib:
1272 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1273 HDC hdc = GetDC(0);
1274 unsigned nc = bi->bmiHeader.biClrUsed;
1276 /* not quite right, especially for bitfields type of compression */
1277 if (!nc && bi->bmiHeader.biBitCount <= 8)
1278 nc = 1 << bi->bmiHeader.biBitCount;
1279 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1280 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1281 bi, DIB_RGB_COLORS)))
1282 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1283 ReleaseDC(0, hdc);
1285 break;
1286 default:
1287 break;
1289 HeapFree(GetProcessHeap(), 0, buffer);
1290 RTFRouteToken (info); /* feed "}" back to router */
1291 return;
1292 skip_group:
1293 HeapFree(GetProcessHeap(), 0, buffer);
1294 RTFSkipGroup(info);
1295 RTFRouteToken(info); /* feed "}" back to router */
1298 /* for now, lookup the \result part and use it, whatever the object */
1299 static void ME_RTFReadObjectGroup(RTF_Info *info)
1301 for (;;)
1303 RTFGetToken (info);
1304 if (info->rtfClass == rtfEOF)
1305 return;
1306 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1307 break;
1308 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1310 RTFGetToken (info);
1311 if (info->rtfClass == rtfEOF)
1312 return;
1313 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1315 int level = 1;
1317 while (RTFGetToken (info) != rtfEOF)
1319 if (info->rtfClass == rtfGroup)
1321 if (info->rtfMajor == rtfBeginGroup) level++;
1322 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1324 RTFRouteToken(info);
1327 else RTFSkipGroup(info);
1328 continue;
1330 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1332 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1333 return;
1336 RTFRouteToken(info); /* feed "}" back to router */
1339 static void ME_RTFReadHook(RTF_Info *info)
1341 switch(info->rtfClass)
1343 case rtfGroup:
1344 switch(info->rtfMajor)
1346 case rtfBeginGroup:
1347 if (info->stackTop < maxStack) {
1348 info->stack[info->stackTop].style = info->style;
1349 ME_AddRefStyle(info->style);
1350 info->stack[info->stackTop].codePage = info->codePage;
1351 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1353 info->stackTop++;
1354 info->styleChanged = FALSE;
1355 break;
1356 case rtfEndGroup:
1358 RTFFlushOutputBuffer(info);
1359 info->stackTop--;
1360 if (info->stackTop <= 0)
1361 info->rtfClass = rtfEOF;
1362 if (info->stackTop < 0)
1363 return;
1365 ME_ReleaseStyle(info->style);
1366 info->style = info->stack[info->stackTop].style;
1367 info->codePage = info->stack[info->stackTop].codePage;
1368 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1369 break;
1372 break;
1376 void
1377 ME_StreamInFill(ME_InStream *stream)
1379 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1380 (BYTE *)stream->buffer,
1381 sizeof(stream->buffer),
1382 (LONG *)&stream->dwSize);
1383 stream->dwUsed = 0;
1386 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1388 RTF_Info parser;
1389 ME_Style *style;
1390 int from, to, nUndoMode;
1391 int nEventMask = editor->nEventMask;
1392 ME_InStream inStream;
1393 BOOL invalidRTF = FALSE;
1394 ME_Cursor *selStart, *selEnd;
1395 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1397 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1398 editor->nEventMask = 0;
1400 ME_GetSelectionOfs(editor, &from, &to);
1401 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1403 ME_GetSelection(editor, &selStart, &selEnd);
1404 style = ME_GetSelectionInsertStyle(editor);
1406 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1408 /* Don't insert text at the end of the table row */
1409 if (!editor->bEmulateVersion10) { /* v4.1 */
1410 ME_DisplayItem *para = editor->pCursors->pPara;
1411 if (para->member.para.nFlags & MEPF_ROWEND)
1413 para = para->member.para.next_para;
1414 editor->pCursors[0].pPara = para;
1415 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1416 editor->pCursors[0].nOffset = 0;
1418 if (para->member.para.nFlags & MEPF_ROWSTART)
1420 para = para->member.para.next_para;
1421 editor->pCursors[0].pPara = para;
1422 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1423 editor->pCursors[0].nOffset = 0;
1425 editor->pCursors[1] = editor->pCursors[0];
1426 } else { /* v1.0 - 3.0 */
1427 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1428 ME_IsInTable(editor->pCursors[0].pRun))
1429 return 0;
1431 } else {
1432 style = editor->pBuffer->pDefaultStyle;
1433 ME_AddRefStyle(style);
1434 ME_SetSelection(editor, 0, 0);
1435 ME_InternalDeleteText(editor, &editor->pCursors[1],
1436 ME_GetTextLength(editor), FALSE);
1437 from = to = 0;
1438 ME_ClearTempStyle(editor);
1439 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1443 /* Back up undo mode to a local variable */
1444 nUndoMode = editor->nUndoMode;
1446 /* Only create an undo if SFF_SELECTION is set */
1447 if (!(format & SFF_SELECTION))
1448 editor->nUndoMode = umIgnore;
1450 inStream.editstream = stream;
1451 inStream.editstream->dwError = 0;
1452 inStream.dwSize = 0;
1453 inStream.dwUsed = 0;
1455 if (format & SF_RTF)
1457 /* Check if it's really RTF, and if it is not, use plain text */
1458 ME_StreamInFill(&inStream);
1459 if (!inStream.editstream->dwError)
1461 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1462 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1464 invalidRTF = TRUE;
1465 inStream.editstream->dwError = -16;
1470 if (!invalidRTF && !inStream.editstream->dwError)
1472 if (format & SF_RTF) {
1473 from = ME_GetCursorOfs(&editor->pCursors[0]);
1475 /* setup the RTF parser */
1476 memset(&parser, 0, sizeof parser);
1477 RTFSetEditStream(&parser, &inStream);
1478 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1479 parser.editor = editor;
1480 parser.style = style;
1481 WriterInit(&parser);
1482 RTFInit(&parser);
1483 RTFSetReadHook(&parser, ME_RTFReadHook);
1484 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1485 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1486 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1488 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1489 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1491 BeginFile(&parser);
1493 /* do the parsing */
1494 RTFRead(&parser);
1495 RTFFlushOutputBuffer(&parser);
1496 if (!editor->bEmulateVersion10) { /* v4.1 */
1497 if (parser.tableDef && parser.tableDef->tableRowStart &&
1498 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1500 /* Delete any incomplete table row at the end of the rich text. */
1501 int nOfs, nChars;
1502 ME_DisplayItem *para;
1504 parser.rtfMinor = rtfRow;
1505 /* Complete the table row before deleting it.
1506 * By doing it this way we will have the current paragraph format set
1507 * properly to reflect that is not in the complete table, and undo items
1508 * will be added for this change to the current paragraph format. */
1509 if (parser.nestingLevel > 0)
1511 while (parser.nestingLevel > 1)
1512 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1513 para = parser.tableDef->tableRowStart;
1514 ME_RTFSpecialCharHook(&parser);
1515 } else {
1516 para = parser.tableDef->tableRowStart;
1517 ME_RTFSpecialCharHook(&parser);
1518 assert(para->member.para.nFlags & MEPF_ROWEND);
1519 para = para->member.para.next_para;
1522 editor->pCursors[1].pPara = para;
1523 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1524 editor->pCursors[1].nOffset = 0;
1525 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1526 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1527 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1528 if (parser.tableDef)
1529 parser.tableDef->tableRowStart = NULL;
1532 ME_CheckTablesForCorruption(editor);
1533 RTFDestroy(&parser);
1534 if (parser.lpRichEditOle)
1535 IRichEditOle_Release(parser.lpRichEditOle);
1537 if (parser.stackTop > 0)
1539 while (--parser.stackTop >= 0)
1541 ME_ReleaseStyle(parser.style);
1542 parser.style = parser.stack[parser.stackTop].style;
1544 if (!inStream.editstream->dwError)
1545 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1548 /* Remove last line break, as mandated by tests. This is not affected by
1549 CR/LF counters, since RTF streaming presents only \para tokens, which
1550 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1552 if (stripLastCR) {
1553 int newto;
1554 ME_GetSelection(editor, &selStart, &selEnd);
1555 newto = ME_GetCursorOfs(selEnd);
1556 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1557 WCHAR lastchar[3] = {'\0', '\0'};
1558 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1559 ME_Cursor linebreakCursor = *selEnd;
1561 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1562 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1563 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1564 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1568 to = ME_GetCursorOfs(&editor->pCursors[0]);
1569 num_read = to - from;
1571 style = parser.style;
1573 else if (format & SF_TEXT)
1574 num_read = ME_StreamInText(editor, format, &inStream, style);
1575 else
1576 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1577 /* put the cursor at the top */
1578 if (!(format & SFF_SELECTION))
1579 ME_SetSelection(editor, 0, 0);
1582 /* Restore saved undo mode */
1583 editor->nUndoMode = nUndoMode;
1585 /* even if we didn't add an undo, we need to commit anything on the stack */
1586 ME_CommitUndo(editor);
1588 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1589 if (!(format & SFF_SELECTION))
1590 ME_EmptyUndoStack(editor);
1592 ME_ReleaseStyle(style);
1593 editor->nEventMask = nEventMask;
1594 ME_UpdateRepaint(editor, FALSE);
1595 if (!(format & SFF_SELECTION)) {
1596 ME_ClearTempStyle(editor);
1598 ITextHost_TxShowCaret(editor->texthost, FALSE);
1599 ME_MoveCaret(editor);
1600 ITextHost_TxShowCaret(editor->texthost, TRUE);
1601 ME_SendSelChange(editor);
1602 ME_SendRequestResize(editor, FALSE);
1604 return num_read;
1608 typedef struct tagME_RTFStringStreamStruct
1610 char *string;
1611 int pos;
1612 int length;
1613 } ME_RTFStringStreamStruct;
1615 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1617 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1618 int count;
1620 count = min(cb, pStruct->length - pStruct->pos);
1621 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1622 pStruct->pos += count;
1623 *pcb = count;
1624 return 0;
1627 static void
1628 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1630 EDITSTREAM es;
1631 ME_RTFStringStreamStruct data;
1633 data.string = string;
1634 data.length = strlen(string);
1635 data.pos = 0;
1636 es.dwCookie = (DWORD_PTR)&data;
1637 es.pfnCallback = ME_ReadFromRTFString;
1638 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1642 static int
1643 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1645 const int nLen = lstrlenW(text);
1646 const int nTextLen = ME_GetTextLength(editor);
1647 int nMin, nMax;
1648 ME_Cursor cursor;
1649 WCHAR wLastChar = ' ';
1651 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1652 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1654 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1655 FIXME("Flags 0x%08x not implemented\n",
1656 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1658 nMin = chrg->cpMin;
1659 if (chrg->cpMax == -1)
1660 nMax = nTextLen;
1661 else
1662 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1664 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1665 if (editor->bEmulateVersion10 && nMax == nTextLen)
1667 flags |= FR_DOWN;
1670 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1671 if (editor->bEmulateVersion10 && nMax < nMin)
1673 if (chrgText)
1675 chrgText->cpMin = -1;
1676 chrgText->cpMax = -1;
1678 return -1;
1681 /* when searching up, if cpMin < cpMax, then instead of searching
1682 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1683 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1684 * case, it is always bigger than cpMin.
1686 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1688 int nSwap = nMax;
1690 nMax = nMin > nTextLen ? nTextLen : nMin;
1691 if (nMin < nSwap || chrg->cpMax == -1)
1692 nMin = 0;
1693 else
1694 nMin = nSwap;
1697 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1699 if (chrgText)
1700 chrgText->cpMin = chrgText->cpMax = -1;
1701 return -1;
1704 if (flags & FR_DOWN) /* Forward search */
1706 /* If possible, find the character before where the search starts */
1707 if ((flags & FR_WHOLEWORD) && nMin)
1709 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1710 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1711 ME_MoveCursorChars(editor, &cursor, 1);
1712 } else {
1713 ME_CursorFromCharOfs(editor, nMin, &cursor);
1716 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1718 ME_DisplayItem *pCurItem = cursor.pRun;
1719 int nCurStart = cursor.nOffset;
1720 int nMatched = 0;
1722 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1724 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1725 break;
1727 nMatched++;
1728 if (nMatched == nLen)
1730 ME_DisplayItem *pNextItem = pCurItem;
1731 int nNextStart = nCurStart;
1732 WCHAR wNextChar;
1734 /* Check to see if next character is a whitespace */
1735 if (flags & FR_WHOLEWORD)
1737 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1739 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1740 nNextStart = -nMatched;
1743 if (pNextItem)
1744 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1745 else
1746 wNextChar = ' ';
1748 if (isalnumW(wNextChar))
1749 break;
1752 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1753 if (chrgText)
1755 chrgText->cpMin = cursor.nOffset;
1756 chrgText->cpMax = cursor.nOffset + nLen;
1758 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1759 return cursor.nOffset;
1761 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1763 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1764 nCurStart = -nMatched;
1767 if (pCurItem)
1768 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1769 else
1770 wLastChar = ' ';
1772 cursor.nOffset++;
1773 if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1775 ME_NextRun(&cursor.pPara, &cursor.pRun);
1776 cursor.nOffset = 0;
1780 else /* Backward search */
1782 /* If possible, find the character after where the search ends */
1783 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1785 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1786 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1787 ME_MoveCursorChars(editor, &cursor, -1);
1788 } else {
1789 ME_CursorFromCharOfs(editor, nMax, &cursor);
1792 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1794 ME_DisplayItem *pCurItem = cursor.pRun;
1795 ME_DisplayItem *pCurPara = cursor.pPara;
1796 int nCurEnd = cursor.nOffset;
1797 int nMatched = 0;
1799 if (nCurEnd == 0)
1801 ME_PrevRun(&pCurPara, &pCurItem);
1802 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1805 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1807 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1808 break;
1810 nMatched++;
1811 if (nMatched == nLen)
1813 ME_DisplayItem *pPrevItem = pCurItem;
1814 int nPrevEnd = nCurEnd;
1815 WCHAR wPrevChar;
1816 int nStart;
1818 /* Check to see if previous character is a whitespace */
1819 if (flags & FR_WHOLEWORD)
1821 if (nPrevEnd - nMatched == 0)
1823 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1824 if (pPrevItem)
1825 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1828 if (pPrevItem)
1829 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1830 else
1831 wPrevChar = ' ';
1833 if (isalnumW(wPrevChar))
1834 break;
1837 nStart = pCurPara->member.para.nCharOfs
1838 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1839 if (chrgText)
1841 chrgText->cpMin = nStart;
1842 chrgText->cpMax = nStart + nLen;
1844 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1845 return nStart;
1847 if (nCurEnd - nMatched == 0)
1849 ME_PrevRun(&pCurPara, &pCurItem);
1850 /* Don't care about pCurItem becoming NULL here; it's already taken
1851 * care of in the exterior loop condition */
1852 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1855 if (pCurItem)
1856 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1857 else
1858 wLastChar = ' ';
1860 cursor.nOffset--;
1861 if (cursor.nOffset < 0)
1863 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1864 cursor.nOffset = cursor.pRun->member.run.strText->nLen;
1868 TRACE("not found\n");
1869 if (chrgText)
1870 chrgText->cpMin = chrgText->cpMax = -1;
1871 return -1;
1874 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1876 int nChars;
1877 ME_Cursor start;
1879 if (!ex->cb || !pText) return 0;
1881 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1882 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1884 if (ex->flags & GT_SELECTION)
1886 int from, to;
1887 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1888 start = editor->pCursors[nStartCur];
1889 nChars = to - from;
1891 else
1893 ME_SetCursorToStart(editor, &start);
1894 nChars = INT_MAX;
1896 if (ex->codepage == 1200)
1898 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1899 &start, nChars, ex->flags & GT_USECRLF);
1901 else
1903 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1904 we can just take a bigger buffer? :)
1905 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1906 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1908 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1909 DWORD buflen;
1910 LPWSTR buffer;
1911 LRESULT rc;
1913 buflen = min(crlfmul * nChars, ex->cb - 1);
1914 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1916 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1917 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1918 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1919 if (rc) rc--; /* do not count 0 terminator */
1921 heap_free(buffer);
1922 return rc;
1926 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1927 const ME_Cursor *start, int nLen, BOOL unicode)
1929 if (!strText) return 0;
1930 if (unicode) {
1931 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1932 } else {
1933 int nChars;
1934 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1935 if (!p) return 0;
1936 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1937 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1938 nLen+1, NULL, NULL);
1939 FREE_OBJ(p);
1940 return nChars;
1944 typedef struct tagME_GlobalDestStruct
1946 HGLOBAL hData;
1947 int nLength;
1948 } ME_GlobalDestStruct;
1950 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1952 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1953 int i;
1954 WORD *pSrc, *pDest;
1956 cb = cb >> 1;
1957 pDest = (WORD *)lpBuff;
1958 pSrc = GlobalLock(pData->hData);
1959 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1960 pDest[i] = pSrc[pData->nLength+i];
1962 pData->nLength += i;
1963 *pcb = 2*i;
1964 GlobalUnlock(pData->hData);
1965 return 0;
1968 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1970 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1971 int i;
1972 BYTE *pSrc, *pDest;
1974 pDest = 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 = i;
1981 GlobalUnlock(pData->hData);
1982 return 0;
1985 static BOOL ME_Paste(ME_TextEditor *editor)
1987 DWORD dwFormat = 0;
1988 EDITSTREAM es;
1989 ME_GlobalDestStruct gds;
1990 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1991 UINT cf = 0;
1993 if (IsClipboardFormatAvailable(nRTFFormat))
1994 cf = nRTFFormat, dwFormat = SF_RTF;
1995 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1996 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1997 else
1998 return FALSE;
2000 if (!OpenClipboard(editor->hWnd))
2001 return FALSE;
2002 gds.hData = GetClipboardData(cf);
2003 gds.nLength = 0;
2004 es.dwCookie = (DWORD_PTR)&gds;
2005 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2006 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2008 CloseClipboard();
2009 return TRUE;
2012 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2014 LPDATAOBJECT dataObj = NULL;
2015 HRESULT hr = S_OK;
2017 if (editor->cPasswordMask)
2018 return FALSE; /* Copying or Cutting masked text isn't allowed */
2020 if(editor->lpOleCallback)
2022 CHARRANGE range;
2023 range.cpMin = ME_GetCursorOfs(start);
2024 range.cpMax = range.cpMin + nChars;
2025 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2027 if(FAILED(hr) || !dataObj)
2028 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2029 if(SUCCEEDED(hr)) {
2030 hr = OleSetClipboard(dataObj);
2031 IDataObject_Release(dataObj);
2033 return SUCCEEDED(hr) != 0;
2036 /* helper to send a msg filter notification */
2037 static BOOL
2038 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2040 MSGFILTER msgf;
2042 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2043 msgf.nmhdr.hwndFrom = editor->hWnd;
2044 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2045 msgf.nmhdr.code = EN_MSGFILTER;
2046 msgf.msg = msg;
2047 msgf.wParam = *wParam;
2048 msgf.lParam = *lParam;
2049 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2050 return FALSE;
2051 *wParam = msgf.wParam;
2052 *lParam = msgf.lParam;
2053 msgf.wParam = *wParam;
2055 return TRUE;
2058 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2060 ME_DisplayItem *startPara, *endPara;
2061 ME_DisplayItem *prev_para;
2062 ME_Cursor *from, *to;
2063 ME_Cursor start;
2064 int nChars;
2066 if (!editor->AutoURLDetect_bEnable) return;
2068 ME_GetSelection(editor, &from, &to);
2070 /* Find paragraph previous to the one that contains start cursor */
2071 startPara = from->pPara;
2072 prev_para = startPara->member.para.prev_para;
2073 if (prev_para->type == diParagraph) startPara = prev_para;
2075 /* Find paragraph that contains end cursor */
2076 endPara = to->pPara->member.para.next_para;
2078 start.pPara = startPara;
2079 start.pRun = ME_FindItemFwd(startPara, diRun);
2080 start.nOffset = 0;
2081 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2083 ME_UpdateLinkAttribute(editor, &start, nChars);
2086 static BOOL
2087 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2089 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2090 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2092 if (editor->bMouseCaptured)
2093 return FALSE;
2094 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2095 editor->nSelectionType = stPosition;
2097 switch (nKey)
2099 case VK_LEFT:
2100 case VK_RIGHT:
2101 case VK_HOME:
2102 case VK_END:
2103 editor->nUDArrowX = -1;
2104 /* fall through */
2105 case VK_UP:
2106 case VK_DOWN:
2107 case VK_PRIOR:
2108 case VK_NEXT:
2109 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2110 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2111 return TRUE;
2112 case VK_BACK:
2113 case VK_DELETE:
2114 editor->nUDArrowX = -1;
2115 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2116 if (editor->styleFlags & ES_READONLY)
2117 return FALSE;
2118 if (ME_IsSelection(editor))
2120 ME_DeleteSelection(editor);
2121 ME_CommitUndo(editor);
2123 else if (nKey == VK_DELETE)
2125 /* Delete stops group typing.
2126 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2127 ME_DeleteTextAtCursor(editor, 1, 1);
2128 ME_CommitUndo(editor);
2130 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2132 BOOL bDeletionSucceeded;
2133 /* Backspace can be grouped for a single undo */
2134 ME_ContinueCoalescingTransaction(editor);
2135 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2136 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2137 /* Deletion was prevented so the cursor is moved back to where it was.
2138 * (e.g. this happens when trying to delete cell boundaries)
2140 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2142 ME_CommitCoalescingUndo(editor);
2144 else
2145 return TRUE;
2146 ME_MoveCursorFromTableRowStartParagraph(editor);
2147 ME_UpdateSelectionLinkAttribute(editor);
2148 ME_UpdateRepaint(editor, FALSE);
2149 ME_SendRequestResize(editor, FALSE);
2150 return TRUE;
2151 case VK_RETURN:
2152 if (editor->bDialogMode)
2154 if (ctrl_is_down)
2155 return TRUE;
2157 if (!(editor->styleFlags & ES_WANTRETURN))
2159 if (editor->hwndParent)
2161 DWORD dw;
2162 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2163 if (HIWORD(dw) == DC_HASDEFID)
2165 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2166 if (hwDefCtrl)
2168 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2169 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2173 return TRUE;
2177 if (editor->styleFlags & ES_MULTILINE)
2179 ME_Cursor cursor = editor->pCursors[0];
2180 ME_DisplayItem *para = cursor.pPara;
2181 int from, to;
2182 const WCHAR endl = '\r';
2183 const WCHAR endlv10[] = {'\r','\n'};
2184 ME_Style *style;
2186 if (editor->styleFlags & ES_READONLY) {
2187 MessageBeep(MB_ICONERROR);
2188 return TRUE;
2191 ME_GetSelectionOfs(editor, &from, &to);
2192 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2194 if (!editor->bEmulateVersion10) { /* v4.1 */
2195 if (para->member.para.nFlags & MEPF_ROWEND) {
2196 /* Add a new table row after this row. */
2197 para = ME_AppendTableRow(editor, para);
2198 para = para->member.para.next_para;
2199 editor->pCursors[0].pPara = para;
2200 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2201 editor->pCursors[0].nOffset = 0;
2202 editor->pCursors[1] = editor->pCursors[0];
2203 ME_CommitUndo(editor);
2204 ME_CheckTablesForCorruption(editor);
2205 ME_UpdateRepaint(editor, FALSE);
2206 return TRUE;
2208 else if (para == editor->pCursors[1].pPara &&
2209 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2210 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2211 !para->member.para.prev_para->member.para.nCharOfs)
2213 /* Insert a newline before the table. */
2214 para = para->member.para.prev_para;
2215 para->member.para.nFlags &= ~MEPF_ROWSTART;
2216 editor->pCursors[0].pPara = para;
2217 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2218 editor->pCursors[1] = editor->pCursors[0];
2219 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2220 editor->pCursors[0].pRun->member.run.style);
2221 para = editor->pBuffer->pFirst->member.para.next_para;
2222 ME_SetDefaultParaFormat(para->member.para.pFmt);
2223 para->member.para.nFlags = MEPF_REWRAP;
2224 editor->pCursors[0].pPara = para;
2225 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2226 editor->pCursors[1] = editor->pCursors[0];
2227 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2228 ME_CommitCoalescingUndo(editor);
2229 ME_CheckTablesForCorruption(editor);
2230 ME_UpdateRepaint(editor, FALSE);
2231 return TRUE;
2233 } else { /* v1.0 - 3.0 */
2234 ME_DisplayItem *para = cursor.pPara;
2235 if (ME_IsInTable(para))
2237 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2239 if (from == to) {
2240 ME_ContinueCoalescingTransaction(editor);
2241 para = ME_AppendTableRow(editor, para);
2242 editor->pCursors[0].pPara = para;
2243 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2244 editor->pCursors[0].nOffset = 0;
2245 editor->pCursors[1] = editor->pCursors[0];
2246 ME_CommitCoalescingUndo(editor);
2247 ME_UpdateRepaint(editor, FALSE);
2248 return TRUE;
2250 } else {
2251 ME_ContinueCoalescingTransaction(editor);
2252 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2253 !ME_IsInTable(para->member.para.prev_para))
2255 /* Insert newline before table */
2256 cursor.pRun = ME_FindItemBack(para, diRun);
2257 if (cursor.pRun) {
2258 editor->pCursors[0].pRun = cursor.pRun;
2259 editor->pCursors[0].pPara = para->member.para.prev_para;
2261 editor->pCursors[0].nOffset = 0;
2262 editor->pCursors[1] = editor->pCursors[0];
2263 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2264 editor->pCursors[0].pRun->member.run.style);
2265 } else {
2266 editor->pCursors[1] = editor->pCursors[0];
2267 para = ME_AppendTableRow(editor, para);
2268 editor->pCursors[0].pPara = para;
2269 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2270 editor->pCursors[0].nOffset = 0;
2271 editor->pCursors[1] = editor->pCursors[0];
2273 ME_CommitCoalescingUndo(editor);
2274 ME_UpdateRepaint(editor, FALSE);
2275 return TRUE;
2280 style = ME_GetInsertStyle(editor, 0);
2281 ME_SaveTempStyle(editor);
2282 ME_ContinueCoalescingTransaction(editor);
2283 if (shift_is_down)
2284 ME_InsertEndRowFromCursor(editor, 0);
2285 else
2286 if (!editor->bEmulateVersion10)
2287 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2288 else
2289 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2290 ME_ReleaseStyle(style);
2291 ME_CommitCoalescingUndo(editor);
2292 SetCursor(NULL);
2294 ME_UpdateSelectionLinkAttribute(editor);
2295 ME_UpdateRepaint(editor, FALSE);
2297 return TRUE;
2299 break;
2300 case VK_ESCAPE:
2301 if (editor->bDialogMode && editor->hwndParent)
2302 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2303 return TRUE;
2304 case VK_TAB:
2305 if (editor->bDialogMode && editor->hwndParent)
2306 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2307 return TRUE;
2308 case 'A':
2309 if (ctrl_is_down)
2311 ME_SetSelection(editor, 0, -1);
2312 return TRUE;
2314 break;
2315 case 'V':
2316 if (ctrl_is_down)
2317 return ME_Paste(editor);
2318 break;
2319 case 'C':
2320 case 'X':
2321 if (ctrl_is_down)
2323 BOOL result;
2324 int nOfs, nChars;
2325 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2326 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2328 nChars -= nOfs;
2329 result = ME_Copy(editor, selStart, nChars);
2330 if (result && nKey == 'X')
2332 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2333 ME_CommitUndo(editor);
2334 ME_UpdateRepaint(editor, TRUE);
2336 return result;
2338 break;
2339 case 'Z':
2340 if (ctrl_is_down)
2342 ME_Undo(editor);
2343 return TRUE;
2345 break;
2346 case 'Y':
2347 if (ctrl_is_down)
2349 ME_Redo(editor);
2350 return TRUE;
2352 break;
2354 default:
2355 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2356 editor->nUDArrowX = -1;
2357 if (ctrl_is_down)
2359 if (nKey == 'W')
2361 CHARFORMAT2W chf;
2362 char buf[2048];
2363 chf.cbSize = sizeof(chf);
2365 ME_GetSelectionCharFormat(editor, &chf);
2366 ME_DumpStyleToBuf(&chf, buf);
2367 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2369 if (nKey == 'Q')
2371 ME_CheckCharOffsets(editor);
2375 return FALSE;
2378 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2379 LPARAM flags, BOOL unicode)
2381 WCHAR wstr;
2383 if (editor->bMouseCaptured)
2384 return 0;
2386 if (unicode)
2387 wstr = (WCHAR)charCode;
2388 else
2390 CHAR charA = charCode;
2391 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2394 if (editor->styleFlags & ES_READONLY) {
2395 MessageBeep(MB_ICONERROR);
2396 return 0; /* FIXME really 0 ? */
2399 if ((unsigned)wstr >= ' ' || wstr == '\t')
2401 ME_Cursor cursor = editor->pCursors[0];
2402 ME_DisplayItem *para = cursor.pPara;
2403 int from, to;
2404 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2405 ME_GetSelectionOfs(editor, &from, &to);
2406 if (wstr == '\t' &&
2407 /* v4.1 allows tabs to be inserted with ctrl key down */
2408 !(ctrl_is_down && !editor->bEmulateVersion10))
2410 ME_DisplayItem *para;
2411 BOOL bSelectedRow = FALSE;
2413 para = cursor.pPara;
2414 if (ME_IsSelection(editor) &&
2415 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2416 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2417 para->member.para.prev_para->type == diParagraph)
2419 para = para->member.para.prev_para;
2420 bSelectedRow = TRUE;
2422 if (ME_IsInTable(para))
2424 ME_TabPressedInTable(editor, bSelectedRow);
2425 ME_CommitUndo(editor);
2426 return 0;
2428 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2429 if (para->member.para.nFlags & MEPF_ROWEND) {
2430 if (from == to) {
2431 para = para->member.para.next_para;
2432 if (para->member.para.nFlags & MEPF_ROWSTART)
2433 para = para->member.para.next_para;
2434 editor->pCursors[0].pPara = para;
2435 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2436 editor->pCursors[0].nOffset = 0;
2437 editor->pCursors[1] = editor->pCursors[0];
2440 } else { /* v1.0 - 3.0 */
2441 if (ME_IsInTable(cursor.pRun) &&
2442 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2443 from == to)
2445 /* Text should not be inserted at the end of the table. */
2446 MessageBeep(-1);
2447 return 0;
2450 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2451 /* WM_CHAR is restricted to nTextLimit */
2452 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2454 ME_Style *style = ME_GetInsertStyle(editor, 0);
2455 ME_SaveTempStyle(editor);
2456 ME_ContinueCoalescingTransaction(editor);
2457 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2458 ME_ReleaseStyle(style);
2459 ME_CommitCoalescingUndo(editor);
2460 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2463 ME_UpdateSelectionLinkAttribute(editor);
2464 ME_UpdateRepaint(editor, FALSE);
2466 return 0;
2469 /* Process the message and calculate the new click count.
2471 * returns: The click count if it is mouse down event, else returns 0. */
2472 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2473 LPARAM lParam)
2475 static int clickNum = 0;
2476 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2477 return 0;
2479 if ((msg == WM_LBUTTONDBLCLK) ||
2480 (msg == WM_RBUTTONDBLCLK) ||
2481 (msg == WM_MBUTTONDBLCLK) ||
2482 (msg == WM_XBUTTONDBLCLK))
2484 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2487 if ((msg == WM_LBUTTONDOWN) ||
2488 (msg == WM_RBUTTONDOWN) ||
2489 (msg == WM_MBUTTONDOWN) ||
2490 (msg == WM_XBUTTONDOWN))
2492 static MSG prevClickMsg;
2493 MSG clickMsg;
2494 /* Compare the editor instead of the hwnd so that the this
2495 * can still be done for windowless richedit controls. */
2496 clickMsg.hwnd = (HWND)editor;
2497 clickMsg.message = msg;
2498 clickMsg.wParam = wParam;
2499 clickMsg.lParam = lParam;
2500 clickMsg.time = GetMessageTime();
2501 clickMsg.pt.x = (short)LOWORD(lParam);
2502 clickMsg.pt.y = (short)HIWORD(lParam);
2503 if ((clickNum != 0) &&
2504 (clickMsg.message == prevClickMsg.message) &&
2505 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2506 (clickMsg.wParam == prevClickMsg.wParam) &&
2507 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2508 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2509 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2511 clickNum++;
2512 } else {
2513 clickNum = 1;
2515 prevClickMsg = clickMsg;
2516 } else {
2517 return 0;
2519 return clickNum;
2522 static BOOL ME_SetCursor(ME_TextEditor *editor)
2524 ME_Cursor cursor;
2525 POINT pt;
2526 BOOL isExact;
2527 SCROLLBARINFO sbi;
2528 DWORD messagePos = GetMessagePos();
2529 pt.x = (short)LOWORD(messagePos);
2530 pt.y = (short)HIWORD(messagePos);
2532 if (editor->hWnd)
2534 sbi.cbSize = sizeof(sbi);
2535 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2536 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2537 PtInRect(&sbi.rcScrollBar, pt))
2539 ITextHost_TxSetCursor(editor->texthost,
2540 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2541 return TRUE;
2543 sbi.cbSize = sizeof(sbi);
2544 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2545 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2546 PtInRect(&sbi.rcScrollBar, pt))
2548 ITextHost_TxSetCursor(editor->texthost,
2549 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2550 return TRUE;
2553 ITextHost_TxScreenToClient(editor->texthost, &pt);
2555 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2556 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2557 return TRUE;
2559 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2560 pt.y < editor->rcFormat.top &&
2561 pt.x < editor->rcFormat.left)
2563 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2564 return TRUE;
2566 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2568 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2569 ITextHost_TxSetCursor(editor->texthost,
2570 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2571 else /* v4.1 */
2572 ITextHost_TxSetCursor(editor->texthost,
2573 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2574 return TRUE;
2576 if (pt.x < editor->rcFormat.left)
2578 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2579 return TRUE;
2581 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2582 if (isExact)
2584 ME_Run *run;
2586 run = &cursor.pRun->member.run;
2587 if (run->style->fmt.dwMask & CFM_LINK &&
2588 run->style->fmt.dwEffects & CFE_LINK)
2590 ITextHost_TxSetCursor(editor->texthost,
2591 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2592 FALSE);
2593 return TRUE;
2596 if (ME_IsSelection(editor))
2598 int selStart, selEnd;
2599 int offset = ME_GetCursorOfs(&cursor);
2601 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2602 if (selStart <= offset && selEnd >= offset) {
2603 ITextHost_TxSetCursor(editor->texthost,
2604 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2605 FALSE);
2606 return TRUE;
2610 ITextHost_TxSetCursor(editor->texthost,
2611 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2612 return TRUE;
2615 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2617 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2618 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2619 editor->rcFormat.left += 1 + editor->selofs;
2620 editor->rcFormat.right -= 1;
2623 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2625 CHARRANGE selrange;
2626 HMENU menu;
2627 int seltype = 0;
2628 if(!editor->lpOleCallback || !editor->hWnd)
2629 return FALSE;
2630 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2631 if(selrange.cpMin == selrange.cpMax)
2632 seltype |= SEL_EMPTY;
2633 else
2635 /* FIXME: Handle objects */
2636 seltype |= SEL_TEXT;
2637 if(selrange.cpMax-selrange.cpMin > 1)
2638 seltype |= SEL_MULTICHAR;
2640 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2642 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2643 DestroyMenu(menu);
2645 return TRUE;
2648 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2650 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2651 int i;
2652 DWORD props;
2653 LONG selbarwidth;
2655 ed->hWnd = NULL;
2656 ed->hwndParent = NULL;
2657 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2658 ed->texthost = texthost;
2659 ed->bEmulateVersion10 = bEmulateVersion10;
2660 ed->styleFlags = 0;
2661 ITextHost_TxGetPropertyBits(texthost,
2662 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2663 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2664 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2665 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2666 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2667 &props);
2668 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2669 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2670 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2671 ed->pBuffer = ME_MakeText();
2672 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2673 ed->nAvailWidth = 0; /* wrap to client area */
2674 ME_MakeFirstParagraph(ed);
2675 /* The four cursors are for:
2676 * 0 - The position where the caret is shown
2677 * 1 - The anchored end of the selection (for normal selection)
2678 * 2 & 3 - The anchored start and end respectively for word, line,
2679 * or paragraph selection.
2681 ed->nCursors = 4;
2682 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2683 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2684 ed->pCursors[1] = ed->pCursors[0];
2685 ed->pCursors[2] = ed->pCursors[0];
2686 ed->pCursors[3] = ed->pCursors[1];
2687 ed->nLastTotalLength = ed->nTotalLength = 0;
2688 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2689 ed->nUDArrowX = -1;
2690 ed->rgbBackColor = -1;
2691 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2692 ed->bCaretAtEnd = FALSE;
2693 ed->nEventMask = 0;
2694 ed->nModifyStep = 0;
2695 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2696 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2697 ed->nUndoStackSize = 0;
2698 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2699 ed->nUndoMode = umAddToUndo;
2700 ed->nParagraphs = 1;
2701 ed->nLastSelStart = ed->nLastSelEnd = 0;
2702 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2703 ed->bHideSelection = FALSE;
2704 ed->pfnWordBreak = NULL;
2705 ed->lpOleCallback = NULL;
2706 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2707 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2708 ed->AutoURLDetect_bEnable = FALSE;
2709 ed->bHaveFocus = FALSE;
2710 ed->bDialogMode = FALSE;
2711 ed->bMouseCaptured = FALSE;
2712 for (i=0; i<HFONT_CACHE_SIZE; i++)
2714 ed->pFontCache[i].nRefs = 0;
2715 ed->pFontCache[i].nAge = 0;
2716 ed->pFontCache[i].hFont = NULL;
2719 ME_CheckCharOffsets(ed);
2720 ed->bDefaultFormatRect = TRUE;
2721 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2722 if (selbarwidth) {
2723 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2724 ed->selofs = SELECTIONBAR_WIDTH;
2725 ed->styleFlags |= ES_SELECTIONBAR;
2726 } else {
2727 ed->selofs = 0;
2729 ed->nSelectionType = stPosition;
2731 ed->cPasswordMask = 0;
2732 if (props & TXTBIT_USEPASSWORD)
2733 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2735 if (props & TXTBIT_AUTOWORDSEL)
2736 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2737 if (props & TXTBIT_MULTILINE) {
2738 ed->styleFlags |= ES_MULTILINE;
2739 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2740 } else {
2741 ed->bWordWrap = FALSE;
2743 if (props & TXTBIT_READONLY)
2744 ed->styleFlags |= ES_READONLY;
2745 if (!(props & TXTBIT_HIDESELECTION))
2746 ed->styleFlags |= ES_NOHIDESEL;
2747 if (props & TXTBIT_SAVESELECTION)
2748 ed->styleFlags |= ES_SAVESEL;
2749 if (props & TXTBIT_VERTICAL)
2750 ed->styleFlags |= ES_VERTICAL;
2751 if (props & TXTBIT_DISABLEDRAG)
2752 ed->styleFlags |= ES_NOOLEDRAGDROP;
2754 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2756 /* Default scrollbar information */
2757 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2758 ed->vert_si.nMin = 0;
2759 ed->vert_si.nMax = 0;
2760 ed->vert_si.nPage = 0;
2761 ed->vert_si.nPos = 0;
2763 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2764 ed->horz_si.nMin = 0;
2765 ed->horz_si.nMax = 0;
2766 ed->horz_si.nPage = 0;
2767 ed->horz_si.nPos = 0;
2769 OleInitialize(NULL);
2771 return ed;
2774 static void ME_DestroyEditor(ME_TextEditor *editor)
2776 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2777 ME_DisplayItem *p = pFirst, *pNext = NULL;
2778 int i;
2780 ME_ClearTempStyle(editor);
2781 ME_EmptyUndoStack(editor);
2782 while(p) {
2783 pNext = p->next;
2784 ME_DestroyDisplayItem(p);
2785 p = pNext;
2787 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2788 for (i=0; i<HFONT_CACHE_SIZE; i++)
2790 if (editor->pFontCache[i].hFont)
2791 DeleteObject(editor->pFontCache[i].hFont);
2793 if (editor->rgbBackColor != -1)
2794 DeleteObject(editor->hbrBackground);
2795 if(editor->lpOleCallback)
2796 IRichEditOleCallback_Release(editor->lpOleCallback);
2797 ITextHost_Release(editor->texthost);
2798 OleUninitialize();
2800 FREE_OBJ(editor->pBuffer);
2801 FREE_OBJ(editor->pCursors);
2803 FREE_OBJ(editor);
2806 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2808 TRACE("\n");
2809 switch (fdwReason)
2811 case DLL_PROCESS_ATTACH:
2812 DisableThreadLibraryCalls(hinstDLL);
2813 me_heap = HeapCreate (0, 0x10000, 0);
2814 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2815 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2816 LookupInit();
2817 break;
2819 case DLL_PROCESS_DETACH:
2820 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2821 UnregisterClassW(MSFTEDIT_CLASS, 0);
2822 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2823 UnregisterClassA("RichEdit50A", 0);
2824 if (ME_ListBoxRegistered)
2825 UnregisterClassW(REListBox20W, 0);
2826 if (ME_ComboBoxRegistered)
2827 UnregisterClassW(REComboBox20W, 0);
2828 LookupCleanup();
2829 HeapDestroy (me_heap);
2830 me_heap = NULL;
2831 break;
2833 return TRUE;
2837 static const char * const edit_messages[] = {
2838 "EM_GETSEL",
2839 "EM_SETSEL",
2840 "EM_GETRECT",
2841 "EM_SETRECT",
2842 "EM_SETRECTNP",
2843 "EM_SCROLL",
2844 "EM_LINESCROLL",
2845 "EM_SCROLLCARET",
2846 "EM_GETMODIFY",
2847 "EM_SETMODIFY",
2848 "EM_GETLINECOUNT",
2849 "EM_LINEINDEX",
2850 "EM_SETHANDLE",
2851 "EM_GETHANDLE",
2852 "EM_GETTHUMB",
2853 "EM_UNKNOWN_BF",
2854 "EM_UNKNOWN_C0",
2855 "EM_LINELENGTH",
2856 "EM_REPLACESEL",
2857 "EM_UNKNOWN_C3",
2858 "EM_GETLINE",
2859 "EM_LIMITTEXT",
2860 "EM_CANUNDO",
2861 "EM_UNDO",
2862 "EM_FMTLINES",
2863 "EM_LINEFROMCHAR",
2864 "EM_UNKNOWN_CA",
2865 "EM_SETTABSTOPS",
2866 "EM_SETPASSWORDCHAR",
2867 "EM_EMPTYUNDOBUFFER",
2868 "EM_GETFIRSTVISIBLELINE",
2869 "EM_SETREADONLY",
2870 "EM_SETWORDBREAKPROC",
2871 "EM_GETWORDBREAKPROC",
2872 "EM_GETPASSWORDCHAR",
2873 "EM_SETMARGINS",
2874 "EM_GETMARGINS",
2875 "EM_GETLIMITTEXT",
2876 "EM_POSFROMCHAR",
2877 "EM_CHARFROMPOS",
2878 "EM_SETIMESTATUS",
2879 "EM_GETIMESTATUS"
2882 static const char * const richedit_messages[] = {
2883 "EM_CANPASTE",
2884 "EM_DISPLAYBAND",
2885 "EM_EXGETSEL",
2886 "EM_EXLIMITTEXT",
2887 "EM_EXLINEFROMCHAR",
2888 "EM_EXSETSEL",
2889 "EM_FINDTEXT",
2890 "EM_FORMATRANGE",
2891 "EM_GETCHARFORMAT",
2892 "EM_GETEVENTMASK",
2893 "EM_GETOLEINTERFACE",
2894 "EM_GETPARAFORMAT",
2895 "EM_GETSELTEXT",
2896 "EM_HIDESELECTION",
2897 "EM_PASTESPECIAL",
2898 "EM_REQUESTRESIZE",
2899 "EM_SELECTIONTYPE",
2900 "EM_SETBKGNDCOLOR",
2901 "EM_SETCHARFORMAT",
2902 "EM_SETEVENTMASK",
2903 "EM_SETOLECALLBACK",
2904 "EM_SETPARAFORMAT",
2905 "EM_SETTARGETDEVICE",
2906 "EM_STREAMIN",
2907 "EM_STREAMOUT",
2908 "EM_GETTEXTRANGE",
2909 "EM_FINDWORDBREAK",
2910 "EM_SETOPTIONS",
2911 "EM_GETOPTIONS",
2912 "EM_FINDTEXTEX",
2913 "EM_GETWORDBREAKPROCEX",
2914 "EM_SETWORDBREAKPROCEX",
2915 "EM_SETUNDOLIMIT",
2916 "EM_UNKNOWN_USER_83",
2917 "EM_REDO",
2918 "EM_CANREDO",
2919 "EM_GETUNDONAME",
2920 "EM_GETREDONAME",
2921 "EM_STOPGROUPTYPING",
2922 "EM_SETTEXTMODE",
2923 "EM_GETTEXTMODE",
2924 "EM_AUTOURLDETECT",
2925 "EM_GETAUTOURLDETECT",
2926 "EM_SETPALETTE",
2927 "EM_GETTEXTEX",
2928 "EM_GETTEXTLENGTHEX",
2929 "EM_SHOWSCROLLBAR",
2930 "EM_SETTEXTEX",
2931 "EM_UNKNOWN_USER_98",
2932 "EM_UNKNOWN_USER_99",
2933 "EM_SETPUNCTUATION",
2934 "EM_GETPUNCTUATION",
2935 "EM_SETWORDWRAPMODE",
2936 "EM_GETWORDWRAPMODE",
2937 "EM_SETIMECOLOR",
2938 "EM_GETIMECOLOR",
2939 "EM_SETIMEOPTIONS",
2940 "EM_GETIMEOPTIONS",
2941 "EM_CONVPOSITION",
2942 "EM_UNKNOWN_USER_109",
2943 "EM_UNKNOWN_USER_110",
2944 "EM_UNKNOWN_USER_111",
2945 "EM_UNKNOWN_USER_112",
2946 "EM_UNKNOWN_USER_113",
2947 "EM_UNKNOWN_USER_114",
2948 "EM_UNKNOWN_USER_115",
2949 "EM_UNKNOWN_USER_116",
2950 "EM_UNKNOWN_USER_117",
2951 "EM_UNKNOWN_USER_118",
2952 "EM_UNKNOWN_USER_119",
2953 "EM_SETLANGOPTIONS",
2954 "EM_GETLANGOPTIONS",
2955 "EM_GETIMECOMPMODE",
2956 "EM_FINDTEXTW",
2957 "EM_FINDTEXTEXW",
2958 "EM_RECONVERSION",
2959 "EM_SETIMEMODEBIAS",
2960 "EM_GETIMEMODEBIAS"
2963 static const char *
2964 get_msg_name(UINT msg)
2966 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2967 return edit_messages[msg - EM_GETSEL];
2968 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2969 return richedit_messages[msg - EM_CANPASTE];
2970 return "";
2973 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2975 int x,y;
2976 BOOL isExact;
2977 ME_Cursor cursor; /* The start of the clicked text. */
2979 ENLINK info;
2980 x = (short)LOWORD(lParam);
2981 y = (short)HIWORD(lParam);
2982 ME_CharFromPos(editor, x, y, &cursor, &isExact);
2983 if (!isExact) return;
2985 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
2986 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
2987 { /* The clicked run has CFE_LINK set */
2988 info.nmhdr.hwndFrom = NULL;
2989 info.nmhdr.idFrom = 0;
2990 info.nmhdr.code = EN_LINK;
2991 info.msg = msg;
2992 info.wParam = wParam;
2993 info.lParam = lParam;
2994 cursor.nOffset = 0;
2995 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
2996 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
2997 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3001 #define UNSUPPORTED_MSG(e) \
3002 case e: \
3003 FIXME(#e ": stub\n"); \
3004 *phresult = S_FALSE; \
3005 return 0;
3007 /* Handle messages for windowless and windoweded richedit controls.
3009 * The LRESULT that is returned is a return value for window procs,
3010 * and the phresult parameter is the COM return code needed by the
3011 * text services interface. */
3012 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3013 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3015 *phresult = S_OK;
3017 switch(msg) {
3019 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3020 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3021 UNSUPPORTED_MSG(EM_FMTLINES)
3022 UNSUPPORTED_MSG(EM_FORMATRANGE)
3023 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3024 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3025 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3026 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3027 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3028 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3029 UNSUPPORTED_MSG(EM_GETREDONAME)
3030 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3031 UNSUPPORTED_MSG(EM_GETUNDONAME)
3032 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3033 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3034 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3035 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3036 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3037 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3038 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3039 UNSUPPORTED_MSG(EM_SETMARGINS)
3040 UNSUPPORTED_MSG(EM_SETPALETTE)
3041 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3042 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3043 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3045 /* Messages specific to Richedit controls */
3047 case EM_STREAMIN:
3048 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3049 case EM_STREAMOUT:
3050 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3051 case WM_GETDLGCODE:
3053 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3054 if (lParam)
3055 editor->bDialogMode = TRUE;
3056 if (editor->styleFlags & ES_MULTILINE)
3057 code |= DLGC_WANTMESSAGE;
3058 return code;
3060 case EM_EMPTYUNDOBUFFER:
3061 ME_EmptyUndoStack(editor);
3062 return 0;
3063 case EM_GETSEL:
3065 /* Note: wParam/lParam can be NULL */
3066 UINT from, to;
3067 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3068 PUINT pto = lParam ? (PUINT)lParam : &to;
3069 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3070 if ((*pfrom|*pto) & 0xFFFF0000)
3071 return -1;
3072 return MAKELONG(*pfrom,*pto);
3074 case EM_EXGETSEL:
3076 CHARRANGE *pRange = (CHARRANGE *)lParam;
3077 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3078 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3079 return 0;
3081 case EM_SETUNDOLIMIT:
3083 if ((int)wParam < 0)
3084 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3085 else
3086 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3087 /* Setting a max stack size keeps wine from getting killed
3088 for hogging memory. Windows allocates all this memory at once, so
3089 no program would realistically set a value above our maximum. */
3090 return editor->nUndoLimit;
3092 case EM_CANUNDO:
3093 return editor->pUndoStack != NULL;
3094 case EM_CANREDO:
3095 return editor->pRedoStack != NULL;
3096 case WM_UNDO: /* FIXME: actually not the same */
3097 case EM_UNDO:
3098 return ME_Undo(editor);
3099 case EM_REDO:
3100 return ME_Redo(editor);
3101 case EM_GETOPTIONS:
3103 /* these flags are equivalent to the ES_* counterparts */
3104 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3105 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3106 DWORD settings = editor->styleFlags & mask;
3108 return settings;
3110 case EM_SETOPTIONS:
3112 /* these flags are equivalent to ES_* counterparts, except for
3113 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3114 * but is still stored in editor->styleFlags. */
3115 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3116 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3117 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3118 DWORD settings = mask & editor->styleFlags;
3119 DWORD oldSettings = settings;
3120 DWORD changedSettings;
3122 switch(wParam)
3124 case ECOOP_SET:
3125 settings = lParam;
3126 break;
3127 case ECOOP_OR:
3128 settings |= lParam;
3129 break;
3130 case ECOOP_AND:
3131 settings &= lParam;
3132 break;
3133 case ECOOP_XOR:
3134 settings ^= lParam;
3136 changedSettings = oldSettings ^ settings;
3138 if (changedSettings) {
3139 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3141 if (changedSettings & ECO_SELECTIONBAR)
3143 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3144 if (settings & ECO_SELECTIONBAR) {
3145 assert(!editor->selofs);
3146 editor->selofs = SELECTIONBAR_WIDTH;
3147 editor->rcFormat.left += editor->selofs;
3148 } else {
3149 editor->rcFormat.left -= editor->selofs;
3150 editor->selofs = 0;
3152 ME_RewrapRepaint(editor);
3155 if (changedSettings & settings & ECO_VERTICAL)
3156 FIXME("ECO_VERTICAL not implemented yet!\n");
3157 if (changedSettings & settings & ECO_AUTOHSCROLL)
3158 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3159 if (changedSettings & settings & ECO_AUTOVSCROLL)
3160 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3161 if (changedSettings & settings & ECO_NOHIDESEL)
3162 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3163 if (changedSettings & settings & ECO_WANTRETURN)
3164 FIXME("ECO_WANTRETURN not implemented yet!\n");
3165 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3166 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3169 return settings;
3171 case EM_SETSEL:
3173 ME_InvalidateSelection(editor);
3174 ME_SetSelection(editor, wParam, lParam);
3175 ME_InvalidateSelection(editor);
3176 ITextHost_TxShowCaret(editor->texthost, FALSE);
3177 ME_ShowCaret(editor);
3178 ME_SendSelChange(editor);
3179 return 0;
3181 case EM_SETSCROLLPOS:
3183 POINT *point = (POINT *)lParam;
3184 ME_ScrollAbs(editor, point->x, point->y);
3185 return 0;
3187 case EM_AUTOURLDETECT:
3189 if (wParam==1 || wParam ==0)
3191 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3192 return 0;
3194 return E_INVALIDARG;
3196 case EM_GETAUTOURLDETECT:
3198 return editor->AutoURLDetect_bEnable;
3200 case EM_EXSETSEL:
3202 int end;
3203 CHARRANGE range = *(CHARRANGE *)lParam;
3205 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3207 ME_InvalidateSelection(editor);
3208 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3209 ME_InvalidateSelection(editor);
3210 ITextHost_TxShowCaret(editor->texthost, FALSE);
3211 ME_ShowCaret(editor);
3212 ME_SendSelChange(editor);
3214 return end;
3216 case EM_SHOWSCROLLBAR:
3218 DWORD flags;
3220 switch (wParam)
3222 case SB_HORZ:
3223 flags = WS_HSCROLL;
3224 break;
3225 case SB_VERT:
3226 flags = WS_VSCROLL;
3227 break;
3228 case SB_BOTH:
3229 flags = WS_HSCROLL|WS_VSCROLL;
3230 break;
3231 default:
3232 return 0;
3235 if (lParam) {
3236 editor->styleFlags |= flags;
3237 if (flags & WS_HSCROLL)
3238 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3239 editor->nTotalWidth > editor->sizeWindow.cx);
3240 if (flags & WS_VSCROLL)
3241 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3242 editor->nTotalLength > editor->sizeWindow.cy);
3243 } else {
3244 editor->styleFlags &= ~flags;
3245 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3247 return 0;
3249 case EM_SETTEXTEX:
3251 LPWSTR wszText;
3252 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3253 size_t len = 0;
3254 int from, to;
3255 ME_Style *style;
3256 BOOL bRtf, bUnicode, bSelection;
3257 int oldModify = editor->nModifyStep;
3259 if (!pStruct) return 0;
3261 /* If we detect ascii rtf at the start of the string,
3262 * we know it isn't unicode. */
3263 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3264 !strncmp((char *)lParam, "{\\urtf", 6)));
3265 bUnicode = !bRtf && pStruct->codepage == 1200;
3267 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3268 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3269 pStruct->flags, pStruct->codepage);
3271 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3272 if (bSelection) {
3273 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3274 style = ME_GetSelectionInsertStyle(editor);
3275 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3276 } else {
3277 ME_Cursor start;
3278 ME_SetCursorToStart(editor, &start);
3279 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3280 style = editor->pBuffer->pDefaultStyle;
3283 if (bRtf) {
3284 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3285 if (bSelection) {
3286 /* FIXME: The length returned doesn't include the rtf control
3287 * characters, only the actual text. */
3288 len = lParam ? strlen((char *)lParam) : 0;
3290 } else {
3291 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3292 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3293 len = wszText ? lstrlenW(wszText) : 0;
3294 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3295 ME_EndToUnicode(bUnicode, wszText);
3298 if (bSelection) {
3299 ME_ReleaseStyle(style);
3300 ME_UpdateSelectionLinkAttribute(editor);
3301 } else {
3302 ME_Cursor cursor;
3303 len = 1;
3304 ME_SetCursorToStart(editor, &cursor);
3305 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3307 ME_CommitUndo(editor);
3308 if (!(pStruct->flags & ST_KEEPUNDO))
3310 editor->nModifyStep = oldModify;
3311 ME_EmptyUndoStack(editor);
3313 ME_UpdateRepaint(editor, FALSE);
3314 return len;
3316 case EM_SETBKGNDCOLOR:
3318 LRESULT lColor;
3319 if (editor->rgbBackColor != -1) {
3320 DeleteObject(editor->hbrBackground);
3321 lColor = editor->rgbBackColor;
3323 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3325 if (wParam)
3327 editor->rgbBackColor = -1;
3328 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3330 else
3332 editor->rgbBackColor = lParam;
3333 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3335 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3336 ITextHost_TxViewChange(editor->texthost, TRUE);
3337 return lColor;
3339 case EM_GETMODIFY:
3340 return editor->nModifyStep == 0 ? 0 : -1;
3341 case EM_SETMODIFY:
3343 if (wParam)
3344 editor->nModifyStep = 1;
3345 else
3346 editor->nModifyStep = 0;
3348 return 0;
3350 case EM_SETREADONLY:
3352 if (wParam)
3353 editor->styleFlags |= ES_READONLY;
3354 else
3355 editor->styleFlags &= ~ES_READONLY;
3356 return 0;
3358 case EM_SETEVENTMASK:
3360 DWORD nOldMask = editor->nEventMask;
3362 editor->nEventMask = lParam;
3363 return nOldMask;
3365 case EM_GETEVENTMASK:
3366 return editor->nEventMask;
3367 case EM_SETCHARFORMAT:
3369 CHARFORMAT2W buf, *p;
3370 BOOL bRepaint = TRUE;
3371 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3372 if (p == NULL) return 0;
3373 if (wParam & SCF_ALL) {
3374 if (editor->mode & TM_PLAINTEXT) {
3375 ME_SetDefaultCharFormat(editor, p);
3376 } else {
3377 ME_Cursor start;
3378 ME_SetCursorToStart(editor, &start);
3379 ME_SetCharFormat(editor, &start, NULL, p);
3380 editor->nModifyStep = 1;
3382 } else if (wParam & SCF_SELECTION) {
3383 if (editor->mode & TM_PLAINTEXT)
3384 return 0;
3385 if (wParam & SCF_WORD) {
3386 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3387 return 0;
3389 bRepaint = ME_IsSelection(editor);
3390 ME_SetSelectionCharFormat(editor, p);
3391 if (bRepaint) editor->nModifyStep = 1;
3392 } else { /* SCF_DEFAULT */
3393 ME_SetDefaultCharFormat(editor, p);
3395 ME_CommitUndo(editor);
3396 if (bRepaint)
3398 ME_WrapMarkedParagraphs(editor);
3399 ME_UpdateScrollBar(editor);
3400 ME_Repaint(editor);
3402 return 1;
3404 case EM_GETCHARFORMAT:
3406 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3407 if (dst->cbSize != sizeof(CHARFORMATA) &&
3408 dst->cbSize != sizeof(CHARFORMATW) &&
3409 dst->cbSize != sizeof(CHARFORMAT2A) &&
3410 dst->cbSize != sizeof(CHARFORMAT2W))
3411 return 0;
3412 tmp.cbSize = sizeof(tmp);
3413 if (!wParam)
3414 ME_GetDefaultCharFormat(editor, &tmp);
3415 else
3416 ME_GetSelectionCharFormat(editor, &tmp);
3417 ME_CopyToCFAny(dst, &tmp);
3418 return tmp.dwMask;
3420 case EM_SETPARAFORMAT:
3422 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3423 ME_WrapMarkedParagraphs(editor);
3424 ME_UpdateScrollBar(editor);
3425 ME_Repaint(editor);
3426 ME_CommitUndo(editor);
3427 return result;
3429 case EM_GETPARAFORMAT:
3430 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3431 return ((PARAFORMAT2 *)lParam)->dwMask;
3432 case EM_GETFIRSTVISIBLELINE:
3434 ME_DisplayItem *p = editor->pBuffer->pFirst;
3435 int y = editor->vert_si.nPos;
3436 int ypara = 0;
3437 int count = 0;
3438 int ystart, yend;
3439 while(p) {
3440 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3441 if (p->type == diTextEnd)
3442 break;
3443 if (p->type == diParagraph) {
3444 ypara = p->member.para.pt.y;
3445 continue;
3447 ystart = ypara + p->member.row.pt.y;
3448 yend = ystart + p->member.row.nHeight;
3449 if (y < yend) {
3450 break;
3452 count++;
3454 return count;
3456 case EM_HIDESELECTION:
3458 editor->bHideSelection = (wParam != 0);
3459 ME_InvalidateSelection(editor);
3460 return 0;
3462 case EM_LINESCROLL:
3464 if (!(editor->styleFlags & ES_MULTILINE))
3465 return FALSE;
3466 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3467 return TRUE;
3469 case WM_CLEAR:
3471 int from, to;
3472 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3473 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3474 ME_CommitUndo(editor);
3475 ME_UpdateRepaint(editor, TRUE);
3476 return 0;
3478 case EM_REPLACESEL:
3480 int from, to, nStartCursor;
3481 ME_Style *style;
3482 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3483 size_t len = wszText ? lstrlenW(wszText) : 0;
3484 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3486 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3487 style = ME_GetSelectionInsertStyle(editor);
3488 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3489 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3490 ME_ReleaseStyle(style);
3491 /* drop temporary style if line end */
3493 * FIXME question: does abc\n mean: put abc,
3494 * clear temp style, put \n? (would require a change)
3496 if (len>0 && wszText[len-1] == '\n')
3497 ME_ClearTempStyle(editor);
3498 ME_EndToUnicode(unicode, wszText);
3499 ME_CommitUndo(editor);
3500 ME_UpdateSelectionLinkAttribute(editor);
3501 if (!wParam)
3502 ME_EmptyUndoStack(editor);
3503 ME_UpdateRepaint(editor, FALSE);
3504 return len;
3506 case EM_SCROLLCARET:
3507 ME_EnsureVisible(editor, &editor->pCursors[0]);
3508 return 0;
3509 case WM_SETFONT:
3511 LOGFONTW lf;
3512 CHARFORMAT2W fmt;
3513 HDC hDC;
3514 BOOL bRepaint = LOWORD(lParam);
3516 if (!wParam)
3517 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3518 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3519 hDC = ITextHost_TxGetDC(editor->texthost);
3520 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3521 ITextHost_TxReleaseDC(editor->texthost, hDC);
3522 if (editor->mode & TM_RICHTEXT) {
3523 ME_Cursor start;
3524 ME_SetCursorToStart(editor, &start);
3525 ME_SetCharFormat(editor, &start, NULL, &fmt);
3527 ME_SetDefaultCharFormat(editor, &fmt);
3529 ME_CommitUndo(editor);
3530 ME_MarkAllForWrapping(editor);
3531 ME_WrapMarkedParagraphs(editor);
3532 ME_UpdateScrollBar(editor);
3533 if (bRepaint)
3534 ME_Repaint(editor);
3535 return 0;
3537 case WM_SETTEXT:
3539 ME_Cursor cursor;
3540 ME_SetCursorToStart(editor, &cursor);
3541 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3542 if (lParam)
3544 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3545 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3546 !strncmp((char *)lParam, "{\\urtf", 6))
3548 /* Undocumented: WM_SETTEXT supports RTF text */
3549 ME_StreamInRTFString(editor, 0, (char *)lParam);
3551 else
3553 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3554 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3555 if (lstrlenW(wszText) > 0)
3557 int len = -1;
3559 /* uses default style! */
3560 if (!(editor->styleFlags & ES_MULTILINE))
3562 WCHAR * p;
3564 p = wszText;
3565 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3566 len = p - wszText;
3568 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3570 ME_EndToUnicode(unicode, wszText);
3573 else
3574 TRACE("WM_SETTEXT - NULL\n");
3575 ME_SetCursorToStart(editor, &cursor);
3576 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3577 ME_SetSelection(editor, 0, 0);
3578 editor->nModifyStep = 0;
3579 ME_CommitUndo(editor);
3580 ME_EmptyUndoStack(editor);
3581 ME_UpdateRepaint(editor, FALSE);
3582 return 1;
3584 case EM_CANPASTE:
3586 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3587 if (IsClipboardFormatAvailable(nRTFFormat))
3588 return TRUE;
3589 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3590 return TRUE;
3591 return FALSE;
3593 case WM_PASTE:
3594 case WM_MBUTTONDOWN:
3595 ME_Paste(editor);
3596 return 0;
3597 case WM_CUT:
3598 case WM_COPY:
3600 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3601 int nChars = nTo - nFrom;
3602 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3604 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3606 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3607 ME_CommitUndo(editor);
3608 ME_UpdateRepaint(editor, TRUE);
3610 return 0;
3612 case WM_GETTEXTLENGTH:
3614 GETTEXTLENGTHEX how;
3616 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3617 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3618 how.codepage = unicode ? 1200 : CP_ACP;
3619 return ME_GetTextLengthEx(editor, &how);
3621 case EM_GETTEXTLENGTHEX:
3622 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3623 case WM_GETTEXT:
3625 GETTEXTEX ex;
3626 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3627 ex.flags = GT_USECRLF;
3628 ex.codepage = unicode ? 1200 : CP_ACP;
3629 ex.lpDefaultChar = NULL;
3630 ex.lpUsedDefChar = NULL;
3631 return ME_GetTextEx(editor, &ex, lParam);
3633 case EM_GETTEXTEX:
3634 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3635 case EM_GETSELTEXT:
3637 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3638 ME_Cursor *from = &editor->pCursors[nStartCur];
3639 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3640 nTo - nFrom, unicode);
3642 case EM_GETSCROLLPOS:
3644 POINT *point = (POINT *)lParam;
3645 point->x = editor->horz_si.nPos;
3646 point->y = editor->vert_si.nPos;
3647 /* 16-bit scaled value is returned as stored in scrollinfo */
3648 if (editor->horz_si.nMax > 0xffff)
3649 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3650 if (editor->vert_si.nMax > 0xffff)
3651 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3652 return 1;
3654 case EM_GETTEXTRANGE:
3656 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3657 ME_Cursor start;
3658 int nStart = rng->chrg.cpMin;
3659 int nEnd = rng->chrg.cpMax;
3660 int textlength = ME_GetTextLength(editor);
3662 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3663 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3664 if (nStart < 0) return 0;
3665 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3666 nEnd = textlength;
3667 if (nStart >= nEnd) return 0;
3669 ME_CursorFromCharOfs(editor, nStart, &start);
3670 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3672 case EM_GETLINE:
3674 ME_DisplayItem *run;
3675 const unsigned int nMaxChars = *(WORD *) lParam;
3676 unsigned int nCharsLeft = nMaxChars;
3677 char *dest = (char *) lParam;
3678 BOOL wroteNull = FALSE;
3680 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3681 unicode ? "Unicode" : "Ansi");
3683 run = ME_FindRowWithNumber(editor, wParam);
3684 if (run == NULL)
3685 return 0;
3687 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3688 && run->type == diRun)
3690 unsigned int nCopy;
3691 ME_String *strText;
3693 strText = run->member.run.strText;
3694 nCopy = min(nCharsLeft, strText->nLen);
3696 if (unicode)
3697 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3698 else
3699 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3700 nCharsLeft, NULL, NULL);
3701 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3702 nCharsLeft -= nCopy;
3705 /* append line termination, space allowing */
3706 if (nCharsLeft > 0)
3708 if (unicode)
3709 *((WCHAR *)dest) = '\0';
3710 else
3711 *dest = '\0';
3712 nCharsLeft--;
3713 wroteNull = TRUE;
3716 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3717 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3719 case EM_GETLINECOUNT:
3721 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3722 int nRows = 0;
3724 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3726 while (item != editor->pBuffer->pLast)
3728 assert(item->type == diParagraph);
3729 prev_para = ME_FindItemBack(item, diRun);
3730 if (prev_para) {
3731 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3733 nRows += item->member.para.nRows;
3734 item = item->member.para.next_para;
3736 last_para = ME_FindItemBack(item, diRun);
3737 assert(last_para);
3738 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3739 if (editor->bEmulateVersion10 && prev_para &&
3740 last_para->member.run.nCharOfs == 0 &&
3741 prev_para->member.run.strText->nLen == 1 &&
3742 prev_para->member.run.strText->szData[0] == '\r')
3744 /* In 1.0 emulation, the last solitary \r at the very end of the text
3745 (if one exists) is NOT a line break.
3746 FIXME: this is an ugly hack. This should have a more regular model. */
3747 nRows--;
3750 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3751 return max(1, nRows);
3753 case EM_LINEFROMCHAR:
3755 if (wParam == -1)
3756 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3757 else
3758 return ME_RowNumberFromCharOfs(editor, wParam);
3760 case EM_EXLINEFROMCHAR:
3762 if (lParam == -1)
3763 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3764 else
3765 return ME_RowNumberFromCharOfs(editor, lParam);
3767 case EM_LINEINDEX:
3769 ME_DisplayItem *item, *para;
3770 int nCharOfs;
3772 if (wParam == -1)
3773 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3774 else
3775 item = ME_FindRowWithNumber(editor, wParam);
3776 if (!item)
3777 return -1;
3778 para = ME_GetParagraph(item);
3779 item = ME_FindItemFwd(item, diRun);
3780 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3781 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3782 return nCharOfs;
3784 case EM_LINELENGTH:
3786 ME_DisplayItem *item, *item_end;
3787 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3788 ME_DisplayItem *para, *run;
3790 if (wParam > ME_GetTextLength(editor))
3791 return 0;
3792 if (wParam == -1)
3794 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3795 return 0;
3797 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3798 item = ME_RowStart(run);
3799 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3800 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3801 if (item_end->type == diStartRow) {
3802 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3803 } else {
3804 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3805 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3806 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3808 nChars = nNextLineOfs - nThisLineOfs;
3809 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3810 return nChars;
3812 case EM_EXLIMITTEXT:
3814 if ((int)lParam < 0)
3815 return 0;
3816 if (lParam == 0)
3817 editor->nTextLimit = 65536;
3818 else
3819 editor->nTextLimit = (int) lParam;
3820 return 0;
3822 case EM_LIMITTEXT:
3824 if (wParam == 0)
3825 editor->nTextLimit = 65536;
3826 else
3827 editor->nTextLimit = (int) wParam;
3828 return 0;
3830 case EM_GETLIMITTEXT:
3832 return editor->nTextLimit;
3834 case EM_FINDTEXT:
3836 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3837 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3838 WCHAR *tmp;
3839 LRESULT r;
3841 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3842 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3843 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3844 FREE_OBJ( tmp );
3845 return r;
3847 case EM_FINDTEXTEX:
3849 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3850 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3851 WCHAR *tmp;
3852 LRESULT r;
3854 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3855 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3856 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3857 FREE_OBJ( tmp );
3858 return r;
3860 case EM_FINDTEXTW:
3862 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3863 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3865 case EM_FINDTEXTEXW:
3867 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3868 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3870 case EM_GETZOOM:
3871 if (!wParam || !lParam)
3872 return FALSE;
3873 *(int *)wParam = editor->nZoomNumerator;
3874 *(int *)lParam = editor->nZoomDenominator;
3875 return TRUE;
3876 case EM_SETZOOM:
3877 return ME_SetZoom(editor, wParam, lParam);
3878 case EM_CHARFROMPOS:
3880 ME_Cursor cursor;
3881 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3882 &cursor, NULL))
3883 return ME_GetCursorOfs(&cursor);
3884 else
3885 return -1;
3887 case EM_POSFROMCHAR:
3889 ME_DisplayItem *pPara, *pRun;
3890 int nCharOfs, nOffset, nLength;
3891 POINTL pt = {0,0};
3893 nCharOfs = wParam;
3894 /* detect which API version we're dealing with */
3895 if (wParam >= 0x40000)
3896 nCharOfs = lParam;
3897 nLength = ME_GetTextLength(editor);
3898 nCharOfs = min(nCharOfs, nLength);
3899 nCharOfs = max(nCharOfs, 0);
3901 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3902 assert(pRun->type == diRun);
3903 pt.y = pRun->member.run.pt.y;
3904 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3905 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3906 pt.x += editor->rcFormat.left;
3908 pt.x -= editor->horz_si.nPos;
3909 pt.y -= editor->vert_si.nPos;
3911 if (wParam >= 0x40000) {
3912 *(POINTL *)wParam = pt;
3914 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3916 case WM_CREATE:
3918 INT max;
3920 ME_SetDefaultFormatRect(editor);
3922 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3923 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3924 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3926 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3927 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3929 if (editor->styleFlags & ES_DISABLENOSCROLL)
3931 if (editor->styleFlags & WS_VSCROLL)
3933 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3934 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3936 if (editor->styleFlags & WS_HSCROLL)
3938 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3939 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3943 ME_CommitUndo(editor);
3944 ME_WrapMarkedParagraphs(editor);
3945 ME_MoveCaret(editor);
3946 return 0;
3948 case WM_DESTROY:
3949 ME_DestroyEditor(editor);
3950 return 0;
3951 case WM_SETCURSOR:
3953 return ME_SetCursor(editor);
3955 case WM_LBUTTONDBLCLK:
3956 case WM_LBUTTONDOWN:
3958 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3959 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3960 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3961 return 0;
3962 ITextHost_TxSetFocus(editor->texthost);
3963 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3964 ME_CalculateClickCount(editor, msg, wParam, lParam));
3965 ITextHost_TxSetCapture(editor->texthost, TRUE);
3966 editor->bMouseCaptured = TRUE;
3967 ME_LinkNotify(editor,msg,wParam,lParam);
3968 if (!ME_SetCursor(editor)) goto do_default;
3969 break;
3971 case WM_MOUSEMOVE:
3972 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3973 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3974 return 0;
3975 if (editor->bMouseCaptured)
3976 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3977 ME_LinkNotify(editor,msg,wParam,lParam);
3978 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3979 if (editor->bMouseCaptured)
3980 ME_SetCursor(editor);
3981 break;
3982 case WM_LBUTTONUP:
3983 if (editor->bMouseCaptured) {
3984 ITextHost_TxSetCapture(editor->texthost, FALSE);
3985 editor->bMouseCaptured = FALSE;
3987 if (editor->nSelectionType == stDocument)
3988 editor->nSelectionType = stPosition;
3989 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3990 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3991 return 0;
3992 else
3994 ME_SetCursor(editor);
3995 ME_LinkNotify(editor,msg,wParam,lParam);
3997 break;
3998 case WM_RBUTTONUP:
3999 case WM_RBUTTONDOWN:
4000 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4001 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4002 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4003 return 0;
4004 goto do_default;
4005 case WM_CONTEXTMENU:
4006 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4007 goto do_default;
4008 break;
4009 case WM_SETFOCUS:
4010 editor->bHaveFocus = TRUE;
4011 ME_ShowCaret(editor);
4012 ME_SendOldNotify(editor, EN_SETFOCUS);
4013 return 0;
4014 case WM_KILLFOCUS:
4015 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4016 editor->bHaveFocus = FALSE;
4017 ME_HideCaret(editor);
4018 ME_SendOldNotify(editor, EN_KILLFOCUS);
4019 return 0;
4020 case WM_COMMAND:
4021 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4022 return 0;
4023 case WM_KEYUP:
4024 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4025 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4026 return 0;
4027 goto do_default;
4028 case WM_KEYDOWN:
4029 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4030 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4031 return 0;
4032 if (ME_KeyDown(editor, LOWORD(wParam)))
4033 return 0;
4034 goto do_default;
4035 case WM_CHAR:
4036 return ME_Char(editor, wParam, lParam, unicode);
4037 case WM_UNICHAR:
4038 if (unicode)
4040 if(wParam == UNICODE_NOCHAR) return TRUE;
4041 if(wParam <= 0x000fffff)
4043 if(wParam > 0xffff) /* convert to surrogates */
4045 wParam -= 0x10000;
4046 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4047 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4048 } else {
4049 ME_Char(editor, wParam, 0, TRUE);
4052 return 0;
4054 break;
4055 case EM_STOPGROUPTYPING:
4056 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4057 return 0;
4058 case WM_HSCROLL:
4060 const int scrollUnit = 7;
4062 switch(LOWORD(wParam))
4064 case SB_LEFT:
4065 ME_ScrollAbs(editor, 0, 0);
4066 break;
4067 case SB_RIGHT:
4068 ME_ScrollAbs(editor,
4069 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4070 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4071 break;
4072 case SB_LINELEFT:
4073 ME_ScrollLeft(editor, scrollUnit);
4074 break;
4075 case SB_LINERIGHT:
4076 ME_ScrollRight(editor, scrollUnit);
4077 break;
4078 case SB_PAGELEFT:
4079 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4080 break;
4081 case SB_PAGERIGHT:
4082 ME_ScrollRight(editor, editor->sizeWindow.cx);
4083 break;
4084 case SB_THUMBTRACK:
4085 case SB_THUMBPOSITION:
4087 int pos = HIWORD(wParam);
4088 if (editor->horz_si.nMax > 0xffff)
4089 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4090 ME_HScrollAbs(editor, pos);
4091 break;
4094 break;
4096 case EM_SCROLL: /* fall through */
4097 case WM_VSCROLL:
4099 int origNPos;
4100 int lineHeight;
4102 origNPos = editor->vert_si.nPos;
4103 lineHeight = 24;
4105 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4106 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4107 if (lineHeight <= 0) lineHeight = 24;
4109 switch(LOWORD(wParam))
4111 case SB_TOP:
4112 ME_ScrollAbs(editor, 0, 0);
4113 break;
4114 case SB_BOTTOM:
4115 ME_ScrollAbs(editor,
4116 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4117 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4118 break;
4119 case SB_LINEUP:
4120 ME_ScrollUp(editor,lineHeight);
4121 break;
4122 case SB_LINEDOWN:
4123 ME_ScrollDown(editor,lineHeight);
4124 break;
4125 case SB_PAGEUP:
4126 ME_ScrollUp(editor,editor->sizeWindow.cy);
4127 break;
4128 case SB_PAGEDOWN:
4129 ME_ScrollDown(editor,editor->sizeWindow.cy);
4130 break;
4131 case SB_THUMBTRACK:
4132 case SB_THUMBPOSITION:
4134 int pos = HIWORD(wParam);
4135 if (editor->vert_si.nMax > 0xffff)
4136 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4137 ME_VScrollAbs(editor, pos);
4138 break;
4141 if (msg == EM_SCROLL)
4142 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4143 break;
4145 case WM_MOUSEWHEEL:
4147 int gcWheelDelta;
4148 UINT pulScrollLines;
4149 BOOL ctrl_is_down;
4151 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4152 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4153 return 0;
4155 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4157 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4159 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4161 if (ctrl_is_down) {
4162 int numerator;
4163 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4165 numerator = 100;
4166 } else {
4167 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4169 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4170 if (numerator >= 10 && numerator <= 500)
4171 ME_SetZoom(editor, numerator, 100);
4172 } else {
4173 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4174 /* FIXME follow the original */
4175 if (pulScrollLines)
4176 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4179 break;
4181 case EM_GETRECT:
4183 *((RECT *)lParam) = editor->rcFormat;
4184 if (editor->bDefaultFormatRect)
4185 ((RECT *)lParam)->left -= editor->selofs;
4186 return 0;
4188 case EM_SETRECT:
4189 case EM_SETRECTNP:
4191 if (lParam)
4193 int border = 0;
4194 RECT clientRect;
4195 RECT *rc = (RECT *)lParam;
4197 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4198 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4199 if (wParam == 0)
4201 editor->rcFormat.top = max(0, rc->top - border);
4202 editor->rcFormat.left = max(0, rc->left - border);
4203 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4204 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4205 } else if (wParam == 1) {
4206 /* MSDN incorrectly says a wParam value of 1 causes the
4207 * lParam rect to be used as a relative offset,
4208 * however, the tests show it just prevents min/max bound
4209 * checking. */
4210 editor->rcFormat.top = rc->top - border;
4211 editor->rcFormat.left = rc->left - border;
4212 editor->rcFormat.bottom = rc->bottom;
4213 editor->rcFormat.right = rc->right + border;
4214 } else {
4215 return 0;
4217 editor->bDefaultFormatRect = FALSE;
4219 else
4221 ME_SetDefaultFormatRect(editor);
4222 editor->bDefaultFormatRect = TRUE;
4224 ME_MarkAllForWrapping(editor);
4225 ME_WrapMarkedParagraphs(editor);
4226 ME_UpdateScrollBar(editor);
4227 if (msg != EM_SETRECTNP)
4228 ME_Repaint(editor);
4229 return 0;
4231 case EM_REQUESTRESIZE:
4232 ME_SendRequestResize(editor, TRUE);
4233 return 0;
4234 case WM_SETREDRAW:
4235 goto do_default;
4236 case WM_SIZE:
4238 RECT clientRect;
4240 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4241 if (editor->bDefaultFormatRect) {
4242 ME_SetDefaultFormatRect(editor);
4243 } else {
4244 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4245 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4247 editor->prevClientRect = clientRect;
4248 ME_RewrapRepaint(editor);
4249 goto do_default;
4251 /* IME messages to make richedit controls IME aware */
4252 case WM_IME_SETCONTEXT:
4253 case WM_IME_CONTROL:
4254 case WM_IME_SELECT:
4255 case WM_IME_COMPOSITIONFULL:
4256 return 0;
4257 case WM_IME_STARTCOMPOSITION:
4259 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4260 ME_DeleteSelection(editor);
4261 ME_CommitUndo(editor);
4262 ME_UpdateRepaint(editor, FALSE);
4263 return 0;
4265 case WM_IME_COMPOSITION:
4267 HIMC hIMC;
4269 ME_Style *style = ME_GetInsertStyle(editor, 0);
4270 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4271 ME_DeleteSelection(editor);
4272 ME_SaveTempStyle(editor);
4273 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4275 LPWSTR lpCompStr = NULL;
4276 DWORD dwBufLen;
4277 DWORD dwIndex = lParam & GCS_RESULTSTR;
4278 if (!dwIndex)
4279 dwIndex = GCS_COMPSTR;
4281 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4282 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4283 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4284 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4285 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4286 HeapFree(GetProcessHeap(), 0, lpCompStr);
4288 if (dwIndex == GCS_COMPSTR)
4289 ME_SetSelection(editor,editor->imeStartIndex,
4290 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4292 ME_ReleaseStyle(style);
4293 ME_CommitUndo(editor);
4294 ME_UpdateRepaint(editor, FALSE);
4295 return 0;
4297 case WM_IME_ENDCOMPOSITION:
4299 ME_DeleteSelection(editor);
4300 editor->imeStartIndex=-1;
4301 return 0;
4303 case EM_GETOLEINTERFACE:
4305 LPVOID *ppvObj = (LPVOID*) lParam;
4306 return CreateIRichEditOle(editor, ppvObj);
4308 case EM_GETPASSWORDCHAR:
4310 return editor->cPasswordMask;
4312 case EM_SETOLECALLBACK:
4313 if(editor->lpOleCallback)
4314 IRichEditOleCallback_Release(editor->lpOleCallback);
4315 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4316 if(editor->lpOleCallback)
4317 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4318 return TRUE;
4319 case EM_GETWORDBREAKPROC:
4320 return (LRESULT)editor->pfnWordBreak;
4321 case EM_SETWORDBREAKPROC:
4323 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4325 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4326 return (LRESULT)pfnOld;
4328 case EM_GETTEXTMODE:
4329 return editor->mode;
4330 case EM_SETTEXTMODE:
4332 int mask = 0;
4333 int changes = 0;
4335 if (ME_GetTextLength(editor) || editor->pUndoStack || editor->pRedoStack)
4336 return E_UNEXPECTED;
4338 /* Check for mutually exclusive flags in adjacent bits of wParam */
4339 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4340 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4341 return E_INVALIDARG;
4343 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4345 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4346 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4347 if (wParam & TM_PLAINTEXT) {
4348 /* Clear selection since it should be possible to select the
4349 * end of text run for rich text */
4350 ME_InvalidateSelection(editor);
4351 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4352 editor->pCursors[1] = editor->pCursors[0];
4353 /* plain text can only have the default style. */
4354 ME_ClearTempStyle(editor);
4355 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4356 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4357 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4360 /* FIXME: Currently no support for undo level and code page options */
4361 editor->mode = (editor->mode & ~mask) | changes;
4362 return 0;
4364 case EM_SETPASSWORDCHAR:
4366 editor->cPasswordMask = wParam;
4367 ME_RewrapRepaint(editor);
4368 return 0;
4370 case EM_SETTARGETDEVICE:
4371 if (wParam == 0)
4373 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4374 if (editor->nAvailWidth || editor->bWordWrap != new)
4376 editor->bWordWrap = new;
4377 editor->nAvailWidth = 0; /* wrap to client area */
4378 ME_RewrapRepaint(editor);
4380 } else {
4381 int width = max(0, lParam);
4382 if ((editor->styleFlags & ES_MULTILINE) &&
4383 (!editor->bWordWrap || editor->nAvailWidth != width))
4385 editor->nAvailWidth = width;
4386 editor->bWordWrap = TRUE;
4387 ME_RewrapRepaint(editor);
4389 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4391 return TRUE;
4392 default:
4393 do_default:
4394 *phresult = S_FALSE;
4395 break;
4397 return 0L;
4400 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4401 LPARAM lParam, BOOL unicode)
4403 ME_TextEditor *editor;
4404 HRESULT hresult;
4405 LRESULT lresult = 0;
4407 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4408 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4410 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4411 if (!editor)
4413 if (msg == WM_NCCREATE)
4415 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4416 ITextHost *texthost;
4418 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4419 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4420 return texthost != NULL;
4422 else
4424 return DefWindowProcW(hWnd, msg, wParam, lParam);
4428 switch (msg)
4430 case WM_PAINT:
4432 HDC hDC;
4433 RECT rc;
4434 PAINTSTRUCT ps;
4436 hDC = BeginPaint(editor->hWnd, &ps);
4437 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4438 ME_SendOldNotify(editor, EN_UPDATE);
4439 /* Erase area outside of the formatting rectangle */
4440 if (ps.rcPaint.top < editor->rcFormat.top)
4442 rc = ps.rcPaint;
4443 rc.bottom = editor->rcFormat.top;
4444 FillRect(hDC, &rc, editor->hbrBackground);
4445 ps.rcPaint.top = editor->rcFormat.top;
4447 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4448 rc = ps.rcPaint;
4449 rc.top = editor->rcFormat.bottom;
4450 FillRect(hDC, &rc, editor->hbrBackground);
4451 ps.rcPaint.bottom = editor->rcFormat.bottom;
4453 if (ps.rcPaint.left < editor->rcFormat.left) {
4454 rc = ps.rcPaint;
4455 rc.right = editor->rcFormat.left;
4456 FillRect(hDC, &rc, editor->hbrBackground);
4457 ps.rcPaint.left = editor->rcFormat.left;
4459 if (ps.rcPaint.right > editor->rcFormat.right) {
4460 rc = ps.rcPaint;
4461 rc.left = editor->rcFormat.right;
4462 FillRect(hDC, &rc, editor->hbrBackground);
4463 ps.rcPaint.right = editor->rcFormat.right;
4466 ME_PaintContent(editor, hDC, &ps.rcPaint);
4467 EndPaint(editor->hWnd, &ps);
4468 return 0;
4470 case WM_ERASEBKGND:
4472 HDC hDC = (HDC)wParam;
4473 RECT rc;
4475 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4476 FillRect(hDC, &rc, editor->hbrBackground);
4477 return 1;
4479 case EM_SETOPTIONS:
4481 DWORD dwStyle;
4482 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4483 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4484 ECO_SELECTIONBAR;
4485 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4486 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4487 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4488 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4489 return lresult;
4491 case EM_SETREADONLY:
4493 DWORD dwStyle;
4494 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4495 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4496 dwStyle &= ~ES_READONLY;
4497 if (wParam)
4498 dwStyle |= ES_READONLY;
4499 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4500 return lresult;
4502 default:
4503 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4506 if (hresult == S_FALSE)
4507 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4509 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4510 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4512 return lresult;
4515 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4517 BOOL unicode = TRUE;
4519 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4520 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4521 unicode = FALSE;
4523 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4526 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4528 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4531 /******************************************************************
4532 * RichEditANSIWndProc (RICHED20.10)
4534 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4536 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4539 /******************************************************************
4540 * RichEdit10ANSIWndProc (RICHED20.9)
4542 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4544 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4546 ITextHost *texthost;
4547 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4549 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4550 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4551 return texthost != NULL;
4553 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4556 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4558 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4561 /* Fill buffer with srcChars unicode characters from the start cursor.
4563 * buffer: destination buffer
4564 * buflen: length of buffer in characters excluding the NULL terminator.
4565 * start: start of editor text to copy into buffer.
4566 * srcChars: Number of characters to use from the editor text.
4567 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4569 * returns the number of characters written excluding the NULL terminator.
4571 * The written text is always NULL terminated.
4573 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4574 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4576 ME_DisplayItem *pRun, *pNextRun;
4577 const WCHAR *pStart = buffer;
4578 const WCHAR cr_lf[] = {'\r', '\n', 0};
4579 const WCHAR *str;
4580 int nLen;
4582 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4583 if (editor->bEmulateVersion10) bCRLF = 0;
4585 pRun = start->pRun;
4586 assert(pRun);
4587 pNextRun = ME_FindItemFwd(pRun, diRun);
4589 nLen = pRun->member.run.strText->nLen - start->nOffset;
4590 str = pRun->member.run.strText->szData + start->nOffset;
4592 /* No '\r' is appended to the last paragraph. */
4593 while (srcChars && buflen && pNextRun)
4595 int nFlags = pRun->member.run.nFlags;
4597 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4599 if (buflen == 1) break;
4600 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4601 * EM_GETTEXTEX, however, this is done for copying text which
4602 * also uses this function. */
4603 srcChars -= min(nLen, srcChars);
4604 nLen = 2;
4605 str = cr_lf;
4606 } else {
4607 nLen = min(nLen, srcChars);
4608 srcChars -= nLen;
4611 nLen = min(nLen, buflen);
4612 buflen -= nLen;
4614 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4616 buffer += nLen;
4618 pRun = pNextRun;
4619 pNextRun = ME_FindItemFwd(pRun, diRun);
4621 nLen = pRun->member.run.strText->nLen;
4622 str = pRun->member.run.strText->szData;
4624 *buffer = 0;
4625 return buffer - pStart;
4628 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4630 WNDCLASSW wcW;
4631 WNDCLASSA wcA;
4633 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4634 wcW.lpfnWndProc = RichEditWndProcW;
4635 wcW.cbClsExtra = 0;
4636 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4637 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4638 wcW.hIcon = NULL;
4639 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4640 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4641 wcW.lpszMenuName = NULL;
4643 if (is_version_nt())
4645 wcW.lpszClassName = RICHEDIT_CLASS20W;
4646 if (!RegisterClassW(&wcW)) return FALSE;
4647 wcW.lpszClassName = MSFTEDIT_CLASS;
4648 if (!RegisterClassW(&wcW)) return FALSE;
4650 else
4652 /* WNDCLASSA/W have the same layout */
4653 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4654 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4655 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4656 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4659 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4660 wcA.lpfnWndProc = RichEditWndProcA;
4661 wcA.cbClsExtra = 0;
4662 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4663 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4664 wcA.hIcon = NULL;
4665 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4666 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4667 wcA.lpszMenuName = NULL;
4668 wcA.lpszClassName = RICHEDIT_CLASS20A;
4669 if (!RegisterClassA(&wcA)) return FALSE;
4670 wcA.lpszClassName = "RichEdit50A";
4671 if (!RegisterClassA(&wcA)) return FALSE;
4673 return TRUE;
4676 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4677 /* FIXME: Not implemented */
4678 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4679 hWnd, msg, get_msg_name(msg), wParam, lParam);
4680 return DefWindowProcW(hWnd, msg, wParam, lParam);
4683 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4684 /* FIXME: Not implemented */
4685 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4686 hWnd, msg, get_msg_name(msg), wParam, lParam);
4687 return DefWindowProcW(hWnd, msg, wParam, lParam);
4690 /******************************************************************
4691 * REExtendedRegisterClass (RICHED20.8)
4693 * FIXME undocumented
4694 * Need to check for errors and implement controls and callbacks
4696 LRESULT WINAPI REExtendedRegisterClass(void)
4698 WNDCLASSW wcW;
4699 UINT result;
4701 FIXME("semi stub\n");
4703 wcW.cbClsExtra = 0;
4704 wcW.cbWndExtra = 4;
4705 wcW.hInstance = NULL;
4706 wcW.hIcon = NULL;
4707 wcW.hCursor = NULL;
4708 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4709 wcW.lpszMenuName = NULL;
4711 if (!ME_ListBoxRegistered)
4713 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4714 wcW.lpfnWndProc = REListWndProc;
4715 wcW.lpszClassName = REListBox20W;
4716 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4719 if (!ME_ComboBoxRegistered)
4721 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4722 wcW.lpfnWndProc = REComboWndProc;
4723 wcW.lpszClassName = REComboBox20W;
4724 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4727 result = 0;
4728 if (ME_ListBoxRegistered)
4729 result += 1;
4730 if (ME_ComboBoxRegistered)
4731 result += 2;
4733 return result;
4736 static BOOL isurlspecial(WCHAR c)
4738 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4739 return strchrW( special_chars, c ) != NULL;
4743 * This proc takes a selection, and scans it forward in order to select the span
4744 * of a possible URL candidate. A possible URL candidate must start with isalnum
4745 * or one of the following special characters: *|/\+%#@ and must consist entirely
4746 * of the characters allowed to start the URL, plus : (colon) which may occur
4747 * at most once, and not at either end.
4749 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4750 const ME_Cursor *start,
4751 int nChars,
4752 ME_Cursor *candidate_min,
4753 ME_Cursor *candidate_max)
4755 ME_Cursor cursor = *start;
4756 BOOL foundColon = FALSE;
4757 BOOL candidateStarted = FALSE;
4758 WCHAR lastAcceptedChar = '\0';
4760 while (nChars > 0)
4762 WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4763 WCHAR *str = strStart + cursor.nOffset;
4764 int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4765 nChars -= nLen;
4767 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4769 /* Find start of candidate */
4770 if (!candidateStarted)
4772 while (nLen)
4774 nLen--;
4775 if (isalnumW(*str) || isurlspecial(*str))
4777 cursor.nOffset = str - strStart;
4778 *candidate_min = cursor;
4779 candidateStarted = TRUE;
4780 lastAcceptedChar = *str++;
4781 break;
4783 str++;
4787 /* Find end of candidate */
4788 if (candidateStarted) {
4789 while (nLen)
4791 nLen--;
4792 if (*str == ':' && !foundColon) {
4793 foundColon = TRUE;
4794 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4795 cursor.nOffset = str - strStart;
4796 if (lastAcceptedChar == ':')
4797 ME_MoveCursorChars(editor, &cursor, -1);
4798 *candidate_max = cursor;
4799 return TRUE;
4801 lastAcceptedChar = *str++;
4804 } else {
4805 /* End of paragraph: skip it if before candidate span, or terminates
4806 current active span */
4807 if (candidateStarted) {
4808 if (lastAcceptedChar == ':')
4809 ME_MoveCursorChars(editor, &cursor, -1);
4810 *candidate_max = cursor;
4811 return TRUE;
4815 /* Reaching this point means no span was found, so get next span */
4816 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4817 if (candidateStarted) {
4818 /* There are no further runs, so take end of text as end of candidate */
4819 cursor.nOffset = str - strStart;
4820 if (lastAcceptedChar == ':')
4821 ME_MoveCursorChars(editor, &cursor, -1);
4822 *candidate_max = cursor;
4823 return TRUE;
4825 *candidate_max = *candidate_min = cursor;
4826 return FALSE;
4828 cursor.nOffset = 0;
4831 if (candidateStarted) {
4832 /* There are no further runs, so take end of text as end of candidate */
4833 if (lastAcceptedChar == ':')
4834 ME_MoveCursorChars(editor, &cursor, -1);
4835 *candidate_max = cursor;
4836 return TRUE;
4838 *candidate_max = *candidate_min = cursor;
4839 return FALSE;
4843 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4845 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4847 #define MAX_PREFIX_LEN 9
4848 struct prefix_s {
4849 const WCHAR text[MAX_PREFIX_LEN];
4850 int length;
4851 }prefixes[] = {
4852 {{'p','r','o','s','p','e','r','o',':'}, 9},
4853 {{'t','e','l','n','e','t',':'}, 7},
4854 {{'g','o','p','h','e','r',':'}, 7},
4855 {{'m','a','i','l','t','o',':'}, 7},
4856 {{'h','t','t','p','s',':'}, 6},
4857 {{'f','i','l','e',':'}, 5},
4858 {{'n','e','w','s',':'}, 5},
4859 {{'w','a','i','s',':'}, 5},
4860 {{'n','n','t','p',':'}, 5},
4861 {{'h','t','t','p',':'}, 5},
4862 {{'w','w','w','.'}, 4},
4863 {{'f','t','p',':'}, 4},
4865 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4866 unsigned int i;
4868 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4869 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4871 if (nChars < prefixes[i].length) continue;
4872 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4873 return TRUE;
4875 return FALSE;
4876 #undef MAX_PREFIX_LEN
4880 * This proc walks through the indicated selection and evaluates whether each
4881 * section identified by ME_FindNextURLCandidate and in-between sections have
4882 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4883 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4885 * Since this function can cause runs to be split, do not depend on the value
4886 * of the start cursor at the end of the function.
4888 * nChars may be set to INT_MAX to update to the end of the text.
4890 * Returns TRUE if at least one section was modified.
4892 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4894 BOOL modified = FALSE;
4895 ME_Cursor startCur = *start;
4897 if (!editor->AutoURLDetect_bEnable) return FALSE;
4901 CHARFORMAT2W link;
4902 ME_Cursor candidateStart, candidateEnd;
4904 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4905 &candidateStart, &candidateEnd))
4907 /* Section before candidate is not an URL */
4908 int cMin = ME_GetCursorOfs(&candidateStart);
4909 int cMax = ME_GetCursorOfs(&candidateEnd);
4911 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4912 candidateStart = candidateEnd;
4913 nChars -= cMax - ME_GetCursorOfs(&startCur);
4915 else
4917 /* No more candidates until end of selection */
4918 nChars = 0;
4921 if (startCur.pRun != candidateStart.pRun ||
4922 startCur.nOffset != candidateStart.nOffset)
4924 /* CFE_LINK effect should be consistently unset */
4925 link.cbSize = sizeof(link);
4926 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4927 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4929 /* CFE_LINK must be unset from this range */
4930 memset(&link, 0, sizeof(CHARFORMAT2W));
4931 link.cbSize = sizeof(link);
4932 link.dwMask = CFM_LINK;
4933 link.dwEffects = 0;
4934 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4935 /* Update candidateEnd since setting character formats may split
4936 * runs, which can cause a cursor to be at an invalid offset within
4937 * a split run. */
4938 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4940 candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4941 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4943 modified = TRUE;
4946 if (candidateStart.pRun != candidateEnd.pRun ||
4947 candidateStart.nOffset != candidateEnd.nOffset)
4949 /* CFE_LINK effect should be consistently set */
4950 link.cbSize = sizeof(link);
4951 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4952 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4954 /* CFE_LINK must be set on this range */
4955 memset(&link, 0, sizeof(CHARFORMAT2W));
4956 link.cbSize = sizeof(link);
4957 link.dwMask = CFM_LINK;
4958 link.dwEffects = CFE_LINK;
4959 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4960 modified = TRUE;
4963 startCur = candidateEnd;
4964 } while (nChars > 0);
4965 return modified;