Release 1.9.16.
[wine.git] / dlls / riched20 / editor.c
blob9ec72e2afd76b6bdf2b0fdf6d6063a64f492672b
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 switch(info->rtfMinor)
549 case rtfParDef: /* restores default paragraph attributes */
550 if (!info->editor->bEmulateVersion10) /* v4.1 */
551 info->borderType = RTFBorderParaLeft;
552 else /* v1.0 - 3.0 */
553 info->borderType = RTFBorderParaTop;
554 info->fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
555 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
556 PFM_STARTINDENT | PFM_RTLPARA;
557 /* TODO: numbering, shading */
558 info->fmt.wAlignment = PFA_LEFT;
559 info->fmt.cTabCount = 0;
560 info->fmt.dxOffset = info->fmt.dxStartIndent = info->fmt.dxRightIndent = 0;
561 info->fmt.wBorderWidth = info->fmt.wBorders = 0;
562 info->fmt.wBorderSpace = 0;
563 info->fmt.bLineSpacingRule = 0;
564 info->fmt.dySpaceBefore = info->fmt.dySpaceAfter = 0;
565 info->fmt.dyLineSpacing = 0;
566 info->fmt.wEffects &= ~PFE_RTLPARA;
567 if (!info->editor->bEmulateVersion10) /* v4.1 */
569 if (info->tableDef && info->tableDef->tableRowStart &&
570 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
572 ME_Cursor cursor;
573 ME_DisplayItem *para;
574 /* We are just after a table row. */
575 RTFFlushOutputBuffer(info);
576 cursor = info->editor->pCursors[0];
577 para = cursor.pPara;
578 if (para == info->tableDef->tableRowStart->member.para.next_para
579 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
581 /* Since the table row end, no text has been inserted, and the \intbl
582 * control word has not be used. We can confirm that we are not in a
583 * table anymore.
585 info->tableDef->tableRowStart = NULL;
586 info->canInheritInTbl = FALSE;
589 } else { /* v1.0 - v3.0 */
590 info->fmt.dwMask |= PFM_TABLE;
591 info->fmt.wEffects &= ~PFE_TABLE;
593 break;
594 case rtfNestLevel:
595 if (!info->editor->bEmulateVersion10) /* v4.1 */
597 while (info->rtfParam > info->nestingLevel) {
598 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
599 ZeroMemory(tableDef, sizeof(RTFTable));
600 tableDef->parent = info->tableDef;
601 info->tableDef = tableDef;
603 RTFFlushOutputBuffer(info);
604 if (tableDef->tableRowStart &&
605 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
607 ME_DisplayItem *para = tableDef->tableRowStart;
608 para = para->member.para.next_para;
609 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
610 tableDef->tableRowStart = para;
611 } else {
612 ME_Cursor cursor;
613 WCHAR endl = '\r';
614 cursor = info->editor->pCursors[0];
615 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
616 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
617 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
620 info->nestingLevel++;
622 info->canInheritInTbl = FALSE;
624 break;
625 case rtfInTable:
627 if (!info->editor->bEmulateVersion10) /* v4.1 */
629 if (info->nestingLevel < 1)
631 RTFTable *tableDef;
632 if (!info->tableDef)
634 info->tableDef = ALLOC_OBJ(RTFTable);
635 ZeroMemory(info->tableDef, sizeof(RTFTable));
637 tableDef = info->tableDef;
638 RTFFlushOutputBuffer(info);
639 if (tableDef->tableRowStart &&
640 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
642 ME_DisplayItem *para = tableDef->tableRowStart;
643 para = para->member.para.next_para;
644 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
645 tableDef->tableRowStart = para;
646 } else {
647 ME_Cursor cursor;
648 WCHAR endl = '\r';
649 cursor = info->editor->pCursors[0];
650 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
651 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
652 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
654 info->nestingLevel = 1;
655 info->canInheritInTbl = TRUE;
657 return;
658 } else { /* v1.0 - v3.0 */
659 info->fmt.dwMask |= PFM_TABLE;
660 info->fmt.wEffects |= PFE_TABLE;
662 break;
664 case rtfFirstIndent:
665 case rtfLeftIndent:
666 if ((info->fmt.dwMask & (PFM_STARTINDENT | PFM_OFFSET)) != (PFM_STARTINDENT | PFM_OFFSET))
668 PARAFORMAT2 fmt;
669 fmt.cbSize = sizeof(fmt);
670 ME_GetSelectionParaFormat(info->editor, &fmt);
671 info->fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
672 info->fmt.dxStartIndent = fmt.dxStartIndent;
673 info->fmt.dxOffset = fmt.dxOffset;
675 if (info->rtfMinor == rtfFirstIndent)
677 info->fmt.dxStartIndent += info->fmt.dxOffset + info->rtfParam;
678 info->fmt.dxOffset = -info->rtfParam;
680 else
681 info->fmt.dxStartIndent = info->rtfParam - info->fmt.dxOffset;
682 break;
683 case rtfRightIndent:
684 info->fmt.dwMask |= PFM_RIGHTINDENT;
685 info->fmt.dxRightIndent = info->rtfParam;
686 break;
687 case rtfQuadLeft:
688 case rtfQuadJust:
689 info->fmt.dwMask |= PFM_ALIGNMENT;
690 info->fmt.wAlignment = PFA_LEFT;
691 break;
692 case rtfQuadRight:
693 info->fmt.dwMask |= PFM_ALIGNMENT;
694 info->fmt.wAlignment = PFA_RIGHT;
695 break;
696 case rtfQuadCenter:
697 info->fmt.dwMask |= PFM_ALIGNMENT;
698 info->fmt.wAlignment = PFA_CENTER;
699 break;
700 case rtfTabPos:
701 if (!(info->fmt.dwMask & PFM_TABSTOPS))
703 PARAFORMAT2 fmt;
704 fmt.cbSize = sizeof(fmt);
705 ME_GetSelectionParaFormat(info->editor, &fmt);
706 memcpy(info->fmt.rgxTabs, fmt.rgxTabs,
707 fmt.cTabCount * sizeof(fmt.rgxTabs[0]));
708 info->fmt.cTabCount = fmt.cTabCount;
709 info->fmt.dwMask |= PFM_TABSTOPS;
711 if (info->fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
712 info->fmt.rgxTabs[info->fmt.cTabCount++] = info->rtfParam;
713 break;
714 case rtfKeep:
715 info->fmt.dwMask |= PFM_KEEP;
716 info->fmt.wEffects |= PFE_KEEP;
717 break;
718 case rtfNoWidowControl:
719 info->fmt.dwMask |= PFM_NOWIDOWCONTROL;
720 info->fmt.wEffects |= PFE_NOWIDOWCONTROL;
721 break;
722 case rtfKeepNext:
723 info->fmt.dwMask |= PFM_KEEPNEXT;
724 info->fmt.wEffects |= PFE_KEEPNEXT;
725 break;
726 case rtfSpaceAfter:
727 info->fmt.dwMask |= PFM_SPACEAFTER;
728 info->fmt.dySpaceAfter = info->rtfParam;
729 break;
730 case rtfSpaceBefore:
731 info->fmt.dwMask |= PFM_SPACEBEFORE;
732 info->fmt.dySpaceBefore = info->rtfParam;
733 break;
734 case rtfSpaceBetween:
735 info->fmt.dwMask |= PFM_LINESPACING;
736 if ((int)info->rtfParam > 0)
738 info->fmt.dyLineSpacing = info->rtfParam;
739 info->fmt.bLineSpacingRule = 3;
741 else
743 info->fmt.dyLineSpacing = info->rtfParam;
744 info->fmt.bLineSpacingRule = 4;
746 break;
747 case rtfSpaceMultiply:
748 info->fmt.dwMask |= PFM_LINESPACING;
749 info->fmt.dyLineSpacing = info->rtfParam * 20;
750 info->fmt.bLineSpacingRule = 5;
751 break;
752 case rtfParBullet:
753 info->fmt.dwMask |= PFM_NUMBERING;
754 info->fmt.wNumbering = PFN_BULLET;
755 break;
756 case rtfParSimple:
757 info->fmt.dwMask |= PFM_NUMBERING;
758 info->fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
759 break;
760 case rtfParNumDecimal:
761 info->fmt.dwMask |= PFM_NUMBERING;
762 info->fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
763 break;
764 case rtfParNumIndent:
765 info->fmt.dwMask |= PFM_NUMBERINGTAB;
766 info->fmt.wNumberingTab = info->rtfParam;
767 break;
768 case rtfParNumStartAt:
769 info->fmt.dwMask |= PFM_NUMBERINGSTART;
770 info->fmt.wNumberingStart = info->rtfParam;
771 break;
772 case rtfBorderLeft:
773 info->borderType = RTFBorderParaLeft;
774 info->fmt.wBorders |= 1;
775 info->fmt.dwMask |= PFM_BORDER;
776 break;
777 case rtfBorderRight:
778 info->borderType = RTFBorderParaRight;
779 info->fmt.wBorders |= 2;
780 info->fmt.dwMask |= PFM_BORDER;
781 break;
782 case rtfBorderTop:
783 info->borderType = RTFBorderParaTop;
784 info->fmt.wBorders |= 4;
785 info->fmt.dwMask |= PFM_BORDER;
786 break;
787 case rtfBorderBottom:
788 info->borderType = RTFBorderParaBottom;
789 info->fmt.wBorders |= 8;
790 info->fmt.dwMask |= PFM_BORDER;
791 break;
792 case rtfBorderSingle:
793 info->fmt.wBorders &= ~0x700;
794 info->fmt.wBorders |= 1 << 8;
795 info->fmt.dwMask |= PFM_BORDER;
796 break;
797 case rtfBorderThick:
798 info->fmt.wBorders &= ~0x700;
799 info->fmt.wBorders |= 2 << 8;
800 info->fmt.dwMask |= PFM_BORDER;
801 break;
802 case rtfBorderShadow:
803 info->fmt.wBorders &= ~0x700;
804 info->fmt.wBorders |= 10 << 8;
805 info->fmt.dwMask |= PFM_BORDER;
806 break;
807 case rtfBorderDouble:
808 info->fmt.wBorders &= ~0x700;
809 info->fmt.wBorders |= 7 << 8;
810 info->fmt.dwMask |= PFM_BORDER;
811 break;
812 case rtfBorderDot:
813 info->fmt.wBorders &= ~0x700;
814 info->fmt.wBorders |= 11 << 8;
815 info->fmt.dwMask |= PFM_BORDER;
816 break;
817 case rtfBorderWidth:
819 int borderSide = info->borderType & RTFBorderSideMask;
820 RTFTable *tableDef = info->tableDef;
821 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
823 RTFBorder *border;
824 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
825 break;
826 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
827 border->width = info->rtfParam;
828 break;
830 info->fmt.wBorderWidth = info->rtfParam;
831 info->fmt.dwMask |= PFM_BORDER;
832 break;
834 case rtfBorderSpace:
835 info->fmt.wBorderSpace = info->rtfParam;
836 info->fmt.dwMask |= PFM_BORDER;
837 break;
838 case rtfBorderColor:
840 RTFTable *tableDef = info->tableDef;
841 int borderSide = info->borderType & RTFBorderSideMask;
842 int borderType = info->borderType & RTFBorderTypeMask;
843 switch(borderType)
845 case RTFBorderTypePara:
846 if (!info->editor->bEmulateVersion10) /* v4.1 */
847 break;
848 /* v1.0 - 3.0 treat paragraph and row borders the same. */
849 case RTFBorderTypeRow:
850 if (tableDef) {
851 tableDef->border[borderSide].color = info->rtfParam;
853 break;
854 case RTFBorderTypeCell:
855 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
856 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
858 break;
860 break;
862 case rtfRTLPar:
863 info->fmt.dwMask |= PFM_RTLPARA;
864 info->fmt.wEffects |= PFE_RTLPARA;
865 break;
866 case rtfLTRPar:
867 info->fmt.dwMask = PFM_RTLPARA;
868 info->fmt.wEffects &= ~PFE_RTLPARA;
869 break;
873 void ME_RTFTblAttrHook(RTF_Info *info)
875 switch (info->rtfMinor)
877 case rtfRowDef:
879 if (!info->editor->bEmulateVersion10) /* v4.1 */
880 info->borderType = 0; /* Not sure */
881 else /* v1.0 - 3.0 */
882 info->borderType = RTFBorderRowTop;
883 if (!info->tableDef) {
884 info->tableDef = ME_MakeTableDef(info->editor);
885 } else {
886 ME_InitTableDef(info->editor, info->tableDef);
888 break;
890 case rtfCellPos:
892 int cellNum;
893 if (!info->tableDef)
895 info->tableDef = ME_MakeTableDef(info->editor);
897 cellNum = info->tableDef->numCellsDefined;
898 if (cellNum >= MAX_TABLE_CELLS)
899 break;
900 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
901 if (cellNum < MAX_TAB_STOPS) {
902 /* Tab stops were used to store cell positions before v4.1 but v4.1
903 * still seems to set the tabstops without using them. */
904 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
905 PARAFORMAT2 *pFmt = para->member.para.pFmt;
906 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
907 pFmt->rgxTabs[cellNum] |= 0x00FFFFFF & info->rtfParam;
909 info->tableDef->numCellsDefined++;
910 break;
912 case rtfRowBordTop:
913 info->borderType = RTFBorderRowTop;
914 break;
915 case rtfRowBordLeft:
916 info->borderType = RTFBorderRowLeft;
917 break;
918 case rtfRowBordBottom:
919 info->borderType = RTFBorderRowBottom;
920 break;
921 case rtfRowBordRight:
922 info->borderType = RTFBorderRowRight;
923 break;
924 case rtfCellBordTop:
925 info->borderType = RTFBorderCellTop;
926 break;
927 case rtfCellBordLeft:
928 info->borderType = RTFBorderCellLeft;
929 break;
930 case rtfCellBordBottom:
931 info->borderType = RTFBorderCellBottom;
932 break;
933 case rtfCellBordRight:
934 info->borderType = RTFBorderCellRight;
935 break;
936 case rtfRowGapH:
937 if (info->tableDef)
938 info->tableDef->gapH = info->rtfParam;
939 break;
940 case rtfRowLeftEdge:
941 if (info->tableDef)
942 info->tableDef->leftEdge = info->rtfParam;
943 break;
947 void ME_RTFSpecialCharHook(RTF_Info *info)
949 RTFTable *tableDef = info->tableDef;
950 switch (info->rtfMinor)
952 case rtfNestCell:
953 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
954 break;
955 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
956 case rtfCell:
957 if (!tableDef)
958 break;
959 RTFFlushOutputBuffer(info);
960 if (!info->editor->bEmulateVersion10) { /* v4.1 */
961 if (tableDef->tableRowStart)
963 if (!info->nestingLevel &&
964 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
966 ME_DisplayItem *para = tableDef->tableRowStart;
967 para = para->member.para.next_para;
968 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
969 tableDef->tableRowStart = para;
970 info->nestingLevel = 1;
972 ME_InsertTableCellFromCursor(info->editor);
974 } else { /* v1.0 - v3.0 */
975 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
976 PARAFORMAT2 *pFmt = para->member.para.pFmt;
977 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
978 tableDef->numCellsInserted < tableDef->numCellsDefined)
980 WCHAR tab = '\t';
981 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
982 tableDef->numCellsInserted++;
985 break;
986 case rtfNestRow:
987 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
988 break;
989 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
990 case rtfRow:
992 ME_DisplayItem *para, *cell, *run;
993 int i;
995 if (!tableDef)
996 break;
997 RTFFlushOutputBuffer(info);
998 if (!info->editor->bEmulateVersion10) { /* v4.1 */
999 if (!tableDef->tableRowStart)
1000 break;
1001 if (!info->nestingLevel &&
1002 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1004 para = tableDef->tableRowStart;
1005 para = para->member.para.next_para;
1006 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1007 tableDef->tableRowStart = para;
1008 info->nestingLevel++;
1010 para = tableDef->tableRowStart;
1011 cell = ME_FindItemFwd(para, diCell);
1012 assert(cell && !cell->member.cell.prev_cell);
1013 if (tableDef->numCellsDefined < 1)
1015 /* 2000 twips appears to be the cell size that native richedit uses
1016 * when no cell sizes are specified. */
1017 const int defaultCellSize = 2000;
1018 int nRightBoundary = defaultCellSize;
1019 cell->member.cell.nRightBoundary = nRightBoundary;
1020 while (cell->member.cell.next_cell) {
1021 cell = cell->member.cell.next_cell;
1022 nRightBoundary += defaultCellSize;
1023 cell->member.cell.nRightBoundary = nRightBoundary;
1025 para = ME_InsertTableCellFromCursor(info->editor);
1026 cell = para->member.para.pCell;
1027 cell->member.cell.nRightBoundary = nRightBoundary;
1028 } else {
1029 for (i = 0; i < tableDef->numCellsDefined; i++)
1031 RTFCell *cellDef = &tableDef->cells[i];
1032 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1033 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1034 cellDef->border);
1035 cell = cell->member.cell.next_cell;
1036 if (!cell)
1038 para = ME_InsertTableCellFromCursor(info->editor);
1039 cell = para->member.para.pCell;
1042 /* Cell for table row delimiter is empty */
1043 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1046 run = ME_FindItemFwd(cell, diRun);
1047 if (info->editor->pCursors[0].pRun != run ||
1048 info->editor->pCursors[0].nOffset)
1050 int nOfs, nChars;
1051 /* Delete inserted cells that aren't defined. */
1052 info->editor->pCursors[1].pRun = run;
1053 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1054 info->editor->pCursors[1].nOffset = 0;
1055 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1056 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1057 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1058 nChars, TRUE);
1061 para = ME_InsertTableRowEndFromCursor(info->editor);
1062 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1063 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1064 ME_ApplyBorderProperties(info, &para->member.para.border,
1065 tableDef->border);
1066 info->nestingLevel--;
1067 if (!info->nestingLevel)
1069 if (info->canInheritInTbl) {
1070 tableDef->tableRowStart = para;
1071 } else {
1072 while (info->tableDef) {
1073 tableDef = info->tableDef;
1074 info->tableDef = tableDef->parent;
1075 heap_free(tableDef);
1078 } else {
1079 info->tableDef = tableDef->parent;
1080 heap_free(tableDef);
1082 } else { /* v1.0 - v3.0 */
1083 WCHAR endl = '\r';
1084 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1085 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1086 pFmt->dxOffset = info->tableDef->gapH;
1087 pFmt->dxStartIndent = info->tableDef->leftEdge;
1089 ME_ApplyBorderProperties(info, &para->member.para.border,
1090 tableDef->border);
1091 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1093 WCHAR tab = '\t';
1094 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1095 tableDef->numCellsInserted++;
1097 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1098 if (!tableDef->numCellsDefined)
1099 pFmt->wEffects &= ~PFE_TABLE;
1100 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1101 tableDef->numCellsInserted = 0;
1103 break;
1105 case rtfTab:
1106 case rtfPar:
1107 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1108 ME_DisplayItem *para;
1109 PARAFORMAT2 *pFmt;
1110 RTFFlushOutputBuffer(info);
1111 para = info->editor->pCursors[0].pPara;
1112 pFmt = para->member.para.pFmt;
1113 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1115 /* rtfPar is treated like a space within a table. */
1116 info->rtfClass = rtfText;
1117 info->rtfMajor = ' ';
1119 else if (info->rtfMinor == rtfPar && tableDef)
1120 tableDef->numCellsInserted = 0;
1122 break;
1126 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1127 const SIZEL* sz)
1129 LPOLEOBJECT lpObject = NULL;
1130 LPSTORAGE lpStorage = NULL;
1131 LPOLECLIENTSITE lpClientSite = NULL;
1132 LPDATAOBJECT lpDataObject = NULL;
1133 LPOLECACHE lpOleCache = NULL;
1134 STGMEDIUM stgm;
1135 FORMATETC fm;
1136 CLSID clsid;
1137 BOOL ret = FALSE;
1138 DWORD conn;
1140 if (hemf)
1142 stgm.tymed = TYMED_ENHMF;
1143 stgm.u.hEnhMetaFile = hemf;
1144 fm.cfFormat = CF_ENHMETAFILE;
1146 else if (hbmp)
1148 stgm.tymed = TYMED_GDI;
1149 stgm.u.hBitmap = hbmp;
1150 fm.cfFormat = CF_BITMAP;
1152 stgm.pUnkForRelease = NULL;
1154 fm.ptd = NULL;
1155 fm.dwAspect = DVASPECT_CONTENT;
1156 fm.lindex = -1;
1157 fm.tymed = stgm.tymed;
1159 if (!info->lpRichEditOle)
1161 CreateIRichEditOle(NULL, info->editor, (VOID**)&info->lpRichEditOle);
1164 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1165 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1166 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1167 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1168 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1169 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1170 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1171 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1173 REOBJECT reobject;
1175 reobject.cbStruct = sizeof(reobject);
1176 reobject.cp = REO_CP_SELECTION;
1177 reobject.clsid = clsid;
1178 reobject.poleobj = lpObject;
1179 reobject.pstg = lpStorage;
1180 reobject.polesite = lpClientSite;
1181 /* convert from twips to .01 mm */
1182 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1183 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1184 reobject.dvaspect = DVASPECT_CONTENT;
1185 reobject.dwFlags = 0; /* FIXME */
1186 reobject.dwUser = 0;
1188 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1189 ret = TRUE;
1192 if (lpObject) IOleObject_Release(lpObject);
1193 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1194 if (lpStorage) IStorage_Release(lpStorage);
1195 if (lpDataObject) IDataObject_Release(lpDataObject);
1196 if (lpOleCache) IOleCache_Release(lpOleCache);
1198 return ret;
1201 static void ME_RTFReadShpPictGroup( RTF_Info *info )
1203 int level = 1;
1205 for (;;)
1207 RTFGetToken (info);
1209 if (info->rtfClass == rtfEOF) return;
1210 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1212 if (--level == 0) break;
1214 else if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1216 level++;
1218 else
1220 RTFRouteToken( info );
1221 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1222 level--;
1226 RTFRouteToken( info ); /* feed "}" back to router */
1227 return;
1230 static DWORD read_hex_data( RTF_Info *info, BYTE **out )
1232 DWORD read = 0, size = 1024;
1233 BYTE *buf, val;
1234 BOOL flip;
1236 *out = NULL;
1238 if (info->rtfClass != rtfText)
1240 ERR("Called with incorrect token\n");
1241 return 0;
1244 buf = HeapAlloc( GetProcessHeap(), 0, size );
1245 if (!buf) return 0;
1247 val = info->rtfMajor;
1248 for (flip = TRUE;; flip = !flip)
1250 RTFGetToken( info );
1251 if (info->rtfClass == rtfEOF)
1253 HeapFree( GetProcessHeap(), 0, buf );
1254 return 0;
1256 if (info->rtfClass != rtfText) break;
1257 if (flip)
1259 if (read >= size)
1261 size *= 2;
1262 buf = HeapReAlloc( GetProcessHeap(), 0, buf, size );
1263 if (!buf) return 0;
1265 buf[read++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1267 else
1268 val = info->rtfMajor;
1270 if (flip) FIXME("wrong hex string\n");
1272 *out = buf;
1273 return read;
1276 static void ME_RTFReadPictGroup(RTF_Info *info)
1278 SIZEL sz;
1279 BYTE *buffer = NULL;
1280 DWORD size = 0;
1281 METAFILEPICT mfp;
1282 HENHMETAFILE hemf;
1283 HBITMAP hbmp;
1284 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1285 int level = 1;
1287 mfp.mm = MM_TEXT;
1288 sz.cx = sz.cy = 0;
1290 for (;;)
1292 RTFGetToken( info );
1294 if (info->rtfClass == rtfText)
1296 if (level == 1)
1298 if (!buffer)
1299 size = read_hex_data( info, &buffer );
1301 else
1303 RTFSkipGroup( info );
1305 } /* We potentially have a new token so fall through. */
1307 if (info->rtfClass == rtfEOF) return;
1309 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1311 if (--level == 0) break;
1312 continue;
1314 if (RTFCheckCM( info, rtfGroup, rtfBeginGroup ))
1316 level++;
1317 continue;
1319 if (!RTFCheckCM( info, rtfControl, rtfPictAttr ))
1321 RTFRouteToken( info );
1322 if (RTFCheckCM( info, rtfGroup, rtfEndGroup ))
1323 level--;
1324 continue;
1327 if (RTFCheckMM( info, rtfPictAttr, rtfWinMetafile ))
1329 mfp.mm = info->rtfParam;
1330 gfx = gfx_metafile;
1332 else if (RTFCheckMM( info, rtfPictAttr, rtfDevIndBitmap ))
1334 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1335 gfx = gfx_dib;
1337 else if (RTFCheckMM( info, rtfPictAttr, rtfEmfBlip ))
1338 gfx = gfx_enhmetafile;
1339 else if (RTFCheckMM( info, rtfPictAttr, rtfPicWid ))
1340 mfp.xExt = info->rtfParam;
1341 else if (RTFCheckMM( info, rtfPictAttr, rtfPicHt ))
1342 mfp.yExt = info->rtfParam;
1343 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalWid ))
1344 sz.cx = info->rtfParam;
1345 else if (RTFCheckMM( info, rtfPictAttr, rtfPicGoalHt ))
1346 sz.cy = info->rtfParam;
1347 else
1348 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1351 if (buffer)
1353 switch (gfx)
1355 case gfx_enhmetafile:
1356 if ((hemf = SetEnhMetaFileBits( size, buffer )))
1357 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1358 break;
1359 case gfx_metafile:
1360 if ((hemf = SetWinMetaFileBits( size, buffer, NULL, &mfp )))
1361 ME_RTFInsertOleObject( info, hemf, NULL, &sz );
1362 break;
1363 case gfx_dib:
1365 BITMAPINFO *bi = (BITMAPINFO*)buffer;
1366 HDC hdc = GetDC(0);
1367 unsigned nc = bi->bmiHeader.biClrUsed;
1369 /* not quite right, especially for bitfields type of compression */
1370 if (!nc && bi->bmiHeader.biBitCount <= 8)
1371 nc = 1 << bi->bmiHeader.biBitCount;
1372 if ((hbmp = CreateDIBitmap( hdc, &bi->bmiHeader,
1373 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1374 bi, DIB_RGB_COLORS)) )
1375 ME_RTFInsertOleObject( info, NULL, hbmp, &sz );
1376 ReleaseDC( 0, hdc );
1377 break;
1379 default:
1380 break;
1383 HeapFree( GetProcessHeap(), 0, buffer );
1384 RTFRouteToken( info ); /* feed "}" back to router */
1385 return;
1388 /* for now, lookup the \result part and use it, whatever the object */
1389 static void ME_RTFReadObjectGroup(RTF_Info *info)
1391 for (;;)
1393 RTFGetToken (info);
1394 if (info->rtfClass == rtfEOF)
1395 return;
1396 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1397 break;
1398 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1400 RTFGetToken (info);
1401 if (info->rtfClass == rtfEOF)
1402 return;
1403 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1405 int level = 1;
1407 while (RTFGetToken (info) != rtfEOF)
1409 if (info->rtfClass == rtfGroup)
1411 if (info->rtfMajor == rtfBeginGroup) level++;
1412 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1414 RTFRouteToken(info);
1417 else RTFSkipGroup(info);
1418 continue;
1420 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1422 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1423 return;
1426 RTFRouteToken(info); /* feed "}" back to router */
1429 static void ME_RTFReadHook(RTF_Info *info)
1431 switch(info->rtfClass)
1433 case rtfGroup:
1434 switch(info->rtfMajor)
1436 case rtfBeginGroup:
1437 if (info->stackTop < maxStack) {
1438 info->stack[info->stackTop].style = info->style;
1439 ME_AddRefStyle(info->style);
1440 info->stack[info->stackTop].codePage = info->codePage;
1441 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1443 info->stackTop++;
1444 info->styleChanged = FALSE;
1445 break;
1446 case rtfEndGroup:
1448 RTFFlushOutputBuffer(info);
1449 info->stackTop--;
1450 if (info->stackTop <= 0)
1451 info->rtfClass = rtfEOF;
1452 if (info->stackTop < 0)
1453 return;
1455 ME_ReleaseStyle(info->style);
1456 info->style = info->stack[info->stackTop].style;
1457 info->codePage = info->stack[info->stackTop].codePage;
1458 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1459 break;
1462 break;
1466 void
1467 ME_StreamInFill(ME_InStream *stream)
1469 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1470 (BYTE *)stream->buffer,
1471 sizeof(stream->buffer),
1472 (LONG *)&stream->dwSize);
1473 stream->dwUsed = 0;
1476 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1478 RTF_Info parser;
1479 ME_Style *style;
1480 int from, to, nUndoMode;
1481 int nEventMask = editor->nEventMask;
1482 ME_InStream inStream;
1483 BOOL invalidRTF = FALSE;
1484 ME_Cursor *selStart, *selEnd;
1485 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1487 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1488 editor->nEventMask = 0;
1490 ME_GetSelectionOfs(editor, &from, &to);
1491 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1493 ME_GetSelection(editor, &selStart, &selEnd);
1494 style = ME_GetSelectionInsertStyle(editor);
1496 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1498 /* Don't insert text at the end of the table row */
1499 if (!editor->bEmulateVersion10) { /* v4.1 */
1500 ME_DisplayItem *para = editor->pCursors->pPara;
1501 if (para->member.para.nFlags & MEPF_ROWEND)
1503 para = para->member.para.next_para;
1504 editor->pCursors[0].pPara = para;
1505 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1506 editor->pCursors[0].nOffset = 0;
1508 if (para->member.para.nFlags & MEPF_ROWSTART)
1510 para = para->member.para.next_para;
1511 editor->pCursors[0].pPara = para;
1512 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1513 editor->pCursors[0].nOffset = 0;
1515 editor->pCursors[1] = editor->pCursors[0];
1516 } else { /* v1.0 - 3.0 */
1517 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1518 ME_IsInTable(editor->pCursors[0].pRun))
1519 return 0;
1521 } else {
1522 style = editor->pBuffer->pDefaultStyle;
1523 ME_AddRefStyle(style);
1524 ME_SetSelection(editor, 0, 0);
1525 ME_InternalDeleteText(editor, &editor->pCursors[1],
1526 ME_GetTextLength(editor), FALSE);
1527 from = to = 0;
1528 ME_ClearTempStyle(editor);
1529 ME_SetDefaultParaFormat(editor, editor->pCursors[0].pPara->member.para.pFmt);
1533 /* Back up undo mode to a local variable */
1534 nUndoMode = editor->nUndoMode;
1536 /* Only create an undo if SFF_SELECTION is set */
1537 if (!(format & SFF_SELECTION))
1538 editor->nUndoMode = umIgnore;
1540 inStream.editstream = stream;
1541 inStream.editstream->dwError = 0;
1542 inStream.dwSize = 0;
1543 inStream.dwUsed = 0;
1545 if (format & SF_RTF)
1547 /* Check if it's really RTF, and if it is not, use plain text */
1548 ME_StreamInFill(&inStream);
1549 if (!inStream.editstream->dwError)
1551 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1552 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1554 invalidRTF = TRUE;
1555 inStream.editstream->dwError = -16;
1560 if (!invalidRTF && !inStream.editstream->dwError)
1562 if (format & SF_RTF) {
1563 from = ME_GetCursorOfs(&editor->pCursors[0]);
1565 /* setup the RTF parser */
1566 memset(&parser, 0, sizeof parser);
1567 RTFSetEditStream(&parser, &inStream);
1568 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1569 parser.editor = editor;
1570 parser.style = style;
1571 WriterInit(&parser);
1572 RTFInit(&parser);
1573 RTFSetReadHook(&parser, ME_RTFReadHook);
1574 RTFSetDestinationCallback(&parser, rtfShpPict, ME_RTFReadShpPictGroup);
1575 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1576 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1577 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1579 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1580 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1582 BeginFile(&parser);
1584 /* do the parsing */
1585 RTFRead(&parser);
1586 RTFFlushOutputBuffer(&parser);
1587 if (!editor->bEmulateVersion10) { /* v4.1 */
1588 if (parser.tableDef && parser.tableDef->tableRowStart &&
1589 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1591 /* Delete any incomplete table row at the end of the rich text. */
1592 int nOfs, nChars;
1593 ME_DisplayItem *para;
1595 parser.rtfMinor = rtfRow;
1596 /* Complete the table row before deleting it.
1597 * By doing it this way we will have the current paragraph format set
1598 * properly to reflect that is not in the complete table, and undo items
1599 * will be added for this change to the current paragraph format. */
1600 if (parser.nestingLevel > 0)
1602 while (parser.nestingLevel > 1)
1603 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1604 para = parser.tableDef->tableRowStart;
1605 ME_RTFSpecialCharHook(&parser);
1606 } else {
1607 para = parser.tableDef->tableRowStart;
1608 ME_RTFSpecialCharHook(&parser);
1609 assert(para->member.para.nFlags & MEPF_ROWEND);
1610 para = para->member.para.next_para;
1613 editor->pCursors[1].pPara = para;
1614 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1615 editor->pCursors[1].nOffset = 0;
1616 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1617 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1618 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1619 if (parser.tableDef)
1620 parser.tableDef->tableRowStart = NULL;
1623 ME_CheckTablesForCorruption(editor);
1624 RTFDestroy(&parser);
1625 if (parser.lpRichEditOle)
1626 IRichEditOle_Release(parser.lpRichEditOle);
1628 if (parser.stackTop > 0)
1630 while (--parser.stackTop >= 0)
1632 ME_ReleaseStyle(parser.style);
1633 parser.style = parser.stack[parser.stackTop].style;
1635 if (!inStream.editstream->dwError)
1636 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1639 /* Remove last line break, as mandated by tests. This is not affected by
1640 CR/LF counters, since RTF streaming presents only \para tokens, which
1641 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1643 if (stripLastCR && !(format & SFF_SELECTION)) {
1644 int newto;
1645 ME_GetSelection(editor, &selStart, &selEnd);
1646 newto = ME_GetCursorOfs(selEnd);
1647 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1648 WCHAR lastchar[3] = {'\0', '\0'};
1649 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1650 ME_Cursor linebreakCursor = *selEnd;
1652 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1653 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE, FALSE);
1654 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1655 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1659 to = ME_GetCursorOfs(&editor->pCursors[0]);
1660 num_read = to - from;
1662 style = parser.style;
1664 else if (format & SF_TEXT)
1665 num_read = ME_StreamInText(editor, format, &inStream, style);
1666 else
1667 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1668 /* put the cursor at the top */
1669 if (!(format & SFF_SELECTION))
1670 ME_SetSelection(editor, 0, 0);
1673 /* Restore saved undo mode */
1674 editor->nUndoMode = nUndoMode;
1676 /* even if we didn't add an undo, we need to commit anything on the stack */
1677 ME_CommitUndo(editor);
1679 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1680 if (!(format & SFF_SELECTION))
1681 ME_EmptyUndoStack(editor);
1683 ME_ReleaseStyle(style);
1684 editor->nEventMask = nEventMask;
1685 ME_UpdateRepaint(editor, FALSE);
1686 if (!(format & SFF_SELECTION)) {
1687 ME_ClearTempStyle(editor);
1689 ITextHost_TxShowCaret(editor->texthost, FALSE);
1690 ME_MoveCaret(editor);
1691 ITextHost_TxShowCaret(editor->texthost, TRUE);
1692 ME_SendSelChange(editor);
1693 ME_SendRequestResize(editor, FALSE);
1695 return num_read;
1699 typedef struct tagME_RTFStringStreamStruct
1701 char *string;
1702 int pos;
1703 int length;
1704 } ME_RTFStringStreamStruct;
1706 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1708 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1709 int count;
1711 count = min(cb, pStruct->length - pStruct->pos);
1712 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1713 pStruct->pos += count;
1714 *pcb = count;
1715 return 0;
1718 static void
1719 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1721 EDITSTREAM es;
1722 ME_RTFStringStreamStruct data;
1724 data.string = string;
1725 data.length = strlen(string);
1726 data.pos = 0;
1727 es.dwCookie = (DWORD_PTR)&data;
1728 es.pfnCallback = ME_ReadFromRTFString;
1729 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, TRUE);
1733 static int
1734 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1736 const int nLen = lstrlenW(text);
1737 const int nTextLen = ME_GetTextLength(editor);
1738 int nMin, nMax;
1739 ME_Cursor cursor;
1740 WCHAR wLastChar = ' ';
1742 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1743 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1745 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1746 FIXME("Flags 0x%08x not implemented\n",
1747 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1749 nMin = chrg->cpMin;
1750 if (chrg->cpMax == -1)
1751 nMax = nTextLen;
1752 else
1753 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1755 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1756 if (editor->bEmulateVersion10 && nMax == nTextLen)
1758 flags |= FR_DOWN;
1761 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1762 if (editor->bEmulateVersion10 && nMax < nMin)
1764 if (chrgText)
1766 chrgText->cpMin = -1;
1767 chrgText->cpMax = -1;
1769 return -1;
1772 /* when searching up, if cpMin < cpMax, then instead of searching
1773 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1774 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1775 * case, it is always bigger than cpMin.
1777 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1779 int nSwap = nMax;
1781 nMax = nMin > nTextLen ? nTextLen : nMin;
1782 if (nMin < nSwap || chrg->cpMax == -1)
1783 nMin = 0;
1784 else
1785 nMin = nSwap;
1788 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1790 if (chrgText)
1791 chrgText->cpMin = chrgText->cpMax = -1;
1792 return -1;
1795 if (flags & FR_DOWN) /* Forward search */
1797 /* If possible, find the character before where the search starts */
1798 if ((flags & FR_WHOLEWORD) && nMin)
1800 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1801 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1802 ME_MoveCursorChars(editor, &cursor, 1);
1803 } else {
1804 ME_CursorFromCharOfs(editor, nMin, &cursor);
1807 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1809 ME_DisplayItem *pCurItem = cursor.pRun;
1810 int nCurStart = cursor.nOffset;
1811 int nMatched = 0;
1813 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1815 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1816 break;
1818 nMatched++;
1819 if (nMatched == nLen)
1821 ME_DisplayItem *pNextItem = pCurItem;
1822 int nNextStart = nCurStart;
1823 WCHAR wNextChar;
1825 /* Check to see if next character is a whitespace */
1826 if (flags & FR_WHOLEWORD)
1828 if (nCurStart + nMatched == pCurItem->member.run.len)
1830 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1831 nNextStart = -nMatched;
1834 if (pNextItem)
1835 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1836 else
1837 wNextChar = ' ';
1839 if (isalnumW(wNextChar))
1840 break;
1843 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1844 if (chrgText)
1846 chrgText->cpMin = cursor.nOffset;
1847 chrgText->cpMax = cursor.nOffset + nLen;
1849 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1850 return cursor.nOffset;
1852 if (nCurStart + nMatched == pCurItem->member.run.len)
1854 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1855 nCurStart = -nMatched;
1858 if (pCurItem)
1859 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1860 else
1861 wLastChar = ' ';
1863 cursor.nOffset++;
1864 if (cursor.nOffset == cursor.pRun->member.run.len)
1866 ME_NextRun(&cursor.pPara, &cursor.pRun, TRUE);
1867 cursor.nOffset = 0;
1871 else /* Backward search */
1873 /* If possible, find the character after where the search ends */
1874 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1876 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1877 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1878 ME_MoveCursorChars(editor, &cursor, -1);
1879 } else {
1880 ME_CursorFromCharOfs(editor, nMax, &cursor);
1883 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1885 ME_DisplayItem *pCurItem = cursor.pRun;
1886 ME_DisplayItem *pCurPara = cursor.pPara;
1887 int nCurEnd = cursor.nOffset;
1888 int nMatched = 0;
1890 if (nCurEnd == 0)
1892 ME_PrevRun(&pCurPara, &pCurItem, TRUE);
1893 nCurEnd = pCurItem->member.run.len;
1896 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1897 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1899 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1900 break;
1902 nMatched++;
1903 if (nMatched == nLen)
1905 ME_DisplayItem *pPrevItem = pCurItem;
1906 int nPrevEnd = nCurEnd;
1907 WCHAR wPrevChar;
1908 int nStart;
1910 /* Check to see if previous character is a whitespace */
1911 if (flags & FR_WHOLEWORD)
1913 if (nPrevEnd - nMatched == 0)
1915 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1916 if (pPrevItem)
1917 nPrevEnd = pPrevItem->member.run.len + nMatched;
1920 if (pPrevItem)
1921 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1922 else
1923 wPrevChar = ' ';
1925 if (isalnumW(wPrevChar))
1926 break;
1929 nStart = pCurPara->member.para.nCharOfs
1930 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1931 if (chrgText)
1933 chrgText->cpMin = nStart;
1934 chrgText->cpMax = nStart + nLen;
1936 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1937 return nStart;
1939 if (nCurEnd - nMatched == 0)
1941 ME_PrevRun(&pCurPara, &pCurItem, TRUE);
1942 /* Don't care about pCurItem becoming NULL here; it's already taken
1943 * care of in the exterior loop condition */
1944 nCurEnd = pCurItem->member.run.len + nMatched;
1947 if (pCurItem)
1948 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1949 else
1950 wLastChar = ' ';
1952 cursor.nOffset--;
1953 if (cursor.nOffset < 0)
1955 ME_PrevRun(&cursor.pPara, &cursor.pRun, TRUE);
1956 cursor.nOffset = cursor.pRun->member.run.len;
1960 TRACE("not found\n");
1961 if (chrgText)
1962 chrgText->cpMin = chrgText->cpMax = -1;
1963 return -1;
1966 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1968 int nChars;
1969 ME_Cursor start;
1971 if (!ex->cb || !pText) return 0;
1973 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1974 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1976 if (ex->flags & GT_SELECTION)
1978 int from, to;
1979 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1980 start = editor->pCursors[nStartCur];
1981 nChars = to - from;
1983 else
1985 ME_SetCursorToStart(editor, &start);
1986 nChars = INT_MAX;
1988 if (ex->codepage == CP_UNICODE)
1990 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1991 &start, nChars, ex->flags & GT_USECRLF, FALSE);
1993 else
1995 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1996 we can just take a bigger buffer? :)
1997 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1998 occurs only in richedit 2.0 mode, in which line breaks have only one CR
2000 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2001 DWORD buflen;
2002 LPWSTR buffer;
2003 LRESULT rc;
2005 buflen = min(crlfmul * nChars, ex->cb - 1);
2006 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
2008 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF, FALSE);
2009 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
2010 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2011 if (rc) rc--; /* do not count 0 terminator */
2013 heap_free(buffer);
2014 return rc;
2018 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2019 const ME_Cursor *start, int nLen, BOOL unicode)
2021 if (!strText) return 0;
2022 if (unicode) {
2023 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE, FALSE);
2024 } else {
2025 int nChars;
2026 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2027 if (!p) return 0;
2028 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE, FALSE);
2029 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2030 nLen+1, NULL, NULL);
2031 FREE_OBJ(p);
2032 return nChars;
2036 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2038 int end;
2040 TRACE("%d - %d\n", to, from );
2042 ME_InvalidateSelection( editor );
2043 end = ME_SetSelection( editor, to, from );
2044 ME_InvalidateSelection( editor );
2045 ITextHost_TxShowCaret( editor->texthost, FALSE );
2046 ME_ShowCaret( editor );
2047 ME_SendSelChange( editor );
2049 return end;
2052 typedef struct tagME_GlobalDestStruct
2054 HGLOBAL hData;
2055 int nLength;
2056 } ME_GlobalDestStruct;
2058 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2060 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2061 int i;
2062 WORD *pSrc, *pDest;
2064 cb = cb >> 1;
2065 pDest = (WORD *)lpBuff;
2066 pSrc = GlobalLock(pData->hData);
2067 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2068 pDest[i] = pSrc[pData->nLength+i];
2070 pData->nLength += i;
2071 *pcb = 2*i;
2072 GlobalUnlock(pData->hData);
2073 return 0;
2076 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2078 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2079 int i;
2080 BYTE *pSrc, *pDest;
2082 pDest = lpBuff;
2083 pSrc = GlobalLock(pData->hData);
2084 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2085 pDest[i] = pSrc[pData->nLength+i];
2087 pData->nLength += i;
2088 *pcb = i;
2089 GlobalUnlock(pData->hData);
2090 return 0;
2093 static BOOL ME_Paste(ME_TextEditor *editor)
2095 DWORD dwFormat = 0;
2096 EDITSTREAM es;
2097 ME_GlobalDestStruct gds;
2098 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2099 UINT cf = 0;
2101 if (IsClipboardFormatAvailable(nRTFFormat))
2102 cf = nRTFFormat, dwFormat = SF_RTF;
2103 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2104 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2105 else
2106 return FALSE;
2108 if (!OpenClipboard(editor->hWnd))
2109 return FALSE;
2110 gds.hData = GetClipboardData(cf);
2111 gds.nLength = 0;
2112 es.dwCookie = (DWORD_PTR)&gds;
2113 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2114 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2116 CloseClipboard();
2117 return TRUE;
2120 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2122 LPDATAOBJECT dataObj = NULL;
2123 HRESULT hr = S_OK;
2125 if (editor->cPasswordMask)
2126 return FALSE; /* Copying or Cutting masked text isn't allowed */
2128 if(editor->lpOleCallback)
2130 CHARRANGE range;
2131 range.cpMin = ME_GetCursorOfs(start);
2132 range.cpMax = range.cpMin + nChars;
2133 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2135 if(FAILED(hr) || !dataObj)
2136 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2137 if(SUCCEEDED(hr)) {
2138 hr = OleSetClipboard(dataObj);
2139 IDataObject_Release(dataObj);
2141 return SUCCEEDED(hr);
2144 /* helper to send a msg filter notification */
2145 static BOOL
2146 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2148 MSGFILTER msgf;
2150 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2151 msgf.nmhdr.hwndFrom = editor->hWnd;
2152 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2153 msgf.nmhdr.code = EN_MSGFILTER;
2154 msgf.msg = msg;
2155 msgf.wParam = *wParam;
2156 msgf.lParam = *lParam;
2157 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2158 return FALSE;
2159 *wParam = msgf.wParam;
2160 *lParam = msgf.lParam;
2161 msgf.wParam = *wParam;
2163 return TRUE;
2166 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2168 ME_DisplayItem *startPara, *endPara;
2169 ME_DisplayItem *prev_para;
2170 ME_Cursor *from, *to;
2171 ME_Cursor start;
2172 int nChars;
2174 if (!editor->AutoURLDetect_bEnable) return;
2176 ME_GetSelection(editor, &from, &to);
2178 /* Find paragraph previous to the one that contains start cursor */
2179 startPara = from->pPara;
2180 prev_para = startPara->member.para.prev_para;
2181 if (prev_para->type == diParagraph) startPara = prev_para;
2183 /* Find paragraph that contains end cursor */
2184 endPara = to->pPara->member.para.next_para;
2186 start.pPara = startPara;
2187 start.pRun = ME_FindItemFwd(startPara, diRun);
2188 start.nOffset = 0;
2189 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2191 ME_UpdateLinkAttribute(editor, &start, nChars);
2194 static BOOL
2195 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2197 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2198 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2200 if (editor->bMouseCaptured)
2201 return FALSE;
2202 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2203 editor->nSelectionType = stPosition;
2205 switch (nKey)
2207 case VK_LEFT:
2208 case VK_RIGHT:
2209 case VK_HOME:
2210 case VK_END:
2211 editor->nUDArrowX = -1;
2212 /* fall through */
2213 case VK_UP:
2214 case VK_DOWN:
2215 case VK_PRIOR:
2216 case VK_NEXT:
2217 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2218 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2219 return TRUE;
2220 case VK_BACK:
2221 case VK_DELETE:
2222 editor->nUDArrowX = -1;
2223 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2224 if (editor->styleFlags & ES_READONLY)
2225 return FALSE;
2226 if (ME_IsSelection(editor))
2228 ME_DeleteSelection(editor);
2229 ME_CommitUndo(editor);
2231 else if (nKey == VK_DELETE)
2233 /* Delete stops group typing.
2234 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2235 ME_DeleteTextAtCursor(editor, 1, 1);
2236 ME_CommitUndo(editor);
2238 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2240 BOOL bDeletionSucceeded;
2241 /* Backspace can be grouped for a single undo */
2242 ME_ContinueCoalescingTransaction(editor);
2243 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2244 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2245 /* Deletion was prevented so the cursor is moved back to where it was.
2246 * (e.g. this happens when trying to delete cell boundaries)
2248 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2250 ME_CommitCoalescingUndo(editor);
2252 else
2253 return TRUE;
2254 ME_MoveCursorFromTableRowStartParagraph(editor);
2255 ME_UpdateSelectionLinkAttribute(editor);
2256 ME_UpdateRepaint(editor, FALSE);
2257 ME_SendRequestResize(editor, FALSE);
2258 return TRUE;
2259 case VK_RETURN:
2260 if (editor->bDialogMode)
2262 if (ctrl_is_down)
2263 return TRUE;
2265 if (!(editor->styleFlags & ES_WANTRETURN))
2267 if (editor->hwndParent)
2269 DWORD dw;
2270 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2271 if (HIWORD(dw) == DC_HASDEFID)
2273 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2274 if (hwDefCtrl)
2276 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2277 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2281 return TRUE;
2285 if (editor->styleFlags & ES_MULTILINE)
2287 ME_Cursor cursor = editor->pCursors[0];
2288 ME_DisplayItem *para = cursor.pPara;
2289 int from, to;
2290 const WCHAR endl = '\r';
2291 const WCHAR endlv10[] = {'\r','\n'};
2292 ME_Style *style;
2294 if (editor->styleFlags & ES_READONLY) {
2295 MessageBeep(MB_ICONERROR);
2296 return TRUE;
2299 ME_GetSelectionOfs(editor, &from, &to);
2300 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2302 if (!editor->bEmulateVersion10) { /* v4.1 */
2303 if (para->member.para.nFlags & MEPF_ROWEND) {
2304 /* Add a new table row after this row. */
2305 para = ME_AppendTableRow(editor, para);
2306 para = para->member.para.next_para;
2307 editor->pCursors[0].pPara = para;
2308 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2309 editor->pCursors[0].nOffset = 0;
2310 editor->pCursors[1] = editor->pCursors[0];
2311 ME_CommitUndo(editor);
2312 ME_CheckTablesForCorruption(editor);
2313 ME_UpdateRepaint(editor, FALSE);
2314 return TRUE;
2316 else if (para == editor->pCursors[1].pPara &&
2317 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2318 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2319 !para->member.para.prev_para->member.para.nCharOfs)
2321 /* Insert a newline before the table. */
2322 para = para->member.para.prev_para;
2323 para->member.para.nFlags &= ~MEPF_ROWSTART;
2324 editor->pCursors[0].pPara = para;
2325 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2326 editor->pCursors[1] = editor->pCursors[0];
2327 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2328 editor->pCursors[0].pRun->member.run.style);
2329 para = editor->pBuffer->pFirst->member.para.next_para;
2330 ME_SetDefaultParaFormat(editor, para->member.para.pFmt);
2331 para->member.para.nFlags = MEPF_REWRAP;
2332 editor->pCursors[0].pPara = para;
2333 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2334 editor->pCursors[1] = editor->pCursors[0];
2335 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2336 ME_CommitCoalescingUndo(editor);
2337 ME_CheckTablesForCorruption(editor);
2338 ME_UpdateRepaint(editor, FALSE);
2339 return TRUE;
2341 } else { /* v1.0 - 3.0 */
2342 ME_DisplayItem *para = cursor.pPara;
2343 if (ME_IsInTable(para))
2345 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2347 if (from == to) {
2348 ME_ContinueCoalescingTransaction(editor);
2349 para = ME_AppendTableRow(editor, para);
2350 editor->pCursors[0].pPara = para;
2351 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2352 editor->pCursors[0].nOffset = 0;
2353 editor->pCursors[1] = editor->pCursors[0];
2354 ME_CommitCoalescingUndo(editor);
2355 ME_UpdateRepaint(editor, FALSE);
2356 return TRUE;
2358 } else {
2359 ME_ContinueCoalescingTransaction(editor);
2360 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2361 !ME_IsInTable(para->member.para.prev_para))
2363 /* Insert newline before table */
2364 cursor.pRun = ME_FindItemBack(para, diRun);
2365 if (cursor.pRun) {
2366 editor->pCursors[0].pRun = cursor.pRun;
2367 editor->pCursors[0].pPara = para->member.para.prev_para;
2369 editor->pCursors[0].nOffset = 0;
2370 editor->pCursors[1] = editor->pCursors[0];
2371 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2372 editor->pCursors[0].pRun->member.run.style);
2373 } else {
2374 editor->pCursors[1] = editor->pCursors[0];
2375 para = ME_AppendTableRow(editor, para);
2376 editor->pCursors[0].pPara = para;
2377 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2378 editor->pCursors[0].nOffset = 0;
2379 editor->pCursors[1] = editor->pCursors[0];
2381 ME_CommitCoalescingUndo(editor);
2382 ME_UpdateRepaint(editor, FALSE);
2383 return TRUE;
2388 style = ME_GetInsertStyle(editor, 0);
2389 ME_SaveTempStyle(editor);
2390 ME_ContinueCoalescingTransaction(editor);
2391 if (shift_is_down)
2392 ME_InsertEndRowFromCursor(editor, 0);
2393 else
2394 if (!editor->bEmulateVersion10)
2395 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2396 else
2397 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2398 ME_ReleaseStyle(style);
2399 ME_CommitCoalescingUndo(editor);
2400 SetCursor(NULL);
2402 ME_UpdateSelectionLinkAttribute(editor);
2403 ME_UpdateRepaint(editor, FALSE);
2405 return TRUE;
2407 break;
2408 case VK_ESCAPE:
2409 if (editor->bDialogMode && editor->hwndParent)
2410 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2411 return TRUE;
2412 case VK_TAB:
2413 if (editor->bDialogMode && editor->hwndParent)
2414 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2415 return TRUE;
2416 case 'A':
2417 if (ctrl_is_down)
2419 handle_EM_EXSETSEL( editor, 0, -1 );
2420 return TRUE;
2422 break;
2423 case 'V':
2424 if (ctrl_is_down)
2425 return ME_Paste(editor);
2426 break;
2427 case 'C':
2428 case 'X':
2429 if (ctrl_is_down)
2431 BOOL result;
2432 int nOfs, nChars;
2433 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2434 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2436 nChars -= nOfs;
2437 result = ME_Copy(editor, selStart, nChars);
2438 if (result && nKey == 'X')
2440 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2441 ME_CommitUndo(editor);
2442 ME_UpdateRepaint(editor, TRUE);
2444 return result;
2446 break;
2447 case 'Z':
2448 if (ctrl_is_down)
2450 ME_Undo(editor);
2451 return TRUE;
2453 break;
2454 case 'Y':
2455 if (ctrl_is_down)
2457 ME_Redo(editor);
2458 return TRUE;
2460 break;
2462 default:
2463 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2464 editor->nUDArrowX = -1;
2465 if (ctrl_is_down)
2467 if (nKey == 'W')
2469 CHARFORMAT2W chf;
2470 char buf[2048];
2471 chf.cbSize = sizeof(chf);
2473 ME_GetSelectionCharFormat(editor, &chf);
2474 ME_DumpStyleToBuf(&chf, buf);
2475 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2477 if (nKey == 'Q')
2479 ME_CheckCharOffsets(editor);
2483 return FALSE;
2486 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2487 LPARAM flags, BOOL unicode)
2489 WCHAR wstr;
2491 if (editor->bMouseCaptured)
2492 return 0;
2494 if (unicode)
2495 wstr = (WCHAR)charCode;
2496 else
2498 CHAR charA = charCode;
2499 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2502 if (editor->styleFlags & ES_READONLY) {
2503 MessageBeep(MB_ICONERROR);
2504 return 0; /* FIXME really 0 ? */
2507 if ((unsigned)wstr >= ' ' || wstr == '\t')
2509 ME_Cursor cursor = editor->pCursors[0];
2510 ME_DisplayItem *para = cursor.pPara;
2511 int from, to;
2512 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2513 ME_GetSelectionOfs(editor, &from, &to);
2514 if (wstr == '\t' &&
2515 /* v4.1 allows tabs to be inserted with ctrl key down */
2516 !(ctrl_is_down && !editor->bEmulateVersion10))
2518 ME_DisplayItem *para;
2519 BOOL bSelectedRow = FALSE;
2521 para = cursor.pPara;
2522 if (ME_IsSelection(editor) &&
2523 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2524 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2525 para->member.para.prev_para->type == diParagraph)
2527 para = para->member.para.prev_para;
2528 bSelectedRow = TRUE;
2530 if (ME_IsInTable(para))
2532 ME_TabPressedInTable(editor, bSelectedRow);
2533 ME_CommitUndo(editor);
2534 return 0;
2536 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2537 if (para->member.para.nFlags & MEPF_ROWEND) {
2538 if (from == to) {
2539 para = para->member.para.next_para;
2540 if (para->member.para.nFlags & MEPF_ROWSTART)
2541 para = para->member.para.next_para;
2542 editor->pCursors[0].pPara = para;
2543 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2544 editor->pCursors[0].nOffset = 0;
2545 editor->pCursors[1] = editor->pCursors[0];
2548 } else { /* v1.0 - 3.0 */
2549 if (ME_IsInTable(cursor.pRun) &&
2550 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2551 from == to)
2553 /* Text should not be inserted at the end of the table. */
2554 MessageBeep(-1);
2555 return 0;
2558 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2559 /* WM_CHAR is restricted to nTextLimit */
2560 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2562 ME_Style *style = ME_GetInsertStyle(editor, 0);
2563 ME_SaveTempStyle(editor);
2564 ME_ContinueCoalescingTransaction(editor);
2565 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2566 ME_ReleaseStyle(style);
2567 ME_CommitCoalescingUndo(editor);
2568 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2571 ME_UpdateSelectionLinkAttribute(editor);
2572 ME_UpdateRepaint(editor, FALSE);
2574 return 0;
2577 /* Process the message and calculate the new click count.
2579 * returns: The click count if it is mouse down event, else returns 0. */
2580 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2581 LPARAM lParam)
2583 static int clickNum = 0;
2584 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2585 return 0;
2587 if ((msg == WM_LBUTTONDBLCLK) ||
2588 (msg == WM_RBUTTONDBLCLK) ||
2589 (msg == WM_MBUTTONDBLCLK) ||
2590 (msg == WM_XBUTTONDBLCLK))
2592 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2595 if ((msg == WM_LBUTTONDOWN) ||
2596 (msg == WM_RBUTTONDOWN) ||
2597 (msg == WM_MBUTTONDOWN) ||
2598 (msg == WM_XBUTTONDOWN))
2600 static MSG prevClickMsg;
2601 MSG clickMsg;
2602 /* Compare the editor instead of the hwnd so that the this
2603 * can still be done for windowless richedit controls. */
2604 clickMsg.hwnd = (HWND)editor;
2605 clickMsg.message = msg;
2606 clickMsg.wParam = wParam;
2607 clickMsg.lParam = lParam;
2608 clickMsg.time = GetMessageTime();
2609 clickMsg.pt.x = (short)LOWORD(lParam);
2610 clickMsg.pt.y = (short)HIWORD(lParam);
2611 if ((clickNum != 0) &&
2612 (clickMsg.message == prevClickMsg.message) &&
2613 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2614 (clickMsg.wParam == prevClickMsg.wParam) &&
2615 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2616 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2617 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2619 clickNum++;
2620 } else {
2621 clickNum = 1;
2623 prevClickMsg = clickMsg;
2624 } else {
2625 return 0;
2627 return clickNum;
2630 static BOOL is_link( ME_Run *run )
2632 return (run->style->fmt.dwMask & CFM_LINK) && (run->style->fmt.dwEffects & CFE_LINK);
2635 static BOOL ME_SetCursor(ME_TextEditor *editor)
2637 ME_Cursor cursor;
2638 POINT pt;
2639 BOOL isExact;
2640 SCROLLBARINFO sbi;
2641 DWORD messagePos = GetMessagePos();
2642 pt.x = (short)LOWORD(messagePos);
2643 pt.y = (short)HIWORD(messagePos);
2645 if (editor->hWnd)
2647 sbi.cbSize = sizeof(sbi);
2648 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2649 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2650 PtInRect(&sbi.rcScrollBar, pt))
2652 ITextHost_TxSetCursor(editor->texthost,
2653 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2654 return TRUE;
2656 sbi.cbSize = sizeof(sbi);
2657 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2658 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2659 PtInRect(&sbi.rcScrollBar, pt))
2661 ITextHost_TxSetCursor(editor->texthost,
2662 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2663 return TRUE;
2666 ITextHost_TxScreenToClient(editor->texthost, &pt);
2668 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2669 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2670 return TRUE;
2672 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2673 pt.y < editor->rcFormat.top &&
2674 pt.x < editor->rcFormat.left)
2676 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2677 return TRUE;
2679 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2681 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2682 ITextHost_TxSetCursor(editor->texthost,
2683 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2684 else /* v4.1 */
2685 ITextHost_TxSetCursor(editor->texthost,
2686 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2687 return TRUE;
2689 if (pt.x < editor->rcFormat.left)
2691 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2692 return TRUE;
2694 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2695 if (isExact)
2697 ME_Run *run;
2699 run = &cursor.pRun->member.run;
2700 if (is_link( run ))
2702 ITextHost_TxSetCursor(editor->texthost,
2703 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2704 FALSE);
2705 return TRUE;
2708 if (ME_IsSelection(editor))
2710 int selStart, selEnd;
2711 int offset = ME_GetCursorOfs(&cursor);
2713 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2714 if (selStart <= offset && selEnd >= offset) {
2715 ITextHost_TxSetCursor(editor->texthost,
2716 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2717 FALSE);
2718 return TRUE;
2722 ITextHost_TxSetCursor(editor->texthost,
2723 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2724 return TRUE;
2727 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2729 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2730 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2731 editor->rcFormat.left += 1 + editor->selofs;
2732 editor->rcFormat.right -= 1;
2735 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2737 CHARRANGE selrange;
2738 HMENU menu;
2739 int seltype = 0;
2740 if(!editor->lpOleCallback || !editor->hWnd)
2741 return FALSE;
2742 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2743 if(selrange.cpMin == selrange.cpMax)
2744 seltype |= SEL_EMPTY;
2745 else
2747 /* FIXME: Handle objects */
2748 seltype |= SEL_TEXT;
2749 if(selrange.cpMax-selrange.cpMin > 1)
2750 seltype |= SEL_MULTICHAR;
2752 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2754 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2755 DestroyMenu(menu);
2757 return TRUE;
2760 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10, DWORD csStyle)
2762 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2763 int i;
2764 DWORD props;
2765 LONG selbarwidth;
2767 ed->hWnd = NULL;
2768 ed->hwndParent = NULL;
2769 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2770 ed->texthost = texthost;
2771 ed->reOle = NULL;
2772 ed->bEmulateVersion10 = bEmulateVersion10;
2773 ed->styleFlags = 0;
2774 ed->alignStyle = PFA_LEFT;
2775 if (csStyle & ES_RIGHT)
2776 ed->alignStyle = PFA_RIGHT;
2777 if (csStyle & ES_CENTER)
2778 ed->alignStyle = PFA_CENTER;
2779 ITextHost_TxGetPropertyBits(texthost,
2780 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2781 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2782 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2783 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2784 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2785 &props);
2786 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2787 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2788 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2789 ed->pBuffer = ME_MakeText();
2790 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2791 ed->nAvailWidth = 0; /* wrap to client area */
2792 ME_MakeFirstParagraph(ed);
2793 /* The four cursors are for:
2794 * 0 - The position where the caret is shown
2795 * 1 - The anchored end of the selection (for normal selection)
2796 * 2 & 3 - The anchored start and end respectively for word, line,
2797 * or paragraph selection.
2799 ed->nCursors = 4;
2800 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2801 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2802 ed->pCursors[1] = ed->pCursors[0];
2803 ed->pCursors[2] = ed->pCursors[0];
2804 ed->pCursors[3] = ed->pCursors[1];
2805 ed->nLastTotalLength = ed->nTotalLength = 0;
2806 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2807 ed->nUDArrowX = -1;
2808 ed->rgbBackColor = -1;
2809 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2810 ed->bCaretAtEnd = FALSE;
2811 ed->nEventMask = 0;
2812 ed->nModifyStep = 0;
2813 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2814 list_init( &ed->undo_stack );
2815 list_init( &ed->redo_stack );
2816 ed->nUndoStackSize = 0;
2817 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2818 ed->nUndoMode = umAddToUndo;
2819 ed->nParagraphs = 1;
2820 ed->nLastSelStart = ed->nLastSelEnd = 0;
2821 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2822 ed->bHideSelection = FALSE;
2823 ed->pfnWordBreak = NULL;
2824 ed->lpOleCallback = NULL;
2825 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2826 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2827 ed->AutoURLDetect_bEnable = FALSE;
2828 ed->bHaveFocus = FALSE;
2829 ed->bDialogMode = FALSE;
2830 ed->bMouseCaptured = FALSE;
2831 for (i=0; i<HFONT_CACHE_SIZE; i++)
2833 ed->pFontCache[i].nRefs = 0;
2834 ed->pFontCache[i].nAge = 0;
2835 ed->pFontCache[i].hFont = NULL;
2838 ME_CheckCharOffsets(ed);
2839 ed->bDefaultFormatRect = TRUE;
2840 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2841 if (selbarwidth) {
2842 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2843 ed->selofs = SELECTIONBAR_WIDTH;
2844 ed->styleFlags |= ES_SELECTIONBAR;
2845 } else {
2846 ed->selofs = 0;
2848 ed->nSelectionType = stPosition;
2850 ed->cPasswordMask = 0;
2851 if (props & TXTBIT_USEPASSWORD)
2852 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2854 if (props & TXTBIT_AUTOWORDSEL)
2855 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2856 if (props & TXTBIT_MULTILINE) {
2857 ed->styleFlags |= ES_MULTILINE;
2858 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2859 } else {
2860 ed->bWordWrap = FALSE;
2862 if (props & TXTBIT_READONLY)
2863 ed->styleFlags |= ES_READONLY;
2864 if (!(props & TXTBIT_HIDESELECTION))
2865 ed->styleFlags |= ES_NOHIDESEL;
2866 if (props & TXTBIT_SAVESELECTION)
2867 ed->styleFlags |= ES_SAVESEL;
2868 if (props & TXTBIT_VERTICAL)
2869 ed->styleFlags |= ES_VERTICAL;
2870 if (props & TXTBIT_DISABLEDRAG)
2871 ed->styleFlags |= ES_NOOLEDRAGDROP;
2873 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2875 /* Default scrollbar information */
2876 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2877 ed->vert_si.nMin = 0;
2878 ed->vert_si.nMax = 0;
2879 ed->vert_si.nPage = 0;
2880 ed->vert_si.nPos = 0;
2882 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2883 ed->horz_si.nMin = 0;
2884 ed->horz_si.nMax = 0;
2885 ed->horz_si.nPage = 0;
2886 ed->horz_si.nPos = 0;
2888 ed->wheel_remain = 0;
2890 list_init( &ed->style_list );
2891 OleInitialize(NULL);
2893 return ed;
2896 void ME_DestroyEditor(ME_TextEditor *editor)
2898 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2899 ME_DisplayItem *p = pFirst, *pNext = NULL;
2900 ME_Style *s, *cursor2;
2901 int i;
2903 ME_ClearTempStyle(editor);
2904 ME_EmptyUndoStack(editor);
2905 while(p) {
2906 pNext = p->next;
2907 ME_DestroyDisplayItem(p);
2908 p = pNext;
2911 LIST_FOR_EACH_ENTRY_SAFE( s, cursor2, &editor->style_list, ME_Style, entry )
2912 ME_DestroyStyle( s );
2914 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2915 for (i=0; i<HFONT_CACHE_SIZE; i++)
2917 if (editor->pFontCache[i].hFont)
2918 DeleteObject(editor->pFontCache[i].hFont);
2920 if (editor->rgbBackColor != -1)
2921 DeleteObject(editor->hbrBackground);
2922 if(editor->lpOleCallback)
2923 IRichEditOleCallback_Release(editor->lpOleCallback);
2924 ITextHost_Release(editor->texthost);
2925 if (editor->reOle)
2927 IRichEditOle_Release(editor->reOle);
2928 editor->reOle = NULL;
2930 OleUninitialize();
2932 FREE_OBJ(editor->pBuffer);
2933 FREE_OBJ(editor->pCursors);
2935 FREE_OBJ(editor);
2938 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2940 TRACE("\n");
2941 switch (fdwReason)
2943 case DLL_PROCESS_ATTACH:
2944 DisableThreadLibraryCalls(hinstDLL);
2945 me_heap = HeapCreate (0, 0x10000, 0);
2946 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2947 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2948 LookupInit();
2949 break;
2951 case DLL_PROCESS_DETACH:
2952 if (lpvReserved) break;
2953 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2954 UnregisterClassW(MSFTEDIT_CLASS, 0);
2955 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2956 UnregisterClassA("RichEdit50A", 0);
2957 if (ME_ListBoxRegistered)
2958 UnregisterClassW(REListBox20W, 0);
2959 if (ME_ComboBoxRegistered)
2960 UnregisterClassW(REComboBox20W, 0);
2961 LookupCleanup();
2962 HeapDestroy (me_heap);
2963 release_typelib();
2964 break;
2966 return TRUE;
2969 static inline int get_default_line_height( ME_TextEditor *editor )
2971 int height = 0;
2973 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2974 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2975 if (height <= 0) height = 24;
2977 return height;
2980 static inline int calc_wheel_change( int *remain, int amount_per_click )
2982 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2983 *remain -= WHEEL_DELTA * change / amount_per_click;
2984 return change;
2987 static const char * const edit_messages[] = {
2988 "EM_GETSEL",
2989 "EM_SETSEL",
2990 "EM_GETRECT",
2991 "EM_SETRECT",
2992 "EM_SETRECTNP",
2993 "EM_SCROLL",
2994 "EM_LINESCROLL",
2995 "EM_SCROLLCARET",
2996 "EM_GETMODIFY",
2997 "EM_SETMODIFY",
2998 "EM_GETLINECOUNT",
2999 "EM_LINEINDEX",
3000 "EM_SETHANDLE",
3001 "EM_GETHANDLE",
3002 "EM_GETTHUMB",
3003 "EM_UNKNOWN_BF",
3004 "EM_UNKNOWN_C0",
3005 "EM_LINELENGTH",
3006 "EM_REPLACESEL",
3007 "EM_UNKNOWN_C3",
3008 "EM_GETLINE",
3009 "EM_LIMITTEXT",
3010 "EM_CANUNDO",
3011 "EM_UNDO",
3012 "EM_FMTLINES",
3013 "EM_LINEFROMCHAR",
3014 "EM_UNKNOWN_CA",
3015 "EM_SETTABSTOPS",
3016 "EM_SETPASSWORDCHAR",
3017 "EM_EMPTYUNDOBUFFER",
3018 "EM_GETFIRSTVISIBLELINE",
3019 "EM_SETREADONLY",
3020 "EM_SETWORDBREAKPROC",
3021 "EM_GETWORDBREAKPROC",
3022 "EM_GETPASSWORDCHAR",
3023 "EM_SETMARGINS",
3024 "EM_GETMARGINS",
3025 "EM_GETLIMITTEXT",
3026 "EM_POSFROMCHAR",
3027 "EM_CHARFROMPOS",
3028 "EM_SETIMESTATUS",
3029 "EM_GETIMESTATUS"
3032 static const char * const richedit_messages[] = {
3033 "EM_CANPASTE",
3034 "EM_DISPLAYBAND",
3035 "EM_EXGETSEL",
3036 "EM_EXLIMITTEXT",
3037 "EM_EXLINEFROMCHAR",
3038 "EM_EXSETSEL",
3039 "EM_FINDTEXT",
3040 "EM_FORMATRANGE",
3041 "EM_GETCHARFORMAT",
3042 "EM_GETEVENTMASK",
3043 "EM_GETOLEINTERFACE",
3044 "EM_GETPARAFORMAT",
3045 "EM_GETSELTEXT",
3046 "EM_HIDESELECTION",
3047 "EM_PASTESPECIAL",
3048 "EM_REQUESTRESIZE",
3049 "EM_SELECTIONTYPE",
3050 "EM_SETBKGNDCOLOR",
3051 "EM_SETCHARFORMAT",
3052 "EM_SETEVENTMASK",
3053 "EM_SETOLECALLBACK",
3054 "EM_SETPARAFORMAT",
3055 "EM_SETTARGETDEVICE",
3056 "EM_STREAMIN",
3057 "EM_STREAMOUT",
3058 "EM_GETTEXTRANGE",
3059 "EM_FINDWORDBREAK",
3060 "EM_SETOPTIONS",
3061 "EM_GETOPTIONS",
3062 "EM_FINDTEXTEX",
3063 "EM_GETWORDBREAKPROCEX",
3064 "EM_SETWORDBREAKPROCEX",
3065 "EM_SETUNDOLIMIT",
3066 "EM_UNKNOWN_USER_83",
3067 "EM_REDO",
3068 "EM_CANREDO",
3069 "EM_GETUNDONAME",
3070 "EM_GETREDONAME",
3071 "EM_STOPGROUPTYPING",
3072 "EM_SETTEXTMODE",
3073 "EM_GETTEXTMODE",
3074 "EM_AUTOURLDETECT",
3075 "EM_GETAUTOURLDETECT",
3076 "EM_SETPALETTE",
3077 "EM_GETTEXTEX",
3078 "EM_GETTEXTLENGTHEX",
3079 "EM_SHOWSCROLLBAR",
3080 "EM_SETTEXTEX",
3081 "EM_UNKNOWN_USER_98",
3082 "EM_UNKNOWN_USER_99",
3083 "EM_SETPUNCTUATION",
3084 "EM_GETPUNCTUATION",
3085 "EM_SETWORDWRAPMODE",
3086 "EM_GETWORDWRAPMODE",
3087 "EM_SETIMECOLOR",
3088 "EM_GETIMECOLOR",
3089 "EM_SETIMEOPTIONS",
3090 "EM_GETIMEOPTIONS",
3091 "EM_CONVPOSITION",
3092 "EM_UNKNOWN_USER_109",
3093 "EM_UNKNOWN_USER_110",
3094 "EM_UNKNOWN_USER_111",
3095 "EM_UNKNOWN_USER_112",
3096 "EM_UNKNOWN_USER_113",
3097 "EM_UNKNOWN_USER_114",
3098 "EM_UNKNOWN_USER_115",
3099 "EM_UNKNOWN_USER_116",
3100 "EM_UNKNOWN_USER_117",
3101 "EM_UNKNOWN_USER_118",
3102 "EM_UNKNOWN_USER_119",
3103 "EM_SETLANGOPTIONS",
3104 "EM_GETLANGOPTIONS",
3105 "EM_GETIMECOMPMODE",
3106 "EM_FINDTEXTW",
3107 "EM_FINDTEXTEXW",
3108 "EM_RECONVERSION",
3109 "EM_SETIMEMODEBIAS",
3110 "EM_GETIMEMODEBIAS"
3113 static const char *
3114 get_msg_name(UINT msg)
3116 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3117 return edit_messages[msg - EM_GETSEL];
3118 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3119 return richedit_messages[msg - EM_CANPASTE];
3120 return "";
3123 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3125 int x,y;
3126 BOOL isExact;
3127 ME_Cursor cursor; /* The start of the clicked text. */
3129 ENLINK info;
3130 x = (short)LOWORD(lParam);
3131 y = (short)HIWORD(lParam);
3132 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3133 if (!isExact) return;
3135 if (is_link( &cursor.pRun->member.run ))
3136 { /* The clicked run has CFE_LINK set */
3137 ME_DisplayItem *di;
3139 info.nmhdr.hwndFrom = NULL;
3140 info.nmhdr.idFrom = 0;
3141 info.nmhdr.code = EN_LINK;
3142 info.msg = msg;
3143 info.wParam = wParam;
3144 info.lParam = lParam;
3145 cursor.nOffset = 0;
3147 /* find the first contiguous run with CFE_LINK set */
3148 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3149 di = cursor.pRun;
3150 while (ME_PrevRun( NULL, &di, FALSE ) && is_link( &di->member.run ))
3151 info.chrg.cpMin -= di->member.run.len;
3153 /* find the last contiguous run with CFE_LINK set */
3154 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3155 di = cursor.pRun;
3156 while (ME_NextRun( NULL, &di, FALSE ) && is_link( &di->member.run ))
3157 info.chrg.cpMax += di->member.run.len;
3159 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3163 void ME_ReplaceSel(ME_TextEditor *editor, BOOL can_undo, const WCHAR *str, int len)
3165 int from, to, nStartCursor;
3166 ME_Style *style;
3168 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3169 style = ME_GetSelectionInsertStyle(editor);
3170 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3171 ME_InsertTextFromCursor(editor, 0, str, len, style);
3172 ME_ReleaseStyle(style);
3173 /* drop temporary style if line end */
3175 * FIXME question: does abc\n mean: put abc,
3176 * clear temp style, put \n? (would require a change)
3178 if (len>0 && str[len-1] == '\n')
3179 ME_ClearTempStyle(editor);
3180 ME_CommitUndo(editor);
3181 ME_UpdateSelectionLinkAttribute(editor);
3182 if (!can_undo)
3183 ME_EmptyUndoStack(editor);
3184 ME_UpdateRepaint(editor, FALSE);
3187 static void ME_SetText(ME_TextEditor *editor, void *text, BOOL unicode)
3189 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3190 int textLen;
3192 LPWSTR wszText = ME_ToUnicode(codepage, text, &textLen);
3194 if (textLen > 0)
3196 int len = -1;
3198 /* uses default style! */
3199 if (!(editor->styleFlags & ES_MULTILINE))
3201 WCHAR *p = wszText;
3203 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3204 len = p - wszText;
3206 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3208 ME_EndToUnicode(codepage, wszText);
3211 static LRESULT ME_WmCreate(ME_TextEditor *editor, LPARAM lParam, BOOL unicode)
3213 CREATESTRUCTW *createW = (CREATESTRUCTW*)lParam;
3214 CREATESTRUCTA *createA = (CREATESTRUCTA*)lParam;
3215 void *text = NULL;
3216 INT max;
3218 if (lParam)
3219 text = unicode ? (void*)createW->lpszName : (void*)createA->lpszName;
3221 ME_SetDefaultFormatRect(editor);
3223 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3224 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3225 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3227 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3228 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3230 if (editor->styleFlags & ES_DISABLENOSCROLL)
3232 if (editor->styleFlags & WS_VSCROLL)
3234 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3235 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3237 if (editor->styleFlags & WS_HSCROLL)
3239 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3240 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3244 if (text)
3246 ME_SetText(editor, text, unicode);
3247 ME_SetCursorToStart(editor, &editor->pCursors[0]);
3248 ME_SetCursorToStart(editor, &editor->pCursors[1]);
3251 ME_CommitUndo(editor);
3252 ME_WrapMarkedParagraphs(editor);
3253 ME_MoveCaret(editor);
3254 return 0;
3258 #define UNSUPPORTED_MSG(e) \
3259 case e: \
3260 FIXME(#e ": stub\n"); \
3261 *phresult = S_FALSE; \
3262 return 0;
3264 /* Handle messages for windowless and windowed richedit controls.
3266 * The LRESULT that is returned is a return value for window procs,
3267 * and the phresult parameter is the COM return code needed by the
3268 * text services interface. */
3269 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3270 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3272 *phresult = S_OK;
3274 switch(msg) {
3276 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3277 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3278 UNSUPPORTED_MSG(EM_FMTLINES)
3279 UNSUPPORTED_MSG(EM_FORMATRANGE)
3280 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3281 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3282 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3283 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3284 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3285 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3286 UNSUPPORTED_MSG(EM_GETREDONAME)
3287 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3288 UNSUPPORTED_MSG(EM_GETUNDONAME)
3289 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3290 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3291 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3292 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3293 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3294 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3295 UNSUPPORTED_MSG(EM_SETMARGINS)
3296 UNSUPPORTED_MSG(EM_SETPALETTE)
3297 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3298 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3299 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3301 /* Messages specific to Richedit controls */
3303 case EM_STREAMIN:
3304 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3305 case EM_STREAMOUT:
3306 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3307 case WM_GETDLGCODE:
3309 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3311 if (lParam)
3312 editor->bDialogMode = TRUE;
3313 if (editor->styleFlags & ES_MULTILINE)
3314 code |= DLGC_WANTMESSAGE;
3315 if (!(editor->styleFlags & ES_SAVESEL))
3316 code |= DLGC_HASSETSEL;
3317 return code;
3319 case EM_EMPTYUNDOBUFFER:
3320 ME_EmptyUndoStack(editor);
3321 return 0;
3322 case EM_GETSEL:
3324 /* Note: wParam/lParam can be NULL */
3325 UINT from, to;
3326 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3327 PUINT pto = lParam ? (PUINT)lParam : &to;
3328 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3329 if ((*pfrom|*pto) & 0xFFFF0000)
3330 return -1;
3331 return MAKELONG(*pfrom,*pto);
3333 case EM_EXGETSEL:
3335 CHARRANGE *pRange = (CHARRANGE *)lParam;
3336 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3337 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3338 return 0;
3340 case EM_SETUNDOLIMIT:
3342 if ((int)wParam < 0)
3343 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3344 else
3345 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3346 /* Setting a max stack size keeps wine from getting killed
3347 for hogging memory. Windows allocates all this memory at once, so
3348 no program would realistically set a value above our maximum. */
3349 return editor->nUndoLimit;
3351 case EM_CANUNDO:
3352 return !list_empty( &editor->undo_stack );
3353 case EM_CANREDO:
3354 return !list_empty( &editor->redo_stack );
3355 case WM_UNDO: /* FIXME: actually not the same */
3356 case EM_UNDO:
3357 return ME_Undo(editor);
3358 case EM_REDO:
3359 return ME_Redo(editor);
3360 case EM_GETOPTIONS:
3362 /* these flags are equivalent to the ES_* counterparts */
3363 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3364 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3365 DWORD settings = editor->styleFlags & mask;
3367 return settings;
3369 case EM_SETFONTSIZE:
3371 CHARFORMAT2W cf;
3372 LONG tmp_size, size;
3373 BOOL is_increase = ((LONG)wParam > 0);
3375 if (editor->mode & TM_PLAINTEXT)
3376 return FALSE;
3378 cf.cbSize = sizeof(cf);
3379 cf.dwMask = CFM_SIZE;
3380 ME_GetSelectionCharFormat(editor, &cf);
3381 tmp_size = (cf.yHeight / 20) + wParam;
3383 if (tmp_size <= 1)
3384 size = 1;
3385 else if (tmp_size > 12 && tmp_size < 28 && tmp_size % 2)
3386 size = tmp_size + (is_increase ? 1 : -1);
3387 else if (tmp_size > 28 && tmp_size < 36)
3388 size = is_increase ? 36 : 28;
3389 else if (tmp_size > 36 && tmp_size < 48)
3390 size = is_increase ? 48 : 36;
3391 else if (tmp_size > 48 && tmp_size < 72)
3392 size = is_increase ? 72 : 48;
3393 else if (tmp_size > 72 && tmp_size < 80)
3394 size = is_increase ? 80 : 72;
3395 else if (tmp_size > 80 && tmp_size < 1638)
3396 size = 10 * (is_increase ? (tmp_size / 10 + 1) : (tmp_size / 10));
3397 else if (tmp_size >= 1638)
3398 size = 1638;
3399 else
3400 size = tmp_size;
3402 cf.yHeight = size * 20; /* convert twips to points */
3403 ME_SetSelectionCharFormat(editor, &cf);
3404 ME_CommitUndo(editor);
3405 ME_WrapMarkedParagraphs(editor);
3406 ME_UpdateScrollBar(editor);
3407 ME_Repaint(editor);
3409 return TRUE;
3411 case EM_SETOPTIONS:
3413 /* these flags are equivalent to ES_* counterparts, except for
3414 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3415 * but is still stored in editor->styleFlags. */
3416 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3417 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3418 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3419 DWORD settings = mask & editor->styleFlags;
3420 DWORD oldSettings = settings;
3421 DWORD changedSettings;
3423 switch(wParam)
3425 case ECOOP_SET:
3426 settings = lParam;
3427 break;
3428 case ECOOP_OR:
3429 settings |= lParam;
3430 break;
3431 case ECOOP_AND:
3432 settings &= lParam;
3433 break;
3434 case ECOOP_XOR:
3435 settings ^= lParam;
3437 changedSettings = oldSettings ^ settings;
3439 if (changedSettings) {
3440 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3442 if (changedSettings & ECO_SELECTIONBAR)
3444 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3445 if (settings & ECO_SELECTIONBAR) {
3446 assert(!editor->selofs);
3447 editor->selofs = SELECTIONBAR_WIDTH;
3448 editor->rcFormat.left += editor->selofs;
3449 } else {
3450 editor->rcFormat.left -= editor->selofs;
3451 editor->selofs = 0;
3453 ME_RewrapRepaint(editor);
3456 if ((changedSettings & settings & ES_NOHIDESEL) && !editor->bHaveFocus)
3457 ME_InvalidateSelection( editor );
3459 if (changedSettings & settings & ECO_VERTICAL)
3460 FIXME("ECO_VERTICAL not implemented yet!\n");
3461 if (changedSettings & settings & ECO_AUTOHSCROLL)
3462 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3463 if (changedSettings & settings & ECO_AUTOVSCROLL)
3464 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3465 if (changedSettings & settings & ECO_WANTRETURN)
3466 FIXME("ECO_WANTRETURN not implemented yet!\n");
3467 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3468 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3471 return settings;
3473 case EM_SETSEL:
3475 return handle_EM_EXSETSEL( editor, wParam, lParam );
3477 case EM_SETSCROLLPOS:
3479 POINT *point = (POINT *)lParam;
3480 ME_ScrollAbs(editor, point->x, point->y);
3481 return 0;
3483 case EM_AUTOURLDETECT:
3485 if (wParam==1 || wParam ==0)
3487 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3488 return 0;
3490 return E_INVALIDARG;
3492 case EM_GETAUTOURLDETECT:
3494 return editor->AutoURLDetect_bEnable;
3496 case EM_EXSETSEL:
3498 CHARRANGE range = *(CHARRANGE *)lParam;
3500 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3502 case EM_SHOWSCROLLBAR:
3504 DWORD flags;
3506 switch (wParam)
3508 case SB_HORZ:
3509 flags = WS_HSCROLL;
3510 break;
3511 case SB_VERT:
3512 flags = WS_VSCROLL;
3513 break;
3514 case SB_BOTH:
3515 flags = WS_HSCROLL|WS_VSCROLL;
3516 break;
3517 default:
3518 return 0;
3521 if (lParam) {
3522 editor->styleFlags |= flags;
3523 if (flags & WS_HSCROLL)
3524 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3525 editor->nTotalWidth > editor->sizeWindow.cx);
3526 if (flags & WS_VSCROLL)
3527 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3528 editor->nTotalLength > editor->sizeWindow.cy);
3529 } else {
3530 editor->styleFlags &= ~flags;
3531 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3533 return 0;
3535 case EM_SETTEXTEX:
3537 LPWSTR wszText;
3538 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3539 int from, to, len;
3540 ME_Style *style;
3541 BOOL bRtf, bUnicode, bSelection, bUTF8;
3542 int oldModify = editor->nModifyStep;
3543 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3545 if (!pStruct) return 0;
3547 /* If we detect ascii rtf at the start of the string,
3548 * we know it isn't unicode. */
3549 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3550 !strncmp((char *)lParam, "{\\urtf", 6)));
3551 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3552 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3554 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3555 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3556 pStruct->flags, pStruct->codepage);
3558 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3559 if (bSelection) {
3560 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3561 style = ME_GetSelectionInsertStyle(editor);
3562 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3563 } else {
3564 ME_Cursor start;
3565 ME_SetCursorToStart(editor, &start);
3566 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3567 style = editor->pBuffer->pDefaultStyle;
3570 if (bRtf) {
3571 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3572 if (bSelection) {
3573 /* FIXME: The length returned doesn't include the rtf control
3574 * characters, only the actual text. */
3575 len = lParam ? strlen((char *)lParam) : 0;
3577 } else {
3578 if (bUTF8 && !bUnicode) {
3579 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3580 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3581 ME_EndToUnicode(CP_UTF8, wszText);
3582 } else {
3583 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3584 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3585 ME_EndToUnicode(pStruct->codepage, wszText);
3589 if (bSelection) {
3590 ME_ReleaseStyle(style);
3591 ME_UpdateSelectionLinkAttribute(editor);
3592 } else {
3593 ME_Cursor cursor;
3594 len = 1;
3595 ME_SetCursorToStart(editor, &cursor);
3596 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3598 ME_CommitUndo(editor);
3599 if (!(pStruct->flags & ST_KEEPUNDO))
3601 editor->nModifyStep = oldModify;
3602 ME_EmptyUndoStack(editor);
3604 ME_UpdateRepaint(editor, FALSE);
3605 return len;
3607 case EM_SETBKGNDCOLOR:
3609 LRESULT lColor;
3610 if (editor->rgbBackColor != -1) {
3611 DeleteObject(editor->hbrBackground);
3612 lColor = editor->rgbBackColor;
3614 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3616 if (wParam)
3618 editor->rgbBackColor = -1;
3619 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3621 else
3623 editor->rgbBackColor = lParam;
3624 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3626 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3627 return lColor;
3629 case EM_GETMODIFY:
3630 return editor->nModifyStep == 0 ? 0 : -1;
3631 case EM_SETMODIFY:
3633 if (wParam)
3634 editor->nModifyStep = 1;
3635 else
3636 editor->nModifyStep = 0;
3638 return 0;
3640 case EM_SETREADONLY:
3642 if (wParam)
3643 editor->styleFlags |= ES_READONLY;
3644 else
3645 editor->styleFlags &= ~ES_READONLY;
3646 return 1;
3648 case EM_SETEVENTMASK:
3650 DWORD nOldMask = editor->nEventMask;
3652 editor->nEventMask = lParam;
3653 return nOldMask;
3655 case EM_GETEVENTMASK:
3656 return editor->nEventMask;
3657 case EM_SETCHARFORMAT:
3659 CHARFORMAT2W buf, *p;
3660 BOOL bRepaint = TRUE;
3661 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3662 if (p == NULL) return 0;
3663 if (wParam & SCF_ALL) {
3664 if (editor->mode & TM_PLAINTEXT) {
3665 ME_SetDefaultCharFormat(editor, p);
3666 } else {
3667 ME_Cursor start;
3668 ME_SetCursorToStart(editor, &start);
3669 ME_SetCharFormat(editor, &start, NULL, p);
3670 editor->nModifyStep = 1;
3672 } else if (wParam & SCF_SELECTION) {
3673 if (editor->mode & TM_PLAINTEXT)
3674 return 0;
3675 if (wParam & SCF_WORD) {
3676 ME_Cursor start;
3677 ME_Cursor end = editor->pCursors[0];
3678 ME_MoveCursorWords(editor, &end, +1);
3679 start = end;
3680 ME_MoveCursorWords(editor, &start, -1);
3681 ME_SetCharFormat(editor, &start, &end, p);
3683 bRepaint = ME_IsSelection(editor);
3684 ME_SetSelectionCharFormat(editor, p);
3685 if (bRepaint) editor->nModifyStep = 1;
3686 } else { /* SCF_DEFAULT */
3687 ME_SetDefaultCharFormat(editor, p);
3689 ME_CommitUndo(editor);
3690 if (bRepaint)
3692 ME_WrapMarkedParagraphs(editor);
3693 ME_UpdateScrollBar(editor);
3694 ME_Repaint(editor);
3696 return 1;
3698 case EM_GETCHARFORMAT:
3700 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3701 if (dst->cbSize != sizeof(CHARFORMATA) &&
3702 dst->cbSize != sizeof(CHARFORMATW) &&
3703 dst->cbSize != sizeof(CHARFORMAT2A) &&
3704 dst->cbSize != sizeof(CHARFORMAT2W))
3705 return 0;
3706 tmp.cbSize = sizeof(tmp);
3707 if (!wParam)
3708 ME_GetDefaultCharFormat(editor, &tmp);
3709 else
3710 ME_GetSelectionCharFormat(editor, &tmp);
3711 ME_CopyToCFAny(dst, &tmp);
3712 return tmp.dwMask;
3714 case EM_SETPARAFORMAT:
3716 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3717 ME_WrapMarkedParagraphs(editor);
3718 ME_UpdateScrollBar(editor);
3719 ME_Repaint(editor);
3720 ME_CommitUndo(editor);
3721 return result;
3723 case EM_GETPARAFORMAT:
3724 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3725 return ((PARAFORMAT2 *)lParam)->dwMask;
3726 case EM_GETFIRSTVISIBLELINE:
3728 ME_DisplayItem *p = editor->pBuffer->pFirst;
3729 int y = editor->vert_si.nPos;
3730 int ypara = 0;
3731 int count = 0;
3732 int ystart, yend;
3733 while(p) {
3734 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3735 if (p->type == diTextEnd)
3736 break;
3737 if (p->type == diParagraph) {
3738 ypara = p->member.para.pt.y;
3739 continue;
3741 ystart = ypara + p->member.row.pt.y;
3742 yend = ystart + p->member.row.nHeight;
3743 if (y < yend) {
3744 break;
3746 count++;
3748 return count;
3750 case EM_HIDESELECTION:
3752 editor->bHideSelection = (wParam != 0);
3753 ME_InvalidateSelection(editor);
3754 return 0;
3756 case EM_LINESCROLL:
3758 if (!(editor->styleFlags & ES_MULTILINE))
3759 return FALSE;
3760 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3761 return TRUE;
3763 case WM_CLEAR:
3765 int from, to;
3766 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3767 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3768 ME_CommitUndo(editor);
3769 ME_UpdateRepaint(editor, TRUE);
3770 return 0;
3772 case EM_REPLACESEL:
3774 int len = 0;
3775 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3776 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3778 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3780 ME_ReplaceSel(editor, !!wParam, wszText, len);
3781 ME_EndToUnicode(codepage, wszText);
3782 return len;
3784 case EM_SCROLLCARET:
3785 ME_EnsureVisible(editor, &editor->pCursors[0]);
3786 return 0;
3787 case WM_SETFONT:
3789 LOGFONTW lf;
3790 CHARFORMAT2W fmt;
3791 HDC hDC;
3792 BOOL bRepaint = LOWORD(lParam);
3794 if (!wParam)
3795 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3797 if (!GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf))
3798 return 0;
3800 hDC = ITextHost_TxGetDC(editor->texthost);
3801 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3802 ITextHost_TxReleaseDC(editor->texthost, hDC);
3803 if (editor->mode & TM_RICHTEXT) {
3804 ME_Cursor start;
3805 ME_SetCursorToStart(editor, &start);
3806 ME_SetCharFormat(editor, &start, NULL, &fmt);
3808 ME_SetDefaultCharFormat(editor, &fmt);
3810 ME_CommitUndo(editor);
3811 ME_MarkAllForWrapping(editor);
3812 ME_WrapMarkedParagraphs(editor);
3813 ME_UpdateScrollBar(editor);
3814 if (bRepaint)
3815 ME_Repaint(editor);
3816 return 0;
3818 case WM_SETTEXT:
3820 ME_Cursor cursor;
3821 ME_SetCursorToStart(editor, &cursor);
3822 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3823 if (lParam)
3825 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3826 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3827 !strncmp((char *)lParam, "{\\urtf", 6))
3829 /* Undocumented: WM_SETTEXT supports RTF text */
3830 ME_StreamInRTFString(editor, 0, (char *)lParam);
3832 else
3833 ME_SetText(editor, (void*)lParam, unicode);
3835 else
3836 TRACE("WM_SETTEXT - NULL\n");
3837 ME_SetCursorToStart(editor, &cursor);
3838 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3839 ME_SetSelection(editor, 0, 0);
3840 editor->nModifyStep = 0;
3841 ME_CommitUndo(editor);
3842 ME_EmptyUndoStack(editor);
3843 ME_UpdateRepaint(editor, FALSE);
3844 return 1;
3846 case EM_CANPASTE:
3848 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3849 if (IsClipboardFormatAvailable(nRTFFormat))
3850 return TRUE;
3851 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3852 return TRUE;
3853 return FALSE;
3855 case WM_PASTE:
3856 case WM_MBUTTONDOWN:
3857 ME_Paste(editor);
3858 return 0;
3859 case WM_CUT:
3860 case WM_COPY:
3862 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3863 int nChars = nTo - nFrom;
3864 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3866 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3868 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3869 ME_CommitUndo(editor);
3870 ME_UpdateRepaint(editor, TRUE);
3872 return 0;
3874 case WM_GETTEXTLENGTH:
3876 GETTEXTLENGTHEX how;
3878 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3879 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3880 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3881 return ME_GetTextLengthEx(editor, &how);
3883 case EM_GETTEXTLENGTHEX:
3884 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3885 case WM_GETTEXT:
3887 GETTEXTEX ex;
3888 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3889 ex.flags = GT_USECRLF;
3890 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3891 ex.lpDefaultChar = NULL;
3892 ex.lpUsedDefChar = NULL;
3893 return ME_GetTextEx(editor, &ex, lParam);
3895 case EM_GETTEXTEX:
3896 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3897 case EM_GETSELTEXT:
3899 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3900 ME_Cursor *from = &editor->pCursors[nStartCur];
3901 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3902 nTo - nFrom, unicode);
3904 case EM_GETSCROLLPOS:
3906 POINT *point = (POINT *)lParam;
3907 point->x = editor->horz_si.nPos;
3908 point->y = editor->vert_si.nPos;
3909 /* 16-bit scaled value is returned as stored in scrollinfo */
3910 if (editor->horz_si.nMax > 0xffff)
3911 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3912 if (editor->vert_si.nMax > 0xffff)
3913 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3914 return 1;
3916 case EM_GETTEXTRANGE:
3918 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3919 ME_Cursor start;
3920 int nStart = rng->chrg.cpMin;
3921 int nEnd = rng->chrg.cpMax;
3922 int textlength = ME_GetTextLength(editor);
3924 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3925 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3926 if (nStart < 0) return 0;
3927 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3928 nEnd = textlength;
3929 if (nStart >= nEnd) return 0;
3931 ME_CursorFromCharOfs(editor, nStart, &start);
3932 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3934 case EM_GETLINE:
3936 ME_DisplayItem *run;
3937 const unsigned int nMaxChars = *(WORD *) lParam;
3938 unsigned int nCharsLeft = nMaxChars;
3939 char *dest = (char *) lParam;
3940 BOOL wroteNull = FALSE;
3942 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3943 unicode ? "Unicode" : "Ansi");
3945 run = ME_FindRowWithNumber(editor, wParam);
3946 if (run == NULL)
3947 return 0;
3949 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3950 && run->type == diRun)
3952 WCHAR *str = get_text( &run->member.run, 0 );
3953 unsigned int nCopy;
3955 nCopy = min(nCharsLeft, run->member.run.len);
3957 if (unicode)
3958 memcpy(dest, str, nCopy * sizeof(WCHAR));
3959 else
3960 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3961 nCharsLeft, NULL, NULL);
3962 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3963 nCharsLeft -= nCopy;
3966 /* append line termination, space allowing */
3967 if (nCharsLeft > 0)
3969 if (unicode)
3970 *((WCHAR *)dest) = '\0';
3971 else
3972 *dest = '\0';
3973 nCharsLeft--;
3974 wroteNull = TRUE;
3977 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3978 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3980 case EM_GETLINECOUNT:
3982 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3983 int nRows = 0;
3985 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3987 while (item != editor->pBuffer->pLast)
3989 assert(item->type == diParagraph);
3990 prev_para = ME_FindItemBack(item, diRun);
3991 if (prev_para) {
3992 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3994 nRows += item->member.para.nRows;
3995 item = item->member.para.next_para;
3997 last_para = ME_FindItemBack(item, diRun);
3998 assert(last_para);
3999 assert(last_para->member.run.nFlags & MERF_ENDPARA);
4000 if (editor->bEmulateVersion10 && prev_para &&
4001 last_para->member.run.nCharOfs == 0 &&
4002 prev_para->member.run.len == 1 &&
4003 *get_text( &prev_para->member.run, 0 ) == '\r')
4005 /* In 1.0 emulation, the last solitary \r at the very end of the text
4006 (if one exists) is NOT a line break.
4007 FIXME: this is an ugly hack. This should have a more regular model. */
4008 nRows--;
4011 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
4012 return max(1, nRows);
4014 case EM_LINEFROMCHAR:
4016 if (wParam == -1)
4017 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4018 else
4019 return ME_RowNumberFromCharOfs(editor, wParam);
4021 case EM_EXLINEFROMCHAR:
4023 if (lParam == -1)
4024 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
4025 else
4026 return ME_RowNumberFromCharOfs(editor, lParam);
4028 case EM_LINEINDEX:
4030 ME_DisplayItem *item, *para;
4031 int nCharOfs;
4033 if (wParam == -1)
4034 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
4035 else
4036 item = ME_FindRowWithNumber(editor, wParam);
4037 if (!item)
4038 return -1;
4039 para = ME_GetParagraph(item);
4040 item = ME_FindItemFwd(item, diRun);
4041 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
4042 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
4043 return nCharOfs;
4045 case EM_LINELENGTH:
4047 ME_DisplayItem *item, *item_end;
4048 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
4049 ME_DisplayItem *para, *run;
4051 if (wParam > ME_GetTextLength(editor))
4052 return 0;
4053 if (wParam == -1)
4055 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
4056 return 0;
4058 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
4059 item = ME_RowStart(run);
4060 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
4061 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
4062 if (item_end->type == diStartRow) {
4063 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
4064 } else {
4065 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
4066 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
4067 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
4069 nChars = nNextLineOfs - nThisLineOfs;
4070 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
4071 return nChars;
4073 case EM_EXLIMITTEXT:
4075 if ((int)lParam < 0)
4076 return 0;
4077 if (lParam == 0)
4078 editor->nTextLimit = 65536;
4079 else
4080 editor->nTextLimit = (int) lParam;
4081 return 0;
4083 case EM_LIMITTEXT:
4085 if (wParam == 0)
4086 editor->nTextLimit = 65536;
4087 else
4088 editor->nTextLimit = (int) wParam;
4089 return 0;
4091 case EM_GETLIMITTEXT:
4093 return editor->nTextLimit;
4095 case EM_FINDTEXT:
4097 LRESULT r;
4098 if(!unicode){
4099 FINDTEXTA *ft = (FINDTEXTA *)lParam;
4100 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
4101 WCHAR *tmp;
4103 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4104 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
4105 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
4106 FREE_OBJ( tmp );
4107 }else{
4108 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4109 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4111 return r;
4113 case EM_FINDTEXTEX:
4115 LRESULT r;
4116 if(!unicode){
4117 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
4118 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
4119 WCHAR *tmp;
4121 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4122 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
4123 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
4124 FREE_OBJ( tmp );
4125 }else{
4126 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4127 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4129 return r;
4131 case EM_FINDTEXTW:
4133 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4134 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4136 case EM_FINDTEXTEXW:
4138 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4139 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4141 case EM_GETZOOM:
4142 if (!wParam || !lParam)
4143 return FALSE;
4144 *(int *)wParam = editor->nZoomNumerator;
4145 *(int *)lParam = editor->nZoomDenominator;
4146 return TRUE;
4147 case EM_SETZOOM:
4148 return ME_SetZoom(editor, wParam, lParam);
4149 case EM_CHARFROMPOS:
4151 ME_Cursor cursor;
4152 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4153 &cursor, NULL))
4154 return ME_GetCursorOfs(&cursor);
4155 else
4156 return -1;
4158 case EM_POSFROMCHAR:
4160 ME_DisplayItem *pPara, *pRun;
4161 int nCharOfs, nOffset, nLength;
4162 POINTL pt = {0,0};
4164 nCharOfs = wParam;
4165 /* detect which API version we're dealing with */
4166 if (wParam >= 0x40000)
4167 nCharOfs = lParam;
4168 nLength = ME_GetTextLength(editor);
4169 nCharOfs = min(nCharOfs, nLength);
4170 nCharOfs = max(nCharOfs, 0);
4172 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4173 assert(pRun->type == diRun);
4174 pt.y = pRun->member.run.pt.y;
4175 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4176 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4177 pt.x += editor->rcFormat.left;
4179 pt.x -= editor->horz_si.nPos;
4180 pt.y -= editor->vert_si.nPos;
4182 if (wParam >= 0x40000) {
4183 *(POINTL *)wParam = pt;
4185 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4187 case WM_CREATE:
4188 return ME_WmCreate(editor, lParam, unicode);
4189 case WM_DESTROY:
4190 ME_DestroyEditor(editor);
4191 return 0;
4192 case WM_SETCURSOR:
4194 POINT cursor_pos;
4195 if (wParam == (WPARAM)editor->hWnd && GetCursorPos(&cursor_pos) &&
4196 ScreenToClient(editor->hWnd, &cursor_pos))
4197 ME_LinkNotify(editor, msg, 0, MAKELPARAM(cursor_pos.x, cursor_pos.y));
4198 return ME_SetCursor(editor);
4200 case WM_LBUTTONDBLCLK:
4201 case WM_LBUTTONDOWN:
4203 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4204 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4205 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4206 return 0;
4207 ITextHost_TxSetFocus(editor->texthost);
4208 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4209 ME_CalculateClickCount(editor, msg, wParam, lParam));
4210 ITextHost_TxSetCapture(editor->texthost, TRUE);
4211 editor->bMouseCaptured = TRUE;
4212 ME_LinkNotify(editor, msg, wParam, lParam);
4213 if (!ME_SetCursor(editor)) goto do_default;
4214 break;
4216 case WM_MOUSEMOVE:
4217 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4218 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4219 return 0;
4220 if (editor->bMouseCaptured)
4221 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4222 else
4223 ME_LinkNotify(editor, msg, wParam, lParam);
4224 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4225 if (editor->bMouseCaptured)
4226 ME_SetCursor(editor);
4227 break;
4228 case WM_LBUTTONUP:
4229 if (editor->bMouseCaptured) {
4230 ITextHost_TxSetCapture(editor->texthost, FALSE);
4231 editor->bMouseCaptured = FALSE;
4233 if (editor->nSelectionType == stDocument)
4234 editor->nSelectionType = stPosition;
4235 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4236 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4237 return 0;
4238 else
4240 ME_SetCursor(editor);
4241 ME_LinkNotify(editor, msg, wParam, lParam);
4243 break;
4244 case WM_RBUTTONUP:
4245 case WM_RBUTTONDOWN:
4246 case WM_RBUTTONDBLCLK:
4247 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4248 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4249 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4250 return 0;
4251 ME_LinkNotify(editor, msg, wParam, lParam);
4252 goto do_default;
4253 case WM_CONTEXTMENU:
4254 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4255 goto do_default;
4256 break;
4257 case WM_SETFOCUS:
4258 editor->bHaveFocus = TRUE;
4259 ME_ShowCaret(editor);
4260 ME_SendOldNotify(editor, EN_SETFOCUS);
4261 if (!editor->bHideSelection && !(editor->styleFlags & ES_NOHIDESEL))
4262 ME_InvalidateSelection( editor );
4263 return 0;
4264 case WM_KILLFOCUS:
4265 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4266 editor->bHaveFocus = FALSE;
4267 editor->wheel_remain = 0;
4268 ME_HideCaret(editor);
4269 ME_SendOldNotify(editor, EN_KILLFOCUS);
4270 if (!editor->bHideSelection && !(editor->styleFlags & ES_NOHIDESEL))
4271 ME_InvalidateSelection( editor );
4272 return 0;
4273 case WM_COMMAND:
4274 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4275 return 0;
4276 case WM_KEYUP:
4277 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4278 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4279 return 0;
4280 goto do_default;
4281 case WM_KEYDOWN:
4282 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4283 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4284 return 0;
4285 if (ME_KeyDown(editor, LOWORD(wParam)))
4286 return 0;
4287 goto do_default;
4288 case WM_CHAR:
4289 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4290 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4291 return 0;
4292 return ME_Char(editor, wParam, lParam, unicode);
4293 case WM_UNICHAR:
4294 if (unicode)
4296 if(wParam == UNICODE_NOCHAR) return TRUE;
4297 if(wParam <= 0x000fffff)
4299 if(wParam > 0xffff) /* convert to surrogates */
4301 wParam -= 0x10000;
4302 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4303 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4304 } else {
4305 ME_Char(editor, wParam, 0, TRUE);
4308 return 0;
4310 break;
4311 case EM_STOPGROUPTYPING:
4312 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4313 return 0;
4314 case WM_HSCROLL:
4316 const int scrollUnit = 7;
4318 switch(LOWORD(wParam))
4320 case SB_LEFT:
4321 ME_ScrollAbs(editor, 0, 0);
4322 break;
4323 case SB_RIGHT:
4324 ME_ScrollAbs(editor,
4325 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4326 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4327 break;
4328 case SB_LINELEFT:
4329 ME_ScrollLeft(editor, scrollUnit);
4330 break;
4331 case SB_LINERIGHT:
4332 ME_ScrollRight(editor, scrollUnit);
4333 break;
4334 case SB_PAGELEFT:
4335 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4336 break;
4337 case SB_PAGERIGHT:
4338 ME_ScrollRight(editor, editor->sizeWindow.cx);
4339 break;
4340 case SB_THUMBTRACK:
4341 case SB_THUMBPOSITION:
4343 int pos = HIWORD(wParam);
4344 if (editor->horz_si.nMax > 0xffff)
4345 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4346 ME_HScrollAbs(editor, pos);
4347 break;
4350 break;
4352 case EM_SCROLL: /* fall through */
4353 case WM_VSCROLL:
4355 int origNPos;
4356 int lineHeight = get_default_line_height( editor );
4358 origNPos = editor->vert_si.nPos;
4360 switch(LOWORD(wParam))
4362 case SB_TOP:
4363 ME_ScrollAbs(editor, 0, 0);
4364 break;
4365 case SB_BOTTOM:
4366 ME_ScrollAbs(editor,
4367 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4368 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4369 break;
4370 case SB_LINEUP:
4371 ME_ScrollUp(editor,lineHeight);
4372 break;
4373 case SB_LINEDOWN:
4374 ME_ScrollDown(editor,lineHeight);
4375 break;
4376 case SB_PAGEUP:
4377 ME_ScrollUp(editor,editor->sizeWindow.cy);
4378 break;
4379 case SB_PAGEDOWN:
4380 ME_ScrollDown(editor,editor->sizeWindow.cy);
4381 break;
4382 case SB_THUMBTRACK:
4383 case SB_THUMBPOSITION:
4385 int pos = HIWORD(wParam);
4386 if (editor->vert_si.nMax > 0xffff)
4387 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4388 ME_VScrollAbs(editor, pos);
4389 break;
4392 if (msg == EM_SCROLL)
4393 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4394 break;
4396 case WM_MOUSEWHEEL:
4398 int delta;
4399 BOOL ctrl_is_down;
4401 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4402 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4403 return 0;
4405 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4407 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4409 /* if scrolling changes direction, ignore left overs */
4410 if ((delta < 0 && editor->wheel_remain < 0) ||
4411 (delta > 0 && editor->wheel_remain > 0))
4412 editor->wheel_remain += delta;
4413 else
4414 editor->wheel_remain = delta;
4416 if (editor->wheel_remain)
4418 if (ctrl_is_down) {
4419 int numerator;
4420 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4422 numerator = 100;
4423 } else {
4424 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4426 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4427 if (numerator >= 10 && numerator <= 500)
4428 ME_SetZoom(editor, numerator, 100);
4429 } else {
4430 UINT max_lines = 3;
4431 int lines = 0;
4433 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4434 if (max_lines)
4435 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4436 if (lines)
4437 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4440 break;
4442 case EM_GETRECT:
4444 *((RECT *)lParam) = editor->rcFormat;
4445 if (editor->bDefaultFormatRect)
4446 ((RECT *)lParam)->left -= editor->selofs;
4447 return 0;
4449 case EM_SETRECT:
4450 case EM_SETRECTNP:
4452 if (lParam)
4454 int border = 0;
4455 RECT clientRect;
4456 RECT *rc = (RECT *)lParam;
4458 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4459 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4460 if (wParam == 0)
4462 editor->rcFormat.top = max(0, rc->top - border);
4463 editor->rcFormat.left = max(0, rc->left - border);
4464 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4465 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4466 } else if (wParam == 1) {
4467 /* MSDN incorrectly says a wParam value of 1 causes the
4468 * lParam rect to be used as a relative offset,
4469 * however, the tests show it just prevents min/max bound
4470 * checking. */
4471 editor->rcFormat.top = rc->top - border;
4472 editor->rcFormat.left = rc->left - border;
4473 editor->rcFormat.bottom = rc->bottom;
4474 editor->rcFormat.right = rc->right + border;
4475 } else {
4476 return 0;
4478 editor->bDefaultFormatRect = FALSE;
4480 else
4482 ME_SetDefaultFormatRect(editor);
4483 editor->bDefaultFormatRect = TRUE;
4485 ME_MarkAllForWrapping(editor);
4486 ME_WrapMarkedParagraphs(editor);
4487 ME_UpdateScrollBar(editor);
4488 if (msg != EM_SETRECTNP)
4489 ME_Repaint(editor);
4490 return 0;
4492 case EM_REQUESTRESIZE:
4493 ME_SendRequestResize(editor, TRUE);
4494 return 0;
4495 case WM_SETREDRAW:
4496 goto do_default;
4497 case WM_WINDOWPOSCHANGED:
4499 RECT clientRect;
4500 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4502 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4503 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4504 if (editor->bDefaultFormatRect) {
4505 ME_SetDefaultFormatRect(editor);
4506 } else {
4507 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4508 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4510 editor->prevClientRect = clientRect;
4511 ME_RewrapRepaint(editor);
4512 goto do_default;
4514 /* IME messages to make richedit controls IME aware */
4515 case WM_IME_SETCONTEXT:
4516 case WM_IME_CONTROL:
4517 case WM_IME_SELECT:
4518 case WM_IME_COMPOSITIONFULL:
4519 return 0;
4520 case WM_IME_STARTCOMPOSITION:
4522 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4523 ME_DeleteSelection(editor);
4524 ME_CommitUndo(editor);
4525 ME_UpdateRepaint(editor, FALSE);
4526 return 0;
4528 case WM_IME_COMPOSITION:
4530 HIMC hIMC;
4532 ME_Style *style = ME_GetInsertStyle(editor, 0);
4533 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4534 ME_DeleteSelection(editor);
4535 ME_SaveTempStyle(editor);
4536 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4538 LPWSTR lpCompStr = NULL;
4539 DWORD dwBufLen;
4540 DWORD dwIndex = lParam & GCS_RESULTSTR;
4541 if (!dwIndex)
4542 dwIndex = GCS_COMPSTR;
4544 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4545 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4546 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4547 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4548 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4549 HeapFree(GetProcessHeap(), 0, lpCompStr);
4551 if (dwIndex == GCS_COMPSTR)
4552 ME_SetSelection(editor,editor->imeStartIndex,
4553 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4555 ME_ReleaseStyle(style);
4556 ME_CommitUndo(editor);
4557 ME_UpdateRepaint(editor, FALSE);
4558 return 0;
4560 case WM_IME_ENDCOMPOSITION:
4562 ME_DeleteSelection(editor);
4563 editor->imeStartIndex=-1;
4564 return 0;
4566 case EM_GETOLEINTERFACE:
4568 if (!editor->reOle)
4569 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4570 return 0;
4571 *(LPVOID *)lParam = editor->reOle;
4572 IRichEditOle_AddRef(editor->reOle);
4573 return 1;
4575 case EM_GETPASSWORDCHAR:
4577 return editor->cPasswordMask;
4579 case EM_SETOLECALLBACK:
4580 if(editor->lpOleCallback)
4581 IRichEditOleCallback_Release(editor->lpOleCallback);
4582 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4583 if(editor->lpOleCallback)
4584 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4585 return TRUE;
4586 case EM_GETWORDBREAKPROC:
4587 return (LRESULT)editor->pfnWordBreak;
4588 case EM_SETWORDBREAKPROC:
4590 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4592 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4593 return (LRESULT)pfnOld;
4595 case EM_GETTEXTMODE:
4596 return editor->mode;
4597 case EM_SETTEXTMODE:
4599 int mask = 0;
4600 int changes = 0;
4602 if (ME_GetTextLength(editor) ||
4603 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4604 return E_UNEXPECTED;
4606 /* Check for mutually exclusive flags in adjacent bits of wParam */
4607 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4608 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4609 return E_INVALIDARG;
4611 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4613 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4614 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4615 if (wParam & TM_PLAINTEXT) {
4616 /* Clear selection since it should be possible to select the
4617 * end of text run for rich text */
4618 ME_InvalidateSelection(editor);
4619 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4620 editor->pCursors[1] = editor->pCursors[0];
4621 /* plain text can only have the default style. */
4622 ME_ClearTempStyle(editor);
4623 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4624 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4625 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4628 /* FIXME: Currently no support for undo level and code page options */
4629 editor->mode = (editor->mode & ~mask) | changes;
4630 return 0;
4632 case EM_SETPASSWORDCHAR:
4634 editor->cPasswordMask = wParam;
4635 ME_RewrapRepaint(editor);
4636 return 0;
4638 case EM_SETTARGETDEVICE:
4639 if (wParam == 0)
4641 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4642 if (editor->nAvailWidth || editor->bWordWrap != new)
4644 editor->bWordWrap = new;
4645 editor->nAvailWidth = 0; /* wrap to client area */
4646 ME_RewrapRepaint(editor);
4648 } else {
4649 int width = max(0, lParam);
4650 if ((editor->styleFlags & ES_MULTILINE) &&
4651 (!editor->bWordWrap || editor->nAvailWidth != width))
4653 editor->nAvailWidth = width;
4654 editor->bWordWrap = TRUE;
4655 ME_RewrapRepaint(editor);
4657 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4659 return TRUE;
4660 default:
4661 do_default:
4662 *phresult = S_FALSE;
4663 break;
4665 return 0L;
4668 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4669 LPARAM lParam, BOOL unicode)
4671 ME_TextEditor *editor;
4672 HRESULT hresult;
4673 LRESULT lresult = 0;
4675 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4676 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4678 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4679 if (!editor)
4681 if (msg == WM_NCCREATE)
4683 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4684 ITextHost *texthost;
4686 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4687 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4688 return texthost != NULL;
4690 else
4692 return DefWindowProcW(hWnd, msg, wParam, lParam);
4696 switch (msg)
4698 case WM_PAINT:
4700 HDC hDC;
4701 RECT rc;
4702 PAINTSTRUCT ps;
4704 hDC = BeginPaint(editor->hWnd, &ps);
4705 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4706 ME_SendOldNotify(editor, EN_UPDATE);
4707 /* Erase area outside of the formatting rectangle */
4708 if (ps.rcPaint.top < editor->rcFormat.top)
4710 rc = ps.rcPaint;
4711 rc.bottom = editor->rcFormat.top;
4712 FillRect(hDC, &rc, editor->hbrBackground);
4713 ps.rcPaint.top = editor->rcFormat.top;
4715 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4716 rc = ps.rcPaint;
4717 rc.top = editor->rcFormat.bottom;
4718 FillRect(hDC, &rc, editor->hbrBackground);
4719 ps.rcPaint.bottom = editor->rcFormat.bottom;
4721 if (ps.rcPaint.left < editor->rcFormat.left) {
4722 rc = ps.rcPaint;
4723 rc.right = editor->rcFormat.left;
4724 FillRect(hDC, &rc, editor->hbrBackground);
4725 ps.rcPaint.left = editor->rcFormat.left;
4727 if (ps.rcPaint.right > editor->rcFormat.right) {
4728 rc = ps.rcPaint;
4729 rc.left = editor->rcFormat.right;
4730 FillRect(hDC, &rc, editor->hbrBackground);
4731 ps.rcPaint.right = editor->rcFormat.right;
4734 ME_PaintContent(editor, hDC, &ps.rcPaint);
4735 EndPaint(editor->hWnd, &ps);
4736 return 0;
4738 case WM_ERASEBKGND:
4740 HDC hDC = (HDC)wParam;
4741 RECT rc;
4743 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4744 FillRect(hDC, &rc, editor->hbrBackground);
4745 return 1;
4747 case EM_SETOPTIONS:
4749 DWORD dwStyle;
4750 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4751 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4752 ECO_SELECTIONBAR;
4753 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4754 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4755 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4756 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4757 return lresult;
4759 case EM_SETREADONLY:
4761 DWORD dwStyle;
4762 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4763 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4764 dwStyle &= ~ES_READONLY;
4765 if (wParam)
4766 dwStyle |= ES_READONLY;
4767 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4768 return lresult;
4770 default:
4771 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4774 if (hresult == S_FALSE)
4775 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4777 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4778 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4780 return lresult;
4783 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4785 BOOL unicode = TRUE;
4787 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4788 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4789 unicode = FALSE;
4791 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4794 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4796 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4799 /******************************************************************
4800 * RichEditANSIWndProc (RICHED20.10)
4802 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4804 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4807 /******************************************************************
4808 * RichEdit10ANSIWndProc (RICHED20.9)
4810 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4812 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4814 ITextHost *texthost;
4815 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4817 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4818 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4819 return texthost != NULL;
4821 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4824 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4826 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4829 /* Fill buffer with srcChars unicode characters from the start cursor.
4831 * buffer: destination buffer
4832 * buflen: length of buffer in characters excluding the NULL terminator.
4833 * start: start of editor text to copy into buffer.
4834 * srcChars: Number of characters to use from the editor text.
4835 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4837 * returns the number of characters written excluding the NULL terminator.
4839 * The written text is always NULL terminated.
4841 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4842 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4843 BOOL bEOP)
4845 ME_DisplayItem *pRun, *pNextRun;
4846 const WCHAR *pStart = buffer;
4847 const WCHAR cr_lf[] = {'\r', '\n', 0};
4848 const WCHAR *str;
4849 int nLen;
4851 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4852 if (editor->bEmulateVersion10) bCRLF = FALSE;
4854 pRun = start->pRun;
4855 assert(pRun);
4856 pNextRun = ME_FindItemFwd(pRun, diRun);
4858 nLen = pRun->member.run.len - start->nOffset;
4859 str = get_text( &pRun->member.run, start->nOffset );
4861 while (srcChars && buflen && pNextRun)
4863 int nFlags = pRun->member.run.nFlags;
4865 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4867 if (buflen == 1) break;
4868 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4869 * EM_GETTEXTEX, however, this is done for copying text which
4870 * also uses this function. */
4871 srcChars -= min(nLen, srcChars);
4872 nLen = 2;
4873 str = cr_lf;
4874 } else {
4875 nLen = min(nLen, srcChars);
4876 srcChars -= nLen;
4879 nLen = min(nLen, buflen);
4880 buflen -= nLen;
4882 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4884 buffer += nLen;
4886 pRun = pNextRun;
4887 pNextRun = ME_FindItemFwd(pRun, diRun);
4889 nLen = pRun->member.run.len;
4890 str = get_text( &pRun->member.run, 0 );
4892 /* append '\r' to the last paragraph. */
4893 if (pRun->next->type == diTextEnd && bEOP)
4895 *buffer = '\r';
4896 buffer ++;
4898 *buffer = 0;
4899 return buffer - pStart;
4902 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4904 WNDCLASSW wcW;
4905 WNDCLASSA wcA;
4907 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4908 wcW.lpfnWndProc = RichEditWndProcW;
4909 wcW.cbClsExtra = 0;
4910 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4911 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4912 wcW.hIcon = NULL;
4913 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4914 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4915 wcW.lpszMenuName = NULL;
4917 if (is_version_nt())
4919 wcW.lpszClassName = RICHEDIT_CLASS20W;
4920 if (!RegisterClassW(&wcW)) return FALSE;
4921 wcW.lpszClassName = MSFTEDIT_CLASS;
4922 if (!RegisterClassW(&wcW)) return FALSE;
4924 else
4926 /* WNDCLASSA/W have the same layout */
4927 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4928 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4929 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4930 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4933 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4934 wcA.lpfnWndProc = RichEditWndProcA;
4935 wcA.cbClsExtra = 0;
4936 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4937 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4938 wcA.hIcon = NULL;
4939 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4940 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4941 wcA.lpszMenuName = NULL;
4942 wcA.lpszClassName = RICHEDIT_CLASS20A;
4943 if (!RegisterClassA(&wcA)) return FALSE;
4944 wcA.lpszClassName = "RichEdit50A";
4945 if (!RegisterClassA(&wcA)) return FALSE;
4947 return TRUE;
4950 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4951 /* FIXME: Not implemented */
4952 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4953 hWnd, msg, get_msg_name(msg), wParam, lParam);
4954 return DefWindowProcW(hWnd, msg, wParam, lParam);
4957 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4958 /* FIXME: Not implemented */
4959 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4960 hWnd, msg, get_msg_name(msg), wParam, lParam);
4961 return DefWindowProcW(hWnd, msg, wParam, lParam);
4964 /******************************************************************
4965 * REExtendedRegisterClass (RICHED20.8)
4967 * FIXME undocumented
4968 * Need to check for errors and implement controls and callbacks
4970 LRESULT WINAPI REExtendedRegisterClass(void)
4972 WNDCLASSW wcW;
4973 UINT result;
4975 FIXME("semi stub\n");
4977 wcW.cbClsExtra = 0;
4978 wcW.cbWndExtra = 4;
4979 wcW.hInstance = NULL;
4980 wcW.hIcon = NULL;
4981 wcW.hCursor = NULL;
4982 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4983 wcW.lpszMenuName = NULL;
4985 if (!ME_ListBoxRegistered)
4987 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4988 wcW.lpfnWndProc = REListWndProc;
4989 wcW.lpszClassName = REListBox20W;
4990 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4993 if (!ME_ComboBoxRegistered)
4995 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4996 wcW.lpfnWndProc = REComboWndProc;
4997 wcW.lpszClassName = REComboBox20W;
4998 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
5001 result = 0;
5002 if (ME_ListBoxRegistered)
5003 result += 1;
5004 if (ME_ComboBoxRegistered)
5005 result += 2;
5007 return result;
5010 static int wchar_comp( const void *key, const void *elem )
5012 return *(const WCHAR *)key - *(const WCHAR *)elem;
5015 /* neutral characters end the url if the next non-neutral character is a space character,
5016 otherwise they are included in the url. */
5017 static BOOL isurlneutral( WCHAR c )
5019 /* NB this list is sorted */
5020 static const WCHAR neutral_chars[] = {'!','\"','\'','(',')',',','-','.',':',';','<','>','?','[',']','{','}'};
5022 /* Some shortcuts */
5023 if (isalnum( c )) return FALSE;
5024 if (c > neutral_chars[sizeof(neutral_chars) / sizeof(neutral_chars[0]) - 1]) return FALSE;
5026 return !!bsearch( &c, neutral_chars, sizeof(neutral_chars) / sizeof(neutral_chars[0]),
5027 sizeof(c), wchar_comp );
5031 * This proc takes a selection, and scans it forward in order to select the span
5032 * of a possible URL candidate. A possible URL candidate must start with isalnum
5033 * or one of the following special characters: *|/\+%#@ and must consist entirely
5034 * of the characters allowed to start the URL, plus : (colon) which may occur
5035 * at most once, and not at either end.
5037 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
5038 const ME_Cursor *start,
5039 int nChars,
5040 ME_Cursor *candidate_min,
5041 ME_Cursor *candidate_max)
5043 ME_Cursor cursor = *start, neutral_end, space_end;
5044 BOOL candidateStarted = FALSE, quoted = FALSE;
5045 WCHAR c;
5047 while (nChars > 0)
5049 WCHAR *str = get_text( &cursor.pRun->member.run, 0 );
5050 int run_len = cursor.pRun->member.run.len;
5052 nChars -= run_len - cursor.nOffset;
5054 /* Find start of candidate */
5055 if (!candidateStarted)
5057 while (cursor.nOffset < run_len)
5059 c = str[cursor.nOffset];
5060 if (!isspaceW( c ) && !isurlneutral( c ))
5062 *candidate_min = cursor;
5063 candidateStarted = TRUE;
5064 neutral_end.pPara = NULL;
5065 space_end.pPara = NULL;
5066 cursor.nOffset++;
5067 break;
5069 quoted = (c == '<');
5070 cursor.nOffset++;
5074 /* Find end of candidate */
5075 if (candidateStarted)
5077 while (cursor.nOffset < run_len)
5079 c = str[cursor.nOffset];
5080 if (isspaceW( c ))
5082 if (quoted && c != '\r')
5084 if (!space_end.pPara)
5086 if (neutral_end.pPara)
5087 space_end = neutral_end;
5088 else
5089 space_end = cursor;
5092 else
5093 goto done;
5095 else if (isurlneutral( c ))
5097 if (quoted && c == '>')
5099 neutral_end.pPara = NULL;
5100 space_end.pPara = NULL;
5101 goto done;
5103 if (!neutral_end.pPara)
5104 neutral_end = cursor;
5106 else
5107 neutral_end.pPara = NULL;
5109 cursor.nOffset++;
5113 cursor.nOffset = 0;
5114 if (!ME_NextRun(&cursor.pPara, &cursor.pRun, TRUE))
5115 goto done;
5118 done:
5119 if (candidateStarted)
5121 if (space_end.pPara)
5122 *candidate_max = space_end;
5123 else if (neutral_end.pPara)
5124 *candidate_max = neutral_end;
5125 else
5126 *candidate_max = cursor;
5127 return TRUE;
5129 *candidate_max = *candidate_min = cursor;
5130 return FALSE;
5134 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5136 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5138 #define MAX_PREFIX_LEN 9
5139 struct prefix_s {
5140 const WCHAR text[MAX_PREFIX_LEN];
5141 int length;
5142 }prefixes[] = {
5143 {{'p','r','o','s','p','e','r','o',':'}, 9},
5144 {{'t','e','l','n','e','t',':'}, 7},
5145 {{'g','o','p','h','e','r',':'}, 7},
5146 {{'m','a','i','l','t','o',':'}, 7},
5147 {{'h','t','t','p','s',':'}, 6},
5148 {{'f','i','l','e',':'}, 5},
5149 {{'n','e','w','s',':'}, 5},
5150 {{'w','a','i','s',':'}, 5},
5151 {{'n','n','t','p',':'}, 5},
5152 {{'h','t','t','p',':'}, 5},
5153 {{'w','w','w','.'}, 4},
5154 {{'f','t','p',':'}, 4},
5156 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5157 unsigned int i;
5159 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5160 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5162 if (nChars < prefixes[i].length) continue;
5163 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5164 return TRUE;
5166 return FALSE;
5167 #undef MAX_PREFIX_LEN
5171 * This proc walks through the indicated selection and evaluates whether each
5172 * section identified by ME_FindNextURLCandidate and in-between sections have
5173 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5174 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5176 * Since this function can cause runs to be split, do not depend on the value
5177 * of the start cursor at the end of the function.
5179 * nChars may be set to INT_MAX to update to the end of the text.
5181 * Returns TRUE if at least one section was modified.
5183 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5185 BOOL modified = FALSE;
5186 ME_Cursor startCur = *start;
5188 if (!editor->AutoURLDetect_bEnable) return FALSE;
5192 CHARFORMAT2W link;
5193 ME_Cursor candidateStart, candidateEnd;
5195 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5196 &candidateStart, &candidateEnd))
5198 /* Section before candidate is not an URL */
5199 int cMin = ME_GetCursorOfs(&candidateStart);
5200 int cMax = ME_GetCursorOfs(&candidateEnd);
5202 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5203 candidateStart = candidateEnd;
5204 nChars -= cMax - ME_GetCursorOfs(&startCur);
5206 else
5208 /* No more candidates until end of selection */
5209 nChars = 0;
5212 if (startCur.pRun != candidateStart.pRun ||
5213 startCur.nOffset != candidateStart.nOffset)
5215 /* CFE_LINK effect should be consistently unset */
5216 link.cbSize = sizeof(link);
5217 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5218 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5220 /* CFE_LINK must be unset from this range */
5221 memset(&link, 0, sizeof(CHARFORMAT2W));
5222 link.cbSize = sizeof(link);
5223 link.dwMask = CFM_LINK;
5224 link.dwEffects = 0;
5225 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5226 /* Update candidateEnd since setting character formats may split
5227 * runs, which can cause a cursor to be at an invalid offset within
5228 * a split run. */
5229 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5231 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5232 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5234 modified = TRUE;
5237 if (candidateStart.pRun != candidateEnd.pRun ||
5238 candidateStart.nOffset != candidateEnd.nOffset)
5240 /* CFE_LINK effect should be consistently set */
5241 link.cbSize = sizeof(link);
5242 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5243 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5245 /* CFE_LINK must be set on this range */
5246 memset(&link, 0, sizeof(CHARFORMAT2W));
5247 link.cbSize = sizeof(link);
5248 link.dwMask = CFM_LINK;
5249 link.dwEffects = CFE_LINK;
5250 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5251 modified = TRUE;
5254 startCur = candidateEnd;
5255 } while (nChars > 0);
5256 return modified;