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)
287 LRESULT total_bytes_read = 0;
288 BOOL is_read = FALSE;
289 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
291 TRACE("%08x %p\n", dwFormat, stream);
295 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
299 ME_StreamInFill(stream);
300 if (stream->editstream->dwError)
304 total_bytes_read += stream->dwSize;
307 if (!(dwFormat & SF_UNICODE))
309 char * buf = stream->buffer;
310 DWORD size = stream->dwSize;
316 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
324 nWideChars = MultiByteToWideChar(cp, 0, buf, size, wszText, STREAMIN_BUFFER_SIZE);
329 nWideChars = stream->dwSize >> 1;
330 pText = (WCHAR *)stream->buffer;
333 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
334 if (stream->dwSize == 0)
338 return total_bytes_read;
341 static void ME_ApplyBorderProperties(RTF_Info *info,
342 ME_BorderRect *borderRect,
343 RTFBorder *borderDef)
346 ME_Border *pBorders[] = {&borderRect->top,
350 for (i = 0; i < 4; i++)
352 RTFColor *colorDef = info->colorList;
353 pBorders[i]->width = borderDef[i].width;
354 colorNum = borderDef[i].color;
355 while (colorDef && colorDef->rtfCNum != colorNum)
356 colorDef = colorDef->rtfNextColor;
358 pBorders[i]->colorRef = RGB(
359 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
360 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
361 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
363 pBorders[i]->colorRef = RGB(0, 0, 0);
367 void ME_RTFCharAttrHook(RTF_Info *info)
370 fmt.cbSize = sizeof(fmt);
374 switch(info->rtfMinor)
377 /* FIXME add more flags once they're implemented */
378 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
379 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
380 fmt.yHeight = 12*20; /* 12pt */
381 fmt.wWeight = FW_NORMAL;
382 fmt.bUnderlineType = CFU_UNDERLINENONE;
385 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
386 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
387 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
390 fmt.dwMask = CFM_ITALIC;
391 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
394 fmt.dwMask = CFM_UNDERLINETYPE;
395 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
397 case rtfDotUnderline:
398 fmt.dwMask = CFM_UNDERLINETYPE;
399 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
402 fmt.dwMask = CFM_UNDERLINETYPE;
403 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
405 case rtfWordUnderline:
406 fmt.dwMask = CFM_UNDERLINETYPE;
407 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
410 fmt.dwMask = CFM_UNDERLINETYPE;
411 fmt.bUnderlineType = CFU_UNDERLINENONE;
414 fmt.dwMask = CFM_STRIKEOUT;
415 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
419 case rtfSubScrShrink:
420 case rtfSuperScrShrink:
422 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
423 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
424 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
425 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
428 fmt.dwMask = CFM_HIDDEN;
429 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
432 fmt.dwMask = CFM_BACKCOLOR;
434 if (info->rtfParam == 0)
435 fmt.dwEffects = CFE_AUTOBACKCOLOR;
436 else if (info->rtfParam != rtfNoParam)
438 RTFColor *c = RTFGetColor(info, info->rtfParam);
439 if (c && c->rtfCBlue >= 0)
440 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
442 fmt.dwEffects = CFE_AUTOBACKCOLOR;
446 fmt.dwMask = CFM_COLOR;
448 if (info->rtfParam == 0)
449 fmt.dwEffects = CFE_AUTOCOLOR;
450 else if (info->rtfParam != rtfNoParam)
452 RTFColor *c = RTFGetColor(info, info->rtfParam);
453 if (c && c->rtfCBlue >= 0)
454 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
456 fmt.dwEffects = CFE_AUTOCOLOR;
461 if (info->rtfParam != rtfNoParam)
463 RTFFont *f = RTFGetFont(info, info->rtfParam);
466 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
467 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
468 fmt.bCharSet = f->rtfFCharSet;
469 fmt.dwMask = CFM_FACE | CFM_CHARSET;
470 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
475 fmt.dwMask = CFM_SIZE;
476 if (info->rtfParam != rtfNoParam)
477 fmt.yHeight = info->rtfParam*10;
482 RTFFlushOutputBuffer(info);
483 /* FIXME too slow ? how come ? */
484 style2 = ME_ApplyStyle(info->style, &fmt);
485 ME_ReleaseStyle(info->style);
486 info->style = style2;
487 info->styleChanged = TRUE;
491 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
492 the same tags mean different things in different contexts */
493 void ME_RTFParAttrHook(RTF_Info *info)
496 fmt.cbSize = sizeof(fmt);
499 switch(info->rtfMinor)
501 case rtfParDef: /* restores default paragraph attributes */
502 if (!info->editor->bEmulateVersion10) /* v4.1 */
503 info->borderType = RTFBorderParaLeft;
504 else /* v1.0 - 3.0 */
505 info->borderType = RTFBorderParaTop;
506 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
507 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
509 /* TODO: numbering, shading */
510 fmt.wAlignment = PFA_LEFT;
512 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
513 fmt.wBorderWidth = fmt.wBorders = 0;
514 fmt.wBorderSpace = 0;
515 fmt.bLineSpacingRule = 0;
516 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
517 fmt.dyLineSpacing = 0;
518 if (!info->editor->bEmulateVersion10) /* v4.1 */
520 if (info->tableDef && info->tableDef->tableRowStart &&
521 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
524 ME_DisplayItem *para;
525 /* We are just after a table row. */
526 RTFFlushOutputBuffer(info);
527 cursor = info->editor->pCursors[0];
529 if (para == info->tableDef->tableRowStart->member.para.next_para
530 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
532 /* Since the table row end, no text has been inserted, and the \intbl
533 * control word has not be used. We can confirm that we are not in a
536 info->tableDef->tableRowStart = NULL;
537 info->canInheritInTbl = FALSE;
540 } else { /* v1.0 - v3.0 */
541 fmt.dwMask |= PFM_TABLE;
542 fmt.wEffects &= ~PFE_TABLE;
546 if (!info->editor->bEmulateVersion10) /* v4.1 */
548 while (info->rtfParam > info->nestingLevel) {
549 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
550 ZeroMemory(tableDef, sizeof(RTFTable));
551 tableDef->parent = info->tableDef;
552 info->tableDef = tableDef;
554 RTFFlushOutputBuffer(info);
555 if (tableDef->tableRowStart &&
556 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
558 ME_DisplayItem *para = tableDef->tableRowStart;
559 para = para->member.para.next_para;
560 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
561 tableDef->tableRowStart = para;
565 cursor = info->editor->pCursors[0];
566 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
567 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
568 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
571 info->nestingLevel++;
573 info->canInheritInTbl = FALSE;
578 if (!info->editor->bEmulateVersion10) /* v4.1 */
580 if (info->nestingLevel < 1)
585 info->tableDef = ALLOC_OBJ(RTFTable);
586 ZeroMemory(info->tableDef, sizeof(RTFTable));
588 tableDef = info->tableDef;
589 RTFFlushOutputBuffer(info);
590 if (tableDef->tableRowStart &&
591 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
593 ME_DisplayItem *para = tableDef->tableRowStart;
594 para = para->member.para.next_para;
595 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
596 tableDef->tableRowStart = para;
600 cursor = info->editor->pCursors[0];
601 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
602 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
603 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
605 info->nestingLevel = 1;
606 info->canInheritInTbl = TRUE;
609 } else { /* v1.0 - v3.0 */
610 fmt.dwMask |= PFM_TABLE;
611 fmt.wEffects |= PFE_TABLE;
616 ME_GetSelectionParaFormat(info->editor, &fmt);
617 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
618 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
619 fmt.dxOffset = -info->rtfParam;
622 ME_GetSelectionParaFormat(info->editor, &fmt);
623 fmt.dwMask = PFM_STARTINDENT;
624 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
627 fmt.dwMask = PFM_RIGHTINDENT;
628 fmt.dxRightIndent = info->rtfParam;
632 fmt.dwMask = PFM_ALIGNMENT;
633 fmt.wAlignment = PFA_LEFT;
636 fmt.dwMask = PFM_ALIGNMENT;
637 fmt.wAlignment = PFA_RIGHT;
640 fmt.dwMask = PFM_ALIGNMENT;
641 fmt.wAlignment = PFA_CENTER;
644 ME_GetSelectionParaFormat(info->editor, &fmt);
645 if (!(fmt.dwMask & PFM_TABSTOPS))
649 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
650 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
651 fmt.dwMask = PFM_TABSTOPS;
654 fmt.dwMask = PFM_KEEP;
655 fmt.wEffects = PFE_KEEP;
657 case rtfNoWidowControl:
658 fmt.dwMask = PFM_NOWIDOWCONTROL;
659 fmt.wEffects = PFE_NOWIDOWCONTROL;
662 fmt.dwMask = PFM_KEEPNEXT;
663 fmt.wEffects = PFE_KEEPNEXT;
666 fmt.dwMask = PFM_SPACEAFTER;
667 fmt.dySpaceAfter = info->rtfParam;
670 fmt.dwMask = PFM_SPACEBEFORE;
671 fmt.dySpaceBefore = info->rtfParam;
673 case rtfSpaceBetween:
674 fmt.dwMask = PFM_LINESPACING;
675 if ((int)info->rtfParam > 0)
677 fmt.dyLineSpacing = info->rtfParam;
678 fmt.bLineSpacingRule = 3;
682 fmt.dyLineSpacing = info->rtfParam;
683 fmt.bLineSpacingRule = 4;
686 case rtfSpaceMultiply:
687 fmt.dwMask = PFM_LINESPACING;
688 fmt.dyLineSpacing = info->rtfParam * 20;
689 fmt.bLineSpacingRule = 5;
692 fmt.dwMask = PFM_NUMBERING;
693 fmt.wNumbering = PFN_BULLET;
696 fmt.dwMask = PFM_NUMBERING;
697 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
699 case rtfParNumDecimal:
700 fmt.dwMask = PFM_NUMBERING;
701 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
703 case rtfParNumIndent:
704 fmt.dwMask = PFM_NUMBERINGTAB;
705 fmt.wNumberingTab = info->rtfParam;
707 case rtfParNumStartAt:
708 fmt.dwMask = PFM_NUMBERINGSTART;
709 fmt.wNumberingStart = info->rtfParam;
712 info->borderType = RTFBorderParaLeft;
713 ME_GetSelectionParaFormat(info->editor, &fmt);
714 if (!(fmt.dwMask & PFM_BORDER))
716 fmt.wBorderSpace = 0;
717 fmt.wBorderWidth = 1;
721 fmt.dwMask = PFM_BORDER;
724 info->borderType = RTFBorderParaRight;
725 ME_GetSelectionParaFormat(info->editor, &fmt);
726 if (!(fmt.dwMask & PFM_BORDER))
728 fmt.wBorderSpace = 0;
729 fmt.wBorderWidth = 1;
733 fmt.dwMask = PFM_BORDER;
736 info->borderType = RTFBorderParaTop;
737 ME_GetSelectionParaFormat(info->editor, &fmt);
738 if (!(fmt.dwMask & PFM_BORDER))
740 fmt.wBorderSpace = 0;
741 fmt.wBorderWidth = 1;
745 fmt.dwMask = PFM_BORDER;
747 case rtfBorderBottom:
748 info->borderType = RTFBorderParaBottom;
749 ME_GetSelectionParaFormat(info->editor, &fmt);
750 if (!(fmt.dwMask & PFM_BORDER))
752 fmt.wBorderSpace = 0;
753 fmt.wBorderWidth = 1;
757 fmt.dwMask = PFM_BORDER;
759 case rtfBorderSingle:
760 ME_GetSelectionParaFormat(info->editor, &fmt);
761 /* we assume that borders have been created before (RTF spec) */
762 fmt.wBorders &= ~0x700;
763 fmt.wBorders |= 1 << 8;
764 fmt.dwMask = PFM_BORDER;
767 ME_GetSelectionParaFormat(info->editor, &fmt);
768 /* we assume that borders have been created before (RTF spec) */
769 fmt.wBorders &= ~0x700;
770 fmt.wBorders |= 2 << 8;
771 fmt.dwMask = PFM_BORDER;
773 case rtfBorderShadow:
774 ME_GetSelectionParaFormat(info->editor, &fmt);
775 /* we assume that borders have been created before (RTF spec) */
776 fmt.wBorders &= ~0x700;
777 fmt.wBorders |= 10 << 8;
778 fmt.dwMask = PFM_BORDER;
780 case rtfBorderDouble:
781 ME_GetSelectionParaFormat(info->editor, &fmt);
782 /* we assume that borders have been created before (RTF spec) */
783 fmt.wBorders &= ~0x700;
784 fmt.wBorders |= 7 << 8;
785 fmt.dwMask = PFM_BORDER;
788 ME_GetSelectionParaFormat(info->editor, &fmt);
789 /* we assume that borders have been created before (RTF spec) */
790 fmt.wBorders &= ~0x700;
791 fmt.wBorders |= 11 << 8;
792 fmt.dwMask = PFM_BORDER;
796 int borderSide = info->borderType & RTFBorderSideMask;
797 RTFTable *tableDef = info->tableDef;
798 ME_GetSelectionParaFormat(info->editor, &fmt);
799 /* we assume that borders have been created before (RTF spec) */
800 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
801 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
804 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
806 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
807 border->width = info->rtfParam;
810 fmt.dwMask = PFM_BORDER;
814 ME_GetSelectionParaFormat(info->editor, &fmt);
815 /* we assume that borders have been created before (RTF spec) */
816 fmt.wBorderSpace = info->rtfParam;
817 fmt.dwMask = PFM_BORDER;
821 RTFTable *tableDef = info->tableDef;
822 int borderSide = info->borderType & RTFBorderSideMask;
823 int borderType = info->borderType & RTFBorderTypeMask;
826 case RTFBorderTypePara:
827 if (!info->editor->bEmulateVersion10) /* v4.1 */
829 /* v1.0 - 3.0 treat paragraph and row borders the same. */
830 case RTFBorderTypeRow:
832 tableDef->border[borderSide].color = info->rtfParam;
835 case RTFBorderTypeCell:
836 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
837 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
845 RTFFlushOutputBuffer(info);
846 /* FIXME too slow ? how come ?*/
847 ME_SetSelectionParaFormat(info->editor, &fmt);
851 void ME_RTFTblAttrHook(RTF_Info *info)
853 switch (info->rtfMinor)
857 if (!info->editor->bEmulateVersion10) /* v4.1 */
858 info->borderType = 0; /* Not sure */
859 else /* v1.0 - 3.0 */
860 info->borderType = RTFBorderRowTop;
861 if (!info->tableDef) {
862 info->tableDef = ME_MakeTableDef(info->editor);
864 ME_InitTableDef(info->editor, info->tableDef);
873 info->tableDef = ME_MakeTableDef(info->editor);
875 cellNum = info->tableDef->numCellsDefined;
876 if (cellNum >= MAX_TABLE_CELLS)
878 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
879 if (cellNum < MAX_TAB_STOPS) {
880 /* Tab stops were used to store cell positions before v4.1 but v4.1
881 * still seems to set the tabstops without using them. */
882 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
883 PARAFORMAT2 *pFmt = para->member.para.pFmt;
884 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
885 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
887 info->tableDef->numCellsDefined++;
891 info->borderType = RTFBorderRowTop;
894 info->borderType = RTFBorderRowLeft;
896 case rtfRowBordBottom:
897 info->borderType = RTFBorderRowBottom;
899 case rtfRowBordRight:
900 info->borderType = RTFBorderRowRight;
903 info->borderType = RTFBorderCellTop;
905 case rtfCellBordLeft:
906 info->borderType = RTFBorderCellLeft;
908 case rtfCellBordBottom:
909 info->borderType = RTFBorderCellBottom;
911 case rtfCellBordRight:
912 info->borderType = RTFBorderCellRight;
916 info->tableDef->gapH = info->rtfParam;
920 info->tableDef->leftEdge = info->rtfParam;
925 void ME_RTFSpecialCharHook(RTF_Info *info)
927 RTFTable *tableDef = info->tableDef;
928 switch (info->rtfMinor)
931 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
933 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
937 RTFFlushOutputBuffer(info);
938 if (!info->editor->bEmulateVersion10) { /* v4.1 */
939 if (tableDef->tableRowStart)
941 if (!info->nestingLevel &&
942 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
944 ME_DisplayItem *para = tableDef->tableRowStart;
945 para = para->member.para.next_para;
946 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
947 tableDef->tableRowStart = para;
948 info->nestingLevel = 1;
950 ME_InsertTableCellFromCursor(info->editor);
952 } else { /* v1.0 - v3.0 */
953 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
954 PARAFORMAT2 *pFmt = para->member.para.pFmt;
955 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
956 tableDef->numCellsInserted < tableDef->numCellsDefined)
959 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
960 tableDef->numCellsInserted++;
965 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
967 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
970 ME_DisplayItem *para, *cell, *run;
975 RTFFlushOutputBuffer(info);
976 if (!info->editor->bEmulateVersion10) { /* v4.1 */
977 if (!tableDef->tableRowStart)
979 if (!info->nestingLevel &&
980 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
982 para = tableDef->tableRowStart;
983 para = para->member.para.next_para;
984 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
985 tableDef->tableRowStart = para;
986 info->nestingLevel++;
988 para = tableDef->tableRowStart;
989 cell = ME_FindItemFwd(para, diCell);
990 assert(cell && !cell->member.cell.prev_cell);
991 if (tableDef->numCellsDefined < 1)
993 /* 2000 twips appears to be the cell size that native richedit uses
994 * when no cell sizes are specified. */
995 const int defaultCellSize = 2000;
996 int nRightBoundary = defaultCellSize;
997 cell->member.cell.nRightBoundary = nRightBoundary;
998 while (cell->member.cell.next_cell) {
999 cell = cell->member.cell.next_cell;
1000 nRightBoundary += defaultCellSize;
1001 cell->member.cell.nRightBoundary = nRightBoundary;
1003 para = ME_InsertTableCellFromCursor(info->editor);
1004 cell = para->member.para.pCell;
1005 cell->member.cell.nRightBoundary = nRightBoundary;
1007 for (i = 0; i < tableDef->numCellsDefined; i++)
1009 RTFCell *cellDef = &tableDef->cells[i];
1010 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1011 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1013 cell = cell->member.cell.next_cell;
1016 para = ME_InsertTableCellFromCursor(info->editor);
1017 cell = para->member.para.pCell;
1020 /* Cell for table row delimiter is empty */
1021 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1024 run = ME_FindItemFwd(cell, diRun);
1025 if (info->editor->pCursors[0].pRun != run ||
1026 info->editor->pCursors[0].nOffset)
1029 /* Delete inserted cells that aren't defined. */
1030 info->editor->pCursors[1].pRun = run;
1031 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1032 info->editor->pCursors[1].nOffset = 0;
1033 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1034 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1035 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1039 para = ME_InsertTableRowEndFromCursor(info->editor);
1040 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1041 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1042 ME_ApplyBorderProperties(info, ¶->member.para.border,
1044 info->nestingLevel--;
1045 if (!info->nestingLevel)
1047 if (info->canInheritInTbl) {
1048 tableDef->tableRowStart = para;
1050 while (info->tableDef) {
1051 tableDef = info->tableDef;
1052 info->tableDef = tableDef->parent;
1053 heap_free(tableDef);
1057 info->tableDef = tableDef->parent;
1058 heap_free(tableDef);
1060 } else { /* v1.0 - v3.0 */
1062 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1063 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1064 pFmt->dxOffset = info->tableDef->gapH;
1065 pFmt->dxStartIndent = info->tableDef->leftEdge;
1067 ME_ApplyBorderProperties(info, ¶->member.para.border,
1069 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1072 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1073 tableDef->numCellsInserted++;
1075 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1076 if (!tableDef->numCellsDefined)
1077 pFmt->wEffects &= ~PFE_TABLE;
1078 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1079 tableDef->numCellsInserted = 0;
1085 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1086 ME_DisplayItem *para;
1088 RTFFlushOutputBuffer(info);
1089 para = info->editor->pCursors[0].pPara;
1090 pFmt = para->member.para.pFmt;
1091 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1093 /* rtfPar is treated like a space within a table. */
1094 info->rtfClass = rtfText;
1095 info->rtfMajor = ' ';
1097 else if (info->rtfMinor == rtfPar && tableDef)
1098 tableDef->numCellsInserted = 0;
1104 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1107 LPOLEOBJECT lpObject = NULL;
1108 LPSTORAGE lpStorage = NULL;
1109 LPOLECLIENTSITE lpClientSite = NULL;
1110 LPDATAOBJECT lpDataObject = NULL;
1111 LPOLECACHE lpOleCache = NULL;
1120 stgm.tymed = TYMED_ENHMF;
1121 stgm.u.hEnhMetaFile = hemf;
1122 fm.cfFormat = CF_ENHMETAFILE;
1126 stgm.tymed = TYMED_GDI;
1127 stgm.u.hBitmap = hbmp;
1128 fm.cfFormat = CF_BITMAP;
1130 stgm.pUnkForRelease = NULL;
1133 fm.dwAspect = DVASPECT_CONTENT;
1135 fm.tymed = stgm.tymed;
1137 if (!info->lpRichEditOle)
1139 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1142 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1144 /* FIXME: enable it when rich-edit properly implements this method */
1145 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1146 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1148 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1149 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1150 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1151 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1152 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1156 reobject.cbStruct = sizeof(reobject);
1157 reobject.cp = REO_CP_SELECTION;
1158 reobject.clsid = clsid;
1159 reobject.poleobj = lpObject;
1160 reobject.pstg = lpStorage;
1161 reobject.polesite = lpClientSite;
1162 /* convert from twips to .01 mm */
1163 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1164 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1165 reobject.dvaspect = DVASPECT_CONTENT;
1166 reobject.dwFlags = 0; /* FIXME */
1167 reobject.dwUser = 0;
1169 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1173 if (lpObject) IOleObject_Release(lpObject);
1174 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1175 if (lpStorage) IStorage_Release(lpStorage);
1176 if (lpDataObject) IDataObject_Release(lpDataObject);
1177 if (lpOleCache) IOleCache_Release(lpOleCache);
1182 static void ME_RTFReadPictGroup(RTF_Info *info)
1185 BYTE* buffer = NULL;
1186 unsigned bufsz, bufidx;
1192 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1195 if (info->rtfClass == rtfEOF)
1198 /* fetch picture type */
1199 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1201 mfp.mm = info->rtfParam;
1204 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1206 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1209 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1211 gfx = gfx_enhmetafile;
1215 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1219 /* fetch picture attributes */
1223 if (info->rtfClass == rtfEOF)
1225 if (info->rtfClass == rtfText)
1227 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1229 ERR("Expected picture attribute (%d %d)\n",
1230 info->rtfClass, info->rtfMajor);
1233 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1235 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1237 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1239 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1241 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1242 sz.cx = info->rtfParam;
1243 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1244 sz.cy = info->rtfParam;
1246 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1248 /* fetch picture data */
1251 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1252 val = info->rtfMajor;
1253 for (flip = TRUE;; flip = !flip)
1256 if (info->rtfClass == rtfEOF)
1258 HeapFree(GetProcessHeap(), 0, buffer);
1259 return; /* Warn ?? */
1261 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1263 if (info->rtfClass != rtfText) goto skip_group;
1266 if (bufidx >= bufsz &&
1267 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1269 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1272 val = info->rtfMajor;
1274 if (flip) FIXME("wrong hex string\n");
1278 case gfx_enhmetafile:
1279 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1280 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1283 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1284 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1288 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1290 unsigned nc = bi->bmiHeader.biClrUsed;
1292 /* not quite right, especially for bitfields type of compression */
1293 if (!nc && bi->bmiHeader.biBitCount <= 8)
1294 nc = 1 << bi->bmiHeader.biBitCount;
1295 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1296 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1297 bi, DIB_RGB_COLORS)))
1298 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1305 HeapFree(GetProcessHeap(), 0, buffer);
1306 RTFRouteToken (info); /* feed "}" back to router */
1309 HeapFree(GetProcessHeap(), 0, buffer);
1311 RTFRouteToken(info); /* feed "}" back to router */
1314 /* for now, lookup the \result part and use it, whatever the object */
1315 static void ME_RTFReadObjectGroup(RTF_Info *info)
1320 if (info->rtfClass == rtfEOF)
1322 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1324 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1327 if (info->rtfClass == rtfEOF)
1329 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1333 while (RTFGetToken (info) != rtfEOF)
1335 if (info->rtfClass == rtfGroup)
1337 if (info->rtfMajor == rtfBeginGroup) level++;
1338 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1340 RTFRouteToken(info);
1343 else RTFSkipGroup(info);
1346 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1348 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1352 RTFRouteToken(info); /* feed "}" back to router */
1355 static void ME_RTFReadHook(RTF_Info *info)
1357 switch(info->rtfClass)
1360 switch(info->rtfMajor)
1363 if (info->stackTop < maxStack) {
1364 info->stack[info->stackTop].style = info->style;
1365 ME_AddRefStyle(info->style);
1366 info->stack[info->stackTop].codePage = info->codePage;
1367 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1370 info->styleChanged = FALSE;
1374 RTFFlushOutputBuffer(info);
1376 if (info->stackTop <= 0)
1377 info->rtfClass = rtfEOF;
1378 if (info->stackTop < 0)
1381 ME_ReleaseStyle(info->style);
1382 info->style = info->stack[info->stackTop].style;
1383 info->codePage = info->stack[info->stackTop].codePage;
1384 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1393 ME_StreamInFill(ME_InStream *stream)
1395 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1396 (BYTE *)stream->buffer,
1397 sizeof(stream->buffer),
1398 (LONG *)&stream->dwSize);
1402 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1406 int from, to, nUndoMode;
1407 int nEventMask = editor->nEventMask;
1408 ME_InStream inStream;
1409 BOOL invalidRTF = FALSE;
1410 ME_Cursor *selStart, *selEnd;
1411 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1413 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1414 editor->nEventMask = 0;
1416 ME_GetSelectionOfs(editor, &from, &to);
1417 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1419 ME_GetSelection(editor, &selStart, &selEnd);
1420 style = ME_GetSelectionInsertStyle(editor);
1422 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1424 /* Don't insert text at the end of the table row */
1425 if (!editor->bEmulateVersion10) { /* v4.1 */
1426 ME_DisplayItem *para = editor->pCursors->pPara;
1427 if (para->member.para.nFlags & MEPF_ROWEND)
1429 para = para->member.para.next_para;
1430 editor->pCursors[0].pPara = para;
1431 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1432 editor->pCursors[0].nOffset = 0;
1434 if (para->member.para.nFlags & MEPF_ROWSTART)
1436 para = para->member.para.next_para;
1437 editor->pCursors[0].pPara = para;
1438 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1439 editor->pCursors[0].nOffset = 0;
1441 editor->pCursors[1] = editor->pCursors[0];
1442 } else { /* v1.0 - 3.0 */
1443 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1444 ME_IsInTable(editor->pCursors[0].pRun))
1448 style = editor->pBuffer->pDefaultStyle;
1449 ME_AddRefStyle(style);
1450 ME_SetSelection(editor, 0, 0);
1451 ME_InternalDeleteText(editor, &editor->pCursors[1],
1452 ME_GetTextLength(editor), FALSE);
1454 ME_ClearTempStyle(editor);
1455 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1459 /* Back up undo mode to a local variable */
1460 nUndoMode = editor->nUndoMode;
1462 /* Only create an undo if SFF_SELECTION is set */
1463 if (!(format & SFF_SELECTION))
1464 editor->nUndoMode = umIgnore;
1466 inStream.editstream = stream;
1467 inStream.editstream->dwError = 0;
1468 inStream.dwSize = 0;
1469 inStream.dwUsed = 0;
1471 if (format & SF_RTF)
1473 /* Check if it's really RTF, and if it is not, use plain text */
1474 ME_StreamInFill(&inStream);
1475 if (!inStream.editstream->dwError)
1477 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1478 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1481 inStream.editstream->dwError = -16;
1486 if (!invalidRTF && !inStream.editstream->dwError)
1488 if (format & SF_RTF) {
1489 from = ME_GetCursorOfs(&editor->pCursors[0]);
1491 /* setup the RTF parser */
1492 memset(&parser, 0, sizeof parser);
1493 RTFSetEditStream(&parser, &inStream);
1494 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1495 parser.editor = editor;
1496 parser.style = style;
1497 WriterInit(&parser);
1499 RTFSetReadHook(&parser, ME_RTFReadHook);
1500 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1501 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1502 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1504 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1505 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1509 /* do the parsing */
1511 RTFFlushOutputBuffer(&parser);
1512 if (!editor->bEmulateVersion10) { /* v4.1 */
1513 if (parser.tableDef && parser.tableDef->tableRowStart &&
1514 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1516 /* Delete any incomplete table row at the end of the rich text. */
1518 ME_DisplayItem *para;
1520 parser.rtfMinor = rtfRow;
1521 /* Complete the table row before deleting it.
1522 * By doing it this way we will have the current paragraph format set
1523 * properly to reflect that is not in the complete table, and undo items
1524 * will be added for this change to the current paragraph format. */
1525 if (parser.nestingLevel > 0)
1527 while (parser.nestingLevel > 1)
1528 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1529 para = parser.tableDef->tableRowStart;
1530 ME_RTFSpecialCharHook(&parser);
1532 para = parser.tableDef->tableRowStart;
1533 ME_RTFSpecialCharHook(&parser);
1534 assert(para->member.para.nFlags & MEPF_ROWEND);
1535 para = para->member.para.next_para;
1538 editor->pCursors[1].pPara = para;
1539 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1540 editor->pCursors[1].nOffset = 0;
1541 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1542 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1543 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1544 if (parser.tableDef)
1545 parser.tableDef->tableRowStart = NULL;
1548 ME_CheckTablesForCorruption(editor);
1549 RTFDestroy(&parser);
1550 if (parser.lpRichEditOle)
1551 IRichEditOle_Release(parser.lpRichEditOle);
1553 if (parser.stackTop > 0)
1555 while (--parser.stackTop >= 0)
1557 ME_ReleaseStyle(parser.style);
1558 parser.style = parser.stack[parser.stackTop].style;
1560 if (!inStream.editstream->dwError)
1561 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1564 /* Remove last line break, as mandated by tests. This is not affected by
1565 CR/LF counters, since RTF streaming presents only \para tokens, which
1566 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1570 ME_GetSelection(editor, &selStart, &selEnd);
1571 newto = ME_GetCursorOfs(selEnd);
1572 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1573 WCHAR lastchar[3] = {'\0', '\0'};
1574 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1575 ME_Cursor linebreakCursor = *selEnd;
1577 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1578 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1579 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1580 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1584 to = ME_GetCursorOfs(&editor->pCursors[0]);
1585 num_read = to - from;
1587 style = parser.style;
1589 else if (format & SF_TEXT)
1590 num_read = ME_StreamInText(editor, format, &inStream, style);
1592 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1593 /* put the cursor at the top */
1594 if (!(format & SFF_SELECTION))
1595 ME_SetSelection(editor, 0, 0);
1598 /* Restore saved undo mode */
1599 editor->nUndoMode = nUndoMode;
1601 /* even if we didn't add an undo, we need to commit anything on the stack */
1602 ME_CommitUndo(editor);
1604 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1605 if (!(format & SFF_SELECTION))
1606 ME_EmptyUndoStack(editor);
1608 ME_ReleaseStyle(style);
1609 editor->nEventMask = nEventMask;
1610 ME_UpdateRepaint(editor, FALSE);
1611 if (!(format & SFF_SELECTION)) {
1612 ME_ClearTempStyle(editor);
1614 ITextHost_TxShowCaret(editor->texthost, FALSE);
1615 ME_MoveCaret(editor);
1616 ITextHost_TxShowCaret(editor->texthost, TRUE);
1617 ME_SendSelChange(editor);
1618 ME_SendRequestResize(editor, FALSE);
1624 typedef struct tagME_RTFStringStreamStruct
1629 } ME_RTFStringStreamStruct;
1631 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1633 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1636 count = min(cb, pStruct->length - pStruct->pos);
1637 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1638 pStruct->pos += count;
1644 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1647 ME_RTFStringStreamStruct data;
1649 data.string = string;
1650 data.length = strlen(string);
1652 es.dwCookie = (DWORD_PTR)&data;
1653 es.pfnCallback = ME_ReadFromRTFString;
1654 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1659 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1661 const int nLen = lstrlenW(text);
1662 const int nTextLen = ME_GetTextLength(editor);
1665 WCHAR wLastChar = ' ';
1667 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1668 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1670 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1671 FIXME("Flags 0x%08x not implemented\n",
1672 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1675 if (chrg->cpMax == -1)
1678 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1680 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1681 if (editor->bEmulateVersion10 && nMax == nTextLen)
1686 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1687 if (editor->bEmulateVersion10 && nMax < nMin)
1691 chrgText->cpMin = -1;
1692 chrgText->cpMax = -1;
1697 /* when searching up, if cpMin < cpMax, then instead of searching
1698 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1699 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1700 * case, it is always bigger than cpMin.
1702 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1706 nMax = nMin > nTextLen ? nTextLen : nMin;
1707 if (nMin < nSwap || chrg->cpMax == -1)
1713 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1716 chrgText->cpMin = chrgText->cpMax = -1;
1720 if (flags & FR_DOWN) /* Forward search */
1722 /* If possible, find the character before where the search starts */
1723 if ((flags & FR_WHOLEWORD) && nMin)
1725 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1726 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1727 ME_MoveCursorChars(editor, &cursor, 1);
1729 ME_CursorFromCharOfs(editor, nMin, &cursor);
1732 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1734 ME_DisplayItem *pCurItem = cursor.pRun;
1735 int nCurStart = cursor.nOffset;
1738 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1740 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1744 if (nMatched == nLen)
1746 ME_DisplayItem *pNextItem = pCurItem;
1747 int nNextStart = nCurStart;
1750 /* Check to see if next character is a whitespace */
1751 if (flags & FR_WHOLEWORD)
1753 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1755 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1756 nNextStart = -nMatched;
1760 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1764 if (isalnumW(wNextChar))
1768 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1771 chrgText->cpMin = cursor.nOffset;
1772 chrgText->cpMax = cursor.nOffset + nLen;
1774 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1775 return cursor.nOffset;
1777 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1779 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1780 nCurStart = -nMatched;
1784 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1789 if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1791 ME_NextRun(&cursor.pPara, &cursor.pRun);
1796 else /* Backward search */
1798 /* If possible, find the character after where the search ends */
1799 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1801 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1802 wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1803 ME_MoveCursorChars(editor, &cursor, -1);
1805 ME_CursorFromCharOfs(editor, nMax, &cursor);
1808 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1810 ME_DisplayItem *pCurItem = cursor.pRun;
1811 ME_DisplayItem *pCurPara = cursor.pPara;
1812 int nCurEnd = cursor.nOffset;
1817 ME_PrevRun(&pCurPara, &pCurItem);
1818 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1821 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1823 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1827 if (nMatched == nLen)
1829 ME_DisplayItem *pPrevItem = pCurItem;
1830 int nPrevEnd = nCurEnd;
1834 /* Check to see if previous character is a whitespace */
1835 if (flags & FR_WHOLEWORD)
1837 if (nPrevEnd - nMatched == 0)
1839 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1841 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1845 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1849 if (isalnumW(wPrevChar))
1853 nStart = pCurPara->member.para.nCharOfs
1854 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1857 chrgText->cpMin = nStart;
1858 chrgText->cpMax = nStart + nLen;
1860 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1863 if (nCurEnd - nMatched == 0)
1865 ME_PrevRun(&pCurPara, &pCurItem);
1866 /* Don't care about pCurItem becoming NULL here; it's already taken
1867 * care of in the exterior loop condition */
1868 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1872 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1877 if (cursor.nOffset < 0)
1879 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1880 cursor.nOffset = cursor.pRun->member.run.strText->nLen;
1884 TRACE("not found\n");
1886 chrgText->cpMin = chrgText->cpMax = -1;
1890 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1895 if (!ex->cb || !pText) return 0;
1897 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1898 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1900 if (ex->flags & GT_SELECTION)
1903 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1904 start = editor->pCursors[nStartCur];
1909 ME_SetCursorToStart(editor, &start);
1912 if (ex->codepage == 1200)
1914 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1915 &start, nChars, ex->flags & GT_USECRLF);
1919 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1920 we can just take a bigger buffer? :)
1921 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1922 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1924 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1929 buflen = min(crlfmul * nChars, ex->cb - 1);
1930 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1932 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1933 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1934 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1935 if (rc) rc--; /* do not count 0 terminator */
1942 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1943 const ME_Cursor *start, int nLen, BOOL unicode)
1945 if (!strText) return 0;
1947 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1950 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1952 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1953 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1954 nLen+1, NULL, NULL);
1960 typedef struct tagME_GlobalDestStruct
1964 } ME_GlobalDestStruct;
1966 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1968 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1973 pDest = (WORD *)lpBuff;
1974 pSrc = GlobalLock(pData->hData);
1975 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1976 pDest[i] = pSrc[pData->nLength+i];
1978 pData->nLength += i;
1980 GlobalUnlock(pData->hData);
1984 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1986 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1991 pSrc = GlobalLock(pData->hData);
1992 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1993 pDest[i] = pSrc[pData->nLength+i];
1995 pData->nLength += i;
1997 GlobalUnlock(pData->hData);
2001 static BOOL ME_Paste(ME_TextEditor *editor)
2005 ME_GlobalDestStruct gds;
2006 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2009 if (IsClipboardFormatAvailable(nRTFFormat))
2010 cf = nRTFFormat, dwFormat = SF_RTF;
2011 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2012 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2016 if (!OpenClipboard(editor->hWnd))
2018 gds.hData = GetClipboardData(cf);
2020 es.dwCookie = (DWORD_PTR)&gds;
2021 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2022 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2028 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2030 LPDATAOBJECT dataObj = NULL;
2033 if (editor->cPasswordMask)
2034 return FALSE; /* Copying or Cutting masked text isn't allowed */
2036 if(editor->lpOleCallback)
2039 range.cpMin = ME_GetCursorOfs(start);
2040 range.cpMax = range.cpMin + nChars;
2041 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2043 if(FAILED(hr) || !dataObj)
2044 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2046 hr = OleSetClipboard(dataObj);
2047 IDataObject_Release(dataObj);
2049 return SUCCEEDED(hr) != 0;
2052 /* helper to send a msg filter notification */
2054 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2058 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2059 msgf.nmhdr.hwndFrom = editor->hWnd;
2060 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2061 msgf.nmhdr.code = EN_MSGFILTER;
2063 msgf.wParam = *wParam;
2064 msgf.lParam = *lParam;
2065 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2067 *wParam = msgf.wParam;
2068 *lParam = msgf.lParam;
2069 msgf.wParam = *wParam;
2074 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2076 ME_DisplayItem *startPara, *endPara;
2077 ME_DisplayItem *prev_para;
2078 ME_Cursor *from, *to;
2082 if (!editor->AutoURLDetect_bEnable) return;
2084 ME_GetSelection(editor, &from, &to);
2086 /* Find paragraph previous to the one that contains start cursor */
2087 startPara = from->pPara;
2088 prev_para = startPara->member.para.prev_para;
2089 if (prev_para->type == diParagraph) startPara = prev_para;
2091 /* Find paragraph that contains end cursor */
2092 endPara = to->pPara->member.para.next_para;
2094 start.pPara = startPara;
2095 start.pRun = ME_FindItemFwd(startPara, diRun);
2097 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2099 ME_UpdateLinkAttribute(editor, &start, nChars);
2103 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2105 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2106 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2108 if (editor->bMouseCaptured)
2110 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2111 editor->nSelectionType = stPosition;
2119 editor->nUDArrowX = -1;
2125 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2126 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2130 editor->nUDArrowX = -1;
2131 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2132 if (editor->styleFlags & ES_READONLY)
2134 if (ME_IsSelection(editor))
2136 ME_DeleteSelection(editor);
2137 ME_CommitUndo(editor);
2139 else if (nKey == VK_DELETE)
2141 /* Delete stops group typing.
2142 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2143 ME_DeleteTextAtCursor(editor, 1, 1);
2144 ME_CommitUndo(editor);
2146 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2148 BOOL bDeletionSucceeded;
2149 /* Backspace can be grouped for a single undo */
2150 ME_ContinueCoalescingTransaction(editor);
2151 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2152 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2153 /* Deletion was prevented so the cursor is moved back to where it was.
2154 * (e.g. this happens when trying to delete cell boundaries)
2156 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2158 ME_CommitCoalescingUndo(editor);
2162 ME_MoveCursorFromTableRowStartParagraph(editor);
2163 ME_UpdateSelectionLinkAttribute(editor);
2164 ME_UpdateRepaint(editor, FALSE);
2165 ME_SendRequestResize(editor, FALSE);
2168 if (editor->bDialogMode)
2173 if (!(editor->styleFlags & ES_WANTRETURN))
2175 if (editor->hwndParent)
2178 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2179 if (HIWORD(dw) == DC_HASDEFID)
2181 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2184 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2185 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2193 if (editor->styleFlags & ES_MULTILINE)
2195 ME_Cursor cursor = editor->pCursors[0];
2196 ME_DisplayItem *para = cursor.pPara;
2198 const WCHAR endl = '\r';
2199 const WCHAR endlv10[] = {'\r','\n'};
2202 if (editor->styleFlags & ES_READONLY) {
2203 MessageBeep(MB_ICONERROR);
2207 ME_GetSelectionOfs(editor, &from, &to);
2208 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2210 if (!editor->bEmulateVersion10) { /* v4.1 */
2211 if (para->member.para.nFlags & MEPF_ROWEND) {
2212 /* Add a new table row after this row. */
2213 para = ME_AppendTableRow(editor, para);
2214 para = para->member.para.next_para;
2215 editor->pCursors[0].pPara = para;
2216 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2217 editor->pCursors[0].nOffset = 0;
2218 editor->pCursors[1] = editor->pCursors[0];
2219 ME_CommitUndo(editor);
2220 ME_CheckTablesForCorruption(editor);
2221 ME_UpdateRepaint(editor, FALSE);
2224 else if (para == editor->pCursors[1].pPara &&
2225 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2226 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2227 !para->member.para.prev_para->member.para.nCharOfs)
2229 /* Insert a newline before the table. */
2230 para = para->member.para.prev_para;
2231 para->member.para.nFlags &= ~MEPF_ROWSTART;
2232 editor->pCursors[0].pPara = para;
2233 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2234 editor->pCursors[1] = editor->pCursors[0];
2235 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2236 editor->pCursors[0].pRun->member.run.style);
2237 para = editor->pBuffer->pFirst->member.para.next_para;
2238 ME_SetDefaultParaFormat(para->member.para.pFmt);
2239 para->member.para.nFlags = MEPF_REWRAP;
2240 editor->pCursors[0].pPara = para;
2241 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2242 editor->pCursors[1] = editor->pCursors[0];
2243 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2244 ME_CommitCoalescingUndo(editor);
2245 ME_CheckTablesForCorruption(editor);
2246 ME_UpdateRepaint(editor, FALSE);
2249 } else { /* v1.0 - 3.0 */
2250 ME_DisplayItem *para = cursor.pPara;
2251 if (ME_IsInTable(para))
2253 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2256 ME_ContinueCoalescingTransaction(editor);
2257 para = ME_AppendTableRow(editor, para);
2258 editor->pCursors[0].pPara = para;
2259 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2260 editor->pCursors[0].nOffset = 0;
2261 editor->pCursors[1] = editor->pCursors[0];
2262 ME_CommitCoalescingUndo(editor);
2263 ME_UpdateRepaint(editor, FALSE);
2267 ME_ContinueCoalescingTransaction(editor);
2268 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2269 !ME_IsInTable(para->member.para.prev_para))
2271 /* Insert newline before table */
2272 cursor.pRun = ME_FindItemBack(para, diRun);
2274 editor->pCursors[0].pRun = cursor.pRun;
2275 editor->pCursors[0].pPara = para->member.para.prev_para;
2277 editor->pCursors[0].nOffset = 0;
2278 editor->pCursors[1] = editor->pCursors[0];
2279 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2280 editor->pCursors[0].pRun->member.run.style);
2282 editor->pCursors[1] = editor->pCursors[0];
2283 para = ME_AppendTableRow(editor, para);
2284 editor->pCursors[0].pPara = para;
2285 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2286 editor->pCursors[0].nOffset = 0;
2287 editor->pCursors[1] = editor->pCursors[0];
2289 ME_CommitCoalescingUndo(editor);
2290 ME_UpdateRepaint(editor, FALSE);
2296 style = ME_GetInsertStyle(editor, 0);
2297 ME_SaveTempStyle(editor);
2298 ME_ContinueCoalescingTransaction(editor);
2300 ME_InsertEndRowFromCursor(editor, 0);
2302 if (!editor->bEmulateVersion10)
2303 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2305 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2306 ME_ReleaseStyle(style);
2307 ME_CommitCoalescingUndo(editor);
2310 ME_UpdateSelectionLinkAttribute(editor);
2311 ME_UpdateRepaint(editor, FALSE);
2317 if (editor->bDialogMode && editor->hwndParent)
2318 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2321 if (editor->bDialogMode && editor->hwndParent)
2322 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2327 ME_SetSelection(editor, 0, -1);
2333 return ME_Paste(editor);
2341 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2342 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2345 result = ME_Copy(editor, selStart, nChars);
2346 if (result && nKey == 'X')
2348 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2349 ME_CommitUndo(editor);
2350 ME_UpdateRepaint(editor, TRUE);
2371 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2372 editor->nUDArrowX = -1;
2379 chf.cbSize = sizeof(chf);
2381 ME_GetSelectionCharFormat(editor, &chf);
2382 ME_DumpStyleToBuf(&chf, buf);
2383 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2387 ME_CheckCharOffsets(editor);
2394 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2395 LPARAM flags, BOOL unicode)
2399 if (editor->bMouseCaptured)
2403 wstr = (WCHAR)charCode;
2406 CHAR charA = charCode;
2407 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2410 if (editor->styleFlags & ES_READONLY) {
2411 MessageBeep(MB_ICONERROR);
2412 return 0; /* FIXME really 0 ? */
2415 if ((unsigned)wstr >= ' ' || wstr == '\t')
2417 ME_Cursor cursor = editor->pCursors[0];
2418 ME_DisplayItem *para = cursor.pPara;
2420 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2421 ME_GetSelectionOfs(editor, &from, &to);
2423 /* v4.1 allows tabs to be inserted with ctrl key down */
2424 !(ctrl_is_down && !editor->bEmulateVersion10))
2426 ME_DisplayItem *para;
2427 BOOL bSelectedRow = FALSE;
2429 para = cursor.pPara;
2430 if (ME_IsSelection(editor) &&
2431 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2432 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2433 para->member.para.prev_para->type == diParagraph)
2435 para = para->member.para.prev_para;
2436 bSelectedRow = TRUE;
2438 if (ME_IsInTable(para))
2440 ME_TabPressedInTable(editor, bSelectedRow);
2441 ME_CommitUndo(editor);
2444 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2445 if (para->member.para.nFlags & MEPF_ROWEND) {
2447 para = para->member.para.next_para;
2448 if (para->member.para.nFlags & MEPF_ROWSTART)
2449 para = para->member.para.next_para;
2450 editor->pCursors[0].pPara = para;
2451 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2452 editor->pCursors[0].nOffset = 0;
2453 editor->pCursors[1] = editor->pCursors[0];
2456 } else { /* v1.0 - 3.0 */
2457 if (ME_IsInTable(cursor.pRun) &&
2458 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2461 /* Text should not be inserted at the end of the table. */
2466 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2467 /* WM_CHAR is restricted to nTextLimit */
2468 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2470 ME_Style *style = ME_GetInsertStyle(editor, 0);
2471 ME_SaveTempStyle(editor);
2472 ME_ContinueCoalescingTransaction(editor);
2473 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2474 ME_ReleaseStyle(style);
2475 ME_CommitCoalescingUndo(editor);
2476 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2479 ME_UpdateSelectionLinkAttribute(editor);
2480 ME_UpdateRepaint(editor, FALSE);
2485 /* Process the message and calculate the new click count.
2487 * returns: The click count if it is mouse down event, else returns 0. */
2488 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2491 static int clickNum = 0;
2492 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2495 if ((msg == WM_LBUTTONDBLCLK) ||
2496 (msg == WM_RBUTTONDBLCLK) ||
2497 (msg == WM_MBUTTONDBLCLK) ||
2498 (msg == WM_XBUTTONDBLCLK))
2500 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2503 if ((msg == WM_LBUTTONDOWN) ||
2504 (msg == WM_RBUTTONDOWN) ||
2505 (msg == WM_MBUTTONDOWN) ||
2506 (msg == WM_XBUTTONDOWN))
2508 static MSG prevClickMsg;
2510 /* Compare the editor instead of the hwnd so that the this
2511 * can still be done for windowless richedit controls. */
2512 clickMsg.hwnd = (HWND)editor;
2513 clickMsg.message = msg;
2514 clickMsg.wParam = wParam;
2515 clickMsg.lParam = lParam;
2516 clickMsg.time = GetMessageTime();
2517 clickMsg.pt.x = (short)LOWORD(lParam);
2518 clickMsg.pt.y = (short)HIWORD(lParam);
2519 if ((clickNum != 0) &&
2520 (clickMsg.message == prevClickMsg.message) &&
2521 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2522 (clickMsg.wParam == prevClickMsg.wParam) &&
2523 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2524 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2525 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2531 prevClickMsg = clickMsg;
2538 static BOOL ME_SetCursor(ME_TextEditor *editor)
2544 DWORD messagePos = GetMessagePos();
2545 pt.x = (short)LOWORD(messagePos);
2546 pt.y = (short)HIWORD(messagePos);
2550 sbi.cbSize = sizeof(sbi);
2551 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2552 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2553 PtInRect(&sbi.rcScrollBar, pt))
2555 ITextHost_TxSetCursor(editor->texthost,
2556 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2559 sbi.cbSize = sizeof(sbi);
2560 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2561 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2562 PtInRect(&sbi.rcScrollBar, pt))
2564 ITextHost_TxSetCursor(editor->texthost,
2565 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2569 ITextHost_TxScreenToClient(editor->texthost, &pt);
2571 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2572 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2575 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2576 pt.y < editor->rcFormat.top &&
2577 pt.x < editor->rcFormat.left)
2579 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2582 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2584 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2585 ITextHost_TxSetCursor(editor->texthost,
2586 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2588 ITextHost_TxSetCursor(editor->texthost,
2589 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2592 if (pt.x < editor->rcFormat.left)
2594 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2597 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2602 run = &cursor.pRun->member.run;
2603 if (run->style->fmt.dwMask & CFM_LINK &&
2604 run->style->fmt.dwEffects & CFE_LINK)
2606 ITextHost_TxSetCursor(editor->texthost,
2607 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2612 if (ME_IsSelection(editor))
2614 int selStart, selEnd;
2615 int offset = ME_GetCursorOfs(&cursor);
2617 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2618 if (selStart <= offset && selEnd >= offset) {
2619 ITextHost_TxSetCursor(editor->texthost,
2620 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2626 ITextHost_TxSetCursor(editor->texthost,
2627 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2631 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2633 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2634 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2635 editor->rcFormat.left += 1 + editor->selofs;
2636 editor->rcFormat.right -= 1;
2639 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2644 if(!editor->lpOleCallback || !editor->hWnd)
2646 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2647 if(selrange.cpMin == selrange.cpMax)
2648 seltype |= SEL_EMPTY;
2651 /* FIXME: Handle objects */
2652 seltype |= SEL_TEXT;
2653 if(selrange.cpMax-selrange.cpMin > 1)
2654 seltype |= SEL_MULTICHAR;
2656 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2658 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2664 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2666 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2672 ed->hwndParent = NULL;
2673 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2674 ed->texthost = texthost;
2675 ed->bEmulateVersion10 = bEmulateVersion10;
2677 ITextHost_TxGetPropertyBits(texthost,
2678 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2679 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2680 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2681 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2682 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2684 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2685 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2686 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2687 ed->pBuffer = ME_MakeText();
2688 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2689 ed->nAvailWidth = 0; /* wrap to client area */
2690 ME_MakeFirstParagraph(ed);
2691 /* The four cursors are for:
2692 * 0 - The position where the caret is shown
2693 * 1 - The anchored end of the selection (for normal selection)
2694 * 2 & 3 - The anchored start and end respectively for word, line,
2695 * or paragraph selection.
2698 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2699 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2700 ed->pCursors[1] = ed->pCursors[0];
2701 ed->pCursors[2] = ed->pCursors[0];
2702 ed->pCursors[3] = ed->pCursors[1];
2703 ed->nLastTotalLength = ed->nTotalLength = 0;
2704 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2706 ed->rgbBackColor = -1;
2707 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2708 ed->bCaretAtEnd = FALSE;
2710 ed->nModifyStep = 0;
2711 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2712 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2713 ed->nUndoStackSize = 0;
2714 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2715 ed->nUndoMode = umAddToUndo;
2716 ed->nParagraphs = 1;
2717 ed->nLastSelStart = ed->nLastSelEnd = 0;
2718 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2719 ed->bHideSelection = FALSE;
2720 ed->pfnWordBreak = NULL;
2721 ed->lpOleCallback = NULL;
2722 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2723 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2724 ed->AutoURLDetect_bEnable = FALSE;
2725 ed->bHaveFocus = FALSE;
2726 ed->bDialogMode = FALSE;
2727 ed->bMouseCaptured = FALSE;
2728 for (i=0; i<HFONT_CACHE_SIZE; i++)
2730 ed->pFontCache[i].nRefs = 0;
2731 ed->pFontCache[i].nAge = 0;
2732 ed->pFontCache[i].hFont = NULL;
2735 ME_CheckCharOffsets(ed);
2736 ed->bDefaultFormatRect = TRUE;
2737 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2739 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2740 ed->selofs = SELECTIONBAR_WIDTH;
2741 ed->styleFlags |= ES_SELECTIONBAR;
2745 ed->nSelectionType = stPosition;
2747 ed->cPasswordMask = 0;
2748 if (props & TXTBIT_USEPASSWORD)
2749 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2751 if (props & TXTBIT_AUTOWORDSEL)
2752 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2753 if (props & TXTBIT_MULTILINE) {
2754 ed->styleFlags |= ES_MULTILINE;
2755 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2757 ed->bWordWrap = FALSE;
2759 if (props & TXTBIT_READONLY)
2760 ed->styleFlags |= ES_READONLY;
2761 if (!(props & TXTBIT_HIDESELECTION))
2762 ed->styleFlags |= ES_NOHIDESEL;
2763 if (props & TXTBIT_SAVESELECTION)
2764 ed->styleFlags |= ES_SAVESEL;
2765 if (props & TXTBIT_VERTICAL)
2766 ed->styleFlags |= ES_VERTICAL;
2767 if (props & TXTBIT_DISABLEDRAG)
2768 ed->styleFlags |= ES_NOOLEDRAGDROP;
2770 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2772 /* Default scrollbar information */
2773 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2774 ed->vert_si.nMin = 0;
2775 ed->vert_si.nMax = 0;
2776 ed->vert_si.nPage = 0;
2777 ed->vert_si.nPos = 0;
2779 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2780 ed->horz_si.nMin = 0;
2781 ed->horz_si.nMax = 0;
2782 ed->horz_si.nPage = 0;
2783 ed->horz_si.nPos = 0;
2785 OleInitialize(NULL);
2790 static void ME_DestroyEditor(ME_TextEditor *editor)
2792 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2793 ME_DisplayItem *p = pFirst, *pNext = NULL;
2796 ME_ClearTempStyle(editor);
2797 ME_EmptyUndoStack(editor);
2800 ME_DestroyDisplayItem(p);
2803 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2804 for (i=0; i<HFONT_CACHE_SIZE; i++)
2806 if (editor->pFontCache[i].hFont)
2807 DeleteObject(editor->pFontCache[i].hFont);
2809 if (editor->rgbBackColor != -1)
2810 DeleteObject(editor->hbrBackground);
2811 if(editor->lpOleCallback)
2812 IRichEditOleCallback_Release(editor->lpOleCallback);
2813 ITextHost_Release(editor->texthost);
2816 FREE_OBJ(editor->pBuffer);
2817 FREE_OBJ(editor->pCursors);
2822 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2827 case DLL_PROCESS_ATTACH:
2828 DisableThreadLibraryCalls(hinstDLL);
2829 me_heap = HeapCreate (0, 0x10000, 0);
2830 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2831 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2835 case DLL_PROCESS_DETACH:
2836 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2837 UnregisterClassW(MSFTEDIT_CLASS, 0);
2838 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2839 UnregisterClassA("RichEdit50A", 0);
2840 if (ME_ListBoxRegistered)
2841 UnregisterClassW(REListBox20W, 0);
2842 if (ME_ComboBoxRegistered)
2843 UnregisterClassW(REComboBox20W, 0);
2845 HeapDestroy (me_heap);
2853 static const char * const edit_messages[] = {
2882 "EM_SETPASSWORDCHAR",
2883 "EM_EMPTYUNDOBUFFER",
2884 "EM_GETFIRSTVISIBLELINE",
2886 "EM_SETWORDBREAKPROC",
2887 "EM_GETWORDBREAKPROC",
2888 "EM_GETPASSWORDCHAR",
2898 static const char * const richedit_messages[] = {
2903 "EM_EXLINEFROMCHAR",
2909 "EM_GETOLEINTERFACE",
2919 "EM_SETOLECALLBACK",
2921 "EM_SETTARGETDEVICE",
2929 "EM_GETWORDBREAKPROCEX",
2930 "EM_SETWORDBREAKPROCEX",
2932 "EM_UNKNOWN_USER_83",
2937 "EM_STOPGROUPTYPING",
2941 "EM_GETAUTOURLDETECT",
2944 "EM_GETTEXTLENGTHEX",
2947 "EM_UNKNOWN_USER_98",
2948 "EM_UNKNOWN_USER_99",
2949 "EM_SETPUNCTUATION",
2950 "EM_GETPUNCTUATION",
2951 "EM_SETWORDWRAPMODE",
2952 "EM_GETWORDWRAPMODE",
2958 "EM_UNKNOWN_USER_109",
2959 "EM_UNKNOWN_USER_110",
2960 "EM_UNKNOWN_USER_111",
2961 "EM_UNKNOWN_USER_112",
2962 "EM_UNKNOWN_USER_113",
2963 "EM_UNKNOWN_USER_114",
2964 "EM_UNKNOWN_USER_115",
2965 "EM_UNKNOWN_USER_116",
2966 "EM_UNKNOWN_USER_117",
2967 "EM_UNKNOWN_USER_118",
2968 "EM_UNKNOWN_USER_119",
2969 "EM_SETLANGOPTIONS",
2970 "EM_GETLANGOPTIONS",
2971 "EM_GETIMECOMPMODE",
2975 "EM_SETIMEMODEBIAS",
2980 get_msg_name(UINT msg)
2982 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2983 return edit_messages[msg - EM_GETSEL];
2984 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2985 return richedit_messages[msg - EM_CANPASTE];
2989 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2993 ME_Cursor cursor; /* The start of the clicked text. */
2996 x = (short)LOWORD(lParam);
2997 y = (short)HIWORD(lParam);
2998 ME_CharFromPos(editor, x, y, &cursor, &isExact);
2999 if (!isExact) return;
3001 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3002 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3003 { /* The clicked run has CFE_LINK set */
3004 info.nmhdr.hwndFrom = NULL;
3005 info.nmhdr.idFrom = 0;
3006 info.nmhdr.code = EN_LINK;
3008 info.wParam = wParam;
3009 info.lParam = lParam;
3011 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3012 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
3013 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3017 #define UNSUPPORTED_MSG(e) \
3019 FIXME(#e ": stub\n"); \
3020 *phresult = S_FALSE; \
3023 /* Handle messages for windowless and windoweded richedit controls.
3025 * The LRESULT that is returned is a return value for window procs,
3026 * and the phresult parameter is the COM return code needed by the
3027 * text services interface. */
3028 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3029 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3035 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3036 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3037 UNSUPPORTED_MSG(EM_FMTLINES)
3038 UNSUPPORTED_MSG(EM_FORMATRANGE)
3039 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3040 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3041 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3042 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3043 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3044 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3045 UNSUPPORTED_MSG(EM_GETREDONAME)
3046 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3047 UNSUPPORTED_MSG(EM_GETUNDONAME)
3048 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3049 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3050 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3051 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3052 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3053 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3054 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3055 UNSUPPORTED_MSG(EM_SETMARGINS)
3056 UNSUPPORTED_MSG(EM_SETPALETTE)
3057 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3058 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3059 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3061 /* Messages specific to Richedit controls */
3064 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3066 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3069 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3071 editor->bDialogMode = TRUE;
3072 if (editor->styleFlags & ES_MULTILINE)
3073 code |= DLGC_WANTMESSAGE;
3076 case EM_EMPTYUNDOBUFFER:
3077 ME_EmptyUndoStack(editor);
3081 /* Note: wParam/lParam can be NULL */
3083 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3084 PUINT pto = lParam ? (PUINT)lParam : &to;
3085 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3086 if ((*pfrom|*pto) & 0xFFFF0000)
3088 return MAKELONG(*pfrom,*pto);
3092 CHARRANGE *pRange = (CHARRANGE *)lParam;
3093 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3094 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3097 case EM_SETUNDOLIMIT:
3099 if ((int)wParam < 0)
3100 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3102 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3103 /* Setting a max stack size keeps wine from getting killed
3104 for hogging memory. Windows allocates all this memory at once, so
3105 no program would realistically set a value above our maximum. */
3106 return editor->nUndoLimit;
3109 return editor->pUndoStack != NULL;
3111 return editor->pRedoStack != NULL;
3112 case WM_UNDO: /* FIXME: actually not the same */
3114 return ME_Undo(editor);
3116 return ME_Redo(editor);
3119 /* these flags are equivalent to the ES_* counterparts */
3120 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3121 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3122 DWORD settings = editor->styleFlags & mask;
3128 /* these flags are equivalent to ES_* counterparts, except for
3129 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3130 * but is still stored in editor->styleFlags. */
3131 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3132 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3133 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3134 DWORD settings = mask & editor->styleFlags;
3135 DWORD oldSettings = settings;
3136 DWORD changedSettings;
3152 changedSettings = oldSettings ^ settings;
3154 if (changedSettings) {
3155 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3157 if (changedSettings & ECO_SELECTIONBAR)
3159 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3160 if (settings & ECO_SELECTIONBAR) {
3161 assert(!editor->selofs);
3162 editor->selofs = SELECTIONBAR_WIDTH;
3163 editor->rcFormat.left += editor->selofs;
3165 editor->rcFormat.left -= editor->selofs;
3168 ME_RewrapRepaint(editor);
3171 if (changedSettings & settings & ECO_VERTICAL)
3172 FIXME("ECO_VERTICAL not implemented yet!\n");
3173 if (changedSettings & settings & ECO_AUTOHSCROLL)
3174 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3175 if (changedSettings & settings & ECO_AUTOVSCROLL)
3176 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3177 if (changedSettings & settings & ECO_NOHIDESEL)
3178 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3179 if (changedSettings & settings & ECO_WANTRETURN)
3180 FIXME("ECO_WANTRETURN not implemented yet!\n");
3181 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3182 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3189 ME_InvalidateSelection(editor);
3190 ME_SetSelection(editor, wParam, lParam);
3191 ME_InvalidateSelection(editor);
3192 ITextHost_TxShowCaret(editor->texthost, FALSE);
3193 ME_ShowCaret(editor);
3194 ME_SendSelChange(editor);
3197 case EM_SETSCROLLPOS:
3199 POINT *point = (POINT *)lParam;
3200 ME_ScrollAbs(editor, point->x, point->y);
3203 case EM_AUTOURLDETECT:
3205 if (wParam==1 || wParam ==0)
3207 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3210 return E_INVALIDARG;
3212 case EM_GETAUTOURLDETECT:
3214 return editor->AutoURLDetect_bEnable;
3219 CHARRANGE range = *(CHARRANGE *)lParam;
3221 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3223 ME_InvalidateSelection(editor);
3224 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3225 ME_InvalidateSelection(editor);
3226 ITextHost_TxShowCaret(editor->texthost, FALSE);
3227 ME_ShowCaret(editor);
3228 ME_SendSelChange(editor);
3232 case EM_SHOWSCROLLBAR:
3245 flags = WS_HSCROLL|WS_VSCROLL;
3252 editor->styleFlags |= flags;
3253 if (flags & WS_HSCROLL)
3254 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3255 editor->nTotalWidth > editor->sizeWindow.cx);
3256 if (flags & WS_VSCROLL)
3257 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3258 editor->nTotalLength > editor->sizeWindow.cy);
3260 editor->styleFlags &= ~flags;
3261 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3268 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3272 BOOL bRtf, bUnicode, bSelection;
3273 int oldModify = editor->nModifyStep;
3275 if (!pStruct) return 0;
3277 /* If we detect ascii rtf at the start of the string,
3278 * we know it isn't unicode. */
3279 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3280 !strncmp((char *)lParam, "{\\urtf", 6)));
3281 bUnicode = !bRtf && pStruct->codepage == 1200;
3283 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3284 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3285 pStruct->flags, pStruct->codepage);
3287 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3289 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3290 style = ME_GetSelectionInsertStyle(editor);
3291 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3294 ME_SetCursorToStart(editor, &start);
3295 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3296 style = editor->pBuffer->pDefaultStyle;
3300 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3302 /* FIXME: The length returned doesn't include the rtf control
3303 * characters, only the actual text. */
3304 len = lParam ? strlen((char *)lParam) : 0;
3307 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3308 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3309 len = wszText ? lstrlenW(wszText) : 0;
3310 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3311 ME_EndToUnicode(bUnicode, wszText);
3315 ME_ReleaseStyle(style);
3316 ME_UpdateSelectionLinkAttribute(editor);
3320 ME_SetCursorToStart(editor, &cursor);
3321 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3323 ME_CommitUndo(editor);
3324 if (!(pStruct->flags & ST_KEEPUNDO))
3326 editor->nModifyStep = oldModify;
3327 ME_EmptyUndoStack(editor);
3329 ME_UpdateRepaint(editor, FALSE);
3332 case EM_SETBKGNDCOLOR:
3335 if (editor->rgbBackColor != -1) {
3336 DeleteObject(editor->hbrBackground);
3337 lColor = editor->rgbBackColor;
3339 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3343 editor->rgbBackColor = -1;
3344 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3348 editor->rgbBackColor = lParam;
3349 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3351 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3352 ITextHost_TxViewChange(editor->texthost, TRUE);
3356 return editor->nModifyStep == 0 ? 0 : -1;
3360 editor->nModifyStep = 1;
3362 editor->nModifyStep = 0;
3366 case EM_SETREADONLY:
3369 editor->styleFlags |= ES_READONLY;
3371 editor->styleFlags &= ~ES_READONLY;
3374 case EM_SETEVENTMASK:
3376 DWORD nOldMask = editor->nEventMask;
3378 editor->nEventMask = lParam;
3381 case EM_GETEVENTMASK:
3382 return editor->nEventMask;
3383 case EM_SETCHARFORMAT:
3385 CHARFORMAT2W buf, *p;
3386 BOOL bRepaint = TRUE;
3387 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3388 if (p == NULL) return 0;
3389 if (wParam & SCF_ALL) {
3390 if (editor->mode & TM_PLAINTEXT) {
3391 ME_SetDefaultCharFormat(editor, p);
3394 ME_SetCursorToStart(editor, &start);
3395 ME_SetCharFormat(editor, &start, NULL, p);
3396 editor->nModifyStep = 1;
3398 } else if (wParam & SCF_SELECTION) {
3399 if (editor->mode & TM_PLAINTEXT)
3401 if (wParam & SCF_WORD) {
3402 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3405 bRepaint = ME_IsSelection(editor);
3406 ME_SetSelectionCharFormat(editor, p);
3407 if (bRepaint) editor->nModifyStep = 1;
3408 } else { /* SCF_DEFAULT */
3409 ME_SetDefaultCharFormat(editor, p);
3411 ME_CommitUndo(editor);
3414 ME_WrapMarkedParagraphs(editor);
3415 ME_UpdateScrollBar(editor);
3420 case EM_GETCHARFORMAT:
3422 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3423 if (dst->cbSize != sizeof(CHARFORMATA) &&
3424 dst->cbSize != sizeof(CHARFORMATW) &&
3425 dst->cbSize != sizeof(CHARFORMAT2A) &&
3426 dst->cbSize != sizeof(CHARFORMAT2W))
3428 tmp.cbSize = sizeof(tmp);
3430 ME_GetDefaultCharFormat(editor, &tmp);
3432 ME_GetSelectionCharFormat(editor, &tmp);
3433 ME_CopyToCFAny(dst, &tmp);
3436 case EM_SETPARAFORMAT:
3438 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3439 ME_WrapMarkedParagraphs(editor);
3440 ME_UpdateScrollBar(editor);
3442 ME_CommitUndo(editor);
3445 case EM_GETPARAFORMAT:
3446 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3447 return ((PARAFORMAT2 *)lParam)->dwMask;
3448 case EM_GETFIRSTVISIBLELINE:
3450 ME_DisplayItem *p = editor->pBuffer->pFirst;
3451 int y = editor->vert_si.nPos;
3456 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3457 if (p->type == diTextEnd)
3459 if (p->type == diParagraph) {
3460 ypara = p->member.para.pt.y;
3463 ystart = ypara + p->member.row.pt.y;
3464 yend = ystart + p->member.row.nHeight;
3472 case EM_HIDESELECTION:
3474 editor->bHideSelection = (wParam != 0);
3475 ME_InvalidateSelection(editor);
3480 if (!(editor->styleFlags & ES_MULTILINE))
3482 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3488 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3489 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3490 ME_CommitUndo(editor);
3491 ME_UpdateRepaint(editor, TRUE);
3496 int from, to, nStartCursor;
3498 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3499 size_t len = wszText ? lstrlenW(wszText) : 0;
3500 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3502 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3503 style = ME_GetSelectionInsertStyle(editor);
3504 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3505 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3506 ME_ReleaseStyle(style);
3507 /* drop temporary style if line end */
3509 * FIXME question: does abc\n mean: put abc,
3510 * clear temp style, put \n? (would require a change)
3512 if (len>0 && wszText[len-1] == '\n')
3513 ME_ClearTempStyle(editor);
3514 ME_EndToUnicode(unicode, wszText);
3515 ME_CommitUndo(editor);
3516 ME_UpdateSelectionLinkAttribute(editor);
3518 ME_EmptyUndoStack(editor);
3519 ME_UpdateRepaint(editor, FALSE);
3522 case EM_SCROLLCARET:
3523 ME_EnsureVisible(editor, &editor->pCursors[0]);
3530 BOOL bRepaint = LOWORD(lParam);
3533 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3534 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3535 hDC = ITextHost_TxGetDC(editor->texthost);
3536 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3537 ITextHost_TxReleaseDC(editor->texthost, hDC);
3538 if (editor->mode & TM_RICHTEXT) {
3540 ME_SetCursorToStart(editor, &start);
3541 ME_SetCharFormat(editor, &start, NULL, &fmt);
3543 ME_SetDefaultCharFormat(editor, &fmt);
3545 ME_CommitUndo(editor);
3546 ME_MarkAllForWrapping(editor);
3547 ME_WrapMarkedParagraphs(editor);
3548 ME_UpdateScrollBar(editor);
3556 ME_SetCursorToStart(editor, &cursor);
3557 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3560 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3561 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3562 !strncmp((char *)lParam, "{\\urtf", 6))
3564 /* Undocumented: WM_SETTEXT supports RTF text */
3565 ME_StreamInRTFString(editor, 0, (char *)lParam);
3569 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3570 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3571 if (lstrlenW(wszText) > 0)
3575 /* uses default style! */
3576 if (!(editor->styleFlags & ES_MULTILINE))
3581 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3584 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3586 ME_EndToUnicode(unicode, wszText);
3590 TRACE("WM_SETTEXT - NULL\n");
3591 ME_SetCursorToStart(editor, &cursor);
3592 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3593 ME_SetSelection(editor, 0, 0);
3594 editor->nModifyStep = 0;
3595 ME_CommitUndo(editor);
3596 ME_EmptyUndoStack(editor);
3597 ME_UpdateRepaint(editor, FALSE);
3602 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3603 if (IsClipboardFormatAvailable(nRTFFormat))
3605 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3610 case WM_MBUTTONDOWN:
3616 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3617 int nChars = nTo - nFrom;
3618 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3620 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3622 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3623 ME_CommitUndo(editor);
3624 ME_UpdateRepaint(editor, TRUE);
3628 case WM_GETTEXTLENGTH:
3630 GETTEXTLENGTHEX how;
3632 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3633 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3634 how.codepage = unicode ? 1200 : CP_ACP;
3635 return ME_GetTextLengthEx(editor, &how);
3637 case EM_GETTEXTLENGTHEX:
3638 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3642 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3643 ex.flags = GT_USECRLF;
3644 ex.codepage = unicode ? 1200 : CP_ACP;
3645 ex.lpDefaultChar = NULL;
3646 ex.lpUsedDefChar = NULL;
3647 return ME_GetTextEx(editor, &ex, lParam);
3650 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3653 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3654 ME_Cursor *from = &editor->pCursors[nStartCur];
3655 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3656 nTo - nFrom, unicode);
3658 case EM_GETSCROLLPOS:
3660 POINT *point = (POINT *)lParam;
3661 point->x = editor->horz_si.nPos;
3662 point->y = editor->vert_si.nPos;
3663 /* 16-bit scaled value is returned as stored in scrollinfo */
3664 if (editor->horz_si.nMax > 0xffff)
3665 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3666 if (editor->vert_si.nMax > 0xffff)
3667 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3670 case EM_GETTEXTRANGE:
3672 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3674 int nStart = rng->chrg.cpMin;
3675 int nEnd = rng->chrg.cpMax;
3676 int textlength = ME_GetTextLength(editor);
3678 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3679 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3680 if (nStart < 0) return 0;
3681 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3683 if (nStart >= nEnd) return 0;
3685 ME_CursorFromCharOfs(editor, nStart, &start);
3686 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3690 ME_DisplayItem *run;
3691 const unsigned int nMaxChars = *(WORD *) lParam;
3692 unsigned int nCharsLeft = nMaxChars;
3693 char *dest = (char *) lParam;
3694 BOOL wroteNull = FALSE;
3696 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3697 unicode ? "Unicode" : "Ansi");
3699 run = ME_FindRowWithNumber(editor, wParam);
3703 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3704 && run->type == diRun)
3709 strText = run->member.run.strText;
3710 nCopy = min(nCharsLeft, strText->nLen);
3713 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3715 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3716 nCharsLeft, NULL, NULL);
3717 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3718 nCharsLeft -= nCopy;
3721 /* append line termination, space allowing */
3725 *((WCHAR *)dest) = '\0';
3732 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3733 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3735 case EM_GETLINECOUNT:
3737 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3740 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3742 while (item != editor->pBuffer->pLast)
3744 assert(item->type == diParagraph);
3745 prev_para = ME_FindItemBack(item, diRun);
3747 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3749 nRows += item->member.para.nRows;
3750 item = item->member.para.next_para;
3752 last_para = ME_FindItemBack(item, diRun);
3754 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3755 if (editor->bEmulateVersion10 && prev_para &&
3756 last_para->member.run.nCharOfs == 0 &&
3757 prev_para->member.run.strText->nLen == 1 &&
3758 prev_para->member.run.strText->szData[0] == '\r')
3760 /* In 1.0 emulation, the last solitary \r at the very end of the text
3761 (if one exists) is NOT a line break.
3762 FIXME: this is an ugly hack. This should have a more regular model. */
3766 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3767 return max(1, nRows);
3769 case EM_LINEFROMCHAR:
3772 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3774 return ME_RowNumberFromCharOfs(editor, wParam);
3776 case EM_EXLINEFROMCHAR:
3779 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3781 return ME_RowNumberFromCharOfs(editor, lParam);
3785 ME_DisplayItem *item, *para;
3789 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3791 item = ME_FindRowWithNumber(editor, wParam);
3794 para = ME_GetParagraph(item);
3795 item = ME_FindItemFwd(item, diRun);
3796 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3797 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3802 ME_DisplayItem *item, *item_end;
3803 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3804 ME_DisplayItem *para, *run;
3806 if (wParam > ME_GetTextLength(editor))
3810 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3813 ME_RunOfsFromCharOfs(editor, wParam, ¶, &run, NULL);
3814 item = ME_RowStart(run);
3815 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3816 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3817 if (item_end->type == diStartRow) {
3818 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3820 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3821 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3822 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3824 nChars = nNextLineOfs - nThisLineOfs;
3825 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3828 case EM_EXLIMITTEXT:
3830 if ((int)lParam < 0)
3833 editor->nTextLimit = 65536;
3835 editor->nTextLimit = (int) lParam;
3841 editor->nTextLimit = 65536;
3843 editor->nTextLimit = (int) wParam;
3846 case EM_GETLIMITTEXT:
3848 return editor->nTextLimit;
3852 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3853 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3857 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3858 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3859 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3865 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3866 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3870 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3871 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3872 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3878 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3879 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3881 case EM_FINDTEXTEXW:
3883 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3884 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3887 if (!wParam || !lParam)
3889 *(int *)wParam = editor->nZoomNumerator;
3890 *(int *)lParam = editor->nZoomDenominator;
3893 return ME_SetZoom(editor, wParam, lParam);
3894 case EM_CHARFROMPOS:
3897 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3899 return ME_GetCursorOfs(&cursor);
3903 case EM_POSFROMCHAR:
3905 ME_DisplayItem *pPara, *pRun;
3906 int nCharOfs, nOffset, nLength;
3910 /* detect which API version we're dealing with */
3911 if (wParam >= 0x40000)
3913 nLength = ME_GetTextLength(editor);
3914 nCharOfs = min(nCharOfs, nLength);
3915 nCharOfs = max(nCharOfs, 0);
3917 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3918 assert(pRun->type == diRun);
3919 pt.y = pRun->member.run.pt.y;
3920 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3921 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3922 pt.x += editor->rcFormat.left;
3924 pt.x -= editor->horz_si.nPos;
3925 pt.y -= editor->vert_si.nPos;
3927 if (wParam >= 0x40000) {
3928 *(POINTL *)wParam = pt;
3930 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3936 ME_SetDefaultFormatRect(editor);
3938 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3939 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3940 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3942 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3943 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3945 if (editor->styleFlags & ES_DISABLENOSCROLL)
3947 if (editor->styleFlags & WS_VSCROLL)
3949 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3950 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3952 if (editor->styleFlags & WS_HSCROLL)
3954 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3955 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3959 ME_CommitUndo(editor);
3960 ME_WrapMarkedParagraphs(editor);
3961 ME_MoveCaret(editor);
3965 ME_DestroyEditor(editor);
3969 return ME_SetCursor(editor);
3971 case WM_LBUTTONDBLCLK:
3972 case WM_LBUTTONDOWN:
3974 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3975 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3976 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3978 ITextHost_TxSetFocus(editor->texthost);
3979 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3980 ME_CalculateClickCount(editor, msg, wParam, lParam));
3981 ITextHost_TxSetCapture(editor->texthost, TRUE);
3982 editor->bMouseCaptured = TRUE;
3983 ME_LinkNotify(editor,msg,wParam,lParam);
3984 if (!ME_SetCursor(editor)) goto do_default;
3988 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3989 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3991 if (editor->bMouseCaptured)
3992 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3993 ME_LinkNotify(editor,msg,wParam,lParam);
3994 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3995 if (editor->bMouseCaptured)
3996 ME_SetCursor(editor);
3999 if (editor->bMouseCaptured) {
4000 ITextHost_TxSetCapture(editor->texthost, FALSE);
4001 editor->bMouseCaptured = FALSE;
4003 if (editor->nSelectionType == stDocument)
4004 editor->nSelectionType = stPosition;
4005 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4006 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4010 ME_SetCursor(editor);
4011 ME_LinkNotify(editor,msg,wParam,lParam);
4015 case WM_RBUTTONDOWN:
4016 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4017 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4018 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4021 case WM_CONTEXTMENU:
4022 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4026 editor->bHaveFocus = TRUE;
4027 ME_ShowCaret(editor);
4028 ME_SendOldNotify(editor, EN_SETFOCUS);
4031 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4032 editor->bHaveFocus = FALSE;
4033 ME_HideCaret(editor);
4034 ME_SendOldNotify(editor, EN_KILLFOCUS);
4037 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4040 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4041 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4045 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4046 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4048 if (ME_KeyDown(editor, LOWORD(wParam)))
4052 return ME_Char(editor, wParam, lParam, unicode);
4056 if(wParam == UNICODE_NOCHAR) return TRUE;
4057 if(wParam <= 0x000fffff)
4059 if(wParam > 0xffff) /* convert to surrogates */
4062 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4063 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4065 ME_Char(editor, wParam, 0, TRUE);
4071 case EM_STOPGROUPTYPING:
4072 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4076 const int scrollUnit = 7;
4078 switch(LOWORD(wParam))
4081 ME_ScrollAbs(editor, 0, 0);
4084 ME_ScrollAbs(editor,
4085 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4086 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4089 ME_ScrollLeft(editor, scrollUnit);
4092 ME_ScrollRight(editor, scrollUnit);
4095 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4098 ME_ScrollRight(editor, editor->sizeWindow.cx);
4101 case SB_THUMBPOSITION:
4103 int pos = HIWORD(wParam);
4104 if (editor->horz_si.nMax > 0xffff)
4105 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4106 ME_HScrollAbs(editor, pos);
4112 case EM_SCROLL: /* fall through */
4118 origNPos = editor->vert_si.nPos;
4121 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4122 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4123 if (lineHeight <= 0) lineHeight = 24;
4125 switch(LOWORD(wParam))
4128 ME_ScrollAbs(editor, 0, 0);
4131 ME_ScrollAbs(editor,
4132 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4133 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4136 ME_ScrollUp(editor,lineHeight);
4139 ME_ScrollDown(editor,lineHeight);
4142 ME_ScrollUp(editor,editor->sizeWindow.cy);
4145 ME_ScrollDown(editor,editor->sizeWindow.cy);
4148 case SB_THUMBPOSITION:
4150 int pos = HIWORD(wParam);
4151 if (editor->vert_si.nMax > 0xffff)
4152 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4153 ME_VScrollAbs(editor, pos);
4157 if (msg == EM_SCROLL)
4158 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4164 UINT pulScrollLines;
4167 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4168 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4171 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4173 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4175 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4179 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4183 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4185 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4186 if (numerator >= 10 && numerator <= 500)
4187 ME_SetZoom(editor, numerator, 100);
4189 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4190 /* FIXME follow the original */
4192 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4199 *((RECT *)lParam) = editor->rcFormat;
4200 if (editor->bDefaultFormatRect)
4201 ((RECT *)lParam)->left -= editor->selofs;
4211 RECT *rc = (RECT *)lParam;
4213 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4214 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4217 editor->rcFormat.top = max(0, rc->top - border);
4218 editor->rcFormat.left = max(0, rc->left - border);
4219 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4220 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4221 } else if (wParam == 1) {
4222 /* MSDN incorrectly says a wParam value of 1 causes the
4223 * lParam rect to be used as a relative offset,
4224 * however, the tests show it just prevents min/max bound
4226 editor->rcFormat.top = rc->top - border;
4227 editor->rcFormat.left = rc->left - border;
4228 editor->rcFormat.bottom = rc->bottom;
4229 editor->rcFormat.right = rc->right + border;
4233 editor->bDefaultFormatRect = FALSE;
4237 ME_SetDefaultFormatRect(editor);
4238 editor->bDefaultFormatRect = TRUE;
4240 ME_MarkAllForWrapping(editor);
4241 ME_WrapMarkedParagraphs(editor);
4242 ME_UpdateScrollBar(editor);
4243 if (msg != EM_SETRECTNP)
4247 case EM_REQUESTRESIZE:
4248 ME_SendRequestResize(editor, TRUE);
4256 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4257 if (editor->bDefaultFormatRect) {
4258 ME_SetDefaultFormatRect(editor);
4260 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4261 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4263 editor->prevClientRect = clientRect;
4264 ME_RewrapRepaint(editor);
4267 /* IME messages to make richedit controls IME aware */
4268 case WM_IME_SETCONTEXT:
4269 case WM_IME_CONTROL:
4271 case WM_IME_COMPOSITIONFULL:
4273 case WM_IME_STARTCOMPOSITION:
4275 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4276 ME_DeleteSelection(editor);
4277 ME_CommitUndo(editor);
4278 ME_UpdateRepaint(editor, FALSE);
4281 case WM_IME_COMPOSITION:
4285 ME_Style *style = ME_GetInsertStyle(editor, 0);
4286 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4287 ME_DeleteSelection(editor);
4288 ME_SaveTempStyle(editor);
4289 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4291 LPWSTR lpCompStr = NULL;
4293 DWORD dwIndex = lParam & GCS_RESULTSTR;
4295 dwIndex = GCS_COMPSTR;
4297 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4298 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4299 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4300 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4301 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4302 HeapFree(GetProcessHeap(), 0, lpCompStr);
4304 if (dwIndex == GCS_COMPSTR)
4305 ME_SetSelection(editor,editor->imeStartIndex,
4306 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4308 ME_ReleaseStyle(style);
4309 ME_CommitUndo(editor);
4310 ME_UpdateRepaint(editor, FALSE);
4313 case WM_IME_ENDCOMPOSITION:
4315 ME_DeleteSelection(editor);
4316 editor->imeStartIndex=-1;
4319 case EM_GETOLEINTERFACE:
4321 LPVOID *ppvObj = (LPVOID*) lParam;
4322 return CreateIRichEditOle(editor, ppvObj);
4324 case EM_GETPASSWORDCHAR:
4326 return editor->cPasswordMask;
4328 case EM_SETOLECALLBACK:
4329 if(editor->lpOleCallback)
4330 IRichEditOleCallback_Release(editor->lpOleCallback);
4331 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4332 if(editor->lpOleCallback)
4333 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4335 case EM_GETWORDBREAKPROC:
4336 return (LRESULT)editor->pfnWordBreak;
4337 case EM_SETWORDBREAKPROC:
4339 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4341 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4342 return (LRESULT)pfnOld;
4344 case EM_GETTEXTMODE:
4345 return editor->mode;
4346 case EM_SETTEXTMODE:
4351 if (ME_GetTextLength(editor) || editor->pUndoStack || editor->pRedoStack)
4352 return E_UNEXPECTED;
4354 /* Check for mutually exclusive flags in adjacent bits of wParam */
4355 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4356 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4357 return E_INVALIDARG;
4359 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4361 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4362 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4363 if (wParam & TM_PLAINTEXT) {
4364 /* Clear selection since it should be possible to select the
4365 * end of text run for rich text */
4366 ME_InvalidateSelection(editor);
4367 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4368 editor->pCursors[1] = editor->pCursors[0];
4369 /* plain text can only have the default style. */
4370 ME_ClearTempStyle(editor);
4371 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4372 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4373 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4376 /* FIXME: Currently no support for undo level and code page options */
4377 editor->mode = (editor->mode & ~mask) | changes;
4380 case EM_SETPASSWORDCHAR:
4382 editor->cPasswordMask = wParam;
4383 ME_RewrapRepaint(editor);
4386 case EM_SETTARGETDEVICE:
4389 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4390 if (editor->nAvailWidth || editor->bWordWrap != new)
4392 editor->bWordWrap = new;
4393 editor->nAvailWidth = 0; /* wrap to client area */
4394 ME_RewrapRepaint(editor);
4397 int width = max(0, lParam);
4398 if ((editor->styleFlags & ES_MULTILINE) &&
4399 (!editor->bWordWrap || editor->nAvailWidth != width))
4401 editor->nAvailWidth = width;
4402 editor->bWordWrap = TRUE;
4403 ME_RewrapRepaint(editor);
4405 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4410 *phresult = S_FALSE;
4416 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4417 LPARAM lParam, BOOL unicode)
4419 ME_TextEditor *editor;
4421 LRESULT lresult = 0;
4423 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4424 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4426 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4429 if (msg == WM_NCCREATE)
4431 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4432 ITextHost *texthost;
4434 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4435 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4436 return texthost != NULL;
4440 return DefWindowProcW(hWnd, msg, wParam, lParam);
4452 hDC = BeginPaint(editor->hWnd, &ps);
4453 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4454 ME_SendOldNotify(editor, EN_UPDATE);
4455 /* Erase area outside of the formatting rectangle */
4456 if (ps.rcPaint.top < editor->rcFormat.top)
4459 rc.bottom = editor->rcFormat.top;
4460 FillRect(hDC, &rc, editor->hbrBackground);
4461 ps.rcPaint.top = editor->rcFormat.top;
4463 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4465 rc.top = editor->rcFormat.bottom;
4466 FillRect(hDC, &rc, editor->hbrBackground);
4467 ps.rcPaint.bottom = editor->rcFormat.bottom;
4469 if (ps.rcPaint.left < editor->rcFormat.left) {
4471 rc.right = editor->rcFormat.left;
4472 FillRect(hDC, &rc, editor->hbrBackground);
4473 ps.rcPaint.left = editor->rcFormat.left;
4475 if (ps.rcPaint.right > editor->rcFormat.right) {
4477 rc.left = editor->rcFormat.right;
4478 FillRect(hDC, &rc, editor->hbrBackground);
4479 ps.rcPaint.right = editor->rcFormat.right;
4482 ME_PaintContent(editor, hDC, &ps.rcPaint);
4483 EndPaint(editor->hWnd, &ps);
4488 HDC hDC = (HDC)wParam;
4491 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4492 FillRect(hDC, &rc, editor->hbrBackground);
4498 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4499 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4501 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4502 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4503 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4504 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4507 case EM_SETREADONLY:
4510 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4511 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4512 dwStyle &= ~ES_READONLY;
4514 dwStyle |= ES_READONLY;
4515 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4519 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4522 if (hresult == S_FALSE)
4523 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4525 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4526 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4531 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4533 BOOL unicode = TRUE;
4535 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4536 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4539 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4542 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4544 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4547 /******************************************************************
4548 * RichEditANSIWndProc (RICHED20.10)
4550 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4552 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4555 /******************************************************************
4556 * RichEdit10ANSIWndProc (RICHED20.9)
4558 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4560 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4562 ITextHost *texthost;
4563 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4565 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4566 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4567 return texthost != NULL;
4569 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4572 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4574 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4577 /* Fill buffer with srcChars unicode characters from the start cursor.
4579 * buffer: destination buffer
4580 * buflen: length of buffer in characters excluding the NULL terminator.
4581 * start: start of editor text to copy into buffer.
4582 * srcChars: Number of characters to use from the editor text.
4583 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4585 * returns the number of characters written excluding the NULL terminator.
4587 * The written text is always NULL terminated.
4589 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4590 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4592 ME_DisplayItem *pRun, *pNextRun;
4593 const WCHAR *pStart = buffer;
4594 const WCHAR cr_lf[] = {'\r', '\n', 0};
4598 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4599 if (editor->bEmulateVersion10) bCRLF = 0;
4603 pNextRun = ME_FindItemFwd(pRun, diRun);
4605 nLen = pRun->member.run.strText->nLen - start->nOffset;
4606 str = pRun->member.run.strText->szData + start->nOffset;
4608 /* No '\r' is appended to the last paragraph. */
4609 while (srcChars && buflen && pNextRun)
4611 int nFlags = pRun->member.run.nFlags;
4613 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4615 if (buflen == 1) break;
4616 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4617 * EM_GETTEXTEX, however, this is done for copying text which
4618 * also uses this function. */
4619 srcChars -= min(nLen, srcChars);
4623 nLen = min(nLen, srcChars);
4627 nLen = min(nLen, buflen);
4630 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4635 pNextRun = ME_FindItemFwd(pRun, diRun);
4637 nLen = pRun->member.run.strText->nLen;
4638 str = pRun->member.run.strText->szData;
4641 return buffer - pStart;
4644 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4649 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4650 wcW.lpfnWndProc = RichEditWndProcW;
4652 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4653 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4655 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4656 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4657 wcW.lpszMenuName = NULL;
4659 if (is_version_nt())
4661 wcW.lpszClassName = RICHEDIT_CLASS20W;
4662 if (!RegisterClassW(&wcW)) return FALSE;
4663 wcW.lpszClassName = MSFTEDIT_CLASS;
4664 if (!RegisterClassW(&wcW)) return FALSE;
4668 /* WNDCLASSA/W have the same layout */
4669 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4670 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4671 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4672 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4675 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4676 wcA.lpfnWndProc = RichEditWndProcA;
4678 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4679 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4681 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4682 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4683 wcA.lpszMenuName = NULL;
4684 wcA.lpszClassName = RICHEDIT_CLASS20A;
4685 if (!RegisterClassA(&wcA)) return FALSE;
4686 wcA.lpszClassName = "RichEdit50A";
4687 if (!RegisterClassA(&wcA)) return FALSE;
4692 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4693 /* FIXME: Not implemented */
4694 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4695 hWnd, msg, get_msg_name(msg), wParam, lParam);
4696 return DefWindowProcW(hWnd, msg, wParam, lParam);
4699 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4700 /* FIXME: Not implemented */
4701 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4702 hWnd, msg, get_msg_name(msg), wParam, lParam);
4703 return DefWindowProcW(hWnd, msg, wParam, lParam);
4706 /******************************************************************
4707 * REExtendedRegisterClass (RICHED20.8)
4709 * FIXME undocumented
4710 * Need to check for errors and implement controls and callbacks
4712 LRESULT WINAPI REExtendedRegisterClass(void)
4717 FIXME("semi stub\n");
4721 wcW.hInstance = NULL;
4724 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4725 wcW.lpszMenuName = NULL;
4727 if (!ME_ListBoxRegistered)
4729 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4730 wcW.lpfnWndProc = REListWndProc;
4731 wcW.lpszClassName = REListBox20W;
4732 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4735 if (!ME_ComboBoxRegistered)
4737 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4738 wcW.lpfnWndProc = REComboWndProc;
4739 wcW.lpszClassName = REComboBox20W;
4740 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4744 if (ME_ListBoxRegistered)
4746 if (ME_ComboBoxRegistered)
4752 static BOOL isurlspecial(WCHAR c)
4754 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4755 return strchrW( special_chars, c ) != NULL;
4759 * This proc takes a selection, and scans it forward in order to select the span
4760 * of a possible URL candidate. A possible URL candidate must start with isalnum
4761 * or one of the following special characters: *|/\+%#@ and must consist entirely
4762 * of the characters allowed to start the URL, plus : (colon) which may occur
4763 * at most once, and not at either end.
4765 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4766 const ME_Cursor *start,
4768 ME_Cursor *candidate_min,
4769 ME_Cursor *candidate_max)
4771 ME_Cursor cursor = *start;
4772 BOOL foundColon = FALSE;
4773 BOOL candidateStarted = FALSE;
4774 WCHAR lastAcceptedChar = '\0';
4778 WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4779 WCHAR *str = strStart + cursor.nOffset;
4780 int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4783 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4785 /* Find start of candidate */
4786 if (!candidateStarted)
4791 if (isalnumW(*str) || isurlspecial(*str))
4793 cursor.nOffset = str - strStart;
4794 *candidate_min = cursor;
4795 candidateStarted = TRUE;
4796 lastAcceptedChar = *str++;
4803 /* Find end of candidate */
4804 if (candidateStarted) {
4808 if (*str == ':' && !foundColon) {
4810 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4811 cursor.nOffset = str - strStart;
4812 if (lastAcceptedChar == ':')
4813 ME_MoveCursorChars(editor, &cursor, -1);
4814 *candidate_max = cursor;
4817 lastAcceptedChar = *str++;
4821 /* End of paragraph: skip it if before candidate span, or terminates
4822 current active span */
4823 if (candidateStarted) {
4824 if (lastAcceptedChar == ':')
4825 ME_MoveCursorChars(editor, &cursor, -1);
4826 *candidate_max = cursor;
4831 /* Reaching this point means no span was found, so get next span */
4832 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4833 if (candidateStarted) {
4834 /* There are no further runs, so take end of text as end of candidate */
4835 cursor.nOffset = str - strStart;
4836 if (lastAcceptedChar == ':')
4837 ME_MoveCursorChars(editor, &cursor, -1);
4838 *candidate_max = cursor;
4841 *candidate_max = *candidate_min = cursor;
4847 if (candidateStarted) {
4848 /* There are no further runs, so take end of text as end of candidate */
4849 if (lastAcceptedChar == ':')
4850 ME_MoveCursorChars(editor, &cursor, -1);
4851 *candidate_max = cursor;
4854 *candidate_max = *candidate_min = cursor;
4859 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4861 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4863 #define MAX_PREFIX_LEN 9
4865 const WCHAR text[MAX_PREFIX_LEN];
4868 {{'p','r','o','s','p','e','r','o',':'}, 9},
4869 {{'t','e','l','n','e','t',':'}, 7},
4870 {{'g','o','p','h','e','r',':'}, 7},
4871 {{'m','a','i','l','t','o',':'}, 7},
4872 {{'h','t','t','p','s',':'}, 6},
4873 {{'f','i','l','e',':'}, 5},
4874 {{'n','e','w','s',':'}, 5},
4875 {{'w','a','i','s',':'}, 5},
4876 {{'n','n','t','p',':'}, 5},
4877 {{'h','t','t','p',':'}, 5},
4878 {{'w','w','w','.'}, 4},
4879 {{'f','t','p',':'}, 4},
4881 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4884 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4885 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4887 if (nChars < prefixes[i].length) continue;
4888 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4892 #undef MAX_PREFIX_LEN
4896 * This proc walks through the indicated selection and evaluates whether each
4897 * section identified by ME_FindNextURLCandidate and in-between sections have
4898 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4899 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4901 * Since this function can cause runs to be split, do not depend on the value
4902 * of the start cursor at the end of the function.
4904 * nChars may be set to INT_MAX to update to the end of the text.
4906 * Returns TRUE if at least one section was modified.
4908 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4910 BOOL modified = FALSE;
4911 ME_Cursor startCur = *start;
4913 if (!editor->AutoURLDetect_bEnable) return FALSE;
4918 ME_Cursor candidateStart, candidateEnd;
4920 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4921 &candidateStart, &candidateEnd))
4923 /* Section before candidate is not an URL */
4924 int cMin = ME_GetCursorOfs(&candidateStart);
4925 int cMax = ME_GetCursorOfs(&candidateEnd);
4927 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4928 candidateStart = candidateEnd;
4929 nChars -= cMax - ME_GetCursorOfs(&startCur);
4933 /* No more candidates until end of selection */
4937 if (startCur.pRun != candidateStart.pRun ||
4938 startCur.nOffset != candidateStart.nOffset)
4940 /* CFE_LINK effect should be consistently unset */
4941 link.cbSize = sizeof(link);
4942 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4943 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4945 /* CFE_LINK must be unset from this range */
4946 memset(&link, 0, sizeof(CHARFORMAT2W));
4947 link.cbSize = sizeof(link);
4948 link.dwMask = CFM_LINK;
4950 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4951 /* Update candidateEnd since setting character formats may split
4952 * runs, which can cause a cursor to be at an invalid offset within
4954 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4956 candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4957 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4962 if (candidateStart.pRun != candidateEnd.pRun ||
4963 candidateStart.nOffset != candidateEnd.nOffset)
4965 /* CFE_LINK effect should be consistently set */
4966 link.cbSize = sizeof(link);
4967 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4968 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4970 /* CFE_LINK must be set on this range */
4971 memset(&link, 0, sizeof(CHARFORMAT2W));
4972 link.cbSize = sizeof(link);
4973 link.dwMask = CFM_LINK;
4974 link.dwEffects = CFE_LINK;
4975 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4979 startCur = candidateEnd;
4980 } while (nChars > 0);