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
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
54 - EM_GETLANGOPTIONS 2.0
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
67 + EM_GETSELTEXT (ANSI&Unicode)
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
94 - EM_SETBIDIOPTIONS 3.0
96 + EM_SETCHARFORMAT (partly done, no ANSI)
98 + EM_SETEVENTMASK (few notifications supported)
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
103 - EM_SETLANGOPTIONS 2.0
106 + EM_SETMODIFY (not sure if implementation is correct)
108 + EM_SETOPTIONS (partially implemented)
111 + EM_SETPASSWORDCHAR 2.0
112 - EM_SETPUNCTUATION 1.0asian
113 + EM_SETREADONLY no beep on modification attempt
115 + EM_SETRECTNP (EM_SETRECT without repainting)
117 + EM_SETSCROLLPOS 3.0
119 - EM_SETTARGETDEVICE (partial)
120 + EM_SETTEXTEX 3.0 (proper style?)
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
128 + EM_SHOWSCROLLBAR 2.0
129 + EM_STOPGROUPTYPING 2.0
137 + WM_GETDLGCODE (the current implementation is incomplete)
138 + WM_GETTEXT (ANSI&Unicode)
139 + WM_GETTEXTLENGTH (ANSI version sucks)
143 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144 + WM_STYLECHANGING (seems to do nothing)
145 + WM_STYLECHANGED (seems to do nothing)
151 * EN_CHANGE (sent from the wrong place)
168 * EN_UPDATE (sent from the wrong place)
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
179 - ES_MULTILINE (currently single line controls aren't supported)
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
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)
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
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
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?
230 #define NO_SHLWAPI_STREAM
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;
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);
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
278 buf->pCharStyle = NULL;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
288 LRESULT total_bytes_read = 0;
290 TRACE("%08x %p\n", dwFormat, stream);
297 ME_StreamInFill(stream);
298 if (stream->editstream->dwError)
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);
313 nWideChars = stream->dwSize >> 1;
314 pText = (WCHAR *)stream->buffer;
317 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
318 if (stream->dwSize == 0)
322 return total_bytes_read;
325 static void ME_ApplyBorderProperties(RTF_Info *info,
326 ME_BorderRect *borderRect,
327 RTFBorder *borderDef)
330 ME_Border *pBorders[] = {&borderRect->top,
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;
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);
347 pBorders[i]->colorRef = RGB(0, 0, 0);
351 void ME_RTFCharAttrHook(RTF_Info *info)
354 fmt.cbSize = sizeof(fmt);
358 switch(info->rtfMinor)
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;
369 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
370 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
371 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
374 fmt.dwMask = CFM_ITALIC;
375 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
378 fmt.dwMask = CFM_UNDERLINETYPE;
379 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
381 case rtfDotUnderline:
382 fmt.dwMask = CFM_UNDERLINETYPE;
383 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
386 fmt.dwMask = CFM_UNDERLINETYPE;
387 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
389 case rtfWordUnderline:
390 fmt.dwMask = CFM_UNDERLINETYPE;
391 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
394 fmt.dwMask = CFM_UNDERLINETYPE;
395 fmt.bUnderlineType = CFU_UNDERLINENONE;
398 fmt.dwMask = CFM_STRIKEOUT;
399 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
403 case rtfSubScrShrink:
404 case rtfSuperScrShrink:
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;
412 fmt.dwMask = CFM_HIDDEN;
413 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
416 fmt.dwMask = CFM_BACKCOLOR;
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);
426 fmt.dwEffects = CFE_AUTOBACKCOLOR;
430 fmt.dwMask = CFM_COLOR;
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);
440 fmt.dwEffects = CFE_AUTOCOLOR;
445 if (info->rtfParam != rtfNoParam)
447 RTFFont *f = RTFGetFont(info, info->rtfParam);
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);
459 fmt.dwMask = CFM_SIZE;
460 if (info->rtfParam != rtfNoParam)
461 fmt.yHeight = info->rtfParam*10;
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)
480 fmt.cbSize = sizeof(fmt);
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 |
493 /* TODO: numbering, shading */
494 fmt.wAlignment = PFA_LEFT;
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)
508 ME_DisplayItem *para;
509 /* We are just after a table row. */
510 RTFFlushOutputBuffer(info);
511 cursor = info->editor->pCursors[0];
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
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;
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;
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;
562 if (!info->editor->bEmulateVersion10) /* v4.1 */
564 if (info->nestingLevel < 1)
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;
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;
593 } else { /* v1.0 - v3.0 */
594 fmt.dwMask |= PFM_TABLE;
595 fmt.wEffects |= PFE_TABLE;
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;
606 ME_GetSelectionParaFormat(info->editor, &fmt);
607 fmt.dwMask = PFM_STARTINDENT;
608 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
611 fmt.dwMask = PFM_RIGHTINDENT;
612 fmt.dxRightIndent = info->rtfParam;
616 fmt.dwMask = PFM_ALIGNMENT;
617 fmt.wAlignment = PFA_LEFT;
620 fmt.dwMask = PFM_ALIGNMENT;
621 fmt.wAlignment = PFA_RIGHT;
624 fmt.dwMask = PFM_ALIGNMENT;
625 fmt.wAlignment = PFA_CENTER;
628 ME_GetSelectionParaFormat(info->editor, &fmt);
629 if (!(fmt.dwMask & PFM_TABSTOPS))
633 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
634 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
635 fmt.dwMask = PFM_TABSTOPS;
638 fmt.dwMask = PFM_KEEP;
639 fmt.wEffects = PFE_KEEP;
641 case rtfNoWidowControl:
642 fmt.dwMask = PFM_NOWIDOWCONTROL;
643 fmt.wEffects = PFE_NOWIDOWCONTROL;
646 fmt.dwMask = PFM_KEEPNEXT;
647 fmt.wEffects = PFE_KEEPNEXT;
650 fmt.dwMask = PFM_SPACEAFTER;
651 fmt.dySpaceAfter = info->rtfParam;
654 fmt.dwMask = PFM_SPACEBEFORE;
655 fmt.dySpaceBefore = info->rtfParam;
657 case rtfSpaceBetween:
658 fmt.dwMask = PFM_LINESPACING;
659 if ((int)info->rtfParam > 0)
661 fmt.dyLineSpacing = info->rtfParam;
662 fmt.bLineSpacingRule = 3;
666 fmt.dyLineSpacing = info->rtfParam;
667 fmt.bLineSpacingRule = 4;
670 case rtfSpaceMultiply:
671 fmt.dwMask = PFM_LINESPACING;
672 fmt.dyLineSpacing = info->rtfParam * 20;
673 fmt.bLineSpacingRule = 5;
676 fmt.dwMask = PFM_NUMBERING;
677 fmt.wNumbering = PFN_BULLET;
680 fmt.dwMask = PFM_NUMBERING;
681 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
683 case rtfParNumDecimal:
684 fmt.dwMask = PFM_NUMBERING;
685 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
687 case rtfParNumIndent:
688 fmt.dwMask = PFM_NUMBERINGTAB;
689 fmt.wNumberingTab = info->rtfParam;
691 case rtfParNumStartAt:
692 fmt.dwMask = PFM_NUMBERINGSTART;
693 fmt.wNumberingStart = info->rtfParam;
696 info->borderType = RTFBorderParaLeft;
697 ME_GetSelectionParaFormat(info->editor, &fmt);
698 if (!(fmt.dwMask & PFM_BORDER))
700 fmt.wBorderSpace = 0;
701 fmt.wBorderWidth = 1;
705 fmt.dwMask = PFM_BORDER;
708 info->borderType = RTFBorderParaRight;
709 ME_GetSelectionParaFormat(info->editor, &fmt);
710 if (!(fmt.dwMask & PFM_BORDER))
712 fmt.wBorderSpace = 0;
713 fmt.wBorderWidth = 1;
717 fmt.dwMask = PFM_BORDER;
720 info->borderType = RTFBorderParaTop;
721 ME_GetSelectionParaFormat(info->editor, &fmt);
722 if (!(fmt.dwMask & PFM_BORDER))
724 fmt.wBorderSpace = 0;
725 fmt.wBorderWidth = 1;
729 fmt.dwMask = PFM_BORDER;
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;
741 fmt.dwMask = PFM_BORDER;
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;
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;
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;
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;
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;
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)
788 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
790 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
791 border->width = info->rtfParam;
794 fmt.dwMask = PFM_BORDER;
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;
805 RTFTable *tableDef = info->tableDef;
806 int borderSide = info->borderType & RTFBorderSideMask;
807 int borderType = info->borderType & RTFBorderTypeMask;
810 case RTFBorderTypePara:
811 if (!info->editor->bEmulateVersion10) /* v4.1 */
813 /* v1.0 - 3.0 treat paragraph and row borders the same. */
814 case RTFBorderTypeRow:
816 tableDef->border[borderSide].color = info->rtfParam;
819 case RTFBorderTypeCell:
820 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
821 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
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)
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);
848 ME_InitTableDef(info->editor, info->tableDef);
857 info->tableDef = ME_MakeTableDef(info->editor);
859 cellNum = info->tableDef->numCellsDefined;
860 if (cellNum >= MAX_TABLE_CELLS)
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++;
875 info->borderType = RTFBorderRowTop;
878 info->borderType = RTFBorderRowLeft;
880 case rtfRowBordBottom:
881 info->borderType = RTFBorderRowBottom;
883 case rtfRowBordRight:
884 info->borderType = RTFBorderRowRight;
887 info->borderType = RTFBorderCellTop;
889 case rtfCellBordLeft:
890 info->borderType = RTFBorderCellLeft;
892 case rtfCellBordBottom:
893 info->borderType = RTFBorderCellBottom;
895 case rtfCellBordRight:
896 info->borderType = RTFBorderCellRight;
900 info->tableDef->gapH = info->rtfParam;
904 info->tableDef->leftEdge = info->rtfParam;
909 void ME_RTFSpecialCharHook(RTF_Info *info)
911 RTFTable *tableDef = info->tableDef;
912 switch (info->rtfMinor)
915 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
917 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
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)
943 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
944 tableDef->numCellsInserted++;
949 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
951 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
954 ME_DisplayItem *para, *cell, *run;
959 RTFFlushOutputBuffer(info);
960 if (!info->editor->bEmulateVersion10) { /* v4.1 */
961 if (!tableDef->tableRowStart)
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;
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,
997 cell = cell->member.cell.next_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)
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],
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, ¶->member.para.border,
1028 info->nestingLevel--;
1029 if (!info->nestingLevel)
1031 if (info->canInheritInTbl) {
1032 tableDef->tableRowStart = para;
1034 while (info->tableDef) {
1035 tableDef = info->tableDef;
1036 info->tableDef = tableDef->parent;
1037 heap_free(tableDef);
1041 info->tableDef = tableDef->parent;
1042 heap_free(tableDef);
1044 } else { /* v1.0 - v3.0 */
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, ¶->member.para.border,
1053 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
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;
1069 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1070 ME_DisplayItem *para;
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;
1088 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1091 LPOLEOBJECT lpObject = NULL;
1092 LPSTORAGE lpStorage = NULL;
1093 LPOLECLIENTSITE lpClientSite = NULL;
1094 LPDATAOBJECT lpDataObject = NULL;
1095 LPOLECACHE lpOleCache = NULL;
1104 stgm.tymed = TYMED_ENHMF;
1105 stgm.u.hEnhMetaFile = hemf;
1106 fm.cfFormat = CF_ENHMETAFILE;
1110 stgm.tymed = TYMED_GDI;
1111 stgm.u.hBitmap = hbmp;
1112 fm.cfFormat = CF_BITMAP;
1114 stgm.pUnkForRelease = NULL;
1117 fm.dwAspect = DVASPECT_CONTENT;
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 &&
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 &&
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)
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);
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);
1166 static void ME_RTFReadPictGroup(RTF_Info *info)
1169 BYTE* buffer = NULL;
1170 unsigned bufsz, bufidx;
1176 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1179 if (info->rtfClass == rtfEOF)
1182 /* fetch picture type */
1183 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1185 mfp.mm = info->rtfParam;
1188 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1190 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1193 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1195 gfx = gfx_enhmetafile;
1199 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1203 /* fetch picture attributes */
1207 if (info->rtfClass == rtfEOF)
1209 if (info->rtfClass == rtfText)
1211 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1213 ERR("Expected picture attribute (%d %d)\n",
1214 info->rtfClass, info->rtfMajor);
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;
1230 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1232 /* fetch picture data */
1235 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1236 val = info->rtfMajor;
1237 for (flip = TRUE;; flip = !flip)
1240 if (info->rtfClass == rtfEOF)
1242 HeapFree(GetProcessHeap(), 0, buffer);
1243 return; /* Warn ?? */
1245 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1247 if (info->rtfClass != rtfText) goto skip_group;
1250 if (bufidx >= bufsz &&
1251 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1253 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1256 val = info->rtfMajor;
1258 if (flip) FIXME("wrong hex string\n");
1262 case gfx_enhmetafile:
1263 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1264 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1267 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1268 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1272 BITMAPINFO* bi = (BITMAPINFO*)buffer;
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);
1289 HeapFree(GetProcessHeap(), 0, buffer);
1290 RTFRouteToken (info); /* feed "}" back to router */
1293 HeapFree(GetProcessHeap(), 0, buffer);
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)
1304 if (info->rtfClass == rtfEOF)
1306 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1308 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1311 if (info->rtfClass == rtfEOF)
1313 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
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);
1330 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1332 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1336 RTFRouteToken(info); /* feed "}" back to router */
1339 static void ME_RTFReadHook(RTF_Info *info)
1341 switch(info->rtfClass)
1344 switch(info->rtfMajor)
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;
1354 info->styleChanged = FALSE;
1358 RTFFlushOutputBuffer(info);
1360 if (info->stackTop <= 0)
1361 info->rtfClass = rtfEOF;
1362 if (info->stackTop < 0)
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;
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);
1386 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
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))
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);
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 != '{'))
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);
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);
1493 /* do the parsing */
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. */
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);
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
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);
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);
1608 typedef struct tagME_RTFStringStreamStruct
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;
1620 count = min(cb, pStruct->length - pStruct->pos);
1621 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1622 pStruct->pos += count;
1628 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1631 ME_RTFStringStreamStruct data;
1633 data.string = string;
1634 data.length = strlen(string);
1636 es.dwCookie = (DWORD_PTR)&data;
1637 es.pfnCallback = ME_ReadFromRTFString;
1638 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
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);
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));
1659 if (chrg->cpMax == -1)
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)
1670 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1671 if (editor->bEmulateVersion10 && nMax < nMin)
1675 chrgText->cpMin = -1;
1676 chrgText->cpMax = -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))
1690 nMax = nMin > nTextLen ? nTextLen : nMin;
1691 if (nMin < nSwap || chrg->cpMax == -1)
1697 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1700 chrgText->cpMin = chrgText->cpMax = -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);
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;
1722 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1724 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1728 if (nMatched == nLen)
1730 ME_DisplayItem *pNextItem = pCurItem;
1731 int nNextStart = nCurStart;
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;
1744 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1748 if (isalnumW(wNextChar))
1752 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
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;
1768 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1773 if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1775 ME_NextRun(&cursor.pPara, &cursor.pRun);
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);
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;
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))
1811 if (nMatched == nLen)
1813 ME_DisplayItem *pPrevItem = pCurItem;
1814 int nPrevEnd = nCurEnd;
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);
1825 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1829 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1833 if (isalnumW(wPrevChar))
1837 nStart = pCurPara->member.para.nCharOfs
1838 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1841 chrgText->cpMin = nStart;
1842 chrgText->cpMax = nStart + nLen;
1844 TRACE("found at %d-%d\n", nStart, nStart + nLen);
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;
1856 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
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");
1870 chrgText->cpMin = chrgText->cpMax = -1;
1874 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
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)
1887 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1888 start = editor->pCursors[nStartCur];
1893 ME_SetCursorToStart(editor, &start);
1896 if (ex->codepage == 1200)
1898 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1899 &start, nChars, ex->flags & GT_USECRLF);
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;
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 */
1926 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1927 const ME_Cursor *start, int nLen, BOOL unicode)
1929 if (!strText) return 0;
1931 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1934 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
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);
1944 typedef struct tagME_GlobalDestStruct
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;
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;
1964 GlobalUnlock(pData->hData);
1968 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1970 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
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;
1981 GlobalUnlock(pData->hData);
1985 static BOOL ME_Paste(ME_TextEditor *editor)
1989 ME_GlobalDestStruct gds;
1990 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
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;
2000 if (!OpenClipboard(editor->hWnd))
2002 gds.hData = GetClipboardData(cf);
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);
2012 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2014 LPDATAOBJECT dataObj = NULL;
2017 if (editor->cPasswordMask)
2018 return FALSE; /* Copying or Cutting masked text isn't allowed */
2020 if(editor->lpOleCallback)
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);
2030 hr = OleSetClipboard(dataObj);
2031 IDataObject_Release(dataObj);
2033 return SUCCEEDED(hr) != 0;
2036 /* helper to send a msg filter notification */
2038 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
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;
2047 msgf.wParam = *wParam;
2048 msgf.lParam = *lParam;
2049 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2051 *wParam = msgf.wParam;
2052 *lParam = msgf.lParam;
2053 msgf.wParam = *wParam;
2058 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2060 ME_DisplayItem *startPara, *endPara;
2061 ME_DisplayItem *prev_para;
2062 ME_Cursor *from, *to;
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);
2081 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2083 ME_UpdateLinkAttribute(editor, &start, nChars);
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)
2094 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2095 editor->nSelectionType = stPosition;
2103 editor->nUDArrowX = -1;
2109 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2110 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
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)
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);
2146 ME_MoveCursorFromTableRowStartParagraph(editor);
2147 ME_UpdateSelectionLinkAttribute(editor);
2148 ME_UpdateRepaint(editor, FALSE);
2149 ME_SendRequestResize(editor, FALSE);
2152 if (editor->bDialogMode)
2157 if (!(editor->styleFlags & ES_WANTRETURN))
2159 if (editor->hwndParent)
2162 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2163 if (HIWORD(dw) == DC_HASDEFID)
2165 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2168 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2169 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2177 if (editor->styleFlags & ES_MULTILINE)
2179 ME_Cursor cursor = editor->pCursors[0];
2180 ME_DisplayItem *para = cursor.pPara;
2182 const WCHAR endl = '\r';
2183 const WCHAR endlv10[] = {'\r','\n'};
2186 if (editor->styleFlags & ES_READONLY) {
2187 MessageBeep(MB_ICONERROR);
2191 ME_GetSelectionOfs(editor, &from, &to);
2192 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2194 if (!editor->bEmulateVersion10) { /* v4.1 */
2195 if (para->member.para.nFlags & MEPF_ROWEND) {
2196 /* Add a new table row after this row. */
2197 para = ME_AppendTableRow(editor, para);
2198 para = para->member.para.next_para;
2199 editor->pCursors[0].pPara = para;
2200 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2201 editor->pCursors[0].nOffset = 0;
2202 editor->pCursors[1] = editor->pCursors[0];
2203 ME_CommitUndo(editor);
2204 ME_CheckTablesForCorruption(editor);
2205 ME_UpdateRepaint(editor, FALSE);
2208 else if (para == editor->pCursors[1].pPara &&
2209 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2210 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2211 !para->member.para.prev_para->member.para.nCharOfs)
2213 /* Insert a newline before the table. */
2214 para = para->member.para.prev_para;
2215 para->member.para.nFlags &= ~MEPF_ROWSTART;
2216 editor->pCursors[0].pPara = para;
2217 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2218 editor->pCursors[1] = editor->pCursors[0];
2219 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2220 editor->pCursors[0].pRun->member.run.style);
2221 para = editor->pBuffer->pFirst->member.para.next_para;
2222 ME_SetDefaultParaFormat(para->member.para.pFmt);
2223 para->member.para.nFlags = MEPF_REWRAP;
2224 editor->pCursors[0].pPara = para;
2225 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2226 editor->pCursors[1] = editor->pCursors[0];
2227 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2228 ME_CommitCoalescingUndo(editor);
2229 ME_CheckTablesForCorruption(editor);
2230 ME_UpdateRepaint(editor, FALSE);
2233 } else { /* v1.0 - 3.0 */
2234 ME_DisplayItem *para = cursor.pPara;
2235 if (ME_IsInTable(para))
2237 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2240 ME_ContinueCoalescingTransaction(editor);
2241 para = ME_AppendTableRow(editor, para);
2242 editor->pCursors[0].pPara = para;
2243 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2244 editor->pCursors[0].nOffset = 0;
2245 editor->pCursors[1] = editor->pCursors[0];
2246 ME_CommitCoalescingUndo(editor);
2247 ME_UpdateRepaint(editor, FALSE);
2251 ME_ContinueCoalescingTransaction(editor);
2252 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2253 !ME_IsInTable(para->member.para.prev_para))
2255 /* Insert newline before table */
2256 cursor.pRun = ME_FindItemBack(para, diRun);
2258 editor->pCursors[0].pRun = cursor.pRun;
2259 editor->pCursors[0].pPara = para->member.para.prev_para;
2261 editor->pCursors[0].nOffset = 0;
2262 editor->pCursors[1] = editor->pCursors[0];
2263 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2264 editor->pCursors[0].pRun->member.run.style);
2266 editor->pCursors[1] = editor->pCursors[0];
2267 para = ME_AppendTableRow(editor, para);
2268 editor->pCursors[0].pPara = para;
2269 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2270 editor->pCursors[0].nOffset = 0;
2271 editor->pCursors[1] = editor->pCursors[0];
2273 ME_CommitCoalescingUndo(editor);
2274 ME_UpdateRepaint(editor, FALSE);
2280 style = ME_GetInsertStyle(editor, 0);
2281 ME_SaveTempStyle(editor);
2282 ME_ContinueCoalescingTransaction(editor);
2284 ME_InsertEndRowFromCursor(editor, 0);
2286 if (!editor->bEmulateVersion10)
2287 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2289 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2290 ME_ReleaseStyle(style);
2291 ME_CommitCoalescingUndo(editor);
2294 ME_UpdateSelectionLinkAttribute(editor);
2295 ME_UpdateRepaint(editor, FALSE);
2301 if (editor->bDialogMode && editor->hwndParent)
2302 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2305 if (editor->bDialogMode && editor->hwndParent)
2306 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2311 ME_SetSelection(editor, 0, -1);
2317 return ME_Paste(editor);
2325 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2326 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2329 result = ME_Copy(editor, selStart, nChars);
2330 if (result && nKey == 'X')
2332 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2333 ME_CommitUndo(editor);
2334 ME_UpdateRepaint(editor, TRUE);
2355 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2356 editor->nUDArrowX = -1;
2363 chf.cbSize = sizeof(chf);
2365 ME_GetSelectionCharFormat(editor, &chf);
2366 ME_DumpStyleToBuf(&chf, buf);
2367 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2371 ME_CheckCharOffsets(editor);
2378 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2379 LPARAM flags, BOOL unicode)
2383 if (editor->bMouseCaptured)
2387 wstr = (WCHAR)charCode;
2390 CHAR charA = charCode;
2391 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2394 if (editor->styleFlags & ES_READONLY) {
2395 MessageBeep(MB_ICONERROR);
2396 return 0; /* FIXME really 0 ? */
2399 if ((unsigned)wstr >= ' ' || wstr == '\t')
2401 ME_Cursor cursor = editor->pCursors[0];
2402 ME_DisplayItem *para = cursor.pPara;
2404 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2405 ME_GetSelectionOfs(editor, &from, &to);
2407 /* v4.1 allows tabs to be inserted with ctrl key down */
2408 !(ctrl_is_down && !editor->bEmulateVersion10))
2410 ME_DisplayItem *para;
2411 BOOL bSelectedRow = FALSE;
2413 para = cursor.pPara;
2414 if (ME_IsSelection(editor) &&
2415 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2416 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2417 para->member.para.prev_para->type == diParagraph)
2419 para = para->member.para.prev_para;
2420 bSelectedRow = TRUE;
2422 if (ME_IsInTable(para))
2424 ME_TabPressedInTable(editor, bSelectedRow);
2425 ME_CommitUndo(editor);
2428 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2429 if (para->member.para.nFlags & MEPF_ROWEND) {
2431 para = para->member.para.next_para;
2432 if (para->member.para.nFlags & MEPF_ROWSTART)
2433 para = para->member.para.next_para;
2434 editor->pCursors[0].pPara = para;
2435 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2436 editor->pCursors[0].nOffset = 0;
2437 editor->pCursors[1] = editor->pCursors[0];
2440 } else { /* v1.0 - 3.0 */
2441 if (ME_IsInTable(cursor.pRun) &&
2442 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2445 /* Text should not be inserted at the end of the table. */
2450 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2451 /* WM_CHAR is restricted to nTextLimit */
2452 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2454 ME_Style *style = ME_GetInsertStyle(editor, 0);
2455 ME_SaveTempStyle(editor);
2456 ME_ContinueCoalescingTransaction(editor);
2457 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2458 ME_ReleaseStyle(style);
2459 ME_CommitCoalescingUndo(editor);
2460 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2463 ME_UpdateSelectionLinkAttribute(editor);
2464 ME_UpdateRepaint(editor, FALSE);
2469 /* Process the message and calculate the new click count.
2471 * returns: The click count if it is mouse down event, else returns 0. */
2472 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2475 static int clickNum = 0;
2476 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2479 if ((msg == WM_LBUTTONDBLCLK) ||
2480 (msg == WM_RBUTTONDBLCLK) ||
2481 (msg == WM_MBUTTONDBLCLK) ||
2482 (msg == WM_XBUTTONDBLCLK))
2484 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2487 if ((msg == WM_LBUTTONDOWN) ||
2488 (msg == WM_RBUTTONDOWN) ||
2489 (msg == WM_MBUTTONDOWN) ||
2490 (msg == WM_XBUTTONDOWN))
2492 static MSG prevClickMsg;
2494 /* Compare the editor instead of the hwnd so that the this
2495 * can still be done for windowless richedit controls. */
2496 clickMsg.hwnd = (HWND)editor;
2497 clickMsg.message = msg;
2498 clickMsg.wParam = wParam;
2499 clickMsg.lParam = lParam;
2500 clickMsg.time = GetMessageTime();
2501 clickMsg.pt.x = (short)LOWORD(lParam);
2502 clickMsg.pt.y = (short)HIWORD(lParam);
2503 if ((clickNum != 0) &&
2504 (clickMsg.message == prevClickMsg.message) &&
2505 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2506 (clickMsg.wParam == prevClickMsg.wParam) &&
2507 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2508 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2509 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2515 prevClickMsg = clickMsg;
2522 static BOOL ME_SetCursor(ME_TextEditor *editor)
2528 DWORD messagePos = GetMessagePos();
2529 pt.x = (short)LOWORD(messagePos);
2530 pt.y = (short)HIWORD(messagePos);
2534 sbi.cbSize = sizeof(sbi);
2535 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2536 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2537 PtInRect(&sbi.rcScrollBar, pt))
2539 ITextHost_TxSetCursor(editor->texthost,
2540 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2543 sbi.cbSize = sizeof(sbi);
2544 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2545 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2546 PtInRect(&sbi.rcScrollBar, pt))
2548 ITextHost_TxSetCursor(editor->texthost,
2549 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2553 ITextHost_TxScreenToClient(editor->texthost, &pt);
2555 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2556 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2559 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2560 pt.y < editor->rcFormat.top &&
2561 pt.x < editor->rcFormat.left)
2563 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2566 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2568 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2569 ITextHost_TxSetCursor(editor->texthost,
2570 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2572 ITextHost_TxSetCursor(editor->texthost,
2573 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2576 if (pt.x < editor->rcFormat.left)
2578 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2581 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2586 run = &cursor.pRun->member.run;
2587 if (run->style->fmt.dwMask & CFM_LINK &&
2588 run->style->fmt.dwEffects & CFE_LINK)
2590 ITextHost_TxSetCursor(editor->texthost,
2591 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2596 if (ME_IsSelection(editor))
2598 int selStart, selEnd;
2599 int offset = ME_GetCursorOfs(&cursor);
2601 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2602 if (selStart <= offset && selEnd >= offset) {
2603 ITextHost_TxSetCursor(editor->texthost,
2604 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2610 ITextHost_TxSetCursor(editor->texthost,
2611 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2615 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2617 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2618 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2619 editor->rcFormat.left += 1 + editor->selofs;
2620 editor->rcFormat.right -= 1;
2623 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2628 if(!editor->lpOleCallback || !editor->hWnd)
2630 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2631 if(selrange.cpMin == selrange.cpMax)
2632 seltype |= SEL_EMPTY;
2635 /* FIXME: Handle objects */
2636 seltype |= SEL_TEXT;
2637 if(selrange.cpMax-selrange.cpMin > 1)
2638 seltype |= SEL_MULTICHAR;
2640 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2642 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2648 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2650 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2656 ed->hwndParent = NULL;
2657 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2658 ed->texthost = texthost;
2659 ed->bEmulateVersion10 = bEmulateVersion10;
2661 ITextHost_TxGetPropertyBits(texthost,
2662 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2663 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2664 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2665 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2666 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2668 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2669 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2670 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2671 ed->pBuffer = ME_MakeText();
2672 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2673 ed->nAvailWidth = 0; /* wrap to client area */
2674 ME_MakeFirstParagraph(ed);
2675 /* The four cursors are for:
2676 * 0 - The position where the caret is shown
2677 * 1 - The anchored end of the selection (for normal selection)
2678 * 2 & 3 - The anchored start and end respectively for word, line,
2679 * or paragraph selection.
2682 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2683 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2684 ed->pCursors[1] = ed->pCursors[0];
2685 ed->pCursors[2] = ed->pCursors[0];
2686 ed->pCursors[3] = ed->pCursors[1];
2687 ed->nLastTotalLength = ed->nTotalLength = 0;
2688 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2691 ed->rgbBackColor = -1;
2692 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2693 ed->bCaretAtEnd = FALSE;
2695 ed->nModifyStep = 0;
2696 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2697 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2698 ed->nUndoStackSize = 0;
2699 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2700 ed->nUndoMode = umAddToUndo;
2701 ed->nParagraphs = 1;
2702 ed->nLastSelStart = ed->nLastSelEnd = 0;
2703 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2704 ed->bHideSelection = FALSE;
2705 ed->pfnWordBreak = NULL;
2706 ed->lpOleCallback = NULL;
2707 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2708 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2709 ed->AutoURLDetect_bEnable = FALSE;
2710 ed->bHaveFocus = FALSE;
2711 ed->bDialogMode = FALSE;
2712 ed->bMouseCaptured = FALSE;
2713 for (i=0; i<HFONT_CACHE_SIZE; i++)
2715 ed->pFontCache[i].nRefs = 0;
2716 ed->pFontCache[i].nAge = 0;
2717 ed->pFontCache[i].hFont = NULL;
2720 ME_CheckCharOffsets(ed);
2721 ed->bDefaultFormatRect = TRUE;
2722 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2724 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2725 ed->selofs = SELECTIONBAR_WIDTH;
2726 ed->styleFlags |= ES_SELECTIONBAR;
2730 ed->nSelectionType = stPosition;
2732 ed->cPasswordMask = 0;
2733 if (props & TXTBIT_USEPASSWORD)
2734 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2736 if (props & TXTBIT_AUTOWORDSEL)
2737 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2738 if (props & TXTBIT_MULTILINE) {
2739 ed->styleFlags |= ES_MULTILINE;
2740 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2742 ed->bWordWrap = FALSE;
2744 if (props & TXTBIT_READONLY)
2745 ed->styleFlags |= ES_READONLY;
2746 if (!(props & TXTBIT_HIDESELECTION))
2747 ed->styleFlags |= ES_NOHIDESEL;
2748 if (props & TXTBIT_SAVESELECTION)
2749 ed->styleFlags |= ES_SAVESEL;
2750 if (props & TXTBIT_VERTICAL)
2751 ed->styleFlags |= ES_VERTICAL;
2752 if (props & TXTBIT_DISABLEDRAG)
2753 ed->styleFlags |= ES_NOOLEDRAGDROP;
2755 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2757 /* Default scrollbar information */
2758 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2759 ed->vert_si.nMin = 0;
2760 ed->vert_si.nMax = 0;
2761 ed->vert_si.nPage = 0;
2762 ed->vert_si.nPos = 0;
2764 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2765 ed->horz_si.nMin = 0;
2766 ed->horz_si.nMax = 0;
2767 ed->horz_si.nPage = 0;
2768 ed->horz_si.nPos = 0;
2770 OleInitialize(NULL);
2775 static void ME_DestroyEditor(ME_TextEditor *editor)
2777 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2778 ME_DisplayItem *p = pFirst, *pNext = NULL;
2781 ME_ClearTempStyle(editor);
2782 ME_EmptyUndoStack(editor);
2785 ME_DestroyDisplayItem(p);
2788 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2789 for (i=0; i<HFONT_CACHE_SIZE; i++)
2791 if (editor->pFontCache[i].hFont)
2792 DeleteObject(editor->pFontCache[i].hFont);
2794 if (editor->rgbBackColor != -1)
2795 DeleteObject(editor->hbrBackground);
2796 if(editor->lpOleCallback)
2797 IUnknown_Release(editor->lpOleCallback);
2798 IUnknown_Release(editor->texthost);
2801 FREE_OBJ(editor->pBuffer);
2802 FREE_OBJ(editor->pCursors);
2807 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2812 case DLL_PROCESS_ATTACH:
2813 DisableThreadLibraryCalls(hinstDLL);
2814 me_heap = HeapCreate (0, 0x10000, 0);
2815 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2816 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2820 case DLL_PROCESS_DETACH:
2821 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2822 UnregisterClassW(MSFTEDIT_CLASS, 0);
2823 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2824 UnregisterClassA("RichEdit50A", 0);
2825 if (ME_ListBoxRegistered)
2826 UnregisterClassW(REListBox20W, 0);
2827 if (ME_ComboBoxRegistered)
2828 UnregisterClassW(REComboBox20W, 0);
2830 HeapDestroy (me_heap);
2838 static const char * const edit_messages[] = {
2867 "EM_SETPASSWORDCHAR",
2868 "EM_EMPTYUNDOBUFFER",
2869 "EM_GETFIRSTVISIBLELINE",
2871 "EM_SETWORDBREAKPROC",
2872 "EM_GETWORDBREAKPROC",
2873 "EM_GETPASSWORDCHAR",
2883 static const char * const richedit_messages[] = {
2888 "EM_EXLINEFROMCHAR",
2894 "EM_GETOLEINTERFACE",
2904 "EM_SETOLECALLBACK",
2906 "EM_SETTARGETDEVICE",
2914 "EM_GETWORDBREAKPROCEX",
2915 "EM_SETWORDBREAKPROCEX",
2917 "EM_UNKNOWN_USER_83",
2922 "EM_STOPGROUPTYPING",
2926 "EM_GETAUTOURLDETECT",
2929 "EM_GETTEXTLENGTHEX",
2932 "EM_UNKNOWN_USER_98",
2933 "EM_UNKNOWN_USER_99",
2934 "EM_SETPUNCTUATION",
2935 "EM_GETPUNCTUATION",
2936 "EM_SETWORDWRAPMODE",
2937 "EM_GETWORDWRAPMODE",
2943 "EM_UNKNOWN_USER_109",
2944 "EM_UNKNOWN_USER_110",
2945 "EM_UNKNOWN_USER_111",
2946 "EM_UNKNOWN_USER_112",
2947 "EM_UNKNOWN_USER_113",
2948 "EM_UNKNOWN_USER_114",
2949 "EM_UNKNOWN_USER_115",
2950 "EM_UNKNOWN_USER_116",
2951 "EM_UNKNOWN_USER_117",
2952 "EM_UNKNOWN_USER_118",
2953 "EM_UNKNOWN_USER_119",
2954 "EM_SETLANGOPTIONS",
2955 "EM_GETLANGOPTIONS",
2956 "EM_GETIMECOMPMODE",
2960 "EM_SETIMEMODEBIAS",
2965 get_msg_name(UINT msg)
2967 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2968 return edit_messages[msg - EM_GETSEL];
2969 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2970 return richedit_messages[msg - EM_CANPASTE];
2974 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2978 ME_Cursor cursor; /* The start of the clicked text. */
2981 x = (short)LOWORD(lParam);
2982 y = (short)HIWORD(lParam);
2983 ME_CharFromPos(editor, x, y, &cursor, &isExact);
2984 if (!isExact) return;
2986 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
2987 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
2988 { /* The clicked run has CFE_LINK set */
2989 info.nmhdr.hwndFrom = NULL;
2990 info.nmhdr.idFrom = 0;
2991 info.nmhdr.code = EN_LINK;
2993 info.wParam = wParam;
2994 info.lParam = lParam;
2996 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
2997 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
2998 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3002 #define UNSUPPORTED_MSG(e) \
3004 FIXME(#e ": stub\n"); \
3005 *phresult = S_FALSE; \
3008 /* Handle messages for windowless and windoweded richedit controls.
3010 * The LRESULT that is returned is a return value for window procs,
3011 * and the phresult parameter is the COM return code needed by the
3012 * text services interface. */
3013 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3014 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3020 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3021 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3022 UNSUPPORTED_MSG(EM_FMTLINES)
3023 UNSUPPORTED_MSG(EM_FORMATRANGE)
3024 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3025 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3026 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3027 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3028 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3029 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3030 UNSUPPORTED_MSG(EM_GETREDONAME)
3031 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3032 UNSUPPORTED_MSG(EM_GETUNDONAME)
3033 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3034 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3035 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3036 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3037 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3038 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3039 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3040 UNSUPPORTED_MSG(EM_SETMARGINS)
3041 UNSUPPORTED_MSG(EM_SETPALETTE)
3042 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3043 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3044 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3046 /* Messages specific to Richedit controls */
3049 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3051 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3054 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3056 editor->bDialogMode = TRUE;
3057 if (editor->styleFlags & ES_MULTILINE)
3058 code |= DLGC_WANTMESSAGE;
3061 case EM_EMPTYUNDOBUFFER:
3062 ME_EmptyUndoStack(editor);
3066 /* Note: wParam/lParam can be NULL */
3068 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3069 PUINT pto = lParam ? (PUINT)lParam : &to;
3070 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3071 if ((*pfrom|*pto) & 0xFFFF0000)
3073 return MAKELONG(*pfrom,*pto);
3077 CHARRANGE *pRange = (CHARRANGE *)lParam;
3078 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3079 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3082 case EM_SETUNDOLIMIT:
3084 if ((int)wParam < 0)
3085 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3087 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3088 /* Setting a max stack size keeps wine from getting killed
3089 for hogging memory. Windows allocates all this memory at once, so
3090 no program would realistically set a value above our maximum. */
3091 return editor->nUndoLimit;
3094 return editor->pUndoStack != NULL;
3096 return editor->pRedoStack != NULL;
3097 case WM_UNDO: /* FIXME: actually not the same */
3099 return ME_Undo(editor);
3101 return ME_Redo(editor);
3104 /* these flags are equivalent to the ES_* counterparts */
3105 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3106 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3107 DWORD settings = editor->styleFlags & mask;
3113 /* these flags are equivalent to ES_* counterparts, except for
3114 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3115 * but is still stored in editor->styleFlags. */
3116 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3117 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3118 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3119 DWORD settings = mask & editor->styleFlags;
3120 DWORD oldSettings = settings;
3121 DWORD changedSettings;
3137 changedSettings = oldSettings ^ settings;
3139 if (changedSettings) {
3140 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3142 if (changedSettings & ECO_SELECTIONBAR)
3144 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3145 if (settings & ECO_SELECTIONBAR) {
3146 assert(!editor->selofs);
3147 editor->selofs = SELECTIONBAR_WIDTH;
3148 editor->rcFormat.left += editor->selofs;
3150 editor->rcFormat.left -= editor->selofs;
3153 ME_RewrapRepaint(editor);
3156 if (changedSettings & settings & ECO_VERTICAL)
3157 FIXME("ECO_VERTICAL not implemented yet!\n");
3158 if (changedSettings & settings & ECO_AUTOHSCROLL)
3159 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3160 if (changedSettings & settings & ECO_AUTOVSCROLL)
3161 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3162 if (changedSettings & settings & ECO_NOHIDESEL)
3163 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3164 if (changedSettings & settings & ECO_WANTRETURN)
3165 FIXME("ECO_WANTRETURN not implemented yet!\n");
3166 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3167 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3174 ME_InvalidateSelection(editor);
3175 ME_SetSelection(editor, wParam, lParam);
3176 ME_InvalidateSelection(editor);
3177 ITextHost_TxShowCaret(editor->texthost, FALSE);
3178 ME_ShowCaret(editor);
3179 ME_SendSelChange(editor);
3182 case EM_SETSCROLLPOS:
3184 POINT *point = (POINT *)lParam;
3185 ME_ScrollAbs(editor, point->x, point->y);
3188 case EM_AUTOURLDETECT:
3190 if (wParam==1 || wParam ==0)
3192 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3195 return E_INVALIDARG;
3197 case EM_GETAUTOURLDETECT:
3199 return editor->AutoURLDetect_bEnable;
3204 CHARRANGE range = *(CHARRANGE *)lParam;
3206 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3208 ME_InvalidateSelection(editor);
3209 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3210 ME_InvalidateSelection(editor);
3211 ITextHost_TxShowCaret(editor->texthost, FALSE);
3212 ME_ShowCaret(editor);
3213 ME_SendSelChange(editor);
3217 case EM_SHOWSCROLLBAR:
3230 flags = WS_HSCROLL|WS_VSCROLL;
3237 editor->styleFlags |= flags;
3238 if (flags & WS_HSCROLL)
3239 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3240 editor->nTotalWidth > editor->sizeWindow.cx);
3241 if (flags & WS_VSCROLL)
3242 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3243 editor->nTotalLength > editor->sizeWindow.cy);
3245 editor->styleFlags &= ~flags;
3246 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3253 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3257 BOOL bRtf, bUnicode, bSelection;
3258 int oldModify = editor->nModifyStep;
3260 if (!pStruct) return 0;
3262 /* If we detect ascii rtf at the start of the string,
3263 * we know it isn't unicode. */
3264 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3265 !strncmp((char *)lParam, "{\\urtf", 6)));
3266 bUnicode = !bRtf && pStruct->codepage == 1200;
3268 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3269 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3270 pStruct->flags, pStruct->codepage);
3272 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3274 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3275 style = ME_GetSelectionInsertStyle(editor);
3276 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3279 ME_SetCursorToStart(editor, &start);
3280 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3281 style = editor->pBuffer->pDefaultStyle;
3285 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3287 /* FIXME: The length returned doesn't include the rtf control
3288 * characters, only the actual text. */
3289 len = lParam ? strlen((char *)lParam) : 0;
3292 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3293 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3294 len = wszText ? lstrlenW(wszText) : 0;
3295 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3296 ME_EndToUnicode(bUnicode, wszText);
3300 ME_ReleaseStyle(style);
3301 ME_UpdateSelectionLinkAttribute(editor);
3305 ME_SetCursorToStart(editor, &cursor);
3306 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3308 ME_CommitUndo(editor);
3309 if (!(pStruct->flags & ST_KEEPUNDO))
3311 editor->nModifyStep = oldModify;
3312 ME_EmptyUndoStack(editor);
3314 ME_UpdateRepaint(editor, FALSE);
3317 case EM_SETBKGNDCOLOR:
3320 if (editor->rgbBackColor != -1) {
3321 DeleteObject(editor->hbrBackground);
3322 lColor = editor->rgbBackColor;
3324 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3328 editor->rgbBackColor = -1;
3329 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3333 editor->rgbBackColor = lParam;
3334 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3336 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3337 ITextHost_TxViewChange(editor->texthost, TRUE);
3341 return editor->nModifyStep == 0 ? 0 : -1;
3345 editor->nModifyStep = 1;
3347 editor->nModifyStep = 0;
3351 case EM_SETREADONLY:
3354 editor->styleFlags |= ES_READONLY;
3356 editor->styleFlags &= ~ES_READONLY;
3359 case EM_SETEVENTMASK:
3361 DWORD nOldMask = editor->nEventMask;
3363 editor->nEventMask = lParam;
3366 case EM_GETEVENTMASK:
3367 return editor->nEventMask;
3368 case EM_SETCHARFORMAT:
3370 CHARFORMAT2W buf, *p;
3371 BOOL bRepaint = TRUE;
3372 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3373 if (p == NULL) return 0;
3374 if (wParam & SCF_ALL) {
3375 if (editor->mode & TM_PLAINTEXT) {
3376 ME_SetDefaultCharFormat(editor, p);
3379 ME_SetCursorToStart(editor, &start);
3380 ME_SetCharFormat(editor, &start, NULL, p);
3381 editor->nModifyStep = 1;
3383 } else if (wParam & SCF_SELECTION) {
3384 if (editor->mode & TM_PLAINTEXT)
3386 if (wParam & SCF_WORD) {
3387 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3390 bRepaint = ME_IsSelection(editor);
3391 ME_SetSelectionCharFormat(editor, p);
3392 if (bRepaint) editor->nModifyStep = 1;
3393 } else { /* SCF_DEFAULT */
3394 ME_SetDefaultCharFormat(editor, p);
3396 ME_CommitUndo(editor);
3399 ME_WrapMarkedParagraphs(editor);
3400 ME_UpdateScrollBar(editor);
3405 case EM_GETCHARFORMAT:
3407 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3408 if (dst->cbSize != sizeof(CHARFORMATA) &&
3409 dst->cbSize != sizeof(CHARFORMATW) &&
3410 dst->cbSize != sizeof(CHARFORMAT2A) &&
3411 dst->cbSize != sizeof(CHARFORMAT2W))
3413 tmp.cbSize = sizeof(tmp);
3415 ME_GetDefaultCharFormat(editor, &tmp);
3417 ME_GetSelectionCharFormat(editor, &tmp);
3418 ME_CopyToCFAny(dst, &tmp);
3421 case EM_SETPARAFORMAT:
3423 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3424 ME_WrapMarkedParagraphs(editor);
3425 ME_UpdateScrollBar(editor);
3427 ME_CommitUndo(editor);
3430 case EM_GETPARAFORMAT:
3431 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3432 return ((PARAFORMAT2 *)lParam)->dwMask;
3433 case EM_GETFIRSTVISIBLELINE:
3435 ME_DisplayItem *p = editor->pBuffer->pFirst;
3436 int y = editor->vert_si.nPos;
3441 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3442 if (p->type == diTextEnd)
3444 if (p->type == diParagraph) {
3445 ypara = p->member.para.pt.y;
3448 ystart = ypara + p->member.row.pt.y;
3449 yend = ystart + p->member.row.nHeight;
3457 case EM_HIDESELECTION:
3459 editor->bHideSelection = (wParam != 0);
3460 ME_InvalidateSelection(editor);
3465 if (!(editor->styleFlags & ES_MULTILINE))
3467 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3473 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3474 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3475 ME_CommitUndo(editor);
3476 ME_UpdateRepaint(editor, TRUE);
3481 int from, to, nStartCursor;
3483 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3484 size_t len = wszText ? lstrlenW(wszText) : 0;
3485 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3487 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3488 style = ME_GetSelectionInsertStyle(editor);
3489 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3490 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3491 ME_ReleaseStyle(style);
3492 /* drop temporary style if line end */
3494 * FIXME question: does abc\n mean: put abc,
3495 * clear temp style, put \n? (would require a change)
3497 if (len>0 && wszText[len-1] == '\n')
3498 ME_ClearTempStyle(editor);
3499 ME_EndToUnicode(unicode, wszText);
3500 ME_CommitUndo(editor);
3501 ME_UpdateSelectionLinkAttribute(editor);
3503 ME_EmptyUndoStack(editor);
3504 ME_UpdateRepaint(editor, FALSE);
3507 case EM_SCROLLCARET:
3508 ME_EnsureVisible(editor, &editor->pCursors[0]);
3515 BOOL bRepaint = LOWORD(lParam);
3518 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3519 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3520 hDC = ITextHost_TxGetDC(editor->texthost);
3521 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3522 ITextHost_TxReleaseDC(editor->texthost, hDC);
3523 if (editor->mode & TM_RICHTEXT) {
3525 ME_SetCursorToStart(editor, &start);
3526 ME_SetCharFormat(editor, &start, NULL, &fmt);
3528 ME_SetDefaultCharFormat(editor, &fmt);
3530 ME_CommitUndo(editor);
3531 ME_MarkAllForWrapping(editor);
3532 ME_WrapMarkedParagraphs(editor);
3533 ME_UpdateScrollBar(editor);
3541 ME_SetCursorToStart(editor, &cursor);
3542 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3545 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3546 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3547 !strncmp((char *)lParam, "{\\urtf", 6))
3549 /* Undocumented: WM_SETTEXT supports RTF text */
3550 ME_StreamInRTFString(editor, 0, (char *)lParam);
3554 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3555 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3556 if (lstrlenW(wszText) > 0)
3560 /* uses default style! */
3561 if (!(editor->styleFlags & ES_MULTILINE))
3566 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3569 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3571 ME_EndToUnicode(unicode, wszText);
3575 TRACE("WM_SETTEXT - NULL\n");
3576 ME_SetCursorToStart(editor, &cursor);
3577 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3578 ME_SetSelection(editor, 0, 0);
3579 editor->nModifyStep = 0;
3580 ME_CommitUndo(editor);
3581 ME_EmptyUndoStack(editor);
3582 ME_UpdateRepaint(editor, FALSE);
3587 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3588 if (IsClipboardFormatAvailable(nRTFFormat))
3590 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3600 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3601 int nChars = nTo - nFrom;
3602 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3604 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3606 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3607 ME_CommitUndo(editor);
3608 ME_UpdateRepaint(editor, TRUE);
3612 case WM_GETTEXTLENGTH:
3614 GETTEXTLENGTHEX how;
3616 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3617 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3618 how.codepage = unicode ? 1200 : CP_ACP;
3619 return ME_GetTextLengthEx(editor, &how);
3621 case EM_GETTEXTLENGTHEX:
3622 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3626 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3627 ex.flags = GT_USECRLF;
3628 ex.codepage = unicode ? 1200 : CP_ACP;
3629 ex.lpDefaultChar = NULL;
3630 ex.lpUsedDefChar = NULL;
3631 return ME_GetTextEx(editor, &ex, lParam);
3634 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3637 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3638 ME_Cursor *from = &editor->pCursors[nStartCur];
3639 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3640 nTo - nFrom, unicode);
3642 case EM_GETSCROLLPOS:
3644 POINT *point = (POINT *)lParam;
3645 point->x = editor->horz_si.nPos;
3646 point->y = editor->vert_si.nPos;
3647 /* 16-bit scaled value is returned as stored in scrollinfo */
3648 if (editor->horz_si.nMax > 0xffff)
3649 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3650 if (editor->vert_si.nMax > 0xffff)
3651 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3654 case EM_GETTEXTRANGE:
3656 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3658 int nStart = rng->chrg.cpMin;
3659 int nEnd = rng->chrg.cpMax;
3660 int textlength = ME_GetTextLength(editor);
3662 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3663 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3664 if (nStart < 0) return 0;
3665 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3667 if (nStart >= nEnd) return 0;
3669 ME_CursorFromCharOfs(editor, nStart, &start);
3670 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3674 ME_DisplayItem *run;
3675 const unsigned int nMaxChars = *(WORD *) lParam;
3676 unsigned int nCharsLeft = nMaxChars;
3677 char *dest = (char *) lParam;
3678 BOOL wroteNull = FALSE;
3680 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3681 unicode ? "Unicode" : "Ansi");
3683 run = ME_FindRowWithNumber(editor, wParam);
3687 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3688 && run->type == diRun)
3693 strText = run->member.run.strText;
3694 nCopy = min(nCharsLeft, strText->nLen);
3697 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3699 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3700 nCharsLeft, NULL, NULL);
3701 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3702 nCharsLeft -= nCopy;
3705 /* append line termination, space allowing */
3709 *((WCHAR *)dest) = '\0';
3716 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3717 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3719 case EM_GETLINECOUNT:
3721 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3724 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3726 while (item != editor->pBuffer->pLast)
3728 assert(item->type == diParagraph);
3729 prev_para = ME_FindItemBack(item, diRun);
3731 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3733 nRows += item->member.para.nRows;
3734 item = item->member.para.next_para;
3736 last_para = ME_FindItemBack(item, diRun);
3738 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3739 if (editor->bEmulateVersion10 && prev_para &&
3740 last_para->member.run.nCharOfs == 0 &&
3741 prev_para->member.run.strText->nLen == 1 &&
3742 prev_para->member.run.strText->szData[0] == '\r')
3744 /* In 1.0 emulation, the last solitary \r at the very end of the text
3745 (if one exists) is NOT a line break.
3746 FIXME: this is an ugly hack. This should have a more regular model. */
3750 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3751 return max(1, nRows);
3753 case EM_LINEFROMCHAR:
3756 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3758 return ME_RowNumberFromCharOfs(editor, wParam);
3760 case EM_EXLINEFROMCHAR:
3763 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3765 return ME_RowNumberFromCharOfs(editor, lParam);
3769 ME_DisplayItem *item, *para;
3773 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3775 item = ME_FindRowWithNumber(editor, wParam);
3778 para = ME_GetParagraph(item);
3779 item = ME_FindItemFwd(item, diRun);
3780 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3781 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3786 ME_DisplayItem *item, *item_end;
3787 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3788 ME_DisplayItem *para, *run;
3790 if (wParam > ME_GetTextLength(editor))
3794 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3797 ME_RunOfsFromCharOfs(editor, wParam, ¶, &run, NULL);
3798 item = ME_RowStart(run);
3799 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3800 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3801 if (item_end->type == diStartRow) {
3802 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3804 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3805 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3806 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3808 nChars = nNextLineOfs - nThisLineOfs;
3809 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3812 case EM_EXLIMITTEXT:
3814 if ((int)lParam < 0)
3817 editor->nTextLimit = 65536;
3819 editor->nTextLimit = (int) lParam;
3825 editor->nTextLimit = 65536;
3827 editor->nTextLimit = (int) wParam;
3830 case EM_GETLIMITTEXT:
3832 return editor->nTextLimit;
3836 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3837 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3841 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3842 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3843 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3849 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3850 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3854 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3855 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3856 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3862 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3863 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3865 case EM_FINDTEXTEXW:
3867 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3868 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3871 if (!wParam || !lParam)
3873 *(int *)wParam = editor->nZoomNumerator;
3874 *(int *)lParam = editor->nZoomDenominator;
3877 return ME_SetZoom(editor, wParam, lParam);
3878 case EM_CHARFROMPOS:
3881 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3883 return ME_GetCursorOfs(&cursor);
3887 case EM_POSFROMCHAR:
3889 ME_DisplayItem *pPara, *pRun;
3890 int nCharOfs, nOffset, nLength;
3894 /* detect which API version we're dealing with */
3895 if (wParam >= 0x40000)
3897 nLength = ME_GetTextLength(editor);
3898 nCharOfs = min(nCharOfs, nLength);
3899 nCharOfs = max(nCharOfs, 0);
3901 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3902 assert(pRun->type == diRun);
3903 pt.y = pRun->member.run.pt.y;
3904 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3905 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3906 pt.x += editor->rcFormat.left;
3908 pt.x -= editor->horz_si.nPos;
3909 pt.y -= editor->vert_si.nPos;
3911 if (wParam >= 0x40000) {
3912 *(POINTL *)wParam = pt;
3914 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3920 ME_SetDefaultFormatRect(editor);
3922 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3923 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3924 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3926 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3927 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3929 if (editor->styleFlags & ES_DISABLENOSCROLL)
3931 if (editor->styleFlags & WS_VSCROLL)
3933 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3934 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3936 if (editor->styleFlags & WS_HSCROLL)
3938 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3939 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3943 ME_CommitUndo(editor);
3944 ME_WrapMarkedParagraphs(editor);
3945 ME_MoveCaret(editor);
3949 ME_DestroyEditor(editor);
3953 return ME_SetCursor(editor);
3955 case WM_LBUTTONDBLCLK:
3956 case WM_LBUTTONDOWN:
3958 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3959 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3960 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3962 ITextHost_TxSetFocus(editor->texthost);
3963 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3964 ME_CalculateClickCount(editor, msg, wParam, lParam));
3965 ITextHost_TxSetCapture(editor->texthost, TRUE);
3966 editor->bMouseCaptured = TRUE;
3967 ME_LinkNotify(editor,msg,wParam,lParam);
3968 if (!ME_SetCursor(editor)) goto do_default;
3972 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3973 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3975 if (editor->bMouseCaptured)
3976 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3977 ME_LinkNotify(editor,msg,wParam,lParam);
3978 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3979 if (editor->bMouseCaptured)
3980 ME_SetCursor(editor);
3983 if (editor->bMouseCaptured) {
3984 ITextHost_TxSetCapture(editor->texthost, FALSE);
3985 editor->bMouseCaptured = FALSE;
3987 if (editor->nSelectionType == stDocument)
3988 editor->nSelectionType = stPosition;
3989 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3990 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3994 ME_SetCursor(editor);
3995 ME_LinkNotify(editor,msg,wParam,lParam);
3999 case WM_RBUTTONDOWN:
4000 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4001 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4002 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4005 case WM_CONTEXTMENU:
4006 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4010 editor->bHaveFocus = TRUE;
4011 ME_ShowCaret(editor);
4012 ME_SendOldNotify(editor, EN_SETFOCUS);
4015 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4016 editor->bHaveFocus = FALSE;
4017 ME_HideCaret(editor);
4018 ME_SendOldNotify(editor, EN_KILLFOCUS);
4021 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4024 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4025 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4029 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4030 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4032 if (ME_KeyDown(editor, LOWORD(wParam)))
4036 return ME_Char(editor, wParam, lParam, unicode);
4040 if(wParam == UNICODE_NOCHAR) return TRUE;
4041 if(wParam <= 0x000fffff)
4043 if(wParam > 0xffff) /* convert to surrogates */
4046 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4047 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4049 ME_Char(editor, wParam, 0, TRUE);
4055 case EM_STOPGROUPTYPING:
4056 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4060 const int scrollUnit = 7;
4062 switch(LOWORD(wParam))
4065 ME_ScrollAbs(editor, 0, 0);
4068 ME_ScrollAbs(editor,
4069 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4070 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4073 ME_ScrollLeft(editor, scrollUnit);
4076 ME_ScrollRight(editor, scrollUnit);
4079 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4082 ME_ScrollRight(editor, editor->sizeWindow.cx);
4085 case SB_THUMBPOSITION:
4087 int pos = HIWORD(wParam);
4088 if (editor->horz_si.nMax > 0xffff)
4089 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4090 ME_HScrollAbs(editor, pos);
4096 case EM_SCROLL: /* fall through */
4102 origNPos = editor->vert_si.nPos;
4105 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4106 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4107 if (lineHeight <= 0) lineHeight = 24;
4109 switch(LOWORD(wParam))
4112 ME_ScrollAbs(editor, 0, 0);
4115 ME_ScrollAbs(editor,
4116 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4117 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4120 ME_ScrollUp(editor,lineHeight);
4123 ME_ScrollDown(editor,lineHeight);
4126 ME_ScrollUp(editor,editor->sizeWindow.cy);
4129 ME_ScrollDown(editor,editor->sizeWindow.cy);
4132 case SB_THUMBPOSITION:
4134 int pos = HIWORD(wParam);
4135 if (editor->vert_si.nMax > 0xffff)
4136 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4137 ME_VScrollAbs(editor, pos);
4141 if (msg == EM_SCROLL)
4142 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4148 UINT pulScrollLines;
4151 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4152 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4155 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4157 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4159 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4163 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4167 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4169 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4170 if (numerator >= 10 && numerator <= 500)
4171 ME_SetZoom(editor, numerator, 100);
4173 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4174 /* FIXME follow the original */
4176 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4183 *((RECT *)lParam) = editor->rcFormat;
4184 if (editor->bDefaultFormatRect)
4185 ((RECT *)lParam)->left -= editor->selofs;
4195 RECT *rc = (RECT *)lParam;
4197 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4198 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4201 editor->rcFormat.top = max(0, rc->top - border);
4202 editor->rcFormat.left = max(0, rc->left - border);
4203 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4204 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4205 } else if (wParam == 1) {
4206 /* MSDN incorrectly says a wParam value of 1 causes the
4207 * lParam rect to be used as a relative offset,
4208 * however, the tests show it just prevents min/max bound
4210 editor->rcFormat.top = rc->top - border;
4211 editor->rcFormat.left = rc->left - border;
4212 editor->rcFormat.bottom = rc->bottom;
4213 editor->rcFormat.right = rc->right + border;
4217 editor->bDefaultFormatRect = FALSE;
4221 ME_SetDefaultFormatRect(editor);
4222 editor->bDefaultFormatRect = TRUE;
4224 ME_MarkAllForWrapping(editor);
4225 ME_WrapMarkedParagraphs(editor);
4226 ME_UpdateScrollBar(editor);
4227 if (msg != EM_SETRECTNP)
4231 case EM_REQUESTRESIZE:
4232 ME_SendRequestResize(editor, TRUE);
4240 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4241 if (editor->bDefaultFormatRect) {
4242 ME_SetDefaultFormatRect(editor);
4244 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4245 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4247 editor->prevClientRect = clientRect;
4248 ME_RewrapRepaint(editor);
4251 /* IME messages to make richedit controls IME aware */
4252 case WM_IME_SETCONTEXT:
4253 case WM_IME_CONTROL:
4255 case WM_IME_COMPOSITIONFULL:
4257 case WM_IME_STARTCOMPOSITION:
4259 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4260 ME_DeleteSelection(editor);
4261 ME_CommitUndo(editor);
4262 ME_UpdateRepaint(editor, FALSE);
4265 case WM_IME_COMPOSITION:
4269 ME_Style *style = ME_GetInsertStyle(editor, 0);
4270 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4271 ME_DeleteSelection(editor);
4272 ME_SaveTempStyle(editor);
4273 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4275 LPWSTR lpCompStr = NULL;
4277 DWORD dwIndex = lParam & GCS_RESULTSTR;
4279 dwIndex = GCS_COMPSTR;
4281 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4282 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4283 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4284 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4285 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4286 HeapFree(GetProcessHeap(), 0, lpCompStr);
4288 if (dwIndex == GCS_COMPSTR)
4289 ME_SetSelection(editor,editor->imeStartIndex,
4290 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4292 ME_ReleaseStyle(style);
4293 ME_CommitUndo(editor);
4294 ME_UpdateRepaint(editor, FALSE);
4297 case WM_IME_ENDCOMPOSITION:
4299 ME_DeleteSelection(editor);
4300 editor->imeStartIndex=-1;
4303 case EM_GETOLEINTERFACE:
4305 LPVOID *ppvObj = (LPVOID*) lParam;
4306 return CreateIRichEditOle(editor, ppvObj);
4308 case EM_GETPASSWORDCHAR:
4310 return editor->cPasswordMask;
4312 case EM_SETOLECALLBACK:
4313 if(editor->lpOleCallback)
4314 IUnknown_Release(editor->lpOleCallback);
4315 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4316 if(editor->lpOleCallback)
4317 IUnknown_AddRef(editor->lpOleCallback);
4319 case EM_GETWORDBREAKPROC:
4320 return (LRESULT)editor->pfnWordBreak;
4321 case EM_SETWORDBREAKPROC:
4323 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4325 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4326 return (LRESULT)pfnOld;
4328 case EM_GETTEXTMODE:
4329 return editor->mode;
4330 case EM_SETTEXTMODE:
4335 if (ME_GetTextLength(editor) || editor->pUndoStack || editor->pRedoStack)
4336 return E_UNEXPECTED;
4338 /* Check for mutually exclusive flags in adjacent bits of wParam */
4339 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4340 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4341 return E_INVALIDARG;
4343 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4345 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4346 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4347 if (wParam & TM_PLAINTEXT) {
4348 /* Clear selection since it should be possible to select the
4349 * end of text run for rich text */
4350 ME_InvalidateSelection(editor);
4351 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4352 editor->pCursors[1] = editor->pCursors[0];
4353 /* plain text can only have the default style. */
4354 ME_ClearTempStyle(editor);
4355 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4356 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4357 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4360 /* FIXME: Currently no support for undo level and code page options */
4361 editor->mode = (editor->mode & ~mask) | changes;
4364 case EM_SETPASSWORDCHAR:
4366 editor->cPasswordMask = wParam;
4367 ME_RewrapRepaint(editor);
4370 case EM_SETTARGETDEVICE:
4373 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4374 if (editor->nAvailWidth || editor->bWordWrap != new)
4376 editor->bWordWrap = new;
4377 editor->nAvailWidth = 0; /* wrap to client area */
4378 ME_RewrapRepaint(editor);
4381 int width = max(0, lParam);
4382 if ((editor->styleFlags & ES_MULTILINE) &&
4383 (!editor->bWordWrap || editor->nAvailWidth != width))
4385 editor->nAvailWidth = width;
4386 editor->bWordWrap = TRUE;
4387 ME_RewrapRepaint(editor);
4389 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4394 *phresult = S_FALSE;
4400 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4401 LPARAM lParam, BOOL unicode)
4403 ME_TextEditor *editor;
4405 LRESULT lresult = 0;
4407 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4408 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4410 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4413 if (msg == WM_NCCREATE)
4415 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4416 ITextHost *texthost;
4418 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4419 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4420 return texthost != NULL;
4424 return DefWindowProcW(hWnd, msg, wParam, lParam);
4436 hDC = BeginPaint(editor->hWnd, &ps);
4437 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4438 ME_SendOldNotify(editor, EN_UPDATE);
4439 /* Erase area outside of the formatting rectangle */
4440 if (ps.rcPaint.top < editor->rcFormat.top)
4443 rc.bottom = editor->rcFormat.top;
4444 FillRect(hDC, &rc, editor->hbrBackground);
4445 ps.rcPaint.top = editor->rcFormat.top;
4447 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4449 rc.top = editor->rcFormat.bottom;
4450 FillRect(hDC, &rc, editor->hbrBackground);
4451 ps.rcPaint.bottom = editor->rcFormat.bottom;
4453 if (ps.rcPaint.left < editor->rcFormat.left) {
4455 rc.right = editor->rcFormat.left;
4456 FillRect(hDC, &rc, editor->hbrBackground);
4457 ps.rcPaint.left = editor->rcFormat.left;
4459 if (ps.rcPaint.right > editor->rcFormat.right) {
4461 rc.left = editor->rcFormat.right;
4462 FillRect(hDC, &rc, editor->hbrBackground);
4463 ps.rcPaint.right = editor->rcFormat.right;
4466 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4467 EndPaint(editor->hWnd, &ps);
4472 HDC hDC = (HDC)wParam;
4475 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4476 FillRect(hDC, &rc, editor->hbrBackground);
4482 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4483 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4485 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4486 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4487 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4488 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4491 case EM_SETREADONLY:
4494 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4495 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4496 dwStyle &= ~ES_READONLY;
4498 dwStyle |= ES_READONLY;
4499 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4503 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4506 if (hresult == S_FALSE)
4507 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4509 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4510 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4515 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4517 BOOL unicode = TRUE;
4519 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4520 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4523 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4526 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4528 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4531 /******************************************************************
4532 * RichEditANSIWndProc (RICHED20.10)
4534 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4536 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4539 /******************************************************************
4540 * RichEdit10ANSIWndProc (RICHED20.9)
4542 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4544 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4546 ITextHost *texthost;
4547 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4549 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4550 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4551 return texthost != NULL;
4553 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4556 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4558 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4561 /* Fill buffer with srcChars unicode characters from the start cursor.
4563 * buffer: destination buffer
4564 * buflen: length of buffer in characters excluding the NULL terminator.
4565 * start: start of editor text to copy into buffer.
4566 * srcChars: Number of characters to use from the editor text.
4567 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4569 * returns the number of characters written excluding the NULL terminator.
4571 * The written text is always NULL terminated.
4573 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4574 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4576 ME_DisplayItem *pRun, *pNextRun;
4577 const WCHAR *pStart = buffer;
4578 const WCHAR cr_lf[] = {'\r', '\n', 0};
4582 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4583 if (editor->bEmulateVersion10) bCRLF = 0;
4587 pNextRun = ME_FindItemFwd(pRun, diRun);
4589 nLen = pRun->member.run.strText->nLen - start->nOffset;
4590 str = pRun->member.run.strText->szData + start->nOffset;
4592 /* No '\r' is appended to the last paragraph. */
4593 while (srcChars && buflen && pNextRun)
4595 int nFlags = pRun->member.run.nFlags;
4597 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4599 if (buflen == 1) break;
4600 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4601 * EM_GETTEXTEX, however, this is done for copying text which
4602 * also uses this function. */
4603 srcChars -= min(nLen, srcChars);
4607 nLen = min(nLen, srcChars);
4611 nLen = min(nLen, buflen);
4614 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4619 pNextRun = ME_FindItemFwd(pRun, diRun);
4621 nLen = pRun->member.run.strText->nLen;
4622 str = pRun->member.run.strText->szData;
4625 return buffer - pStart;
4628 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4633 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4634 wcW.lpfnWndProc = RichEditWndProcW;
4636 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4637 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4639 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4640 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4641 wcW.lpszMenuName = NULL;
4643 if (is_version_nt())
4645 wcW.lpszClassName = RICHEDIT_CLASS20W;
4646 if (!RegisterClassW(&wcW)) return FALSE;
4647 wcW.lpszClassName = MSFTEDIT_CLASS;
4648 if (!RegisterClassW(&wcW)) return FALSE;
4652 /* WNDCLASSA/W have the same layout */
4653 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4654 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4655 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4656 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4659 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4660 wcA.lpfnWndProc = RichEditWndProcA;
4662 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4663 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4665 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4666 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4667 wcA.lpszMenuName = NULL;
4668 wcA.lpszClassName = RICHEDIT_CLASS20A;
4669 if (!RegisterClassA(&wcA)) return FALSE;
4670 wcA.lpszClassName = "RichEdit50A";
4671 if (!RegisterClassA(&wcA)) return FALSE;
4676 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4677 /* FIXME: Not implemented */
4678 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4679 hWnd, msg, get_msg_name(msg), wParam, lParam);
4680 return DefWindowProcW(hWnd, msg, wParam, lParam);
4683 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4684 /* FIXME: Not implemented */
4685 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4686 hWnd, msg, get_msg_name(msg), wParam, lParam);
4687 return DefWindowProcW(hWnd, msg, wParam, lParam);
4690 /******************************************************************
4691 * REExtendedRegisterClass (RICHED20.8)
4693 * FIXME undocumented
4694 * Need to check for errors and implement controls and callbacks
4696 LRESULT WINAPI REExtendedRegisterClass(void)
4701 FIXME("semi stub\n");
4705 wcW.hInstance = NULL;
4708 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4709 wcW.lpszMenuName = NULL;
4711 if (!ME_ListBoxRegistered)
4713 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4714 wcW.lpfnWndProc = REListWndProc;
4715 wcW.lpszClassName = REListBox20W;
4716 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4719 if (!ME_ComboBoxRegistered)
4721 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4722 wcW.lpfnWndProc = REComboWndProc;
4723 wcW.lpszClassName = REComboBox20W;
4724 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4728 if (ME_ListBoxRegistered)
4730 if (ME_ComboBoxRegistered)
4736 static BOOL isurlspecial(WCHAR c)
4738 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4739 return strchrW( special_chars, c ) != NULL;
4743 * This proc takes a selection, and scans it forward in order to select the span
4744 * of a possible URL candidate. A possible URL candidate must start with isalnum
4745 * or one of the following special characters: *|/\+%#@ and must consist entirely
4746 * of the characters allowed to start the URL, plus : (colon) which may occur
4747 * at most once, and not at either end.
4749 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4750 const ME_Cursor *start,
4752 ME_Cursor *candidate_min,
4753 ME_Cursor *candidate_max)
4755 ME_Cursor cursor = *start;
4756 BOOL foundColon = FALSE;
4757 BOOL candidateStarted = FALSE;
4758 WCHAR lastAcceptedChar = '\0';
4762 WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4763 WCHAR *str = strStart + cursor.nOffset;
4764 int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4767 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4769 /* Find start of candidate */
4770 if (!candidateStarted)
4775 if (isalnumW(*str) || isurlspecial(*str))
4777 cursor.nOffset = str - strStart;
4778 *candidate_min = cursor;
4779 candidateStarted = TRUE;
4780 lastAcceptedChar = *str++;
4787 /* Find end of candidate */
4788 if (candidateStarted) {
4792 if (*str == ':' && !foundColon) {
4794 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4795 cursor.nOffset = str - strStart;
4796 if (lastAcceptedChar == ':')
4797 ME_MoveCursorChars(editor, &cursor, -1);
4798 *candidate_max = cursor;
4801 lastAcceptedChar = *str++;
4805 /* End of paragraph: skip it if before candidate span, or terminates
4806 current active span */
4807 if (candidateStarted) {
4808 if (lastAcceptedChar == ':')
4809 ME_MoveCursorChars(editor, &cursor, -1);
4810 *candidate_max = cursor;
4815 /* Reaching this point means no span was found, so get next span */
4816 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4817 if (candidateStarted) {
4818 /* There are no further runs, so take end of text as end of candidate */
4819 cursor.nOffset = str - strStart;
4820 if (lastAcceptedChar == ':')
4821 ME_MoveCursorChars(editor, &cursor, -1);
4822 *candidate_max = cursor;
4825 *candidate_max = *candidate_min = cursor;
4831 if (candidateStarted) {
4832 /* There are no further runs, so take end of text as end of candidate */
4833 if (lastAcceptedChar == ':')
4834 ME_MoveCursorChars(editor, &cursor, -1);
4835 *candidate_max = cursor;
4838 *candidate_max = *candidate_min = cursor;
4843 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4845 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4847 #define MAX_PREFIX_LEN 9
4849 const WCHAR text[MAX_PREFIX_LEN];
4852 {{'p','r','o','s','p','e','r','o',':'}, 9},
4853 {{'t','e','l','n','e','t',':'}, 7},
4854 {{'g','o','p','h','e','r',':'}, 7},
4855 {{'m','a','i','l','t','o',':'}, 7},
4856 {{'h','t','t','p','s',':'}, 6},
4857 {{'f','i','l','e',':'}, 5},
4858 {{'n','e','w','s',':'}, 5},
4859 {{'w','a','i','s',':'}, 5},
4860 {{'n','n','t','p',':'}, 5},
4861 {{'h','t','t','p',':'}, 5},
4862 {{'w','w','w','.'}, 4},
4863 {{'f','t','p',':'}, 4},
4865 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4868 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4869 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4871 if (nChars < prefixes[i].length) continue;
4872 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4876 #undef MAX_PREFIX_LEN
4880 * This proc walks through the indicated selection and evaluates whether each
4881 * section identified by ME_FindNextURLCandidate and in-between sections have
4882 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4883 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4885 * Since this function can cause runs to be split, do not depend on the value
4886 * of the start cursor at the end of the function.
4888 * nChars may be set to INT_MAX to update to the end of the text.
4890 * Returns TRUE if at least one section was modified.
4892 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4894 BOOL modified = FALSE;
4895 ME_Cursor startCur = *start;
4897 if (!editor->AutoURLDetect_bEnable) return FALSE;
4902 ME_Cursor candidateStart, candidateEnd;
4904 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4905 &candidateStart, &candidateEnd))
4907 /* Section before candidate is not an URL */
4908 int cMin = ME_GetCursorOfs(&candidateStart);
4909 int cMax = ME_GetCursorOfs(&candidateEnd);
4911 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4912 candidateStart = candidateEnd;
4913 nChars -= cMax - ME_GetCursorOfs(&startCur);
4917 /* No more candidates until end of selection */
4921 if (startCur.pRun != candidateStart.pRun ||
4922 startCur.nOffset != candidateStart.nOffset)
4924 /* CFE_LINK effect should be consistently unset */
4925 link.cbSize = sizeof(link);
4926 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4927 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4929 /* CFE_LINK must be unset from this range */
4930 memset(&link, 0, sizeof(CHARFORMAT2W));
4931 link.cbSize = sizeof(link);
4932 link.dwMask = CFM_LINK;
4934 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4935 /* Update candidateEnd since setting character formats may split
4936 * runs, which can cause a cursor to be at an invalid offset within
4938 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4940 candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4941 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4946 if (candidateStart.pRun != candidateEnd.pRun ||
4947 candidateStart.nOffset != candidateEnd.nOffset)
4949 /* CFE_LINK effect should be consistently set */
4950 link.cbSize = sizeof(link);
4951 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4952 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4954 /* CFE_LINK must be set on this range */
4955 memset(&link, 0, sizeof(CHARFORMAT2W));
4956 link.cbSize = sizeof(link);
4957 link.dwMask = CFM_LINK;
4958 link.dwEffects = CFE_LINK;
4959 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4963 startCur = candidateEnd;
4964 } while (nChars > 0);