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 = *get_text( &cursor.pRun->member.run, 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( *get_text( &pCurItem->member.run, 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.len)
1755 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1756 nNextStart = -nMatched;
1760 wNextChar = *get_text( &pNextItem->member.run, 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.len)
1779 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1780 nCurStart = -nMatched;
1784 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1789 if (cursor.nOffset == cursor.pRun->member.run.len)
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 = *get_text( &cursor.pRun->member.run, 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.len + nMatched;
1821 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1822 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1824 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1828 if (nMatched == nLen)
1830 ME_DisplayItem *pPrevItem = pCurItem;
1831 int nPrevEnd = nCurEnd;
1835 /* Check to see if previous character is a whitespace */
1836 if (flags & FR_WHOLEWORD)
1838 if (nPrevEnd - nMatched == 0)
1840 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1842 nPrevEnd = pPrevItem->member.run.len + nMatched;
1846 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1850 if (isalnumW(wPrevChar))
1854 nStart = pCurPara->member.para.nCharOfs
1855 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1858 chrgText->cpMin = nStart;
1859 chrgText->cpMax = nStart + nLen;
1861 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1864 if (nCurEnd - nMatched == 0)
1866 ME_PrevRun(&pCurPara, &pCurItem);
1867 /* Don't care about pCurItem becoming NULL here; it's already taken
1868 * care of in the exterior loop condition */
1869 nCurEnd = pCurItem->member.run.len + nMatched;
1873 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1878 if (cursor.nOffset < 0)
1880 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1881 cursor.nOffset = cursor.pRun->member.run.len;
1885 TRACE("not found\n");
1887 chrgText->cpMin = chrgText->cpMax = -1;
1891 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1896 if (!ex->cb || !pText) return 0;
1898 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1899 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1901 if (ex->flags & GT_SELECTION)
1904 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1905 start = editor->pCursors[nStartCur];
1910 ME_SetCursorToStart(editor, &start);
1913 if (ex->codepage == 1200)
1915 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1916 &start, nChars, ex->flags & GT_USECRLF);
1920 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1921 we can just take a bigger buffer? :)
1922 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1923 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1925 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1930 buflen = min(crlfmul * nChars, ex->cb - 1);
1931 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1933 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1934 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1935 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1936 if (rc) rc--; /* do not count 0 terminator */
1943 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1944 const ME_Cursor *start, int nLen, BOOL unicode)
1946 if (!strText) return 0;
1948 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1951 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1953 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1954 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1955 nLen+1, NULL, NULL);
1961 typedef struct tagME_GlobalDestStruct
1965 } ME_GlobalDestStruct;
1967 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1969 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1974 pDest = (WORD *)lpBuff;
1975 pSrc = GlobalLock(pData->hData);
1976 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1977 pDest[i] = pSrc[pData->nLength+i];
1979 pData->nLength += i;
1981 GlobalUnlock(pData->hData);
1985 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1987 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1992 pSrc = GlobalLock(pData->hData);
1993 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1994 pDest[i] = pSrc[pData->nLength+i];
1996 pData->nLength += i;
1998 GlobalUnlock(pData->hData);
2002 static BOOL ME_Paste(ME_TextEditor *editor)
2006 ME_GlobalDestStruct gds;
2007 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2010 if (IsClipboardFormatAvailable(nRTFFormat))
2011 cf = nRTFFormat, dwFormat = SF_RTF;
2012 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2013 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2017 if (!OpenClipboard(editor->hWnd))
2019 gds.hData = GetClipboardData(cf);
2021 es.dwCookie = (DWORD_PTR)&gds;
2022 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2023 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2029 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2031 LPDATAOBJECT dataObj = NULL;
2034 if (editor->cPasswordMask)
2035 return FALSE; /* Copying or Cutting masked text isn't allowed */
2037 if(editor->lpOleCallback)
2040 range.cpMin = ME_GetCursorOfs(start);
2041 range.cpMax = range.cpMin + nChars;
2042 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2044 if(FAILED(hr) || !dataObj)
2045 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2047 hr = OleSetClipboard(dataObj);
2048 IDataObject_Release(dataObj);
2050 return SUCCEEDED(hr) != 0;
2053 /* helper to send a msg filter notification */
2055 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2059 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2060 msgf.nmhdr.hwndFrom = editor->hWnd;
2061 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2062 msgf.nmhdr.code = EN_MSGFILTER;
2064 msgf.wParam = *wParam;
2065 msgf.lParam = *lParam;
2066 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2068 *wParam = msgf.wParam;
2069 *lParam = msgf.lParam;
2070 msgf.wParam = *wParam;
2075 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2077 ME_DisplayItem *startPara, *endPara;
2078 ME_DisplayItem *prev_para;
2079 ME_Cursor *from, *to;
2083 if (!editor->AutoURLDetect_bEnable) return;
2085 ME_GetSelection(editor, &from, &to);
2087 /* Find paragraph previous to the one that contains start cursor */
2088 startPara = from->pPara;
2089 prev_para = startPara->member.para.prev_para;
2090 if (prev_para->type == diParagraph) startPara = prev_para;
2092 /* Find paragraph that contains end cursor */
2093 endPara = to->pPara->member.para.next_para;
2095 start.pPara = startPara;
2096 start.pRun = ME_FindItemFwd(startPara, diRun);
2098 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2100 ME_UpdateLinkAttribute(editor, &start, nChars);
2104 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2106 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2107 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2109 if (editor->bMouseCaptured)
2111 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2112 editor->nSelectionType = stPosition;
2120 editor->nUDArrowX = -1;
2126 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2127 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2131 editor->nUDArrowX = -1;
2132 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2133 if (editor->styleFlags & ES_READONLY)
2135 if (ME_IsSelection(editor))
2137 ME_DeleteSelection(editor);
2138 ME_CommitUndo(editor);
2140 else if (nKey == VK_DELETE)
2142 /* Delete stops group typing.
2143 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2144 ME_DeleteTextAtCursor(editor, 1, 1);
2145 ME_CommitUndo(editor);
2147 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2149 BOOL bDeletionSucceeded;
2150 /* Backspace can be grouped for a single undo */
2151 ME_ContinueCoalescingTransaction(editor);
2152 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2153 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2154 /* Deletion was prevented so the cursor is moved back to where it was.
2155 * (e.g. this happens when trying to delete cell boundaries)
2157 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2159 ME_CommitCoalescingUndo(editor);
2163 ME_MoveCursorFromTableRowStartParagraph(editor);
2164 ME_UpdateSelectionLinkAttribute(editor);
2165 ME_UpdateRepaint(editor, FALSE);
2166 ME_SendRequestResize(editor, FALSE);
2169 if (editor->bDialogMode)
2174 if (!(editor->styleFlags & ES_WANTRETURN))
2176 if (editor->hwndParent)
2179 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2180 if (HIWORD(dw) == DC_HASDEFID)
2182 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2185 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2186 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2194 if (editor->styleFlags & ES_MULTILINE)
2196 ME_Cursor cursor = editor->pCursors[0];
2197 ME_DisplayItem *para = cursor.pPara;
2199 const WCHAR endl = '\r';
2200 const WCHAR endlv10[] = {'\r','\n'};
2203 if (editor->styleFlags & ES_READONLY) {
2204 MessageBeep(MB_ICONERROR);
2208 ME_GetSelectionOfs(editor, &from, &to);
2209 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2211 if (!editor->bEmulateVersion10) { /* v4.1 */
2212 if (para->member.para.nFlags & MEPF_ROWEND) {
2213 /* Add a new table row after this row. */
2214 para = ME_AppendTableRow(editor, para);
2215 para = para->member.para.next_para;
2216 editor->pCursors[0].pPara = para;
2217 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2218 editor->pCursors[0].nOffset = 0;
2219 editor->pCursors[1] = editor->pCursors[0];
2220 ME_CommitUndo(editor);
2221 ME_CheckTablesForCorruption(editor);
2222 ME_UpdateRepaint(editor, FALSE);
2225 else if (para == editor->pCursors[1].pPara &&
2226 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2227 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2228 !para->member.para.prev_para->member.para.nCharOfs)
2230 /* Insert a newline before the table. */
2231 para = para->member.para.prev_para;
2232 para->member.para.nFlags &= ~MEPF_ROWSTART;
2233 editor->pCursors[0].pPara = para;
2234 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2235 editor->pCursors[1] = editor->pCursors[0];
2236 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2237 editor->pCursors[0].pRun->member.run.style);
2238 para = editor->pBuffer->pFirst->member.para.next_para;
2239 ME_SetDefaultParaFormat(para->member.para.pFmt);
2240 para->member.para.nFlags = MEPF_REWRAP;
2241 editor->pCursors[0].pPara = para;
2242 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2243 editor->pCursors[1] = editor->pCursors[0];
2244 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2245 ME_CommitCoalescingUndo(editor);
2246 ME_CheckTablesForCorruption(editor);
2247 ME_UpdateRepaint(editor, FALSE);
2250 } else { /* v1.0 - 3.0 */
2251 ME_DisplayItem *para = cursor.pPara;
2252 if (ME_IsInTable(para))
2254 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2257 ME_ContinueCoalescingTransaction(editor);
2258 para = ME_AppendTableRow(editor, para);
2259 editor->pCursors[0].pPara = para;
2260 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2261 editor->pCursors[0].nOffset = 0;
2262 editor->pCursors[1] = editor->pCursors[0];
2263 ME_CommitCoalescingUndo(editor);
2264 ME_UpdateRepaint(editor, FALSE);
2268 ME_ContinueCoalescingTransaction(editor);
2269 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2270 !ME_IsInTable(para->member.para.prev_para))
2272 /* Insert newline before table */
2273 cursor.pRun = ME_FindItemBack(para, diRun);
2275 editor->pCursors[0].pRun = cursor.pRun;
2276 editor->pCursors[0].pPara = para->member.para.prev_para;
2278 editor->pCursors[0].nOffset = 0;
2279 editor->pCursors[1] = editor->pCursors[0];
2280 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2281 editor->pCursors[0].pRun->member.run.style);
2283 editor->pCursors[1] = editor->pCursors[0];
2284 para = ME_AppendTableRow(editor, para);
2285 editor->pCursors[0].pPara = para;
2286 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2287 editor->pCursors[0].nOffset = 0;
2288 editor->pCursors[1] = editor->pCursors[0];
2290 ME_CommitCoalescingUndo(editor);
2291 ME_UpdateRepaint(editor, FALSE);
2297 style = ME_GetInsertStyle(editor, 0);
2298 ME_SaveTempStyle(editor);
2299 ME_ContinueCoalescingTransaction(editor);
2301 ME_InsertEndRowFromCursor(editor, 0);
2303 if (!editor->bEmulateVersion10)
2304 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2306 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2307 ME_ReleaseStyle(style);
2308 ME_CommitCoalescingUndo(editor);
2311 ME_UpdateSelectionLinkAttribute(editor);
2312 ME_UpdateRepaint(editor, FALSE);
2318 if (editor->bDialogMode && editor->hwndParent)
2319 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2322 if (editor->bDialogMode && editor->hwndParent)
2323 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2328 ME_SetSelection(editor, 0, -1);
2334 return ME_Paste(editor);
2342 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2343 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2346 result = ME_Copy(editor, selStart, nChars);
2347 if (result && nKey == 'X')
2349 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2350 ME_CommitUndo(editor);
2351 ME_UpdateRepaint(editor, TRUE);
2372 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2373 editor->nUDArrowX = -1;
2380 chf.cbSize = sizeof(chf);
2382 ME_GetSelectionCharFormat(editor, &chf);
2383 ME_DumpStyleToBuf(&chf, buf);
2384 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2388 ME_CheckCharOffsets(editor);
2395 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2396 LPARAM flags, BOOL unicode)
2400 if (editor->bMouseCaptured)
2404 wstr = (WCHAR)charCode;
2407 CHAR charA = charCode;
2408 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2411 if (editor->styleFlags & ES_READONLY) {
2412 MessageBeep(MB_ICONERROR);
2413 return 0; /* FIXME really 0 ? */
2416 if ((unsigned)wstr >= ' ' || wstr == '\t')
2418 ME_Cursor cursor = editor->pCursors[0];
2419 ME_DisplayItem *para = cursor.pPara;
2421 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2422 ME_GetSelectionOfs(editor, &from, &to);
2424 /* v4.1 allows tabs to be inserted with ctrl key down */
2425 !(ctrl_is_down && !editor->bEmulateVersion10))
2427 ME_DisplayItem *para;
2428 BOOL bSelectedRow = FALSE;
2430 para = cursor.pPara;
2431 if (ME_IsSelection(editor) &&
2432 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2433 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2434 para->member.para.prev_para->type == diParagraph)
2436 para = para->member.para.prev_para;
2437 bSelectedRow = TRUE;
2439 if (ME_IsInTable(para))
2441 ME_TabPressedInTable(editor, bSelectedRow);
2442 ME_CommitUndo(editor);
2445 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2446 if (para->member.para.nFlags & MEPF_ROWEND) {
2448 para = para->member.para.next_para;
2449 if (para->member.para.nFlags & MEPF_ROWSTART)
2450 para = para->member.para.next_para;
2451 editor->pCursors[0].pPara = para;
2452 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2453 editor->pCursors[0].nOffset = 0;
2454 editor->pCursors[1] = editor->pCursors[0];
2457 } else { /* v1.0 - 3.0 */
2458 if (ME_IsInTable(cursor.pRun) &&
2459 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2462 /* Text should not be inserted at the end of the table. */
2467 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2468 /* WM_CHAR is restricted to nTextLimit */
2469 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2471 ME_Style *style = ME_GetInsertStyle(editor, 0);
2472 ME_SaveTempStyle(editor);
2473 ME_ContinueCoalescingTransaction(editor);
2474 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2475 ME_ReleaseStyle(style);
2476 ME_CommitCoalescingUndo(editor);
2477 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2480 ME_UpdateSelectionLinkAttribute(editor);
2481 ME_UpdateRepaint(editor, FALSE);
2486 /* Process the message and calculate the new click count.
2488 * returns: The click count if it is mouse down event, else returns 0. */
2489 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2492 static int clickNum = 0;
2493 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2496 if ((msg == WM_LBUTTONDBLCLK) ||
2497 (msg == WM_RBUTTONDBLCLK) ||
2498 (msg == WM_MBUTTONDBLCLK) ||
2499 (msg == WM_XBUTTONDBLCLK))
2501 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2504 if ((msg == WM_LBUTTONDOWN) ||
2505 (msg == WM_RBUTTONDOWN) ||
2506 (msg == WM_MBUTTONDOWN) ||
2507 (msg == WM_XBUTTONDOWN))
2509 static MSG prevClickMsg;
2511 /* Compare the editor instead of the hwnd so that the this
2512 * can still be done for windowless richedit controls. */
2513 clickMsg.hwnd = (HWND)editor;
2514 clickMsg.message = msg;
2515 clickMsg.wParam = wParam;
2516 clickMsg.lParam = lParam;
2517 clickMsg.time = GetMessageTime();
2518 clickMsg.pt.x = (short)LOWORD(lParam);
2519 clickMsg.pt.y = (short)HIWORD(lParam);
2520 if ((clickNum != 0) &&
2521 (clickMsg.message == prevClickMsg.message) &&
2522 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2523 (clickMsg.wParam == prevClickMsg.wParam) &&
2524 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2525 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2526 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2532 prevClickMsg = clickMsg;
2539 static BOOL ME_SetCursor(ME_TextEditor *editor)
2545 DWORD messagePos = GetMessagePos();
2546 pt.x = (short)LOWORD(messagePos);
2547 pt.y = (short)HIWORD(messagePos);
2551 sbi.cbSize = sizeof(sbi);
2552 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2553 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2554 PtInRect(&sbi.rcScrollBar, pt))
2556 ITextHost_TxSetCursor(editor->texthost,
2557 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2560 sbi.cbSize = sizeof(sbi);
2561 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2562 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2563 PtInRect(&sbi.rcScrollBar, pt))
2565 ITextHost_TxSetCursor(editor->texthost,
2566 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2570 ITextHost_TxScreenToClient(editor->texthost, &pt);
2572 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2573 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2576 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2577 pt.y < editor->rcFormat.top &&
2578 pt.x < editor->rcFormat.left)
2580 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2583 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2585 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2586 ITextHost_TxSetCursor(editor->texthost,
2587 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2589 ITextHost_TxSetCursor(editor->texthost,
2590 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2593 if (pt.x < editor->rcFormat.left)
2595 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2598 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2603 run = &cursor.pRun->member.run;
2604 if (run->style->fmt.dwMask & CFM_LINK &&
2605 run->style->fmt.dwEffects & CFE_LINK)
2607 ITextHost_TxSetCursor(editor->texthost,
2608 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2613 if (ME_IsSelection(editor))
2615 int selStart, selEnd;
2616 int offset = ME_GetCursorOfs(&cursor);
2618 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2619 if (selStart <= offset && selEnd >= offset) {
2620 ITextHost_TxSetCursor(editor->texthost,
2621 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2627 ITextHost_TxSetCursor(editor->texthost,
2628 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2632 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2634 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2635 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2636 editor->rcFormat.left += 1 + editor->selofs;
2637 editor->rcFormat.right -= 1;
2640 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2645 if(!editor->lpOleCallback || !editor->hWnd)
2647 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2648 if(selrange.cpMin == selrange.cpMax)
2649 seltype |= SEL_EMPTY;
2652 /* FIXME: Handle objects */
2653 seltype |= SEL_TEXT;
2654 if(selrange.cpMax-selrange.cpMin > 1)
2655 seltype |= SEL_MULTICHAR;
2657 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2659 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2665 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2667 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2673 ed->hwndParent = NULL;
2674 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2675 ed->texthost = texthost;
2676 ed->bEmulateVersion10 = bEmulateVersion10;
2678 ITextHost_TxGetPropertyBits(texthost,
2679 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2680 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2681 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2682 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2683 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2685 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2686 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2687 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2688 ed->pBuffer = ME_MakeText();
2689 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2690 ed->nAvailWidth = 0; /* wrap to client area */
2691 ME_MakeFirstParagraph(ed);
2692 /* The four cursors are for:
2693 * 0 - The position where the caret is shown
2694 * 1 - The anchored end of the selection (for normal selection)
2695 * 2 & 3 - The anchored start and end respectively for word, line,
2696 * or paragraph selection.
2699 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2700 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2701 ed->pCursors[1] = ed->pCursors[0];
2702 ed->pCursors[2] = ed->pCursors[0];
2703 ed->pCursors[3] = ed->pCursors[1];
2704 ed->nLastTotalLength = ed->nTotalLength = 0;
2705 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2707 ed->rgbBackColor = -1;
2708 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2709 ed->bCaretAtEnd = FALSE;
2711 ed->nModifyStep = 0;
2712 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2713 list_init( &ed->undo_stack );
2714 list_init( &ed->redo_stack );
2715 ed->nUndoStackSize = 0;
2716 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2717 ed->nUndoMode = umAddToUndo;
2718 ed->nParagraphs = 1;
2719 ed->nLastSelStart = ed->nLastSelEnd = 0;
2720 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2721 ed->bHideSelection = FALSE;
2722 ed->pfnWordBreak = NULL;
2723 ed->lpOleCallback = NULL;
2724 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2725 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2726 ed->AutoURLDetect_bEnable = FALSE;
2727 ed->bHaveFocus = FALSE;
2728 ed->bDialogMode = FALSE;
2729 ed->bMouseCaptured = FALSE;
2730 for (i=0; i<HFONT_CACHE_SIZE; i++)
2732 ed->pFontCache[i].nRefs = 0;
2733 ed->pFontCache[i].nAge = 0;
2734 ed->pFontCache[i].hFont = NULL;
2737 ME_CheckCharOffsets(ed);
2738 ed->bDefaultFormatRect = TRUE;
2739 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2741 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2742 ed->selofs = SELECTIONBAR_WIDTH;
2743 ed->styleFlags |= ES_SELECTIONBAR;
2747 ed->nSelectionType = stPosition;
2749 ed->cPasswordMask = 0;
2750 if (props & TXTBIT_USEPASSWORD)
2751 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2753 if (props & TXTBIT_AUTOWORDSEL)
2754 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2755 if (props & TXTBIT_MULTILINE) {
2756 ed->styleFlags |= ES_MULTILINE;
2757 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2759 ed->bWordWrap = FALSE;
2761 if (props & TXTBIT_READONLY)
2762 ed->styleFlags |= ES_READONLY;
2763 if (!(props & TXTBIT_HIDESELECTION))
2764 ed->styleFlags |= ES_NOHIDESEL;
2765 if (props & TXTBIT_SAVESELECTION)
2766 ed->styleFlags |= ES_SAVESEL;
2767 if (props & TXTBIT_VERTICAL)
2768 ed->styleFlags |= ES_VERTICAL;
2769 if (props & TXTBIT_DISABLEDRAG)
2770 ed->styleFlags |= ES_NOOLEDRAGDROP;
2772 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2774 /* Default scrollbar information */
2775 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2776 ed->vert_si.nMin = 0;
2777 ed->vert_si.nMax = 0;
2778 ed->vert_si.nPage = 0;
2779 ed->vert_si.nPos = 0;
2781 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2782 ed->horz_si.nMin = 0;
2783 ed->horz_si.nMax = 0;
2784 ed->horz_si.nPage = 0;
2785 ed->horz_si.nPos = 0;
2787 OleInitialize(NULL);
2792 static void ME_DestroyEditor(ME_TextEditor *editor)
2794 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2795 ME_DisplayItem *p = pFirst, *pNext = NULL;
2798 ME_ClearTempStyle(editor);
2799 ME_EmptyUndoStack(editor);
2802 ME_DestroyDisplayItem(p);
2805 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2806 for (i=0; i<HFONT_CACHE_SIZE; i++)
2808 if (editor->pFontCache[i].hFont)
2809 DeleteObject(editor->pFontCache[i].hFont);
2811 if (editor->rgbBackColor != -1)
2812 DeleteObject(editor->hbrBackground);
2813 if(editor->lpOleCallback)
2814 IRichEditOleCallback_Release(editor->lpOleCallback);
2815 ITextHost_Release(editor->texthost);
2818 FREE_OBJ(editor->pBuffer);
2819 FREE_OBJ(editor->pCursors);
2824 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2829 case DLL_PROCESS_ATTACH:
2830 DisableThreadLibraryCalls(hinstDLL);
2831 me_heap = HeapCreate (0, 0x10000, 0);
2832 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2833 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2837 case DLL_PROCESS_DETACH:
2838 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2839 UnregisterClassW(MSFTEDIT_CLASS, 0);
2840 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2841 UnregisterClassA("RichEdit50A", 0);
2842 if (ME_ListBoxRegistered)
2843 UnregisterClassW(REListBox20W, 0);
2844 if (ME_ComboBoxRegistered)
2845 UnregisterClassW(REComboBox20W, 0);
2847 HeapDestroy (me_heap);
2855 static const char * const edit_messages[] = {
2884 "EM_SETPASSWORDCHAR",
2885 "EM_EMPTYUNDOBUFFER",
2886 "EM_GETFIRSTVISIBLELINE",
2888 "EM_SETWORDBREAKPROC",
2889 "EM_GETWORDBREAKPROC",
2890 "EM_GETPASSWORDCHAR",
2900 static const char * const richedit_messages[] = {
2905 "EM_EXLINEFROMCHAR",
2911 "EM_GETOLEINTERFACE",
2921 "EM_SETOLECALLBACK",
2923 "EM_SETTARGETDEVICE",
2931 "EM_GETWORDBREAKPROCEX",
2932 "EM_SETWORDBREAKPROCEX",
2934 "EM_UNKNOWN_USER_83",
2939 "EM_STOPGROUPTYPING",
2943 "EM_GETAUTOURLDETECT",
2946 "EM_GETTEXTLENGTHEX",
2949 "EM_UNKNOWN_USER_98",
2950 "EM_UNKNOWN_USER_99",
2951 "EM_SETPUNCTUATION",
2952 "EM_GETPUNCTUATION",
2953 "EM_SETWORDWRAPMODE",
2954 "EM_GETWORDWRAPMODE",
2960 "EM_UNKNOWN_USER_109",
2961 "EM_UNKNOWN_USER_110",
2962 "EM_UNKNOWN_USER_111",
2963 "EM_UNKNOWN_USER_112",
2964 "EM_UNKNOWN_USER_113",
2965 "EM_UNKNOWN_USER_114",
2966 "EM_UNKNOWN_USER_115",
2967 "EM_UNKNOWN_USER_116",
2968 "EM_UNKNOWN_USER_117",
2969 "EM_UNKNOWN_USER_118",
2970 "EM_UNKNOWN_USER_119",
2971 "EM_SETLANGOPTIONS",
2972 "EM_GETLANGOPTIONS",
2973 "EM_GETIMECOMPMODE",
2977 "EM_SETIMEMODEBIAS",
2982 get_msg_name(UINT msg)
2984 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2985 return edit_messages[msg - EM_GETSEL];
2986 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2987 return richedit_messages[msg - EM_CANPASTE];
2991 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2995 ME_Cursor cursor; /* The start of the clicked text. */
2998 x = (short)LOWORD(lParam);
2999 y = (short)HIWORD(lParam);
3000 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3001 if (!isExact) return;
3003 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3004 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3005 { /* The clicked run has CFE_LINK set */
3006 info.nmhdr.hwndFrom = NULL;
3007 info.nmhdr.idFrom = 0;
3008 info.nmhdr.code = EN_LINK;
3010 info.wParam = wParam;
3011 info.lParam = lParam;
3013 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3014 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3015 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3019 #define UNSUPPORTED_MSG(e) \
3021 FIXME(#e ": stub\n"); \
3022 *phresult = S_FALSE; \
3025 /* Handle messages for windowless and windoweded richedit controls.
3027 * The LRESULT that is returned is a return value for window procs,
3028 * and the phresult parameter is the COM return code needed by the
3029 * text services interface. */
3030 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3031 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3037 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3038 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3039 UNSUPPORTED_MSG(EM_FMTLINES)
3040 UNSUPPORTED_MSG(EM_FORMATRANGE)
3041 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3042 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3043 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3044 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3045 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3046 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3047 UNSUPPORTED_MSG(EM_GETREDONAME)
3048 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3049 UNSUPPORTED_MSG(EM_GETUNDONAME)
3050 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3051 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3052 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3053 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3054 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3055 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3056 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3057 UNSUPPORTED_MSG(EM_SETMARGINS)
3058 UNSUPPORTED_MSG(EM_SETPALETTE)
3059 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3060 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3061 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3063 /* Messages specific to Richedit controls */
3066 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3068 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3071 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3073 editor->bDialogMode = TRUE;
3074 if (editor->styleFlags & ES_MULTILINE)
3075 code |= DLGC_WANTMESSAGE;
3078 case EM_EMPTYUNDOBUFFER:
3079 ME_EmptyUndoStack(editor);
3083 /* Note: wParam/lParam can be NULL */
3085 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3086 PUINT pto = lParam ? (PUINT)lParam : &to;
3087 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3088 if ((*pfrom|*pto) & 0xFFFF0000)
3090 return MAKELONG(*pfrom,*pto);
3094 CHARRANGE *pRange = (CHARRANGE *)lParam;
3095 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3096 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3099 case EM_SETUNDOLIMIT:
3101 if ((int)wParam < 0)
3102 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3104 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3105 /* Setting a max stack size keeps wine from getting killed
3106 for hogging memory. Windows allocates all this memory at once, so
3107 no program would realistically set a value above our maximum. */
3108 return editor->nUndoLimit;
3111 return !list_empty( &editor->undo_stack );
3113 return !list_empty( &editor->redo_stack );
3114 case WM_UNDO: /* FIXME: actually not the same */
3116 return ME_Undo(editor);
3118 return ME_Redo(editor);
3121 /* these flags are equivalent to the ES_* counterparts */
3122 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3123 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3124 DWORD settings = editor->styleFlags & mask;
3130 /* these flags are equivalent to ES_* counterparts, except for
3131 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3132 * but is still stored in editor->styleFlags. */
3133 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3134 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3135 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3136 DWORD settings = mask & editor->styleFlags;
3137 DWORD oldSettings = settings;
3138 DWORD changedSettings;
3154 changedSettings = oldSettings ^ settings;
3156 if (changedSettings) {
3157 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3159 if (changedSettings & ECO_SELECTIONBAR)
3161 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3162 if (settings & ECO_SELECTIONBAR) {
3163 assert(!editor->selofs);
3164 editor->selofs = SELECTIONBAR_WIDTH;
3165 editor->rcFormat.left += editor->selofs;
3167 editor->rcFormat.left -= editor->selofs;
3170 ME_RewrapRepaint(editor);
3173 if (changedSettings & settings & ECO_VERTICAL)
3174 FIXME("ECO_VERTICAL not implemented yet!\n");
3175 if (changedSettings & settings & ECO_AUTOHSCROLL)
3176 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3177 if (changedSettings & settings & ECO_AUTOVSCROLL)
3178 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3179 if (changedSettings & settings & ECO_NOHIDESEL)
3180 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3181 if (changedSettings & settings & ECO_WANTRETURN)
3182 FIXME("ECO_WANTRETURN not implemented yet!\n");
3183 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3184 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3191 ME_InvalidateSelection(editor);
3192 ME_SetSelection(editor, wParam, lParam);
3193 ME_InvalidateSelection(editor);
3194 ITextHost_TxShowCaret(editor->texthost, FALSE);
3195 ME_ShowCaret(editor);
3196 ME_SendSelChange(editor);
3199 case EM_SETSCROLLPOS:
3201 POINT *point = (POINT *)lParam;
3202 ME_ScrollAbs(editor, point->x, point->y);
3205 case EM_AUTOURLDETECT:
3207 if (wParam==1 || wParam ==0)
3209 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3212 return E_INVALIDARG;
3214 case EM_GETAUTOURLDETECT:
3216 return editor->AutoURLDetect_bEnable;
3221 CHARRANGE range = *(CHARRANGE *)lParam;
3223 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3225 ME_InvalidateSelection(editor);
3226 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3227 ME_InvalidateSelection(editor);
3228 ITextHost_TxShowCaret(editor->texthost, FALSE);
3229 ME_ShowCaret(editor);
3230 ME_SendSelChange(editor);
3234 case EM_SHOWSCROLLBAR:
3247 flags = WS_HSCROLL|WS_VSCROLL;
3254 editor->styleFlags |= flags;
3255 if (flags & WS_HSCROLL)
3256 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3257 editor->nTotalWidth > editor->sizeWindow.cx);
3258 if (flags & WS_VSCROLL)
3259 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3260 editor->nTotalLength > editor->sizeWindow.cy);
3262 editor->styleFlags &= ~flags;
3263 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3270 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3274 BOOL bRtf, bUnicode, bSelection;
3275 int oldModify = editor->nModifyStep;
3277 if (!pStruct) return 0;
3279 /* If we detect ascii rtf at the start of the string,
3280 * we know it isn't unicode. */
3281 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3282 !strncmp((char *)lParam, "{\\urtf", 6)));
3283 bUnicode = !bRtf && pStruct->codepage == 1200;
3285 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3286 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3287 pStruct->flags, pStruct->codepage);
3289 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3291 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3292 style = ME_GetSelectionInsertStyle(editor);
3293 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3296 ME_SetCursorToStart(editor, &start);
3297 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3298 style = editor->pBuffer->pDefaultStyle;
3302 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3304 /* FIXME: The length returned doesn't include the rtf control
3305 * characters, only the actual text. */
3306 len = lParam ? strlen((char *)lParam) : 0;
3309 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3310 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3311 len = wszText ? lstrlenW(wszText) : 0;
3312 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3313 ME_EndToUnicode(bUnicode, wszText);
3317 ME_ReleaseStyle(style);
3318 ME_UpdateSelectionLinkAttribute(editor);
3322 ME_SetCursorToStart(editor, &cursor);
3323 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3325 ME_CommitUndo(editor);
3326 if (!(pStruct->flags & ST_KEEPUNDO))
3328 editor->nModifyStep = oldModify;
3329 ME_EmptyUndoStack(editor);
3331 ME_UpdateRepaint(editor, FALSE);
3334 case EM_SETBKGNDCOLOR:
3337 if (editor->rgbBackColor != -1) {
3338 DeleteObject(editor->hbrBackground);
3339 lColor = editor->rgbBackColor;
3341 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3345 editor->rgbBackColor = -1;
3346 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3350 editor->rgbBackColor = lParam;
3351 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3353 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3354 ITextHost_TxViewChange(editor->texthost, TRUE);
3358 return editor->nModifyStep == 0 ? 0 : -1;
3362 editor->nModifyStep = 1;
3364 editor->nModifyStep = 0;
3368 case EM_SETREADONLY:
3371 editor->styleFlags |= ES_READONLY;
3373 editor->styleFlags &= ~ES_READONLY;
3376 case EM_SETEVENTMASK:
3378 DWORD nOldMask = editor->nEventMask;
3380 editor->nEventMask = lParam;
3383 case EM_GETEVENTMASK:
3384 return editor->nEventMask;
3385 case EM_SETCHARFORMAT:
3387 CHARFORMAT2W buf, *p;
3388 BOOL bRepaint = TRUE;
3389 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3390 if (p == NULL) return 0;
3391 if (wParam & SCF_ALL) {
3392 if (editor->mode & TM_PLAINTEXT) {
3393 ME_SetDefaultCharFormat(editor, p);
3396 ME_SetCursorToStart(editor, &start);
3397 ME_SetCharFormat(editor, &start, NULL, p);
3398 editor->nModifyStep = 1;
3400 } else if (wParam & SCF_SELECTION) {
3401 if (editor->mode & TM_PLAINTEXT)
3403 if (wParam & SCF_WORD) {
3404 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3407 bRepaint = ME_IsSelection(editor);
3408 ME_SetSelectionCharFormat(editor, p);
3409 if (bRepaint) editor->nModifyStep = 1;
3410 } else { /* SCF_DEFAULT */
3411 ME_SetDefaultCharFormat(editor, p);
3413 ME_CommitUndo(editor);
3416 ME_WrapMarkedParagraphs(editor);
3417 ME_UpdateScrollBar(editor);
3422 case EM_GETCHARFORMAT:
3424 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3425 if (dst->cbSize != sizeof(CHARFORMATA) &&
3426 dst->cbSize != sizeof(CHARFORMATW) &&
3427 dst->cbSize != sizeof(CHARFORMAT2A) &&
3428 dst->cbSize != sizeof(CHARFORMAT2W))
3430 tmp.cbSize = sizeof(tmp);
3432 ME_GetDefaultCharFormat(editor, &tmp);
3434 ME_GetSelectionCharFormat(editor, &tmp);
3435 ME_CopyToCFAny(dst, &tmp);
3438 case EM_SETPARAFORMAT:
3440 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3441 ME_WrapMarkedParagraphs(editor);
3442 ME_UpdateScrollBar(editor);
3444 ME_CommitUndo(editor);
3447 case EM_GETPARAFORMAT:
3448 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3449 return ((PARAFORMAT2 *)lParam)->dwMask;
3450 case EM_GETFIRSTVISIBLELINE:
3452 ME_DisplayItem *p = editor->pBuffer->pFirst;
3453 int y = editor->vert_si.nPos;
3458 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3459 if (p->type == diTextEnd)
3461 if (p->type == diParagraph) {
3462 ypara = p->member.para.pt.y;
3465 ystart = ypara + p->member.row.pt.y;
3466 yend = ystart + p->member.row.nHeight;
3474 case EM_HIDESELECTION:
3476 editor->bHideSelection = (wParam != 0);
3477 ME_InvalidateSelection(editor);
3482 if (!(editor->styleFlags & ES_MULTILINE))
3484 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3490 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3491 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3492 ME_CommitUndo(editor);
3493 ME_UpdateRepaint(editor, TRUE);
3498 int from, to, nStartCursor;
3500 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3501 size_t len = wszText ? lstrlenW(wszText) : 0;
3502 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3504 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3505 style = ME_GetSelectionInsertStyle(editor);
3506 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3507 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3508 ME_ReleaseStyle(style);
3509 /* drop temporary style if line end */
3511 * FIXME question: does abc\n mean: put abc,
3512 * clear temp style, put \n? (would require a change)
3514 if (len>0 && wszText[len-1] == '\n')
3515 ME_ClearTempStyle(editor);
3516 ME_EndToUnicode(unicode, wszText);
3517 ME_CommitUndo(editor);
3518 ME_UpdateSelectionLinkAttribute(editor);
3520 ME_EmptyUndoStack(editor);
3521 ME_UpdateRepaint(editor, FALSE);
3524 case EM_SCROLLCARET:
3525 ME_EnsureVisible(editor, &editor->pCursors[0]);
3532 BOOL bRepaint = LOWORD(lParam);
3535 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3536 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3537 hDC = ITextHost_TxGetDC(editor->texthost);
3538 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3539 ITextHost_TxReleaseDC(editor->texthost, hDC);
3540 if (editor->mode & TM_RICHTEXT) {
3542 ME_SetCursorToStart(editor, &start);
3543 ME_SetCharFormat(editor, &start, NULL, &fmt);
3545 ME_SetDefaultCharFormat(editor, &fmt);
3547 ME_CommitUndo(editor);
3548 ME_MarkAllForWrapping(editor);
3549 ME_WrapMarkedParagraphs(editor);
3550 ME_UpdateScrollBar(editor);
3558 ME_SetCursorToStart(editor, &cursor);
3559 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3562 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3563 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3564 !strncmp((char *)lParam, "{\\urtf", 6))
3566 /* Undocumented: WM_SETTEXT supports RTF text */
3567 ME_StreamInRTFString(editor, 0, (char *)lParam);
3571 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3572 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3573 if (lstrlenW(wszText) > 0)
3577 /* uses default style! */
3578 if (!(editor->styleFlags & ES_MULTILINE))
3583 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3586 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3588 ME_EndToUnicode(unicode, wszText);
3592 TRACE("WM_SETTEXT - NULL\n");
3593 ME_SetCursorToStart(editor, &cursor);
3594 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3595 ME_SetSelection(editor, 0, 0);
3596 editor->nModifyStep = 0;
3597 ME_CommitUndo(editor);
3598 ME_EmptyUndoStack(editor);
3599 ME_UpdateRepaint(editor, FALSE);
3604 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3605 if (IsClipboardFormatAvailable(nRTFFormat))
3607 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3612 case WM_MBUTTONDOWN:
3618 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3619 int nChars = nTo - nFrom;
3620 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3622 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3624 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3625 ME_CommitUndo(editor);
3626 ME_UpdateRepaint(editor, TRUE);
3630 case WM_GETTEXTLENGTH:
3632 GETTEXTLENGTHEX how;
3634 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3635 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3636 how.codepage = unicode ? 1200 : CP_ACP;
3637 return ME_GetTextLengthEx(editor, &how);
3639 case EM_GETTEXTLENGTHEX:
3640 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3644 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3645 ex.flags = GT_USECRLF;
3646 ex.codepage = unicode ? 1200 : CP_ACP;
3647 ex.lpDefaultChar = NULL;
3648 ex.lpUsedDefChar = NULL;
3649 return ME_GetTextEx(editor, &ex, lParam);
3652 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3655 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3656 ME_Cursor *from = &editor->pCursors[nStartCur];
3657 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3658 nTo - nFrom, unicode);
3660 case EM_GETSCROLLPOS:
3662 POINT *point = (POINT *)lParam;
3663 point->x = editor->horz_si.nPos;
3664 point->y = editor->vert_si.nPos;
3665 /* 16-bit scaled value is returned as stored in scrollinfo */
3666 if (editor->horz_si.nMax > 0xffff)
3667 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3668 if (editor->vert_si.nMax > 0xffff)
3669 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3672 case EM_GETTEXTRANGE:
3674 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3676 int nStart = rng->chrg.cpMin;
3677 int nEnd = rng->chrg.cpMax;
3678 int textlength = ME_GetTextLength(editor);
3680 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3681 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3682 if (nStart < 0) return 0;
3683 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3685 if (nStart >= nEnd) return 0;
3687 ME_CursorFromCharOfs(editor, nStart, &start);
3688 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3692 ME_DisplayItem *run;
3693 const unsigned int nMaxChars = *(WORD *) lParam;
3694 unsigned int nCharsLeft = nMaxChars;
3695 char *dest = (char *) lParam;
3696 BOOL wroteNull = FALSE;
3698 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3699 unicode ? "Unicode" : "Ansi");
3701 run = ME_FindRowWithNumber(editor, wParam);
3705 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3706 && run->type == diRun)
3708 WCHAR *str = get_text( &run->member.run, 0 );
3711 nCopy = min(nCharsLeft, run->member.run.len);
3714 memcpy(dest, str, nCopy * sizeof(WCHAR));
3716 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3717 nCharsLeft, NULL, NULL);
3718 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3719 nCharsLeft -= nCopy;
3722 /* append line termination, space allowing */
3726 *((WCHAR *)dest) = '\0';
3733 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3734 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3736 case EM_GETLINECOUNT:
3738 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3741 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3743 while (item != editor->pBuffer->pLast)
3745 assert(item->type == diParagraph);
3746 prev_para = ME_FindItemBack(item, diRun);
3748 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3750 nRows += item->member.para.nRows;
3751 item = item->member.para.next_para;
3753 last_para = ME_FindItemBack(item, diRun);
3755 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3756 if (editor->bEmulateVersion10 && prev_para &&
3757 last_para->member.run.nCharOfs == 0 &&
3758 prev_para->member.run.len == 1 &&
3759 *get_text( &prev_para->member.run, 0 ) == '\r')
3761 /* In 1.0 emulation, the last solitary \r at the very end of the text
3762 (if one exists) is NOT a line break.
3763 FIXME: this is an ugly hack. This should have a more regular model. */
3767 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3768 return max(1, nRows);
3770 case EM_LINEFROMCHAR:
3773 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3775 return ME_RowNumberFromCharOfs(editor, wParam);
3777 case EM_EXLINEFROMCHAR:
3780 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3782 return ME_RowNumberFromCharOfs(editor, lParam);
3786 ME_DisplayItem *item, *para;
3790 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3792 item = ME_FindRowWithNumber(editor, wParam);
3795 para = ME_GetParagraph(item);
3796 item = ME_FindItemFwd(item, diRun);
3797 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3798 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3803 ME_DisplayItem *item, *item_end;
3804 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3805 ME_DisplayItem *para, *run;
3807 if (wParam > ME_GetTextLength(editor))
3811 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3814 ME_RunOfsFromCharOfs(editor, wParam, ¶, &run, NULL);
3815 item = ME_RowStart(run);
3816 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3817 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3818 if (item_end->type == diStartRow) {
3819 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3821 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3822 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3823 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3825 nChars = nNextLineOfs - nThisLineOfs;
3826 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3829 case EM_EXLIMITTEXT:
3831 if ((int)lParam < 0)
3834 editor->nTextLimit = 65536;
3836 editor->nTextLimit = (int) lParam;
3842 editor->nTextLimit = 65536;
3844 editor->nTextLimit = (int) wParam;
3847 case EM_GETLIMITTEXT:
3849 return editor->nTextLimit;
3853 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3854 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3858 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3859 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3860 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3866 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3867 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3871 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3872 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3873 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3879 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3880 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3882 case EM_FINDTEXTEXW:
3884 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3885 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3888 if (!wParam || !lParam)
3890 *(int *)wParam = editor->nZoomNumerator;
3891 *(int *)lParam = editor->nZoomDenominator;
3894 return ME_SetZoom(editor, wParam, lParam);
3895 case EM_CHARFROMPOS:
3898 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3900 return ME_GetCursorOfs(&cursor);
3904 case EM_POSFROMCHAR:
3906 ME_DisplayItem *pPara, *pRun;
3907 int nCharOfs, nOffset, nLength;
3911 /* detect which API version we're dealing with */
3912 if (wParam >= 0x40000)
3914 nLength = ME_GetTextLength(editor);
3915 nCharOfs = min(nCharOfs, nLength);
3916 nCharOfs = max(nCharOfs, 0);
3918 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3919 assert(pRun->type == diRun);
3920 pt.y = pRun->member.run.pt.y;
3921 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3922 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3923 pt.x += editor->rcFormat.left;
3925 pt.x -= editor->horz_si.nPos;
3926 pt.y -= editor->vert_si.nPos;
3928 if (wParam >= 0x40000) {
3929 *(POINTL *)wParam = pt;
3931 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3937 ME_SetDefaultFormatRect(editor);
3939 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3940 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3941 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3943 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3944 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3946 if (editor->styleFlags & ES_DISABLENOSCROLL)
3948 if (editor->styleFlags & WS_VSCROLL)
3950 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3951 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3953 if (editor->styleFlags & WS_HSCROLL)
3955 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3956 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3960 ME_CommitUndo(editor);
3961 ME_WrapMarkedParagraphs(editor);
3962 ME_MoveCaret(editor);
3966 ME_DestroyEditor(editor);
3970 return ME_SetCursor(editor);
3972 case WM_LBUTTONDBLCLK:
3973 case WM_LBUTTONDOWN:
3975 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3976 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3977 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3979 ITextHost_TxSetFocus(editor->texthost);
3980 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3981 ME_CalculateClickCount(editor, msg, wParam, lParam));
3982 ITextHost_TxSetCapture(editor->texthost, TRUE);
3983 editor->bMouseCaptured = TRUE;
3984 ME_LinkNotify(editor,msg,wParam,lParam);
3985 if (!ME_SetCursor(editor)) goto do_default;
3989 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3990 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3992 if (editor->bMouseCaptured)
3993 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3994 ME_LinkNotify(editor,msg,wParam,lParam);
3995 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3996 if (editor->bMouseCaptured)
3997 ME_SetCursor(editor);
4000 if (editor->bMouseCaptured) {
4001 ITextHost_TxSetCapture(editor->texthost, FALSE);
4002 editor->bMouseCaptured = FALSE;
4004 if (editor->nSelectionType == stDocument)
4005 editor->nSelectionType = stPosition;
4006 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4007 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4011 ME_SetCursor(editor);
4012 ME_LinkNotify(editor,msg,wParam,lParam);
4016 case WM_RBUTTONDOWN:
4017 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4018 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4019 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4022 case WM_CONTEXTMENU:
4023 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4027 editor->bHaveFocus = TRUE;
4028 ME_ShowCaret(editor);
4029 ME_SendOldNotify(editor, EN_SETFOCUS);
4032 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4033 editor->bHaveFocus = FALSE;
4034 ME_HideCaret(editor);
4035 ME_SendOldNotify(editor, EN_KILLFOCUS);
4038 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4041 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4042 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4046 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4047 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4049 if (ME_KeyDown(editor, LOWORD(wParam)))
4053 return ME_Char(editor, wParam, lParam, unicode);
4057 if(wParam == UNICODE_NOCHAR) return TRUE;
4058 if(wParam <= 0x000fffff)
4060 if(wParam > 0xffff) /* convert to surrogates */
4063 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4064 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4066 ME_Char(editor, wParam, 0, TRUE);
4072 case EM_STOPGROUPTYPING:
4073 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4077 const int scrollUnit = 7;
4079 switch(LOWORD(wParam))
4082 ME_ScrollAbs(editor, 0, 0);
4085 ME_ScrollAbs(editor,
4086 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4087 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4090 ME_ScrollLeft(editor, scrollUnit);
4093 ME_ScrollRight(editor, scrollUnit);
4096 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4099 ME_ScrollRight(editor, editor->sizeWindow.cx);
4102 case SB_THUMBPOSITION:
4104 int pos = HIWORD(wParam);
4105 if (editor->horz_si.nMax > 0xffff)
4106 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4107 ME_HScrollAbs(editor, pos);
4113 case EM_SCROLL: /* fall through */
4119 origNPos = editor->vert_si.nPos;
4122 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4123 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4124 if (lineHeight <= 0) lineHeight = 24;
4126 switch(LOWORD(wParam))
4129 ME_ScrollAbs(editor, 0, 0);
4132 ME_ScrollAbs(editor,
4133 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4134 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4137 ME_ScrollUp(editor,lineHeight);
4140 ME_ScrollDown(editor,lineHeight);
4143 ME_ScrollUp(editor,editor->sizeWindow.cy);
4146 ME_ScrollDown(editor,editor->sizeWindow.cy);
4149 case SB_THUMBPOSITION:
4151 int pos = HIWORD(wParam);
4152 if (editor->vert_si.nMax > 0xffff)
4153 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4154 ME_VScrollAbs(editor, pos);
4158 if (msg == EM_SCROLL)
4159 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4165 UINT pulScrollLines;
4168 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4169 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4172 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4174 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4176 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4180 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4184 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4186 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4187 if (numerator >= 10 && numerator <= 500)
4188 ME_SetZoom(editor, numerator, 100);
4190 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4191 /* FIXME follow the original */
4193 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4200 *((RECT *)lParam) = editor->rcFormat;
4201 if (editor->bDefaultFormatRect)
4202 ((RECT *)lParam)->left -= editor->selofs;
4212 RECT *rc = (RECT *)lParam;
4214 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4215 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4218 editor->rcFormat.top = max(0, rc->top - border);
4219 editor->rcFormat.left = max(0, rc->left - border);
4220 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4221 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4222 } else if (wParam == 1) {
4223 /* MSDN incorrectly says a wParam value of 1 causes the
4224 * lParam rect to be used as a relative offset,
4225 * however, the tests show it just prevents min/max bound
4227 editor->rcFormat.top = rc->top - border;
4228 editor->rcFormat.left = rc->left - border;
4229 editor->rcFormat.bottom = rc->bottom;
4230 editor->rcFormat.right = rc->right + border;
4234 editor->bDefaultFormatRect = FALSE;
4238 ME_SetDefaultFormatRect(editor);
4239 editor->bDefaultFormatRect = TRUE;
4241 ME_MarkAllForWrapping(editor);
4242 ME_WrapMarkedParagraphs(editor);
4243 ME_UpdateScrollBar(editor);
4244 if (msg != EM_SETRECTNP)
4248 case EM_REQUESTRESIZE:
4249 ME_SendRequestResize(editor, TRUE);
4257 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4258 if (editor->bDefaultFormatRect) {
4259 ME_SetDefaultFormatRect(editor);
4261 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4262 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4264 editor->prevClientRect = clientRect;
4265 ME_RewrapRepaint(editor);
4268 /* IME messages to make richedit controls IME aware */
4269 case WM_IME_SETCONTEXT:
4270 case WM_IME_CONTROL:
4272 case WM_IME_COMPOSITIONFULL:
4274 case WM_IME_STARTCOMPOSITION:
4276 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4277 ME_DeleteSelection(editor);
4278 ME_CommitUndo(editor);
4279 ME_UpdateRepaint(editor, FALSE);
4282 case WM_IME_COMPOSITION:
4286 ME_Style *style = ME_GetInsertStyle(editor, 0);
4287 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4288 ME_DeleteSelection(editor);
4289 ME_SaveTempStyle(editor);
4290 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4292 LPWSTR lpCompStr = NULL;
4294 DWORD dwIndex = lParam & GCS_RESULTSTR;
4296 dwIndex = GCS_COMPSTR;
4298 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4299 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4300 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4301 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4302 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4303 HeapFree(GetProcessHeap(), 0, lpCompStr);
4305 if (dwIndex == GCS_COMPSTR)
4306 ME_SetSelection(editor,editor->imeStartIndex,
4307 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4309 ME_ReleaseStyle(style);
4310 ME_CommitUndo(editor);
4311 ME_UpdateRepaint(editor, FALSE);
4314 case WM_IME_ENDCOMPOSITION:
4316 ME_DeleteSelection(editor);
4317 editor->imeStartIndex=-1;
4320 case EM_GETOLEINTERFACE:
4322 LPVOID *ppvObj = (LPVOID*) lParam;
4323 return CreateIRichEditOle(editor, ppvObj);
4325 case EM_GETPASSWORDCHAR:
4327 return editor->cPasswordMask;
4329 case EM_SETOLECALLBACK:
4330 if(editor->lpOleCallback)
4331 IRichEditOleCallback_Release(editor->lpOleCallback);
4332 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4333 if(editor->lpOleCallback)
4334 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4336 case EM_GETWORDBREAKPROC:
4337 return (LRESULT)editor->pfnWordBreak;
4338 case EM_SETWORDBREAKPROC:
4340 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4342 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4343 return (LRESULT)pfnOld;
4345 case EM_GETTEXTMODE:
4346 return editor->mode;
4347 case EM_SETTEXTMODE:
4352 if (ME_GetTextLength(editor) ||
4353 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4354 return E_UNEXPECTED;
4356 /* Check for mutually exclusive flags in adjacent bits of wParam */
4357 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4358 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4359 return E_INVALIDARG;
4361 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4363 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4364 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4365 if (wParam & TM_PLAINTEXT) {
4366 /* Clear selection since it should be possible to select the
4367 * end of text run for rich text */
4368 ME_InvalidateSelection(editor);
4369 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4370 editor->pCursors[1] = editor->pCursors[0];
4371 /* plain text can only have the default style. */
4372 ME_ClearTempStyle(editor);
4373 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4374 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4375 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4378 /* FIXME: Currently no support for undo level and code page options */
4379 editor->mode = (editor->mode & ~mask) | changes;
4382 case EM_SETPASSWORDCHAR:
4384 editor->cPasswordMask = wParam;
4385 ME_RewrapRepaint(editor);
4388 case EM_SETTARGETDEVICE:
4391 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4392 if (editor->nAvailWidth || editor->bWordWrap != new)
4394 editor->bWordWrap = new;
4395 editor->nAvailWidth = 0; /* wrap to client area */
4396 ME_RewrapRepaint(editor);
4399 int width = max(0, lParam);
4400 if ((editor->styleFlags & ES_MULTILINE) &&
4401 (!editor->bWordWrap || editor->nAvailWidth != width))
4403 editor->nAvailWidth = width;
4404 editor->bWordWrap = TRUE;
4405 ME_RewrapRepaint(editor);
4407 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4412 *phresult = S_FALSE;
4418 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4419 LPARAM lParam, BOOL unicode)
4421 ME_TextEditor *editor;
4423 LRESULT lresult = 0;
4425 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4426 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4428 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4431 if (msg == WM_NCCREATE)
4433 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4434 ITextHost *texthost;
4436 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4437 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4438 return texthost != NULL;
4442 return DefWindowProcW(hWnd, msg, wParam, lParam);
4454 hDC = BeginPaint(editor->hWnd, &ps);
4455 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4456 ME_SendOldNotify(editor, EN_UPDATE);
4457 /* Erase area outside of the formatting rectangle */
4458 if (ps.rcPaint.top < editor->rcFormat.top)
4461 rc.bottom = editor->rcFormat.top;
4462 FillRect(hDC, &rc, editor->hbrBackground);
4463 ps.rcPaint.top = editor->rcFormat.top;
4465 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4467 rc.top = editor->rcFormat.bottom;
4468 FillRect(hDC, &rc, editor->hbrBackground);
4469 ps.rcPaint.bottom = editor->rcFormat.bottom;
4471 if (ps.rcPaint.left < editor->rcFormat.left) {
4473 rc.right = editor->rcFormat.left;
4474 FillRect(hDC, &rc, editor->hbrBackground);
4475 ps.rcPaint.left = editor->rcFormat.left;
4477 if (ps.rcPaint.right > editor->rcFormat.right) {
4479 rc.left = editor->rcFormat.right;
4480 FillRect(hDC, &rc, editor->hbrBackground);
4481 ps.rcPaint.right = editor->rcFormat.right;
4484 ME_PaintContent(editor, hDC, &ps.rcPaint);
4485 EndPaint(editor->hWnd, &ps);
4490 HDC hDC = (HDC)wParam;
4493 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4494 FillRect(hDC, &rc, editor->hbrBackground);
4500 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4501 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4503 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4504 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4505 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4506 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4509 case EM_SETREADONLY:
4512 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4513 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4514 dwStyle &= ~ES_READONLY;
4516 dwStyle |= ES_READONLY;
4517 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4521 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4524 if (hresult == S_FALSE)
4525 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4527 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4528 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4533 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4535 BOOL unicode = TRUE;
4537 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4538 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4541 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4544 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4546 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4549 /******************************************************************
4550 * RichEditANSIWndProc (RICHED20.10)
4552 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4554 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4557 /******************************************************************
4558 * RichEdit10ANSIWndProc (RICHED20.9)
4560 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4562 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4564 ITextHost *texthost;
4565 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4567 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4568 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4569 return texthost != NULL;
4571 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4574 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4576 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4579 /* Fill buffer with srcChars unicode characters from the start cursor.
4581 * buffer: destination buffer
4582 * buflen: length of buffer in characters excluding the NULL terminator.
4583 * start: start of editor text to copy into buffer.
4584 * srcChars: Number of characters to use from the editor text.
4585 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4587 * returns the number of characters written excluding the NULL terminator.
4589 * The written text is always NULL terminated.
4591 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4592 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4594 ME_DisplayItem *pRun, *pNextRun;
4595 const WCHAR *pStart = buffer;
4596 const WCHAR cr_lf[] = {'\r', '\n', 0};
4600 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4601 if (editor->bEmulateVersion10) bCRLF = 0;
4605 pNextRun = ME_FindItemFwd(pRun, diRun);
4607 nLen = pRun->member.run.len - start->nOffset;
4608 str = get_text( &pRun->member.run, start->nOffset );
4610 /* No '\r' is appended to the last paragraph. */
4611 while (srcChars && buflen && pNextRun)
4613 int nFlags = pRun->member.run.nFlags;
4615 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4617 if (buflen == 1) break;
4618 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4619 * EM_GETTEXTEX, however, this is done for copying text which
4620 * also uses this function. */
4621 srcChars -= min(nLen, srcChars);
4625 nLen = min(nLen, srcChars);
4629 nLen = min(nLen, buflen);
4632 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4637 pNextRun = ME_FindItemFwd(pRun, diRun);
4639 nLen = pRun->member.run.len;
4640 str = get_text( &pRun->member.run, 0 );
4643 return buffer - pStart;
4646 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4651 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4652 wcW.lpfnWndProc = RichEditWndProcW;
4654 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4655 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4657 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4658 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4659 wcW.lpszMenuName = NULL;
4661 if (is_version_nt())
4663 wcW.lpszClassName = RICHEDIT_CLASS20W;
4664 if (!RegisterClassW(&wcW)) return FALSE;
4665 wcW.lpszClassName = MSFTEDIT_CLASS;
4666 if (!RegisterClassW(&wcW)) return FALSE;
4670 /* WNDCLASSA/W have the same layout */
4671 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4672 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4673 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4674 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4677 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4678 wcA.lpfnWndProc = RichEditWndProcA;
4680 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4681 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4683 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4684 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4685 wcA.lpszMenuName = NULL;
4686 wcA.lpszClassName = RICHEDIT_CLASS20A;
4687 if (!RegisterClassA(&wcA)) return FALSE;
4688 wcA.lpszClassName = "RichEdit50A";
4689 if (!RegisterClassA(&wcA)) return FALSE;
4694 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4695 /* FIXME: Not implemented */
4696 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4697 hWnd, msg, get_msg_name(msg), wParam, lParam);
4698 return DefWindowProcW(hWnd, msg, wParam, lParam);
4701 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4702 /* FIXME: Not implemented */
4703 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4704 hWnd, msg, get_msg_name(msg), wParam, lParam);
4705 return DefWindowProcW(hWnd, msg, wParam, lParam);
4708 /******************************************************************
4709 * REExtendedRegisterClass (RICHED20.8)
4711 * FIXME undocumented
4712 * Need to check for errors and implement controls and callbacks
4714 LRESULT WINAPI REExtendedRegisterClass(void)
4719 FIXME("semi stub\n");
4723 wcW.hInstance = NULL;
4726 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4727 wcW.lpszMenuName = NULL;
4729 if (!ME_ListBoxRegistered)
4731 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4732 wcW.lpfnWndProc = REListWndProc;
4733 wcW.lpszClassName = REListBox20W;
4734 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4737 if (!ME_ComboBoxRegistered)
4739 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4740 wcW.lpfnWndProc = REComboWndProc;
4741 wcW.lpszClassName = REComboBox20W;
4742 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4746 if (ME_ListBoxRegistered)
4748 if (ME_ComboBoxRegistered)
4754 static BOOL isurlspecial(WCHAR c)
4756 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4757 return strchrW( special_chars, c ) != NULL;
4761 * This proc takes a selection, and scans it forward in order to select the span
4762 * of a possible URL candidate. A possible URL candidate must start with isalnum
4763 * or one of the following special characters: *|/\+%#@ and must consist entirely
4764 * of the characters allowed to start the URL, plus : (colon) which may occur
4765 * at most once, and not at either end.
4767 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4768 const ME_Cursor *start,
4770 ME_Cursor *candidate_min,
4771 ME_Cursor *candidate_max)
4773 ME_Cursor cursor = *start;
4774 BOOL foundColon = FALSE;
4775 BOOL candidateStarted = FALSE;
4776 WCHAR lastAcceptedChar = '\0';
4780 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4781 WCHAR *str = strStart + cursor.nOffset;
4782 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4785 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4787 /* Find start of candidate */
4788 if (!candidateStarted)
4793 if (isalnumW(*str) || isurlspecial(*str))
4795 cursor.nOffset = str - strStart;
4796 *candidate_min = cursor;
4797 candidateStarted = TRUE;
4798 lastAcceptedChar = *str++;
4805 /* Find end of candidate */
4806 if (candidateStarted) {
4810 if (*str == ':' && !foundColon) {
4812 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4813 cursor.nOffset = str - strStart;
4814 if (lastAcceptedChar == ':')
4815 ME_MoveCursorChars(editor, &cursor, -1);
4816 *candidate_max = cursor;
4819 lastAcceptedChar = *str++;
4823 /* End of paragraph: skip it if before candidate span, or terminates
4824 current active span */
4825 if (candidateStarted) {
4826 if (lastAcceptedChar == ':')
4827 ME_MoveCursorChars(editor, &cursor, -1);
4828 *candidate_max = cursor;
4833 /* Reaching this point means no span was found, so get next span */
4834 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4835 if (candidateStarted) {
4836 /* There are no further runs, so take end of text as end of candidate */
4837 cursor.nOffset = str - strStart;
4838 if (lastAcceptedChar == ':')
4839 ME_MoveCursorChars(editor, &cursor, -1);
4840 *candidate_max = cursor;
4843 *candidate_max = *candidate_min = cursor;
4849 if (candidateStarted) {
4850 /* There are no further runs, so take end of text as end of candidate */
4851 if (lastAcceptedChar == ':')
4852 ME_MoveCursorChars(editor, &cursor, -1);
4853 *candidate_max = cursor;
4856 *candidate_max = *candidate_min = cursor;
4861 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4863 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4865 #define MAX_PREFIX_LEN 9
4867 const WCHAR text[MAX_PREFIX_LEN];
4870 {{'p','r','o','s','p','e','r','o',':'}, 9},
4871 {{'t','e','l','n','e','t',':'}, 7},
4872 {{'g','o','p','h','e','r',':'}, 7},
4873 {{'m','a','i','l','t','o',':'}, 7},
4874 {{'h','t','t','p','s',':'}, 6},
4875 {{'f','i','l','e',':'}, 5},
4876 {{'n','e','w','s',':'}, 5},
4877 {{'w','a','i','s',':'}, 5},
4878 {{'n','n','t','p',':'}, 5},
4879 {{'h','t','t','p',':'}, 5},
4880 {{'w','w','w','.'}, 4},
4881 {{'f','t','p',':'}, 4},
4883 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4886 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4887 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4889 if (nChars < prefixes[i].length) continue;
4890 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4894 #undef MAX_PREFIX_LEN
4898 * This proc walks through the indicated selection and evaluates whether each
4899 * section identified by ME_FindNextURLCandidate and in-between sections have
4900 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4901 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4903 * Since this function can cause runs to be split, do not depend on the value
4904 * of the start cursor at the end of the function.
4906 * nChars may be set to INT_MAX to update to the end of the text.
4908 * Returns TRUE if at least one section was modified.
4910 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4912 BOOL modified = FALSE;
4913 ME_Cursor startCur = *start;
4915 if (!editor->AutoURLDetect_bEnable) return FALSE;
4920 ME_Cursor candidateStart, candidateEnd;
4922 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4923 &candidateStart, &candidateEnd))
4925 /* Section before candidate is not an URL */
4926 int cMin = ME_GetCursorOfs(&candidateStart);
4927 int cMax = ME_GetCursorOfs(&candidateEnd);
4929 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4930 candidateStart = candidateEnd;
4931 nChars -= cMax - ME_GetCursorOfs(&startCur);
4935 /* No more candidates until end of selection */
4939 if (startCur.pRun != candidateStart.pRun ||
4940 startCur.nOffset != candidateStart.nOffset)
4942 /* CFE_LINK effect should be consistently unset */
4943 link.cbSize = sizeof(link);
4944 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4945 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4947 /* CFE_LINK must be unset from this range */
4948 memset(&link, 0, sizeof(CHARFORMAT2W));
4949 link.cbSize = sizeof(link);
4950 link.dwMask = CFM_LINK;
4952 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4953 /* Update candidateEnd since setting character formats may split
4954 * runs, which can cause a cursor to be at an invalid offset within
4956 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
4958 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
4959 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4964 if (candidateStart.pRun != candidateEnd.pRun ||
4965 candidateStart.nOffset != candidateEnd.nOffset)
4967 /* CFE_LINK effect should be consistently set */
4968 link.cbSize = sizeof(link);
4969 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4970 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4972 /* CFE_LINK must be set on this range */
4973 memset(&link, 0, sizeof(CHARFORMAT2W));
4974 link.cbSize = sizeof(link);
4975 link.dwMask = CFM_LINK;
4976 link.dwEffects = CFE_LINK;
4977 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4981 startCur = candidateEnd;
4982 } while (nChars > 0);