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