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