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;
844 fmt.dwMask = PFM_RTLPARA;
845 fmt.wEffects = PFE_RTLPARA;
848 fmt.dwMask = PFM_RTLPARA;
853 RTFFlushOutputBuffer(info);
854 /* FIXME too slow ? how come ?*/
855 ME_SetSelectionParaFormat(info->editor, &fmt);
859 void ME_RTFTblAttrHook(RTF_Info *info)
861 switch (info->rtfMinor)
865 if (!info->editor->bEmulateVersion10) /* v4.1 */
866 info->borderType = 0; /* Not sure */
867 else /* v1.0 - 3.0 */
868 info->borderType = RTFBorderRowTop;
869 if (!info->tableDef) {
870 info->tableDef = ME_MakeTableDef(info->editor);
872 ME_InitTableDef(info->editor, info->tableDef);
881 info->tableDef = ME_MakeTableDef(info->editor);
883 cellNum = info->tableDef->numCellsDefined;
884 if (cellNum >= MAX_TABLE_CELLS)
886 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
887 if (cellNum < MAX_TAB_STOPS) {
888 /* Tab stops were used to store cell positions before v4.1 but v4.1
889 * still seems to set the tabstops without using them. */
890 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
891 PARAFORMAT2 *pFmt = para->member.para.pFmt;
892 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
893 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
895 info->tableDef->numCellsDefined++;
899 info->borderType = RTFBorderRowTop;
902 info->borderType = RTFBorderRowLeft;
904 case rtfRowBordBottom:
905 info->borderType = RTFBorderRowBottom;
907 case rtfRowBordRight:
908 info->borderType = RTFBorderRowRight;
911 info->borderType = RTFBorderCellTop;
913 case rtfCellBordLeft:
914 info->borderType = RTFBorderCellLeft;
916 case rtfCellBordBottom:
917 info->borderType = RTFBorderCellBottom;
919 case rtfCellBordRight:
920 info->borderType = RTFBorderCellRight;
924 info->tableDef->gapH = info->rtfParam;
928 info->tableDef->leftEdge = info->rtfParam;
933 void ME_RTFSpecialCharHook(RTF_Info *info)
935 RTFTable *tableDef = info->tableDef;
936 switch (info->rtfMinor)
939 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
941 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
945 RTFFlushOutputBuffer(info);
946 if (!info->editor->bEmulateVersion10) { /* v4.1 */
947 if (tableDef->tableRowStart)
949 if (!info->nestingLevel &&
950 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
952 ME_DisplayItem *para = tableDef->tableRowStart;
953 para = para->member.para.next_para;
954 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
955 tableDef->tableRowStart = para;
956 info->nestingLevel = 1;
958 ME_InsertTableCellFromCursor(info->editor);
960 } else { /* v1.0 - v3.0 */
961 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
962 PARAFORMAT2 *pFmt = para->member.para.pFmt;
963 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
964 tableDef->numCellsInserted < tableDef->numCellsDefined)
967 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
968 tableDef->numCellsInserted++;
973 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
975 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
978 ME_DisplayItem *para, *cell, *run;
983 RTFFlushOutputBuffer(info);
984 if (!info->editor->bEmulateVersion10) { /* v4.1 */
985 if (!tableDef->tableRowStart)
987 if (!info->nestingLevel &&
988 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
990 para = tableDef->tableRowStart;
991 para = para->member.para.next_para;
992 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
993 tableDef->tableRowStart = para;
994 info->nestingLevel++;
996 para = tableDef->tableRowStart;
997 cell = ME_FindItemFwd(para, diCell);
998 assert(cell && !cell->member.cell.prev_cell);
999 if (tableDef->numCellsDefined < 1)
1001 /* 2000 twips appears to be the cell size that native richedit uses
1002 * when no cell sizes are specified. */
1003 const int defaultCellSize = 2000;
1004 int nRightBoundary = defaultCellSize;
1005 cell->member.cell.nRightBoundary = nRightBoundary;
1006 while (cell->member.cell.next_cell) {
1007 cell = cell->member.cell.next_cell;
1008 nRightBoundary += defaultCellSize;
1009 cell->member.cell.nRightBoundary = nRightBoundary;
1011 para = ME_InsertTableCellFromCursor(info->editor);
1012 cell = para->member.para.pCell;
1013 cell->member.cell.nRightBoundary = nRightBoundary;
1015 for (i = 0; i < tableDef->numCellsDefined; i++)
1017 RTFCell *cellDef = &tableDef->cells[i];
1018 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1019 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1021 cell = cell->member.cell.next_cell;
1024 para = ME_InsertTableCellFromCursor(info->editor);
1025 cell = para->member.para.pCell;
1028 /* Cell for table row delimiter is empty */
1029 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1032 run = ME_FindItemFwd(cell, diRun);
1033 if (info->editor->pCursors[0].pRun != run ||
1034 info->editor->pCursors[0].nOffset)
1037 /* Delete inserted cells that aren't defined. */
1038 info->editor->pCursors[1].pRun = run;
1039 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1040 info->editor->pCursors[1].nOffset = 0;
1041 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1042 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1043 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1047 para = ME_InsertTableRowEndFromCursor(info->editor);
1048 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1049 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1050 ME_ApplyBorderProperties(info, ¶->member.para.border,
1052 info->nestingLevel--;
1053 if (!info->nestingLevel)
1055 if (info->canInheritInTbl) {
1056 tableDef->tableRowStart = para;
1058 while (info->tableDef) {
1059 tableDef = info->tableDef;
1060 info->tableDef = tableDef->parent;
1061 heap_free(tableDef);
1065 info->tableDef = tableDef->parent;
1066 heap_free(tableDef);
1068 } else { /* v1.0 - v3.0 */
1070 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1071 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1072 pFmt->dxOffset = info->tableDef->gapH;
1073 pFmt->dxStartIndent = info->tableDef->leftEdge;
1075 ME_ApplyBorderProperties(info, ¶->member.para.border,
1077 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1080 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1081 tableDef->numCellsInserted++;
1083 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1084 if (!tableDef->numCellsDefined)
1085 pFmt->wEffects &= ~PFE_TABLE;
1086 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1087 tableDef->numCellsInserted = 0;
1093 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1094 ME_DisplayItem *para;
1096 RTFFlushOutputBuffer(info);
1097 para = info->editor->pCursors[0].pPara;
1098 pFmt = para->member.para.pFmt;
1099 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1101 /* rtfPar is treated like a space within a table. */
1102 info->rtfClass = rtfText;
1103 info->rtfMajor = ' ';
1105 else if (info->rtfMinor == rtfPar && tableDef)
1106 tableDef->numCellsInserted = 0;
1112 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1115 LPOLEOBJECT lpObject = NULL;
1116 LPSTORAGE lpStorage = NULL;
1117 LPOLECLIENTSITE lpClientSite = NULL;
1118 LPDATAOBJECT lpDataObject = NULL;
1119 LPOLECACHE lpOleCache = NULL;
1128 stgm.tymed = TYMED_ENHMF;
1129 stgm.u.hEnhMetaFile = hemf;
1130 fm.cfFormat = CF_ENHMETAFILE;
1134 stgm.tymed = TYMED_GDI;
1135 stgm.u.hBitmap = hbmp;
1136 fm.cfFormat = CF_BITMAP;
1138 stgm.pUnkForRelease = NULL;
1141 fm.dwAspect = DVASPECT_CONTENT;
1143 fm.tymed = stgm.tymed;
1145 if (!info->lpRichEditOle)
1147 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1150 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1152 /* FIXME: enable it when rich-edit properly implements this method */
1153 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1154 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1156 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1157 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1158 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1159 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1160 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1164 reobject.cbStruct = sizeof(reobject);
1165 reobject.cp = REO_CP_SELECTION;
1166 reobject.clsid = clsid;
1167 reobject.poleobj = lpObject;
1168 reobject.pstg = lpStorage;
1169 reobject.polesite = lpClientSite;
1170 /* convert from twips to .01 mm */
1171 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1172 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1173 reobject.dvaspect = DVASPECT_CONTENT;
1174 reobject.dwFlags = 0; /* FIXME */
1175 reobject.dwUser = 0;
1177 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1181 if (lpObject) IOleObject_Release(lpObject);
1182 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1183 if (lpStorage) IStorage_Release(lpStorage);
1184 if (lpDataObject) IDataObject_Release(lpDataObject);
1185 if (lpOleCache) IOleCache_Release(lpOleCache);
1190 static void ME_RTFReadPictGroup(RTF_Info *info)
1193 BYTE* buffer = NULL;
1194 unsigned bufsz, bufidx;
1200 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1203 if (info->rtfClass == rtfEOF)
1206 /* fetch picture type */
1207 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1209 mfp.mm = info->rtfParam;
1212 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1214 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1217 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1219 gfx = gfx_enhmetafile;
1223 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1227 /* fetch picture attributes */
1231 if (info->rtfClass == rtfEOF)
1233 if (info->rtfClass == rtfText)
1235 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1237 ERR("Expected picture attribute (%d %d)\n",
1238 info->rtfClass, info->rtfMajor);
1241 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1243 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1245 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1247 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1249 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1250 sz.cx = info->rtfParam;
1251 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1252 sz.cy = info->rtfParam;
1254 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1256 /* fetch picture data */
1259 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1260 val = info->rtfMajor;
1261 for (flip = TRUE;; flip = !flip)
1264 if (info->rtfClass == rtfEOF)
1266 HeapFree(GetProcessHeap(), 0, buffer);
1267 return; /* Warn ?? */
1269 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1271 if (info->rtfClass != rtfText) goto skip_group;
1274 if (bufidx >= bufsz &&
1275 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1277 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1280 val = info->rtfMajor;
1282 if (flip) FIXME("wrong hex string\n");
1286 case gfx_enhmetafile:
1287 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1288 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1291 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1292 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1296 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1298 unsigned nc = bi->bmiHeader.biClrUsed;
1300 /* not quite right, especially for bitfields type of compression */
1301 if (!nc && bi->bmiHeader.biBitCount <= 8)
1302 nc = 1 << bi->bmiHeader.biBitCount;
1303 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1304 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1305 bi, DIB_RGB_COLORS)))
1306 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1313 HeapFree(GetProcessHeap(), 0, buffer);
1314 RTFRouteToken (info); /* feed "}" back to router */
1317 HeapFree(GetProcessHeap(), 0, buffer);
1319 RTFRouteToken(info); /* feed "}" back to router */
1322 /* for now, lookup the \result part and use it, whatever the object */
1323 static void ME_RTFReadObjectGroup(RTF_Info *info)
1328 if (info->rtfClass == rtfEOF)
1330 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1332 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1335 if (info->rtfClass == rtfEOF)
1337 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1341 while (RTFGetToken (info) != rtfEOF)
1343 if (info->rtfClass == rtfGroup)
1345 if (info->rtfMajor == rtfBeginGroup) level++;
1346 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1348 RTFRouteToken(info);
1351 else RTFSkipGroup(info);
1354 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1356 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1360 RTFRouteToken(info); /* feed "}" back to router */
1363 static void ME_RTFReadHook(RTF_Info *info)
1365 switch(info->rtfClass)
1368 switch(info->rtfMajor)
1371 if (info->stackTop < maxStack) {
1372 info->stack[info->stackTop].style = info->style;
1373 ME_AddRefStyle(info->style);
1374 info->stack[info->stackTop].codePage = info->codePage;
1375 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1378 info->styleChanged = FALSE;
1382 RTFFlushOutputBuffer(info);
1384 if (info->stackTop <= 0)
1385 info->rtfClass = rtfEOF;
1386 if (info->stackTop < 0)
1389 ME_ReleaseStyle(info->style);
1390 info->style = info->stack[info->stackTop].style;
1391 info->codePage = info->stack[info->stackTop].codePage;
1392 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1401 ME_StreamInFill(ME_InStream *stream)
1403 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1404 (BYTE *)stream->buffer,
1405 sizeof(stream->buffer),
1406 (LONG *)&stream->dwSize);
1410 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1414 int from, to, nUndoMode;
1415 int nEventMask = editor->nEventMask;
1416 ME_InStream inStream;
1417 BOOL invalidRTF = FALSE;
1418 ME_Cursor *selStart, *selEnd;
1419 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1421 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1422 editor->nEventMask = 0;
1424 ME_GetSelectionOfs(editor, &from, &to);
1425 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1427 ME_GetSelection(editor, &selStart, &selEnd);
1428 style = ME_GetSelectionInsertStyle(editor);
1430 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1432 /* Don't insert text at the end of the table row */
1433 if (!editor->bEmulateVersion10) { /* v4.1 */
1434 ME_DisplayItem *para = editor->pCursors->pPara;
1435 if (para->member.para.nFlags & MEPF_ROWEND)
1437 para = para->member.para.next_para;
1438 editor->pCursors[0].pPara = para;
1439 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1440 editor->pCursors[0].nOffset = 0;
1442 if (para->member.para.nFlags & MEPF_ROWSTART)
1444 para = para->member.para.next_para;
1445 editor->pCursors[0].pPara = para;
1446 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1447 editor->pCursors[0].nOffset = 0;
1449 editor->pCursors[1] = editor->pCursors[0];
1450 } else { /* v1.0 - 3.0 */
1451 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1452 ME_IsInTable(editor->pCursors[0].pRun))
1456 style = editor->pBuffer->pDefaultStyle;
1457 ME_AddRefStyle(style);
1458 ME_SetSelection(editor, 0, 0);
1459 ME_InternalDeleteText(editor, &editor->pCursors[1],
1460 ME_GetTextLength(editor), FALSE);
1462 ME_ClearTempStyle(editor);
1463 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1467 /* Back up undo mode to a local variable */
1468 nUndoMode = editor->nUndoMode;
1470 /* Only create an undo if SFF_SELECTION is set */
1471 if (!(format & SFF_SELECTION))
1472 editor->nUndoMode = umIgnore;
1474 inStream.editstream = stream;
1475 inStream.editstream->dwError = 0;
1476 inStream.dwSize = 0;
1477 inStream.dwUsed = 0;
1479 if (format & SF_RTF)
1481 /* Check if it's really RTF, and if it is not, use plain text */
1482 ME_StreamInFill(&inStream);
1483 if (!inStream.editstream->dwError)
1485 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1486 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1489 inStream.editstream->dwError = -16;
1494 if (!invalidRTF && !inStream.editstream->dwError)
1496 if (format & SF_RTF) {
1497 from = ME_GetCursorOfs(&editor->pCursors[0]);
1499 /* setup the RTF parser */
1500 memset(&parser, 0, sizeof parser);
1501 RTFSetEditStream(&parser, &inStream);
1502 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1503 parser.editor = editor;
1504 parser.style = style;
1505 WriterInit(&parser);
1507 RTFSetReadHook(&parser, ME_RTFReadHook);
1508 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1509 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1510 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1512 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1513 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1517 /* do the parsing */
1519 RTFFlushOutputBuffer(&parser);
1520 if (!editor->bEmulateVersion10) { /* v4.1 */
1521 if (parser.tableDef && parser.tableDef->tableRowStart &&
1522 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1524 /* Delete any incomplete table row at the end of the rich text. */
1526 ME_DisplayItem *para;
1528 parser.rtfMinor = rtfRow;
1529 /* Complete the table row before deleting it.
1530 * By doing it this way we will have the current paragraph format set
1531 * properly to reflect that is not in the complete table, and undo items
1532 * will be added for this change to the current paragraph format. */
1533 if (parser.nestingLevel > 0)
1535 while (parser.nestingLevel > 1)
1536 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1537 para = parser.tableDef->tableRowStart;
1538 ME_RTFSpecialCharHook(&parser);
1540 para = parser.tableDef->tableRowStart;
1541 ME_RTFSpecialCharHook(&parser);
1542 assert(para->member.para.nFlags & MEPF_ROWEND);
1543 para = para->member.para.next_para;
1546 editor->pCursors[1].pPara = para;
1547 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1548 editor->pCursors[1].nOffset = 0;
1549 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1550 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1551 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1552 if (parser.tableDef)
1553 parser.tableDef->tableRowStart = NULL;
1556 ME_CheckTablesForCorruption(editor);
1557 RTFDestroy(&parser);
1558 if (parser.lpRichEditOle)
1559 IRichEditOle_Release(parser.lpRichEditOle);
1561 if (parser.stackTop > 0)
1563 while (--parser.stackTop >= 0)
1565 ME_ReleaseStyle(parser.style);
1566 parser.style = parser.stack[parser.stackTop].style;
1568 if (!inStream.editstream->dwError)
1569 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1572 /* Remove last line break, as mandated by tests. This is not affected by
1573 CR/LF counters, since RTF streaming presents only \para tokens, which
1574 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1578 ME_GetSelection(editor, &selStart, &selEnd);
1579 newto = ME_GetCursorOfs(selEnd);
1580 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1581 WCHAR lastchar[3] = {'\0', '\0'};
1582 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1583 ME_Cursor linebreakCursor = *selEnd;
1585 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1586 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1587 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1588 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1592 to = ME_GetCursorOfs(&editor->pCursors[0]);
1593 num_read = to - from;
1595 style = parser.style;
1597 else if (format & SF_TEXT)
1598 num_read = ME_StreamInText(editor, format, &inStream, style);
1600 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1601 /* put the cursor at the top */
1602 if (!(format & SFF_SELECTION))
1603 ME_SetSelection(editor, 0, 0);
1606 /* Restore saved undo mode */
1607 editor->nUndoMode = nUndoMode;
1609 /* even if we didn't add an undo, we need to commit anything on the stack */
1610 ME_CommitUndo(editor);
1612 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1613 if (!(format & SFF_SELECTION))
1614 ME_EmptyUndoStack(editor);
1616 ME_ReleaseStyle(style);
1617 editor->nEventMask = nEventMask;
1618 ME_UpdateRepaint(editor, FALSE);
1619 if (!(format & SFF_SELECTION)) {
1620 ME_ClearTempStyle(editor);
1622 ITextHost_TxShowCaret(editor->texthost, FALSE);
1623 ME_MoveCaret(editor);
1624 ITextHost_TxShowCaret(editor->texthost, TRUE);
1625 ME_SendSelChange(editor);
1626 ME_SendRequestResize(editor, FALSE);
1632 typedef struct tagME_RTFStringStreamStruct
1637 } ME_RTFStringStreamStruct;
1639 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1641 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1644 count = min(cb, pStruct->length - pStruct->pos);
1645 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1646 pStruct->pos += count;
1652 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1655 ME_RTFStringStreamStruct data;
1657 data.string = string;
1658 data.length = strlen(string);
1660 es.dwCookie = (DWORD_PTR)&data;
1661 es.pfnCallback = ME_ReadFromRTFString;
1662 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1667 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1669 const int nLen = lstrlenW(text);
1670 const int nTextLen = ME_GetTextLength(editor);
1673 WCHAR wLastChar = ' ';
1675 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1676 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1678 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1679 FIXME("Flags 0x%08x not implemented\n",
1680 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1683 if (chrg->cpMax == -1)
1686 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1688 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1689 if (editor->bEmulateVersion10 && nMax == nTextLen)
1694 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1695 if (editor->bEmulateVersion10 && nMax < nMin)
1699 chrgText->cpMin = -1;
1700 chrgText->cpMax = -1;
1705 /* when searching up, if cpMin < cpMax, then instead of searching
1706 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1707 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1708 * case, it is always bigger than cpMin.
1710 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1714 nMax = nMin > nTextLen ? nTextLen : nMin;
1715 if (nMin < nSwap || chrg->cpMax == -1)
1721 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1724 chrgText->cpMin = chrgText->cpMax = -1;
1728 if (flags & FR_DOWN) /* Forward search */
1730 /* If possible, find the character before where the search starts */
1731 if ((flags & FR_WHOLEWORD) && nMin)
1733 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1734 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1735 ME_MoveCursorChars(editor, &cursor, 1);
1737 ME_CursorFromCharOfs(editor, nMin, &cursor);
1740 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1742 ME_DisplayItem *pCurItem = cursor.pRun;
1743 int nCurStart = cursor.nOffset;
1746 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1748 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1752 if (nMatched == nLen)
1754 ME_DisplayItem *pNextItem = pCurItem;
1755 int nNextStart = nCurStart;
1758 /* Check to see if next character is a whitespace */
1759 if (flags & FR_WHOLEWORD)
1761 if (nCurStart + nMatched == pCurItem->member.run.len)
1763 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1764 nNextStart = -nMatched;
1768 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1772 if (isalnumW(wNextChar))
1776 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1779 chrgText->cpMin = cursor.nOffset;
1780 chrgText->cpMax = cursor.nOffset + nLen;
1782 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1783 return cursor.nOffset;
1785 if (nCurStart + nMatched == pCurItem->member.run.len)
1787 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1788 nCurStart = -nMatched;
1792 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1797 if (cursor.nOffset == cursor.pRun->member.run.len)
1799 ME_NextRun(&cursor.pPara, &cursor.pRun);
1804 else /* Backward search */
1806 /* If possible, find the character after where the search ends */
1807 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1809 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1810 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1811 ME_MoveCursorChars(editor, &cursor, -1);
1813 ME_CursorFromCharOfs(editor, nMax, &cursor);
1816 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1818 ME_DisplayItem *pCurItem = cursor.pRun;
1819 ME_DisplayItem *pCurPara = cursor.pPara;
1820 int nCurEnd = cursor.nOffset;
1825 ME_PrevRun(&pCurPara, &pCurItem);
1826 nCurEnd = pCurItem->member.run.len + nMatched;
1829 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1830 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1832 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1836 if (nMatched == nLen)
1838 ME_DisplayItem *pPrevItem = pCurItem;
1839 int nPrevEnd = nCurEnd;
1843 /* Check to see if previous character is a whitespace */
1844 if (flags & FR_WHOLEWORD)
1846 if (nPrevEnd - nMatched == 0)
1848 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1850 nPrevEnd = pPrevItem->member.run.len + nMatched;
1854 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1858 if (isalnumW(wPrevChar))
1862 nStart = pCurPara->member.para.nCharOfs
1863 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1866 chrgText->cpMin = nStart;
1867 chrgText->cpMax = nStart + nLen;
1869 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1872 if (nCurEnd - nMatched == 0)
1874 ME_PrevRun(&pCurPara, &pCurItem);
1875 /* Don't care about pCurItem becoming NULL here; it's already taken
1876 * care of in the exterior loop condition */
1877 nCurEnd = pCurItem->member.run.len + nMatched;
1881 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1886 if (cursor.nOffset < 0)
1888 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1889 cursor.nOffset = cursor.pRun->member.run.len;
1893 TRACE("not found\n");
1895 chrgText->cpMin = chrgText->cpMax = -1;
1899 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1904 if (!ex->cb || !pText) return 0;
1906 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1907 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1909 if (ex->flags & GT_SELECTION)
1912 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1913 start = editor->pCursors[nStartCur];
1918 ME_SetCursorToStart(editor, &start);
1921 if (ex->codepage == 1200)
1923 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1924 &start, nChars, ex->flags & GT_USECRLF);
1928 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1929 we can just take a bigger buffer? :)
1930 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1931 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1933 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1938 buflen = min(crlfmul * nChars, ex->cb - 1);
1939 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1941 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1942 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1943 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1944 if (rc) rc--; /* do not count 0 terminator */
1951 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1952 const ME_Cursor *start, int nLen, BOOL unicode)
1954 if (!strText) return 0;
1956 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1959 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1961 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1962 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1963 nLen+1, NULL, NULL);
1969 typedef struct tagME_GlobalDestStruct
1973 } ME_GlobalDestStruct;
1975 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1977 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1982 pDest = (WORD *)lpBuff;
1983 pSrc = GlobalLock(pData->hData);
1984 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1985 pDest[i] = pSrc[pData->nLength+i];
1987 pData->nLength += i;
1989 GlobalUnlock(pData->hData);
1993 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1995 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2000 pSrc = GlobalLock(pData->hData);
2001 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2002 pDest[i] = pSrc[pData->nLength+i];
2004 pData->nLength += i;
2006 GlobalUnlock(pData->hData);
2010 static BOOL ME_Paste(ME_TextEditor *editor)
2014 ME_GlobalDestStruct gds;
2015 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2018 if (IsClipboardFormatAvailable(nRTFFormat))
2019 cf = nRTFFormat, dwFormat = SF_RTF;
2020 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2021 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2025 if (!OpenClipboard(editor->hWnd))
2027 gds.hData = GetClipboardData(cf);
2029 es.dwCookie = (DWORD_PTR)&gds;
2030 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2031 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2037 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2039 LPDATAOBJECT dataObj = NULL;
2042 if (editor->cPasswordMask)
2043 return FALSE; /* Copying or Cutting masked text isn't allowed */
2045 if(editor->lpOleCallback)
2048 range.cpMin = ME_GetCursorOfs(start);
2049 range.cpMax = range.cpMin + nChars;
2050 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2052 if(FAILED(hr) || !dataObj)
2053 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2055 hr = OleSetClipboard(dataObj);
2056 IDataObject_Release(dataObj);
2058 return SUCCEEDED(hr) != 0;
2061 /* helper to send a msg filter notification */
2063 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2067 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2068 msgf.nmhdr.hwndFrom = editor->hWnd;
2069 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2070 msgf.nmhdr.code = EN_MSGFILTER;
2072 msgf.wParam = *wParam;
2073 msgf.lParam = *lParam;
2074 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2076 *wParam = msgf.wParam;
2077 *lParam = msgf.lParam;
2078 msgf.wParam = *wParam;
2083 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2085 ME_DisplayItem *startPara, *endPara;
2086 ME_DisplayItem *prev_para;
2087 ME_Cursor *from, *to;
2091 if (!editor->AutoURLDetect_bEnable) return;
2093 ME_GetSelection(editor, &from, &to);
2095 /* Find paragraph previous to the one that contains start cursor */
2096 startPara = from->pPara;
2097 prev_para = startPara->member.para.prev_para;
2098 if (prev_para->type == diParagraph) startPara = prev_para;
2100 /* Find paragraph that contains end cursor */
2101 endPara = to->pPara->member.para.next_para;
2103 start.pPara = startPara;
2104 start.pRun = ME_FindItemFwd(startPara, diRun);
2106 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2108 ME_UpdateLinkAttribute(editor, &start, nChars);
2112 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2114 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2115 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2117 if (editor->bMouseCaptured)
2119 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2120 editor->nSelectionType = stPosition;
2128 editor->nUDArrowX = -1;
2134 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2135 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2139 editor->nUDArrowX = -1;
2140 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2141 if (editor->styleFlags & ES_READONLY)
2143 if (ME_IsSelection(editor))
2145 ME_DeleteSelection(editor);
2146 ME_CommitUndo(editor);
2148 else if (nKey == VK_DELETE)
2150 /* Delete stops group typing.
2151 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2152 ME_DeleteTextAtCursor(editor, 1, 1);
2153 ME_CommitUndo(editor);
2155 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2157 BOOL bDeletionSucceeded;
2158 /* Backspace can be grouped for a single undo */
2159 ME_ContinueCoalescingTransaction(editor);
2160 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2161 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2162 /* Deletion was prevented so the cursor is moved back to where it was.
2163 * (e.g. this happens when trying to delete cell boundaries)
2165 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2167 ME_CommitCoalescingUndo(editor);
2171 ME_MoveCursorFromTableRowStartParagraph(editor);
2172 ME_UpdateSelectionLinkAttribute(editor);
2173 ME_UpdateRepaint(editor, FALSE);
2174 ME_SendRequestResize(editor, FALSE);
2177 if (editor->bDialogMode)
2182 if (!(editor->styleFlags & ES_WANTRETURN))
2184 if (editor->hwndParent)
2187 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2188 if (HIWORD(dw) == DC_HASDEFID)
2190 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2193 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2194 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2202 if (editor->styleFlags & ES_MULTILINE)
2204 ME_Cursor cursor = editor->pCursors[0];
2205 ME_DisplayItem *para = cursor.pPara;
2207 const WCHAR endl = '\r';
2208 const WCHAR endlv10[] = {'\r','\n'};
2211 if (editor->styleFlags & ES_READONLY) {
2212 MessageBeep(MB_ICONERROR);
2216 ME_GetSelectionOfs(editor, &from, &to);
2217 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2219 if (!editor->bEmulateVersion10) { /* v4.1 */
2220 if (para->member.para.nFlags & MEPF_ROWEND) {
2221 /* Add a new table row after this row. */
2222 para = ME_AppendTableRow(editor, para);
2223 para = para->member.para.next_para;
2224 editor->pCursors[0].pPara = para;
2225 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2226 editor->pCursors[0].nOffset = 0;
2227 editor->pCursors[1] = editor->pCursors[0];
2228 ME_CommitUndo(editor);
2229 ME_CheckTablesForCorruption(editor);
2230 ME_UpdateRepaint(editor, FALSE);
2233 else if (para == editor->pCursors[1].pPara &&
2234 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2235 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2236 !para->member.para.prev_para->member.para.nCharOfs)
2238 /* Insert a newline before the table. */
2239 para = para->member.para.prev_para;
2240 para->member.para.nFlags &= ~MEPF_ROWSTART;
2241 editor->pCursors[0].pPara = para;
2242 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2243 editor->pCursors[1] = editor->pCursors[0];
2244 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2245 editor->pCursors[0].pRun->member.run.style);
2246 para = editor->pBuffer->pFirst->member.para.next_para;
2247 ME_SetDefaultParaFormat(para->member.para.pFmt);
2248 para->member.para.nFlags = MEPF_REWRAP;
2249 editor->pCursors[0].pPara = para;
2250 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2251 editor->pCursors[1] = editor->pCursors[0];
2252 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2253 ME_CommitCoalescingUndo(editor);
2254 ME_CheckTablesForCorruption(editor);
2255 ME_UpdateRepaint(editor, FALSE);
2258 } else { /* v1.0 - 3.0 */
2259 ME_DisplayItem *para = cursor.pPara;
2260 if (ME_IsInTable(para))
2262 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2265 ME_ContinueCoalescingTransaction(editor);
2266 para = ME_AppendTableRow(editor, para);
2267 editor->pCursors[0].pPara = para;
2268 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2269 editor->pCursors[0].nOffset = 0;
2270 editor->pCursors[1] = editor->pCursors[0];
2271 ME_CommitCoalescingUndo(editor);
2272 ME_UpdateRepaint(editor, FALSE);
2276 ME_ContinueCoalescingTransaction(editor);
2277 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2278 !ME_IsInTable(para->member.para.prev_para))
2280 /* Insert newline before table */
2281 cursor.pRun = ME_FindItemBack(para, diRun);
2283 editor->pCursors[0].pRun = cursor.pRun;
2284 editor->pCursors[0].pPara = para->member.para.prev_para;
2286 editor->pCursors[0].nOffset = 0;
2287 editor->pCursors[1] = editor->pCursors[0];
2288 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2289 editor->pCursors[0].pRun->member.run.style);
2291 editor->pCursors[1] = editor->pCursors[0];
2292 para = ME_AppendTableRow(editor, para);
2293 editor->pCursors[0].pPara = para;
2294 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2295 editor->pCursors[0].nOffset = 0;
2296 editor->pCursors[1] = editor->pCursors[0];
2298 ME_CommitCoalescingUndo(editor);
2299 ME_UpdateRepaint(editor, FALSE);
2305 style = ME_GetInsertStyle(editor, 0);
2306 ME_SaveTempStyle(editor);
2307 ME_ContinueCoalescingTransaction(editor);
2309 ME_InsertEndRowFromCursor(editor, 0);
2311 if (!editor->bEmulateVersion10)
2312 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2314 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2315 ME_ReleaseStyle(style);
2316 ME_CommitCoalescingUndo(editor);
2319 ME_UpdateSelectionLinkAttribute(editor);
2320 ME_UpdateRepaint(editor, FALSE);
2326 if (editor->bDialogMode && editor->hwndParent)
2327 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2330 if (editor->bDialogMode && editor->hwndParent)
2331 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2336 ME_SetSelection(editor, 0, -1);
2342 return ME_Paste(editor);
2350 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2351 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2354 result = ME_Copy(editor, selStart, nChars);
2355 if (result && nKey == 'X')
2357 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2358 ME_CommitUndo(editor);
2359 ME_UpdateRepaint(editor, TRUE);
2380 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2381 editor->nUDArrowX = -1;
2388 chf.cbSize = sizeof(chf);
2390 ME_GetSelectionCharFormat(editor, &chf);
2391 ME_DumpStyleToBuf(&chf, buf);
2392 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2396 ME_CheckCharOffsets(editor);
2403 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2404 LPARAM flags, BOOL unicode)
2408 if (editor->bMouseCaptured)
2412 wstr = (WCHAR)charCode;
2415 CHAR charA = charCode;
2416 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2419 if (editor->styleFlags & ES_READONLY) {
2420 MessageBeep(MB_ICONERROR);
2421 return 0; /* FIXME really 0 ? */
2424 if ((unsigned)wstr >= ' ' || wstr == '\t')
2426 ME_Cursor cursor = editor->pCursors[0];
2427 ME_DisplayItem *para = cursor.pPara;
2429 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2430 ME_GetSelectionOfs(editor, &from, &to);
2432 /* v4.1 allows tabs to be inserted with ctrl key down */
2433 !(ctrl_is_down && !editor->bEmulateVersion10))
2435 ME_DisplayItem *para;
2436 BOOL bSelectedRow = FALSE;
2438 para = cursor.pPara;
2439 if (ME_IsSelection(editor) &&
2440 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2441 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2442 para->member.para.prev_para->type == diParagraph)
2444 para = para->member.para.prev_para;
2445 bSelectedRow = TRUE;
2447 if (ME_IsInTable(para))
2449 ME_TabPressedInTable(editor, bSelectedRow);
2450 ME_CommitUndo(editor);
2453 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2454 if (para->member.para.nFlags & MEPF_ROWEND) {
2456 para = para->member.para.next_para;
2457 if (para->member.para.nFlags & MEPF_ROWSTART)
2458 para = para->member.para.next_para;
2459 editor->pCursors[0].pPara = para;
2460 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2461 editor->pCursors[0].nOffset = 0;
2462 editor->pCursors[1] = editor->pCursors[0];
2465 } else { /* v1.0 - 3.0 */
2466 if (ME_IsInTable(cursor.pRun) &&
2467 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2470 /* Text should not be inserted at the end of the table. */
2475 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2476 /* WM_CHAR is restricted to nTextLimit */
2477 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2479 ME_Style *style = ME_GetInsertStyle(editor, 0);
2480 ME_SaveTempStyle(editor);
2481 ME_ContinueCoalescingTransaction(editor);
2482 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2483 ME_ReleaseStyle(style);
2484 ME_CommitCoalescingUndo(editor);
2485 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2488 ME_UpdateSelectionLinkAttribute(editor);
2489 ME_UpdateRepaint(editor, FALSE);
2494 /* Process the message and calculate the new click count.
2496 * returns: The click count if it is mouse down event, else returns 0. */
2497 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2500 static int clickNum = 0;
2501 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2504 if ((msg == WM_LBUTTONDBLCLK) ||
2505 (msg == WM_RBUTTONDBLCLK) ||
2506 (msg == WM_MBUTTONDBLCLK) ||
2507 (msg == WM_XBUTTONDBLCLK))
2509 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2512 if ((msg == WM_LBUTTONDOWN) ||
2513 (msg == WM_RBUTTONDOWN) ||
2514 (msg == WM_MBUTTONDOWN) ||
2515 (msg == WM_XBUTTONDOWN))
2517 static MSG prevClickMsg;
2519 /* Compare the editor instead of the hwnd so that the this
2520 * can still be done for windowless richedit controls. */
2521 clickMsg.hwnd = (HWND)editor;
2522 clickMsg.message = msg;
2523 clickMsg.wParam = wParam;
2524 clickMsg.lParam = lParam;
2525 clickMsg.time = GetMessageTime();
2526 clickMsg.pt.x = (short)LOWORD(lParam);
2527 clickMsg.pt.y = (short)HIWORD(lParam);
2528 if ((clickNum != 0) &&
2529 (clickMsg.message == prevClickMsg.message) &&
2530 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2531 (clickMsg.wParam == prevClickMsg.wParam) &&
2532 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2533 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2534 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2540 prevClickMsg = clickMsg;
2547 static BOOL ME_SetCursor(ME_TextEditor *editor)
2553 DWORD messagePos = GetMessagePos();
2554 pt.x = (short)LOWORD(messagePos);
2555 pt.y = (short)HIWORD(messagePos);
2559 sbi.cbSize = sizeof(sbi);
2560 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2561 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2562 PtInRect(&sbi.rcScrollBar, pt))
2564 ITextHost_TxSetCursor(editor->texthost,
2565 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2568 sbi.cbSize = sizeof(sbi);
2569 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2570 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2571 PtInRect(&sbi.rcScrollBar, pt))
2573 ITextHost_TxSetCursor(editor->texthost,
2574 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2578 ITextHost_TxScreenToClient(editor->texthost, &pt);
2580 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2581 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2584 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2585 pt.y < editor->rcFormat.top &&
2586 pt.x < editor->rcFormat.left)
2588 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2591 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2593 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2594 ITextHost_TxSetCursor(editor->texthost,
2595 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2597 ITextHost_TxSetCursor(editor->texthost,
2598 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2601 if (pt.x < editor->rcFormat.left)
2603 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2606 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2611 run = &cursor.pRun->member.run;
2612 if (run->style->fmt.dwMask & CFM_LINK &&
2613 run->style->fmt.dwEffects & CFE_LINK)
2615 ITextHost_TxSetCursor(editor->texthost,
2616 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2621 if (ME_IsSelection(editor))
2623 int selStart, selEnd;
2624 int offset = ME_GetCursorOfs(&cursor);
2626 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2627 if (selStart <= offset && selEnd >= offset) {
2628 ITextHost_TxSetCursor(editor->texthost,
2629 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2635 ITextHost_TxSetCursor(editor->texthost,
2636 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2640 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2642 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2643 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2644 editor->rcFormat.left += 1 + editor->selofs;
2645 editor->rcFormat.right -= 1;
2648 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2653 if(!editor->lpOleCallback || !editor->hWnd)
2655 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2656 if(selrange.cpMin == selrange.cpMax)
2657 seltype |= SEL_EMPTY;
2660 /* FIXME: Handle objects */
2661 seltype |= SEL_TEXT;
2662 if(selrange.cpMax-selrange.cpMin > 1)
2663 seltype |= SEL_MULTICHAR;
2665 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2667 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2673 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2675 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2681 ed->hwndParent = NULL;
2682 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2683 ed->texthost = texthost;
2684 ed->bEmulateVersion10 = bEmulateVersion10;
2686 ITextHost_TxGetPropertyBits(texthost,
2687 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2688 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2689 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2690 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2691 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2693 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2694 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2695 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2696 ed->pBuffer = ME_MakeText();
2697 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2698 ed->nAvailWidth = 0; /* wrap to client area */
2699 ME_MakeFirstParagraph(ed);
2700 /* The four cursors are for:
2701 * 0 - The position where the caret is shown
2702 * 1 - The anchored end of the selection (for normal selection)
2703 * 2 & 3 - The anchored start and end respectively for word, line,
2704 * or paragraph selection.
2707 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2708 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2709 ed->pCursors[1] = ed->pCursors[0];
2710 ed->pCursors[2] = ed->pCursors[0];
2711 ed->pCursors[3] = ed->pCursors[1];
2712 ed->nLastTotalLength = ed->nTotalLength = 0;
2713 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2715 ed->rgbBackColor = -1;
2716 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2717 ed->bCaretAtEnd = FALSE;
2719 ed->nModifyStep = 0;
2720 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2721 list_init( &ed->undo_stack );
2722 list_init( &ed->redo_stack );
2723 ed->nUndoStackSize = 0;
2724 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2725 ed->nUndoMode = umAddToUndo;
2726 ed->nParagraphs = 1;
2727 ed->nLastSelStart = ed->nLastSelEnd = 0;
2728 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2729 ed->bHideSelection = FALSE;
2730 ed->pfnWordBreak = NULL;
2731 ed->lpOleCallback = NULL;
2732 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2733 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2734 ed->AutoURLDetect_bEnable = FALSE;
2735 ed->bHaveFocus = FALSE;
2736 ed->bDialogMode = FALSE;
2737 ed->bMouseCaptured = FALSE;
2738 for (i=0; i<HFONT_CACHE_SIZE; i++)
2740 ed->pFontCache[i].nRefs = 0;
2741 ed->pFontCache[i].nAge = 0;
2742 ed->pFontCache[i].hFont = NULL;
2745 ME_CheckCharOffsets(ed);
2746 ed->bDefaultFormatRect = TRUE;
2747 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2749 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2750 ed->selofs = SELECTIONBAR_WIDTH;
2751 ed->styleFlags |= ES_SELECTIONBAR;
2755 ed->nSelectionType = stPosition;
2757 ed->cPasswordMask = 0;
2758 if (props & TXTBIT_USEPASSWORD)
2759 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2761 if (props & TXTBIT_AUTOWORDSEL)
2762 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2763 if (props & TXTBIT_MULTILINE) {
2764 ed->styleFlags |= ES_MULTILINE;
2765 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2767 ed->bWordWrap = FALSE;
2769 if (props & TXTBIT_READONLY)
2770 ed->styleFlags |= ES_READONLY;
2771 if (!(props & TXTBIT_HIDESELECTION))
2772 ed->styleFlags |= ES_NOHIDESEL;
2773 if (props & TXTBIT_SAVESELECTION)
2774 ed->styleFlags |= ES_SAVESEL;
2775 if (props & TXTBIT_VERTICAL)
2776 ed->styleFlags |= ES_VERTICAL;
2777 if (props & TXTBIT_DISABLEDRAG)
2778 ed->styleFlags |= ES_NOOLEDRAGDROP;
2780 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2782 /* Default scrollbar information */
2783 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2784 ed->vert_si.nMin = 0;
2785 ed->vert_si.nMax = 0;
2786 ed->vert_si.nPage = 0;
2787 ed->vert_si.nPos = 0;
2789 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2790 ed->horz_si.nMin = 0;
2791 ed->horz_si.nMax = 0;
2792 ed->horz_si.nPage = 0;
2793 ed->horz_si.nPos = 0;
2795 OleInitialize(NULL);
2800 static void ME_DestroyEditor(ME_TextEditor *editor)
2802 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2803 ME_DisplayItem *p = pFirst, *pNext = NULL;
2806 ME_ClearTempStyle(editor);
2807 ME_EmptyUndoStack(editor);
2810 ME_DestroyDisplayItem(p);
2813 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2814 for (i=0; i<HFONT_CACHE_SIZE; i++)
2816 if (editor->pFontCache[i].hFont)
2817 DeleteObject(editor->pFontCache[i].hFont);
2819 if (editor->rgbBackColor != -1)
2820 DeleteObject(editor->hbrBackground);
2821 if(editor->lpOleCallback)
2822 IRichEditOleCallback_Release(editor->lpOleCallback);
2823 ITextHost_Release(editor->texthost);
2826 FREE_OBJ(editor->pBuffer);
2827 FREE_OBJ(editor->pCursors);
2832 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2837 case DLL_PROCESS_ATTACH:
2838 DisableThreadLibraryCalls(hinstDLL);
2839 me_heap = HeapCreate (0, 0x10000, 0);
2840 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2841 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2845 case DLL_PROCESS_DETACH:
2846 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2847 UnregisterClassW(MSFTEDIT_CLASS, 0);
2848 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2849 UnregisterClassA("RichEdit50A", 0);
2850 if (ME_ListBoxRegistered)
2851 UnregisterClassW(REListBox20W, 0);
2852 if (ME_ComboBoxRegistered)
2853 UnregisterClassW(REComboBox20W, 0);
2855 HeapDestroy (me_heap);
2863 static const char * const edit_messages[] = {
2892 "EM_SETPASSWORDCHAR",
2893 "EM_EMPTYUNDOBUFFER",
2894 "EM_GETFIRSTVISIBLELINE",
2896 "EM_SETWORDBREAKPROC",
2897 "EM_GETWORDBREAKPROC",
2898 "EM_GETPASSWORDCHAR",
2908 static const char * const richedit_messages[] = {
2913 "EM_EXLINEFROMCHAR",
2919 "EM_GETOLEINTERFACE",
2929 "EM_SETOLECALLBACK",
2931 "EM_SETTARGETDEVICE",
2939 "EM_GETWORDBREAKPROCEX",
2940 "EM_SETWORDBREAKPROCEX",
2942 "EM_UNKNOWN_USER_83",
2947 "EM_STOPGROUPTYPING",
2951 "EM_GETAUTOURLDETECT",
2954 "EM_GETTEXTLENGTHEX",
2957 "EM_UNKNOWN_USER_98",
2958 "EM_UNKNOWN_USER_99",
2959 "EM_SETPUNCTUATION",
2960 "EM_GETPUNCTUATION",
2961 "EM_SETWORDWRAPMODE",
2962 "EM_GETWORDWRAPMODE",
2968 "EM_UNKNOWN_USER_109",
2969 "EM_UNKNOWN_USER_110",
2970 "EM_UNKNOWN_USER_111",
2971 "EM_UNKNOWN_USER_112",
2972 "EM_UNKNOWN_USER_113",
2973 "EM_UNKNOWN_USER_114",
2974 "EM_UNKNOWN_USER_115",
2975 "EM_UNKNOWN_USER_116",
2976 "EM_UNKNOWN_USER_117",
2977 "EM_UNKNOWN_USER_118",
2978 "EM_UNKNOWN_USER_119",
2979 "EM_SETLANGOPTIONS",
2980 "EM_GETLANGOPTIONS",
2981 "EM_GETIMECOMPMODE",
2985 "EM_SETIMEMODEBIAS",
2990 get_msg_name(UINT msg)
2992 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2993 return edit_messages[msg - EM_GETSEL];
2994 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2995 return richedit_messages[msg - EM_CANPASTE];
2999 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3003 ME_Cursor cursor; /* The start of the clicked text. */
3006 x = (short)LOWORD(lParam);
3007 y = (short)HIWORD(lParam);
3008 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3009 if (!isExact) return;
3011 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3012 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3013 { /* The clicked run has CFE_LINK set */
3014 info.nmhdr.hwndFrom = NULL;
3015 info.nmhdr.idFrom = 0;
3016 info.nmhdr.code = EN_LINK;
3018 info.wParam = wParam;
3019 info.lParam = lParam;
3021 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3022 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3023 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3027 #define UNSUPPORTED_MSG(e) \
3029 FIXME(#e ": stub\n"); \
3030 *phresult = S_FALSE; \
3033 /* Handle messages for windowless and windoweded richedit controls.
3035 * The LRESULT that is returned is a return value for window procs,
3036 * and the phresult parameter is the COM return code needed by the
3037 * text services interface. */
3038 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3039 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3045 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3046 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3047 UNSUPPORTED_MSG(EM_FMTLINES)
3048 UNSUPPORTED_MSG(EM_FORMATRANGE)
3049 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3050 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3051 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3052 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3053 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3054 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3055 UNSUPPORTED_MSG(EM_GETREDONAME)
3056 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3057 UNSUPPORTED_MSG(EM_GETUNDONAME)
3058 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3059 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3060 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3061 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3062 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3063 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3064 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3065 UNSUPPORTED_MSG(EM_SETMARGINS)
3066 UNSUPPORTED_MSG(EM_SETPALETTE)
3067 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3068 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3069 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3071 /* Messages specific to Richedit controls */
3074 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3076 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3079 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3081 editor->bDialogMode = TRUE;
3082 if (editor->styleFlags & ES_MULTILINE)
3083 code |= DLGC_WANTMESSAGE;
3086 case EM_EMPTYUNDOBUFFER:
3087 ME_EmptyUndoStack(editor);
3091 /* Note: wParam/lParam can be NULL */
3093 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3094 PUINT pto = lParam ? (PUINT)lParam : &to;
3095 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3096 if ((*pfrom|*pto) & 0xFFFF0000)
3098 return MAKELONG(*pfrom,*pto);
3102 CHARRANGE *pRange = (CHARRANGE *)lParam;
3103 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3104 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3107 case EM_SETUNDOLIMIT:
3109 if ((int)wParam < 0)
3110 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3112 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3113 /* Setting a max stack size keeps wine from getting killed
3114 for hogging memory. Windows allocates all this memory at once, so
3115 no program would realistically set a value above our maximum. */
3116 return editor->nUndoLimit;
3119 return !list_empty( &editor->undo_stack );
3121 return !list_empty( &editor->redo_stack );
3122 case WM_UNDO: /* FIXME: actually not the same */
3124 return ME_Undo(editor);
3126 return ME_Redo(editor);
3129 /* these flags are equivalent to the ES_* counterparts */
3130 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3131 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3132 DWORD settings = editor->styleFlags & mask;
3138 /* these flags are equivalent to ES_* counterparts, except for
3139 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3140 * but is still stored in editor->styleFlags. */
3141 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3142 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3143 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3144 DWORD settings = mask & editor->styleFlags;
3145 DWORD oldSettings = settings;
3146 DWORD changedSettings;
3162 changedSettings = oldSettings ^ settings;
3164 if (changedSettings) {
3165 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3167 if (changedSettings & ECO_SELECTIONBAR)
3169 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3170 if (settings & ECO_SELECTIONBAR) {
3171 assert(!editor->selofs);
3172 editor->selofs = SELECTIONBAR_WIDTH;
3173 editor->rcFormat.left += editor->selofs;
3175 editor->rcFormat.left -= editor->selofs;
3178 ME_RewrapRepaint(editor);
3181 if (changedSettings & settings & ECO_VERTICAL)
3182 FIXME("ECO_VERTICAL not implemented yet!\n");
3183 if (changedSettings & settings & ECO_AUTOHSCROLL)
3184 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3185 if (changedSettings & settings & ECO_AUTOVSCROLL)
3186 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3187 if (changedSettings & settings & ECO_NOHIDESEL)
3188 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3189 if (changedSettings & settings & ECO_WANTRETURN)
3190 FIXME("ECO_WANTRETURN not implemented yet!\n");
3191 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3192 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3199 ME_InvalidateSelection(editor);
3200 ME_SetSelection(editor, wParam, lParam);
3201 ME_InvalidateSelection(editor);
3202 ITextHost_TxShowCaret(editor->texthost, FALSE);
3203 ME_ShowCaret(editor);
3204 ME_SendSelChange(editor);
3207 case EM_SETSCROLLPOS:
3209 POINT *point = (POINT *)lParam;
3210 ME_ScrollAbs(editor, point->x, point->y);
3213 case EM_AUTOURLDETECT:
3215 if (wParam==1 || wParam ==0)
3217 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3220 return E_INVALIDARG;
3222 case EM_GETAUTOURLDETECT:
3224 return editor->AutoURLDetect_bEnable;
3229 CHARRANGE range = *(CHARRANGE *)lParam;
3231 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3233 ME_InvalidateSelection(editor);
3234 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3235 ME_InvalidateSelection(editor);
3236 ITextHost_TxShowCaret(editor->texthost, FALSE);
3237 ME_ShowCaret(editor);
3238 ME_SendSelChange(editor);
3242 case EM_SHOWSCROLLBAR:
3255 flags = WS_HSCROLL|WS_VSCROLL;
3262 editor->styleFlags |= flags;
3263 if (flags & WS_HSCROLL)
3264 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3265 editor->nTotalWidth > editor->sizeWindow.cx);
3266 if (flags & WS_VSCROLL)
3267 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3268 editor->nTotalLength > editor->sizeWindow.cy);
3270 editor->styleFlags &= ~flags;
3271 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3278 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3282 BOOL bRtf, bUnicode, bSelection;
3283 int oldModify = editor->nModifyStep;
3285 if (!pStruct) return 0;
3287 /* If we detect ascii rtf at the start of the string,
3288 * we know it isn't unicode. */
3289 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3290 !strncmp((char *)lParam, "{\\urtf", 6)));
3291 bUnicode = !bRtf && pStruct->codepage == 1200;
3293 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3294 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3295 pStruct->flags, pStruct->codepage);
3297 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3299 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3300 style = ME_GetSelectionInsertStyle(editor);
3301 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3304 ME_SetCursorToStart(editor, &start);
3305 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3306 style = editor->pBuffer->pDefaultStyle;
3310 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3312 /* FIXME: The length returned doesn't include the rtf control
3313 * characters, only the actual text. */
3314 len = lParam ? strlen((char *)lParam) : 0;
3317 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3318 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3319 len = wszText ? lstrlenW(wszText) : 0;
3320 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3321 ME_EndToUnicode(bUnicode, wszText);
3325 ME_ReleaseStyle(style);
3326 ME_UpdateSelectionLinkAttribute(editor);
3330 ME_SetCursorToStart(editor, &cursor);
3331 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3333 ME_CommitUndo(editor);
3334 if (!(pStruct->flags & ST_KEEPUNDO))
3336 editor->nModifyStep = oldModify;
3337 ME_EmptyUndoStack(editor);
3339 ME_UpdateRepaint(editor, FALSE);
3342 case EM_SETBKGNDCOLOR:
3345 if (editor->rgbBackColor != -1) {
3346 DeleteObject(editor->hbrBackground);
3347 lColor = editor->rgbBackColor;
3349 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3353 editor->rgbBackColor = -1;
3354 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3358 editor->rgbBackColor = lParam;
3359 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3361 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3362 ITextHost_TxViewChange(editor->texthost, TRUE);
3366 return editor->nModifyStep == 0 ? 0 : -1;
3370 editor->nModifyStep = 1;
3372 editor->nModifyStep = 0;
3376 case EM_SETREADONLY:
3379 editor->styleFlags |= ES_READONLY;
3381 editor->styleFlags &= ~ES_READONLY;
3384 case EM_SETEVENTMASK:
3386 DWORD nOldMask = editor->nEventMask;
3388 editor->nEventMask = lParam;
3391 case EM_GETEVENTMASK:
3392 return editor->nEventMask;
3393 case EM_SETCHARFORMAT:
3395 CHARFORMAT2W buf, *p;
3396 BOOL bRepaint = TRUE;
3397 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3398 if (p == NULL) return 0;
3399 if (wParam & SCF_ALL) {
3400 if (editor->mode & TM_PLAINTEXT) {
3401 ME_SetDefaultCharFormat(editor, p);
3404 ME_SetCursorToStart(editor, &start);
3405 ME_SetCharFormat(editor, &start, NULL, p);
3406 editor->nModifyStep = 1;
3408 } else if (wParam & SCF_SELECTION) {
3409 if (editor->mode & TM_PLAINTEXT)
3411 if (wParam & SCF_WORD) {
3412 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3415 bRepaint = ME_IsSelection(editor);
3416 ME_SetSelectionCharFormat(editor, p);
3417 if (bRepaint) editor->nModifyStep = 1;
3418 } else { /* SCF_DEFAULT */
3419 ME_SetDefaultCharFormat(editor, p);
3421 ME_CommitUndo(editor);
3424 ME_WrapMarkedParagraphs(editor);
3425 ME_UpdateScrollBar(editor);
3430 case EM_GETCHARFORMAT:
3432 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3433 if (dst->cbSize != sizeof(CHARFORMATA) &&
3434 dst->cbSize != sizeof(CHARFORMATW) &&
3435 dst->cbSize != sizeof(CHARFORMAT2A) &&
3436 dst->cbSize != sizeof(CHARFORMAT2W))
3438 tmp.cbSize = sizeof(tmp);
3440 ME_GetDefaultCharFormat(editor, &tmp);
3442 ME_GetSelectionCharFormat(editor, &tmp);
3443 ME_CopyToCFAny(dst, &tmp);
3446 case EM_SETPARAFORMAT:
3448 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3449 ME_WrapMarkedParagraphs(editor);
3450 ME_UpdateScrollBar(editor);
3452 ME_CommitUndo(editor);
3455 case EM_GETPARAFORMAT:
3456 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3457 return ((PARAFORMAT2 *)lParam)->dwMask;
3458 case EM_GETFIRSTVISIBLELINE:
3460 ME_DisplayItem *p = editor->pBuffer->pFirst;
3461 int y = editor->vert_si.nPos;
3466 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3467 if (p->type == diTextEnd)
3469 if (p->type == diParagraph) {
3470 ypara = p->member.para.pt.y;
3473 ystart = ypara + p->member.row.pt.y;
3474 yend = ystart + p->member.row.nHeight;
3482 case EM_HIDESELECTION:
3484 editor->bHideSelection = (wParam != 0);
3485 ME_InvalidateSelection(editor);
3490 if (!(editor->styleFlags & ES_MULTILINE))
3492 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3498 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3499 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3500 ME_CommitUndo(editor);
3501 ME_UpdateRepaint(editor, TRUE);
3506 int from, to, nStartCursor;
3508 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3509 size_t len = wszText ? lstrlenW(wszText) : 0;
3510 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3512 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3513 style = ME_GetSelectionInsertStyle(editor);
3514 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3515 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3516 ME_ReleaseStyle(style);
3517 /* drop temporary style if line end */
3519 * FIXME question: does abc\n mean: put abc,
3520 * clear temp style, put \n? (would require a change)
3522 if (len>0 && wszText[len-1] == '\n')
3523 ME_ClearTempStyle(editor);
3524 ME_EndToUnicode(unicode, wszText);
3525 ME_CommitUndo(editor);
3526 ME_UpdateSelectionLinkAttribute(editor);
3528 ME_EmptyUndoStack(editor);
3529 ME_UpdateRepaint(editor, FALSE);
3532 case EM_SCROLLCARET:
3533 ME_EnsureVisible(editor, &editor->pCursors[0]);
3540 BOOL bRepaint = LOWORD(lParam);
3543 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3544 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3545 hDC = ITextHost_TxGetDC(editor->texthost);
3546 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3547 ITextHost_TxReleaseDC(editor->texthost, hDC);
3548 if (editor->mode & TM_RICHTEXT) {
3550 ME_SetCursorToStart(editor, &start);
3551 ME_SetCharFormat(editor, &start, NULL, &fmt);
3553 ME_SetDefaultCharFormat(editor, &fmt);
3555 ME_CommitUndo(editor);
3556 ME_MarkAllForWrapping(editor);
3557 ME_WrapMarkedParagraphs(editor);
3558 ME_UpdateScrollBar(editor);
3566 ME_SetCursorToStart(editor, &cursor);
3567 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3570 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3571 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3572 !strncmp((char *)lParam, "{\\urtf", 6))
3574 /* Undocumented: WM_SETTEXT supports RTF text */
3575 ME_StreamInRTFString(editor, 0, (char *)lParam);
3579 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3580 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3581 if (lstrlenW(wszText) > 0)
3585 /* uses default style! */
3586 if (!(editor->styleFlags & ES_MULTILINE))
3591 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3594 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3596 ME_EndToUnicode(unicode, wszText);
3600 TRACE("WM_SETTEXT - NULL\n");
3601 ME_SetCursorToStart(editor, &cursor);
3602 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3603 ME_SetSelection(editor, 0, 0);
3604 editor->nModifyStep = 0;
3605 ME_CommitUndo(editor);
3606 ME_EmptyUndoStack(editor);
3607 ME_UpdateRepaint(editor, FALSE);
3612 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3613 if (IsClipboardFormatAvailable(nRTFFormat))
3615 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3620 case WM_MBUTTONDOWN:
3626 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3627 int nChars = nTo - nFrom;
3628 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3630 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3632 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3633 ME_CommitUndo(editor);
3634 ME_UpdateRepaint(editor, TRUE);
3638 case WM_GETTEXTLENGTH:
3640 GETTEXTLENGTHEX how;
3642 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3643 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3644 how.codepage = unicode ? 1200 : CP_ACP;
3645 return ME_GetTextLengthEx(editor, &how);
3647 case EM_GETTEXTLENGTHEX:
3648 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3652 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3653 ex.flags = GT_USECRLF;
3654 ex.codepage = unicode ? 1200 : CP_ACP;
3655 ex.lpDefaultChar = NULL;
3656 ex.lpUsedDefChar = NULL;
3657 return ME_GetTextEx(editor, &ex, lParam);
3660 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3663 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3664 ME_Cursor *from = &editor->pCursors[nStartCur];
3665 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3666 nTo - nFrom, unicode);
3668 case EM_GETSCROLLPOS:
3670 POINT *point = (POINT *)lParam;
3671 point->x = editor->horz_si.nPos;
3672 point->y = editor->vert_si.nPos;
3673 /* 16-bit scaled value is returned as stored in scrollinfo */
3674 if (editor->horz_si.nMax > 0xffff)
3675 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3676 if (editor->vert_si.nMax > 0xffff)
3677 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3680 case EM_GETTEXTRANGE:
3682 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3684 int nStart = rng->chrg.cpMin;
3685 int nEnd = rng->chrg.cpMax;
3686 int textlength = ME_GetTextLength(editor);
3688 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3689 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3690 if (nStart < 0) return 0;
3691 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3693 if (nStart >= nEnd) return 0;
3695 ME_CursorFromCharOfs(editor, nStart, &start);
3696 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3700 ME_DisplayItem *run;
3701 const unsigned int nMaxChars = *(WORD *) lParam;
3702 unsigned int nCharsLeft = nMaxChars;
3703 char *dest = (char *) lParam;
3704 BOOL wroteNull = FALSE;
3706 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3707 unicode ? "Unicode" : "Ansi");
3709 run = ME_FindRowWithNumber(editor, wParam);
3713 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3714 && run->type == diRun)
3716 WCHAR *str = get_text( &run->member.run, 0 );
3719 nCopy = min(nCharsLeft, run->member.run.len);
3722 memcpy(dest, str, nCopy * sizeof(WCHAR));
3724 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3725 nCharsLeft, NULL, NULL);
3726 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3727 nCharsLeft -= nCopy;
3730 /* append line termination, space allowing */
3734 *((WCHAR *)dest) = '\0';
3741 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3742 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3744 case EM_GETLINECOUNT:
3746 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3749 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3751 while (item != editor->pBuffer->pLast)
3753 assert(item->type == diParagraph);
3754 prev_para = ME_FindItemBack(item, diRun);
3756 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3758 nRows += item->member.para.nRows;
3759 item = item->member.para.next_para;
3761 last_para = ME_FindItemBack(item, diRun);
3763 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3764 if (editor->bEmulateVersion10 && prev_para &&
3765 last_para->member.run.nCharOfs == 0 &&
3766 prev_para->member.run.len == 1 &&
3767 *get_text( &prev_para->member.run, 0 ) == '\r')
3769 /* In 1.0 emulation, the last solitary \r at the very end of the text
3770 (if one exists) is NOT a line break.
3771 FIXME: this is an ugly hack. This should have a more regular model. */
3775 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3776 return max(1, nRows);
3778 case EM_LINEFROMCHAR:
3781 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3783 return ME_RowNumberFromCharOfs(editor, wParam);
3785 case EM_EXLINEFROMCHAR:
3788 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3790 return ME_RowNumberFromCharOfs(editor, lParam);
3794 ME_DisplayItem *item, *para;
3798 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3800 item = ME_FindRowWithNumber(editor, wParam);
3803 para = ME_GetParagraph(item);
3804 item = ME_FindItemFwd(item, diRun);
3805 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3806 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3811 ME_DisplayItem *item, *item_end;
3812 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3813 ME_DisplayItem *para, *run;
3815 if (wParam > ME_GetTextLength(editor))
3819 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3822 ME_RunOfsFromCharOfs(editor, wParam, ¶, &run, NULL);
3823 item = ME_RowStart(run);
3824 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3825 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3826 if (item_end->type == diStartRow) {
3827 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3829 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3830 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3831 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3833 nChars = nNextLineOfs - nThisLineOfs;
3834 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3837 case EM_EXLIMITTEXT:
3839 if ((int)lParam < 0)
3842 editor->nTextLimit = 65536;
3844 editor->nTextLimit = (int) lParam;
3850 editor->nTextLimit = 65536;
3852 editor->nTextLimit = (int) wParam;
3855 case EM_GETLIMITTEXT:
3857 return editor->nTextLimit;
3863 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3864 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3867 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3868 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3869 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3872 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3873 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3881 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3882 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3885 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3886 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3887 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3890 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3891 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3897 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3898 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3900 case EM_FINDTEXTEXW:
3902 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3903 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3906 if (!wParam || !lParam)
3908 *(int *)wParam = editor->nZoomNumerator;
3909 *(int *)lParam = editor->nZoomDenominator;
3912 return ME_SetZoom(editor, wParam, lParam);
3913 case EM_CHARFROMPOS:
3916 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3918 return ME_GetCursorOfs(&cursor);
3922 case EM_POSFROMCHAR:
3924 ME_DisplayItem *pPara, *pRun;
3925 int nCharOfs, nOffset, nLength;
3929 /* detect which API version we're dealing with */
3930 if (wParam >= 0x40000)
3932 nLength = ME_GetTextLength(editor);
3933 nCharOfs = min(nCharOfs, nLength);
3934 nCharOfs = max(nCharOfs, 0);
3936 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3937 assert(pRun->type == diRun);
3938 pt.y = pRun->member.run.pt.y;
3939 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3940 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3941 pt.x += editor->rcFormat.left;
3943 pt.x -= editor->horz_si.nPos;
3944 pt.y -= editor->vert_si.nPos;
3946 if (wParam >= 0x40000) {
3947 *(POINTL *)wParam = pt;
3949 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3955 ME_SetDefaultFormatRect(editor);
3957 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3958 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3959 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3961 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3962 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3964 if (editor->styleFlags & ES_DISABLENOSCROLL)
3966 if (editor->styleFlags & WS_VSCROLL)
3968 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3969 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3971 if (editor->styleFlags & WS_HSCROLL)
3973 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3974 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3978 ME_CommitUndo(editor);
3979 ME_WrapMarkedParagraphs(editor);
3980 ME_MoveCaret(editor);
3984 ME_DestroyEditor(editor);
3988 return ME_SetCursor(editor);
3990 case WM_LBUTTONDBLCLK:
3991 case WM_LBUTTONDOWN:
3993 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3994 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3995 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3997 ITextHost_TxSetFocus(editor->texthost);
3998 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3999 ME_CalculateClickCount(editor, msg, wParam, lParam));
4000 ITextHost_TxSetCapture(editor->texthost, TRUE);
4001 editor->bMouseCaptured = TRUE;
4002 ME_LinkNotify(editor,msg,wParam,lParam);
4003 if (!ME_SetCursor(editor)) goto do_default;
4007 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4008 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4010 if (editor->bMouseCaptured)
4011 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4012 ME_LinkNotify(editor,msg,wParam,lParam);
4013 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4014 if (editor->bMouseCaptured)
4015 ME_SetCursor(editor);
4018 if (editor->bMouseCaptured) {
4019 ITextHost_TxSetCapture(editor->texthost, FALSE);
4020 editor->bMouseCaptured = FALSE;
4022 if (editor->nSelectionType == stDocument)
4023 editor->nSelectionType = stPosition;
4024 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4025 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4029 ME_SetCursor(editor);
4030 ME_LinkNotify(editor,msg,wParam,lParam);
4034 case WM_RBUTTONDOWN:
4035 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4036 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4037 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4040 case WM_CONTEXTMENU:
4041 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4045 editor->bHaveFocus = TRUE;
4046 ME_ShowCaret(editor);
4047 ME_SendOldNotify(editor, EN_SETFOCUS);
4050 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4051 editor->bHaveFocus = FALSE;
4052 ME_HideCaret(editor);
4053 ME_SendOldNotify(editor, EN_KILLFOCUS);
4056 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4059 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4060 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4064 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4065 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4067 if (ME_KeyDown(editor, LOWORD(wParam)))
4071 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4072 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4074 return ME_Char(editor, wParam, lParam, unicode);
4078 if(wParam == UNICODE_NOCHAR) return TRUE;
4079 if(wParam <= 0x000fffff)
4081 if(wParam > 0xffff) /* convert to surrogates */
4084 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4085 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4087 ME_Char(editor, wParam, 0, TRUE);
4093 case EM_STOPGROUPTYPING:
4094 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4098 const int scrollUnit = 7;
4100 switch(LOWORD(wParam))
4103 ME_ScrollAbs(editor, 0, 0);
4106 ME_ScrollAbs(editor,
4107 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4108 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4111 ME_ScrollLeft(editor, scrollUnit);
4114 ME_ScrollRight(editor, scrollUnit);
4117 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4120 ME_ScrollRight(editor, editor->sizeWindow.cx);
4123 case SB_THUMBPOSITION:
4125 int pos = HIWORD(wParam);
4126 if (editor->horz_si.nMax > 0xffff)
4127 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4128 ME_HScrollAbs(editor, pos);
4134 case EM_SCROLL: /* fall through */
4140 origNPos = editor->vert_si.nPos;
4143 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4144 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4145 if (lineHeight <= 0) lineHeight = 24;
4147 switch(LOWORD(wParam))
4150 ME_ScrollAbs(editor, 0, 0);
4153 ME_ScrollAbs(editor,
4154 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4155 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4158 ME_ScrollUp(editor,lineHeight);
4161 ME_ScrollDown(editor,lineHeight);
4164 ME_ScrollUp(editor,editor->sizeWindow.cy);
4167 ME_ScrollDown(editor,editor->sizeWindow.cy);
4170 case SB_THUMBPOSITION:
4172 int pos = HIWORD(wParam);
4173 if (editor->vert_si.nMax > 0xffff)
4174 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4175 ME_VScrollAbs(editor, pos);
4179 if (msg == EM_SCROLL)
4180 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4186 UINT pulScrollLines;
4189 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4190 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4193 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4195 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4197 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4201 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4205 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4207 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4208 if (numerator >= 10 && numerator <= 500)
4209 ME_SetZoom(editor, numerator, 100);
4211 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4212 /* FIXME follow the original */
4214 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4221 *((RECT *)lParam) = editor->rcFormat;
4222 if (editor->bDefaultFormatRect)
4223 ((RECT *)lParam)->left -= editor->selofs;
4233 RECT *rc = (RECT *)lParam;
4235 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4236 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4239 editor->rcFormat.top = max(0, rc->top - border);
4240 editor->rcFormat.left = max(0, rc->left - border);
4241 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4242 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4243 } else if (wParam == 1) {
4244 /* MSDN incorrectly says a wParam value of 1 causes the
4245 * lParam rect to be used as a relative offset,
4246 * however, the tests show it just prevents min/max bound
4248 editor->rcFormat.top = rc->top - border;
4249 editor->rcFormat.left = rc->left - border;
4250 editor->rcFormat.bottom = rc->bottom;
4251 editor->rcFormat.right = rc->right + border;
4255 editor->bDefaultFormatRect = FALSE;
4259 ME_SetDefaultFormatRect(editor);
4260 editor->bDefaultFormatRect = TRUE;
4262 ME_MarkAllForWrapping(editor);
4263 ME_WrapMarkedParagraphs(editor);
4264 ME_UpdateScrollBar(editor);
4265 if (msg != EM_SETRECTNP)
4269 case EM_REQUESTRESIZE:
4270 ME_SendRequestResize(editor, TRUE);
4278 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4279 if (editor->bDefaultFormatRect) {
4280 ME_SetDefaultFormatRect(editor);
4282 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4283 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4285 editor->prevClientRect = clientRect;
4286 ME_RewrapRepaint(editor);
4289 /* IME messages to make richedit controls IME aware */
4290 case WM_IME_SETCONTEXT:
4291 case WM_IME_CONTROL:
4293 case WM_IME_COMPOSITIONFULL:
4295 case WM_IME_STARTCOMPOSITION:
4297 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4298 ME_DeleteSelection(editor);
4299 ME_CommitUndo(editor);
4300 ME_UpdateRepaint(editor, FALSE);
4303 case WM_IME_COMPOSITION:
4307 ME_Style *style = ME_GetInsertStyle(editor, 0);
4308 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4309 ME_DeleteSelection(editor);
4310 ME_SaveTempStyle(editor);
4311 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4313 LPWSTR lpCompStr = NULL;
4315 DWORD dwIndex = lParam & GCS_RESULTSTR;
4317 dwIndex = GCS_COMPSTR;
4319 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4320 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4321 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4322 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4323 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4324 HeapFree(GetProcessHeap(), 0, lpCompStr);
4326 if (dwIndex == GCS_COMPSTR)
4327 ME_SetSelection(editor,editor->imeStartIndex,
4328 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4330 ME_ReleaseStyle(style);
4331 ME_CommitUndo(editor);
4332 ME_UpdateRepaint(editor, FALSE);
4335 case WM_IME_ENDCOMPOSITION:
4337 ME_DeleteSelection(editor);
4338 editor->imeStartIndex=-1;
4341 case EM_GETOLEINTERFACE:
4343 LPVOID *ppvObj = (LPVOID*) lParam;
4344 return CreateIRichEditOle(editor, ppvObj);
4346 case EM_GETPASSWORDCHAR:
4348 return editor->cPasswordMask;
4350 case EM_SETOLECALLBACK:
4351 if(editor->lpOleCallback)
4352 IRichEditOleCallback_Release(editor->lpOleCallback);
4353 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4354 if(editor->lpOleCallback)
4355 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4357 case EM_GETWORDBREAKPROC:
4358 return (LRESULT)editor->pfnWordBreak;
4359 case EM_SETWORDBREAKPROC:
4361 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4363 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4364 return (LRESULT)pfnOld;
4366 case EM_GETTEXTMODE:
4367 return editor->mode;
4368 case EM_SETTEXTMODE:
4373 if (ME_GetTextLength(editor) ||
4374 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4375 return E_UNEXPECTED;
4377 /* Check for mutually exclusive flags in adjacent bits of wParam */
4378 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4379 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4380 return E_INVALIDARG;
4382 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4384 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4385 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4386 if (wParam & TM_PLAINTEXT) {
4387 /* Clear selection since it should be possible to select the
4388 * end of text run for rich text */
4389 ME_InvalidateSelection(editor);
4390 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4391 editor->pCursors[1] = editor->pCursors[0];
4392 /* plain text can only have the default style. */
4393 ME_ClearTempStyle(editor);
4394 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4395 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4396 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4399 /* FIXME: Currently no support for undo level and code page options */
4400 editor->mode = (editor->mode & ~mask) | changes;
4403 case EM_SETPASSWORDCHAR:
4405 editor->cPasswordMask = wParam;
4406 ME_RewrapRepaint(editor);
4409 case EM_SETTARGETDEVICE:
4412 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4413 if (editor->nAvailWidth || editor->bWordWrap != new)
4415 editor->bWordWrap = new;
4416 editor->nAvailWidth = 0; /* wrap to client area */
4417 ME_RewrapRepaint(editor);
4420 int width = max(0, lParam);
4421 if ((editor->styleFlags & ES_MULTILINE) &&
4422 (!editor->bWordWrap || editor->nAvailWidth != width))
4424 editor->nAvailWidth = width;
4425 editor->bWordWrap = TRUE;
4426 ME_RewrapRepaint(editor);
4428 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4433 *phresult = S_FALSE;
4439 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4440 LPARAM lParam, BOOL unicode)
4442 ME_TextEditor *editor;
4444 LRESULT lresult = 0;
4446 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4447 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4449 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4452 if (msg == WM_NCCREATE)
4454 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4455 ITextHost *texthost;
4457 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4458 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4459 return texthost != NULL;
4463 return DefWindowProcW(hWnd, msg, wParam, lParam);
4475 hDC = BeginPaint(editor->hWnd, &ps);
4476 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4477 ME_SendOldNotify(editor, EN_UPDATE);
4478 /* Erase area outside of the formatting rectangle */
4479 if (ps.rcPaint.top < editor->rcFormat.top)
4482 rc.bottom = editor->rcFormat.top;
4483 FillRect(hDC, &rc, editor->hbrBackground);
4484 ps.rcPaint.top = editor->rcFormat.top;
4486 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4488 rc.top = editor->rcFormat.bottom;
4489 FillRect(hDC, &rc, editor->hbrBackground);
4490 ps.rcPaint.bottom = editor->rcFormat.bottom;
4492 if (ps.rcPaint.left < editor->rcFormat.left) {
4494 rc.right = editor->rcFormat.left;
4495 FillRect(hDC, &rc, editor->hbrBackground);
4496 ps.rcPaint.left = editor->rcFormat.left;
4498 if (ps.rcPaint.right > editor->rcFormat.right) {
4500 rc.left = editor->rcFormat.right;
4501 FillRect(hDC, &rc, editor->hbrBackground);
4502 ps.rcPaint.right = editor->rcFormat.right;
4505 ME_PaintContent(editor, hDC, &ps.rcPaint);
4506 EndPaint(editor->hWnd, &ps);
4511 HDC hDC = (HDC)wParam;
4514 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4515 FillRect(hDC, &rc, editor->hbrBackground);
4521 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4522 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4524 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4525 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4526 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4527 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4530 case EM_SETREADONLY:
4533 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4534 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4535 dwStyle &= ~ES_READONLY;
4537 dwStyle |= ES_READONLY;
4538 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4542 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4545 if (hresult == S_FALSE)
4546 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4548 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4549 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4554 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4556 BOOL unicode = TRUE;
4558 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4559 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4562 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4565 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4567 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4570 /******************************************************************
4571 * RichEditANSIWndProc (RICHED20.10)
4573 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4575 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4578 /******************************************************************
4579 * RichEdit10ANSIWndProc (RICHED20.9)
4581 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4583 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4585 ITextHost *texthost;
4586 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4588 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4589 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4590 return texthost != NULL;
4592 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4595 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4597 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4600 /* Fill buffer with srcChars unicode characters from the start cursor.
4602 * buffer: destination buffer
4603 * buflen: length of buffer in characters excluding the NULL terminator.
4604 * start: start of editor text to copy into buffer.
4605 * srcChars: Number of characters to use from the editor text.
4606 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4608 * returns the number of characters written excluding the NULL terminator.
4610 * The written text is always NULL terminated.
4612 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4613 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4615 ME_DisplayItem *pRun, *pNextRun;
4616 const WCHAR *pStart = buffer;
4617 const WCHAR cr_lf[] = {'\r', '\n', 0};
4621 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4622 if (editor->bEmulateVersion10) bCRLF = 0;
4626 pNextRun = ME_FindItemFwd(pRun, diRun);
4628 nLen = pRun->member.run.len - start->nOffset;
4629 str = get_text( &pRun->member.run, start->nOffset );
4631 /* No '\r' is appended to the last paragraph. */
4632 while (srcChars && buflen && pNextRun)
4634 int nFlags = pRun->member.run.nFlags;
4636 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4638 if (buflen == 1) break;
4639 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4640 * EM_GETTEXTEX, however, this is done for copying text which
4641 * also uses this function. */
4642 srcChars -= min(nLen, srcChars);
4646 nLen = min(nLen, srcChars);
4650 nLen = min(nLen, buflen);
4653 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4658 pNextRun = ME_FindItemFwd(pRun, diRun);
4660 nLen = pRun->member.run.len;
4661 str = get_text( &pRun->member.run, 0 );
4664 return buffer - pStart;
4667 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4672 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4673 wcW.lpfnWndProc = RichEditWndProcW;
4675 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4676 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4678 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4679 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4680 wcW.lpszMenuName = NULL;
4682 if (is_version_nt())
4684 wcW.lpszClassName = RICHEDIT_CLASS20W;
4685 if (!RegisterClassW(&wcW)) return FALSE;
4686 wcW.lpszClassName = MSFTEDIT_CLASS;
4687 if (!RegisterClassW(&wcW)) return FALSE;
4691 /* WNDCLASSA/W have the same layout */
4692 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4693 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4694 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4695 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4698 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4699 wcA.lpfnWndProc = RichEditWndProcA;
4701 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4702 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4704 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4705 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4706 wcA.lpszMenuName = NULL;
4707 wcA.lpszClassName = RICHEDIT_CLASS20A;
4708 if (!RegisterClassA(&wcA)) return FALSE;
4709 wcA.lpszClassName = "RichEdit50A";
4710 if (!RegisterClassA(&wcA)) return FALSE;
4715 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4716 /* FIXME: Not implemented */
4717 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4718 hWnd, msg, get_msg_name(msg), wParam, lParam);
4719 return DefWindowProcW(hWnd, msg, wParam, lParam);
4722 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4723 /* FIXME: Not implemented */
4724 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4725 hWnd, msg, get_msg_name(msg), wParam, lParam);
4726 return DefWindowProcW(hWnd, msg, wParam, lParam);
4729 /******************************************************************
4730 * REExtendedRegisterClass (RICHED20.8)
4732 * FIXME undocumented
4733 * Need to check for errors and implement controls and callbacks
4735 LRESULT WINAPI REExtendedRegisterClass(void)
4740 FIXME("semi stub\n");
4744 wcW.hInstance = NULL;
4747 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4748 wcW.lpszMenuName = NULL;
4750 if (!ME_ListBoxRegistered)
4752 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4753 wcW.lpfnWndProc = REListWndProc;
4754 wcW.lpszClassName = REListBox20W;
4755 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4758 if (!ME_ComboBoxRegistered)
4760 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4761 wcW.lpfnWndProc = REComboWndProc;
4762 wcW.lpszClassName = REComboBox20W;
4763 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4767 if (ME_ListBoxRegistered)
4769 if (ME_ComboBoxRegistered)
4775 static BOOL isurlspecial(WCHAR c)
4777 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4778 return strchrW( special_chars, c ) != NULL;
4782 * This proc takes a selection, and scans it forward in order to select the span
4783 * of a possible URL candidate. A possible URL candidate must start with isalnum
4784 * or one of the following special characters: *|/\+%#@ and must consist entirely
4785 * of the characters allowed to start the URL, plus : (colon) which may occur
4786 * at most once, and not at either end.
4788 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4789 const ME_Cursor *start,
4791 ME_Cursor *candidate_min,
4792 ME_Cursor *candidate_max)
4794 ME_Cursor cursor = *start;
4795 BOOL foundColon = FALSE;
4796 BOOL candidateStarted = FALSE;
4797 WCHAR lastAcceptedChar = '\0';
4801 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4802 WCHAR *str = strStart + cursor.nOffset;
4803 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4806 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4808 /* Find start of candidate */
4809 if (!candidateStarted)
4814 if (isalnumW(*str) || isurlspecial(*str))
4816 cursor.nOffset = str - strStart;
4817 *candidate_min = cursor;
4818 candidateStarted = TRUE;
4819 lastAcceptedChar = *str++;
4826 /* Find end of candidate */
4827 if (candidateStarted) {
4831 if (*str == ':' && !foundColon) {
4833 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4834 cursor.nOffset = str - strStart;
4835 if (lastAcceptedChar == ':')
4836 ME_MoveCursorChars(editor, &cursor, -1);
4837 *candidate_max = cursor;
4840 lastAcceptedChar = *str++;
4844 /* End of paragraph: skip it if before candidate span, or terminates
4845 current active span */
4846 if (candidateStarted) {
4847 if (lastAcceptedChar == ':')
4848 ME_MoveCursorChars(editor, &cursor, -1);
4849 *candidate_max = cursor;
4854 /* Reaching this point means no span was found, so get next span */
4855 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4856 if (candidateStarted) {
4857 /* There are no further runs, so take end of text as end of candidate */
4858 cursor.nOffset = str - strStart;
4859 if (lastAcceptedChar == ':')
4860 ME_MoveCursorChars(editor, &cursor, -1);
4861 *candidate_max = cursor;
4864 *candidate_max = *candidate_min = cursor;
4870 if (candidateStarted) {
4871 /* There are no further runs, so take end of text as end of candidate */
4872 if (lastAcceptedChar == ':')
4873 ME_MoveCursorChars(editor, &cursor, -1);
4874 *candidate_max = cursor;
4877 *candidate_max = *candidate_min = cursor;
4882 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4884 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4886 #define MAX_PREFIX_LEN 9
4888 const WCHAR text[MAX_PREFIX_LEN];
4891 {{'p','r','o','s','p','e','r','o',':'}, 9},
4892 {{'t','e','l','n','e','t',':'}, 7},
4893 {{'g','o','p','h','e','r',':'}, 7},
4894 {{'m','a','i','l','t','o',':'}, 7},
4895 {{'h','t','t','p','s',':'}, 6},
4896 {{'f','i','l','e',':'}, 5},
4897 {{'n','e','w','s',':'}, 5},
4898 {{'w','a','i','s',':'}, 5},
4899 {{'n','n','t','p',':'}, 5},
4900 {{'h','t','t','p',':'}, 5},
4901 {{'w','w','w','.'}, 4},
4902 {{'f','t','p',':'}, 4},
4904 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4907 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4908 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4910 if (nChars < prefixes[i].length) continue;
4911 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4915 #undef MAX_PREFIX_LEN
4919 * This proc walks through the indicated selection and evaluates whether each
4920 * section identified by ME_FindNextURLCandidate and in-between sections have
4921 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4922 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4924 * Since this function can cause runs to be split, do not depend on the value
4925 * of the start cursor at the end of the function.
4927 * nChars may be set to INT_MAX to update to the end of the text.
4929 * Returns TRUE if at least one section was modified.
4931 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4933 BOOL modified = FALSE;
4934 ME_Cursor startCur = *start;
4936 if (!editor->AutoURLDetect_bEnable) return FALSE;
4941 ME_Cursor candidateStart, candidateEnd;
4943 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4944 &candidateStart, &candidateEnd))
4946 /* Section before candidate is not an URL */
4947 int cMin = ME_GetCursorOfs(&candidateStart);
4948 int cMax = ME_GetCursorOfs(&candidateEnd);
4950 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4951 candidateStart = candidateEnd;
4952 nChars -= cMax - ME_GetCursorOfs(&startCur);
4956 /* No more candidates until end of selection */
4960 if (startCur.pRun != candidateStart.pRun ||
4961 startCur.nOffset != candidateStart.nOffset)
4963 /* CFE_LINK effect should be consistently unset */
4964 link.cbSize = sizeof(link);
4965 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4966 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4968 /* CFE_LINK must be unset from this range */
4969 memset(&link, 0, sizeof(CHARFORMAT2W));
4970 link.cbSize = sizeof(link);
4971 link.dwMask = CFM_LINK;
4973 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4974 /* Update candidateEnd since setting character formats may split
4975 * runs, which can cause a cursor to be at an invalid offset within
4977 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
4979 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
4980 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4985 if (candidateStart.pRun != candidateEnd.pRun ||
4986 candidateStart.nOffset != candidateEnd.nOffset)
4988 /* CFE_LINK effect should be consistently set */
4989 link.cbSize = sizeof(link);
4990 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4991 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4993 /* CFE_LINK must be set on this range */
4994 memset(&link, 0, sizeof(CHARFORMAT2W));
4995 link.cbSize = sizeof(link);
4996 link.dwMask = CFM_LINK;
4997 link.dwEffects = CFE_LINK;
4998 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5002 startCur = candidateEnd;
5003 } while (nChars > 0);