wineoss.drv: Avoid potential overflow (Coverity).
[wine.git] / dlls / riched20 / editor.c
blob24121a70273bd1116c663f344cf6b0e7a5ff34e8
1 /*
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
24 /*
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
29 + EM_CANPASTE
30 + EM_CANREDO 2.0
31 + EM_CANUNDO
32 + EM_CHARFROMPOS
33 - EM_DISPLAYBAND
34 + EM_EMPTYUNDOBUFFER
35 + EM_EXGETSEL
36 + EM_EXLIMITTEXT
37 + EM_EXLINEFROMCHAR
38 + EM_EXSETSEL
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41 - EM_FINDWORDBREAK
42 - EM_FMTLINES
43 - EM_FORMATRANGE
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
47 - EM_GETEDITSTYLE
48 + EM_GETEVENTMASK
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
53 - EM_GETIMESTATUS
54 - EM_GETLANGOPTIONS 2.0
55 + EM_GETLIMITTEXT
56 + EM_GETLINE
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
58 + EM_GETMODIFY
59 + EM_GETOLEINTERFACE
60 + EM_GETOPTIONS
61 + EM_GETPARAFORMAT
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
64 + EM_GETRECT
65 - EM_GETREDONAME 2.0
66 + EM_GETSEL
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0
69 ! - EM_GETTHUMB
70 + EM_GETTEXTEX 2.0
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72 + EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
75 - EM_GETUNDONAME
76 + EM_GETWORDBREAKPROC
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
79 + EM_GETZOOM 3.0
80 + EM_HIDESELECTION
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82 + EM_LINEFROMCHAR
83 + EM_LINEINDEX
84 + EM_LINELENGTH
85 + EM_LINESCROLL
86 - EM_PASTESPECIAL
87 + EM_POSFROMCHAR
88 + EM_REDO 2.0
89 + EM_REQUESTRESIZE
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
91 + EM_SCROLL
92 + EM_SCROLLCARET
93 - EM_SELECTIONTYPE
94 - EM_SETBIDIOPTIONS 3.0
95 + EM_SETBKGNDCOLOR
96 + EM_SETCHARFORMAT (partly done, no ANSI)
97 - EM_SETEDITSTYLE
98 + EM_SETEVENTMASK (few notifications supported)
99 + EM_SETFONTSIZE
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETIMESTATUS
103 - EM_SETLANGOPTIONS 2.0
104 - EM_SETLIMITTEXT
105 - EM_SETMARGINS
106 + EM_SETMODIFY (not sure if implementation is correct)
107 - EM_SETOLECALLBACK
108 + EM_SETOPTIONS (partially implemented)
109 - EM_SETPALETTE 2.0
110 + EM_SETPARAFORMAT
111 + EM_SETPASSWORDCHAR 2.0
112 - EM_SETPUNCTUATION 1.0asian
113 + EM_SETREADONLY no beep on modification attempt
114 + EM_SETRECT
115 + EM_SETRECTNP (EM_SETRECT without repainting)
116 + EM_SETSEL
117 + EM_SETSCROLLPOS 3.0
118 - EM_SETTABSTOPS 3.0
119 - EM_SETTARGETDEVICE (partial)
120 + EM_SETTEXTEX 3.0 (proper style?)
121 - EM_SETTEXTMODE 2.0
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
127 + EM_SETZOOM 3.0
128 + EM_SHOWSCROLLBAR 2.0
129 + EM_STOPGROUPTYPING 2.0
130 + EM_STREAMIN
131 + EM_STREAMOUT
132 + EM_UNDO
133 + WM_CHAR
134 + WM_CLEAR
135 + WM_COPY
136 + WM_CUT
137 + WM_GETDLGCODE (the current implementation is incomplete)
138 + WM_GETTEXT (ANSI&Unicode)
139 + WM_GETTEXTLENGTH (ANSI version sucks)
140 + WM_HSCROLL
141 + WM_PASTE
142 + WM_SETFONT
143 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144 + WM_STYLECHANGING (seems to do nothing)
145 + WM_STYLECHANGED (seems to do nothing)
146 + WM_UNICHAR
147 + WM_VSCROLL
149 Notifications
151 * EN_CHANGE (sent from the wrong place)
152 - EN_CORRECTTEXT
153 - EN_DROPFILES
154 - EN_ERRSPACE
155 - EN_HSCROLL
156 - EN_IMECHANGE
157 + EN_KILLFOCUS
158 - EN_LINK
159 - EN_MAXTEXT
160 - EN_MSGFILTER
161 - EN_OLEOPFAILED
162 - EN_PROTECTED
163 + EN_REQUESTRESIZE
164 - EN_SAVECLIPBOARD
165 + EN_SELCHANGE
166 + EN_SETFOCUS
167 - EN_STOPNOUNDO
168 * EN_UPDATE (sent from the wrong place)
169 - EN_VSCROLL
171 Styles
173 - ES_AUTOHSCROLL
174 - ES_AUTOVSCROLL
175 + ES_CENTER
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
178 + ES_LEFT
179 - ES_MULTILINE (currently single line controls aren't supported)
180 - ES_NOIME
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182 + ES_RIGHT
183 - ES_SAVESEL
184 - ES_SELFIME
185 - ES_SUNKEN
186 - ES_VERTICAL
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188 - WS_SETFONT
189 + WS_HSCROLL
190 + WS_VSCROLL
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)
203 * - find/replace
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
206 * - IME
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
212 * - hyphenation
213 * - tables
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?
227 #define NONAMELESSUNION
229 #include "editor.h"
230 #include "commdlg.h"
231 #include "winreg.h"
232 #define NO_SHLWAPI_STREAM
233 #include "shlwapi.h"
234 #include "rtf.h"
235 #include "imm.h"
236 #include "res.h"
238 #define STACK_SIZE_DEFAULT 100
239 #define STACK_SIZE_MAX 1000
241 #define TEXT_LIMIT_DEFAULT 32767
243 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
245 static BOOL ME_RegisterEditorClass(HINSTANCE);
246 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
248 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
249 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
250 static HCURSOR hLeft;
252 BOOL me_debug = FALSE;
253 HANDLE me_heap = NULL;
255 static BOOL ME_ListBoxRegistered = FALSE;
256 static BOOL ME_ComboBoxRegistered = FALSE;
258 static inline BOOL is_version_nt(void)
260 return !(GetVersion() & 0x80000000);
263 static ME_TextBuffer *ME_MakeText(void) {
265 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
267 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
268 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
270 p1->prev = NULL;
271 p1->next = p2;
272 p2->prev = p1;
273 p2->next = NULL;
274 p1->member.para.next_para = p2;
275 p2->member.para.prev_para = p1;
276 p2->member.para.nCharOfs = 0;
278 buf->pFirst = p1;
279 buf->pLast = p2;
280 buf->pCharStyle = NULL;
282 return buf;
286 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
288 WCHAR *pText;
289 LRESULT total_bytes_read = 0;
290 BOOL is_read = FALSE;
291 DWORD cp = CP_ACP, copy = 0;
292 char conv_buf[4 + STREAMIN_BUFFER_SIZE]; /* up to 4 additional UTF-8 bytes */
294 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
296 TRACE("%08x %p\n", dwFormat, stream);
298 do {
299 LONG nWideChars = 0;
300 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
302 if (!stream->dwSize)
304 ME_StreamInFill(stream);
305 if (stream->editstream->dwError)
306 break;
307 if (!stream->dwSize)
308 break;
309 total_bytes_read += stream->dwSize;
312 if (!(dwFormat & SF_UNICODE))
314 char * buf = stream->buffer;
315 DWORD size = stream->dwSize, end;
317 if (!is_read)
319 is_read = TRUE;
320 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
322 cp = CP_UTF8;
323 buf += 3;
324 size -= 3;
328 if (cp == CP_UTF8)
330 if (copy)
332 memcpy(conv_buf + copy, buf, size);
333 buf = conv_buf;
334 size += copy;
336 end = size;
337 while ((buf[end-1] & 0xC0) == 0x80)
339 --end;
340 --total_bytes_read; /* strange, but seems to match windows */
342 if (buf[end-1] & 0x80)
344 DWORD need = 0;
345 if ((buf[end-1] & 0xE0) == 0xC0)
346 need = 1;
347 if ((buf[end-1] & 0xF0) == 0xE0)
348 need = 2;
349 if ((buf[end-1] & 0xF8) == 0xF0)
350 need = 3;
352 if (size - end >= need)
354 /* we have enough bytes for this sequence */
355 end = size;
357 else
359 /* need more bytes, so don't transcode this sequence */
360 --end;
364 else
365 end = size;
367 nWideChars = MultiByteToWideChar(cp, 0, buf, end, wszText, STREAMIN_BUFFER_SIZE);
368 pText = wszText;
370 if (cp == CP_UTF8)
372 if (end != size)
374 memcpy(conv_buf, buf + end, size - end);
375 copy = size - end;
379 else
381 nWideChars = stream->dwSize >> 1;
382 pText = (WCHAR *)stream->buffer;
385 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
386 if (stream->dwSize == 0)
387 break;
388 stream->dwSize = 0;
389 } while(1);
390 return total_bytes_read;
393 static void ME_ApplyBorderProperties(RTF_Info *info,
394 ME_BorderRect *borderRect,
395 RTFBorder *borderDef)
397 int i, colorNum;
398 ME_Border *pBorders[] = {&borderRect->top,
399 &borderRect->left,
400 &borderRect->bottom,
401 &borderRect->right};
402 for (i = 0; i < 4; i++)
404 RTFColor *colorDef = info->colorList;
405 pBorders[i]->width = borderDef[i].width;
406 colorNum = borderDef[i].color;
407 while (colorDef && colorDef->rtfCNum != colorNum)
408 colorDef = colorDef->rtfNextColor;
409 if (colorDef)
410 pBorders[i]->colorRef = RGB(
411 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
412 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
413 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
414 else
415 pBorders[i]->colorRef = RGB(0, 0, 0);
419 void ME_RTFCharAttrHook(RTF_Info *info)
421 CHARFORMAT2W fmt;
422 fmt.cbSize = sizeof(fmt);
423 fmt.dwMask = 0;
424 fmt.dwEffects = 0;
426 switch(info->rtfMinor)
428 case rtfPlain:
429 /* FIXME add more flags once they're implemented */
430 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
431 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
432 fmt.yHeight = 12*20; /* 12pt */
433 fmt.wWeight = FW_NORMAL;
434 fmt.bUnderlineType = CFU_UNDERLINENONE;
435 break;
436 case rtfBold:
437 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
438 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
439 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
440 break;
441 case rtfItalic:
442 fmt.dwMask = CFM_ITALIC;
443 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
444 break;
445 case rtfUnderline:
446 fmt.dwMask = CFM_UNDERLINETYPE;
447 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
448 break;
449 case rtfDotUnderline:
450 fmt.dwMask = CFM_UNDERLINETYPE;
451 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
452 break;
453 case rtfDbUnderline:
454 fmt.dwMask = CFM_UNDERLINETYPE;
455 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
456 break;
457 case rtfWordUnderline:
458 fmt.dwMask = CFM_UNDERLINETYPE;
459 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
460 break;
461 case rtfNoUnderline:
462 fmt.dwMask = CFM_UNDERLINETYPE;
463 fmt.bUnderlineType = CFU_UNDERLINENONE;
464 break;
465 case rtfStrikeThru:
466 fmt.dwMask = CFM_STRIKEOUT;
467 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
468 break;
469 case rtfSubScript:
470 case rtfSuperScript:
471 case rtfSubScrShrink:
472 case rtfSuperScrShrink:
473 case rtfNoSuperSub:
474 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
475 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
476 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
477 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
478 break;
479 case rtfInvisible:
480 fmt.dwMask = CFM_HIDDEN;
481 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
482 break;
483 case rtfBackColor:
484 fmt.dwMask = CFM_BACKCOLOR;
485 fmt.dwEffects = 0;
486 if (info->rtfParam == 0)
487 fmt.dwEffects = CFE_AUTOBACKCOLOR;
488 else if (info->rtfParam != rtfNoParam)
490 RTFColor *c = RTFGetColor(info, info->rtfParam);
491 if (c && c->rtfCBlue >= 0)
492 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
493 else
494 fmt.dwEffects = CFE_AUTOBACKCOLOR;
496 break;
497 case rtfForeColor:
498 fmt.dwMask = CFM_COLOR;
499 fmt.dwEffects = 0;
500 if (info->rtfParam == 0)
501 fmt.dwEffects = CFE_AUTOCOLOR;
502 else if (info->rtfParam != rtfNoParam)
504 RTFColor *c = RTFGetColor(info, info->rtfParam);
505 if (c && c->rtfCBlue >= 0)
506 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
507 else {
508 fmt.dwEffects = CFE_AUTOCOLOR;
511 break;
512 case rtfFontNum:
513 if (info->rtfParam != rtfNoParam)
515 RTFFont *f = RTFGetFont(info, info->rtfParam);
516 if (f)
518 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
519 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
520 fmt.bCharSet = f->rtfFCharSet;
521 fmt.dwMask = CFM_FACE | CFM_CHARSET;
522 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
525 break;
526 case rtfFontSize:
527 fmt.dwMask = CFM_SIZE;
528 if (info->rtfParam != rtfNoParam)
529 fmt.yHeight = info->rtfParam*10;
530 break;
532 if (fmt.dwMask) {
533 ME_Style *style2;
534 RTFFlushOutputBuffer(info);
535 /* FIXME too slow ? how come ? */
536 style2 = ME_ApplyStyle(info->editor, info->style, &fmt);
537 ME_ReleaseStyle(info->style);
538 info->style = style2;
539 info->styleChanged = TRUE;
543 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
544 the same tags mean different things in different contexts */
545 void ME_RTFParAttrHook(RTF_Info *info)
547 PARAFORMAT2 fmt;
548 fmt.cbSize = sizeof(fmt);
549 fmt.dwMask = 0;
550 fmt.wEffects = 0;
552 switch(info->rtfMinor)
554 case rtfParDef: /* restores default paragraph attributes */
555 if (!info->editor->bEmulateVersion10) /* v4.1 */
556 info->borderType = RTFBorderParaLeft;
557 else /* v1.0 - 3.0 */
558 info->borderType = RTFBorderParaTop;
559 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
560 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
561 PFM_STARTINDENT;
562 /* TODO: numbering, shading */
563 fmt.wAlignment = PFA_LEFT;
564 fmt.cTabCount = 0;
565 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
566 fmt.wBorderWidth = fmt.wBorders = 0;
567 fmt.wBorderSpace = 0;
568 fmt.bLineSpacingRule = 0;
569 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
570 fmt.dyLineSpacing = 0;
571 if (!info->editor->bEmulateVersion10) /* v4.1 */
573 if (info->tableDef && info->tableDef->tableRowStart &&
574 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
576 ME_Cursor cursor;
577 ME_DisplayItem *para;
578 /* We are just after a table row. */
579 RTFFlushOutputBuffer(info);
580 cursor = info->editor->pCursors[0];
581 para = cursor.pPara;
582 if (para == info->tableDef->tableRowStart->member.para.next_para
583 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
585 /* Since the table row end, no text has been inserted, and the \intbl
586 * control word has not be used. We can confirm that we are not in a
587 * table anymore.
589 info->tableDef->tableRowStart = NULL;
590 info->canInheritInTbl = FALSE;
593 } else { /* v1.0 - v3.0 */
594 fmt.dwMask |= PFM_TABLE;
595 fmt.wEffects &= ~PFE_TABLE;
597 break;
598 case rtfNestLevel:
599 if (!info->editor->bEmulateVersion10) /* v4.1 */
601 while (info->rtfParam > info->nestingLevel) {
602 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
603 ZeroMemory(tableDef, sizeof(RTFTable));
604 tableDef->parent = info->tableDef;
605 info->tableDef = tableDef;
607 RTFFlushOutputBuffer(info);
608 if (tableDef->tableRowStart &&
609 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
611 ME_DisplayItem *para = tableDef->tableRowStart;
612 para = para->member.para.next_para;
613 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
614 tableDef->tableRowStart = para;
615 } else {
616 ME_Cursor cursor;
617 WCHAR endl = '\r';
618 cursor = info->editor->pCursors[0];
619 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
620 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
621 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
624 info->nestingLevel++;
626 info->canInheritInTbl = FALSE;
628 break;
629 case rtfInTable:
631 if (!info->editor->bEmulateVersion10) /* v4.1 */
633 if (info->nestingLevel < 1)
635 RTFTable *tableDef;
636 if (!info->tableDef)
638 info->tableDef = ALLOC_OBJ(RTFTable);
639 ZeroMemory(info->tableDef, sizeof(RTFTable));
641 tableDef = info->tableDef;
642 RTFFlushOutputBuffer(info);
643 if (tableDef->tableRowStart &&
644 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
646 ME_DisplayItem *para = tableDef->tableRowStart;
647 para = para->member.para.next_para;
648 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
649 tableDef->tableRowStart = para;
650 } else {
651 ME_Cursor cursor;
652 WCHAR endl = '\r';
653 cursor = info->editor->pCursors[0];
654 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
655 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
656 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
658 info->nestingLevel = 1;
659 info->canInheritInTbl = TRUE;
661 return;
662 } else { /* v1.0 - v3.0 */
663 fmt.dwMask |= PFM_TABLE;
664 fmt.wEffects |= PFE_TABLE;
666 break;
668 case rtfFirstIndent:
669 ME_GetSelectionParaFormat(info->editor, &fmt);
670 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
671 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
672 fmt.dxOffset = -info->rtfParam;
673 break;
674 case rtfLeftIndent:
675 ME_GetSelectionParaFormat(info->editor, &fmt);
676 fmt.dwMask = PFM_STARTINDENT;
677 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
678 break;
679 case rtfRightIndent:
680 fmt.dwMask = PFM_RIGHTINDENT;
681 fmt.dxRightIndent = info->rtfParam;
682 break;
683 case rtfQuadLeft:
684 case rtfQuadJust:
685 fmt.dwMask = PFM_ALIGNMENT;
686 fmt.wAlignment = PFA_LEFT;
687 break;
688 case rtfQuadRight:
689 fmt.dwMask = PFM_ALIGNMENT;
690 fmt.wAlignment = PFA_RIGHT;
691 break;
692 case rtfQuadCenter:
693 fmt.dwMask = PFM_ALIGNMENT;
694 fmt.wAlignment = PFA_CENTER;
695 break;
696 case rtfTabPos:
697 ME_GetSelectionParaFormat(info->editor, &fmt);
698 if (!(fmt.dwMask & PFM_TABSTOPS))
700 fmt.cTabCount = 0;
702 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
703 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
704 fmt.dwMask = PFM_TABSTOPS;
705 break;
706 case rtfKeep:
707 fmt.dwMask = PFM_KEEP;
708 fmt.wEffects = PFE_KEEP;
709 break;
710 case rtfNoWidowControl:
711 fmt.dwMask = PFM_NOWIDOWCONTROL;
712 fmt.wEffects = PFE_NOWIDOWCONTROL;
713 break;
714 case rtfKeepNext:
715 fmt.dwMask = PFM_KEEPNEXT;
716 fmt.wEffects = PFE_KEEPNEXT;
717 break;
718 case rtfSpaceAfter:
719 fmt.dwMask = PFM_SPACEAFTER;
720 fmt.dySpaceAfter = info->rtfParam;
721 break;
722 case rtfSpaceBefore:
723 fmt.dwMask = PFM_SPACEBEFORE;
724 fmt.dySpaceBefore = info->rtfParam;
725 break;
726 case rtfSpaceBetween:
727 fmt.dwMask = PFM_LINESPACING;
728 if ((int)info->rtfParam > 0)
730 fmt.dyLineSpacing = info->rtfParam;
731 fmt.bLineSpacingRule = 3;
733 else
735 fmt.dyLineSpacing = info->rtfParam;
736 fmt.bLineSpacingRule = 4;
738 break;
739 case rtfSpaceMultiply:
740 fmt.dwMask = PFM_LINESPACING;
741 fmt.dyLineSpacing = info->rtfParam * 20;
742 fmt.bLineSpacingRule = 5;
743 break;
744 case rtfParBullet:
745 fmt.dwMask = PFM_NUMBERING;
746 fmt.wNumbering = PFN_BULLET;
747 break;
748 case rtfParSimple:
749 fmt.dwMask = PFM_NUMBERING;
750 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
751 break;
752 case rtfParNumDecimal:
753 fmt.dwMask = PFM_NUMBERING;
754 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
755 break;
756 case rtfParNumIndent:
757 fmt.dwMask = PFM_NUMBERINGTAB;
758 fmt.wNumberingTab = info->rtfParam;
759 break;
760 case rtfParNumStartAt:
761 fmt.dwMask = PFM_NUMBERINGSTART;
762 fmt.wNumberingStart = info->rtfParam;
763 break;
764 case rtfBorderLeft:
765 info->borderType = RTFBorderParaLeft;
766 ME_GetSelectionParaFormat(info->editor, &fmt);
767 if (!(fmt.dwMask & PFM_BORDER))
769 fmt.wBorderSpace = 0;
770 fmt.wBorderWidth = 1;
771 fmt.wBorders = 0;
773 fmt.wBorders |= 1;
774 fmt.dwMask = PFM_BORDER;
775 break;
776 case rtfBorderRight:
777 info->borderType = RTFBorderParaRight;
778 ME_GetSelectionParaFormat(info->editor, &fmt);
779 if (!(fmt.dwMask & PFM_BORDER))
781 fmt.wBorderSpace = 0;
782 fmt.wBorderWidth = 1;
783 fmt.wBorders = 0;
785 fmt.wBorders |= 2;
786 fmt.dwMask = PFM_BORDER;
787 break;
788 case rtfBorderTop:
789 info->borderType = RTFBorderParaTop;
790 ME_GetSelectionParaFormat(info->editor, &fmt);
791 if (!(fmt.dwMask & PFM_BORDER))
793 fmt.wBorderSpace = 0;
794 fmt.wBorderWidth = 1;
795 fmt.wBorders = 0;
797 fmt.wBorders |= 4;
798 fmt.dwMask = PFM_BORDER;
799 break;
800 case rtfBorderBottom:
801 info->borderType = RTFBorderParaBottom;
802 ME_GetSelectionParaFormat(info->editor, &fmt);
803 if (!(fmt.dwMask & PFM_BORDER))
805 fmt.wBorderSpace = 0;
806 fmt.wBorderWidth = 1;
807 fmt.wBorders = 0;
809 fmt.wBorders |= 8;
810 fmt.dwMask = PFM_BORDER;
811 break;
812 case rtfBorderSingle:
813 ME_GetSelectionParaFormat(info->editor, &fmt);
814 /* we assume that borders have been created before (RTF spec) */
815 fmt.wBorders &= ~0x700;
816 fmt.wBorders |= 1 << 8;
817 fmt.dwMask = PFM_BORDER;
818 break;
819 case rtfBorderThick:
820 ME_GetSelectionParaFormat(info->editor, &fmt);
821 /* we assume that borders have been created before (RTF spec) */
822 fmt.wBorders &= ~0x700;
823 fmt.wBorders |= 2 << 8;
824 fmt.dwMask = PFM_BORDER;
825 break;
826 case rtfBorderShadow:
827 ME_GetSelectionParaFormat(info->editor, &fmt);
828 /* we assume that borders have been created before (RTF spec) */
829 fmt.wBorders &= ~0x700;
830 fmt.wBorders |= 10 << 8;
831 fmt.dwMask = PFM_BORDER;
832 break;
833 case rtfBorderDouble:
834 ME_GetSelectionParaFormat(info->editor, &fmt);
835 /* we assume that borders have been created before (RTF spec) */
836 fmt.wBorders &= ~0x700;
837 fmt.wBorders |= 7 << 8;
838 fmt.dwMask = PFM_BORDER;
839 break;
840 case rtfBorderDot:
841 ME_GetSelectionParaFormat(info->editor, &fmt);
842 /* we assume that borders have been created before (RTF spec) */
843 fmt.wBorders &= ~0x700;
844 fmt.wBorders |= 11 << 8;
845 fmt.dwMask = PFM_BORDER;
846 break;
847 case rtfBorderWidth:
849 int borderSide = info->borderType & RTFBorderSideMask;
850 RTFTable *tableDef = info->tableDef;
851 ME_GetSelectionParaFormat(info->editor, &fmt);
852 /* we assume that borders have been created before (RTF spec) */
853 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
854 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
856 RTFBorder *border;
857 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
858 break;
859 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
860 border->width = info->rtfParam;
861 break;
863 fmt.dwMask = PFM_BORDER;
864 break;
866 case rtfBorderSpace:
867 ME_GetSelectionParaFormat(info->editor, &fmt);
868 /* we assume that borders have been created before (RTF spec) */
869 fmt.wBorderSpace = info->rtfParam;
870 fmt.dwMask = PFM_BORDER;
871 break;
872 case rtfBorderColor:
874 RTFTable *tableDef = info->tableDef;
875 int borderSide = info->borderType & RTFBorderSideMask;
876 int borderType = info->borderType & RTFBorderTypeMask;
877 switch(borderType)
879 case RTFBorderTypePara:
880 if (!info->editor->bEmulateVersion10) /* v4.1 */
881 break;
882 /* v1.0 - 3.0 treat paragraph and row borders the same. */
883 case RTFBorderTypeRow:
884 if (tableDef) {
885 tableDef->border[borderSide].color = info->rtfParam;
887 break;
888 case RTFBorderTypeCell:
889 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
890 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
892 break;
894 break;
896 case rtfRTLPar:
897 fmt.dwMask = PFM_RTLPARA;
898 fmt.wEffects = PFE_RTLPARA;
899 break;
900 case rtfLTRPar:
901 fmt.dwMask = PFM_RTLPARA;
902 fmt.wEffects = 0;
903 break;
905 if (fmt.dwMask) {
906 RTFFlushOutputBuffer(info);
907 /* FIXME too slow ? how come ?*/
908 ME_SetSelectionParaFormat(info->editor, &fmt);
912 void ME_RTFTblAttrHook(RTF_Info *info)
914 switch (info->rtfMinor)
916 case rtfRowDef:
918 if (!info->editor->bEmulateVersion10) /* v4.1 */
919 info->borderType = 0; /* Not sure */
920 else /* v1.0 - 3.0 */
921 info->borderType = RTFBorderRowTop;
922 if (!info->tableDef) {
923 info->tableDef = ME_MakeTableDef(info->editor);
924 } else {
925 ME_InitTableDef(info->editor, info->tableDef);
927 break;
929 case rtfCellPos:
931 int cellNum;
932 if (!info->tableDef)
934 info->tableDef = ME_MakeTableDef(info->editor);
936 cellNum = info->tableDef->numCellsDefined;
937 if (cellNum >= MAX_TABLE_CELLS)
938 break;
939 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
940 if (cellNum < MAX_TAB_STOPS) {
941 /* Tab stops were used to store cell positions before v4.1 but v4.1
942 * still seems to set the tabstops without using them. */
943 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
944 PARAFORMAT2 *pFmt = para->member.para.pFmt;
945 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
946 pFmt->rgxTabs[cellNum] |= 0x00FFFFFF & info->rtfParam;
948 info->tableDef->numCellsDefined++;
949 break;
951 case rtfRowBordTop:
952 info->borderType = RTFBorderRowTop;
953 break;
954 case rtfRowBordLeft:
955 info->borderType = RTFBorderRowLeft;
956 break;
957 case rtfRowBordBottom:
958 info->borderType = RTFBorderRowBottom;
959 break;
960 case rtfRowBordRight:
961 info->borderType = RTFBorderRowRight;
962 break;
963 case rtfCellBordTop:
964 info->borderType = RTFBorderCellTop;
965 break;
966 case rtfCellBordLeft:
967 info->borderType = RTFBorderCellLeft;
968 break;
969 case rtfCellBordBottom:
970 info->borderType = RTFBorderCellBottom;
971 break;
972 case rtfCellBordRight:
973 info->borderType = RTFBorderCellRight;
974 break;
975 case rtfRowGapH:
976 if (info->tableDef)
977 info->tableDef->gapH = info->rtfParam;
978 break;
979 case rtfRowLeftEdge:
980 if (info->tableDef)
981 info->tableDef->leftEdge = info->rtfParam;
982 break;
986 void ME_RTFSpecialCharHook(RTF_Info *info)
988 RTFTable *tableDef = info->tableDef;
989 switch (info->rtfMinor)
991 case rtfNestCell:
992 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
993 break;
994 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
995 case rtfCell:
996 if (!tableDef)
997 break;
998 RTFFlushOutputBuffer(info);
999 if (!info->editor->bEmulateVersion10) { /* v4.1 */
1000 if (tableDef->tableRowStart)
1002 if (!info->nestingLevel &&
1003 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1005 ME_DisplayItem *para = tableDef->tableRowStart;
1006 para = para->member.para.next_para;
1007 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1008 tableDef->tableRowStart = para;
1009 info->nestingLevel = 1;
1011 ME_InsertTableCellFromCursor(info->editor);
1013 } else { /* v1.0 - v3.0 */
1014 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1015 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1016 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
1017 tableDef->numCellsInserted < tableDef->numCellsDefined)
1019 WCHAR tab = '\t';
1020 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1021 tableDef->numCellsInserted++;
1024 break;
1025 case rtfNestRow:
1026 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
1027 break;
1028 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
1029 case rtfRow:
1031 ME_DisplayItem *para, *cell, *run;
1032 int i;
1034 if (!tableDef)
1035 break;
1036 RTFFlushOutputBuffer(info);
1037 if (!info->editor->bEmulateVersion10) { /* v4.1 */
1038 if (!tableDef->tableRowStart)
1039 break;
1040 if (!info->nestingLevel &&
1041 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1043 para = tableDef->tableRowStart;
1044 para = para->member.para.next_para;
1045 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1046 tableDef->tableRowStart = para;
1047 info->nestingLevel++;
1049 para = tableDef->tableRowStart;
1050 cell = ME_FindItemFwd(para, diCell);
1051 assert(cell && !cell->member.cell.prev_cell);
1052 if (tableDef->numCellsDefined < 1)
1054 /* 2000 twips appears to be the cell size that native richedit uses
1055 * when no cell sizes are specified. */
1056 const int defaultCellSize = 2000;
1057 int nRightBoundary = defaultCellSize;
1058 cell->member.cell.nRightBoundary = nRightBoundary;
1059 while (cell->member.cell.next_cell) {
1060 cell = cell->member.cell.next_cell;
1061 nRightBoundary += defaultCellSize;
1062 cell->member.cell.nRightBoundary = nRightBoundary;
1064 para = ME_InsertTableCellFromCursor(info->editor);
1065 cell = para->member.para.pCell;
1066 cell->member.cell.nRightBoundary = nRightBoundary;
1067 } else {
1068 for (i = 0; i < tableDef->numCellsDefined; i++)
1070 RTFCell *cellDef = &tableDef->cells[i];
1071 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1072 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1073 cellDef->border);
1074 cell = cell->member.cell.next_cell;
1075 if (!cell)
1077 para = ME_InsertTableCellFromCursor(info->editor);
1078 cell = para->member.para.pCell;
1081 /* Cell for table row delimiter is empty */
1082 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1085 run = ME_FindItemFwd(cell, diRun);
1086 if (info->editor->pCursors[0].pRun != run ||
1087 info->editor->pCursors[0].nOffset)
1089 int nOfs, nChars;
1090 /* Delete inserted cells that aren't defined. */
1091 info->editor->pCursors[1].pRun = run;
1092 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1093 info->editor->pCursors[1].nOffset = 0;
1094 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1095 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1096 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1097 nChars, TRUE);
1100 para = ME_InsertTableRowEndFromCursor(info->editor);
1101 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1102 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1103 ME_ApplyBorderProperties(info, &para->member.para.border,
1104 tableDef->border);
1105 info->nestingLevel--;
1106 if (!info->nestingLevel)
1108 if (info->canInheritInTbl) {
1109 tableDef->tableRowStart = para;
1110 } else {
1111 while (info->tableDef) {
1112 tableDef = info->tableDef;
1113 info->tableDef = tableDef->parent;
1114 heap_free(tableDef);
1117 } else {
1118 info->tableDef = tableDef->parent;
1119 heap_free(tableDef);
1121 } else { /* v1.0 - v3.0 */
1122 WCHAR endl = '\r';
1123 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1124 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1125 pFmt->dxOffset = info->tableDef->gapH;
1126 pFmt->dxStartIndent = info->tableDef->leftEdge;
1128 ME_ApplyBorderProperties(info, &para->member.para.border,
1129 tableDef->border);
1130 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1132 WCHAR tab = '\t';
1133 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1134 tableDef->numCellsInserted++;
1136 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1137 if (!tableDef->numCellsDefined)
1138 pFmt->wEffects &= ~PFE_TABLE;
1139 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1140 tableDef->numCellsInserted = 0;
1142 break;
1144 case rtfTab:
1145 case rtfPar:
1146 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1147 ME_DisplayItem *para;
1148 PARAFORMAT2 *pFmt;
1149 RTFFlushOutputBuffer(info);
1150 para = info->editor->pCursors[0].pPara;
1151 pFmt = para->member.para.pFmt;
1152 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1154 /* rtfPar is treated like a space within a table. */
1155 info->rtfClass = rtfText;
1156 info->rtfMajor = ' ';
1158 else if (info->rtfMinor == rtfPar && tableDef)
1159 tableDef->numCellsInserted = 0;
1161 break;
1165 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1166 const SIZEL* sz)
1168 LPOLEOBJECT lpObject = NULL;
1169 LPSTORAGE lpStorage = NULL;
1170 LPOLECLIENTSITE lpClientSite = NULL;
1171 LPDATAOBJECT lpDataObject = NULL;
1172 LPOLECACHE lpOleCache = NULL;
1173 STGMEDIUM stgm;
1174 FORMATETC fm;
1175 CLSID clsid;
1176 BOOL ret = FALSE;
1177 DWORD conn;
1179 if (hemf)
1181 stgm.tymed = TYMED_ENHMF;
1182 stgm.u.hEnhMetaFile = hemf;
1183 fm.cfFormat = CF_ENHMETAFILE;
1185 else if (hbmp)
1187 stgm.tymed = TYMED_GDI;
1188 stgm.u.hBitmap = hbmp;
1189 fm.cfFormat = CF_BITMAP;
1191 stgm.pUnkForRelease = NULL;
1193 fm.ptd = NULL;
1194 fm.dwAspect = DVASPECT_CONTENT;
1195 fm.lindex = -1;
1196 fm.tymed = stgm.tymed;
1198 if (!info->lpRichEditOle)
1200 CreateIRichEditOle(NULL, info->editor, (VOID**)&info->lpRichEditOle);
1203 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1204 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1205 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1206 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1207 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1208 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1209 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1210 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1212 REOBJECT reobject;
1214 reobject.cbStruct = sizeof(reobject);
1215 reobject.cp = REO_CP_SELECTION;
1216 reobject.clsid = clsid;
1217 reobject.poleobj = lpObject;
1218 reobject.pstg = lpStorage;
1219 reobject.polesite = lpClientSite;
1220 /* convert from twips to .01 mm */
1221 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1222 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1223 reobject.dvaspect = DVASPECT_CONTENT;
1224 reobject.dwFlags = 0; /* FIXME */
1225 reobject.dwUser = 0;
1227 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1228 ret = TRUE;
1231 if (lpObject) IOleObject_Release(lpObject);
1232 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1233 if (lpStorage) IStorage_Release(lpStorage);
1234 if (lpDataObject) IDataObject_Release(lpDataObject);
1235 if (lpOleCache) IOleCache_Release(lpOleCache);
1237 return ret;
1240 static void ME_RTFReadShpPictGroup( RTF_Info *info )
1242 int level = 1;
1244 for (;;)
1246 RTFGetToken (info);
1248 if (info->rtfClass == rtfEOF) return;
1249 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1251 if (--level == 0) break;
1253 else if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1255 level++;
1257 else
1259 RTFRouteToken( info );
1260 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1261 level--;
1265 RTFRouteToken( info ); /* feed "}" back to router */
1266 return;
1269 static DWORD read_hex_data( RTF_Info *info, BYTE **out )
1271 DWORD read = 0, size = 1024;
1272 BYTE *buf, val;
1273 BOOL flip;
1275 *out = NULL;
1277 if (info->rtfClass != rtfText)
1279 ERR("Called with incorrect token\n");
1280 return 0;
1283 buf = HeapAlloc( GetProcessHeap(), 0, size );
1284 if (!buf) return 0;
1286 val = info->rtfMajor;
1287 for (flip = TRUE;; flip = !flip)
1289 RTFGetToken( info );
1290 if (info->rtfClass == rtfEOF)
1292 HeapFree( GetProcessHeap(), 0, buf );
1293 return 0;
1295 if (info->rtfClass != rtfText) break;
1296 if (flip)
1298 if (read >= size)
1300 size *= 2;
1301 buf = HeapReAlloc( GetProcessHeap(), 0, buf, size );
1302 if (!buf) return 0;
1304 buf[read++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1306 else
1307 val = info->rtfMajor;
1309 if (flip) FIXME("wrong hex string\n");
1311 *out = buf;
1312 return read;
1315 static void ME_RTFReadPictGroup(RTF_Info *info)
1317 SIZEL sz;
1318 BYTE *buffer = NULL;
1319 DWORD size = 0;
1320 METAFILEPICT mfp;
1321 HENHMETAFILE hemf;
1322 HBITMAP hbmp;
1323 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1324 int level = 1;
1326 mfp.mm = MM_TEXT;
1327 sz.cx = sz.cy = 0;
1329 for (;;)
1331 RTFGetToken( info );
1333 if (info->rtfClass == rtfText)
1335 if (level == 1)
1337 if (!buffer)
1338 size = read_hex_data( info, &buffer );
1340 else
1342 RTFSkipGroup( info );
1344 } /* We potentially have a new token so fall through. */
1346 if (info->rtfClass == rtfEOF) return;
1348 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1350 if (--level == 0) break;
1351 continue;
1353 if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1355 level++;
1356 continue;
1358 if (!RTFCheckCM( info, rtfControl, rtfPictAttr ))
1360 RTFRouteToken( info );
1361 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1362 level--;
1363 continue;
1366 if (RTFCheckMM( info, rtfPictAttr, rtfWinMetafile ))
1368 mfp.mm = info->rtfParam;
1369 gfx = gfx_metafile;
1371 else if (RTFCheckMM( info, rtfPictAttr, rtfDevIndBitmap ))
1373 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1374 gfx = gfx_dib;
1376 else if (RTFCheckMM( info, rtfPictAttr, rtfEmfBlip ))
1377 gfx = gfx_enhmetafile;
1378 else if (RTFCheckMM( info, rtfPictAttr, rtfPicWid ))
1379 mfp.xExt = info->rtfParam;
1380 else if (RTFCheckMM( info, rtfPictAttr, rtfPicHt ))
1381 mfp.yExt = info->rtfParam;
1382 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalWid ))
1383 sz.cx = info->rtfParam;
1384 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalHt ))
1385 sz.cy = info->rtfParam;
1386 else
1387 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1390 if (buffer)
1392 switch (gfx)
1394 case gfx_enhmetafile:
1395 if ((hemf = SetEnhMetaFileBits( size, buffer )))
1396 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1397 break;
1398 case gfx_metafile:
1399 if ((hemf = SetWinMetaFileBits( size, buffer, NULL, &mfp )))
1400 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1401 break;
1402 case gfx_dib:
1404 BITMAPINFO *bi = (BITMAPINFO*)buffer;
1405 HDC hdc = GetDC(0);
1406 unsigned nc = bi->bmiHeader.biClrUsed;
1408 /* not quite right, especially for bitfields type of compression */
1409 if (!nc && bi->bmiHeader.biBitCount <= 8)
1410 nc = 1 << bi->bmiHeader.biBitCount;
1411 if ((hbmp = CreateDIBitmap( hdc, &bi->bmiHeader,
1412 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1413 bi, DIB_RGB_COLORS)) )
1414 ME_RTFInsertOleObject( info, NULL, hbmp, &sz );
1415 ReleaseDC( 0, hdc );
1416 break;
1418 default:
1419 break;
1422 HeapFree( GetProcessHeap(), 0, buffer );
1423 RTFRouteToken( info ); /* feed "}" back to router */
1424 return;
1427 /* for now, lookup the \result part and use it, whatever the object */
1428 static void ME_RTFReadObjectGroup(RTF_Info *info)
1430 for (;;)
1432 RTFGetToken (info);
1433 if (info->rtfClass == rtfEOF)
1434 return;
1435 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1436 break;
1437 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1439 RTFGetToken (info);
1440 if (info->rtfClass == rtfEOF)
1441 return;
1442 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1444 int level = 1;
1446 while (RTFGetToken (info) != rtfEOF)
1448 if (info->rtfClass == rtfGroup)
1450 if (info->rtfMajor == rtfBeginGroup) level++;
1451 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1453 RTFRouteToken(info);
1456 else RTFSkipGroup(info);
1457 continue;
1459 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1461 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1462 return;
1465 RTFRouteToken(info); /* feed "}" back to router */
1468 static void ME_RTFReadHook(RTF_Info *info)
1470 switch(info->rtfClass)
1472 case rtfGroup:
1473 switch(info->rtfMajor)
1475 case rtfBeginGroup:
1476 if (info->stackTop < maxStack) {
1477 info->stack[info->stackTop].style = info->style;
1478 ME_AddRefStyle(info->style);
1479 info->stack[info->stackTop].codePage = info->codePage;
1480 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1482 info->stackTop++;
1483 info->styleChanged = FALSE;
1484 break;
1485 case rtfEndGroup:
1487 RTFFlushOutputBuffer(info);
1488 info->stackTop--;
1489 if (info->stackTop <= 0)
1490 info->rtfClass = rtfEOF;
1491 if (info->stackTop < 0)
1492 return;
1494 ME_ReleaseStyle(info->style);
1495 info->style = info->stack[info->stackTop].style;
1496 info->codePage = info->stack[info->stackTop].codePage;
1497 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1498 break;
1501 break;
1505 void
1506 ME_StreamInFill(ME_InStream *stream)
1508 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1509 (BYTE *)stream->buffer,
1510 sizeof(stream->buffer),
1511 (LONG *)&stream->dwSize);
1512 stream->dwUsed = 0;
1515 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1517 RTF_Info parser;
1518 ME_Style *style;
1519 int from, to, nUndoMode;
1520 int nEventMask = editor->nEventMask;
1521 ME_InStream inStream;
1522 BOOL invalidRTF = FALSE;
1523 ME_Cursor *selStart, *selEnd;
1524 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1526 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1527 editor->nEventMask = 0;
1529 ME_GetSelectionOfs(editor, &from, &to);
1530 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1532 ME_GetSelection(editor, &selStart, &selEnd);
1533 style = ME_GetSelectionInsertStyle(editor);
1535 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1537 /* Don't insert text at the end of the table row */
1538 if (!editor->bEmulateVersion10) { /* v4.1 */
1539 ME_DisplayItem *para = editor->pCursors->pPara;
1540 if (para->member.para.nFlags & MEPF_ROWEND)
1542 para = para->member.para.next_para;
1543 editor->pCursors[0].pPara = para;
1544 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1545 editor->pCursors[0].nOffset = 0;
1547 if (para->member.para.nFlags & MEPF_ROWSTART)
1549 para = para->member.para.next_para;
1550 editor->pCursors[0].pPara = para;
1551 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1552 editor->pCursors[0].nOffset = 0;
1554 editor->pCursors[1] = editor->pCursors[0];
1555 } else { /* v1.0 - 3.0 */
1556 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1557 ME_IsInTable(editor->pCursors[0].pRun))
1558 return 0;
1560 } else {
1561 style = editor->pBuffer->pDefaultStyle;
1562 ME_AddRefStyle(style);
1563 ME_SetSelection(editor, 0, 0);
1564 ME_InternalDeleteText(editor, &editor->pCursors[1],
1565 ME_GetTextLength(editor), FALSE);
1566 from = to = 0;
1567 ME_ClearTempStyle(editor);
1568 ME_SetDefaultParaFormat(editor, editor->pCursors[0].pPara->member.para.pFmt);
1572 /* Back up undo mode to a local variable */
1573 nUndoMode = editor->nUndoMode;
1575 /* Only create an undo if SFF_SELECTION is set */
1576 if (!(format & SFF_SELECTION))
1577 editor->nUndoMode = umIgnore;
1579 inStream.editstream = stream;
1580 inStream.editstream->dwError = 0;
1581 inStream.dwSize = 0;
1582 inStream.dwUsed = 0;
1584 if (format & SF_RTF)
1586 /* Check if it's really RTF, and if it is not, use plain text */
1587 ME_StreamInFill(&inStream);
1588 if (!inStream.editstream->dwError)
1590 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1591 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1593 invalidRTF = TRUE;
1594 inStream.editstream->dwError = -16;
1599 if (!invalidRTF && !inStream.editstream->dwError)
1601 if (format & SF_RTF) {
1602 from = ME_GetCursorOfs(&editor->pCursors[0]);
1604 /* setup the RTF parser */
1605 memset(&parser, 0, sizeof parser);
1606 RTFSetEditStream(&parser, &inStream);
1607 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1608 parser.editor = editor;
1609 parser.style = style;
1610 WriterInit(&parser);
1611 RTFInit(&parser);
1612 RTFSetReadHook(&parser, ME_RTFReadHook);
1613 RTFSetDestinationCallback(&parser, rtfShpPict, ME_RTFReadShpPictGroup);
1614 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1615 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1616 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1618 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1619 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1621 BeginFile(&parser);
1623 /* do the parsing */
1624 RTFRead(&parser);
1625 RTFFlushOutputBuffer(&parser);
1626 if (!editor->bEmulateVersion10) { /* v4.1 */
1627 if (parser.tableDef && parser.tableDef->tableRowStart &&
1628 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1630 /* Delete any incomplete table row at the end of the rich text. */
1631 int nOfs, nChars;
1632 ME_DisplayItem *para;
1634 parser.rtfMinor = rtfRow;
1635 /* Complete the table row before deleting it.
1636 * By doing it this way we will have the current paragraph format set
1637 * properly to reflect that is not in the complete table, and undo items
1638 * will be added for this change to the current paragraph format. */
1639 if (parser.nestingLevel > 0)
1641 while (parser.nestingLevel > 1)
1642 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1643 para = parser.tableDef->tableRowStart;
1644 ME_RTFSpecialCharHook(&parser);
1645 } else {
1646 para = parser.tableDef->tableRowStart;
1647 ME_RTFSpecialCharHook(&parser);
1648 assert(para->member.para.nFlags & MEPF_ROWEND);
1649 para = para->member.para.next_para;
1652 editor->pCursors[1].pPara = para;
1653 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1654 editor->pCursors[1].nOffset = 0;
1655 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1656 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1657 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1658 if (parser.tableDef)
1659 parser.tableDef->tableRowStart = NULL;
1662 ME_CheckTablesForCorruption(editor);
1663 RTFDestroy(&parser);
1664 if (parser.lpRichEditOle)
1665 IRichEditOle_Release(parser.lpRichEditOle);
1667 if (parser.stackTop > 0)
1669 while (--parser.stackTop >= 0)
1671 ME_ReleaseStyle(parser.style);
1672 parser.style = parser.stack[parser.stackTop].style;
1674 if (!inStream.editstream->dwError)
1675 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1678 /* Remove last line break, as mandated by tests. This is not affected by
1679 CR/LF counters, since RTF streaming presents only \para tokens, which
1680 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1682 if (stripLastCR && !(format & SFF_SELECTION)) {
1683 int newto;
1684 ME_GetSelection(editor, &selStart, &selEnd);
1685 newto = ME_GetCursorOfs(selEnd);
1686 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1687 WCHAR lastchar[3] = {'\0', '\0'};
1688 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1689 ME_Cursor linebreakCursor = *selEnd;
1691 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1692 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE, FALSE);
1693 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1694 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1698 to = ME_GetCursorOfs(&editor->pCursors[0]);
1699 num_read = to - from;
1701 style = parser.style;
1703 else if (format & SF_TEXT)
1704 num_read = ME_StreamInText(editor, format, &inStream, style);
1705 else
1706 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1707 /* put the cursor at the top */
1708 if (!(format & SFF_SELECTION))
1709 ME_SetSelection(editor, 0, 0);
1712 /* Restore saved undo mode */
1713 editor->nUndoMode = nUndoMode;
1715 /* even if we didn't add an undo, we need to commit anything on the stack */
1716 ME_CommitUndo(editor);
1718 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1719 if (!(format & SFF_SELECTION))
1720 ME_EmptyUndoStack(editor);
1722 ME_ReleaseStyle(style);
1723 editor->nEventMask = nEventMask;
1724 ME_UpdateRepaint(editor, FALSE);
1725 if (!(format & SFF_SELECTION)) {
1726 ME_ClearTempStyle(editor);
1728 ITextHost_TxShowCaret(editor->texthost, FALSE);
1729 ME_MoveCaret(editor);
1730 ITextHost_TxShowCaret(editor->texthost, TRUE);
1731 ME_SendSelChange(editor);
1732 ME_SendRequestResize(editor, FALSE);
1734 return num_read;
1738 typedef struct tagME_RTFStringStreamStruct
1740 char *string;
1741 int pos;
1742 int length;
1743 } ME_RTFStringStreamStruct;
1745 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1747 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1748 int count;
1750 count = min(cb, pStruct->length - pStruct->pos);
1751 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1752 pStruct->pos += count;
1753 *pcb = count;
1754 return 0;
1757 static void
1758 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1760 EDITSTREAM es;
1761 ME_RTFStringStreamStruct data;
1763 data.string = string;
1764 data.length = strlen(string);
1765 data.pos = 0;
1766 es.dwCookie = (DWORD_PTR)&data;
1767 es.pfnCallback = ME_ReadFromRTFString;
1768 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, TRUE);
1772 static int
1773 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1775 const int nLen = lstrlenW(text);
1776 const int nTextLen = ME_GetTextLength(editor);
1777 int nMin, nMax;
1778 ME_Cursor cursor;
1779 WCHAR wLastChar = ' ';
1781 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1782 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1784 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1785 FIXME("Flags 0x%08x not implemented\n",
1786 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1788 nMin = chrg->cpMin;
1789 if (chrg->cpMax == -1)
1790 nMax = nTextLen;
1791 else
1792 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1794 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1795 if (editor->bEmulateVersion10 && nMax == nTextLen)
1797 flags |= FR_DOWN;
1800 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1801 if (editor->bEmulateVersion10 && nMax < nMin)
1803 if (chrgText)
1805 chrgText->cpMin = -1;
1806 chrgText->cpMax = -1;
1808 return -1;
1811 /* when searching up, if cpMin < cpMax, then instead of searching
1812 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1813 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1814 * case, it is always bigger than cpMin.
1816 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1818 int nSwap = nMax;
1820 nMax = nMin > nTextLen ? nTextLen : nMin;
1821 if (nMin < nSwap || chrg->cpMax == -1)
1822 nMin = 0;
1823 else
1824 nMin = nSwap;
1827 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1829 if (chrgText)
1830 chrgText->cpMin = chrgText->cpMax = -1;
1831 return -1;
1834 if (flags & FR_DOWN) /* Forward search */
1836 /* If possible, find the character before where the search starts */
1837 if ((flags & FR_WHOLEWORD) && nMin)
1839 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1840 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1841 ME_MoveCursorChars(editor, &cursor, 1);
1842 } else {
1843 ME_CursorFromCharOfs(editor, nMin, &cursor);
1846 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1848 ME_DisplayItem *pCurItem = cursor.pRun;
1849 int nCurStart = cursor.nOffset;
1850 int nMatched = 0;
1852 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1854 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1855 break;
1857 nMatched++;
1858 if (nMatched == nLen)
1860 ME_DisplayItem *pNextItem = pCurItem;
1861 int nNextStart = nCurStart;
1862 WCHAR wNextChar;
1864 /* Check to see if next character is a whitespace */
1865 if (flags & FR_WHOLEWORD)
1867 if (nCurStart + nMatched == pCurItem->member.run.len)
1869 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1870 nNextStart = -nMatched;
1873 if (pNextItem)
1874 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1875 else
1876 wNextChar = ' ';
1878 if (isalnumW(wNextChar))
1879 break;
1882 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1883 if (chrgText)
1885 chrgText->cpMin = cursor.nOffset;
1886 chrgText->cpMax = cursor.nOffset + nLen;
1888 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1889 return cursor.nOffset;
1891 if (nCurStart + nMatched == pCurItem->member.run.len)
1893 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1894 nCurStart = -nMatched;
1897 if (pCurItem)
1898 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1899 else
1900 wLastChar = ' ';
1902 cursor.nOffset++;
1903 if (cursor.nOffset == cursor.pRun->member.run.len)
1905 ME_NextRun(&cursor.pPara, &cursor.pRun);
1906 cursor.nOffset = 0;
1910 else /* Backward search */
1912 /* If possible, find the character after where the search ends */
1913 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1915 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1916 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1917 ME_MoveCursorChars(editor, &cursor, -1);
1918 } else {
1919 ME_CursorFromCharOfs(editor, nMax, &cursor);
1922 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1924 ME_DisplayItem *pCurItem = cursor.pRun;
1925 ME_DisplayItem *pCurPara = cursor.pPara;
1926 int nCurEnd = cursor.nOffset;
1927 int nMatched = 0;
1929 if (nCurEnd == 0)
1931 ME_PrevRun(&pCurPara, &pCurItem);
1932 nCurEnd = pCurItem->member.run.len;
1935 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1936 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1938 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1939 break;
1941 nMatched++;
1942 if (nMatched == nLen)
1944 ME_DisplayItem *pPrevItem = pCurItem;
1945 int nPrevEnd = nCurEnd;
1946 WCHAR wPrevChar;
1947 int nStart;
1949 /* Check to see if previous character is a whitespace */
1950 if (flags & FR_WHOLEWORD)
1952 if (nPrevEnd - nMatched == 0)
1954 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1955 if (pPrevItem)
1956 nPrevEnd = pPrevItem->member.run.len + nMatched;
1959 if (pPrevItem)
1960 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1961 else
1962 wPrevChar = ' ';
1964 if (isalnumW(wPrevChar))
1965 break;
1968 nStart = pCurPara->member.para.nCharOfs
1969 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1970 if (chrgText)
1972 chrgText->cpMin = nStart;
1973 chrgText->cpMax = nStart + nLen;
1975 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1976 return nStart;
1978 if (nCurEnd - nMatched == 0)
1980 ME_PrevRun(&pCurPara, &pCurItem);
1981 /* Don't care about pCurItem becoming NULL here; it's already taken
1982 * care of in the exterior loop condition */
1983 nCurEnd = pCurItem->member.run.len + nMatched;
1986 if (pCurItem)
1987 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1988 else
1989 wLastChar = ' ';
1991 cursor.nOffset--;
1992 if (cursor.nOffset < 0)
1994 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1995 cursor.nOffset = cursor.pRun->member.run.len;
1999 TRACE("not found\n");
2000 if (chrgText)
2001 chrgText->cpMin = chrgText->cpMax = -1;
2002 return -1;
2005 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
2007 int nChars;
2008 ME_Cursor start;
2010 if (!ex->cb || !pText) return 0;
2012 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2013 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2015 if (ex->flags & GT_SELECTION)
2017 int from, to;
2018 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
2019 start = editor->pCursors[nStartCur];
2020 nChars = to - from;
2022 else
2024 ME_SetCursorToStart(editor, &start);
2025 nChars = INT_MAX;
2027 if (ex->codepage == CP_UNICODE)
2029 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
2030 &start, nChars, ex->flags & GT_USECRLF, FALSE);
2032 else
2034 /* potentially each char may be a CR, why calculate the exact value with O(N) when
2035 we can just take a bigger buffer? :)
2036 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2037 occurs only in richedit 2.0 mode, in which line breaks have only one CR
2039 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2040 DWORD buflen;
2041 LPWSTR buffer;
2042 LRESULT rc;
2044 buflen = min(crlfmul * nChars, ex->cb - 1);
2045 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
2047 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF, FALSE);
2048 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
2049 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2050 if (rc) rc--; /* do not count 0 terminator */
2052 heap_free(buffer);
2053 return rc;
2057 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2058 const ME_Cursor *start, int nLen, BOOL unicode)
2060 if (!strText) return 0;
2061 if (unicode) {
2062 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE, FALSE);
2063 } else {
2064 int nChars;
2065 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2066 if (!p) return 0;
2067 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE, FALSE);
2068 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2069 nLen+1, NULL, NULL);
2070 FREE_OBJ(p);
2071 return nChars;
2075 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2077 int end;
2079 TRACE("%d - %d\n", to, from );
2081 ME_InvalidateSelection( editor );
2082 end = ME_SetSelection( editor, to, from );
2083 ME_InvalidateSelection( editor );
2084 ITextHost_TxShowCaret( editor->texthost, FALSE );
2085 ME_ShowCaret( editor );
2086 ME_SendSelChange( editor );
2088 return end;
2091 typedef struct tagME_GlobalDestStruct
2093 HGLOBAL hData;
2094 int nLength;
2095 } ME_GlobalDestStruct;
2097 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2099 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2100 int i;
2101 WORD *pSrc, *pDest;
2103 cb = cb >> 1;
2104 pDest = (WORD *)lpBuff;
2105 pSrc = GlobalLock(pData->hData);
2106 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2107 pDest[i] = pSrc[pData->nLength+i];
2109 pData->nLength += i;
2110 *pcb = 2*i;
2111 GlobalUnlock(pData->hData);
2112 return 0;
2115 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2117 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2118 int i;
2119 BYTE *pSrc, *pDest;
2121 pDest = lpBuff;
2122 pSrc = GlobalLock(pData->hData);
2123 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2124 pDest[i] = pSrc[pData->nLength+i];
2126 pData->nLength += i;
2127 *pcb = i;
2128 GlobalUnlock(pData->hData);
2129 return 0;
2132 static BOOL ME_Paste(ME_TextEditor *editor)
2134 DWORD dwFormat = 0;
2135 EDITSTREAM es;
2136 ME_GlobalDestStruct gds;
2137 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2138 UINT cf = 0;
2140 if (IsClipboardFormatAvailable(nRTFFormat))
2141 cf = nRTFFormat, dwFormat = SF_RTF;
2142 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2143 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2144 else
2145 return FALSE;
2147 if (!OpenClipboard(editor->hWnd))
2148 return FALSE;
2149 gds.hData = GetClipboardData(cf);
2150 gds.nLength = 0;
2151 es.dwCookie = (DWORD_PTR)&gds;
2152 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2153 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2155 CloseClipboard();
2156 return TRUE;
2159 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2161 LPDATAOBJECT dataObj = NULL;
2162 HRESULT hr = S_OK;
2164 if (editor->cPasswordMask)
2165 return FALSE; /* Copying or Cutting masked text isn't allowed */
2167 if(editor->lpOleCallback)
2169 CHARRANGE range;
2170 range.cpMin = ME_GetCursorOfs(start);
2171 range.cpMax = range.cpMin + nChars;
2172 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2174 if(FAILED(hr) || !dataObj)
2175 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2176 if(SUCCEEDED(hr)) {
2177 hr = OleSetClipboard(dataObj);
2178 IDataObject_Release(dataObj);
2180 return SUCCEEDED(hr);
2183 /* helper to send a msg filter notification */
2184 static BOOL
2185 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2187 MSGFILTER msgf;
2189 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2190 msgf.nmhdr.hwndFrom = editor->hWnd;
2191 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2192 msgf.nmhdr.code = EN_MSGFILTER;
2193 msgf.msg = msg;
2194 msgf.wParam = *wParam;
2195 msgf.lParam = *lParam;
2196 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2197 return FALSE;
2198 *wParam = msgf.wParam;
2199 *lParam = msgf.lParam;
2200 msgf.wParam = *wParam;
2202 return TRUE;
2205 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2207 ME_DisplayItem *startPara, *endPara;
2208 ME_DisplayItem *prev_para;
2209 ME_Cursor *from, *to;
2210 ME_Cursor start;
2211 int nChars;
2213 if (!editor->AutoURLDetect_bEnable) return;
2215 ME_GetSelection(editor, &from, &to);
2217 /* Find paragraph previous to the one that contains start cursor */
2218 startPara = from->pPara;
2219 prev_para = startPara->member.para.prev_para;
2220 if (prev_para->type == diParagraph) startPara = prev_para;
2222 /* Find paragraph that contains end cursor */
2223 endPara = to->pPara->member.para.next_para;
2225 start.pPara = startPara;
2226 start.pRun = ME_FindItemFwd(startPara, diRun);
2227 start.nOffset = 0;
2228 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2230 ME_UpdateLinkAttribute(editor, &start, nChars);
2233 static BOOL
2234 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2236 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2237 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2239 if (editor->bMouseCaptured)
2240 return FALSE;
2241 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2242 editor->nSelectionType = stPosition;
2244 switch (nKey)
2246 case VK_LEFT:
2247 case VK_RIGHT:
2248 case VK_HOME:
2249 case VK_END:
2250 editor->nUDArrowX = -1;
2251 /* fall through */
2252 case VK_UP:
2253 case VK_DOWN:
2254 case VK_PRIOR:
2255 case VK_NEXT:
2256 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2257 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2258 return TRUE;
2259 case VK_BACK:
2260 case VK_DELETE:
2261 editor->nUDArrowX = -1;
2262 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2263 if (editor->styleFlags & ES_READONLY)
2264 return FALSE;
2265 if (ME_IsSelection(editor))
2267 ME_DeleteSelection(editor);
2268 ME_CommitUndo(editor);
2270 else if (nKey == VK_DELETE)
2272 /* Delete stops group typing.
2273 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2274 ME_DeleteTextAtCursor(editor, 1, 1);
2275 ME_CommitUndo(editor);
2277 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2279 BOOL bDeletionSucceeded;
2280 /* Backspace can be grouped for a single undo */
2281 ME_ContinueCoalescingTransaction(editor);
2282 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2283 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2284 /* Deletion was prevented so the cursor is moved back to where it was.
2285 * (e.g. this happens when trying to delete cell boundaries)
2287 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2289 ME_CommitCoalescingUndo(editor);
2291 else
2292 return TRUE;
2293 ME_MoveCursorFromTableRowStartParagraph(editor);
2294 ME_UpdateSelectionLinkAttribute(editor);
2295 ME_UpdateRepaint(editor, FALSE);
2296 ME_SendRequestResize(editor, FALSE);
2297 return TRUE;
2298 case VK_RETURN:
2299 if (editor->bDialogMode)
2301 if (ctrl_is_down)
2302 return TRUE;
2304 if (!(editor->styleFlags & ES_WANTRETURN))
2306 if (editor->hwndParent)
2308 DWORD dw;
2309 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2310 if (HIWORD(dw) == DC_HASDEFID)
2312 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2313 if (hwDefCtrl)
2315 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2316 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2320 return TRUE;
2324 if (editor->styleFlags & ES_MULTILINE)
2326 ME_Cursor cursor = editor->pCursors[0];
2327 ME_DisplayItem *para = cursor.pPara;
2328 int from, to;
2329 const WCHAR endl = '\r';
2330 const WCHAR endlv10[] = {'\r','\n'};
2331 ME_Style *style;
2333 if (editor->styleFlags & ES_READONLY) {
2334 MessageBeep(MB_ICONERROR);
2335 return TRUE;
2338 ME_GetSelectionOfs(editor, &from, &to);
2339 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2341 if (!editor->bEmulateVersion10) { /* v4.1 */
2342 if (para->member.para.nFlags & MEPF_ROWEND) {
2343 /* Add a new table row after this row. */
2344 para = ME_AppendTableRow(editor, para);
2345 para = para->member.para.next_para;
2346 editor->pCursors[0].pPara = para;
2347 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2348 editor->pCursors[0].nOffset = 0;
2349 editor->pCursors[1] = editor->pCursors[0];
2350 ME_CommitUndo(editor);
2351 ME_CheckTablesForCorruption(editor);
2352 ME_UpdateRepaint(editor, FALSE);
2353 return TRUE;
2355 else if (para == editor->pCursors[1].pPara &&
2356 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2357 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2358 !para->member.para.prev_para->member.para.nCharOfs)
2360 /* Insert a newline before the table. */
2361 para = para->member.para.prev_para;
2362 para->member.para.nFlags &= ~MEPF_ROWSTART;
2363 editor->pCursors[0].pPara = para;
2364 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2365 editor->pCursors[1] = editor->pCursors[0];
2366 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2367 editor->pCursors[0].pRun->member.run.style);
2368 para = editor->pBuffer->pFirst->member.para.next_para;
2369 ME_SetDefaultParaFormat(editor, para->member.para.pFmt);
2370 para->member.para.nFlags = MEPF_REWRAP;
2371 editor->pCursors[0].pPara = para;
2372 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2373 editor->pCursors[1] = editor->pCursors[0];
2374 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2375 ME_CommitCoalescingUndo(editor);
2376 ME_CheckTablesForCorruption(editor);
2377 ME_UpdateRepaint(editor, FALSE);
2378 return TRUE;
2380 } else { /* v1.0 - 3.0 */
2381 ME_DisplayItem *para = cursor.pPara;
2382 if (ME_IsInTable(para))
2384 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2386 if (from == to) {
2387 ME_ContinueCoalescingTransaction(editor);
2388 para = ME_AppendTableRow(editor, para);
2389 editor->pCursors[0].pPara = para;
2390 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2391 editor->pCursors[0].nOffset = 0;
2392 editor->pCursors[1] = editor->pCursors[0];
2393 ME_CommitCoalescingUndo(editor);
2394 ME_UpdateRepaint(editor, FALSE);
2395 return TRUE;
2397 } else {
2398 ME_ContinueCoalescingTransaction(editor);
2399 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2400 !ME_IsInTable(para->member.para.prev_para))
2402 /* Insert newline before table */
2403 cursor.pRun = ME_FindItemBack(para, diRun);
2404 if (cursor.pRun) {
2405 editor->pCursors[0].pRun = cursor.pRun;
2406 editor->pCursors[0].pPara = para->member.para.prev_para;
2408 editor->pCursors[0].nOffset = 0;
2409 editor->pCursors[1] = editor->pCursors[0];
2410 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2411 editor->pCursors[0].pRun->member.run.style);
2412 } else {
2413 editor->pCursors[1] = editor->pCursors[0];
2414 para = ME_AppendTableRow(editor, para);
2415 editor->pCursors[0].pPara = para;
2416 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2417 editor->pCursors[0].nOffset = 0;
2418 editor->pCursors[1] = editor->pCursors[0];
2420 ME_CommitCoalescingUndo(editor);
2421 ME_UpdateRepaint(editor, FALSE);
2422 return TRUE;
2427 style = ME_GetInsertStyle(editor, 0);
2428 ME_SaveTempStyle(editor);
2429 ME_ContinueCoalescingTransaction(editor);
2430 if (shift_is_down)
2431 ME_InsertEndRowFromCursor(editor, 0);
2432 else
2433 if (!editor->bEmulateVersion10)
2434 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2435 else
2436 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2437 ME_ReleaseStyle(style);
2438 ME_CommitCoalescingUndo(editor);
2439 SetCursor(NULL);
2441 ME_UpdateSelectionLinkAttribute(editor);
2442 ME_UpdateRepaint(editor, FALSE);
2444 return TRUE;
2446 break;
2447 case VK_ESCAPE:
2448 if (editor->bDialogMode && editor->hwndParent)
2449 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2450 return TRUE;
2451 case VK_TAB:
2452 if (editor->bDialogMode && editor->hwndParent)
2453 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2454 return TRUE;
2455 case 'A':
2456 if (ctrl_is_down)
2458 handle_EM_EXSETSEL( editor, 0, -1 );
2459 return TRUE;
2461 break;
2462 case 'V':
2463 if (ctrl_is_down)
2464 return ME_Paste(editor);
2465 break;
2466 case 'C':
2467 case 'X':
2468 if (ctrl_is_down)
2470 BOOL result;
2471 int nOfs, nChars;
2472 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2473 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2475 nChars -= nOfs;
2476 result = ME_Copy(editor, selStart, nChars);
2477 if (result && nKey == 'X')
2479 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2480 ME_CommitUndo(editor);
2481 ME_UpdateRepaint(editor, TRUE);
2483 return result;
2485 break;
2486 case 'Z':
2487 if (ctrl_is_down)
2489 ME_Undo(editor);
2490 return TRUE;
2492 break;
2493 case 'Y':
2494 if (ctrl_is_down)
2496 ME_Redo(editor);
2497 return TRUE;
2499 break;
2501 default:
2502 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2503 editor->nUDArrowX = -1;
2504 if (ctrl_is_down)
2506 if (nKey == 'W')
2508 CHARFORMAT2W chf;
2509 char buf[2048];
2510 chf.cbSize = sizeof(chf);
2512 ME_GetSelectionCharFormat(editor, &chf);
2513 ME_DumpStyleToBuf(&chf, buf);
2514 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2516 if (nKey == 'Q')
2518 ME_CheckCharOffsets(editor);
2522 return FALSE;
2525 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2526 LPARAM flags, BOOL unicode)
2528 WCHAR wstr;
2530 if (editor->bMouseCaptured)
2531 return 0;
2533 if (unicode)
2534 wstr = (WCHAR)charCode;
2535 else
2537 CHAR charA = charCode;
2538 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2541 if (editor->styleFlags & ES_READONLY) {
2542 MessageBeep(MB_ICONERROR);
2543 return 0; /* FIXME really 0 ? */
2546 if ((unsigned)wstr >= ' ' || wstr == '\t')
2548 ME_Cursor cursor = editor->pCursors[0];
2549 ME_DisplayItem *para = cursor.pPara;
2550 int from, to;
2551 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2552 ME_GetSelectionOfs(editor, &from, &to);
2553 if (wstr == '\t' &&
2554 /* v4.1 allows tabs to be inserted with ctrl key down */
2555 !(ctrl_is_down && !editor->bEmulateVersion10))
2557 ME_DisplayItem *para;
2558 BOOL bSelectedRow = FALSE;
2560 para = cursor.pPara;
2561 if (ME_IsSelection(editor) &&
2562 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2563 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2564 para->member.para.prev_para->type == diParagraph)
2566 para = para->member.para.prev_para;
2567 bSelectedRow = TRUE;
2569 if (ME_IsInTable(para))
2571 ME_TabPressedInTable(editor, bSelectedRow);
2572 ME_CommitUndo(editor);
2573 return 0;
2575 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2576 if (para->member.para.nFlags & MEPF_ROWEND) {
2577 if (from == to) {
2578 para = para->member.para.next_para;
2579 if (para->member.para.nFlags & MEPF_ROWSTART)
2580 para = para->member.para.next_para;
2581 editor->pCursors[0].pPara = para;
2582 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2583 editor->pCursors[0].nOffset = 0;
2584 editor->pCursors[1] = editor->pCursors[0];
2587 } else { /* v1.0 - 3.0 */
2588 if (ME_IsInTable(cursor.pRun) &&
2589 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2590 from == to)
2592 /* Text should not be inserted at the end of the table. */
2593 MessageBeep(-1);
2594 return 0;
2597 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2598 /* WM_CHAR is restricted to nTextLimit */
2599 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2601 ME_Style *style = ME_GetInsertStyle(editor, 0);
2602 ME_SaveTempStyle(editor);
2603 ME_ContinueCoalescingTransaction(editor);
2604 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2605 ME_ReleaseStyle(style);
2606 ME_CommitCoalescingUndo(editor);
2607 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2610 ME_UpdateSelectionLinkAttribute(editor);
2611 ME_UpdateRepaint(editor, FALSE);
2613 return 0;
2616 /* Process the message and calculate the new click count.
2618 * returns: The click count if it is mouse down event, else returns 0. */
2619 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2620 LPARAM lParam)
2622 static int clickNum = 0;
2623 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2624 return 0;
2626 if ((msg == WM_LBUTTONDBLCLK) ||
2627 (msg == WM_RBUTTONDBLCLK) ||
2628 (msg == WM_MBUTTONDBLCLK) ||
2629 (msg == WM_XBUTTONDBLCLK))
2631 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2634 if ((msg == WM_LBUTTONDOWN) ||
2635 (msg == WM_RBUTTONDOWN) ||
2636 (msg == WM_MBUTTONDOWN) ||
2637 (msg == WM_XBUTTONDOWN))
2639 static MSG prevClickMsg;
2640 MSG clickMsg;
2641 /* Compare the editor instead of the hwnd so that the this
2642 * can still be done for windowless richedit controls. */
2643 clickMsg.hwnd = (HWND)editor;
2644 clickMsg.message = msg;
2645 clickMsg.wParam = wParam;
2646 clickMsg.lParam = lParam;
2647 clickMsg.time = GetMessageTime();
2648 clickMsg.pt.x = (short)LOWORD(lParam);
2649 clickMsg.pt.y = (short)HIWORD(lParam);
2650 if ((clickNum != 0) &&
2651 (clickMsg.message == prevClickMsg.message) &&
2652 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2653 (clickMsg.wParam == prevClickMsg.wParam) &&
2654 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2655 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2656 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2658 clickNum++;
2659 } else {
2660 clickNum = 1;
2662 prevClickMsg = clickMsg;
2663 } else {
2664 return 0;
2666 return clickNum;
2669 static BOOL ME_SetCursor(ME_TextEditor *editor)
2671 ME_Cursor cursor;
2672 POINT pt;
2673 BOOL isExact;
2674 SCROLLBARINFO sbi;
2675 DWORD messagePos = GetMessagePos();
2676 pt.x = (short)LOWORD(messagePos);
2677 pt.y = (short)HIWORD(messagePos);
2679 if (editor->hWnd)
2681 sbi.cbSize = sizeof(sbi);
2682 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2683 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2684 PtInRect(&sbi.rcScrollBar, pt))
2686 ITextHost_TxSetCursor(editor->texthost,
2687 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2688 return TRUE;
2690 sbi.cbSize = sizeof(sbi);
2691 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2692 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2693 PtInRect(&sbi.rcScrollBar, pt))
2695 ITextHost_TxSetCursor(editor->texthost,
2696 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2697 return TRUE;
2700 ITextHost_TxScreenToClient(editor->texthost, &pt);
2702 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2703 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2704 return TRUE;
2706 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2707 pt.y < editor->rcFormat.top &&
2708 pt.x < editor->rcFormat.left)
2710 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2711 return TRUE;
2713 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2715 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2716 ITextHost_TxSetCursor(editor->texthost,
2717 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2718 else /* v4.1 */
2719 ITextHost_TxSetCursor(editor->texthost,
2720 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2721 return TRUE;
2723 if (pt.x < editor->rcFormat.left)
2725 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2726 return TRUE;
2728 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2729 if (isExact)
2731 ME_Run *run;
2733 run = &cursor.pRun->member.run;
2734 if (run->style->fmt.dwMask & CFM_LINK &&
2735 run->style->fmt.dwEffects & CFE_LINK)
2737 ITextHost_TxSetCursor(editor->texthost,
2738 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2739 FALSE);
2740 return TRUE;
2743 if (ME_IsSelection(editor))
2745 int selStart, selEnd;
2746 int offset = ME_GetCursorOfs(&cursor);
2748 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2749 if (selStart <= offset && selEnd >= offset) {
2750 ITextHost_TxSetCursor(editor->texthost,
2751 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2752 FALSE);
2753 return TRUE;
2757 ITextHost_TxSetCursor(editor->texthost,
2758 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2759 return TRUE;
2762 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2764 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2765 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2766 editor->rcFormat.left += 1 + editor->selofs;
2767 editor->rcFormat.right -= 1;
2770 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2772 CHARRANGE selrange;
2773 HMENU menu;
2774 int seltype = 0;
2775 if(!editor->lpOleCallback || !editor->hWnd)
2776 return FALSE;
2777 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2778 if(selrange.cpMin == selrange.cpMax)
2779 seltype |= SEL_EMPTY;
2780 else
2782 /* FIXME: Handle objects */
2783 seltype |= SEL_TEXT;
2784 if(selrange.cpMax-selrange.cpMin > 1)
2785 seltype |= SEL_MULTICHAR;
2787 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2789 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2790 DestroyMenu(menu);
2792 return TRUE;
2795 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10, DWORD csStyle)
2797 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2798 int i;
2799 DWORD props;
2800 LONG selbarwidth;
2802 ed->hWnd = NULL;
2803 ed->hwndParent = NULL;
2804 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2805 ed->texthost = texthost;
2806 ed->reOle = NULL;
2807 ed->bEmulateVersion10 = bEmulateVersion10;
2808 ed->styleFlags = 0;
2809 ed->alignStyle = PFA_LEFT;
2810 if (csStyle & ES_RIGHT)
2811 ed->alignStyle = PFA_RIGHT;
2812 if (csStyle & ES_CENTER)
2813 ed->alignStyle = PFA_CENTER;
2814 ITextHost_TxGetPropertyBits(texthost,
2815 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2816 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2817 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2818 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2819 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2820 &props);
2821 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2822 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2823 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2824 ed->pBuffer = ME_MakeText();
2825 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2826 ed->nAvailWidth = 0; /* wrap to client area */
2827 ME_MakeFirstParagraph(ed);
2828 /* The four cursors are for:
2829 * 0 - The position where the caret is shown
2830 * 1 - The anchored end of the selection (for normal selection)
2831 * 2 & 3 - The anchored start and end respectively for word, line,
2832 * or paragraph selection.
2834 ed->nCursors = 4;
2835 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2836 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2837 ed->pCursors[1] = ed->pCursors[0];
2838 ed->pCursors[2] = ed->pCursors[0];
2839 ed->pCursors[3] = ed->pCursors[1];
2840 ed->nLastTotalLength = ed->nTotalLength = 0;
2841 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2842 ed->nUDArrowX = -1;
2843 ed->rgbBackColor = -1;
2844 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2845 ed->bCaretAtEnd = FALSE;
2846 ed->nEventMask = 0;
2847 ed->nModifyStep = 0;
2848 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2849 list_init( &ed->undo_stack );
2850 list_init( &ed->redo_stack );
2851 ed->nUndoStackSize = 0;
2852 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2853 ed->nUndoMode = umAddToUndo;
2854 ed->nParagraphs = 1;
2855 ed->nLastSelStart = ed->nLastSelEnd = 0;
2856 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2857 ed->bHideSelection = FALSE;
2858 ed->pfnWordBreak = NULL;
2859 ed->lpOleCallback = NULL;
2860 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2861 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2862 ed->AutoURLDetect_bEnable = FALSE;
2863 ed->bHaveFocus = FALSE;
2864 ed->bDialogMode = FALSE;
2865 ed->bMouseCaptured = FALSE;
2866 for (i=0; i<HFONT_CACHE_SIZE; i++)
2868 ed->pFontCache[i].nRefs = 0;
2869 ed->pFontCache[i].nAge = 0;
2870 ed->pFontCache[i].hFont = NULL;
2873 ME_CheckCharOffsets(ed);
2874 ed->bDefaultFormatRect = TRUE;
2875 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2876 if (selbarwidth) {
2877 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2878 ed->selofs = SELECTIONBAR_WIDTH;
2879 ed->styleFlags |= ES_SELECTIONBAR;
2880 } else {
2881 ed->selofs = 0;
2883 ed->nSelectionType = stPosition;
2885 ed->cPasswordMask = 0;
2886 if (props & TXTBIT_USEPASSWORD)
2887 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2889 if (props & TXTBIT_AUTOWORDSEL)
2890 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2891 if (props & TXTBIT_MULTILINE) {
2892 ed->styleFlags |= ES_MULTILINE;
2893 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2894 } else {
2895 ed->bWordWrap = FALSE;
2897 if (props & TXTBIT_READONLY)
2898 ed->styleFlags |= ES_READONLY;
2899 if (!(props & TXTBIT_HIDESELECTION))
2900 ed->styleFlags |= ES_NOHIDESEL;
2901 if (props & TXTBIT_SAVESELECTION)
2902 ed->styleFlags |= ES_SAVESEL;
2903 if (props & TXTBIT_VERTICAL)
2904 ed->styleFlags |= ES_VERTICAL;
2905 if (props & TXTBIT_DISABLEDRAG)
2906 ed->styleFlags |= ES_NOOLEDRAGDROP;
2908 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2910 /* Default scrollbar information */
2911 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2912 ed->vert_si.nMin = 0;
2913 ed->vert_si.nMax = 0;
2914 ed->vert_si.nPage = 0;
2915 ed->vert_si.nPos = 0;
2917 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2918 ed->horz_si.nMin = 0;
2919 ed->horz_si.nMax = 0;
2920 ed->horz_si.nPage = 0;
2921 ed->horz_si.nPos = 0;
2923 ed->wheel_remain = 0;
2925 list_init( &ed->style_list );
2926 OleInitialize(NULL);
2928 return ed;
2931 void ME_DestroyEditor(ME_TextEditor *editor)
2933 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2934 ME_DisplayItem *p = pFirst, *pNext = NULL;
2935 ME_Style *s, *cursor2;
2936 int i;
2938 ME_ClearTempStyle(editor);
2939 ME_EmptyUndoStack(editor);
2940 while(p) {
2941 pNext = p->next;
2942 ME_DestroyDisplayItem(p);
2943 p = pNext;
2946 LIST_FOR_EACH_ENTRY_SAFE( s, cursor2, &editor->style_list, ME_Style, entry )
2947 ME_DestroyStyle( s );
2949 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2950 for (i=0; i<HFONT_CACHE_SIZE; i++)
2952 if (editor->pFontCache[i].hFont)
2953 DeleteObject(editor->pFontCache[i].hFont);
2955 if (editor->rgbBackColor != -1)
2956 DeleteObject(editor->hbrBackground);
2957 if(editor->lpOleCallback)
2958 IRichEditOleCallback_Release(editor->lpOleCallback);
2959 ITextHost_Release(editor->texthost);
2960 if (editor->reOle)
2962 IRichEditOle_Release(editor->reOle);
2963 editor->reOle = NULL;
2965 OleUninitialize();
2967 FREE_OBJ(editor->pBuffer);
2968 FREE_OBJ(editor->pCursors);
2970 FREE_OBJ(editor);
2973 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2975 TRACE("\n");
2976 switch (fdwReason)
2978 case DLL_PROCESS_ATTACH:
2979 DisableThreadLibraryCalls(hinstDLL);
2980 me_heap = HeapCreate (0, 0x10000, 0);
2981 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2982 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2983 LookupInit();
2984 break;
2986 case DLL_PROCESS_DETACH:
2987 if (lpvReserved) break;
2988 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2989 UnregisterClassW(MSFTEDIT_CLASS, 0);
2990 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2991 UnregisterClassA("RichEdit50A", 0);
2992 if (ME_ListBoxRegistered)
2993 UnregisterClassW(REListBox20W, 0);
2994 if (ME_ComboBoxRegistered)
2995 UnregisterClassW(REComboBox20W, 0);
2996 LookupCleanup();
2997 HeapDestroy (me_heap);
2998 release_typelib();
2999 break;
3001 return TRUE;
3004 static inline int get_default_line_height( ME_TextEditor *editor )
3006 int height = 0;
3008 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
3009 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3010 if (height <= 0) height = 24;
3012 return height;
3015 static inline int calc_wheel_change( int *remain, int amount_per_click )
3017 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
3018 *remain -= WHEEL_DELTA * change / amount_per_click;
3019 return change;
3022 static const char * const edit_messages[] = {
3023 "EM_GETSEL",
3024 "EM_SETSEL",
3025 "EM_GETRECT",
3026 "EM_SETRECT",
3027 "EM_SETRECTNP",
3028 "EM_SCROLL",
3029 "EM_LINESCROLL",
3030 "EM_SCROLLCARET",
3031 "EM_GETMODIFY",
3032 "EM_SETMODIFY",
3033 "EM_GETLINECOUNT",
3034 "EM_LINEINDEX",
3035 "EM_SETHANDLE",
3036 "EM_GETHANDLE",
3037 "EM_GETTHUMB",
3038 "EM_UNKNOWN_BF",
3039 "EM_UNKNOWN_C0",
3040 "EM_LINELENGTH",
3041 "EM_REPLACESEL",
3042 "EM_UNKNOWN_C3",
3043 "EM_GETLINE",
3044 "EM_LIMITTEXT",
3045 "EM_CANUNDO",
3046 "EM_UNDO",
3047 "EM_FMTLINES",
3048 "EM_LINEFROMCHAR",
3049 "EM_UNKNOWN_CA",
3050 "EM_SETTABSTOPS",
3051 "EM_SETPASSWORDCHAR",
3052 "EM_EMPTYUNDOBUFFER",
3053 "EM_GETFIRSTVISIBLELINE",
3054 "EM_SETREADONLY",
3055 "EM_SETWORDBREAKPROC",
3056 "EM_GETWORDBREAKPROC",
3057 "EM_GETPASSWORDCHAR",
3058 "EM_SETMARGINS",
3059 "EM_GETMARGINS",
3060 "EM_GETLIMITTEXT",
3061 "EM_POSFROMCHAR",
3062 "EM_CHARFROMPOS",
3063 "EM_SETIMESTATUS",
3064 "EM_GETIMESTATUS"
3067 static const char * const richedit_messages[] = {
3068 "EM_CANPASTE",
3069 "EM_DISPLAYBAND",
3070 "EM_EXGETSEL",
3071 "EM_EXLIMITTEXT",
3072 "EM_EXLINEFROMCHAR",
3073 "EM_EXSETSEL",
3074 "EM_FINDTEXT",
3075 "EM_FORMATRANGE",
3076 "EM_GETCHARFORMAT",
3077 "EM_GETEVENTMASK",
3078 "EM_GETOLEINTERFACE",
3079 "EM_GETPARAFORMAT",
3080 "EM_GETSELTEXT",
3081 "EM_HIDESELECTION",
3082 "EM_PASTESPECIAL",
3083 "EM_REQUESTRESIZE",
3084 "EM_SELECTIONTYPE",
3085 "EM_SETBKGNDCOLOR",
3086 "EM_SETCHARFORMAT",
3087 "EM_SETEVENTMASK",
3088 "EM_SETOLECALLBACK",
3089 "EM_SETPARAFORMAT",
3090 "EM_SETTARGETDEVICE",
3091 "EM_STREAMIN",
3092 "EM_STREAMOUT",
3093 "EM_GETTEXTRANGE",
3094 "EM_FINDWORDBREAK",
3095 "EM_SETOPTIONS",
3096 "EM_GETOPTIONS",
3097 "EM_FINDTEXTEX",
3098 "EM_GETWORDBREAKPROCEX",
3099 "EM_SETWORDBREAKPROCEX",
3100 "EM_SETUNDOLIMIT",
3101 "EM_UNKNOWN_USER_83",
3102 "EM_REDO",
3103 "EM_CANREDO",
3104 "EM_GETUNDONAME",
3105 "EM_GETREDONAME",
3106 "EM_STOPGROUPTYPING",
3107 "EM_SETTEXTMODE",
3108 "EM_GETTEXTMODE",
3109 "EM_AUTOURLDETECT",
3110 "EM_GETAUTOURLDETECT",
3111 "EM_SETPALETTE",
3112 "EM_GETTEXTEX",
3113 "EM_GETTEXTLENGTHEX",
3114 "EM_SHOWSCROLLBAR",
3115 "EM_SETTEXTEX",
3116 "EM_UNKNOWN_USER_98",
3117 "EM_UNKNOWN_USER_99",
3118 "EM_SETPUNCTUATION",
3119 "EM_GETPUNCTUATION",
3120 "EM_SETWORDWRAPMODE",
3121 "EM_GETWORDWRAPMODE",
3122 "EM_SETIMECOLOR",
3123 "EM_GETIMECOLOR",
3124 "EM_SETIMEOPTIONS",
3125 "EM_GETIMEOPTIONS",
3126 "EM_CONVPOSITION",
3127 "EM_UNKNOWN_USER_109",
3128 "EM_UNKNOWN_USER_110",
3129 "EM_UNKNOWN_USER_111",
3130 "EM_UNKNOWN_USER_112",
3131 "EM_UNKNOWN_USER_113",
3132 "EM_UNKNOWN_USER_114",
3133 "EM_UNKNOWN_USER_115",
3134 "EM_UNKNOWN_USER_116",
3135 "EM_UNKNOWN_USER_117",
3136 "EM_UNKNOWN_USER_118",
3137 "EM_UNKNOWN_USER_119",
3138 "EM_SETLANGOPTIONS",
3139 "EM_GETLANGOPTIONS",
3140 "EM_GETIMECOMPMODE",
3141 "EM_FINDTEXTW",
3142 "EM_FINDTEXTEXW",
3143 "EM_RECONVERSION",
3144 "EM_SETIMEMODEBIAS",
3145 "EM_GETIMEMODEBIAS"
3148 static const char *
3149 get_msg_name(UINT msg)
3151 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3152 return edit_messages[msg - EM_GETSEL];
3153 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3154 return richedit_messages[msg - EM_CANPASTE];
3155 return "";
3158 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3160 int x,y;
3161 BOOL isExact;
3162 ME_Cursor cursor; /* The start of the clicked text. */
3164 ENLINK info;
3165 x = (short)LOWORD(lParam);
3166 y = (short)HIWORD(lParam);
3167 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3168 if (!isExact) return;
3170 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3171 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3172 { /* The clicked run has CFE_LINK set */
3173 ME_DisplayItem *di;
3175 info.nmhdr.hwndFrom = NULL;
3176 info.nmhdr.idFrom = 0;
3177 info.nmhdr.code = EN_LINK;
3178 info.msg = msg;
3179 info.wParam = wParam;
3180 info.lParam = lParam;
3181 cursor.nOffset = 0;
3183 /* find the first contiguous run with CFE_LINK set */
3184 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3185 for (di = cursor.pRun->prev;
3186 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3187 di = di->prev)
3189 info.chrg.cpMin -= di->member.run.len;
3192 /* find the last contiguous run with CFE_LINK set */
3193 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3194 for (di = cursor.pRun->next;
3195 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3196 di = di->next)
3198 info.chrg.cpMax += di->member.run.len;
3201 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3205 void ME_ReplaceSel(ME_TextEditor *editor, BOOL can_undo, const WCHAR *str, int len)
3207 int from, to, nStartCursor;
3208 ME_Style *style;
3210 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3211 style = ME_GetSelectionInsertStyle(editor);
3212 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3213 ME_InsertTextFromCursor(editor, 0, str, len, style);
3214 ME_ReleaseStyle(style);
3215 /* drop temporary style if line end */
3217 * FIXME question: does abc\n mean: put abc,
3218 * clear temp style, put \n? (would require a change)
3220 if (len>0 && str[len-1] == '\n')
3221 ME_ClearTempStyle(editor);
3222 ME_CommitUndo(editor);
3223 ME_UpdateSelectionLinkAttribute(editor);
3224 if (!can_undo)
3225 ME_EmptyUndoStack(editor);
3226 ME_UpdateRepaint(editor, FALSE);
3229 static void ME_SetText(ME_TextEditor *editor, void *text, BOOL unicode)
3231 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3232 int textLen;
3234 LPWSTR wszText = ME_ToUnicode(codepage, text, &textLen);
3236 if (textLen > 0)
3238 int len = -1;
3240 /* uses default style! */
3241 if (!(editor->styleFlags & ES_MULTILINE))
3243 WCHAR *p = wszText;
3245 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3246 len = p - wszText;
3248 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3250 ME_EndToUnicode(codepage, wszText);
3253 static LRESULT ME_WmCreate(ME_TextEditor *editor, LPARAM lParam, BOOL unicode)
3255 CREATESTRUCTW *createW = (CREATESTRUCTW*)lParam;
3256 CREATESTRUCTA *createA = (CREATESTRUCTA*)lParam;
3257 void *text = NULL;
3258 INT max;
3260 if (lParam)
3261 text = unicode ? (void*)createW->lpszName : (void*)createA->lpszName;
3263 ME_SetDefaultFormatRect(editor);
3265 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3266 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3267 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3269 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3270 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3272 if (editor->styleFlags & ES_DISABLENOSCROLL)
3274 if (editor->styleFlags & WS_VSCROLL)
3276 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3277 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3279 if (editor->styleFlags & WS_HSCROLL)
3281 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3282 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3286 if (text)
3288 ME_SetText(editor, text, unicode);
3289 ME_SetCursorToStart(editor, &editor->pCursors[0]);
3290 ME_SetCursorToStart(editor, &editor->pCursors[1]);
3293 ME_CommitUndo(editor);
3294 ME_WrapMarkedParagraphs(editor);
3295 ME_MoveCaret(editor);
3296 return 0;
3300 #define UNSUPPORTED_MSG(e) \
3301 case e: \
3302 FIXME(#e ": stub\n"); \
3303 *phresult = S_FALSE; \
3304 return 0;
3306 /* Handle messages for windowless and windowed richedit controls.
3308 * The LRESULT that is returned is a return value for window procs,
3309 * and the phresult parameter is the COM return code needed by the
3310 * text services interface. */
3311 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3312 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3314 *phresult = S_OK;
3316 switch(msg) {
3318 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3319 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3320 UNSUPPORTED_MSG(EM_FMTLINES)
3321 UNSUPPORTED_MSG(EM_FORMATRANGE)
3322 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3323 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3324 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3325 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3326 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3327 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3328 UNSUPPORTED_MSG(EM_GETREDONAME)
3329 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3330 UNSUPPORTED_MSG(EM_GETUNDONAME)
3331 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3332 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3333 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3334 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3335 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3336 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3337 UNSUPPORTED_MSG(EM_SETMARGINS)
3338 UNSUPPORTED_MSG(EM_SETPALETTE)
3339 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3340 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3341 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3343 /* Messages specific to Richedit controls */
3345 case EM_STREAMIN:
3346 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3347 case EM_STREAMOUT:
3348 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3349 case WM_GETDLGCODE:
3351 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3353 if (lParam)
3354 editor->bDialogMode = TRUE;
3355 if (editor->styleFlags & ES_MULTILINE)
3356 code |= DLGC_WANTMESSAGE;
3357 if (!(editor->styleFlags & ES_SAVESEL))
3358 code |= DLGC_HASSETSEL;
3359 return code;
3361 case EM_EMPTYUNDOBUFFER:
3362 ME_EmptyUndoStack(editor);
3363 return 0;
3364 case EM_GETSEL:
3366 /* Note: wParam/lParam can be NULL */
3367 UINT from, to;
3368 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3369 PUINT pto = lParam ? (PUINT)lParam : &to;
3370 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3371 if ((*pfrom|*pto) & 0xFFFF0000)
3372 return -1;
3373 return MAKELONG(*pfrom,*pto);
3375 case EM_EXGETSEL:
3377 CHARRANGE *pRange = (CHARRANGE *)lParam;
3378 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3379 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3380 return 0;
3382 case EM_SETUNDOLIMIT:
3384 if ((int)wParam < 0)
3385 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3386 else
3387 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3388 /* Setting a max stack size keeps wine from getting killed
3389 for hogging memory. Windows allocates all this memory at once, so
3390 no program would realistically set a value above our maximum. */
3391 return editor->nUndoLimit;
3393 case EM_CANUNDO:
3394 return !list_empty( &editor->undo_stack );
3395 case EM_CANREDO:
3396 return !list_empty( &editor->redo_stack );
3397 case WM_UNDO: /* FIXME: actually not the same */
3398 case EM_UNDO:
3399 return ME_Undo(editor);
3400 case EM_REDO:
3401 return ME_Redo(editor);
3402 case EM_GETOPTIONS:
3404 /* these flags are equivalent to the ES_* counterparts */
3405 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3406 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3407 DWORD settings = editor->styleFlags & mask;
3409 return settings;
3411 case EM_SETFONTSIZE:
3413 CHARFORMAT2W cf;
3414 LONG tmp_size, size;
3415 BOOL is_increase = ((LONG)wParam > 0);
3417 if (editor->mode & TM_PLAINTEXT)
3418 return FALSE;
3420 cf.cbSize = sizeof(cf);
3421 cf.dwMask = CFM_SIZE;
3422 ME_GetSelectionCharFormat(editor, &cf);
3423 tmp_size = (cf.yHeight / 20) + wParam;
3425 if (tmp_size <= 1)
3426 size = 1;
3427 else if (tmp_size > 12 && tmp_size < 28 && tmp_size % 2)
3428 size = tmp_size + (is_increase ? 1 : -1);
3429 else if (tmp_size > 28 && tmp_size < 36)
3430 size = is_increase ? 36 : 28;
3431 else if (tmp_size > 36 && tmp_size < 48)
3432 size = is_increase ? 48 : 36;
3433 else if (tmp_size > 48 && tmp_size < 72)
3434 size = is_increase ? 72 : 48;
3435 else if (tmp_size > 72 && tmp_size < 80)
3436 size = is_increase ? 80 : 72;
3437 else if (tmp_size > 80 && tmp_size < 1638)
3438 size = 10 * (is_increase ? (tmp_size / 10 + 1) : (tmp_size / 10));
3439 else if (tmp_size >= 1638)
3440 size = 1638;
3441 else
3442 size = tmp_size;
3444 cf.yHeight = size * 20; /* convert twips to points */
3445 ME_SetSelectionCharFormat(editor, &cf);
3446 ME_CommitUndo(editor);
3447 ME_WrapMarkedParagraphs(editor);
3448 ME_UpdateScrollBar(editor);
3449 ME_Repaint(editor);
3451 return TRUE;
3453 case EM_SETOPTIONS:
3455 /* these flags are equivalent to ES_* counterparts, except for
3456 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3457 * but is still stored in editor->styleFlags. */
3458 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3459 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3460 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3461 DWORD settings = mask & editor->styleFlags;
3462 DWORD oldSettings = settings;
3463 DWORD changedSettings;
3465 switch(wParam)
3467 case ECOOP_SET:
3468 settings = lParam;
3469 break;
3470 case ECOOP_OR:
3471 settings |= lParam;
3472 break;
3473 case ECOOP_AND:
3474 settings &= lParam;
3475 break;
3476 case ECOOP_XOR:
3477 settings ^= lParam;
3479 changedSettings = oldSettings ^ settings;
3481 if (changedSettings) {
3482 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3484 if (changedSettings & ECO_SELECTIONBAR)
3486 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3487 if (settings & ECO_SELECTIONBAR) {
3488 assert(!editor->selofs);
3489 editor->selofs = SELECTIONBAR_WIDTH;
3490 editor->rcFormat.left += editor->selofs;
3491 } else {
3492 editor->rcFormat.left -= editor->selofs;
3493 editor->selofs = 0;
3495 ME_RewrapRepaint(editor);
3498 if (changedSettings & settings & ECO_VERTICAL)
3499 FIXME("ECO_VERTICAL not implemented yet!\n");
3500 if (changedSettings & settings & ECO_AUTOHSCROLL)
3501 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3502 if (changedSettings & settings & ECO_AUTOVSCROLL)
3503 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3504 if (changedSettings & settings & ECO_NOHIDESEL)
3505 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3506 if (changedSettings & settings & ECO_WANTRETURN)
3507 FIXME("ECO_WANTRETURN not implemented yet!\n");
3508 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3509 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3512 return settings;
3514 case EM_SETSEL:
3516 return handle_EM_EXSETSEL( editor, wParam, lParam );
3518 case EM_SETSCROLLPOS:
3520 POINT *point = (POINT *)lParam;
3521 ME_ScrollAbs(editor, point->x, point->y);
3522 return 0;
3524 case EM_AUTOURLDETECT:
3526 if (wParam==1 || wParam ==0)
3528 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3529 return 0;
3531 return E_INVALIDARG;
3533 case EM_GETAUTOURLDETECT:
3535 return editor->AutoURLDetect_bEnable;
3537 case EM_EXSETSEL:
3539 CHARRANGE range = *(CHARRANGE *)lParam;
3541 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3543 case EM_SHOWSCROLLBAR:
3545 DWORD flags;
3547 switch (wParam)
3549 case SB_HORZ:
3550 flags = WS_HSCROLL;
3551 break;
3552 case SB_VERT:
3553 flags = WS_VSCROLL;
3554 break;
3555 case SB_BOTH:
3556 flags = WS_HSCROLL|WS_VSCROLL;
3557 break;
3558 default:
3559 return 0;
3562 if (lParam) {
3563 editor->styleFlags |= flags;
3564 if (flags & WS_HSCROLL)
3565 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3566 editor->nTotalWidth > editor->sizeWindow.cx);
3567 if (flags & WS_VSCROLL)
3568 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3569 editor->nTotalLength > editor->sizeWindow.cy);
3570 } else {
3571 editor->styleFlags &= ~flags;
3572 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3574 return 0;
3576 case EM_SETTEXTEX:
3578 LPWSTR wszText;
3579 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3580 int from, to, len;
3581 ME_Style *style;
3582 BOOL bRtf, bUnicode, bSelection, bUTF8;
3583 int oldModify = editor->nModifyStep;
3584 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3586 if (!pStruct) return 0;
3588 /* If we detect ascii rtf at the start of the string,
3589 * we know it isn't unicode. */
3590 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3591 !strncmp((char *)lParam, "{\\urtf", 6)));
3592 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3593 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3595 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3596 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3597 pStruct->flags, pStruct->codepage);
3599 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3600 if (bSelection) {
3601 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3602 style = ME_GetSelectionInsertStyle(editor);
3603 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3604 } else {
3605 ME_Cursor start;
3606 ME_SetCursorToStart(editor, &start);
3607 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3608 style = editor->pBuffer->pDefaultStyle;
3611 if (bRtf) {
3612 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3613 if (bSelection) {
3614 /* FIXME: The length returned doesn't include the rtf control
3615 * characters, only the actual text. */
3616 len = lParam ? strlen((char *)lParam) : 0;
3618 } else {
3619 if (bUTF8 && !bUnicode) {
3620 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3621 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3622 ME_EndToUnicode(CP_UTF8, wszText);
3623 } else {
3624 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3625 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3626 ME_EndToUnicode(pStruct->codepage, wszText);
3630 if (bSelection) {
3631 ME_ReleaseStyle(style);
3632 ME_UpdateSelectionLinkAttribute(editor);
3633 } else {
3634 ME_Cursor cursor;
3635 len = 1;
3636 ME_SetCursorToStart(editor, &cursor);
3637 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3639 ME_CommitUndo(editor);
3640 if (!(pStruct->flags & ST_KEEPUNDO))
3642 editor->nModifyStep = oldModify;
3643 ME_EmptyUndoStack(editor);
3645 ME_UpdateRepaint(editor, FALSE);
3646 return len;
3648 case EM_SETBKGNDCOLOR:
3650 LRESULT lColor;
3651 if (editor->rgbBackColor != -1) {
3652 DeleteObject(editor->hbrBackground);
3653 lColor = editor->rgbBackColor;
3655 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3657 if (wParam)
3659 editor->rgbBackColor = -1;
3660 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3662 else
3664 editor->rgbBackColor = lParam;
3665 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3667 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3668 ITextHost_TxViewChange(editor->texthost, TRUE);
3669 return lColor;
3671 case EM_GETMODIFY:
3672 return editor->nModifyStep == 0 ? 0 : -1;
3673 case EM_SETMODIFY:
3675 if (wParam)
3676 editor->nModifyStep = 1;
3677 else
3678 editor->nModifyStep = 0;
3680 return 0;
3682 case EM_SETREADONLY:
3684 if (wParam)
3685 editor->styleFlags |= ES_READONLY;
3686 else
3687 editor->styleFlags &= ~ES_READONLY;
3688 return 1;
3690 case EM_SETEVENTMASK:
3692 DWORD nOldMask = editor->nEventMask;
3694 editor->nEventMask = lParam;
3695 return nOldMask;
3697 case EM_GETEVENTMASK:
3698 return editor->nEventMask;
3699 case EM_SETCHARFORMAT:
3701 CHARFORMAT2W buf, *p;
3702 BOOL bRepaint = TRUE;
3703 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3704 if (p == NULL) return 0;
3705 if (wParam & SCF_ALL) {
3706 if (editor->mode & TM_PLAINTEXT) {
3707 ME_SetDefaultCharFormat(editor, p);
3708 } else {
3709 ME_Cursor start;
3710 ME_SetCursorToStart(editor, &start);
3711 ME_SetCharFormat(editor, &start, NULL, p);
3712 editor->nModifyStep = 1;
3714 } else if (wParam & SCF_SELECTION) {
3715 if (editor->mode & TM_PLAINTEXT)
3716 return 0;
3717 if (wParam & SCF_WORD) {
3718 ME_Cursor start;
3719 ME_Cursor end = editor->pCursors[0];
3720 ME_MoveCursorWords(editor, &end, +1);
3721 start = end;
3722 ME_MoveCursorWords(editor, &start, -1);
3723 ME_SetCharFormat(editor, &start, &end, p);
3725 bRepaint = ME_IsSelection(editor);
3726 ME_SetSelectionCharFormat(editor, p);
3727 if (bRepaint) editor->nModifyStep = 1;
3728 } else { /* SCF_DEFAULT */
3729 ME_SetDefaultCharFormat(editor, p);
3731 ME_CommitUndo(editor);
3732 if (bRepaint)
3734 ME_WrapMarkedParagraphs(editor);
3735 ME_UpdateScrollBar(editor);
3736 ME_Repaint(editor);
3738 return 1;
3740 case EM_GETCHARFORMAT:
3742 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3743 if (dst->cbSize != sizeof(CHARFORMATA) &&
3744 dst->cbSize != sizeof(CHARFORMATW) &&
3745 dst->cbSize != sizeof(CHARFORMAT2A) &&
3746 dst->cbSize != sizeof(CHARFORMAT2W))
3747 return 0;
3748 tmp.cbSize = sizeof(tmp);
3749 if (!wParam)
3750 ME_GetDefaultCharFormat(editor, &tmp);
3751 else
3752 ME_GetSelectionCharFormat(editor, &tmp);
3753 ME_CopyToCFAny(dst, &tmp);
3754 return tmp.dwMask;
3756 case EM_SETPARAFORMAT:
3758 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3759 ME_WrapMarkedParagraphs(editor);
3760 ME_UpdateScrollBar(editor);
3761 ME_Repaint(editor);
3762 ME_CommitUndo(editor);
3763 return result;
3765 case EM_GETPARAFORMAT:
3766 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3767 return ((PARAFORMAT2 *)lParam)->dwMask;
3768 case EM_GETFIRSTVISIBLELINE:
3770 ME_DisplayItem *p = editor->pBuffer->pFirst;
3771 int y = editor->vert_si.nPos;
3772 int ypara = 0;
3773 int count = 0;
3774 int ystart, yend;
3775 while(p) {
3776 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3777 if (p->type == diTextEnd)
3778 break;
3779 if (p->type == diParagraph) {
3780 ypara = p->member.para.pt.y;
3781 continue;
3783 ystart = ypara + p->member.row.pt.y;
3784 yend = ystart + p->member.row.nHeight;
3785 if (y < yend) {
3786 break;
3788 count++;
3790 return count;
3792 case EM_HIDESELECTION:
3794 editor->bHideSelection = (wParam != 0);
3795 ME_InvalidateSelection(editor);
3796 return 0;
3798 case EM_LINESCROLL:
3800 if (!(editor->styleFlags & ES_MULTILINE))
3801 return FALSE;
3802 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3803 return TRUE;
3805 case WM_CLEAR:
3807 int from, to;
3808 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3809 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3810 ME_CommitUndo(editor);
3811 ME_UpdateRepaint(editor, TRUE);
3812 return 0;
3814 case EM_REPLACESEL:
3816 int len = 0;
3817 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3818 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3820 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3822 ME_ReplaceSel(editor, !!wParam, wszText, len);
3823 ME_EndToUnicode(codepage, wszText);
3824 return len;
3826 case EM_SCROLLCARET:
3827 ME_EnsureVisible(editor, &editor->pCursors[0]);
3828 return 0;
3829 case WM_SETFONT:
3831 LOGFONTW lf;
3832 CHARFORMAT2W fmt;
3833 HDC hDC;
3834 BOOL bRepaint = LOWORD(lParam);
3836 if (!wParam)
3837 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3839 if (!GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf))
3840 return 0;
3842 hDC = ITextHost_TxGetDC(editor->texthost);
3843 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3844 ITextHost_TxReleaseDC(editor->texthost, hDC);
3845 if (editor->mode & TM_RICHTEXT) {
3846 ME_Cursor start;
3847 ME_SetCursorToStart(editor, &start);
3848 ME_SetCharFormat(editor, &start, NULL, &fmt);
3850 ME_SetDefaultCharFormat(editor, &fmt);
3852 ME_CommitUndo(editor);
3853 ME_MarkAllForWrapping(editor);
3854 ME_WrapMarkedParagraphs(editor);
3855 ME_UpdateScrollBar(editor);
3856 if (bRepaint)
3857 ME_Repaint(editor);
3858 return 0;
3860 case WM_SETTEXT:
3862 ME_Cursor cursor;
3863 ME_SetCursorToStart(editor, &cursor);
3864 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3865 if (lParam)
3867 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3868 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3869 !strncmp((char *)lParam, "{\\urtf", 6))
3871 /* Undocumented: WM_SETTEXT supports RTF text */
3872 ME_StreamInRTFString(editor, 0, (char *)lParam);
3874 else
3875 ME_SetText(editor, (void*)lParam, unicode);
3877 else
3878 TRACE("WM_SETTEXT - NULL\n");
3879 ME_SetCursorToStart(editor, &cursor);
3880 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3881 ME_SetSelection(editor, 0, 0);
3882 editor->nModifyStep = 0;
3883 ME_CommitUndo(editor);
3884 ME_EmptyUndoStack(editor);
3885 ME_UpdateRepaint(editor, FALSE);
3886 return 1;
3888 case EM_CANPASTE:
3890 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3891 if (IsClipboardFormatAvailable(nRTFFormat))
3892 return TRUE;
3893 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3894 return TRUE;
3895 return FALSE;
3897 case WM_PASTE:
3898 case WM_MBUTTONDOWN:
3899 ME_Paste(editor);
3900 return 0;
3901 case WM_CUT:
3902 case WM_COPY:
3904 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3905 int nChars = nTo - nFrom;
3906 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3908 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3910 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3911 ME_CommitUndo(editor);
3912 ME_UpdateRepaint(editor, TRUE);
3914 return 0;
3916 case WM_GETTEXTLENGTH:
3918 GETTEXTLENGTHEX how;
3920 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3921 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3922 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3923 return ME_GetTextLengthEx(editor, &how);
3925 case EM_GETTEXTLENGTHEX:
3926 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3927 case WM_GETTEXT:
3929 GETTEXTEX ex;
3930 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3931 ex.flags = GT_USECRLF;
3932 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3933 ex.lpDefaultChar = NULL;
3934 ex.lpUsedDefChar = NULL;
3935 return ME_GetTextEx(editor, &ex, lParam);
3937 case EM_GETTEXTEX:
3938 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3939 case EM_GETSELTEXT:
3941 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3942 ME_Cursor *from = &editor->pCursors[nStartCur];
3943 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3944 nTo - nFrom, unicode);
3946 case EM_GETSCROLLPOS:
3948 POINT *point = (POINT *)lParam;
3949 point->x = editor->horz_si.nPos;
3950 point->y = editor->vert_si.nPos;
3951 /* 16-bit scaled value is returned as stored in scrollinfo */
3952 if (editor->horz_si.nMax > 0xffff)
3953 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3954 if (editor->vert_si.nMax > 0xffff)
3955 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3956 return 1;
3958 case EM_GETTEXTRANGE:
3960 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3961 ME_Cursor start;
3962 int nStart = rng->chrg.cpMin;
3963 int nEnd = rng->chrg.cpMax;
3964 int textlength = ME_GetTextLength(editor);
3966 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3967 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3968 if (nStart < 0) return 0;
3969 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3970 nEnd = textlength;
3971 if (nStart >= nEnd) return 0;
3973 ME_CursorFromCharOfs(editor, nStart, &start);
3974 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3976 case EM_GETLINE:
3978 ME_DisplayItem *run;
3979 const unsigned int nMaxChars = *(WORD *) lParam;
3980 unsigned int nCharsLeft = nMaxChars;
3981 char *dest = (char *) lParam;
3982 BOOL wroteNull = FALSE;
3984 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3985 unicode ? "Unicode" : "Ansi");
3987 run = ME_FindRowWithNumber(editor, wParam);
3988 if (run == NULL)
3989 return 0;
3991 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3992 && run->type == diRun)
3994 WCHAR *str = get_text( &run->member.run, 0 );
3995 unsigned int nCopy;
3997 nCopy = min(nCharsLeft, run->member.run.len);
3999 if (unicode)
4000 memcpy(dest, str, nCopy * sizeof(WCHAR));
4001 else
4002 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
4003 nCharsLeft, NULL, NULL);
4004 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
4005 nCharsLeft -= nCopy;
4008 /* append line termination, space allowing */
4009 if (nCharsLeft > 0)
4011 if (unicode)
4012 *((WCHAR *)dest) = '\0';
4013 else
4014 *dest = '\0';
4015 nCharsLeft--;
4016 wroteNull = TRUE;
4019 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
4020 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
4022 case EM_GETLINECOUNT:
4024 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
4025 int nRows = 0;
4027 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
4029 while (item != editor->pBuffer->pLast)
4031 assert(item->type == diParagraph);
4032 prev_para = ME_FindItemBack(item, diRun);
4033 if (prev_para) {
4034 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
4036 nRows += item->member.para.nRows;
4037 item = item->member.para.next_para;
4039 last_para = ME_FindItemBack(item, diRun);
4040 assert(last_para);
4041 assert(last_para->member.run.nFlags & MERF_ENDPARA);
4042 if (editor->bEmulateVersion10 && prev_para &&
4043 last_para->member.run.nCharOfs == 0 &&
4044 prev_para->member.run.len == 1 &&
4045 *get_text( &prev_para->member.run, 0 ) == '\r')
4047 /* In 1.0 emulation, the last solitary \r at the very end of the text
4048 (if one exists) is NOT a line break.
4049 FIXME: this is an ugly hack. This should have a more regular model. */
4050 nRows--;
4053 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
4054 return max(1, nRows);
4056 case EM_LINEFROMCHAR:
4058 if (wParam == -1)
4059 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4060 else
4061 return ME_RowNumberFromCharOfs(editor, wParam);
4063 case EM_EXLINEFROMCHAR:
4065 if (lParam == -1)
4066 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4067 else
4068 return ME_RowNumberFromCharOfs(editor, lParam);
4070 case EM_LINEINDEX:
4072 ME_DisplayItem *item, *para;
4073 int nCharOfs;
4075 if (wParam == -1)
4076 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
4077 else
4078 item = ME_FindRowWithNumber(editor, wParam);
4079 if (!item)
4080 return -1;
4081 para = ME_GetParagraph(item);
4082 item = ME_FindItemFwd(item, diRun);
4083 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
4084 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
4085 return nCharOfs;
4087 case EM_LINELENGTH:
4089 ME_DisplayItem *item, *item_end;
4090 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
4091 ME_DisplayItem *para, *run;
4093 if (wParam > ME_GetTextLength(editor))
4094 return 0;
4095 if (wParam == -1)
4097 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
4098 return 0;
4100 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
4101 item = ME_RowStart(run);
4102 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
4103 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
4104 if (item_end->type == diStartRow) {
4105 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
4106 } else {
4107 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
4108 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
4109 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
4111 nChars = nNextLineOfs - nThisLineOfs;
4112 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
4113 return nChars;
4115 case EM_EXLIMITTEXT:
4117 if ((int)lParam < 0)
4118 return 0;
4119 if (lParam == 0)
4120 editor->nTextLimit = 65536;
4121 else
4122 editor->nTextLimit = (int) lParam;
4123 return 0;
4125 case EM_LIMITTEXT:
4127 if (wParam == 0)
4128 editor->nTextLimit = 65536;
4129 else
4130 editor->nTextLimit = (int) wParam;
4131 return 0;
4133 case EM_GETLIMITTEXT:
4135 return editor->nTextLimit;
4137 case EM_FINDTEXT:
4139 LRESULT r;
4140 if(!unicode){
4141 FINDTEXTA *ft = (FINDTEXTA *)lParam;
4142 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
4143 WCHAR *tmp;
4145 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4146 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
4147 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
4148 FREE_OBJ( tmp );
4149 }else{
4150 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4151 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4153 return r;
4155 case EM_FINDTEXTEX:
4157 LRESULT r;
4158 if(!unicode){
4159 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
4160 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
4161 WCHAR *tmp;
4163 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4164 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
4165 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
4166 FREE_OBJ( tmp );
4167 }else{
4168 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4169 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4171 return r;
4173 case EM_FINDTEXTW:
4175 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4176 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4178 case EM_FINDTEXTEXW:
4180 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4181 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4183 case EM_GETZOOM:
4184 if (!wParam || !lParam)
4185 return FALSE;
4186 *(int *)wParam = editor->nZoomNumerator;
4187 *(int *)lParam = editor->nZoomDenominator;
4188 return TRUE;
4189 case EM_SETZOOM:
4190 return ME_SetZoom(editor, wParam, lParam);
4191 case EM_CHARFROMPOS:
4193 ME_Cursor cursor;
4194 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4195 &cursor, NULL))
4196 return ME_GetCursorOfs(&cursor);
4197 else
4198 return -1;
4200 case EM_POSFROMCHAR:
4202 ME_DisplayItem *pPara, *pRun;
4203 int nCharOfs, nOffset, nLength;
4204 POINTL pt = {0,0};
4206 nCharOfs = wParam;
4207 /* detect which API version we're dealing with */
4208 if (wParam >= 0x40000)
4209 nCharOfs = lParam;
4210 nLength = ME_GetTextLength(editor);
4211 nCharOfs = min(nCharOfs, nLength);
4212 nCharOfs = max(nCharOfs, 0);
4214 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4215 assert(pRun->type == diRun);
4216 pt.y = pRun->member.run.pt.y;
4217 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4218 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4219 pt.x += editor->rcFormat.left;
4221 pt.x -= editor->horz_si.nPos;
4222 pt.y -= editor->vert_si.nPos;
4224 if (wParam >= 0x40000) {
4225 *(POINTL *)wParam = pt;
4227 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4229 case WM_CREATE:
4230 return ME_WmCreate(editor, lParam, unicode);
4231 case WM_DESTROY:
4232 ME_DestroyEditor(editor);
4233 return 0;
4234 case WM_SETCURSOR:
4236 POINT cursor_pos;
4237 if (wParam == (WPARAM)editor->hWnd && GetCursorPos(&cursor_pos) &&
4238 ScreenToClient(editor->hWnd, &cursor_pos))
4239 ME_LinkNotify(editor, msg, 0, MAKELPARAM(cursor_pos.x, cursor_pos.y));
4240 return ME_SetCursor(editor);
4242 case WM_LBUTTONDBLCLK:
4243 case WM_LBUTTONDOWN:
4245 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4246 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4247 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4248 return 0;
4249 ITextHost_TxSetFocus(editor->texthost);
4250 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4251 ME_CalculateClickCount(editor, msg, wParam, lParam));
4252 ITextHost_TxSetCapture(editor->texthost, TRUE);
4253 editor->bMouseCaptured = TRUE;
4254 ME_LinkNotify(editor, msg, wParam, lParam);
4255 if (!ME_SetCursor(editor)) goto do_default;
4256 break;
4258 case WM_MOUSEMOVE:
4259 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4260 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4261 return 0;
4262 if (editor->bMouseCaptured)
4263 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4264 else
4265 ME_LinkNotify(editor, msg, wParam, lParam);
4266 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4267 if (editor->bMouseCaptured)
4268 ME_SetCursor(editor);
4269 break;
4270 case WM_LBUTTONUP:
4271 if (editor->bMouseCaptured) {
4272 ITextHost_TxSetCapture(editor->texthost, FALSE);
4273 editor->bMouseCaptured = FALSE;
4275 if (editor->nSelectionType == stDocument)
4276 editor->nSelectionType = stPosition;
4277 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4278 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4279 return 0;
4280 else
4282 ME_SetCursor(editor);
4283 ME_LinkNotify(editor, msg, wParam, lParam);
4285 break;
4286 case WM_RBUTTONUP:
4287 case WM_RBUTTONDOWN:
4288 case WM_RBUTTONDBLCLK:
4289 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4290 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4291 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4292 return 0;
4293 ME_LinkNotify(editor, msg, wParam, lParam);
4294 goto do_default;
4295 case WM_CONTEXTMENU:
4296 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4297 goto do_default;
4298 break;
4299 case WM_SETFOCUS:
4300 editor->bHaveFocus = TRUE;
4301 ME_ShowCaret(editor);
4302 ME_SendOldNotify(editor, EN_SETFOCUS);
4303 return 0;
4304 case WM_KILLFOCUS:
4305 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4306 editor->bHaveFocus = FALSE;
4307 editor->wheel_remain = 0;
4308 ME_HideCaret(editor);
4309 ME_SendOldNotify(editor, EN_KILLFOCUS);
4310 return 0;
4311 case WM_COMMAND:
4312 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4313 return 0;
4314 case WM_KEYUP:
4315 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4316 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4317 return 0;
4318 goto do_default;
4319 case WM_KEYDOWN:
4320 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4321 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4322 return 0;
4323 if (ME_KeyDown(editor, LOWORD(wParam)))
4324 return 0;
4325 goto do_default;
4326 case WM_CHAR:
4327 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4328 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4329 return 0;
4330 return ME_Char(editor, wParam, lParam, unicode);
4331 case WM_UNICHAR:
4332 if (unicode)
4334 if(wParam == UNICODE_NOCHAR) return TRUE;
4335 if(wParam <= 0x000fffff)
4337 if(wParam > 0xffff) /* convert to surrogates */
4339 wParam -= 0x10000;
4340 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4341 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4342 } else {
4343 ME_Char(editor, wParam, 0, TRUE);
4346 return 0;
4348 break;
4349 case EM_STOPGROUPTYPING:
4350 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4351 return 0;
4352 case WM_HSCROLL:
4354 const int scrollUnit = 7;
4356 switch(LOWORD(wParam))
4358 case SB_LEFT:
4359 ME_ScrollAbs(editor, 0, 0);
4360 break;
4361 case SB_RIGHT:
4362 ME_ScrollAbs(editor,
4363 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4364 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4365 break;
4366 case SB_LINELEFT:
4367 ME_ScrollLeft(editor, scrollUnit);
4368 break;
4369 case SB_LINERIGHT:
4370 ME_ScrollRight(editor, scrollUnit);
4371 break;
4372 case SB_PAGELEFT:
4373 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4374 break;
4375 case SB_PAGERIGHT:
4376 ME_ScrollRight(editor, editor->sizeWindow.cx);
4377 break;
4378 case SB_THUMBTRACK:
4379 case SB_THUMBPOSITION:
4381 int pos = HIWORD(wParam);
4382 if (editor->horz_si.nMax > 0xffff)
4383 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4384 ME_HScrollAbs(editor, pos);
4385 break;
4388 break;
4390 case EM_SCROLL: /* fall through */
4391 case WM_VSCROLL:
4393 int origNPos;
4394 int lineHeight = get_default_line_height( editor );
4396 origNPos = editor->vert_si.nPos;
4398 switch(LOWORD(wParam))
4400 case SB_TOP:
4401 ME_ScrollAbs(editor, 0, 0);
4402 break;
4403 case SB_BOTTOM:
4404 ME_ScrollAbs(editor,
4405 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4406 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4407 break;
4408 case SB_LINEUP:
4409 ME_ScrollUp(editor,lineHeight);
4410 break;
4411 case SB_LINEDOWN:
4412 ME_ScrollDown(editor,lineHeight);
4413 break;
4414 case SB_PAGEUP:
4415 ME_ScrollUp(editor,editor->sizeWindow.cy);
4416 break;
4417 case SB_PAGEDOWN:
4418 ME_ScrollDown(editor,editor->sizeWindow.cy);
4419 break;
4420 case SB_THUMBTRACK:
4421 case SB_THUMBPOSITION:
4423 int pos = HIWORD(wParam);
4424 if (editor->vert_si.nMax > 0xffff)
4425 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4426 ME_VScrollAbs(editor, pos);
4427 break;
4430 if (msg == EM_SCROLL)
4431 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4432 break;
4434 case WM_MOUSEWHEEL:
4436 int delta;
4437 BOOL ctrl_is_down;
4439 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4440 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4441 return 0;
4443 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4445 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4447 /* if scrolling changes direction, ignore left overs */
4448 if ((delta < 0 && editor->wheel_remain < 0) ||
4449 (delta > 0 && editor->wheel_remain > 0))
4450 editor->wheel_remain += delta;
4451 else
4452 editor->wheel_remain = delta;
4454 if (editor->wheel_remain)
4456 if (ctrl_is_down) {
4457 int numerator;
4458 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4460 numerator = 100;
4461 } else {
4462 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4464 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4465 if (numerator >= 10 && numerator <= 500)
4466 ME_SetZoom(editor, numerator, 100);
4467 } else {
4468 UINT max_lines = 3;
4469 int lines = 0;
4471 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4472 if (max_lines)
4473 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4474 if (lines)
4475 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4478 break;
4480 case EM_GETRECT:
4482 *((RECT *)lParam) = editor->rcFormat;
4483 if (editor->bDefaultFormatRect)
4484 ((RECT *)lParam)->left -= editor->selofs;
4485 return 0;
4487 case EM_SETRECT:
4488 case EM_SETRECTNP:
4490 if (lParam)
4492 int border = 0;
4493 RECT clientRect;
4494 RECT *rc = (RECT *)lParam;
4496 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4497 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4498 if (wParam == 0)
4500 editor->rcFormat.top = max(0, rc->top - border);
4501 editor->rcFormat.left = max(0, rc->left - border);
4502 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4503 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4504 } else if (wParam == 1) {
4505 /* MSDN incorrectly says a wParam value of 1 causes the
4506 * lParam rect to be used as a relative offset,
4507 * however, the tests show it just prevents min/max bound
4508 * checking. */
4509 editor->rcFormat.top = rc->top - border;
4510 editor->rcFormat.left = rc->left - border;
4511 editor->rcFormat.bottom = rc->bottom;
4512 editor->rcFormat.right = rc->right + border;
4513 } else {
4514 return 0;
4516 editor->bDefaultFormatRect = FALSE;
4518 else
4520 ME_SetDefaultFormatRect(editor);
4521 editor->bDefaultFormatRect = TRUE;
4523 ME_MarkAllForWrapping(editor);
4524 ME_WrapMarkedParagraphs(editor);
4525 ME_UpdateScrollBar(editor);
4526 if (msg != EM_SETRECTNP)
4527 ME_Repaint(editor);
4528 return 0;
4530 case EM_REQUESTRESIZE:
4531 ME_SendRequestResize(editor, TRUE);
4532 return 0;
4533 case WM_SETREDRAW:
4534 goto do_default;
4535 case WM_WINDOWPOSCHANGED:
4537 RECT clientRect;
4538 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4540 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4541 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4542 if (editor->bDefaultFormatRect) {
4543 ME_SetDefaultFormatRect(editor);
4544 } else {
4545 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4546 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4548 editor->prevClientRect = clientRect;
4549 ME_RewrapRepaint(editor);
4550 goto do_default;
4552 /* IME messages to make richedit controls IME aware */
4553 case WM_IME_SETCONTEXT:
4554 case WM_IME_CONTROL:
4555 case WM_IME_SELECT:
4556 case WM_IME_COMPOSITIONFULL:
4557 return 0;
4558 case WM_IME_STARTCOMPOSITION:
4560 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4561 ME_DeleteSelection(editor);
4562 ME_CommitUndo(editor);
4563 ME_UpdateRepaint(editor, FALSE);
4564 return 0;
4566 case WM_IME_COMPOSITION:
4568 HIMC hIMC;
4570 ME_Style *style = ME_GetInsertStyle(editor, 0);
4571 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4572 ME_DeleteSelection(editor);
4573 ME_SaveTempStyle(editor);
4574 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4576 LPWSTR lpCompStr = NULL;
4577 DWORD dwBufLen;
4578 DWORD dwIndex = lParam & GCS_RESULTSTR;
4579 if (!dwIndex)
4580 dwIndex = GCS_COMPSTR;
4582 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4583 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4584 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4585 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4586 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4587 HeapFree(GetProcessHeap(), 0, lpCompStr);
4589 if (dwIndex == GCS_COMPSTR)
4590 ME_SetSelection(editor,editor->imeStartIndex,
4591 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4593 ME_ReleaseStyle(style);
4594 ME_CommitUndo(editor);
4595 ME_UpdateRepaint(editor, FALSE);
4596 return 0;
4598 case WM_IME_ENDCOMPOSITION:
4600 ME_DeleteSelection(editor);
4601 editor->imeStartIndex=-1;
4602 return 0;
4604 case EM_GETOLEINTERFACE:
4606 if (!editor->reOle)
4607 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4608 return 0;
4609 *(LPVOID *)lParam = editor->reOle;
4610 IRichEditOle_AddRef(editor->reOle);
4611 return 1;
4613 case EM_GETPASSWORDCHAR:
4615 return editor->cPasswordMask;
4617 case EM_SETOLECALLBACK:
4618 if(editor->lpOleCallback)
4619 IRichEditOleCallback_Release(editor->lpOleCallback);
4620 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4621 if(editor->lpOleCallback)
4622 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4623 return TRUE;
4624 case EM_GETWORDBREAKPROC:
4625 return (LRESULT)editor->pfnWordBreak;
4626 case EM_SETWORDBREAKPROC:
4628 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4630 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4631 return (LRESULT)pfnOld;
4633 case EM_GETTEXTMODE:
4634 return editor->mode;
4635 case EM_SETTEXTMODE:
4637 int mask = 0;
4638 int changes = 0;
4640 if (ME_GetTextLength(editor) ||
4641 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4642 return E_UNEXPECTED;
4644 /* Check for mutually exclusive flags in adjacent bits of wParam */
4645 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4646 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4647 return E_INVALIDARG;
4649 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4651 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4652 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4653 if (wParam & TM_PLAINTEXT) {
4654 /* Clear selection since it should be possible to select the
4655 * end of text run for rich text */
4656 ME_InvalidateSelection(editor);
4657 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4658 editor->pCursors[1] = editor->pCursors[0];
4659 /* plain text can only have the default style. */
4660 ME_ClearTempStyle(editor);
4661 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4662 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4663 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4666 /* FIXME: Currently no support for undo level and code page options */
4667 editor->mode = (editor->mode & ~mask) | changes;
4668 return 0;
4670 case EM_SETPASSWORDCHAR:
4672 editor->cPasswordMask = wParam;
4673 ME_RewrapRepaint(editor);
4674 return 0;
4676 case EM_SETTARGETDEVICE:
4677 if (wParam == 0)
4679 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4680 if (editor->nAvailWidth || editor->bWordWrap != new)
4682 editor->bWordWrap = new;
4683 editor->nAvailWidth = 0; /* wrap to client area */
4684 ME_RewrapRepaint(editor);
4686 } else {
4687 int width = max(0, lParam);
4688 if ((editor->styleFlags & ES_MULTILINE) &&
4689 (!editor->bWordWrap || editor->nAvailWidth != width))
4691 editor->nAvailWidth = width;
4692 editor->bWordWrap = TRUE;
4693 ME_RewrapRepaint(editor);
4695 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4697 return TRUE;
4698 default:
4699 do_default:
4700 *phresult = S_FALSE;
4701 break;
4703 return 0L;
4706 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4707 LPARAM lParam, BOOL unicode)
4709 ME_TextEditor *editor;
4710 HRESULT hresult;
4711 LRESULT lresult = 0;
4713 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4714 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4716 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4717 if (!editor)
4719 if (msg == WM_NCCREATE)
4721 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4722 ITextHost *texthost;
4724 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4725 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4726 return texthost != NULL;
4728 else
4730 return DefWindowProcW(hWnd, msg, wParam, lParam);
4734 switch (msg)
4736 case WM_PAINT:
4738 HDC hDC;
4739 RECT rc;
4740 PAINTSTRUCT ps;
4742 hDC = BeginPaint(editor->hWnd, &ps);
4743 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4744 ME_SendOldNotify(editor, EN_UPDATE);
4745 /* Erase area outside of the formatting rectangle */
4746 if (ps.rcPaint.top < editor->rcFormat.top)
4748 rc = ps.rcPaint;
4749 rc.bottom = editor->rcFormat.top;
4750 FillRect(hDC, &rc, editor->hbrBackground);
4751 ps.rcPaint.top = editor->rcFormat.top;
4753 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4754 rc = ps.rcPaint;
4755 rc.top = editor->rcFormat.bottom;
4756 FillRect(hDC, &rc, editor->hbrBackground);
4757 ps.rcPaint.bottom = editor->rcFormat.bottom;
4759 if (ps.rcPaint.left < editor->rcFormat.left) {
4760 rc = ps.rcPaint;
4761 rc.right = editor->rcFormat.left;
4762 FillRect(hDC, &rc, editor->hbrBackground);
4763 ps.rcPaint.left = editor->rcFormat.left;
4765 if (ps.rcPaint.right > editor->rcFormat.right) {
4766 rc = ps.rcPaint;
4767 rc.left = editor->rcFormat.right;
4768 FillRect(hDC, &rc, editor->hbrBackground);
4769 ps.rcPaint.right = editor->rcFormat.right;
4772 ME_PaintContent(editor, hDC, &ps.rcPaint);
4773 EndPaint(editor->hWnd, &ps);
4774 return 0;
4776 case WM_ERASEBKGND:
4778 HDC hDC = (HDC)wParam;
4779 RECT rc;
4781 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4782 FillRect(hDC, &rc, editor->hbrBackground);
4783 return 1;
4785 case EM_SETOPTIONS:
4787 DWORD dwStyle;
4788 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4789 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4790 ECO_SELECTIONBAR;
4791 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4792 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4793 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4794 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4795 return lresult;
4797 case EM_SETREADONLY:
4799 DWORD dwStyle;
4800 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4801 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4802 dwStyle &= ~ES_READONLY;
4803 if (wParam)
4804 dwStyle |= ES_READONLY;
4805 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4806 return lresult;
4808 default:
4809 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4812 if (hresult == S_FALSE)
4813 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4815 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4816 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4818 return lresult;
4821 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4823 BOOL unicode = TRUE;
4825 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4826 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4827 unicode = FALSE;
4829 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4832 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4834 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4837 /******************************************************************
4838 * RichEditANSIWndProc (RICHED20.10)
4840 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4842 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4845 /******************************************************************
4846 * RichEdit10ANSIWndProc (RICHED20.9)
4848 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4850 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4852 ITextHost *texthost;
4853 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4855 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4856 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4857 return texthost != NULL;
4859 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4862 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4864 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4867 /* Fill buffer with srcChars unicode characters from the start cursor.
4869 * buffer: destination buffer
4870 * buflen: length of buffer in characters excluding the NULL terminator.
4871 * start: start of editor text to copy into buffer.
4872 * srcChars: Number of characters to use from the editor text.
4873 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4875 * returns the number of characters written excluding the NULL terminator.
4877 * The written text is always NULL terminated.
4879 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4880 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4881 BOOL bEOP)
4883 ME_DisplayItem *pRun, *pNextRun;
4884 const WCHAR *pStart = buffer;
4885 const WCHAR cr_lf[] = {'\r', '\n', 0};
4886 const WCHAR *str;
4887 int nLen;
4889 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4890 if (editor->bEmulateVersion10) bCRLF = FALSE;
4892 pRun = start->pRun;
4893 assert(pRun);
4894 pNextRun = ME_FindItemFwd(pRun, diRun);
4896 nLen = pRun->member.run.len - start->nOffset;
4897 str = get_text( &pRun->member.run, start->nOffset );
4899 while (srcChars && buflen && pNextRun)
4901 int nFlags = pRun->member.run.nFlags;
4903 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4905 if (buflen == 1) break;
4906 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4907 * EM_GETTEXTEX, however, this is done for copying text which
4908 * also uses this function. */
4909 srcChars -= min(nLen, srcChars);
4910 nLen = 2;
4911 str = cr_lf;
4912 } else {
4913 nLen = min(nLen, srcChars);
4914 srcChars -= nLen;
4917 nLen = min(nLen, buflen);
4918 buflen -= nLen;
4920 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4922 buffer += nLen;
4924 pRun = pNextRun;
4925 pNextRun = ME_FindItemFwd(pRun, diRun);
4927 nLen = pRun->member.run.len;
4928 str = get_text( &pRun->member.run, 0 );
4930 /* append '\r' to the last paragraph. */
4931 if (pRun->next->type == diTextEnd && bEOP)
4933 *buffer = '\r';
4934 buffer ++;
4936 *buffer = 0;
4937 return buffer - pStart;
4940 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4942 WNDCLASSW wcW;
4943 WNDCLASSA wcA;
4945 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4946 wcW.lpfnWndProc = RichEditWndProcW;
4947 wcW.cbClsExtra = 0;
4948 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4949 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4950 wcW.hIcon = NULL;
4951 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4952 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4953 wcW.lpszMenuName = NULL;
4955 if (is_version_nt())
4957 wcW.lpszClassName = RICHEDIT_CLASS20W;
4958 if (!RegisterClassW(&wcW)) return FALSE;
4959 wcW.lpszClassName = MSFTEDIT_CLASS;
4960 if (!RegisterClassW(&wcW)) return FALSE;
4962 else
4964 /* WNDCLASSA/W have the same layout */
4965 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4966 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4967 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4968 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4971 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4972 wcA.lpfnWndProc = RichEditWndProcA;
4973 wcA.cbClsExtra = 0;
4974 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4975 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4976 wcA.hIcon = NULL;
4977 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4978 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4979 wcA.lpszMenuName = NULL;
4980 wcA.lpszClassName = RICHEDIT_CLASS20A;
4981 if (!RegisterClassA(&wcA)) return FALSE;
4982 wcA.lpszClassName = "RichEdit50A";
4983 if (!RegisterClassA(&wcA)) return FALSE;
4985 return TRUE;
4988 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4989 /* FIXME: Not implemented */
4990 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4991 hWnd, msg, get_msg_name(msg), wParam, lParam);
4992 return DefWindowProcW(hWnd, msg, wParam, lParam);
4995 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4996 /* FIXME: Not implemented */
4997 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4998 hWnd, msg, get_msg_name(msg), wParam, lParam);
4999 return DefWindowProcW(hWnd, msg, wParam, lParam);
5002 /******************************************************************
5003 * REExtendedRegisterClass (RICHED20.8)
5005 * FIXME undocumented
5006 * Need to check for errors and implement controls and callbacks
5008 LRESULT WINAPI REExtendedRegisterClass(void)
5010 WNDCLASSW wcW;
5011 UINT result;
5013 FIXME("semi stub\n");
5015 wcW.cbClsExtra = 0;
5016 wcW.cbWndExtra = 4;
5017 wcW.hInstance = NULL;
5018 wcW.hIcon = NULL;
5019 wcW.hCursor = NULL;
5020 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
5021 wcW.lpszMenuName = NULL;
5023 if (!ME_ListBoxRegistered)
5025 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
5026 wcW.lpfnWndProc = REListWndProc;
5027 wcW.lpszClassName = REListBox20W;
5028 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
5031 if (!ME_ComboBoxRegistered)
5033 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
5034 wcW.lpfnWndProc = REComboWndProc;
5035 wcW.lpszClassName = REComboBox20W;
5036 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
5039 result = 0;
5040 if (ME_ListBoxRegistered)
5041 result += 1;
5042 if (ME_ComboBoxRegistered)
5043 result += 2;
5045 return result;
5048 static BOOL isurlspecial(WCHAR c)
5050 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
5051 return strchrW( special_chars, c ) != NULL;
5055 * This proc takes a selection, and scans it forward in order to select the span
5056 * of a possible URL candidate. A possible URL candidate must start with isalnum
5057 * or one of the following special characters: *|/\+%#@ and must consist entirely
5058 * of the characters allowed to start the URL, plus : (colon) which may occur
5059 * at most once, and not at either end.
5061 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
5062 const ME_Cursor *start,
5063 int nChars,
5064 ME_Cursor *candidate_min,
5065 ME_Cursor *candidate_max)
5067 ME_Cursor cursor = *start;
5068 BOOL foundColon = FALSE;
5069 BOOL candidateStarted = FALSE;
5070 WCHAR lastAcceptedChar = '\0';
5072 while (nChars > 0)
5074 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
5075 WCHAR *str = strStart + cursor.nOffset;
5076 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
5077 nChars -= nLen;
5079 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
5081 /* Find start of candidate */
5082 if (!candidateStarted)
5084 while (nLen)
5086 nLen--;
5087 if (isalnumW(*str) || isurlspecial(*str))
5089 cursor.nOffset = str - strStart;
5090 *candidate_min = cursor;
5091 candidateStarted = TRUE;
5092 lastAcceptedChar = *str++;
5093 break;
5095 str++;
5099 /* Find end of candidate */
5100 if (candidateStarted) {
5101 while (nLen)
5103 nLen--;
5104 if (*str == ':' && !foundColon) {
5105 foundColon = TRUE;
5106 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
5107 cursor.nOffset = str - strStart;
5108 if (lastAcceptedChar == ':')
5109 ME_MoveCursorChars(editor, &cursor, -1);
5110 *candidate_max = cursor;
5111 return TRUE;
5113 lastAcceptedChar = *str++;
5116 } else {
5117 /* End of paragraph: skip it if before candidate span, or terminates
5118 current active span */
5119 if (candidateStarted) {
5120 if (lastAcceptedChar == ':')
5121 ME_MoveCursorChars(editor, &cursor, -1);
5122 *candidate_max = cursor;
5123 return TRUE;
5127 /* Reaching this point means no span was found, so get next span */
5128 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
5129 if (candidateStarted) {
5130 /* There are no further runs, so take end of text as end of candidate */
5131 cursor.nOffset = str - strStart;
5132 if (lastAcceptedChar == ':')
5133 ME_MoveCursorChars(editor, &cursor, -1);
5134 *candidate_max = cursor;
5135 return TRUE;
5137 *candidate_max = *candidate_min = cursor;
5138 return FALSE;
5140 cursor.nOffset = 0;
5143 if (candidateStarted) {
5144 /* There are no further runs, so take end of text as end of candidate */
5145 if (lastAcceptedChar == ':')
5146 ME_MoveCursorChars(editor, &cursor, -1);
5147 *candidate_max = cursor;
5148 return TRUE;
5150 *candidate_max = *candidate_min = cursor;
5151 return FALSE;
5155 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5157 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5159 #define MAX_PREFIX_LEN 9
5160 struct prefix_s {
5161 const WCHAR text[MAX_PREFIX_LEN];
5162 int length;
5163 }prefixes[] = {
5164 {{'p','r','o','s','p','e','r','o',':'}, 9},
5165 {{'t','e','l','n','e','t',':'}, 7},
5166 {{'g','o','p','h','e','r',':'}, 7},
5167 {{'m','a','i','l','t','o',':'}, 7},
5168 {{'h','t','t','p','s',':'}, 6},
5169 {{'f','i','l','e',':'}, 5},
5170 {{'n','e','w','s',':'}, 5},
5171 {{'w','a','i','s',':'}, 5},
5172 {{'n','n','t','p',':'}, 5},
5173 {{'h','t','t','p',':'}, 5},
5174 {{'w','w','w','.'}, 4},
5175 {{'f','t','p',':'}, 4},
5177 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5178 unsigned int i;
5180 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5181 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5183 if (nChars < prefixes[i].length) continue;
5184 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5185 return TRUE;
5187 return FALSE;
5188 #undef MAX_PREFIX_LEN
5192 * This proc walks through the indicated selection and evaluates whether each
5193 * section identified by ME_FindNextURLCandidate and in-between sections have
5194 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5195 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5197 * Since this function can cause runs to be split, do not depend on the value
5198 * of the start cursor at the end of the function.
5200 * nChars may be set to INT_MAX to update to the end of the text.
5202 * Returns TRUE if at least one section was modified.
5204 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5206 BOOL modified = FALSE;
5207 ME_Cursor startCur = *start;
5209 if (!editor->AutoURLDetect_bEnable) return FALSE;
5213 CHARFORMAT2W link;
5214 ME_Cursor candidateStart, candidateEnd;
5216 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5217 &candidateStart, &candidateEnd))
5219 /* Section before candidate is not an URL */
5220 int cMin = ME_GetCursorOfs(&candidateStart);
5221 int cMax = ME_GetCursorOfs(&candidateEnd);
5223 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5224 candidateStart = candidateEnd;
5225 nChars -= cMax - ME_GetCursorOfs(&startCur);
5227 else
5229 /* No more candidates until end of selection */
5230 nChars = 0;
5233 if (startCur.pRun != candidateStart.pRun ||
5234 startCur.nOffset != candidateStart.nOffset)
5236 /* CFE_LINK effect should be consistently unset */
5237 link.cbSize = sizeof(link);
5238 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5239 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5241 /* CFE_LINK must be unset from this range */
5242 memset(&link, 0, sizeof(CHARFORMAT2W));
5243 link.cbSize = sizeof(link);
5244 link.dwMask = CFM_LINK;
5245 link.dwEffects = 0;
5246 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5247 /* Update candidateEnd since setting character formats may split
5248 * runs, which can cause a cursor to be at an invalid offset within
5249 * a split run. */
5250 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5252 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5253 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5255 modified = TRUE;
5258 if (candidateStart.pRun != candidateEnd.pRun ||
5259 candidateStart.nOffset != candidateEnd.nOffset)
5261 /* CFE_LINK effect should be consistently set */
5262 link.cbSize = sizeof(link);
5263 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5264 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5266 /* CFE_LINK must be set on this range */
5267 memset(&link, 0, sizeof(CHARFORMAT2W));
5268 link.cbSize = sizeof(link);
5269 link.dwMask = CFM_LINK;
5270 link.dwEffects = CFE_LINK;
5271 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5272 modified = TRUE;
5275 startCur = candidateEnd;
5276 } while (nChars > 0);
5277 return modified;