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];
289 TRACE("%08x %p\n", dwFormat, stream);
296 ME_StreamInFill(stream);
297 if (stream->editstream->dwError)
303 if (!(dwFormat & SF_UNICODE))
305 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
306 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
311 nWideChars = stream->dwSize >> 1;
312 pText = (WCHAR *)stream->buffer;
315 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
316 if (stream->dwSize == 0)
323 static void ME_ApplyBorderProperties(RTF_Info *info,
324 ME_BorderRect *borderRect,
325 RTFBorder *borderDef)
328 ME_Border *pBorders[] = {&borderRect->top,
332 for (i = 0; i < 4; i++)
334 RTFColor *colorDef = info->colorList;
335 pBorders[i]->width = borderDef[i].width;
336 colorNum = borderDef[i].color;
337 while (colorDef && colorDef->rtfCNum != colorNum)
338 colorDef = colorDef->rtfNextColor;
340 pBorders[i]->colorRef = RGB(
341 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
342 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
343 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
345 pBorders[i]->colorRef = RGB(0, 0, 0);
349 void ME_RTFCharAttrHook(RTF_Info *info)
352 fmt.cbSize = sizeof(fmt);
356 switch(info->rtfMinor)
359 /* FIXME add more flags once they're implemented */
360 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
361 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
362 fmt.yHeight = 12*20; /* 12pt */
363 fmt.wWeight = FW_NORMAL;
364 fmt.bUnderlineType = CFU_UNDERLINENONE;
367 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
368 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
369 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
372 fmt.dwMask = CFM_ITALIC;
373 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
376 fmt.dwMask = CFM_UNDERLINETYPE;
377 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
379 case rtfDotUnderline:
380 fmt.dwMask = CFM_UNDERLINETYPE;
381 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
384 fmt.dwMask = CFM_UNDERLINETYPE;
385 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
387 case rtfWordUnderline:
388 fmt.dwMask = CFM_UNDERLINETYPE;
389 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
392 fmt.dwMask = CFM_UNDERLINETYPE;
393 fmt.bUnderlineType = CFU_UNDERLINENONE;
396 fmt.dwMask = CFM_STRIKEOUT;
397 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
401 case rtfSubScrShrink:
402 case rtfSuperScrShrink:
404 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
405 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
406 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
407 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
410 fmt.dwMask = CFM_HIDDEN;
411 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
414 fmt.dwMask = CFM_BACKCOLOR;
416 if (info->rtfParam == 0)
417 fmt.dwEffects = CFE_AUTOBACKCOLOR;
418 else if (info->rtfParam != rtfNoParam)
420 RTFColor *c = RTFGetColor(info, info->rtfParam);
421 if (c && c->rtfCBlue >= 0)
422 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
424 fmt.dwEffects = CFE_AUTOBACKCOLOR;
428 fmt.dwMask = CFM_COLOR;
430 if (info->rtfParam == 0)
431 fmt.dwEffects = CFE_AUTOCOLOR;
432 else if (info->rtfParam != rtfNoParam)
434 RTFColor *c = RTFGetColor(info, info->rtfParam);
435 if (c && c->rtfCBlue >= 0)
436 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
438 fmt.dwEffects = CFE_AUTOCOLOR;
443 if (info->rtfParam != rtfNoParam)
445 RTFFont *f = RTFGetFont(info, info->rtfParam);
448 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
449 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
450 fmt.bCharSet = f->rtfFCharSet;
451 fmt.dwMask = CFM_FACE | CFM_CHARSET;
452 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
457 fmt.dwMask = CFM_SIZE;
458 if (info->rtfParam != rtfNoParam)
459 fmt.yHeight = info->rtfParam*10;
464 RTFFlushOutputBuffer(info);
465 /* FIXME too slow ? how come ? */
466 style2 = ME_ApplyStyle(info->style, &fmt);
467 ME_ReleaseStyle(info->style);
468 info->style = style2;
469 info->styleChanged = TRUE;
473 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
474 the same tags mean different things in different contexts */
475 void ME_RTFParAttrHook(RTF_Info *info)
478 fmt.cbSize = sizeof(fmt);
481 switch(info->rtfMinor)
483 case rtfParDef: /* restores default paragraph attributes */
484 if (!info->editor->bEmulateVersion10) /* v4.1 */
485 info->borderType = RTFBorderParaLeft;
486 else /* v1.0 - 3.0 */
487 info->borderType = RTFBorderParaTop;
488 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
489 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
491 /* TODO: numbering, shading */
492 fmt.wAlignment = PFA_LEFT;
494 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
495 fmt.wBorderWidth = fmt.wBorders = 0;
496 fmt.wBorderSpace = 0;
497 fmt.bLineSpacingRule = 0;
498 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
499 fmt.dyLineSpacing = 0;
500 if (!info->editor->bEmulateVersion10) /* v4.1 */
502 if (info->tableDef && info->tableDef->tableRowStart &&
503 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
506 ME_DisplayItem *para;
507 /* We are just after a table row. */
508 RTFFlushOutputBuffer(info);
509 cursor = info->editor->pCursors[0];
511 if (para == info->tableDef->tableRowStart->member.para.next_para
512 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
514 /* Since the table row end, no text has been inserted, and the \intbl
515 * control word has not be used. We can confirm that we are not in a
518 info->tableDef->tableRowStart = NULL;
519 info->canInheritInTbl = FALSE;
522 } else { /* v1.0 - v3.0 */
523 fmt.dwMask |= PFM_TABLE;
524 fmt.wEffects &= ~PFE_TABLE;
528 if (!info->editor->bEmulateVersion10) /* v4.1 */
530 while (info->rtfParam > info->nestingLevel) {
531 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
532 ZeroMemory(tableDef, sizeof(RTFTable));
533 tableDef->parent = info->tableDef;
534 info->tableDef = tableDef;
536 RTFFlushOutputBuffer(info);
537 if (tableDef->tableRowStart &&
538 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
540 ME_DisplayItem *para = tableDef->tableRowStart;
541 para = para->member.para.next_para;
542 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
543 tableDef->tableRowStart = para;
547 cursor = info->editor->pCursors[0];
548 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
549 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
550 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
553 info->nestingLevel++;
555 info->canInheritInTbl = FALSE;
560 if (!info->editor->bEmulateVersion10) /* v4.1 */
562 if (info->nestingLevel < 1)
567 info->tableDef = ALLOC_OBJ(RTFTable);
568 ZeroMemory(info->tableDef, sizeof(RTFTable));
570 tableDef = info->tableDef;
571 RTFFlushOutputBuffer(info);
572 if (tableDef->tableRowStart &&
573 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
575 ME_DisplayItem *para = tableDef->tableRowStart;
576 para = para->member.para.next_para;
577 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
578 tableDef->tableRowStart = para;
582 cursor = info->editor->pCursors[0];
583 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
584 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
585 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
587 info->nestingLevel = 1;
588 info->canInheritInTbl = TRUE;
591 } else { /* v1.0 - v3.0 */
592 fmt.dwMask |= PFM_TABLE;
593 fmt.wEffects |= PFE_TABLE;
598 ME_GetSelectionParaFormat(info->editor, &fmt);
599 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
600 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
601 fmt.dxOffset = -info->rtfParam;
604 ME_GetSelectionParaFormat(info->editor, &fmt);
605 fmt.dwMask = PFM_STARTINDENT;
606 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
609 fmt.dwMask = PFM_RIGHTINDENT;
610 fmt.dxRightIndent = info->rtfParam;
614 fmt.dwMask = PFM_ALIGNMENT;
615 fmt.wAlignment = PFA_LEFT;
618 fmt.dwMask = PFM_ALIGNMENT;
619 fmt.wAlignment = PFA_RIGHT;
622 fmt.dwMask = PFM_ALIGNMENT;
623 fmt.wAlignment = PFA_CENTER;
626 ME_GetSelectionParaFormat(info->editor, &fmt);
627 if (!(fmt.dwMask & PFM_TABSTOPS))
631 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
632 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
633 fmt.dwMask = PFM_TABSTOPS;
636 fmt.dwMask = PFM_KEEP;
637 fmt.wEffects = PFE_KEEP;
639 case rtfNoWidowControl:
640 fmt.dwMask = PFM_NOWIDOWCONTROL;
641 fmt.wEffects = PFE_NOWIDOWCONTROL;
644 fmt.dwMask = PFM_KEEPNEXT;
645 fmt.wEffects = PFE_KEEPNEXT;
648 fmt.dwMask = PFM_SPACEAFTER;
649 fmt.dySpaceAfter = info->rtfParam;
652 fmt.dwMask = PFM_SPACEBEFORE;
653 fmt.dySpaceBefore = info->rtfParam;
655 case rtfSpaceBetween:
656 fmt.dwMask = PFM_LINESPACING;
657 if ((int)info->rtfParam > 0)
659 fmt.dyLineSpacing = info->rtfParam;
660 fmt.bLineSpacingRule = 3;
664 fmt.dyLineSpacing = info->rtfParam;
665 fmt.bLineSpacingRule = 4;
667 case rtfSpaceMultiply:
668 fmt.dwMask = PFM_LINESPACING;
669 fmt.dyLineSpacing = info->rtfParam * 20;
670 fmt.bLineSpacingRule = 5;
673 fmt.dwMask = PFM_NUMBERING;
674 fmt.wNumbering = PFN_BULLET;
677 fmt.dwMask = PFM_NUMBERING;
678 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
680 case rtfParNumDecimal:
681 fmt.dwMask = PFM_NUMBERING;
682 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
684 case rtfParNumIndent:
685 fmt.dwMask = PFM_NUMBERINGTAB;
686 fmt.wNumberingTab = info->rtfParam;
688 case rtfParNumStartAt:
689 fmt.dwMask = PFM_NUMBERINGSTART;
690 fmt.wNumberingStart = info->rtfParam;
693 info->borderType = RTFBorderParaLeft;
694 ME_GetSelectionParaFormat(info->editor, &fmt);
695 if (!(fmt.dwMask & PFM_BORDER))
697 fmt.wBorderSpace = 0;
698 fmt.wBorderWidth = 1;
702 fmt.dwMask = PFM_BORDER;
705 info->borderType = RTFBorderParaRight;
706 ME_GetSelectionParaFormat(info->editor, &fmt);
707 if (!(fmt.dwMask & PFM_BORDER))
709 fmt.wBorderSpace = 0;
710 fmt.wBorderWidth = 1;
714 fmt.dwMask = PFM_BORDER;
717 info->borderType = RTFBorderParaTop;
718 ME_GetSelectionParaFormat(info->editor, &fmt);
719 if (!(fmt.dwMask & PFM_BORDER))
721 fmt.wBorderSpace = 0;
722 fmt.wBorderWidth = 1;
726 fmt.dwMask = PFM_BORDER;
728 case rtfBorderBottom:
729 info->borderType = RTFBorderParaBottom;
730 ME_GetSelectionParaFormat(info->editor, &fmt);
731 if (!(fmt.dwMask & PFM_BORDER))
733 fmt.wBorderSpace = 0;
734 fmt.wBorderWidth = 1;
738 fmt.dwMask = PFM_BORDER;
740 case rtfBorderSingle:
741 ME_GetSelectionParaFormat(info->editor, &fmt);
742 /* we assume that borders have been created before (RTF spec) */
743 fmt.wBorders &= ~0x700;
744 fmt.wBorders |= 1 << 8;
745 fmt.dwMask = PFM_BORDER;
748 ME_GetSelectionParaFormat(info->editor, &fmt);
749 /* we assume that borders have been created before (RTF spec) */
750 fmt.wBorders &= ~0x700;
751 fmt.wBorders |= 2 << 8;
752 fmt.dwMask = PFM_BORDER;
754 case rtfBorderShadow:
755 ME_GetSelectionParaFormat(info->editor, &fmt);
756 /* we assume that borders have been created before (RTF spec) */
757 fmt.wBorders &= ~0x700;
758 fmt.wBorders |= 10 << 8;
759 fmt.dwMask = PFM_BORDER;
761 case rtfBorderDouble:
762 ME_GetSelectionParaFormat(info->editor, &fmt);
763 /* we assume that borders have been created before (RTF spec) */
764 fmt.wBorders &= ~0x700;
765 fmt.wBorders |= 7 << 8;
766 fmt.dwMask = PFM_BORDER;
769 ME_GetSelectionParaFormat(info->editor, &fmt);
770 /* we assume that borders have been created before (RTF spec) */
771 fmt.wBorders &= ~0x700;
772 fmt.wBorders |= 11 << 8;
773 fmt.dwMask = PFM_BORDER;
777 int borderSide = info->borderType & RTFBorderSideMask;
778 RTFTable *tableDef = info->tableDef;
779 ME_GetSelectionParaFormat(info->editor, &fmt);
780 /* we assume that borders have been created before (RTF spec) */
781 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
782 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
785 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
787 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
788 border->width = info->rtfParam;
791 fmt.dwMask = PFM_BORDER;
795 ME_GetSelectionParaFormat(info->editor, &fmt);
796 /* we assume that borders have been created before (RTF spec) */
797 fmt.wBorderSpace = info->rtfParam;
798 fmt.dwMask = PFM_BORDER;
802 RTFTable *tableDef = info->tableDef;
803 int borderSide = info->borderType & RTFBorderSideMask;
804 int borderType = info->borderType & RTFBorderTypeMask;
807 case RTFBorderTypePara:
808 if (!info->editor->bEmulateVersion10) /* v4.1 */
810 /* v1.0 - 3.0 treat paragraph and row borders the same. */
811 case RTFBorderTypeRow:
813 tableDef->border[borderSide].color = info->rtfParam;
816 case RTFBorderTypeCell:
817 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
818 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
826 RTFFlushOutputBuffer(info);
827 /* FIXME too slow ? how come ?*/
828 ME_SetSelectionParaFormat(info->editor, &fmt);
832 void ME_RTFTblAttrHook(RTF_Info *info)
834 switch (info->rtfMinor)
838 if (!info->editor->bEmulateVersion10) /* v4.1 */
839 info->borderType = 0; /* Not sure */
840 else /* v1.0 - 3.0 */
841 info->borderType = RTFBorderRowTop;
842 if (!info->tableDef) {
843 info->tableDef = ME_MakeTableDef(info->editor);
845 ME_InitTableDef(info->editor, info->tableDef);
854 info->tableDef = ME_MakeTableDef(info->editor);
856 cellNum = info->tableDef->numCellsDefined;
857 if (cellNum >= MAX_TABLE_CELLS)
859 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
860 if (cellNum < MAX_TAB_STOPS) {
861 /* Tab stops were used to store cell positions before v4.1 but v4.1
862 * still seems to set the tabstops without using them. */
863 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
864 PARAFORMAT2 *pFmt = para->member.para.pFmt;
865 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
866 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
868 info->tableDef->numCellsDefined++;
872 info->borderType = RTFBorderRowTop;
875 info->borderType = RTFBorderRowLeft;
877 case rtfRowBordBottom:
878 info->borderType = RTFBorderRowBottom;
880 case rtfRowBordRight:
881 info->borderType = RTFBorderRowRight;
884 info->borderType = RTFBorderCellTop;
886 case rtfCellBordLeft:
887 info->borderType = RTFBorderCellLeft;
889 case rtfCellBordBottom:
890 info->borderType = RTFBorderCellBottom;
892 case rtfCellBordRight:
893 info->borderType = RTFBorderCellRight;
897 info->tableDef->gapH = info->rtfParam;
901 info->tableDef->leftEdge = info->rtfParam;
906 void ME_RTFSpecialCharHook(RTF_Info *info)
908 RTFTable *tableDef = info->tableDef;
909 switch (info->rtfMinor)
912 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
914 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
918 RTFFlushOutputBuffer(info);
919 if (!info->editor->bEmulateVersion10) { /* v4.1 */
920 if (tableDef->tableRowStart)
922 if (!info->nestingLevel &&
923 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
925 ME_DisplayItem *para = tableDef->tableRowStart;
926 para = para->member.para.next_para;
927 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
928 tableDef->tableRowStart = para;
929 info->nestingLevel = 1;
931 ME_InsertTableCellFromCursor(info->editor);
933 } else { /* v1.0 - v3.0 */
934 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
935 PARAFORMAT2 *pFmt = para->member.para.pFmt;
936 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
937 tableDef->numCellsInserted < tableDef->numCellsDefined)
940 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
941 tableDef->numCellsInserted++;
946 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
948 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
951 ME_DisplayItem *para, *cell, *run;
956 RTFFlushOutputBuffer(info);
957 if (!info->editor->bEmulateVersion10) { /* v4.1 */
958 if (!tableDef->tableRowStart)
960 if (!info->nestingLevel &&
961 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
963 para = tableDef->tableRowStart;
964 para = para->member.para.next_para;
965 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
966 tableDef->tableRowStart = para;
967 info->nestingLevel++;
969 para = tableDef->tableRowStart;
970 cell = ME_FindItemFwd(para, diCell);
971 assert(cell && !cell->member.cell.prev_cell);
972 if (tableDef->numCellsDefined < 1)
974 /* 2000 twips appears to be the cell size that native richedit uses
975 * when no cell sizes are specified. */
976 const int defaultCellSize = 2000;
977 int nRightBoundary = defaultCellSize;
978 cell->member.cell.nRightBoundary = nRightBoundary;
979 while (cell->member.cell.next_cell) {
980 cell = cell->member.cell.next_cell;
981 nRightBoundary += defaultCellSize;
982 cell->member.cell.nRightBoundary = nRightBoundary;
984 para = ME_InsertTableCellFromCursor(info->editor);
985 cell = para->member.para.pCell;
986 cell->member.cell.nRightBoundary = nRightBoundary;
988 for (i = 0; i < tableDef->numCellsDefined; i++)
990 RTFCell *cellDef = &tableDef->cells[i];
991 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
992 ME_ApplyBorderProperties(info, &cell->member.cell.border,
994 cell = cell->member.cell.next_cell;
997 para = ME_InsertTableCellFromCursor(info->editor);
998 cell = para->member.para.pCell;
1001 /* Cell for table row delimiter is empty */
1002 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1005 run = ME_FindItemFwd(cell, diRun);
1006 if (info->editor->pCursors[0].pRun != run ||
1007 info->editor->pCursors[0].nOffset)
1010 /* Delete inserted cells that aren't defined. */
1011 info->editor->pCursors[1].pRun = run;
1012 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1013 info->editor->pCursors[1].nOffset = 0;
1014 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1015 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1016 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1020 para = ME_InsertTableRowEndFromCursor(info->editor);
1021 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1022 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1023 ME_ApplyBorderProperties(info, ¶->member.para.border,
1025 info->nestingLevel--;
1026 if (!info->nestingLevel)
1028 if (info->canInheritInTbl) {
1029 tableDef->tableRowStart = para;
1031 while (info->tableDef) {
1032 tableDef = info->tableDef;
1033 info->tableDef = tableDef->parent;
1034 heap_free(tableDef);
1038 info->tableDef = tableDef->parent;
1039 heap_free(tableDef);
1041 } else { /* v1.0 - v3.0 */
1043 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1044 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1045 pFmt->dxOffset = info->tableDef->gapH;
1046 pFmt->dxStartIndent = info->tableDef->leftEdge;
1048 ME_ApplyBorderProperties(info, ¶->member.para.border,
1050 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1053 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1054 tableDef->numCellsInserted++;
1056 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1057 if (!tableDef->numCellsDefined)
1058 pFmt->wEffects &= ~PFE_TABLE;
1059 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1060 tableDef->numCellsInserted = 0;
1066 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1067 ME_DisplayItem *para;
1069 RTFFlushOutputBuffer(info);
1070 para = info->editor->pCursors[0].pPara;
1071 pFmt = para->member.para.pFmt;
1072 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1074 /* rtfPar is treated like a space within a table. */
1075 info->rtfClass = rtfText;
1076 info->rtfMajor = ' ';
1078 else if (info->rtfMinor == rtfPar && tableDef)
1079 tableDef->numCellsInserted = 0;
1085 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1088 LPOLEOBJECT lpObject = NULL;
1089 LPSTORAGE lpStorage = NULL;
1090 LPOLECLIENTSITE lpClientSite = NULL;
1091 LPDATAOBJECT lpDataObject = NULL;
1092 LPOLECACHE lpOleCache = NULL;
1101 stgm.tymed = TYMED_ENHMF;
1102 stgm.u.hEnhMetaFile = hemf;
1103 fm.cfFormat = CF_ENHMETAFILE;
1107 stgm.tymed = TYMED_GDI;
1108 stgm.u.hBitmap = hbmp;
1109 fm.cfFormat = CF_BITMAP;
1111 stgm.pUnkForRelease = NULL;
1114 fm.dwAspect = DVASPECT_CONTENT;
1116 fm.tymed = stgm.tymed;
1118 if (!info->lpRichEditOle)
1120 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1123 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1125 /* FIXME: enable it when rich-edit properly implements this method */
1126 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1127 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1129 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1130 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1131 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1132 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1133 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1137 reobject.cbStruct = sizeof(reobject);
1138 reobject.cp = REO_CP_SELECTION;
1139 reobject.clsid = clsid;
1140 reobject.poleobj = lpObject;
1141 reobject.pstg = lpStorage;
1142 reobject.polesite = lpClientSite;
1143 /* convert from twips to .01 mm */
1144 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1145 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1146 reobject.dvaspect = DVASPECT_CONTENT;
1147 reobject.dwFlags = 0; /* FIXME */
1148 reobject.dwUser = 0;
1150 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1154 if (lpObject) IOleObject_Release(lpObject);
1155 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1156 if (lpStorage) IStorage_Release(lpStorage);
1157 if (lpDataObject) IDataObject_Release(lpDataObject);
1158 if (lpOleCache) IOleCache_Release(lpOleCache);
1163 static void ME_RTFReadPictGroup(RTF_Info *info)
1166 BYTE* buffer = NULL;
1167 unsigned bufsz, bufidx;
1173 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1176 if (info->rtfClass == rtfEOF)
1179 /* fetch picture type */
1180 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1182 mfp.mm = info->rtfParam;
1185 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1187 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1190 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1192 gfx = gfx_enhmetafile;
1196 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1200 /* fetch picture attributes */
1204 if (info->rtfClass == rtfEOF)
1206 if (info->rtfClass == rtfText)
1208 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1210 ERR("Expected picture attribute (%d %d)\n",
1211 info->rtfClass, info->rtfMajor);
1214 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1216 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1218 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1220 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1222 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1223 sz.cx = info->rtfParam;
1224 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1225 sz.cy = info->rtfParam;
1227 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1229 /* fetch picture data */
1232 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1233 val = info->rtfMajor;
1234 for (flip = TRUE;; flip = !flip)
1237 if (info->rtfClass == rtfEOF)
1239 HeapFree(GetProcessHeap(), 0, buffer);
1240 return; /* Warn ?? */
1242 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1244 if (info->rtfClass != rtfText) goto skip_group;
1247 if (bufidx >= bufsz &&
1248 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1250 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1253 val = info->rtfMajor;
1255 if (flip) FIXME("wrong hex string\n");
1259 case gfx_enhmetafile:
1260 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1261 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1264 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1265 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1269 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1271 unsigned nc = bi->bmiHeader.biClrUsed;
1273 /* not quite right, especially for bitfields type of compression */
1274 if (!nc && bi->bmiHeader.biBitCount <= 8)
1275 nc = 1 << bi->bmiHeader.biBitCount;
1276 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1277 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1278 bi, DIB_RGB_COLORS)))
1279 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1286 HeapFree(GetProcessHeap(), 0, buffer);
1287 RTFRouteToken (info); /* feed "}" back to router */
1290 HeapFree(GetProcessHeap(), 0, buffer);
1292 RTFRouteToken(info); /* feed "}" back to router */
1295 /* for now, lookup the \result part and use it, whatever the object */
1296 static void ME_RTFReadObjectGroup(RTF_Info *info)
1301 if (info->rtfClass == rtfEOF)
1303 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1305 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1308 if (info->rtfClass == rtfEOF)
1310 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1314 while (RTFGetToken (info) != rtfEOF)
1316 if (info->rtfClass == rtfGroup)
1318 if (info->rtfMajor == rtfBeginGroup) level++;
1319 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1321 RTFRouteToken(info);
1324 else RTFSkipGroup(info);
1327 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1329 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1333 RTFRouteToken(info); /* feed "}" back to router */
1336 static void ME_RTFReadHook(RTF_Info *info)
1338 switch(info->rtfClass)
1341 switch(info->rtfMajor)
1344 if (info->stackTop < maxStack) {
1345 info->stack[info->stackTop].style = info->style;
1346 ME_AddRefStyle(info->style);
1347 info->stack[info->stackTop].codePage = info->codePage;
1348 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1351 info->styleChanged = FALSE;
1355 RTFFlushOutputBuffer(info);
1357 if (info->stackTop <= 0)
1358 info->rtfClass = rtfEOF;
1359 if (info->stackTop < 0)
1362 ME_ReleaseStyle(info->style);
1363 info->style = info->stack[info->stackTop].style;
1364 info->codePage = info->stack[info->stackTop].codePage;
1365 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1374 ME_StreamInFill(ME_InStream *stream)
1376 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1377 (BYTE *)stream->buffer,
1378 sizeof(stream->buffer),
1379 (LONG *)&stream->dwSize);
1383 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1387 int from, to, nUndoMode;
1388 int nEventMask = editor->nEventMask;
1389 ME_InStream inStream;
1390 BOOL invalidRTF = FALSE;
1391 ME_Cursor *selStart, *selEnd;
1393 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1394 editor->nEventMask = 0;
1396 ME_GetSelectionOfs(editor, &from, &to);
1397 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1399 ME_GetSelection(editor, &selStart, &selEnd);
1400 style = ME_GetSelectionInsertStyle(editor);
1402 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1404 /* Don't insert text at the end of the table row */
1405 if (!editor->bEmulateVersion10) { /* v4.1 */
1406 ME_DisplayItem *para = editor->pCursors->pPara;
1407 if (para->member.para.nFlags & MEPF_ROWEND)
1409 para = para->member.para.next_para;
1410 editor->pCursors[0].pPara = para;
1411 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1412 editor->pCursors[0].nOffset = 0;
1414 if (para->member.para.nFlags & MEPF_ROWSTART)
1416 para = para->member.para.next_para;
1417 editor->pCursors[0].pPara = para;
1418 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1419 editor->pCursors[0].nOffset = 0;
1421 editor->pCursors[1] = editor->pCursors[0];
1422 } else { /* v1.0 - 3.0 */
1423 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1424 ME_IsInTable(editor->pCursors[0].pRun))
1428 style = editor->pBuffer->pDefaultStyle;
1429 ME_AddRefStyle(style);
1430 ME_SetSelection(editor, 0, 0);
1431 ME_InternalDeleteText(editor, &editor->pCursors[1],
1432 ME_GetTextLength(editor), FALSE);
1434 ME_ClearTempStyle(editor);
1435 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1439 /* Back up undo mode to a local variable */
1440 nUndoMode = editor->nUndoMode;
1442 /* Only create an undo if SFF_SELECTION is set */
1443 if (!(format & SFF_SELECTION))
1444 editor->nUndoMode = umIgnore;
1446 inStream.editstream = stream;
1447 inStream.editstream->dwError = 0;
1448 inStream.dwSize = 0;
1449 inStream.dwUsed = 0;
1451 if (format & SF_RTF)
1453 /* Check if it's really RTF, and if it is not, use plain text */
1454 ME_StreamInFill(&inStream);
1455 if (!inStream.editstream->dwError)
1457 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1458 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1461 inStream.editstream->dwError = -16;
1466 if (!invalidRTF && !inStream.editstream->dwError)
1468 if (format & SF_RTF) {
1469 /* setup the RTF parser */
1470 memset(&parser, 0, sizeof parser);
1471 RTFSetEditStream(&parser, &inStream);
1472 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1473 parser.editor = editor;
1474 parser.style = style;
1475 WriterInit(&parser);
1477 RTFSetReadHook(&parser, ME_RTFReadHook);
1478 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1479 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1480 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1482 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1483 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1487 /* do the parsing */
1489 RTFFlushOutputBuffer(&parser);
1490 if (!editor->bEmulateVersion10) { /* v4.1 */
1491 if (parser.tableDef && parser.tableDef->tableRowStart &&
1492 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1494 /* Delete any incomplete table row at the end of the rich text. */
1496 ME_DisplayItem *para;
1498 parser.rtfMinor = rtfRow;
1499 /* Complete the table row before deleting it.
1500 * By doing it this way we will have the current paragraph format set
1501 * properly to reflect that is not in the complete table, and undo items
1502 * will be added for this change to the current paragraph format. */
1503 if (parser.nestingLevel > 0)
1505 while (parser.nestingLevel > 1)
1506 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1507 para = parser.tableDef->tableRowStart;
1508 ME_RTFSpecialCharHook(&parser);
1510 para = parser.tableDef->tableRowStart;
1511 ME_RTFSpecialCharHook(&parser);
1512 assert(para->member.para.nFlags & MEPF_ROWEND);
1513 para = para->member.para.next_para;
1516 editor->pCursors[1].pPara = para;
1517 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1518 editor->pCursors[1].nOffset = 0;
1519 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1520 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1521 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1522 if (parser.tableDef)
1523 parser.tableDef->tableRowStart = NULL;
1526 ME_CheckTablesForCorruption(editor);
1527 RTFDestroy(&parser);
1528 if (parser.lpRichEditOle)
1529 IRichEditOle_Release(parser.lpRichEditOle);
1531 if (parser.stackTop > 0)
1533 while (--parser.stackTop >= 0)
1535 ME_ReleaseStyle(parser.style);
1536 parser.style = parser.stack[parser.stackTop].style;
1538 if (!inStream.editstream->dwError)
1539 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1542 /* Remove last line break, as mandated by tests. This is not affected by
1543 CR/LF counters, since RTF streaming presents only \para tokens, which
1544 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1548 ME_GetSelection(editor, &selStart, &selEnd);
1549 newto = ME_GetCursorOfs(selEnd);
1550 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1551 WCHAR lastchar[3] = {'\0', '\0'};
1552 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1553 ME_Cursor linebreakCursor = *selEnd;
1555 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1556 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1557 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1558 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1563 style = parser.style;
1565 else if (format & SF_TEXT)
1566 ME_StreamInText(editor, format, &inStream, style);
1568 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1569 /* put the cursor at the top */
1570 if (!(format & SFF_SELECTION))
1571 ME_SetSelection(editor, 0, 0);
1574 /* Restore saved undo mode */
1575 editor->nUndoMode = nUndoMode;
1577 /* even if we didn't add an undo, we need to commit anything on the stack */
1578 ME_CommitUndo(editor);
1580 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1581 if (!(format & SFF_SELECTION))
1582 ME_EmptyUndoStack(editor);
1584 ME_ReleaseStyle(style);
1585 editor->nEventMask = nEventMask;
1586 ME_UpdateRepaint(editor, FALSE);
1587 if (!(format & SFF_SELECTION)) {
1588 ME_ClearTempStyle(editor);
1590 ITextHost_TxShowCaret(editor->texthost, FALSE);
1591 ME_MoveCaret(editor);
1592 ITextHost_TxShowCaret(editor->texthost, TRUE);
1593 ME_SendSelChange(editor);
1594 ME_SendRequestResize(editor, FALSE);
1600 typedef struct tagME_RTFStringStreamStruct
1605 } ME_RTFStringStreamStruct;
1607 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1609 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1612 count = min(cb, pStruct->length - pStruct->pos);
1613 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1614 pStruct->pos += count;
1620 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1623 ME_RTFStringStreamStruct data;
1625 data.string = string;
1626 data.length = strlen(string);
1628 es.dwCookie = (DWORD_PTR)&data;
1629 es.pfnCallback = ME_ReadFromRTFString;
1630 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1635 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1637 const int nLen = lstrlenW(text);
1638 const int nTextLen = ME_GetTextLength(editor);
1641 WCHAR wLastChar = ' ';
1643 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1644 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1646 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1647 FIXME("Flags 0x%08x not implemented\n",
1648 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1651 if (chrg->cpMax == -1)
1654 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1656 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1657 if (editor->bEmulateVersion10 && nMax == nTextLen)
1662 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1663 if (editor->bEmulateVersion10 && nMax < nMin)
1667 chrgText->cpMin = -1;
1668 chrgText->cpMax = -1;
1673 /* when searching up, if cpMin < cpMax, then instead of searching
1674 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1675 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1676 * case, it is always bigger than cpMin.
1678 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1682 nMax = nMin > nTextLen ? nTextLen : nMin;
1683 if (nMin < nSwap || chrg->cpMax == -1)
1689 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1692 chrgText->cpMin = chrgText->cpMax = -1;
1696 if (flags & FR_DOWN) /* Forward search */
1698 /* If possible, find the character before where the search starts */
1699 if ((flags & FR_WHOLEWORD) && nMin)
1701 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1702 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1703 ME_MoveCursorChars(editor, &cursor, 1);
1705 ME_CursorFromCharOfs(editor, nMin, &cursor);
1708 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1710 ME_DisplayItem *pCurItem = cursor.pRun;
1711 int nCurStart = cursor.nOffset;
1714 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1716 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1720 if (nMatched == nLen)
1722 ME_DisplayItem *pNextItem = pCurItem;
1723 int nNextStart = nCurStart;
1726 /* Check to see if next character is a whitespace */
1727 if (flags & FR_WHOLEWORD)
1729 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1731 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1732 nNextStart = -nMatched;
1736 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1740 if (isalnumW(wNextChar))
1744 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1747 chrgText->cpMin = cursor.nOffset;
1748 chrgText->cpMax = cursor.nOffset + nLen;
1750 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1751 return cursor.nOffset;
1753 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1755 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1756 nCurStart = -nMatched;
1760 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1765 if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1767 ME_NextRun(&cursor.pPara, &cursor.pRun);
1772 else /* Backward search */
1774 /* If possible, find the character after where the search ends */
1775 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1777 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1778 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1779 ME_MoveCursorChars(editor, &cursor, -1);
1781 ME_CursorFromCharOfs(editor, nMax, &cursor);
1784 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1786 ME_DisplayItem *pCurItem = cursor.pRun;
1787 ME_DisplayItem *pCurPara = cursor.pPara;
1788 int nCurEnd = cursor.nOffset;
1793 ME_PrevRun(&pCurPara, &pCurItem);
1794 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1797 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1799 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1803 if (nMatched == nLen)
1805 ME_DisplayItem *pPrevItem = pCurItem;
1806 int nPrevEnd = nCurEnd;
1810 /* Check to see if previous character is a whitespace */
1811 if (flags & FR_WHOLEWORD)
1813 if (nPrevEnd - nMatched == 0)
1815 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1817 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1821 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1825 if (isalnumW(wPrevChar))
1829 nStart = pCurPara->member.para.nCharOfs
1830 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1833 chrgText->cpMin = nStart;
1834 chrgText->cpMax = nStart + nLen;
1836 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1839 if (nCurEnd - nMatched == 0)
1841 ME_PrevRun(&pCurPara, &pCurItem);
1842 /* Don't care about pCurItem becoming NULL here; it's already taken
1843 * care of in the exterior loop condition */
1844 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1848 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1853 if (cursor.nOffset < 0)
1855 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1856 cursor.nOffset = cursor.pRun->member.run.strText->nLen;
1860 TRACE("not found\n");
1862 chrgText->cpMin = chrgText->cpMax = -1;
1866 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1871 if (!ex->cb || !pText) return 0;
1873 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1874 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1876 if (ex->flags & GT_SELECTION)
1879 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1880 start = editor->pCursors[nStartCur];
1885 ME_SetCursorToStart(editor, &start);
1888 if (ex->codepage == 1200)
1890 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1891 &start, nChars, ex->flags & GT_USECRLF);
1895 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1896 we can just take a bigger buffer? :)
1897 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1898 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1900 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1905 buflen = min(crlfmul * nChars, ex->cb - 1);
1906 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1908 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1909 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1910 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1911 if (rc) rc--; /* do not count 0 terminator */
1918 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1919 const ME_Cursor *start, int nLen, BOOL unicode)
1921 if (!strText) return 0;
1923 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1926 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1928 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1929 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1930 nLen+1, NULL, NULL);
1936 typedef struct tagME_GlobalDestStruct
1940 } ME_GlobalDestStruct;
1942 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1944 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1949 pDest = (WORD *)lpBuff;
1950 pSrc = GlobalLock(pData->hData);
1951 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1952 pDest[i] = pSrc[pData->nLength+i];
1954 pData->nLength += i;
1956 GlobalUnlock(pData->hData);
1960 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1962 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1967 pSrc = GlobalLock(pData->hData);
1968 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1969 pDest[i] = pSrc[pData->nLength+i];
1971 pData->nLength += i;
1973 GlobalUnlock(pData->hData);
1977 static BOOL ME_Paste(ME_TextEditor *editor)
1981 ME_GlobalDestStruct gds;
1982 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1985 if (IsClipboardFormatAvailable(nRTFFormat))
1986 cf = nRTFFormat, dwFormat = SF_RTF;
1987 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1988 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1992 if (!OpenClipboard(editor->hWnd))
1994 gds.hData = GetClipboardData(cf);
1996 es.dwCookie = (DWORD_PTR)&gds;
1997 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1998 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2004 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2006 LPDATAOBJECT dataObj = NULL;
2009 if (editor->cPasswordMask)
2010 return FALSE; /* Copying or Cutting masked text isn't allowed */
2012 if(editor->lpOleCallback)
2015 range.cpMin = ME_GetCursorOfs(start);
2016 range.cpMax = range.cpMin + nChars;
2017 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2019 if(FAILED(hr) || !dataObj)
2020 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2022 hr = OleSetClipboard(dataObj);
2023 IDataObject_Release(dataObj);
2025 return SUCCEEDED(hr) != 0;
2028 /* helper to send a msg filter notification */
2030 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2034 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2035 msgf.nmhdr.hwndFrom = editor->hWnd;
2036 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2037 msgf.nmhdr.code = EN_MSGFILTER;
2039 msgf.wParam = *wParam;
2040 msgf.lParam = *lParam;
2041 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2043 *wParam = msgf.wParam;
2044 *lParam = msgf.lParam;
2045 msgf.wParam = *wParam;
2050 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2052 ME_DisplayItem *startPara, *endPara;
2053 ME_DisplayItem *prev_para;
2054 ME_Cursor *from, *to;
2058 if (!editor->AutoURLDetect_bEnable) return;
2060 ME_GetSelection(editor, &from, &to);
2062 /* Find paragraph previous to the one that contains start cursor */
2063 startPara = from->pPara;
2064 prev_para = startPara->member.para.prev_para;
2065 if (prev_para->type == diParagraph) startPara = prev_para;
2067 /* Find paragraph that contains end cursor */
2068 endPara = to->pPara->member.para.next_para;
2070 start.pPara = startPara;
2071 start.pRun = ME_FindItemFwd(startPara, diRun);
2073 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2075 ME_UpdateLinkAttribute(editor, &start, nChars);
2079 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2081 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2082 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2084 if (editor->bMouseCaptured)
2086 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2087 editor->nSelectionType = stPosition;
2095 editor->nUDArrowX = -1;
2101 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2102 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2106 editor->nUDArrowX = -1;
2107 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2108 if (editor->styleFlags & ES_READONLY)
2110 if (ME_IsSelection(editor))
2112 ME_DeleteSelection(editor);
2113 ME_CommitUndo(editor);
2115 else if (nKey == VK_DELETE)
2117 /* Delete stops group typing.
2118 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2119 ME_DeleteTextAtCursor(editor, 1, 1);
2120 ME_CommitUndo(editor);
2122 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2124 BOOL bDeletionSucceeded;
2125 /* Backspace can be grouped for a single undo */
2126 ME_ContinueCoalescingTransaction(editor);
2127 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2128 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2129 /* Deletion was prevented so the cursor is moved back to where it was.
2130 * (e.g. this happens when trying to delete cell boundaries)
2132 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2134 ME_CommitCoalescingUndo(editor);
2138 ME_MoveCursorFromTableRowStartParagraph(editor);
2139 ME_UpdateSelectionLinkAttribute(editor);
2140 ME_UpdateRepaint(editor, FALSE);
2141 ME_SendRequestResize(editor, FALSE);
2144 if (editor->bDialogMode)
2149 if (!(editor->styleFlags & ES_WANTRETURN))
2151 if (editor->hwndParent)
2154 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2155 if (HIWORD(dw) == DC_HASDEFID)
2157 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2160 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2161 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2169 if (editor->styleFlags & ES_MULTILINE)
2171 ME_Cursor cursor = editor->pCursors[0];
2172 ME_DisplayItem *para = cursor.pPara;
2174 const WCHAR endl = '\r';
2177 if (editor->styleFlags & ES_READONLY) {
2178 MessageBeep(MB_ICONERROR);
2182 ME_GetSelectionOfs(editor, &from, &to);
2183 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2185 if (!editor->bEmulateVersion10) { /* v4.1 */
2186 if (para->member.para.nFlags & MEPF_ROWEND) {
2187 /* Add a new table row after this row. */
2188 para = ME_AppendTableRow(editor, para);
2189 para = para->member.para.next_para;
2190 editor->pCursors[0].pPara = para;
2191 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2192 editor->pCursors[0].nOffset = 0;
2193 editor->pCursors[1] = editor->pCursors[0];
2194 ME_CommitUndo(editor);
2195 ME_CheckTablesForCorruption(editor);
2196 ME_UpdateRepaint(editor, FALSE);
2199 else if (para == editor->pCursors[1].pPara &&
2200 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2201 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2202 !para->member.para.prev_para->member.para.nCharOfs)
2204 /* Insert a newline before the table. */
2205 para = para->member.para.prev_para;
2206 para->member.para.nFlags &= ~MEPF_ROWSTART;
2207 editor->pCursors[0].pPara = para;
2208 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2209 editor->pCursors[1] = editor->pCursors[0];
2210 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2211 editor->pCursors[0].pRun->member.run.style);
2212 para = editor->pBuffer->pFirst->member.para.next_para;
2213 ME_SetDefaultParaFormat(para->member.para.pFmt);
2214 para->member.para.nFlags = MEPF_REWRAP;
2215 editor->pCursors[0].pPara = para;
2216 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2217 editor->pCursors[1] = editor->pCursors[0];
2218 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2219 ME_CommitCoalescingUndo(editor);
2220 ME_CheckTablesForCorruption(editor);
2221 ME_UpdateRepaint(editor, FALSE);
2224 } else { /* v1.0 - 3.0 */
2225 ME_DisplayItem *para = cursor.pPara;
2226 if (ME_IsInTable(para))
2228 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2231 ME_ContinueCoalescingTransaction(editor);
2232 para = ME_AppendTableRow(editor, para);
2233 editor->pCursors[0].pPara = para;
2234 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2235 editor->pCursors[0].nOffset = 0;
2236 editor->pCursors[1] = editor->pCursors[0];
2237 ME_CommitCoalescingUndo(editor);
2238 ME_UpdateRepaint(editor, FALSE);
2242 ME_ContinueCoalescingTransaction(editor);
2243 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2244 !ME_IsInTable(para->member.para.prev_para))
2246 /* Insert newline before table */
2247 cursor.pRun = ME_FindItemBack(para, diRun);
2249 editor->pCursors[0].pRun = cursor.pRun;
2250 editor->pCursors[0].pPara = para->member.para.prev_para;
2252 editor->pCursors[0].nOffset = 0;
2253 editor->pCursors[1] = editor->pCursors[0];
2254 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2255 editor->pCursors[0].pRun->member.run.style);
2257 editor->pCursors[1] = editor->pCursors[0];
2258 para = ME_AppendTableRow(editor, para);
2259 editor->pCursors[0].pPara = para;
2260 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2261 editor->pCursors[0].nOffset = 0;
2262 editor->pCursors[1] = editor->pCursors[0];
2264 ME_CommitCoalescingUndo(editor);
2265 ME_UpdateRepaint(editor, FALSE);
2271 style = ME_GetInsertStyle(editor, 0);
2272 ME_SaveTempStyle(editor);
2273 ME_ContinueCoalescingTransaction(editor);
2275 ME_InsertEndRowFromCursor(editor, 0);
2277 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2278 ME_ReleaseStyle(style);
2279 ME_CommitCoalescingUndo(editor);
2282 ME_UpdateSelectionLinkAttribute(editor);
2283 ME_UpdateRepaint(editor, FALSE);
2289 if (editor->bDialogMode && editor->hwndParent)
2290 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2293 if (editor->bDialogMode && editor->hwndParent)
2294 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2299 ME_SetSelection(editor, 0, -1);
2305 return ME_Paste(editor);
2313 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2314 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2317 result = ME_Copy(editor, selStart, nChars);
2318 if (result && nKey == 'X')
2320 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2321 ME_CommitUndo(editor);
2322 ME_UpdateRepaint(editor, TRUE);
2343 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2344 editor->nUDArrowX = -1;
2351 chf.cbSize = sizeof(chf);
2353 ME_GetSelectionCharFormat(editor, &chf);
2354 ME_DumpStyleToBuf(&chf, buf);
2355 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2359 ME_CheckCharOffsets(editor);
2366 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2367 LPARAM flags, BOOL unicode)
2371 if (editor->bMouseCaptured)
2375 wstr = (WCHAR)charCode;
2378 CHAR charA = charCode;
2379 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2382 if (editor->styleFlags & ES_READONLY) {
2383 MessageBeep(MB_ICONERROR);
2384 return 0; /* FIXME really 0 ? */
2387 if ((unsigned)wstr >= ' ' || wstr == '\t')
2389 ME_Cursor cursor = editor->pCursors[0];
2390 ME_DisplayItem *para = cursor.pPara;
2392 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2393 ME_GetSelectionOfs(editor, &from, &to);
2395 /* v4.1 allows tabs to be inserted with ctrl key down */
2396 !(ctrl_is_down && !editor->bEmulateVersion10))
2398 ME_DisplayItem *para;
2399 BOOL bSelectedRow = FALSE;
2401 para = cursor.pPara;
2402 if (ME_IsSelection(editor) &&
2403 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2404 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2405 para->member.para.prev_para->type == diParagraph)
2407 para = para->member.para.prev_para;
2408 bSelectedRow = TRUE;
2410 if (ME_IsInTable(para))
2412 ME_TabPressedInTable(editor, bSelectedRow);
2413 ME_CommitUndo(editor);
2416 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2417 if (para->member.para.nFlags & MEPF_ROWEND) {
2419 para = para->member.para.next_para;
2420 if (para->member.para.nFlags & MEPF_ROWSTART)
2421 para = para->member.para.next_para;
2422 editor->pCursors[0].pPara = para;
2423 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2424 editor->pCursors[0].nOffset = 0;
2425 editor->pCursors[1] = editor->pCursors[0];
2428 } else { /* v1.0 - 3.0 */
2429 if (ME_IsInTable(cursor.pRun) &&
2430 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2433 /* Text should not be inserted at the end of the table. */
2438 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2439 /* WM_CHAR is restricted to nTextLimit */
2440 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2442 ME_Style *style = ME_GetInsertStyle(editor, 0);
2443 ME_SaveTempStyle(editor);
2444 ME_ContinueCoalescingTransaction(editor);
2445 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2446 ME_ReleaseStyle(style);
2447 ME_CommitCoalescingUndo(editor);
2448 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2451 ME_UpdateSelectionLinkAttribute(editor);
2452 ME_UpdateRepaint(editor, FALSE);
2457 /* Process the message and calculate the new click count.
2459 * returns: The click count if it is mouse down event, else returns 0. */
2460 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2463 static int clickNum = 0;
2464 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2467 if ((msg == WM_LBUTTONDBLCLK) ||
2468 (msg == WM_RBUTTONDBLCLK) ||
2469 (msg == WM_MBUTTONDBLCLK) ||
2470 (msg == WM_XBUTTONDBLCLK))
2472 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2475 if ((msg == WM_LBUTTONDOWN) ||
2476 (msg == WM_RBUTTONDOWN) ||
2477 (msg == WM_MBUTTONDOWN) ||
2478 (msg == WM_XBUTTONDOWN))
2480 static MSG prevClickMsg;
2482 /* Compare the editor instead of the hwnd so that the this
2483 * can still be done for windowless richedit controls. */
2484 clickMsg.hwnd = (HWND)editor;
2485 clickMsg.message = msg;
2486 clickMsg.wParam = wParam;
2487 clickMsg.lParam = lParam;
2488 clickMsg.time = GetMessageTime();
2489 clickMsg.pt.x = (short)LOWORD(lParam);
2490 clickMsg.pt.y = (short)HIWORD(lParam);
2491 if ((clickNum != 0) &&
2492 (clickMsg.message == prevClickMsg.message) &&
2493 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2494 (clickMsg.wParam == prevClickMsg.wParam) &&
2495 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2496 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2497 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2503 prevClickMsg = clickMsg;
2510 static BOOL ME_SetCursor(ME_TextEditor *editor)
2516 DWORD messagePos = GetMessagePos();
2517 pt.x = (short)LOWORD(messagePos);
2518 pt.y = (short)HIWORD(messagePos);
2522 sbi.cbSize = sizeof(sbi);
2523 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2524 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2525 PtInRect(&sbi.rcScrollBar, pt))
2527 ITextHost_TxSetCursor(editor->texthost,
2528 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2531 sbi.cbSize = sizeof(sbi);
2532 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2533 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2534 PtInRect(&sbi.rcScrollBar, pt))
2536 ITextHost_TxSetCursor(editor->texthost,
2537 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2541 ITextHost_TxScreenToClient(editor->texthost, &pt);
2543 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2544 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2547 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2548 pt.y < editor->rcFormat.top &&
2549 pt.x < editor->rcFormat.left)
2551 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2554 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2556 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2557 ITextHost_TxSetCursor(editor->texthost,
2558 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2560 ITextHost_TxSetCursor(editor->texthost,
2561 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2564 if (pt.x < editor->rcFormat.left)
2566 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2569 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2574 run = &cursor.pRun->member.run;
2575 if (run->style->fmt.dwMask & CFM_LINK &&
2576 run->style->fmt.dwEffects & CFE_LINK)
2578 ITextHost_TxSetCursor(editor->texthost,
2579 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2584 if (ME_IsSelection(editor))
2586 int selStart, selEnd;
2587 int offset = ME_GetCursorOfs(&cursor);
2589 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2590 if (selStart <= offset && selEnd >= offset) {
2591 ITextHost_TxSetCursor(editor->texthost,
2592 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2598 ITextHost_TxSetCursor(editor->texthost,
2599 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2603 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2605 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2606 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2607 editor->rcFormat.left += 1 + editor->selofs;
2608 editor->rcFormat.right -= 1;
2611 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2616 if(!editor->lpOleCallback || !editor->hWnd)
2618 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2619 if(selrange.cpMin == selrange.cpMax)
2620 seltype |= SEL_EMPTY;
2623 /* FIXME: Handle objects */
2624 seltype |= SEL_TEXT;
2625 if(selrange.cpMax-selrange.cpMin > 1)
2626 seltype |= SEL_MULTICHAR;
2628 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2630 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2636 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2638 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2644 ed->hwndParent = NULL;
2645 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2646 ed->texthost = texthost;
2647 ed->bEmulateVersion10 = bEmulateVersion10;
2649 ITextHost_TxGetPropertyBits(texthost,
2650 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2651 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2652 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2653 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2654 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2656 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2657 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2658 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2659 ed->pBuffer = ME_MakeText();
2660 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2661 ed->nAvailWidth = 0; /* wrap to client area */
2662 ME_MakeFirstParagraph(ed);
2663 /* The four cursors are for:
2664 * 0 - The position where the caret is shown
2665 * 1 - The anchored end of the selection (for normal selection)
2666 * 2 & 3 - The anchored start and end respectively for word, line,
2667 * or paragraph selection.
2670 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2671 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2672 ed->pCursors[1] = ed->pCursors[0];
2673 ed->pCursors[2] = ed->pCursors[0];
2674 ed->pCursors[3] = ed->pCursors[1];
2675 ed->nLastTotalLength = ed->nTotalLength = 0;
2676 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2679 ed->rgbBackColor = -1;
2680 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2681 ed->bCaretAtEnd = FALSE;
2683 ed->nModifyStep = 0;
2684 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2685 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2686 ed->nUndoStackSize = 0;
2687 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2688 ed->nUndoMode = umAddToUndo;
2689 ed->nParagraphs = 1;
2690 ed->nLastSelStart = ed->nLastSelEnd = 0;
2691 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2692 ed->bHideSelection = FALSE;
2693 ed->pfnWordBreak = NULL;
2694 ed->lpOleCallback = NULL;
2695 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2696 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2697 ed->AutoURLDetect_bEnable = FALSE;
2698 ed->bHaveFocus = FALSE;
2699 ed->bDialogMode = FALSE;
2700 ed->bMouseCaptured = FALSE;
2701 for (i=0; i<HFONT_CACHE_SIZE; i++)
2703 ed->pFontCache[i].nRefs = 0;
2704 ed->pFontCache[i].nAge = 0;
2705 ed->pFontCache[i].hFont = NULL;
2708 ME_CheckCharOffsets(ed);
2709 ed->bDefaultFormatRect = TRUE;
2710 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2712 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2713 ed->selofs = SELECTIONBAR_WIDTH;
2714 ed->styleFlags |= ES_SELECTIONBAR;
2718 ed->nSelectionType = stPosition;
2720 ed->cPasswordMask = 0;
2721 if (props & TXTBIT_USEPASSWORD)
2722 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2724 if (props & TXTBIT_AUTOWORDSEL)
2725 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2726 if (props & TXTBIT_MULTILINE) {
2727 ed->styleFlags |= ES_MULTILINE;
2728 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2730 ed->bWordWrap = FALSE;
2732 if (props & TXTBIT_READONLY)
2733 ed->styleFlags |= ES_READONLY;
2734 if (!(props & TXTBIT_HIDESELECTION))
2735 ed->styleFlags |= ES_NOHIDESEL;
2736 if (props & TXTBIT_SAVESELECTION)
2737 ed->styleFlags |= ES_SAVESEL;
2738 if (props & TXTBIT_VERTICAL)
2739 ed->styleFlags |= ES_VERTICAL;
2740 if (props & TXTBIT_DISABLEDRAG)
2741 ed->styleFlags |= ES_NOOLEDRAGDROP;
2743 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2745 /* Default scrollbar information */
2746 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2747 ed->vert_si.nMin = 0;
2748 ed->vert_si.nMax = 0;
2749 ed->vert_si.nPage = 0;
2750 ed->vert_si.nPos = 0;
2752 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2753 ed->horz_si.nMin = 0;
2754 ed->horz_si.nMax = 0;
2755 ed->horz_si.nPage = 0;
2756 ed->horz_si.nPos = 0;
2758 OleInitialize(NULL);
2763 static void ME_DestroyEditor(ME_TextEditor *editor)
2765 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2766 ME_DisplayItem *p = pFirst, *pNext = NULL;
2769 ME_ClearTempStyle(editor);
2770 ME_EmptyUndoStack(editor);
2773 ME_DestroyDisplayItem(p);
2776 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2777 for (i=0; i<HFONT_CACHE_SIZE; i++)
2779 if (editor->pFontCache[i].hFont)
2780 DeleteObject(editor->pFontCache[i].hFont);
2782 if (editor->rgbBackColor != -1)
2783 DeleteObject(editor->hbrBackground);
2784 if(editor->lpOleCallback)
2785 IUnknown_Release(editor->lpOleCallback);
2786 IUnknown_Release(editor->texthost);
2789 FREE_OBJ(editor->pBuffer);
2790 FREE_OBJ(editor->pCursors);
2795 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2800 case DLL_PROCESS_ATTACH:
2801 DisableThreadLibraryCalls(hinstDLL);
2802 me_heap = HeapCreate (0, 0x10000, 0);
2803 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2804 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2808 case DLL_PROCESS_DETACH:
2809 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2810 UnregisterClassW(MSFTEDIT_CLASS, 0);
2811 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2812 UnregisterClassA("RichEdit50A", 0);
2813 if (ME_ListBoxRegistered)
2814 UnregisterClassW(REListBox20W, 0);
2815 if (ME_ComboBoxRegistered)
2816 UnregisterClassW(REComboBox20W, 0);
2818 HeapDestroy (me_heap);
2826 static const char * const edit_messages[] = {
2855 "EM_SETPASSWORDCHAR",
2856 "EM_EMPTYUNDOBUFFER",
2857 "EM_GETFIRSTVISIBLELINE",
2859 "EM_SETWORDBREAKPROC",
2860 "EM_GETWORDBREAKPROC",
2861 "EM_GETPASSWORDCHAR",
2871 static const char * const richedit_messages[] = {
2876 "EM_EXLINEFROMCHAR",
2882 "EM_GETOLEINTERFACE",
2892 "EM_SETOLECALLBACK",
2894 "EM_SETTARGETDEVICE",
2902 "EM_GETWORDBREAKPROCEX",
2903 "EM_SETWORDBREAKPROCEX",
2905 "EM_UNKNOWN_USER_83",
2910 "EM_STOPGROUPTYPING",
2914 "EM_GETAUTOURLDETECT",
2917 "EM_GETTEXTLENGTHEX",
2920 "EM_UNKNOWN_USER_98",
2921 "EM_UNKNOWN_USER_99",
2922 "EM_SETPUNCTUATION",
2923 "EM_GETPUNCTUATION",
2924 "EM_SETWORDWRAPMODE",
2925 "EM_GETWORDWRAPMODE",
2931 "EM_UNKNOWN_USER_109",
2932 "EM_UNKNOWN_USER_110",
2933 "EM_UNKNOWN_USER_111",
2934 "EM_UNKNOWN_USER_112",
2935 "EM_UNKNOWN_USER_113",
2936 "EM_UNKNOWN_USER_114",
2937 "EM_UNKNOWN_USER_115",
2938 "EM_UNKNOWN_USER_116",
2939 "EM_UNKNOWN_USER_117",
2940 "EM_UNKNOWN_USER_118",
2941 "EM_UNKNOWN_USER_119",
2942 "EM_SETLANGOPTIONS",
2943 "EM_GETLANGOPTIONS",
2944 "EM_GETIMECOMPMODE",
2948 "EM_SETIMEMODEBIAS",
2953 get_msg_name(UINT msg)
2955 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2956 return edit_messages[msg - EM_GETSEL];
2957 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2958 return richedit_messages[msg - EM_CANPASTE];
2962 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2966 ME_Cursor cursor; /* The start of the clicked text. */
2969 x = (short)LOWORD(lParam);
2970 y = (short)HIWORD(lParam);
2971 ME_CharFromPos(editor, x, y, &cursor, &isExact);
2972 if (!isExact) return;
2974 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
2975 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
2976 { /* The clicked run has CFE_LINK set */
2977 info.nmhdr.hwndFrom = NULL;
2978 info.nmhdr.idFrom = 0;
2979 info.nmhdr.code = EN_LINK;
2981 info.wParam = wParam;
2982 info.lParam = lParam;
2984 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
2985 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
2986 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
2990 #define UNSUPPORTED_MSG(e) \
2992 FIXME(#e ": stub\n"); \
2993 *phresult = S_FALSE; \
2996 /* Handle messages for windowless and windoweded richedit controls.
2998 * The LRESULT that is returned is a return value for window procs,
2999 * and the phresult parameter is the COM return code needed by the
3000 * text services interface. */
3001 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3002 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3008 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3009 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3010 UNSUPPORTED_MSG(EM_FMTLINES)
3011 UNSUPPORTED_MSG(EM_FORMATRANGE)
3012 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3013 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3014 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3015 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3016 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3017 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3018 UNSUPPORTED_MSG(EM_GETREDONAME)
3019 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3020 UNSUPPORTED_MSG(EM_GETUNDONAME)
3021 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3022 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3023 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3024 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3025 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3026 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3027 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3028 UNSUPPORTED_MSG(EM_SETMARGINS)
3029 UNSUPPORTED_MSG(EM_SETPALETTE)
3030 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3031 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3032 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3034 /* Messages specific to Richedit controls */
3037 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3039 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3042 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3044 editor->bDialogMode = TRUE;
3045 if (editor->styleFlags & ES_MULTILINE)
3046 code |= DLGC_WANTMESSAGE;
3049 case EM_EMPTYUNDOBUFFER:
3050 ME_EmptyUndoStack(editor);
3054 /* Note: wParam/lParam can be NULL */
3056 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3057 PUINT pto = lParam ? (PUINT)lParam : &to;
3058 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3059 if ((*pfrom|*pto) & 0xFFFF0000)
3061 return MAKELONG(*pfrom,*pto);
3065 CHARRANGE *pRange = (CHARRANGE *)lParam;
3066 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3067 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3070 case EM_SETUNDOLIMIT:
3072 if ((int)wParam < 0)
3073 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3075 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3076 /* Setting a max stack size keeps wine from getting killed
3077 for hogging memory. Windows allocates all this memory at once, so
3078 no program would realistically set a value above our maximum. */
3079 return editor->nUndoLimit;
3082 return editor->pUndoStack != NULL;
3084 return editor->pRedoStack != NULL;
3085 case WM_UNDO: /* FIXME: actually not the same */
3087 return ME_Undo(editor);
3089 return ME_Redo(editor);
3092 /* these flags are equivalent to the ES_* counterparts */
3093 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3094 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3095 DWORD settings = editor->styleFlags & mask;
3101 /* these flags are equivalent to ES_* counterparts, except for
3102 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3103 * but is still stored in editor->styleFlags. */
3104 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3105 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3106 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3107 DWORD settings = mask & editor->styleFlags;
3108 DWORD oldSettings = settings;
3109 DWORD changedSettings;
3125 changedSettings = oldSettings ^ settings;
3127 if (changedSettings) {
3128 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3130 if (changedSettings & ECO_SELECTIONBAR)
3132 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3133 if (settings & ECO_SELECTIONBAR) {
3134 assert(!editor->selofs);
3135 editor->selofs = SELECTIONBAR_WIDTH;
3136 editor->rcFormat.left += editor->selofs;
3138 editor->rcFormat.left -= editor->selofs;
3141 ME_RewrapRepaint(editor);
3144 if (changedSettings & settings & ECO_VERTICAL)
3145 FIXME("ECO_VERTICAL not implemented yet!\n");
3146 if (changedSettings & settings & ECO_AUTOHSCROLL)
3147 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3148 if (changedSettings & settings & ECO_AUTOVSCROLL)
3149 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3150 if (changedSettings & settings & ECO_NOHIDESEL)
3151 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3152 if (changedSettings & settings & ECO_WANTRETURN)
3153 FIXME("ECO_WANTRETURN not implemented yet!\n");
3154 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3155 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3162 ME_InvalidateSelection(editor);
3163 ME_SetSelection(editor, wParam, lParam);
3164 ME_InvalidateSelection(editor);
3165 ITextHost_TxShowCaret(editor->texthost, FALSE);
3166 ME_ShowCaret(editor);
3167 ME_SendSelChange(editor);
3170 case EM_SETSCROLLPOS:
3172 POINT *point = (POINT *)lParam;
3173 ME_ScrollAbs(editor, point->x, point->y);
3176 case EM_AUTOURLDETECT:
3178 if (wParam==1 || wParam ==0)
3180 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3183 return E_INVALIDARG;
3185 case EM_GETAUTOURLDETECT:
3187 return editor->AutoURLDetect_bEnable;
3192 CHARRANGE range = *(CHARRANGE *)lParam;
3194 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3196 ME_InvalidateSelection(editor);
3197 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3198 ME_InvalidateSelection(editor);
3199 ITextHost_TxShowCaret(editor->texthost, FALSE);
3200 ME_ShowCaret(editor);
3201 ME_SendSelChange(editor);
3205 case EM_SHOWSCROLLBAR:
3218 flags = WS_HSCROLL|WS_VSCROLL;
3225 editor->styleFlags |= flags;
3226 if (flags & WS_HSCROLL)
3227 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3228 editor->nTotalWidth > editor->sizeWindow.cx);
3229 if (flags & WS_VSCROLL)
3230 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3231 editor->nTotalLength > editor->sizeWindow.cy);
3233 editor->styleFlags &= ~flags;
3234 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3241 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3245 BOOL bRtf, bUnicode, bSelection;
3246 int oldModify = editor->nModifyStep;
3248 if (!pStruct) return 0;
3250 /* If we detect ascii rtf at the start of the string,
3251 * we know it isn't unicode. */
3252 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3253 !strncmp((char *)lParam, "{\\urtf", 6)));
3254 bUnicode = !bRtf && pStruct->codepage == 1200;
3256 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3257 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3258 pStruct->flags, pStruct->codepage);
3260 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3262 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3263 style = ME_GetSelectionInsertStyle(editor);
3264 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3267 ME_SetCursorToStart(editor, &start);
3268 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3269 style = editor->pBuffer->pDefaultStyle;
3273 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3275 /* FIXME: The length returned doesn't include the rtf control
3276 * characters, only the actual text. */
3277 len = lParam ? strlen((char *)lParam) : 0;
3280 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3281 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3282 len = wszText ? lstrlenW(wszText) : 0;
3283 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3284 ME_EndToUnicode(bUnicode, wszText);
3288 ME_ReleaseStyle(style);
3289 ME_UpdateSelectionLinkAttribute(editor);
3293 ME_SetCursorToStart(editor, &cursor);
3294 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3296 ME_CommitUndo(editor);
3297 if (!(pStruct->flags & ST_KEEPUNDO))
3299 editor->nModifyStep = oldModify;
3300 ME_EmptyUndoStack(editor);
3302 ME_UpdateRepaint(editor, FALSE);
3305 case EM_SETBKGNDCOLOR:
3308 if (editor->rgbBackColor != -1) {
3309 DeleteObject(editor->hbrBackground);
3310 lColor = editor->rgbBackColor;
3312 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3316 editor->rgbBackColor = -1;
3317 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3321 editor->rgbBackColor = lParam;
3322 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3324 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3325 ITextHost_TxViewChange(editor->texthost, TRUE);
3329 return editor->nModifyStep == 0 ? 0 : -1;
3333 editor->nModifyStep = 1;
3335 editor->nModifyStep = 0;
3339 case EM_SETREADONLY:
3342 editor->styleFlags |= ES_READONLY;
3344 editor->styleFlags &= ~ES_READONLY;
3347 case EM_SETEVENTMASK:
3349 DWORD nOldMask = editor->nEventMask;
3351 editor->nEventMask = lParam;
3354 case EM_GETEVENTMASK:
3355 return editor->nEventMask;
3356 case EM_SETCHARFORMAT:
3358 CHARFORMAT2W buf, *p;
3359 BOOL bRepaint = TRUE;
3360 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3361 if (p == NULL) return 0;
3362 if (wParam & SCF_ALL) {
3363 if (editor->mode & TM_PLAINTEXT) {
3364 ME_SetDefaultCharFormat(editor, p);
3367 ME_SetCursorToStart(editor, &start);
3368 ME_SetCharFormat(editor, &start, NULL, p);
3369 editor->nModifyStep = 1;
3371 } else if (wParam & SCF_SELECTION) {
3372 if (editor->mode & TM_PLAINTEXT)
3374 if (wParam & SCF_WORD) {
3375 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3378 bRepaint = ME_IsSelection(editor);
3379 ME_SetSelectionCharFormat(editor, p);
3380 if (bRepaint) editor->nModifyStep = 1;
3381 } else { /* SCF_DEFAULT */
3382 ME_SetDefaultCharFormat(editor, p);
3384 ME_CommitUndo(editor);
3387 ME_WrapMarkedParagraphs(editor);
3388 ME_UpdateScrollBar(editor);
3393 case EM_GETCHARFORMAT:
3395 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3396 if (dst->cbSize != sizeof(CHARFORMATA) &&
3397 dst->cbSize != sizeof(CHARFORMATW) &&
3398 dst->cbSize != sizeof(CHARFORMAT2A) &&
3399 dst->cbSize != sizeof(CHARFORMAT2W))
3401 tmp.cbSize = sizeof(tmp);
3403 ME_GetDefaultCharFormat(editor, &tmp);
3405 ME_GetSelectionCharFormat(editor, &tmp);
3406 ME_CopyToCFAny(dst, &tmp);
3409 case EM_SETPARAFORMAT:
3411 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3412 ME_WrapMarkedParagraphs(editor);
3413 ME_UpdateScrollBar(editor);
3415 ME_CommitUndo(editor);
3418 case EM_GETPARAFORMAT:
3419 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3420 return ((PARAFORMAT2 *)lParam)->dwMask;
3421 case EM_GETFIRSTVISIBLELINE:
3423 ME_DisplayItem *p = editor->pBuffer->pFirst;
3424 int y = editor->vert_si.nPos;
3429 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3430 if (p->type == diTextEnd)
3432 if (p->type == diParagraph) {
3433 ypara = p->member.para.pt.y;
3436 ystart = ypara + p->member.row.pt.y;
3437 yend = ystart + p->member.row.nHeight;
3445 case EM_HIDESELECTION:
3447 editor->bHideSelection = (wParam != 0);
3448 ME_InvalidateSelection(editor);
3453 if (!(editor->styleFlags & ES_MULTILINE))
3455 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3461 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3462 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3463 ME_CommitUndo(editor);
3464 ME_UpdateRepaint(editor, TRUE);
3469 int from, to, nStartCursor;
3471 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3472 size_t len = wszText ? lstrlenW(wszText) : 0;
3473 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3475 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3476 style = ME_GetSelectionInsertStyle(editor);
3477 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3478 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3479 ME_ReleaseStyle(style);
3480 /* drop temporary style if line end */
3482 * FIXME question: does abc\n mean: put abc,
3483 * clear temp style, put \n? (would require a change)
3485 if (len>0 && wszText[len-1] == '\n')
3486 ME_ClearTempStyle(editor);
3487 ME_EndToUnicode(unicode, wszText);
3488 ME_CommitUndo(editor);
3489 ME_UpdateSelectionLinkAttribute(editor);
3491 ME_EmptyUndoStack(editor);
3492 ME_UpdateRepaint(editor, FALSE);
3495 case EM_SCROLLCARET:
3496 ME_EnsureVisible(editor, &editor->pCursors[0]);
3503 BOOL bRepaint = LOWORD(lParam);
3506 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3507 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3508 hDC = ITextHost_TxGetDC(editor->texthost);
3509 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3510 ITextHost_TxReleaseDC(editor->texthost, hDC);
3511 if (editor->mode & TM_RICHTEXT) {
3513 ME_SetCursorToStart(editor, &start);
3514 ME_SetCharFormat(editor, &start, NULL, &fmt);
3516 ME_SetDefaultCharFormat(editor, &fmt);
3518 ME_CommitUndo(editor);
3519 ME_MarkAllForWrapping(editor);
3520 ME_WrapMarkedParagraphs(editor);
3521 ME_UpdateScrollBar(editor);
3529 ME_SetCursorToStart(editor, &cursor);
3530 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3533 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3534 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3535 !strncmp((char *)lParam, "{\\urtf", 6))
3537 /* Undocumented: WM_SETTEXT supports RTF text */
3538 ME_StreamInRTFString(editor, 0, (char *)lParam);
3542 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3543 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3544 if (lstrlenW(wszText) > 0)
3548 /* uses default style! */
3549 if (!(editor->styleFlags & ES_MULTILINE))
3554 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3557 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3559 ME_EndToUnicode(unicode, wszText);
3563 TRACE("WM_SETTEXT - NULL\n");
3564 ME_SetCursorToStart(editor, &cursor);
3565 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3566 ME_SetSelection(editor, 0, 0);
3567 editor->nModifyStep = 0;
3568 ME_CommitUndo(editor);
3569 ME_EmptyUndoStack(editor);
3570 ME_UpdateRepaint(editor, FALSE);
3575 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3576 if (IsClipboardFormatAvailable(nRTFFormat))
3578 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3588 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3589 int nChars = nTo - nFrom;
3590 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3592 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3594 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3595 ME_CommitUndo(editor);
3596 ME_UpdateRepaint(editor, TRUE);
3600 case WM_GETTEXTLENGTH:
3602 GETTEXTLENGTHEX how;
3604 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3605 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3606 how.codepage = unicode ? 1200 : CP_ACP;
3607 return ME_GetTextLengthEx(editor, &how);
3609 case EM_GETTEXTLENGTHEX:
3610 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3614 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3615 ex.flags = GT_USECRLF;
3616 ex.codepage = unicode ? 1200 : CP_ACP;
3617 ex.lpDefaultChar = NULL;
3618 ex.lpUsedDefChar = NULL;
3619 return ME_GetTextEx(editor, &ex, lParam);
3622 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3625 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3626 ME_Cursor *from = &editor->pCursors[nStartCur];
3627 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3628 nTo - nFrom, unicode);
3630 case EM_GETSCROLLPOS:
3632 POINT *point = (POINT *)lParam;
3633 point->x = editor->horz_si.nPos;
3634 point->y = editor->vert_si.nPos;
3635 /* 16-bit scaled value is returned as stored in scrollinfo */
3636 if (editor->horz_si.nMax > 0xffff)
3637 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3638 if (editor->vert_si.nMax > 0xffff)
3639 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3642 case EM_GETTEXTRANGE:
3644 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3646 int nStart = rng->chrg.cpMin;
3647 int nEnd = rng->chrg.cpMax;
3648 int textlength = ME_GetTextLength(editor);
3650 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3651 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3652 if (nStart < 0) return 0;
3653 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3655 if (nStart >= nEnd) return 0;
3657 ME_CursorFromCharOfs(editor, nStart, &start);
3658 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3662 ME_DisplayItem *run;
3663 const unsigned int nMaxChars = *(WORD *) lParam;
3664 unsigned int nCharsLeft = nMaxChars;
3665 char *dest = (char *) lParam;
3666 BOOL wroteNull = FALSE;
3668 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3669 unicode ? "Unicode" : "Ansi");
3671 run = ME_FindRowWithNumber(editor, wParam);
3675 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3676 && run->type == diRun)
3681 strText = run->member.run.strText;
3682 nCopy = min(nCharsLeft, strText->nLen);
3685 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3687 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3688 nCharsLeft, NULL, NULL);
3689 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3690 nCharsLeft -= nCopy;
3693 /* append line termination, space allowing */
3697 *((WCHAR *)dest) = '\0';
3704 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3705 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3707 case EM_GETLINECOUNT:
3709 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3712 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3714 while (item != editor->pBuffer->pLast)
3716 assert(item->type == diParagraph);
3717 prev_para = ME_FindItemBack(item, diRun);
3719 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3721 nRows += item->member.para.nRows;
3722 item = item->member.para.next_para;
3724 last_para = ME_FindItemBack(item, diRun);
3726 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3727 if (editor->bEmulateVersion10 && prev_para &&
3728 last_para->member.run.nCharOfs == 0 &&
3729 prev_para->member.run.strText->nLen == 1 &&
3730 prev_para->member.run.strText->szData[0] == '\r')
3732 /* In 1.0 emulation, the last solitary \r at the very end of the text
3733 (if one exists) is NOT a line break.
3734 FIXME: this is an ugly hack. This should have a more regular model. */
3738 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3739 return max(1, nRows);
3741 case EM_LINEFROMCHAR:
3744 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3746 return ME_RowNumberFromCharOfs(editor, wParam);
3748 case EM_EXLINEFROMCHAR:
3751 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3753 return ME_RowNumberFromCharOfs(editor, lParam);
3757 ME_DisplayItem *item, *para;
3761 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3763 item = ME_FindRowWithNumber(editor, wParam);
3766 para = ME_GetParagraph(item);
3767 item = ME_FindItemFwd(item, diRun);
3768 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3769 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3774 ME_DisplayItem *item, *item_end;
3775 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3776 ME_DisplayItem *para, *run;
3778 if (wParam > ME_GetTextLength(editor))
3782 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3785 ME_RunOfsFromCharOfs(editor, wParam, ¶, &run, NULL);
3786 item = ME_RowStart(run);
3787 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3788 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3789 if (item_end->type == diStartRow) {
3790 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3792 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3793 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3794 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3796 nChars = nNextLineOfs - nThisLineOfs;
3797 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3800 case EM_EXLIMITTEXT:
3802 if ((int)lParam < 0)
3805 editor->nTextLimit = 65536;
3807 editor->nTextLimit = (int) lParam;
3813 editor->nTextLimit = 65536;
3815 editor->nTextLimit = (int) wParam;
3818 case EM_GETLIMITTEXT:
3820 return editor->nTextLimit;
3824 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3825 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3829 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3830 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3831 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3837 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3838 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3842 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3843 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3844 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3850 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3851 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3853 case EM_FINDTEXTEXW:
3855 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3856 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3859 if (!wParam || !lParam)
3861 *(int *)wParam = editor->nZoomNumerator;
3862 *(int *)lParam = editor->nZoomDenominator;
3865 return ME_SetZoom(editor, wParam, lParam);
3866 case EM_CHARFROMPOS:
3869 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3871 return ME_GetCursorOfs(&cursor);
3875 case EM_POSFROMCHAR:
3877 ME_DisplayItem *pPara, *pRun;
3878 int nCharOfs, nOffset, nLength;
3882 /* detect which API version we're dealing with */
3883 if (wParam >= 0x40000)
3885 nLength = ME_GetTextLength(editor);
3886 nCharOfs = min(nCharOfs, nLength);
3887 nCharOfs = max(nCharOfs, 0);
3889 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3890 assert(pRun->type == diRun);
3891 pt.y = pRun->member.run.pt.y;
3892 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3893 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3894 pt.x += editor->rcFormat.left;
3896 pt.x -= editor->horz_si.nPos;
3897 pt.y -= editor->vert_si.nPos;
3899 if (wParam >= 0x40000) {
3900 *(POINTL *)wParam = pt;
3902 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3908 ME_SetDefaultFormatRect(editor);
3910 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3911 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3912 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3914 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3915 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3917 if (editor->styleFlags & ES_DISABLENOSCROLL)
3919 if (editor->styleFlags & WS_VSCROLL)
3921 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3922 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3924 if (editor->styleFlags & WS_HSCROLL)
3926 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3927 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3931 ME_CommitUndo(editor);
3932 ME_WrapMarkedParagraphs(editor);
3933 ME_MoveCaret(editor);
3937 ME_DestroyEditor(editor);
3941 return ME_SetCursor(editor);
3943 case WM_LBUTTONDBLCLK:
3944 case WM_LBUTTONDOWN:
3946 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3947 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3948 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3950 ITextHost_TxSetFocus(editor->texthost);
3951 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3952 ME_CalculateClickCount(editor, msg, wParam, lParam));
3953 ITextHost_TxSetCapture(editor->texthost, TRUE);
3954 editor->bMouseCaptured = TRUE;
3955 ME_LinkNotify(editor,msg,wParam,lParam);
3956 if (!ME_SetCursor(editor)) goto do_default;
3960 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3961 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3963 if (editor->bMouseCaptured)
3964 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3965 ME_LinkNotify(editor,msg,wParam,lParam);
3966 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3967 if (editor->bMouseCaptured)
3968 ME_SetCursor(editor);
3971 if (editor->bMouseCaptured) {
3972 ITextHost_TxSetCapture(editor->texthost, FALSE);
3973 editor->bMouseCaptured = FALSE;
3975 if (editor->nSelectionType == stDocument)
3976 editor->nSelectionType = stPosition;
3977 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3978 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3982 ME_SetCursor(editor);
3983 ME_LinkNotify(editor,msg,wParam,lParam);
3987 case WM_RBUTTONDOWN:
3988 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3989 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3990 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3993 case WM_CONTEXTMENU:
3994 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3998 editor->bHaveFocus = TRUE;
3999 ME_ShowCaret(editor);
4000 ME_SendOldNotify(editor, EN_SETFOCUS);
4003 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4004 editor->bHaveFocus = FALSE;
4005 ME_HideCaret(editor);
4006 ME_SendOldNotify(editor, EN_KILLFOCUS);
4009 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4012 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4013 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4017 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4018 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4020 if (ME_KeyDown(editor, LOWORD(wParam)))
4024 return ME_Char(editor, wParam, lParam, unicode);
4028 if(wParam == UNICODE_NOCHAR) return TRUE;
4029 if(wParam <= 0x000fffff)
4031 if(wParam > 0xffff) /* convert to surrogates */
4034 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4035 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4037 ME_Char(editor, wParam, 0, TRUE);
4043 case EM_STOPGROUPTYPING:
4044 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4048 const int scrollUnit = 7;
4050 switch(LOWORD(wParam))
4053 ME_ScrollAbs(editor, 0, 0);
4056 ME_ScrollAbs(editor,
4057 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4058 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4061 ME_ScrollLeft(editor, scrollUnit);
4064 ME_ScrollRight(editor, scrollUnit);
4067 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4070 ME_ScrollRight(editor, editor->sizeWindow.cx);
4073 case SB_THUMBPOSITION:
4075 int pos = HIWORD(wParam);
4076 if (editor->horz_si.nMax > 0xffff)
4077 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4078 ME_HScrollAbs(editor, pos);
4084 case EM_SCROLL: /* fall through */
4090 origNPos = editor->vert_si.nPos;
4093 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4094 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4095 if (lineHeight <= 0) lineHeight = 24;
4097 switch(LOWORD(wParam))
4100 ME_ScrollAbs(editor, 0, 0);
4103 ME_ScrollAbs(editor,
4104 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4105 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4108 ME_ScrollUp(editor,lineHeight);
4111 ME_ScrollDown(editor,lineHeight);
4114 ME_ScrollUp(editor,editor->sizeWindow.cy);
4117 ME_ScrollDown(editor,editor->sizeWindow.cy);
4120 case SB_THUMBPOSITION:
4122 int pos = HIWORD(wParam);
4123 if (editor->vert_si.nMax > 0xffff)
4124 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4125 ME_VScrollAbs(editor, pos);
4129 if (msg == EM_SCROLL)
4130 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4136 UINT pulScrollLines;
4139 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4140 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4143 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4145 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4147 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4151 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4155 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4157 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4158 if (numerator >= 10 && numerator <= 500)
4159 ME_SetZoom(editor, numerator, 100);
4161 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4162 /* FIXME follow the original */
4164 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4171 *((RECT *)lParam) = editor->rcFormat;
4172 if (editor->bDefaultFormatRect)
4173 ((RECT *)lParam)->left -= editor->selofs;
4183 RECT *rc = (RECT *)lParam;
4185 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4186 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4189 editor->rcFormat.top = max(0, rc->top - border);
4190 editor->rcFormat.left = max(0, rc->left - border);
4191 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4192 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4193 } else if (wParam == 1) {
4194 /* MSDN incorrectly says a wParam value of 1 causes the
4195 * lParam rect to be used as a relative offset,
4196 * however, the tests show it just prevents min/max bound
4198 editor->rcFormat.top = rc->top - border;
4199 editor->rcFormat.left = rc->left - border;
4200 editor->rcFormat.bottom = rc->bottom;
4201 editor->rcFormat.right = rc->right + border;
4205 editor->bDefaultFormatRect = FALSE;
4209 ME_SetDefaultFormatRect(editor);
4210 editor->bDefaultFormatRect = TRUE;
4212 ME_MarkAllForWrapping(editor);
4213 ME_WrapMarkedParagraphs(editor);
4214 ME_UpdateScrollBar(editor);
4215 if (msg != EM_SETRECTNP)
4219 case EM_REQUESTRESIZE:
4220 ME_SendRequestResize(editor, TRUE);
4228 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4229 if (editor->bDefaultFormatRect) {
4230 ME_SetDefaultFormatRect(editor);
4232 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4233 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4235 editor->prevClientRect = clientRect;
4236 ME_RewrapRepaint(editor);
4239 /* IME messages to make richedit controls IME aware */
4240 case WM_IME_SETCONTEXT:
4241 case WM_IME_CONTROL:
4243 case WM_IME_COMPOSITIONFULL:
4245 case WM_IME_STARTCOMPOSITION:
4247 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4248 ME_DeleteSelection(editor);
4249 ME_CommitUndo(editor);
4250 ME_UpdateRepaint(editor, FALSE);
4253 case WM_IME_COMPOSITION:
4257 ME_Style *style = ME_GetInsertStyle(editor, 0);
4258 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4259 ME_DeleteSelection(editor);
4260 ME_SaveTempStyle(editor);
4261 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4263 LPWSTR lpCompStr = NULL;
4265 DWORD dwIndex = lParam & GCS_RESULTSTR;
4267 dwIndex = GCS_COMPSTR;
4269 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4270 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4271 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4272 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4273 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4274 HeapFree(GetProcessHeap(), 0, lpCompStr);
4276 if (dwIndex == GCS_COMPSTR)
4277 ME_SetSelection(editor,editor->imeStartIndex,
4278 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4280 ME_ReleaseStyle(style);
4281 ME_CommitUndo(editor);
4282 ME_UpdateRepaint(editor, FALSE);
4285 case WM_IME_ENDCOMPOSITION:
4287 ME_DeleteSelection(editor);
4288 editor->imeStartIndex=-1;
4291 case EM_GETOLEINTERFACE:
4293 LPVOID *ppvObj = (LPVOID*) lParam;
4294 return CreateIRichEditOle(editor, ppvObj);
4296 case EM_GETPASSWORDCHAR:
4298 return editor->cPasswordMask;
4300 case EM_SETOLECALLBACK:
4301 if(editor->lpOleCallback)
4302 IUnknown_Release(editor->lpOleCallback);
4303 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4304 if(editor->lpOleCallback)
4305 IUnknown_AddRef(editor->lpOleCallback);
4307 case EM_GETWORDBREAKPROC:
4308 return (LRESULT)editor->pfnWordBreak;
4309 case EM_SETWORDBREAKPROC:
4311 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4313 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4314 return (LRESULT)pfnOld;
4316 case EM_GETTEXTMODE:
4317 return editor->mode;
4318 case EM_SETTEXTMODE:
4323 if (ME_GetTextLength(editor) || editor->pUndoStack || editor->pRedoStack)
4324 return E_UNEXPECTED;
4326 /* Check for mutually exclusive flags in adjacent bits of wParam */
4327 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4328 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4329 return E_INVALIDARG;
4331 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4333 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4334 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4336 /* FIXME: Currently no support for undo level and code page options */
4337 editor->mode = (editor->mode & ~mask) | changes;
4340 case EM_SETPASSWORDCHAR:
4342 editor->cPasswordMask = wParam;
4343 ME_RewrapRepaint(editor);
4346 case EM_SETTARGETDEVICE:
4349 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4350 if (editor->nAvailWidth || editor->bWordWrap != new)
4352 editor->bWordWrap = new;
4353 editor->nAvailWidth = 0; /* wrap to client area */
4354 ME_RewrapRepaint(editor);
4357 int width = max(0, lParam);
4358 if ((editor->styleFlags & ES_MULTILINE) &&
4359 (!editor->bWordWrap || editor->nAvailWidth != width))
4361 editor->nAvailWidth = width;
4362 editor->bWordWrap = TRUE;
4363 ME_RewrapRepaint(editor);
4365 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4370 *phresult = S_FALSE;
4376 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4377 LPARAM lParam, BOOL unicode)
4379 ME_TextEditor *editor;
4381 LRESULT lresult = 0;
4383 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4384 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4386 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4389 if (msg == WM_NCCREATE)
4391 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4392 ITextHost *texthost;
4394 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4395 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4396 return texthost != NULL;
4400 return DefWindowProcW(hWnd, msg, wParam, lParam);
4412 hDC = BeginPaint(editor->hWnd, &ps);
4413 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4414 ME_SendOldNotify(editor, EN_UPDATE);
4415 /* Erase area outside of the formatting rectangle */
4416 if (ps.rcPaint.top < editor->rcFormat.top)
4419 rc.bottom = editor->rcFormat.top;
4420 FillRect(hDC, &rc, editor->hbrBackground);
4421 ps.rcPaint.top = editor->rcFormat.top;
4423 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4425 rc.top = editor->rcFormat.bottom;
4426 FillRect(hDC, &rc, editor->hbrBackground);
4427 ps.rcPaint.bottom = editor->rcFormat.bottom;
4429 if (ps.rcPaint.left < editor->rcFormat.left) {
4431 rc.right = editor->rcFormat.left;
4432 FillRect(hDC, &rc, editor->hbrBackground);
4433 ps.rcPaint.left = editor->rcFormat.left;
4435 if (ps.rcPaint.right > editor->rcFormat.right) {
4437 rc.left = editor->rcFormat.right;
4438 FillRect(hDC, &rc, editor->hbrBackground);
4439 ps.rcPaint.right = editor->rcFormat.right;
4442 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4443 EndPaint(editor->hWnd, &ps);
4448 HDC hDC = (HDC)wParam;
4451 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4452 FillRect(hDC, &rc, editor->hbrBackground);
4458 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4459 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4461 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4462 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4463 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4464 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4467 case EM_SETREADONLY:
4470 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4471 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4472 dwStyle &= ~ES_READONLY;
4474 dwStyle |= ES_READONLY;
4475 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4479 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4482 if (hresult == S_FALSE)
4483 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4485 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4486 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4491 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4493 BOOL unicode = TRUE;
4495 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4496 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4499 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4502 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4504 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4507 /******************************************************************
4508 * RichEditANSIWndProc (RICHED20.10)
4510 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4512 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4515 /******************************************************************
4516 * RichEdit10ANSIWndProc (RICHED20.9)
4518 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4520 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4522 ITextHost *texthost;
4523 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4525 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4526 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4527 return texthost != NULL;
4529 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4532 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4534 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4537 /* Fill buffer with srcChars unicode characters from the start cursor.
4539 * buffer: destination buffer
4540 * buflen: length of buffer in characters excluding the NULL terminator.
4541 * start: start of editor text to copy into buffer.
4542 * srcChars: Number of characters to use from the editor text.
4543 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4545 * returns the number of characters written excluding the NULL terminator.
4547 * The written text is always NULL terminated.
4549 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4550 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4552 ME_DisplayItem *pRun, *pNextRun;
4553 const WCHAR *pStart = buffer;
4554 const WCHAR cr_lf[] = {'\r', '\n', 0};
4558 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4559 if (editor->bEmulateVersion10) bCRLF = 0;
4563 pNextRun = ME_FindItemFwd(pRun, diRun);
4565 nLen = pRun->member.run.strText->nLen - start->nOffset;
4566 str = pRun->member.run.strText->szData + start->nOffset;
4568 /* No '\r' is appended to the last paragraph. */
4569 while (srcChars && buflen && pNextRun)
4571 int nFlags = pRun->member.run.nFlags;
4573 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4575 if (buflen == 1) break;
4576 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4577 * EM_GETTEXTEX, however, this is done for copying text which
4578 * also uses this function. */
4579 srcChars -= min(nLen, srcChars);
4583 nLen = min(nLen, srcChars);
4587 nLen = min(nLen, buflen);
4590 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4595 pNextRun = ME_FindItemFwd(pRun, diRun);
4597 nLen = pRun->member.run.strText->nLen;
4598 str = pRun->member.run.strText->szData;
4601 return buffer - pStart;
4604 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4609 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4610 wcW.lpfnWndProc = RichEditWndProcW;
4612 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4613 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4615 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4616 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4617 wcW.lpszMenuName = NULL;
4619 if (is_version_nt())
4621 wcW.lpszClassName = RICHEDIT_CLASS20W;
4622 if (!RegisterClassW(&wcW)) return FALSE;
4623 wcW.lpszClassName = MSFTEDIT_CLASS;
4624 if (!RegisterClassW(&wcW)) return FALSE;
4628 /* WNDCLASSA/W have the same layout */
4629 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4630 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4631 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4632 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4635 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4636 wcA.lpfnWndProc = RichEditWndProcA;
4638 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4639 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4641 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4642 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4643 wcA.lpszMenuName = NULL;
4644 wcA.lpszClassName = RICHEDIT_CLASS20A;
4645 if (!RegisterClassA(&wcA)) return FALSE;
4646 wcA.lpszClassName = "RichEdit50A";
4647 if (!RegisterClassA(&wcA)) return FALSE;
4652 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4653 /* FIXME: Not implemented */
4654 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4655 hWnd, msg, get_msg_name(msg), wParam, lParam);
4656 return DefWindowProcW(hWnd, msg, wParam, lParam);
4659 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4660 /* FIXME: Not implemented */
4661 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4662 hWnd, msg, get_msg_name(msg), wParam, lParam);
4663 return DefWindowProcW(hWnd, msg, wParam, lParam);
4666 /******************************************************************
4667 * REExtendedRegisterClass (RICHED20.8)
4669 * FIXME undocumented
4670 * Need to check for errors and implement controls and callbacks
4672 LRESULT WINAPI REExtendedRegisterClass(void)
4677 FIXME("semi stub\n");
4681 wcW.hInstance = NULL;
4684 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4685 wcW.lpszMenuName = NULL;
4687 if (!ME_ListBoxRegistered)
4689 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4690 wcW.lpfnWndProc = REListWndProc;
4691 wcW.lpszClassName = REListBox20W;
4692 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4695 if (!ME_ComboBoxRegistered)
4697 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4698 wcW.lpfnWndProc = REComboWndProc;
4699 wcW.lpszClassName = REComboBox20W;
4700 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4704 if (ME_ListBoxRegistered)
4706 if (ME_ComboBoxRegistered)
4712 static BOOL isurlspecial(WCHAR c)
4714 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4715 return strchrW( special_chars, c ) != NULL;
4719 * This proc takes a selection, and scans it forward in order to select the span
4720 * of a possible URL candidate. A possible URL candidate must start with isalnum
4721 * or one of the following special characters: *|/\+%#@ and must consist entirely
4722 * of the characters allowed to start the URL, plus : (colon) which may occur
4723 * at most once, and not at either end.
4725 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4726 const ME_Cursor *start,
4728 ME_Cursor *candidate_min,
4729 ME_Cursor *candidate_max)
4731 ME_Cursor cursor = *start;
4732 BOOL foundColon = FALSE;
4733 BOOL candidateStarted = FALSE;
4734 WCHAR lastAcceptedChar = '\0';
4738 WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4739 WCHAR *str = strStart + cursor.nOffset;
4740 int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4743 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4745 /* Find start of candidate */
4746 if (!candidateStarted)
4751 if (isalnumW(*str) || isurlspecial(*str))
4753 cursor.nOffset = str - strStart;
4754 *candidate_min = cursor;
4755 candidateStarted = TRUE;
4756 lastAcceptedChar = *str++;
4763 /* Find end of candidate */
4764 if (candidateStarted) {
4768 if (*str == ':' && !foundColon) {
4770 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4771 cursor.nOffset = str - strStart;
4772 if (lastAcceptedChar == ':')
4773 ME_MoveCursorChars(editor, &cursor, -1);
4774 *candidate_max = cursor;
4777 lastAcceptedChar = *str++;
4781 /* End of paragraph: skip it if before candidate span, or terminates
4782 current active span */
4783 if (candidateStarted) {
4784 if (lastAcceptedChar == ':')
4785 ME_MoveCursorChars(editor, &cursor, -1);
4786 *candidate_max = cursor;
4791 /* Reaching this point means no span was found, so get next span */
4792 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4793 if (candidateStarted) {
4794 /* There are no further runs, so take end of text as end of candidate */
4795 cursor.nOffset = str - strStart;
4796 if (lastAcceptedChar == ':')
4797 ME_MoveCursorChars(editor, &cursor, -1);
4798 *candidate_max = cursor;
4801 *candidate_max = *candidate_min = cursor;
4807 if (candidateStarted) {
4808 /* There are no further runs, so take end of text as end of candidate */
4809 if (lastAcceptedChar == ':')
4810 ME_MoveCursorChars(editor, &cursor, -1);
4811 *candidate_max = cursor;
4814 *candidate_max = *candidate_min = cursor;
4819 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4821 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4823 #define MAX_PREFIX_LEN 9
4825 const WCHAR text[MAX_PREFIX_LEN];
4828 {{'p','r','o','s','p','e','r','o',':'}, 9},
4829 {{'t','e','l','n','e','t',':'}, 7},
4830 {{'g','o','p','h','e','r',':'}, 7},
4831 {{'m','a','i','l','t','o',':'}, 7},
4832 {{'h','t','t','p','s',':'}, 6},
4833 {{'f','i','l','e',':'}, 5},
4834 {{'n','e','w','s',':'}, 5},
4835 {{'w','a','i','s',':'}, 5},
4836 {{'n','n','t','p',':'}, 5},
4837 {{'h','t','t','p',':'}, 5},
4838 {{'w','w','w','.'}, 4},
4839 {{'f','t','p',':'}, 4},
4841 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4844 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4845 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4847 if (nChars < prefixes[i].length) continue;
4848 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4852 #undef MAX_PREFIX_LEN
4856 * This proc walks through the indicated selection and evaluates whether each
4857 * section identified by ME_FindNextURLCandidate and in-between sections have
4858 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4859 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4861 * Since this function can cause runs to be split, do not depend on the value
4862 * of the start cursor at the end of the function.
4864 * nChars may be set to INT_MAX to update to the end of the text.
4866 * Returns TRUE if at least one section was modified.
4868 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4870 BOOL modified = FALSE;
4871 ME_Cursor startCur = *start;
4873 if (!editor->AutoURLDetect_bEnable) return FALSE;
4878 ME_Cursor candidateStart, candidateEnd;
4880 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4881 &candidateStart, &candidateEnd))
4883 /* Section before candidate is not an URL */
4884 int cMin = ME_GetCursorOfs(&candidateStart);
4885 int cMax = ME_GetCursorOfs(&candidateEnd);
4887 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4888 candidateStart = candidateEnd;
4889 nChars -= cMax - ME_GetCursorOfs(&startCur);
4893 /* No more candidates until end of selection */
4897 if (startCur.pRun != candidateStart.pRun ||
4898 startCur.nOffset != candidateStart.nOffset)
4900 /* CFE_LINK effect should be consistently unset */
4901 link.cbSize = sizeof(link);
4902 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4903 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4905 /* CFE_LINK must be unset from this range */
4906 memset(&link, 0, sizeof(CHARFORMAT2W));
4907 link.cbSize = sizeof(link);
4908 link.dwMask = CFM_LINK;
4910 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4911 /* Update candidateEnd since setting character formats may split
4912 * runs, which can cause a cursor to be at an invalid offset within
4914 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4916 candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4917 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4922 if (candidateStart.pRun != candidateEnd.pRun ||
4923 candidateStart.nOffset != candidateEnd.nOffset)
4925 /* CFE_LINK effect should be consistently set */
4926 link.cbSize = sizeof(link);
4927 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4928 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4930 /* CFE_LINK must be set on this range */
4931 memset(&link, 0, sizeof(CHARFORMAT2W));
4932 link.cbSize = sizeof(link);
4933 link.dwMask = CFM_LINK;
4934 link.dwEffects = CFE_LINK;
4935 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4939 startCur = candidateEnd;
4940 } while (nChars > 0);