winex11: Send XEMBED_REQUEST_FOCUS request for embedded windows.
[wine/wine-gecko.git] / dlls / riched20 / editor.c
blobe70bbbe6c52cc1120bbe1f1f424fdffafe525968
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 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
236 #define STACK_SIZE_DEFAULT 100
237 #define STACK_SIZE_MAX 1000
239 #define TEXT_LIMIT_DEFAULT 32767
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
250 int me_debug = 0;
251 HANDLE me_heap = NULL;
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
256 static inline BOOL is_version_nt(void)
258 return !(GetVersion() & 0x80000000);
261 static ME_TextBuffer *ME_MakeText(void) {
263 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
265 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
268 p1->prev = NULL;
269 p1->next = p2;
270 p2->prev = p1;
271 p2->next = NULL;
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
276 buf->pFirst = p1;
277 buf->pLast = p2;
278 buf->pCharStyle = NULL;
280 return buf;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR *pText;
287 LRESULT total_bytes_read = 0;
288 BOOL is_read = FALSE;
289 DWORD cp = CP_ACP, copy = 0;
290 char conv_buf[4 + STREAMIN_BUFFER_SIZE]; /* up to 4 additional UTF-8 bytes */
292 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
294 TRACE("%08x %p\n", dwFormat, stream);
296 do {
297 LONG nWideChars = 0;
298 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
300 if (!stream->dwSize)
302 ME_StreamInFill(stream);
303 if (stream->editstream->dwError)
304 break;
305 if (!stream->dwSize)
306 break;
307 total_bytes_read += stream->dwSize;
310 if (!(dwFormat & SF_UNICODE))
312 char * buf = stream->buffer;
313 DWORD size = stream->dwSize, end;
315 if (!is_read)
317 is_read = TRUE;
318 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
320 cp = CP_UTF8;
321 buf += 3;
322 size -= 3;
326 if (cp == CP_UTF8)
328 if (copy)
330 memcpy(conv_buf + copy, buf, size);
331 buf = conv_buf;
332 size += copy;
334 end = size;
335 while ((buf[end-1] & 0xC0) == 0x80)
337 --end;
338 --total_bytes_read; /* strange, but seems to match windows */
340 if (buf[end-1] & 0x80)
342 DWORD need = 0;
343 if ((buf[end-1] & 0xE0) == 0xC0)
344 need = 1;
345 if ((buf[end-1] & 0xF0) == 0xE0)
346 need = 2;
347 if ((buf[end-1] & 0xF8) == 0xF0)
348 need = 3;
350 if (size - end >= need)
352 /* we have enough bytes for this sequence */
353 end = size;
355 else
357 /* need more bytes, so don't transcode this sequence */
358 --end;
362 else
363 end = size;
365 nWideChars = MultiByteToWideChar(cp, 0, buf, end, wszText, STREAMIN_BUFFER_SIZE);
366 pText = wszText;
368 if (cp == CP_UTF8)
370 if (end != size)
372 memcpy(conv_buf, buf + end, size - end);
373 copy = size - end;
377 else
379 nWideChars = stream->dwSize >> 1;
380 pText = (WCHAR *)stream->buffer;
383 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
384 if (stream->dwSize == 0)
385 break;
386 stream->dwSize = 0;
387 } while(1);
388 return total_bytes_read;
391 static void ME_ApplyBorderProperties(RTF_Info *info,
392 ME_BorderRect *borderRect,
393 RTFBorder *borderDef)
395 int i, colorNum;
396 ME_Border *pBorders[] = {&borderRect->top,
397 &borderRect->left,
398 &borderRect->bottom,
399 &borderRect->right};
400 for (i = 0; i < 4; i++)
402 RTFColor *colorDef = info->colorList;
403 pBorders[i]->width = borderDef[i].width;
404 colorNum = borderDef[i].color;
405 while (colorDef && colorDef->rtfCNum != colorNum)
406 colorDef = colorDef->rtfNextColor;
407 if (colorDef)
408 pBorders[i]->colorRef = RGB(
409 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
410 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
411 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
412 else
413 pBorders[i]->colorRef = RGB(0, 0, 0);
417 void ME_RTFCharAttrHook(RTF_Info *info)
419 CHARFORMAT2W fmt;
420 fmt.cbSize = sizeof(fmt);
421 fmt.dwMask = 0;
422 fmt.dwEffects = 0;
424 switch(info->rtfMinor)
426 case rtfPlain:
427 /* FIXME add more flags once they're implemented */
428 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
429 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
430 fmt.yHeight = 12*20; /* 12pt */
431 fmt.wWeight = FW_NORMAL;
432 fmt.bUnderlineType = CFU_UNDERLINENONE;
433 break;
434 case rtfBold:
435 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
436 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
437 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
438 break;
439 case rtfItalic:
440 fmt.dwMask = CFM_ITALIC;
441 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
442 break;
443 case rtfUnderline:
444 fmt.dwMask = CFM_UNDERLINETYPE;
445 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
446 break;
447 case rtfDotUnderline:
448 fmt.dwMask = CFM_UNDERLINETYPE;
449 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
450 break;
451 case rtfDbUnderline:
452 fmt.dwMask = CFM_UNDERLINETYPE;
453 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
454 break;
455 case rtfWordUnderline:
456 fmt.dwMask = CFM_UNDERLINETYPE;
457 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
458 break;
459 case rtfNoUnderline:
460 fmt.dwMask = CFM_UNDERLINETYPE;
461 fmt.bUnderlineType = CFU_UNDERLINENONE;
462 break;
463 case rtfStrikeThru:
464 fmt.dwMask = CFM_STRIKEOUT;
465 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
466 break;
467 case rtfSubScript:
468 case rtfSuperScript:
469 case rtfSubScrShrink:
470 case rtfSuperScrShrink:
471 case rtfNoSuperSub:
472 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
473 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
474 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
475 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
476 break;
477 case rtfInvisible:
478 fmt.dwMask = CFM_HIDDEN;
479 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
480 break;
481 case rtfBackColor:
482 fmt.dwMask = CFM_BACKCOLOR;
483 fmt.dwEffects = 0;
484 if (info->rtfParam == 0)
485 fmt.dwEffects = CFE_AUTOBACKCOLOR;
486 else if (info->rtfParam != rtfNoParam)
488 RTFColor *c = RTFGetColor(info, info->rtfParam);
489 if (c && c->rtfCBlue >= 0)
490 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
491 else
492 fmt.dwEffects = CFE_AUTOBACKCOLOR;
494 break;
495 case rtfForeColor:
496 fmt.dwMask = CFM_COLOR;
497 fmt.dwEffects = 0;
498 if (info->rtfParam == 0)
499 fmt.dwEffects = CFE_AUTOCOLOR;
500 else if (info->rtfParam != rtfNoParam)
502 RTFColor *c = RTFGetColor(info, info->rtfParam);
503 if (c && c->rtfCBlue >= 0)
504 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
505 else {
506 fmt.dwEffects = CFE_AUTOCOLOR;
509 break;
510 case rtfFontNum:
511 if (info->rtfParam != rtfNoParam)
513 RTFFont *f = RTFGetFont(info, info->rtfParam);
514 if (f)
516 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
517 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
518 fmt.bCharSet = f->rtfFCharSet;
519 fmt.dwMask = CFM_FACE | CFM_CHARSET;
520 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
523 break;
524 case rtfFontSize:
525 fmt.dwMask = CFM_SIZE;
526 if (info->rtfParam != rtfNoParam)
527 fmt.yHeight = info->rtfParam*10;
528 break;
530 if (fmt.dwMask) {
531 ME_Style *style2;
532 RTFFlushOutputBuffer(info);
533 /* FIXME too slow ? how come ? */
534 style2 = ME_ApplyStyle(info->style, &fmt);
535 ME_ReleaseStyle(info->style);
536 info->style = style2;
537 info->styleChanged = TRUE;
541 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
542 the same tags mean different things in different contexts */
543 void ME_RTFParAttrHook(RTF_Info *info)
545 PARAFORMAT2 fmt;
546 fmt.cbSize = sizeof(fmt);
547 fmt.dwMask = 0;
549 switch(info->rtfMinor)
551 case rtfParDef: /* restores default paragraph attributes */
552 if (!info->editor->bEmulateVersion10) /* v4.1 */
553 info->borderType = RTFBorderParaLeft;
554 else /* v1.0 - 3.0 */
555 info->borderType = RTFBorderParaTop;
556 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
557 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
558 PFM_STARTINDENT;
559 /* TODO: numbering, shading */
560 fmt.wAlignment = PFA_LEFT;
561 fmt.cTabCount = 0;
562 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
563 fmt.wBorderWidth = fmt.wBorders = 0;
564 fmt.wBorderSpace = 0;
565 fmt.bLineSpacingRule = 0;
566 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
567 fmt.dyLineSpacing = 0;
568 if (!info->editor->bEmulateVersion10) /* v4.1 */
570 if (info->tableDef && info->tableDef->tableRowStart &&
571 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
573 ME_Cursor cursor;
574 ME_DisplayItem *para;
575 /* We are just after a table row. */
576 RTFFlushOutputBuffer(info);
577 cursor = info->editor->pCursors[0];
578 para = cursor.pPara;
579 if (para == info->tableDef->tableRowStart->member.para.next_para
580 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
582 /* Since the table row end, no text has been inserted, and the \intbl
583 * control word has not be used. We can confirm that we are not in a
584 * table anymore.
586 info->tableDef->tableRowStart = NULL;
587 info->canInheritInTbl = FALSE;
590 } else { /* v1.0 - v3.0 */
591 fmt.dwMask |= PFM_TABLE;
592 fmt.wEffects &= ~PFE_TABLE;
594 break;
595 case rtfNestLevel:
596 if (!info->editor->bEmulateVersion10) /* v4.1 */
598 while (info->rtfParam > info->nestingLevel) {
599 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
600 ZeroMemory(tableDef, sizeof(RTFTable));
601 tableDef->parent = info->tableDef;
602 info->tableDef = tableDef;
604 RTFFlushOutputBuffer(info);
605 if (tableDef->tableRowStart &&
606 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
608 ME_DisplayItem *para = tableDef->tableRowStart;
609 para = para->member.para.next_para;
610 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
611 tableDef->tableRowStart = para;
612 } else {
613 ME_Cursor cursor;
614 WCHAR endl = '\r';
615 cursor = info->editor->pCursors[0];
616 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
617 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
618 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
621 info->nestingLevel++;
623 info->canInheritInTbl = FALSE;
625 break;
626 case rtfInTable:
628 if (!info->editor->bEmulateVersion10) /* v4.1 */
630 if (info->nestingLevel < 1)
632 RTFTable *tableDef;
633 if (!info->tableDef)
635 info->tableDef = ALLOC_OBJ(RTFTable);
636 ZeroMemory(info->tableDef, sizeof(RTFTable));
638 tableDef = info->tableDef;
639 RTFFlushOutputBuffer(info);
640 if (tableDef->tableRowStart &&
641 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
643 ME_DisplayItem *para = tableDef->tableRowStart;
644 para = para->member.para.next_para;
645 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
646 tableDef->tableRowStart = para;
647 } else {
648 ME_Cursor cursor;
649 WCHAR endl = '\r';
650 cursor = info->editor->pCursors[0];
651 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
652 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
653 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
655 info->nestingLevel = 1;
656 info->canInheritInTbl = TRUE;
658 return;
659 } else { /* v1.0 - v3.0 */
660 fmt.dwMask |= PFM_TABLE;
661 fmt.wEffects |= PFE_TABLE;
663 break;
665 case rtfFirstIndent:
666 ME_GetSelectionParaFormat(info->editor, &fmt);
667 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
668 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
669 fmt.dxOffset = -info->rtfParam;
670 break;
671 case rtfLeftIndent:
672 ME_GetSelectionParaFormat(info->editor, &fmt);
673 fmt.dwMask = PFM_STARTINDENT;
674 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
675 break;
676 case rtfRightIndent:
677 fmt.dwMask = PFM_RIGHTINDENT;
678 fmt.dxRightIndent = info->rtfParam;
679 break;
680 case rtfQuadLeft:
681 case rtfQuadJust:
682 fmt.dwMask = PFM_ALIGNMENT;
683 fmt.wAlignment = PFA_LEFT;
684 break;
685 case rtfQuadRight:
686 fmt.dwMask = PFM_ALIGNMENT;
687 fmt.wAlignment = PFA_RIGHT;
688 break;
689 case rtfQuadCenter:
690 fmt.dwMask = PFM_ALIGNMENT;
691 fmt.wAlignment = PFA_CENTER;
692 break;
693 case rtfTabPos:
694 ME_GetSelectionParaFormat(info->editor, &fmt);
695 if (!(fmt.dwMask & PFM_TABSTOPS))
697 fmt.cTabCount = 0;
699 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
700 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
701 fmt.dwMask = PFM_TABSTOPS;
702 break;
703 case rtfKeep:
704 fmt.dwMask = PFM_KEEP;
705 fmt.wEffects = PFE_KEEP;
706 break;
707 case rtfNoWidowControl:
708 fmt.dwMask = PFM_NOWIDOWCONTROL;
709 fmt.wEffects = PFE_NOWIDOWCONTROL;
710 break;
711 case rtfKeepNext:
712 fmt.dwMask = PFM_KEEPNEXT;
713 fmt.wEffects = PFE_KEEPNEXT;
714 break;
715 case rtfSpaceAfter:
716 fmt.dwMask = PFM_SPACEAFTER;
717 fmt.dySpaceAfter = info->rtfParam;
718 break;
719 case rtfSpaceBefore:
720 fmt.dwMask = PFM_SPACEBEFORE;
721 fmt.dySpaceBefore = info->rtfParam;
722 break;
723 case rtfSpaceBetween:
724 fmt.dwMask = PFM_LINESPACING;
725 if ((int)info->rtfParam > 0)
727 fmt.dyLineSpacing = info->rtfParam;
728 fmt.bLineSpacingRule = 3;
730 else
732 fmt.dyLineSpacing = info->rtfParam;
733 fmt.bLineSpacingRule = 4;
735 break;
736 case rtfSpaceMultiply:
737 fmt.dwMask = PFM_LINESPACING;
738 fmt.dyLineSpacing = info->rtfParam * 20;
739 fmt.bLineSpacingRule = 5;
740 break;
741 case rtfParBullet:
742 fmt.dwMask = PFM_NUMBERING;
743 fmt.wNumbering = PFN_BULLET;
744 break;
745 case rtfParSimple:
746 fmt.dwMask = PFM_NUMBERING;
747 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
748 break;
749 case rtfParNumDecimal:
750 fmt.dwMask = PFM_NUMBERING;
751 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
752 break;
753 case rtfParNumIndent:
754 fmt.dwMask = PFM_NUMBERINGTAB;
755 fmt.wNumberingTab = info->rtfParam;
756 break;
757 case rtfParNumStartAt:
758 fmt.dwMask = PFM_NUMBERINGSTART;
759 fmt.wNumberingStart = info->rtfParam;
760 break;
761 case rtfBorderLeft:
762 info->borderType = RTFBorderParaLeft;
763 ME_GetSelectionParaFormat(info->editor, &fmt);
764 if (!(fmt.dwMask & PFM_BORDER))
766 fmt.wBorderSpace = 0;
767 fmt.wBorderWidth = 1;
768 fmt.wBorders = 0;
770 fmt.wBorders |= 1;
771 fmt.dwMask = PFM_BORDER;
772 break;
773 case rtfBorderRight:
774 info->borderType = RTFBorderParaRight;
775 ME_GetSelectionParaFormat(info->editor, &fmt);
776 if (!(fmt.dwMask & PFM_BORDER))
778 fmt.wBorderSpace = 0;
779 fmt.wBorderWidth = 1;
780 fmt.wBorders = 0;
782 fmt.wBorders |= 2;
783 fmt.dwMask = PFM_BORDER;
784 break;
785 case rtfBorderTop:
786 info->borderType = RTFBorderParaTop;
787 ME_GetSelectionParaFormat(info->editor, &fmt);
788 if (!(fmt.dwMask & PFM_BORDER))
790 fmt.wBorderSpace = 0;
791 fmt.wBorderWidth = 1;
792 fmt.wBorders = 0;
794 fmt.wBorders |= 4;
795 fmt.dwMask = PFM_BORDER;
796 break;
797 case rtfBorderBottom:
798 info->borderType = RTFBorderParaBottom;
799 ME_GetSelectionParaFormat(info->editor, &fmt);
800 if (!(fmt.dwMask & PFM_BORDER))
802 fmt.wBorderSpace = 0;
803 fmt.wBorderWidth = 1;
804 fmt.wBorders = 0;
806 fmt.wBorders |= 8;
807 fmt.dwMask = PFM_BORDER;
808 break;
809 case rtfBorderSingle:
810 ME_GetSelectionParaFormat(info->editor, &fmt);
811 /* we assume that borders have been created before (RTF spec) */
812 fmt.wBorders &= ~0x700;
813 fmt.wBorders |= 1 << 8;
814 fmt.dwMask = PFM_BORDER;
815 break;
816 case rtfBorderThick:
817 ME_GetSelectionParaFormat(info->editor, &fmt);
818 /* we assume that borders have been created before (RTF spec) */
819 fmt.wBorders &= ~0x700;
820 fmt.wBorders |= 2 << 8;
821 fmt.dwMask = PFM_BORDER;
822 break;
823 case rtfBorderShadow:
824 ME_GetSelectionParaFormat(info->editor, &fmt);
825 /* we assume that borders have been created before (RTF spec) */
826 fmt.wBorders &= ~0x700;
827 fmt.wBorders |= 10 << 8;
828 fmt.dwMask = PFM_BORDER;
829 break;
830 case rtfBorderDouble:
831 ME_GetSelectionParaFormat(info->editor, &fmt);
832 /* we assume that borders have been created before (RTF spec) */
833 fmt.wBorders &= ~0x700;
834 fmt.wBorders |= 7 << 8;
835 fmt.dwMask = PFM_BORDER;
836 break;
837 case rtfBorderDot:
838 ME_GetSelectionParaFormat(info->editor, &fmt);
839 /* we assume that borders have been created before (RTF spec) */
840 fmt.wBorders &= ~0x700;
841 fmt.wBorders |= 11 << 8;
842 fmt.dwMask = PFM_BORDER;
843 break;
844 case rtfBorderWidth:
846 int borderSide = info->borderType & RTFBorderSideMask;
847 RTFTable *tableDef = info->tableDef;
848 ME_GetSelectionParaFormat(info->editor, &fmt);
849 /* we assume that borders have been created before (RTF spec) */
850 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
851 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
853 RTFBorder *border;
854 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
855 break;
856 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
857 border->width = info->rtfParam;
858 break;
860 fmt.dwMask = PFM_BORDER;
861 break;
863 case rtfBorderSpace:
864 ME_GetSelectionParaFormat(info->editor, &fmt);
865 /* we assume that borders have been created before (RTF spec) */
866 fmt.wBorderSpace = info->rtfParam;
867 fmt.dwMask = PFM_BORDER;
868 break;
869 case rtfBorderColor:
871 RTFTable *tableDef = info->tableDef;
872 int borderSide = info->borderType & RTFBorderSideMask;
873 int borderType = info->borderType & RTFBorderTypeMask;
874 switch(borderType)
876 case RTFBorderTypePara:
877 if (!info->editor->bEmulateVersion10) /* v4.1 */
878 break;
879 /* v1.0 - 3.0 treat paragraph and row borders the same. */
880 case RTFBorderTypeRow:
881 if (tableDef) {
882 tableDef->border[borderSide].color = info->rtfParam;
884 break;
885 case RTFBorderTypeCell:
886 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
887 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
889 break;
891 break;
893 case rtfRTLPar:
894 fmt.dwMask = PFM_RTLPARA;
895 fmt.wEffects = PFE_RTLPARA;
896 break;
897 case rtfLTRPar:
898 fmt.dwMask = PFM_RTLPARA;
899 fmt.wEffects = 0;
900 break;
902 if (fmt.dwMask) {
903 RTFFlushOutputBuffer(info);
904 /* FIXME too slow ? how come ?*/
905 ME_SetSelectionParaFormat(info->editor, &fmt);
909 void ME_RTFTblAttrHook(RTF_Info *info)
911 switch (info->rtfMinor)
913 case rtfRowDef:
915 if (!info->editor->bEmulateVersion10) /* v4.1 */
916 info->borderType = 0; /* Not sure */
917 else /* v1.0 - 3.0 */
918 info->borderType = RTFBorderRowTop;
919 if (!info->tableDef) {
920 info->tableDef = ME_MakeTableDef(info->editor);
921 } else {
922 ME_InitTableDef(info->editor, info->tableDef);
924 break;
926 case rtfCellPos:
928 int cellNum;
929 if (!info->tableDef)
931 info->tableDef = ME_MakeTableDef(info->editor);
933 cellNum = info->tableDef->numCellsDefined;
934 if (cellNum >= MAX_TABLE_CELLS)
935 break;
936 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
937 if (cellNum < MAX_TAB_STOPS) {
938 /* Tab stops were used to store cell positions before v4.1 but v4.1
939 * still seems to set the tabstops without using them. */
940 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
941 PARAFORMAT2 *pFmt = para->member.para.pFmt;
942 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
943 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
945 info->tableDef->numCellsDefined++;
946 break;
948 case rtfRowBordTop:
949 info->borderType = RTFBorderRowTop;
950 break;
951 case rtfRowBordLeft:
952 info->borderType = RTFBorderRowLeft;
953 break;
954 case rtfRowBordBottom:
955 info->borderType = RTFBorderRowBottom;
956 break;
957 case rtfRowBordRight:
958 info->borderType = RTFBorderRowRight;
959 break;
960 case rtfCellBordTop:
961 info->borderType = RTFBorderCellTop;
962 break;
963 case rtfCellBordLeft:
964 info->borderType = RTFBorderCellLeft;
965 break;
966 case rtfCellBordBottom:
967 info->borderType = RTFBorderCellBottom;
968 break;
969 case rtfCellBordRight:
970 info->borderType = RTFBorderCellRight;
971 break;
972 case rtfRowGapH:
973 if (info->tableDef)
974 info->tableDef->gapH = info->rtfParam;
975 break;
976 case rtfRowLeftEdge:
977 if (info->tableDef)
978 info->tableDef->leftEdge = info->rtfParam;
979 break;
983 void ME_RTFSpecialCharHook(RTF_Info *info)
985 RTFTable *tableDef = info->tableDef;
986 switch (info->rtfMinor)
988 case rtfNestCell:
989 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
990 break;
991 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
992 case rtfCell:
993 if (!tableDef)
994 break;
995 RTFFlushOutputBuffer(info);
996 if (!info->editor->bEmulateVersion10) { /* v4.1 */
997 if (tableDef->tableRowStart)
999 if (!info->nestingLevel &&
1000 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1002 ME_DisplayItem *para = tableDef->tableRowStart;
1003 para = para->member.para.next_para;
1004 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1005 tableDef->tableRowStart = para;
1006 info->nestingLevel = 1;
1008 ME_InsertTableCellFromCursor(info->editor);
1010 } else { /* v1.0 - v3.0 */
1011 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1012 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1013 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
1014 tableDef->numCellsInserted < tableDef->numCellsDefined)
1016 WCHAR tab = '\t';
1017 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1018 tableDef->numCellsInserted++;
1021 break;
1022 case rtfNestRow:
1023 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
1024 break;
1025 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
1026 case rtfRow:
1028 ME_DisplayItem *para, *cell, *run;
1029 int i;
1031 if (!tableDef)
1032 break;
1033 RTFFlushOutputBuffer(info);
1034 if (!info->editor->bEmulateVersion10) { /* v4.1 */
1035 if (!tableDef->tableRowStart)
1036 break;
1037 if (!info->nestingLevel &&
1038 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1040 para = tableDef->tableRowStart;
1041 para = para->member.para.next_para;
1042 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1043 tableDef->tableRowStart = para;
1044 info->nestingLevel++;
1046 para = tableDef->tableRowStart;
1047 cell = ME_FindItemFwd(para, diCell);
1048 assert(cell && !cell->member.cell.prev_cell);
1049 if (tableDef->numCellsDefined < 1)
1051 /* 2000 twips appears to be the cell size that native richedit uses
1052 * when no cell sizes are specified. */
1053 const int defaultCellSize = 2000;
1054 int nRightBoundary = defaultCellSize;
1055 cell->member.cell.nRightBoundary = nRightBoundary;
1056 while (cell->member.cell.next_cell) {
1057 cell = cell->member.cell.next_cell;
1058 nRightBoundary += defaultCellSize;
1059 cell->member.cell.nRightBoundary = nRightBoundary;
1061 para = ME_InsertTableCellFromCursor(info->editor);
1062 cell = para->member.para.pCell;
1063 cell->member.cell.nRightBoundary = nRightBoundary;
1064 } else {
1065 for (i = 0; i < tableDef->numCellsDefined; i++)
1067 RTFCell *cellDef = &tableDef->cells[i];
1068 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1069 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1070 cellDef->border);
1071 cell = cell->member.cell.next_cell;
1072 if (!cell)
1074 para = ME_InsertTableCellFromCursor(info->editor);
1075 cell = para->member.para.pCell;
1078 /* Cell for table row delimiter is empty */
1079 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1082 run = ME_FindItemFwd(cell, diRun);
1083 if (info->editor->pCursors[0].pRun != run ||
1084 info->editor->pCursors[0].nOffset)
1086 int nOfs, nChars;
1087 /* Delete inserted cells that aren't defined. */
1088 info->editor->pCursors[1].pRun = run;
1089 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1090 info->editor->pCursors[1].nOffset = 0;
1091 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1092 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1093 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1094 nChars, TRUE);
1097 para = ME_InsertTableRowEndFromCursor(info->editor);
1098 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1099 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1100 ME_ApplyBorderProperties(info, &para->member.para.border,
1101 tableDef->border);
1102 info->nestingLevel--;
1103 if (!info->nestingLevel)
1105 if (info->canInheritInTbl) {
1106 tableDef->tableRowStart = para;
1107 } else {
1108 while (info->tableDef) {
1109 tableDef = info->tableDef;
1110 info->tableDef = tableDef->parent;
1111 heap_free(tableDef);
1114 } else {
1115 info->tableDef = tableDef->parent;
1116 heap_free(tableDef);
1118 } else { /* v1.0 - v3.0 */
1119 WCHAR endl = '\r';
1120 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1121 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1122 pFmt->dxOffset = info->tableDef->gapH;
1123 pFmt->dxStartIndent = info->tableDef->leftEdge;
1125 ME_ApplyBorderProperties(info, &para->member.para.border,
1126 tableDef->border);
1127 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1129 WCHAR tab = '\t';
1130 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1131 tableDef->numCellsInserted++;
1133 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1134 if (!tableDef->numCellsDefined)
1135 pFmt->wEffects &= ~PFE_TABLE;
1136 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1137 tableDef->numCellsInserted = 0;
1139 break;
1141 case rtfTab:
1142 case rtfPar:
1143 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1144 ME_DisplayItem *para;
1145 PARAFORMAT2 *pFmt;
1146 RTFFlushOutputBuffer(info);
1147 para = info->editor->pCursors[0].pPara;
1148 pFmt = para->member.para.pFmt;
1149 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1151 /* rtfPar is treated like a space within a table. */
1152 info->rtfClass = rtfText;
1153 info->rtfMajor = ' ';
1155 else if (info->rtfMinor == rtfPar && tableDef)
1156 tableDef->numCellsInserted = 0;
1158 break;
1162 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1163 const SIZEL* sz)
1165 LPOLEOBJECT lpObject = NULL;
1166 LPSTORAGE lpStorage = NULL;
1167 LPOLECLIENTSITE lpClientSite = NULL;
1168 LPDATAOBJECT lpDataObject = NULL;
1169 LPOLECACHE lpOleCache = NULL;
1170 STGMEDIUM stgm;
1171 FORMATETC fm;
1172 CLSID clsid;
1173 BOOL ret = FALSE;
1174 DWORD conn;
1176 if (hemf)
1178 stgm.tymed = TYMED_ENHMF;
1179 stgm.u.hEnhMetaFile = hemf;
1180 fm.cfFormat = CF_ENHMETAFILE;
1182 else if (hbmp)
1184 stgm.tymed = TYMED_GDI;
1185 stgm.u.hBitmap = hbmp;
1186 fm.cfFormat = CF_BITMAP;
1188 stgm.pUnkForRelease = NULL;
1190 fm.ptd = NULL;
1191 fm.dwAspect = DVASPECT_CONTENT;
1192 fm.lindex = -1;
1193 fm.tymed = stgm.tymed;
1195 if (!info->lpRichEditOle)
1197 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1200 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1201 #if 0
1202 /* FIXME: enable it when rich-edit properly implements this method */
1203 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1204 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1205 #endif
1206 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1207 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1208 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1209 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1210 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1212 REOBJECT reobject;
1214 reobject.cbStruct = sizeof(reobject);
1215 reobject.cp = REO_CP_SELECTION;
1216 reobject.clsid = clsid;
1217 reobject.poleobj = lpObject;
1218 reobject.pstg = lpStorage;
1219 reobject.polesite = lpClientSite;
1220 /* convert from twips to .01 mm */
1221 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1222 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1223 reobject.dvaspect = DVASPECT_CONTENT;
1224 reobject.dwFlags = 0; /* FIXME */
1225 reobject.dwUser = 0;
1227 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1228 ret = TRUE;
1231 if (lpObject) IOleObject_Release(lpObject);
1232 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1233 if (lpStorage) IStorage_Release(lpStorage);
1234 if (lpDataObject) IDataObject_Release(lpDataObject);
1235 if (lpOleCache) IOleCache_Release(lpOleCache);
1237 return ret;
1240 static void ME_RTFReadPictGroup(RTF_Info *info)
1242 SIZEL sz;
1243 BYTE* buffer = NULL;
1244 unsigned bufsz, bufidx;
1245 BOOL flip;
1246 BYTE val;
1247 METAFILEPICT mfp;
1248 HENHMETAFILE hemf;
1249 HBITMAP hbmp;
1250 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1252 RTFGetToken (info);
1253 if (info->rtfClass == rtfEOF)
1254 return;
1255 mfp.mm = MM_TEXT;
1256 /* fetch picture type */
1257 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1259 mfp.mm = info->rtfParam;
1260 gfx = gfx_metafile;
1262 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1264 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1265 gfx = gfx_dib;
1267 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1269 gfx = gfx_enhmetafile;
1271 else
1273 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1274 goto skip_group;
1276 sz.cx = sz.cy = 0;
1277 /* fetch picture attributes */
1278 for (;;)
1280 RTFGetToken (info);
1281 if (info->rtfClass == rtfEOF)
1282 return;
1283 if (info->rtfClass == rtfText)
1284 break;
1285 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1287 ERR("Expected picture attribute (%d %d)\n",
1288 info->rtfClass, info->rtfMajor);
1289 goto skip_group;
1291 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1293 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1295 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1297 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1299 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1300 sz.cx = info->rtfParam;
1301 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1302 sz.cy = info->rtfParam;
1303 else
1304 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1306 /* fetch picture data */
1307 bufsz = 1024;
1308 bufidx = 0;
1309 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1310 val = info->rtfMajor;
1311 for (flip = TRUE;; flip = !flip)
1313 RTFGetToken (info);
1314 if (info->rtfClass == rtfEOF)
1316 HeapFree(GetProcessHeap(), 0, buffer);
1317 return; /* Warn ?? */
1319 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1320 break;
1321 if (info->rtfClass != rtfText) goto skip_group;
1322 if (flip)
1324 if (bufidx >= bufsz &&
1325 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1326 goto skip_group;
1327 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1329 else
1330 val = info->rtfMajor;
1332 if (flip) FIXME("wrong hex string\n");
1334 switch (gfx)
1336 case gfx_enhmetafile:
1337 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1338 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1339 break;
1340 case gfx_metafile:
1341 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1342 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1343 break;
1344 case gfx_dib:
1346 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1347 HDC hdc = GetDC(0);
1348 unsigned nc = bi->bmiHeader.biClrUsed;
1350 /* not quite right, especially for bitfields type of compression */
1351 if (!nc && bi->bmiHeader.biBitCount <= 8)
1352 nc = 1 << bi->bmiHeader.biBitCount;
1353 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1354 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1355 bi, DIB_RGB_COLORS)))
1356 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1357 ReleaseDC(0, hdc);
1359 break;
1360 default:
1361 break;
1363 HeapFree(GetProcessHeap(), 0, buffer);
1364 RTFRouteToken (info); /* feed "}" back to router */
1365 return;
1366 skip_group:
1367 HeapFree(GetProcessHeap(), 0, buffer);
1368 RTFSkipGroup(info);
1369 RTFRouteToken(info); /* feed "}" back to router */
1372 /* for now, lookup the \result part and use it, whatever the object */
1373 static void ME_RTFReadObjectGroup(RTF_Info *info)
1375 for (;;)
1377 RTFGetToken (info);
1378 if (info->rtfClass == rtfEOF)
1379 return;
1380 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1381 break;
1382 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1384 RTFGetToken (info);
1385 if (info->rtfClass == rtfEOF)
1386 return;
1387 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1389 int level = 1;
1391 while (RTFGetToken (info) != rtfEOF)
1393 if (info->rtfClass == rtfGroup)
1395 if (info->rtfMajor == rtfBeginGroup) level++;
1396 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1398 RTFRouteToken(info);
1401 else RTFSkipGroup(info);
1402 continue;
1404 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1406 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1407 return;
1410 RTFRouteToken(info); /* feed "}" back to router */
1413 static void ME_RTFReadHook(RTF_Info *info)
1415 switch(info->rtfClass)
1417 case rtfGroup:
1418 switch(info->rtfMajor)
1420 case rtfBeginGroup:
1421 if (info->stackTop < maxStack) {
1422 info->stack[info->stackTop].style = info->style;
1423 ME_AddRefStyle(info->style);
1424 info->stack[info->stackTop].codePage = info->codePage;
1425 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1427 info->stackTop++;
1428 info->styleChanged = FALSE;
1429 break;
1430 case rtfEndGroup:
1432 RTFFlushOutputBuffer(info);
1433 info->stackTop--;
1434 if (info->stackTop <= 0)
1435 info->rtfClass = rtfEOF;
1436 if (info->stackTop < 0)
1437 return;
1439 ME_ReleaseStyle(info->style);
1440 info->style = info->stack[info->stackTop].style;
1441 info->codePage = info->stack[info->stackTop].codePage;
1442 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1443 break;
1446 break;
1450 void
1451 ME_StreamInFill(ME_InStream *stream)
1453 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1454 (BYTE *)stream->buffer,
1455 sizeof(stream->buffer),
1456 (LONG *)&stream->dwSize);
1457 stream->dwUsed = 0;
1460 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1462 RTF_Info parser;
1463 ME_Style *style;
1464 int from, to, nUndoMode;
1465 int nEventMask = editor->nEventMask;
1466 ME_InStream inStream;
1467 BOOL invalidRTF = FALSE;
1468 ME_Cursor *selStart, *selEnd;
1469 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1471 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1472 editor->nEventMask = 0;
1474 ME_GetSelectionOfs(editor, &from, &to);
1475 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1477 ME_GetSelection(editor, &selStart, &selEnd);
1478 style = ME_GetSelectionInsertStyle(editor);
1480 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1482 /* Don't insert text at the end of the table row */
1483 if (!editor->bEmulateVersion10) { /* v4.1 */
1484 ME_DisplayItem *para = editor->pCursors->pPara;
1485 if (para->member.para.nFlags & MEPF_ROWEND)
1487 para = para->member.para.next_para;
1488 editor->pCursors[0].pPara = para;
1489 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1490 editor->pCursors[0].nOffset = 0;
1492 if (para->member.para.nFlags & MEPF_ROWSTART)
1494 para = para->member.para.next_para;
1495 editor->pCursors[0].pPara = para;
1496 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1497 editor->pCursors[0].nOffset = 0;
1499 editor->pCursors[1] = editor->pCursors[0];
1500 } else { /* v1.0 - 3.0 */
1501 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1502 ME_IsInTable(editor->pCursors[0].pRun))
1503 return 0;
1505 } else {
1506 style = editor->pBuffer->pDefaultStyle;
1507 ME_AddRefStyle(style);
1508 ME_SetSelection(editor, 0, 0);
1509 ME_InternalDeleteText(editor, &editor->pCursors[1],
1510 ME_GetTextLength(editor), FALSE);
1511 from = to = 0;
1512 ME_ClearTempStyle(editor);
1513 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1517 /* Back up undo mode to a local variable */
1518 nUndoMode = editor->nUndoMode;
1520 /* Only create an undo if SFF_SELECTION is set */
1521 if (!(format & SFF_SELECTION))
1522 editor->nUndoMode = umIgnore;
1524 inStream.editstream = stream;
1525 inStream.editstream->dwError = 0;
1526 inStream.dwSize = 0;
1527 inStream.dwUsed = 0;
1529 if (format & SF_RTF)
1531 /* Check if it's really RTF, and if it is not, use plain text */
1532 ME_StreamInFill(&inStream);
1533 if (!inStream.editstream->dwError)
1535 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1536 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1538 invalidRTF = TRUE;
1539 inStream.editstream->dwError = -16;
1544 if (!invalidRTF && !inStream.editstream->dwError)
1546 if (format & SF_RTF) {
1547 from = ME_GetCursorOfs(&editor->pCursors[0]);
1549 /* setup the RTF parser */
1550 memset(&parser, 0, sizeof parser);
1551 RTFSetEditStream(&parser, &inStream);
1552 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1553 parser.editor = editor;
1554 parser.style = style;
1555 WriterInit(&parser);
1556 RTFInit(&parser);
1557 RTFSetReadHook(&parser, ME_RTFReadHook);
1558 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1559 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1560 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1562 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1563 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1565 BeginFile(&parser);
1567 /* do the parsing */
1568 RTFRead(&parser);
1569 RTFFlushOutputBuffer(&parser);
1570 if (!editor->bEmulateVersion10) { /* v4.1 */
1571 if (parser.tableDef && parser.tableDef->tableRowStart &&
1572 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1574 /* Delete any incomplete table row at the end of the rich text. */
1575 int nOfs, nChars;
1576 ME_DisplayItem *para;
1578 parser.rtfMinor = rtfRow;
1579 /* Complete the table row before deleting it.
1580 * By doing it this way we will have the current paragraph format set
1581 * properly to reflect that is not in the complete table, and undo items
1582 * will be added for this change to the current paragraph format. */
1583 if (parser.nestingLevel > 0)
1585 while (parser.nestingLevel > 1)
1586 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1587 para = parser.tableDef->tableRowStart;
1588 ME_RTFSpecialCharHook(&parser);
1589 } else {
1590 para = parser.tableDef->tableRowStart;
1591 ME_RTFSpecialCharHook(&parser);
1592 assert(para->member.para.nFlags & MEPF_ROWEND);
1593 para = para->member.para.next_para;
1596 editor->pCursors[1].pPara = para;
1597 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1598 editor->pCursors[1].nOffset = 0;
1599 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1600 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1601 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1602 if (parser.tableDef)
1603 parser.tableDef->tableRowStart = NULL;
1606 ME_CheckTablesForCorruption(editor);
1607 RTFDestroy(&parser);
1608 if (parser.lpRichEditOle)
1609 IRichEditOle_Release(parser.lpRichEditOle);
1611 if (parser.stackTop > 0)
1613 while (--parser.stackTop >= 0)
1615 ME_ReleaseStyle(parser.style);
1616 parser.style = parser.stack[parser.stackTop].style;
1618 if (!inStream.editstream->dwError)
1619 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1622 /* Remove last line break, as mandated by tests. This is not affected by
1623 CR/LF counters, since RTF streaming presents only \para tokens, which
1624 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1626 if (stripLastCR) {
1627 int newto;
1628 ME_GetSelection(editor, &selStart, &selEnd);
1629 newto = ME_GetCursorOfs(selEnd);
1630 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1631 WCHAR lastchar[3] = {'\0', '\0'};
1632 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1633 ME_Cursor linebreakCursor = *selEnd;
1635 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1636 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1637 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1638 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1642 to = ME_GetCursorOfs(&editor->pCursors[0]);
1643 num_read = to - from;
1645 style = parser.style;
1647 else if (format & SF_TEXT)
1648 num_read = ME_StreamInText(editor, format, &inStream, style);
1649 else
1650 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1651 /* put the cursor at the top */
1652 if (!(format & SFF_SELECTION))
1653 ME_SetSelection(editor, 0, 0);
1656 /* Restore saved undo mode */
1657 editor->nUndoMode = nUndoMode;
1659 /* even if we didn't add an undo, we need to commit anything on the stack */
1660 ME_CommitUndo(editor);
1662 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1663 if (!(format & SFF_SELECTION))
1664 ME_EmptyUndoStack(editor);
1666 ME_ReleaseStyle(style);
1667 editor->nEventMask = nEventMask;
1668 ME_UpdateRepaint(editor, FALSE);
1669 if (!(format & SFF_SELECTION)) {
1670 ME_ClearTempStyle(editor);
1672 ITextHost_TxShowCaret(editor->texthost, FALSE);
1673 ME_MoveCaret(editor);
1674 ITextHost_TxShowCaret(editor->texthost, TRUE);
1675 ME_SendSelChange(editor);
1676 ME_SendRequestResize(editor, FALSE);
1678 return num_read;
1682 typedef struct tagME_RTFStringStreamStruct
1684 char *string;
1685 int pos;
1686 int length;
1687 } ME_RTFStringStreamStruct;
1689 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1691 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1692 int count;
1694 count = min(cb, pStruct->length - pStruct->pos);
1695 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1696 pStruct->pos += count;
1697 *pcb = count;
1698 return 0;
1701 static void
1702 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1704 EDITSTREAM es;
1705 ME_RTFStringStreamStruct data;
1707 data.string = string;
1708 data.length = strlen(string);
1709 data.pos = 0;
1710 es.dwCookie = (DWORD_PTR)&data;
1711 es.pfnCallback = ME_ReadFromRTFString;
1712 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1716 static int
1717 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1719 const int nLen = lstrlenW(text);
1720 const int nTextLen = ME_GetTextLength(editor);
1721 int nMin, nMax;
1722 ME_Cursor cursor;
1723 WCHAR wLastChar = ' ';
1725 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1726 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1728 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1729 FIXME("Flags 0x%08x not implemented\n",
1730 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1732 nMin = chrg->cpMin;
1733 if (chrg->cpMax == -1)
1734 nMax = nTextLen;
1735 else
1736 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1738 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1739 if (editor->bEmulateVersion10 && nMax == nTextLen)
1741 flags |= FR_DOWN;
1744 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1745 if (editor->bEmulateVersion10 && nMax < nMin)
1747 if (chrgText)
1749 chrgText->cpMin = -1;
1750 chrgText->cpMax = -1;
1752 return -1;
1755 /* when searching up, if cpMin < cpMax, then instead of searching
1756 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1757 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1758 * case, it is always bigger than cpMin.
1760 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1762 int nSwap = nMax;
1764 nMax = nMin > nTextLen ? nTextLen : nMin;
1765 if (nMin < nSwap || chrg->cpMax == -1)
1766 nMin = 0;
1767 else
1768 nMin = nSwap;
1771 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1773 if (chrgText)
1774 chrgText->cpMin = chrgText->cpMax = -1;
1775 return -1;
1778 if (flags & FR_DOWN) /* Forward search */
1780 /* If possible, find the character before where the search starts */
1781 if ((flags & FR_WHOLEWORD) && nMin)
1783 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1784 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1785 ME_MoveCursorChars(editor, &cursor, 1);
1786 } else {
1787 ME_CursorFromCharOfs(editor, nMin, &cursor);
1790 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1792 ME_DisplayItem *pCurItem = cursor.pRun;
1793 int nCurStart = cursor.nOffset;
1794 int nMatched = 0;
1796 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1798 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1799 break;
1801 nMatched++;
1802 if (nMatched == nLen)
1804 ME_DisplayItem *pNextItem = pCurItem;
1805 int nNextStart = nCurStart;
1806 WCHAR wNextChar;
1808 /* Check to see if next character is a whitespace */
1809 if (flags & FR_WHOLEWORD)
1811 if (nCurStart + nMatched == pCurItem->member.run.len)
1813 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1814 nNextStart = -nMatched;
1817 if (pNextItem)
1818 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1819 else
1820 wNextChar = ' ';
1822 if (isalnumW(wNextChar))
1823 break;
1826 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1827 if (chrgText)
1829 chrgText->cpMin = cursor.nOffset;
1830 chrgText->cpMax = cursor.nOffset + nLen;
1832 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1833 return cursor.nOffset;
1835 if (nCurStart + nMatched == pCurItem->member.run.len)
1837 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1838 nCurStart = -nMatched;
1841 if (pCurItem)
1842 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1843 else
1844 wLastChar = ' ';
1846 cursor.nOffset++;
1847 if (cursor.nOffset == cursor.pRun->member.run.len)
1849 ME_NextRun(&cursor.pPara, &cursor.pRun);
1850 cursor.nOffset = 0;
1854 else /* Backward search */
1856 /* If possible, find the character after where the search ends */
1857 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1859 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1860 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1861 ME_MoveCursorChars(editor, &cursor, -1);
1862 } else {
1863 ME_CursorFromCharOfs(editor, nMax, &cursor);
1866 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1868 ME_DisplayItem *pCurItem = cursor.pRun;
1869 ME_DisplayItem *pCurPara = cursor.pPara;
1870 int nCurEnd = cursor.nOffset;
1871 int nMatched = 0;
1873 if (nCurEnd == 0)
1875 ME_PrevRun(&pCurPara, &pCurItem);
1876 nCurEnd = pCurItem->member.run.len + nMatched;
1879 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1880 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1882 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1883 break;
1885 nMatched++;
1886 if (nMatched == nLen)
1888 ME_DisplayItem *pPrevItem = pCurItem;
1889 int nPrevEnd = nCurEnd;
1890 WCHAR wPrevChar;
1891 int nStart;
1893 /* Check to see if previous character is a whitespace */
1894 if (flags & FR_WHOLEWORD)
1896 if (nPrevEnd - nMatched == 0)
1898 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1899 if (pPrevItem)
1900 nPrevEnd = pPrevItem->member.run.len + nMatched;
1903 if (pPrevItem)
1904 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1905 else
1906 wPrevChar = ' ';
1908 if (isalnumW(wPrevChar))
1909 break;
1912 nStart = pCurPara->member.para.nCharOfs
1913 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1914 if (chrgText)
1916 chrgText->cpMin = nStart;
1917 chrgText->cpMax = nStart + nLen;
1919 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1920 return nStart;
1922 if (nCurEnd - nMatched == 0)
1924 ME_PrevRun(&pCurPara, &pCurItem);
1925 /* Don't care about pCurItem becoming NULL here; it's already taken
1926 * care of in the exterior loop condition */
1927 nCurEnd = pCurItem->member.run.len + nMatched;
1930 if (pCurItem)
1931 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1932 else
1933 wLastChar = ' ';
1935 cursor.nOffset--;
1936 if (cursor.nOffset < 0)
1938 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1939 cursor.nOffset = cursor.pRun->member.run.len;
1943 TRACE("not found\n");
1944 if (chrgText)
1945 chrgText->cpMin = chrgText->cpMax = -1;
1946 return -1;
1949 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1951 int nChars;
1952 ME_Cursor start;
1954 if (!ex->cb || !pText) return 0;
1956 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1957 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1959 if (ex->flags & GT_SELECTION)
1961 int from, to;
1962 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1963 start = editor->pCursors[nStartCur];
1964 nChars = to - from;
1966 else
1968 ME_SetCursorToStart(editor, &start);
1969 nChars = INT_MAX;
1971 if (ex->codepage == 1200)
1973 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1974 &start, nChars, ex->flags & GT_USECRLF);
1976 else
1978 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1979 we can just take a bigger buffer? :)
1980 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1981 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1983 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1984 DWORD buflen;
1985 LPWSTR buffer;
1986 LRESULT rc;
1988 buflen = min(crlfmul * nChars, ex->cb - 1);
1989 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1991 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1992 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1993 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1994 if (rc) rc--; /* do not count 0 terminator */
1996 heap_free(buffer);
1997 return rc;
2001 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2002 const ME_Cursor *start, int nLen, BOOL unicode)
2004 if (!strText) return 0;
2005 if (unicode) {
2006 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
2007 } else {
2008 int nChars;
2009 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2010 if (!p) return 0;
2011 nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
2012 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2013 nLen+1, NULL, NULL);
2014 FREE_OBJ(p);
2015 return nChars;
2019 typedef struct tagME_GlobalDestStruct
2021 HGLOBAL hData;
2022 int nLength;
2023 } ME_GlobalDestStruct;
2025 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2027 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2028 int i;
2029 WORD *pSrc, *pDest;
2031 cb = cb >> 1;
2032 pDest = (WORD *)lpBuff;
2033 pSrc = GlobalLock(pData->hData);
2034 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2035 pDest[i] = pSrc[pData->nLength+i];
2037 pData->nLength += i;
2038 *pcb = 2*i;
2039 GlobalUnlock(pData->hData);
2040 return 0;
2043 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2045 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2046 int i;
2047 BYTE *pSrc, *pDest;
2049 pDest = lpBuff;
2050 pSrc = GlobalLock(pData->hData);
2051 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2052 pDest[i] = pSrc[pData->nLength+i];
2054 pData->nLength += i;
2055 *pcb = i;
2056 GlobalUnlock(pData->hData);
2057 return 0;
2060 static BOOL ME_Paste(ME_TextEditor *editor)
2062 DWORD dwFormat = 0;
2063 EDITSTREAM es;
2064 ME_GlobalDestStruct gds;
2065 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2066 UINT cf = 0;
2068 if (IsClipboardFormatAvailable(nRTFFormat))
2069 cf = nRTFFormat, dwFormat = SF_RTF;
2070 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2071 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2072 else
2073 return FALSE;
2075 if (!OpenClipboard(editor->hWnd))
2076 return FALSE;
2077 gds.hData = GetClipboardData(cf);
2078 gds.nLength = 0;
2079 es.dwCookie = (DWORD_PTR)&gds;
2080 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2081 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2083 CloseClipboard();
2084 return TRUE;
2087 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2089 LPDATAOBJECT dataObj = NULL;
2090 HRESULT hr = S_OK;
2092 if (editor->cPasswordMask)
2093 return FALSE; /* Copying or Cutting masked text isn't allowed */
2095 if(editor->lpOleCallback)
2097 CHARRANGE range;
2098 range.cpMin = ME_GetCursorOfs(start);
2099 range.cpMax = range.cpMin + nChars;
2100 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2102 if(FAILED(hr) || !dataObj)
2103 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2104 if(SUCCEEDED(hr)) {
2105 hr = OleSetClipboard(dataObj);
2106 IDataObject_Release(dataObj);
2108 return SUCCEEDED(hr) != 0;
2111 /* helper to send a msg filter notification */
2112 static BOOL
2113 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2115 MSGFILTER msgf;
2117 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2118 msgf.nmhdr.hwndFrom = editor->hWnd;
2119 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2120 msgf.nmhdr.code = EN_MSGFILTER;
2121 msgf.msg = msg;
2122 msgf.wParam = *wParam;
2123 msgf.lParam = *lParam;
2124 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2125 return FALSE;
2126 *wParam = msgf.wParam;
2127 *lParam = msgf.lParam;
2128 msgf.wParam = *wParam;
2130 return TRUE;
2133 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2135 ME_DisplayItem *startPara, *endPara;
2136 ME_DisplayItem *prev_para;
2137 ME_Cursor *from, *to;
2138 ME_Cursor start;
2139 int nChars;
2141 if (!editor->AutoURLDetect_bEnable) return;
2143 ME_GetSelection(editor, &from, &to);
2145 /* Find paragraph previous to the one that contains start cursor */
2146 startPara = from->pPara;
2147 prev_para = startPara->member.para.prev_para;
2148 if (prev_para->type == diParagraph) startPara = prev_para;
2150 /* Find paragraph that contains end cursor */
2151 endPara = to->pPara->member.para.next_para;
2153 start.pPara = startPara;
2154 start.pRun = ME_FindItemFwd(startPara, diRun);
2155 start.nOffset = 0;
2156 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2158 ME_UpdateLinkAttribute(editor, &start, nChars);
2161 static BOOL
2162 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2164 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2165 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2167 if (editor->bMouseCaptured)
2168 return FALSE;
2169 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2170 editor->nSelectionType = stPosition;
2172 switch (nKey)
2174 case VK_LEFT:
2175 case VK_RIGHT:
2176 case VK_HOME:
2177 case VK_END:
2178 editor->nUDArrowX = -1;
2179 /* fall through */
2180 case VK_UP:
2181 case VK_DOWN:
2182 case VK_PRIOR:
2183 case VK_NEXT:
2184 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2185 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2186 return TRUE;
2187 case VK_BACK:
2188 case VK_DELETE:
2189 editor->nUDArrowX = -1;
2190 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2191 if (editor->styleFlags & ES_READONLY)
2192 return FALSE;
2193 if (ME_IsSelection(editor))
2195 ME_DeleteSelection(editor);
2196 ME_CommitUndo(editor);
2198 else if (nKey == VK_DELETE)
2200 /* Delete stops group typing.
2201 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2202 ME_DeleteTextAtCursor(editor, 1, 1);
2203 ME_CommitUndo(editor);
2205 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2207 BOOL bDeletionSucceeded;
2208 /* Backspace can be grouped for a single undo */
2209 ME_ContinueCoalescingTransaction(editor);
2210 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2211 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2212 /* Deletion was prevented so the cursor is moved back to where it was.
2213 * (e.g. this happens when trying to delete cell boundaries)
2215 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2217 ME_CommitCoalescingUndo(editor);
2219 else
2220 return TRUE;
2221 ME_MoveCursorFromTableRowStartParagraph(editor);
2222 ME_UpdateSelectionLinkAttribute(editor);
2223 ME_UpdateRepaint(editor, FALSE);
2224 ME_SendRequestResize(editor, FALSE);
2225 return TRUE;
2226 case VK_RETURN:
2227 if (editor->bDialogMode)
2229 if (ctrl_is_down)
2230 return TRUE;
2232 if (!(editor->styleFlags & ES_WANTRETURN))
2234 if (editor->hwndParent)
2236 DWORD dw;
2237 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2238 if (HIWORD(dw) == DC_HASDEFID)
2240 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2241 if (hwDefCtrl)
2243 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2244 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2248 return TRUE;
2252 if (editor->styleFlags & ES_MULTILINE)
2254 ME_Cursor cursor = editor->pCursors[0];
2255 ME_DisplayItem *para = cursor.pPara;
2256 int from, to;
2257 const WCHAR endl = '\r';
2258 const WCHAR endlv10[] = {'\r','\n'};
2259 ME_Style *style;
2261 if (editor->styleFlags & ES_READONLY) {
2262 MessageBeep(MB_ICONERROR);
2263 return TRUE;
2266 ME_GetSelectionOfs(editor, &from, &to);
2267 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2269 if (!editor->bEmulateVersion10) { /* v4.1 */
2270 if (para->member.para.nFlags & MEPF_ROWEND) {
2271 /* Add a new table row after this row. */
2272 para = ME_AppendTableRow(editor, para);
2273 para = para->member.para.next_para;
2274 editor->pCursors[0].pPara = para;
2275 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2276 editor->pCursors[0].nOffset = 0;
2277 editor->pCursors[1] = editor->pCursors[0];
2278 ME_CommitUndo(editor);
2279 ME_CheckTablesForCorruption(editor);
2280 ME_UpdateRepaint(editor, FALSE);
2281 return TRUE;
2283 else if (para == editor->pCursors[1].pPara &&
2284 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2285 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2286 !para->member.para.prev_para->member.para.nCharOfs)
2288 /* Insert a newline before the table. */
2289 para = para->member.para.prev_para;
2290 para->member.para.nFlags &= ~MEPF_ROWSTART;
2291 editor->pCursors[0].pPara = para;
2292 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2293 editor->pCursors[1] = editor->pCursors[0];
2294 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2295 editor->pCursors[0].pRun->member.run.style);
2296 para = editor->pBuffer->pFirst->member.para.next_para;
2297 ME_SetDefaultParaFormat(para->member.para.pFmt);
2298 para->member.para.nFlags = MEPF_REWRAP;
2299 editor->pCursors[0].pPara = para;
2300 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2301 editor->pCursors[1] = editor->pCursors[0];
2302 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2303 ME_CommitCoalescingUndo(editor);
2304 ME_CheckTablesForCorruption(editor);
2305 ME_UpdateRepaint(editor, FALSE);
2306 return TRUE;
2308 } else { /* v1.0 - 3.0 */
2309 ME_DisplayItem *para = cursor.pPara;
2310 if (ME_IsInTable(para))
2312 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2314 if (from == to) {
2315 ME_ContinueCoalescingTransaction(editor);
2316 para = ME_AppendTableRow(editor, para);
2317 editor->pCursors[0].pPara = para;
2318 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2319 editor->pCursors[0].nOffset = 0;
2320 editor->pCursors[1] = editor->pCursors[0];
2321 ME_CommitCoalescingUndo(editor);
2322 ME_UpdateRepaint(editor, FALSE);
2323 return TRUE;
2325 } else {
2326 ME_ContinueCoalescingTransaction(editor);
2327 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2328 !ME_IsInTable(para->member.para.prev_para))
2330 /* Insert newline before table */
2331 cursor.pRun = ME_FindItemBack(para, diRun);
2332 if (cursor.pRun) {
2333 editor->pCursors[0].pRun = cursor.pRun;
2334 editor->pCursors[0].pPara = para->member.para.prev_para;
2336 editor->pCursors[0].nOffset = 0;
2337 editor->pCursors[1] = editor->pCursors[0];
2338 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2339 editor->pCursors[0].pRun->member.run.style);
2340 } else {
2341 editor->pCursors[1] = editor->pCursors[0];
2342 para = ME_AppendTableRow(editor, para);
2343 editor->pCursors[0].pPara = para;
2344 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2345 editor->pCursors[0].nOffset = 0;
2346 editor->pCursors[1] = editor->pCursors[0];
2348 ME_CommitCoalescingUndo(editor);
2349 ME_UpdateRepaint(editor, FALSE);
2350 return TRUE;
2355 style = ME_GetInsertStyle(editor, 0);
2356 ME_SaveTempStyle(editor);
2357 ME_ContinueCoalescingTransaction(editor);
2358 if (shift_is_down)
2359 ME_InsertEndRowFromCursor(editor, 0);
2360 else
2361 if (!editor->bEmulateVersion10)
2362 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2363 else
2364 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2365 ME_ReleaseStyle(style);
2366 ME_CommitCoalescingUndo(editor);
2367 SetCursor(NULL);
2369 ME_UpdateSelectionLinkAttribute(editor);
2370 ME_UpdateRepaint(editor, FALSE);
2372 return TRUE;
2374 break;
2375 case VK_ESCAPE:
2376 if (editor->bDialogMode && editor->hwndParent)
2377 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2378 return TRUE;
2379 case VK_TAB:
2380 if (editor->bDialogMode && editor->hwndParent)
2381 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2382 return TRUE;
2383 case 'A':
2384 if (ctrl_is_down)
2386 ME_SetSelection(editor, 0, -1);
2387 return TRUE;
2389 break;
2390 case 'V':
2391 if (ctrl_is_down)
2392 return ME_Paste(editor);
2393 break;
2394 case 'C':
2395 case 'X':
2396 if (ctrl_is_down)
2398 BOOL result;
2399 int nOfs, nChars;
2400 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2401 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2403 nChars -= nOfs;
2404 result = ME_Copy(editor, selStart, nChars);
2405 if (result && nKey == 'X')
2407 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2408 ME_CommitUndo(editor);
2409 ME_UpdateRepaint(editor, TRUE);
2411 return result;
2413 break;
2414 case 'Z':
2415 if (ctrl_is_down)
2417 ME_Undo(editor);
2418 return TRUE;
2420 break;
2421 case 'Y':
2422 if (ctrl_is_down)
2424 ME_Redo(editor);
2425 return TRUE;
2427 break;
2429 default:
2430 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2431 editor->nUDArrowX = -1;
2432 if (ctrl_is_down)
2434 if (nKey == 'W')
2436 CHARFORMAT2W chf;
2437 char buf[2048];
2438 chf.cbSize = sizeof(chf);
2440 ME_GetSelectionCharFormat(editor, &chf);
2441 ME_DumpStyleToBuf(&chf, buf);
2442 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2444 if (nKey == 'Q')
2446 ME_CheckCharOffsets(editor);
2450 return FALSE;
2453 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2454 LPARAM flags, BOOL unicode)
2456 WCHAR wstr;
2458 if (editor->bMouseCaptured)
2459 return 0;
2461 if (unicode)
2462 wstr = (WCHAR)charCode;
2463 else
2465 CHAR charA = charCode;
2466 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2469 if (editor->styleFlags & ES_READONLY) {
2470 MessageBeep(MB_ICONERROR);
2471 return 0; /* FIXME really 0 ? */
2474 if ((unsigned)wstr >= ' ' || wstr == '\t')
2476 ME_Cursor cursor = editor->pCursors[0];
2477 ME_DisplayItem *para = cursor.pPara;
2478 int from, to;
2479 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2480 ME_GetSelectionOfs(editor, &from, &to);
2481 if (wstr == '\t' &&
2482 /* v4.1 allows tabs to be inserted with ctrl key down */
2483 !(ctrl_is_down && !editor->bEmulateVersion10))
2485 ME_DisplayItem *para;
2486 BOOL bSelectedRow = FALSE;
2488 para = cursor.pPara;
2489 if (ME_IsSelection(editor) &&
2490 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2491 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2492 para->member.para.prev_para->type == diParagraph)
2494 para = para->member.para.prev_para;
2495 bSelectedRow = TRUE;
2497 if (ME_IsInTable(para))
2499 ME_TabPressedInTable(editor, bSelectedRow);
2500 ME_CommitUndo(editor);
2501 return 0;
2503 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2504 if (para->member.para.nFlags & MEPF_ROWEND) {
2505 if (from == to) {
2506 para = para->member.para.next_para;
2507 if (para->member.para.nFlags & MEPF_ROWSTART)
2508 para = para->member.para.next_para;
2509 editor->pCursors[0].pPara = para;
2510 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2511 editor->pCursors[0].nOffset = 0;
2512 editor->pCursors[1] = editor->pCursors[0];
2515 } else { /* v1.0 - 3.0 */
2516 if (ME_IsInTable(cursor.pRun) &&
2517 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2518 from == to)
2520 /* Text should not be inserted at the end of the table. */
2521 MessageBeep(-1);
2522 return 0;
2525 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2526 /* WM_CHAR is restricted to nTextLimit */
2527 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2529 ME_Style *style = ME_GetInsertStyle(editor, 0);
2530 ME_SaveTempStyle(editor);
2531 ME_ContinueCoalescingTransaction(editor);
2532 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2533 ME_ReleaseStyle(style);
2534 ME_CommitCoalescingUndo(editor);
2535 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2538 ME_UpdateSelectionLinkAttribute(editor);
2539 ME_UpdateRepaint(editor, FALSE);
2541 return 0;
2544 /* Process the message and calculate the new click count.
2546 * returns: The click count if it is mouse down event, else returns 0. */
2547 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2548 LPARAM lParam)
2550 static int clickNum = 0;
2551 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2552 return 0;
2554 if ((msg == WM_LBUTTONDBLCLK) ||
2555 (msg == WM_RBUTTONDBLCLK) ||
2556 (msg == WM_MBUTTONDBLCLK) ||
2557 (msg == WM_XBUTTONDBLCLK))
2559 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2562 if ((msg == WM_LBUTTONDOWN) ||
2563 (msg == WM_RBUTTONDOWN) ||
2564 (msg == WM_MBUTTONDOWN) ||
2565 (msg == WM_XBUTTONDOWN))
2567 static MSG prevClickMsg;
2568 MSG clickMsg;
2569 /* Compare the editor instead of the hwnd so that the this
2570 * can still be done for windowless richedit controls. */
2571 clickMsg.hwnd = (HWND)editor;
2572 clickMsg.message = msg;
2573 clickMsg.wParam = wParam;
2574 clickMsg.lParam = lParam;
2575 clickMsg.time = GetMessageTime();
2576 clickMsg.pt.x = (short)LOWORD(lParam);
2577 clickMsg.pt.y = (short)HIWORD(lParam);
2578 if ((clickNum != 0) &&
2579 (clickMsg.message == prevClickMsg.message) &&
2580 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2581 (clickMsg.wParam == prevClickMsg.wParam) &&
2582 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2583 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2584 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2586 clickNum++;
2587 } else {
2588 clickNum = 1;
2590 prevClickMsg = clickMsg;
2591 } else {
2592 return 0;
2594 return clickNum;
2597 static BOOL ME_SetCursor(ME_TextEditor *editor)
2599 ME_Cursor cursor;
2600 POINT pt;
2601 BOOL isExact;
2602 SCROLLBARINFO sbi;
2603 DWORD messagePos = GetMessagePos();
2604 pt.x = (short)LOWORD(messagePos);
2605 pt.y = (short)HIWORD(messagePos);
2607 if (editor->hWnd)
2609 sbi.cbSize = sizeof(sbi);
2610 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2611 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2612 PtInRect(&sbi.rcScrollBar, pt))
2614 ITextHost_TxSetCursor(editor->texthost,
2615 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2616 return TRUE;
2618 sbi.cbSize = sizeof(sbi);
2619 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2620 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2621 PtInRect(&sbi.rcScrollBar, pt))
2623 ITextHost_TxSetCursor(editor->texthost,
2624 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2625 return TRUE;
2628 ITextHost_TxScreenToClient(editor->texthost, &pt);
2630 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2631 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2632 return TRUE;
2634 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2635 pt.y < editor->rcFormat.top &&
2636 pt.x < editor->rcFormat.left)
2638 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2639 return TRUE;
2641 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2643 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2644 ITextHost_TxSetCursor(editor->texthost,
2645 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2646 else /* v4.1 */
2647 ITextHost_TxSetCursor(editor->texthost,
2648 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2649 return TRUE;
2651 if (pt.x < editor->rcFormat.left)
2653 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2654 return TRUE;
2656 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2657 if (isExact)
2659 ME_Run *run;
2661 run = &cursor.pRun->member.run;
2662 if (run->style->fmt.dwMask & CFM_LINK &&
2663 run->style->fmt.dwEffects & CFE_LINK)
2665 ITextHost_TxSetCursor(editor->texthost,
2666 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2667 FALSE);
2668 return TRUE;
2671 if (ME_IsSelection(editor))
2673 int selStart, selEnd;
2674 int offset = ME_GetCursorOfs(&cursor);
2676 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2677 if (selStart <= offset && selEnd >= offset) {
2678 ITextHost_TxSetCursor(editor->texthost,
2679 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2680 FALSE);
2681 return TRUE;
2685 ITextHost_TxSetCursor(editor->texthost,
2686 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2687 return TRUE;
2690 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2692 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2693 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2694 editor->rcFormat.left += 1 + editor->selofs;
2695 editor->rcFormat.right -= 1;
2698 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2700 CHARRANGE selrange;
2701 HMENU menu;
2702 int seltype = 0;
2703 if(!editor->lpOleCallback || !editor->hWnd)
2704 return FALSE;
2705 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2706 if(selrange.cpMin == selrange.cpMax)
2707 seltype |= SEL_EMPTY;
2708 else
2710 /* FIXME: Handle objects */
2711 seltype |= SEL_TEXT;
2712 if(selrange.cpMax-selrange.cpMin > 1)
2713 seltype |= SEL_MULTICHAR;
2715 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2717 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2718 DestroyMenu(menu);
2720 return TRUE;
2723 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2725 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2726 int i;
2727 DWORD props;
2728 LONG selbarwidth;
2730 ed->hWnd = NULL;
2731 ed->hwndParent = NULL;
2732 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2733 ed->texthost = texthost;
2734 ed->bEmulateVersion10 = bEmulateVersion10;
2735 ed->styleFlags = 0;
2736 ITextHost_TxGetPropertyBits(texthost,
2737 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2738 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2739 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2740 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2741 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2742 &props);
2743 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2744 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2745 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2746 ed->pBuffer = ME_MakeText();
2747 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2748 ed->nAvailWidth = 0; /* wrap to client area */
2749 ME_MakeFirstParagraph(ed);
2750 /* The four cursors are for:
2751 * 0 - The position where the caret is shown
2752 * 1 - The anchored end of the selection (for normal selection)
2753 * 2 & 3 - The anchored start and end respectively for word, line,
2754 * or paragraph selection.
2756 ed->nCursors = 4;
2757 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2758 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2759 ed->pCursors[1] = ed->pCursors[0];
2760 ed->pCursors[2] = ed->pCursors[0];
2761 ed->pCursors[3] = ed->pCursors[1];
2762 ed->nLastTotalLength = ed->nTotalLength = 0;
2763 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2764 ed->nUDArrowX = -1;
2765 ed->rgbBackColor = -1;
2766 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2767 ed->bCaretAtEnd = FALSE;
2768 ed->nEventMask = 0;
2769 ed->nModifyStep = 0;
2770 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2771 list_init( &ed->undo_stack );
2772 list_init( &ed->redo_stack );
2773 ed->nUndoStackSize = 0;
2774 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2775 ed->nUndoMode = umAddToUndo;
2776 ed->nParagraphs = 1;
2777 ed->nLastSelStart = ed->nLastSelEnd = 0;
2778 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2779 ed->bHideSelection = FALSE;
2780 ed->pfnWordBreak = NULL;
2781 ed->lpOleCallback = NULL;
2782 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2783 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2784 ed->AutoURLDetect_bEnable = FALSE;
2785 ed->bHaveFocus = FALSE;
2786 ed->bDialogMode = FALSE;
2787 ed->bMouseCaptured = FALSE;
2788 for (i=0; i<HFONT_CACHE_SIZE; i++)
2790 ed->pFontCache[i].nRefs = 0;
2791 ed->pFontCache[i].nAge = 0;
2792 ed->pFontCache[i].hFont = NULL;
2795 ME_CheckCharOffsets(ed);
2796 ed->bDefaultFormatRect = TRUE;
2797 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2798 if (selbarwidth) {
2799 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2800 ed->selofs = SELECTIONBAR_WIDTH;
2801 ed->styleFlags |= ES_SELECTIONBAR;
2802 } else {
2803 ed->selofs = 0;
2805 ed->nSelectionType = stPosition;
2807 ed->cPasswordMask = 0;
2808 if (props & TXTBIT_USEPASSWORD)
2809 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2811 if (props & TXTBIT_AUTOWORDSEL)
2812 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2813 if (props & TXTBIT_MULTILINE) {
2814 ed->styleFlags |= ES_MULTILINE;
2815 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2816 } else {
2817 ed->bWordWrap = FALSE;
2819 if (props & TXTBIT_READONLY)
2820 ed->styleFlags |= ES_READONLY;
2821 if (!(props & TXTBIT_HIDESELECTION))
2822 ed->styleFlags |= ES_NOHIDESEL;
2823 if (props & TXTBIT_SAVESELECTION)
2824 ed->styleFlags |= ES_SAVESEL;
2825 if (props & TXTBIT_VERTICAL)
2826 ed->styleFlags |= ES_VERTICAL;
2827 if (props & TXTBIT_DISABLEDRAG)
2828 ed->styleFlags |= ES_NOOLEDRAGDROP;
2830 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2832 /* Default scrollbar information */
2833 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2834 ed->vert_si.nMin = 0;
2835 ed->vert_si.nMax = 0;
2836 ed->vert_si.nPage = 0;
2837 ed->vert_si.nPos = 0;
2839 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2840 ed->horz_si.nMin = 0;
2841 ed->horz_si.nMax = 0;
2842 ed->horz_si.nPage = 0;
2843 ed->horz_si.nPos = 0;
2845 OleInitialize(NULL);
2847 return ed;
2850 static void ME_DestroyEditor(ME_TextEditor *editor)
2852 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2853 ME_DisplayItem *p = pFirst, *pNext = NULL;
2854 int i;
2856 ME_ClearTempStyle(editor);
2857 ME_EmptyUndoStack(editor);
2858 while(p) {
2859 pNext = p->next;
2860 ME_DestroyDisplayItem(p);
2861 p = pNext;
2863 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2864 for (i=0; i<HFONT_CACHE_SIZE; i++)
2866 if (editor->pFontCache[i].hFont)
2867 DeleteObject(editor->pFontCache[i].hFont);
2869 if (editor->rgbBackColor != -1)
2870 DeleteObject(editor->hbrBackground);
2871 if(editor->lpOleCallback)
2872 IRichEditOleCallback_Release(editor->lpOleCallback);
2873 ITextHost_Release(editor->texthost);
2874 OleUninitialize();
2876 FREE_OBJ(editor->pBuffer);
2877 FREE_OBJ(editor->pCursors);
2879 FREE_OBJ(editor);
2882 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2884 TRACE("\n");
2885 switch (fdwReason)
2887 case DLL_PROCESS_ATTACH:
2888 DisableThreadLibraryCalls(hinstDLL);
2889 me_heap = HeapCreate (0, 0x10000, 0);
2890 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2891 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2892 LookupInit();
2893 break;
2895 case DLL_PROCESS_DETACH:
2896 if (lpvReserved) break;
2897 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2898 UnregisterClassW(MSFTEDIT_CLASS, 0);
2899 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2900 UnregisterClassA("RichEdit50A", 0);
2901 if (ME_ListBoxRegistered)
2902 UnregisterClassW(REListBox20W, 0);
2903 if (ME_ComboBoxRegistered)
2904 UnregisterClassW(REComboBox20W, 0);
2905 LookupCleanup();
2906 HeapDestroy (me_heap);
2907 break;
2909 return TRUE;
2913 static const char * const edit_messages[] = {
2914 "EM_GETSEL",
2915 "EM_SETSEL",
2916 "EM_GETRECT",
2917 "EM_SETRECT",
2918 "EM_SETRECTNP",
2919 "EM_SCROLL",
2920 "EM_LINESCROLL",
2921 "EM_SCROLLCARET",
2922 "EM_GETMODIFY",
2923 "EM_SETMODIFY",
2924 "EM_GETLINECOUNT",
2925 "EM_LINEINDEX",
2926 "EM_SETHANDLE",
2927 "EM_GETHANDLE",
2928 "EM_GETTHUMB",
2929 "EM_UNKNOWN_BF",
2930 "EM_UNKNOWN_C0",
2931 "EM_LINELENGTH",
2932 "EM_REPLACESEL",
2933 "EM_UNKNOWN_C3",
2934 "EM_GETLINE",
2935 "EM_LIMITTEXT",
2936 "EM_CANUNDO",
2937 "EM_UNDO",
2938 "EM_FMTLINES",
2939 "EM_LINEFROMCHAR",
2940 "EM_UNKNOWN_CA",
2941 "EM_SETTABSTOPS",
2942 "EM_SETPASSWORDCHAR",
2943 "EM_EMPTYUNDOBUFFER",
2944 "EM_GETFIRSTVISIBLELINE",
2945 "EM_SETREADONLY",
2946 "EM_SETWORDBREAKPROC",
2947 "EM_GETWORDBREAKPROC",
2948 "EM_GETPASSWORDCHAR",
2949 "EM_SETMARGINS",
2950 "EM_GETMARGINS",
2951 "EM_GETLIMITTEXT",
2952 "EM_POSFROMCHAR",
2953 "EM_CHARFROMPOS",
2954 "EM_SETIMESTATUS",
2955 "EM_GETIMESTATUS"
2958 static const char * const richedit_messages[] = {
2959 "EM_CANPASTE",
2960 "EM_DISPLAYBAND",
2961 "EM_EXGETSEL",
2962 "EM_EXLIMITTEXT",
2963 "EM_EXLINEFROMCHAR",
2964 "EM_EXSETSEL",
2965 "EM_FINDTEXT",
2966 "EM_FORMATRANGE",
2967 "EM_GETCHARFORMAT",
2968 "EM_GETEVENTMASK",
2969 "EM_GETOLEINTERFACE",
2970 "EM_GETPARAFORMAT",
2971 "EM_GETSELTEXT",
2972 "EM_HIDESELECTION",
2973 "EM_PASTESPECIAL",
2974 "EM_REQUESTRESIZE",
2975 "EM_SELECTIONTYPE",
2976 "EM_SETBKGNDCOLOR",
2977 "EM_SETCHARFORMAT",
2978 "EM_SETEVENTMASK",
2979 "EM_SETOLECALLBACK",
2980 "EM_SETPARAFORMAT",
2981 "EM_SETTARGETDEVICE",
2982 "EM_STREAMIN",
2983 "EM_STREAMOUT",
2984 "EM_GETTEXTRANGE",
2985 "EM_FINDWORDBREAK",
2986 "EM_SETOPTIONS",
2987 "EM_GETOPTIONS",
2988 "EM_FINDTEXTEX",
2989 "EM_GETWORDBREAKPROCEX",
2990 "EM_SETWORDBREAKPROCEX",
2991 "EM_SETUNDOLIMIT",
2992 "EM_UNKNOWN_USER_83",
2993 "EM_REDO",
2994 "EM_CANREDO",
2995 "EM_GETUNDONAME",
2996 "EM_GETREDONAME",
2997 "EM_STOPGROUPTYPING",
2998 "EM_SETTEXTMODE",
2999 "EM_GETTEXTMODE",
3000 "EM_AUTOURLDETECT",
3001 "EM_GETAUTOURLDETECT",
3002 "EM_SETPALETTE",
3003 "EM_GETTEXTEX",
3004 "EM_GETTEXTLENGTHEX",
3005 "EM_SHOWSCROLLBAR",
3006 "EM_SETTEXTEX",
3007 "EM_UNKNOWN_USER_98",
3008 "EM_UNKNOWN_USER_99",
3009 "EM_SETPUNCTUATION",
3010 "EM_GETPUNCTUATION",
3011 "EM_SETWORDWRAPMODE",
3012 "EM_GETWORDWRAPMODE",
3013 "EM_SETIMECOLOR",
3014 "EM_GETIMECOLOR",
3015 "EM_SETIMEOPTIONS",
3016 "EM_GETIMEOPTIONS",
3017 "EM_CONVPOSITION",
3018 "EM_UNKNOWN_USER_109",
3019 "EM_UNKNOWN_USER_110",
3020 "EM_UNKNOWN_USER_111",
3021 "EM_UNKNOWN_USER_112",
3022 "EM_UNKNOWN_USER_113",
3023 "EM_UNKNOWN_USER_114",
3024 "EM_UNKNOWN_USER_115",
3025 "EM_UNKNOWN_USER_116",
3026 "EM_UNKNOWN_USER_117",
3027 "EM_UNKNOWN_USER_118",
3028 "EM_UNKNOWN_USER_119",
3029 "EM_SETLANGOPTIONS",
3030 "EM_GETLANGOPTIONS",
3031 "EM_GETIMECOMPMODE",
3032 "EM_FINDTEXTW",
3033 "EM_FINDTEXTEXW",
3034 "EM_RECONVERSION",
3035 "EM_SETIMEMODEBIAS",
3036 "EM_GETIMEMODEBIAS"
3039 static const char *
3040 get_msg_name(UINT msg)
3042 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3043 return edit_messages[msg - EM_GETSEL];
3044 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3045 return richedit_messages[msg - EM_CANPASTE];
3046 return "";
3049 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3051 int x,y;
3052 BOOL isExact;
3053 ME_Cursor cursor; /* The start of the clicked text. */
3055 ENLINK info;
3056 x = (short)LOWORD(lParam);
3057 y = (short)HIWORD(lParam);
3058 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3059 if (!isExact) return;
3061 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3062 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3063 { /* The clicked run has CFE_LINK set */
3064 info.nmhdr.hwndFrom = NULL;
3065 info.nmhdr.idFrom = 0;
3066 info.nmhdr.code = EN_LINK;
3067 info.msg = msg;
3068 info.wParam = wParam;
3069 info.lParam = lParam;
3070 cursor.nOffset = 0;
3071 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3072 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3073 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3077 #define UNSUPPORTED_MSG(e) \
3078 case e: \
3079 FIXME(#e ": stub\n"); \
3080 *phresult = S_FALSE; \
3081 return 0;
3083 /* Handle messages for windowless and windoweded richedit controls.
3085 * The LRESULT that is returned is a return value for window procs,
3086 * and the phresult parameter is the COM return code needed by the
3087 * text services interface. */
3088 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3089 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3091 *phresult = S_OK;
3093 switch(msg) {
3095 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3096 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3097 UNSUPPORTED_MSG(EM_FMTLINES)
3098 UNSUPPORTED_MSG(EM_FORMATRANGE)
3099 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3100 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3101 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3102 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3103 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3104 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3105 UNSUPPORTED_MSG(EM_GETREDONAME)
3106 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3107 UNSUPPORTED_MSG(EM_GETUNDONAME)
3108 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3109 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3110 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3111 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3112 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3113 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3114 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3115 UNSUPPORTED_MSG(EM_SETMARGINS)
3116 UNSUPPORTED_MSG(EM_SETPALETTE)
3117 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3118 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3119 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3121 /* Messages specific to Richedit controls */
3123 case EM_STREAMIN:
3124 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3125 case EM_STREAMOUT:
3126 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3127 case WM_GETDLGCODE:
3129 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3130 if (lParam)
3131 editor->bDialogMode = TRUE;
3132 if (editor->styleFlags & ES_MULTILINE)
3133 code |= DLGC_WANTMESSAGE;
3134 return code;
3136 case EM_EMPTYUNDOBUFFER:
3137 ME_EmptyUndoStack(editor);
3138 return 0;
3139 case EM_GETSEL:
3141 /* Note: wParam/lParam can be NULL */
3142 UINT from, to;
3143 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3144 PUINT pto = lParam ? (PUINT)lParam : &to;
3145 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3146 if ((*pfrom|*pto) & 0xFFFF0000)
3147 return -1;
3148 return MAKELONG(*pfrom,*pto);
3150 case EM_EXGETSEL:
3152 CHARRANGE *pRange = (CHARRANGE *)lParam;
3153 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3154 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3155 return 0;
3157 case EM_SETUNDOLIMIT:
3159 if ((int)wParam < 0)
3160 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3161 else
3162 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3163 /* Setting a max stack size keeps wine from getting killed
3164 for hogging memory. Windows allocates all this memory at once, so
3165 no program would realistically set a value above our maximum. */
3166 return editor->nUndoLimit;
3168 case EM_CANUNDO:
3169 return !list_empty( &editor->undo_stack );
3170 case EM_CANREDO:
3171 return !list_empty( &editor->redo_stack );
3172 case WM_UNDO: /* FIXME: actually not the same */
3173 case EM_UNDO:
3174 return ME_Undo(editor);
3175 case EM_REDO:
3176 return ME_Redo(editor);
3177 case EM_GETOPTIONS:
3179 /* these flags are equivalent to the ES_* counterparts */
3180 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3181 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3182 DWORD settings = editor->styleFlags & mask;
3184 return settings;
3186 case EM_SETOPTIONS:
3188 /* these flags are equivalent to ES_* counterparts, except for
3189 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3190 * but is still stored in editor->styleFlags. */
3191 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3192 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3193 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3194 DWORD settings = mask & editor->styleFlags;
3195 DWORD oldSettings = settings;
3196 DWORD changedSettings;
3198 switch(wParam)
3200 case ECOOP_SET:
3201 settings = lParam;
3202 break;
3203 case ECOOP_OR:
3204 settings |= lParam;
3205 break;
3206 case ECOOP_AND:
3207 settings &= lParam;
3208 break;
3209 case ECOOP_XOR:
3210 settings ^= lParam;
3212 changedSettings = oldSettings ^ settings;
3214 if (changedSettings) {
3215 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3217 if (changedSettings & ECO_SELECTIONBAR)
3219 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3220 if (settings & ECO_SELECTIONBAR) {
3221 assert(!editor->selofs);
3222 editor->selofs = SELECTIONBAR_WIDTH;
3223 editor->rcFormat.left += editor->selofs;
3224 } else {
3225 editor->rcFormat.left -= editor->selofs;
3226 editor->selofs = 0;
3228 ME_RewrapRepaint(editor);
3231 if (changedSettings & settings & ECO_VERTICAL)
3232 FIXME("ECO_VERTICAL not implemented yet!\n");
3233 if (changedSettings & settings & ECO_AUTOHSCROLL)
3234 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3235 if (changedSettings & settings & ECO_AUTOVSCROLL)
3236 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3237 if (changedSettings & settings & ECO_NOHIDESEL)
3238 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3239 if (changedSettings & settings & ECO_WANTRETURN)
3240 FIXME("ECO_WANTRETURN not implemented yet!\n");
3241 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3242 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3245 return settings;
3247 case EM_SETSEL:
3249 ME_InvalidateSelection(editor);
3250 ME_SetSelection(editor, wParam, lParam);
3251 ME_InvalidateSelection(editor);
3252 ITextHost_TxShowCaret(editor->texthost, FALSE);
3253 ME_ShowCaret(editor);
3254 ME_SendSelChange(editor);
3255 return 0;
3257 case EM_SETSCROLLPOS:
3259 POINT *point = (POINT *)lParam;
3260 ME_ScrollAbs(editor, point->x, point->y);
3261 return 0;
3263 case EM_AUTOURLDETECT:
3265 if (wParam==1 || wParam ==0)
3267 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3268 return 0;
3270 return E_INVALIDARG;
3272 case EM_GETAUTOURLDETECT:
3274 return editor->AutoURLDetect_bEnable;
3276 case EM_EXSETSEL:
3278 int end;
3279 CHARRANGE range = *(CHARRANGE *)lParam;
3281 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3283 ME_InvalidateSelection(editor);
3284 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3285 ME_InvalidateSelection(editor);
3286 ITextHost_TxShowCaret(editor->texthost, FALSE);
3287 ME_ShowCaret(editor);
3288 ME_SendSelChange(editor);
3290 return end;
3292 case EM_SHOWSCROLLBAR:
3294 DWORD flags;
3296 switch (wParam)
3298 case SB_HORZ:
3299 flags = WS_HSCROLL;
3300 break;
3301 case SB_VERT:
3302 flags = WS_VSCROLL;
3303 break;
3304 case SB_BOTH:
3305 flags = WS_HSCROLL|WS_VSCROLL;
3306 break;
3307 default:
3308 return 0;
3311 if (lParam) {
3312 editor->styleFlags |= flags;
3313 if (flags & WS_HSCROLL)
3314 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3315 editor->nTotalWidth > editor->sizeWindow.cx);
3316 if (flags & WS_VSCROLL)
3317 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3318 editor->nTotalLength > editor->sizeWindow.cy);
3319 } else {
3320 editor->styleFlags &= ~flags;
3321 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3323 return 0;
3325 case EM_SETTEXTEX:
3327 LPWSTR wszText;
3328 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3329 int from, to, len;
3330 ME_Style *style;
3331 BOOL bRtf, bUnicode, bSelection;
3332 int oldModify = editor->nModifyStep;
3334 if (!pStruct) return 0;
3336 /* If we detect ascii rtf at the start of the string,
3337 * we know it isn't unicode. */
3338 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3339 !strncmp((char *)lParam, "{\\urtf", 6)));
3340 bUnicode = !bRtf && pStruct->codepage == 1200;
3342 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3343 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3344 pStruct->flags, pStruct->codepage);
3346 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3347 if (bSelection) {
3348 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3349 style = ME_GetSelectionInsertStyle(editor);
3350 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3351 } else {
3352 ME_Cursor start;
3353 ME_SetCursorToStart(editor, &start);
3354 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3355 style = editor->pBuffer->pDefaultStyle;
3358 if (bRtf) {
3359 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3360 if (bSelection) {
3361 /* FIXME: The length returned doesn't include the rtf control
3362 * characters, only the actual text. */
3363 len = lParam ? strlen((char *)lParam) : 0;
3365 } else {
3366 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3367 wszText = ME_ToUnicode(bUnicode, (void *)lParam, &len);
3368 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3369 ME_EndToUnicode(bUnicode, wszText);
3372 if (bSelection) {
3373 ME_ReleaseStyle(style);
3374 ME_UpdateSelectionLinkAttribute(editor);
3375 } else {
3376 ME_Cursor cursor;
3377 len = 1;
3378 ME_SetCursorToStart(editor, &cursor);
3379 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3381 ME_CommitUndo(editor);
3382 if (!(pStruct->flags & ST_KEEPUNDO))
3384 editor->nModifyStep = oldModify;
3385 ME_EmptyUndoStack(editor);
3387 ME_UpdateRepaint(editor, FALSE);
3388 return len;
3390 case EM_SETBKGNDCOLOR:
3392 LRESULT lColor;
3393 if (editor->rgbBackColor != -1) {
3394 DeleteObject(editor->hbrBackground);
3395 lColor = editor->rgbBackColor;
3397 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3399 if (wParam)
3401 editor->rgbBackColor = -1;
3402 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3404 else
3406 editor->rgbBackColor = lParam;
3407 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3409 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3410 ITextHost_TxViewChange(editor->texthost, TRUE);
3411 return lColor;
3413 case EM_GETMODIFY:
3414 return editor->nModifyStep == 0 ? 0 : -1;
3415 case EM_SETMODIFY:
3417 if (wParam)
3418 editor->nModifyStep = 1;
3419 else
3420 editor->nModifyStep = 0;
3422 return 0;
3424 case EM_SETREADONLY:
3426 if (wParam)
3427 editor->styleFlags |= ES_READONLY;
3428 else
3429 editor->styleFlags &= ~ES_READONLY;
3430 return 0;
3432 case EM_SETEVENTMASK:
3434 DWORD nOldMask = editor->nEventMask;
3436 editor->nEventMask = lParam;
3437 return nOldMask;
3439 case EM_GETEVENTMASK:
3440 return editor->nEventMask;
3441 case EM_SETCHARFORMAT:
3443 CHARFORMAT2W buf, *p;
3444 BOOL bRepaint = TRUE;
3445 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3446 if (p == NULL) return 0;
3447 if (wParam & SCF_ALL) {
3448 if (editor->mode & TM_PLAINTEXT) {
3449 ME_SetDefaultCharFormat(editor, p);
3450 } else {
3451 ME_Cursor start;
3452 ME_SetCursorToStart(editor, &start);
3453 ME_SetCharFormat(editor, &start, NULL, p);
3454 editor->nModifyStep = 1;
3456 } else if (wParam & SCF_SELECTION) {
3457 if (editor->mode & TM_PLAINTEXT)
3458 return 0;
3459 if (wParam & SCF_WORD) {
3460 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3461 return 0;
3463 bRepaint = ME_IsSelection(editor);
3464 ME_SetSelectionCharFormat(editor, p);
3465 if (bRepaint) editor->nModifyStep = 1;
3466 } else { /* SCF_DEFAULT */
3467 ME_SetDefaultCharFormat(editor, p);
3469 ME_CommitUndo(editor);
3470 if (bRepaint)
3472 ME_WrapMarkedParagraphs(editor);
3473 ME_UpdateScrollBar(editor);
3474 ME_Repaint(editor);
3476 return 1;
3478 case EM_GETCHARFORMAT:
3480 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3481 if (dst->cbSize != sizeof(CHARFORMATA) &&
3482 dst->cbSize != sizeof(CHARFORMATW) &&
3483 dst->cbSize != sizeof(CHARFORMAT2A) &&
3484 dst->cbSize != sizeof(CHARFORMAT2W))
3485 return 0;
3486 tmp.cbSize = sizeof(tmp);
3487 if (!wParam)
3488 ME_GetDefaultCharFormat(editor, &tmp);
3489 else
3490 ME_GetSelectionCharFormat(editor, &tmp);
3491 ME_CopyToCFAny(dst, &tmp);
3492 return tmp.dwMask;
3494 case EM_SETPARAFORMAT:
3496 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3497 ME_WrapMarkedParagraphs(editor);
3498 ME_UpdateScrollBar(editor);
3499 ME_Repaint(editor);
3500 ME_CommitUndo(editor);
3501 return result;
3503 case EM_GETPARAFORMAT:
3504 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3505 return ((PARAFORMAT2 *)lParam)->dwMask;
3506 case EM_GETFIRSTVISIBLELINE:
3508 ME_DisplayItem *p = editor->pBuffer->pFirst;
3509 int y = editor->vert_si.nPos;
3510 int ypara = 0;
3511 int count = 0;
3512 int ystart, yend;
3513 while(p) {
3514 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3515 if (p->type == diTextEnd)
3516 break;
3517 if (p->type == diParagraph) {
3518 ypara = p->member.para.pt.y;
3519 continue;
3521 ystart = ypara + p->member.row.pt.y;
3522 yend = ystart + p->member.row.nHeight;
3523 if (y < yend) {
3524 break;
3526 count++;
3528 return count;
3530 case EM_HIDESELECTION:
3532 editor->bHideSelection = (wParam != 0);
3533 ME_InvalidateSelection(editor);
3534 return 0;
3536 case EM_LINESCROLL:
3538 if (!(editor->styleFlags & ES_MULTILINE))
3539 return FALSE;
3540 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3541 return TRUE;
3543 case WM_CLEAR:
3545 int from, to;
3546 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3547 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3548 ME_CommitUndo(editor);
3549 ME_UpdateRepaint(editor, TRUE);
3550 return 0;
3552 case EM_REPLACESEL:
3554 int from, to, nStartCursor;
3555 ME_Style *style;
3556 int len = 0;
3557 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam, &len);
3558 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3560 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3561 style = ME_GetSelectionInsertStyle(editor);
3562 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3563 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3564 ME_ReleaseStyle(style);
3565 /* drop temporary style if line end */
3567 * FIXME question: does abc\n mean: put abc,
3568 * clear temp style, put \n? (would require a change)
3570 if (len>0 && wszText[len-1] == '\n')
3571 ME_ClearTempStyle(editor);
3572 ME_EndToUnicode(unicode, wszText);
3573 ME_CommitUndo(editor);
3574 ME_UpdateSelectionLinkAttribute(editor);
3575 if (!wParam)
3576 ME_EmptyUndoStack(editor);
3577 ME_UpdateRepaint(editor, FALSE);
3578 return len;
3580 case EM_SCROLLCARET:
3581 ME_EnsureVisible(editor, &editor->pCursors[0]);
3582 return 0;
3583 case WM_SETFONT:
3585 LOGFONTW lf;
3586 CHARFORMAT2W fmt;
3587 HDC hDC;
3588 BOOL bRepaint = LOWORD(lParam);
3590 if (!wParam)
3591 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3592 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3593 hDC = ITextHost_TxGetDC(editor->texthost);
3594 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3595 ITextHost_TxReleaseDC(editor->texthost, hDC);
3596 if (editor->mode & TM_RICHTEXT) {
3597 ME_Cursor start;
3598 ME_SetCursorToStart(editor, &start);
3599 ME_SetCharFormat(editor, &start, NULL, &fmt);
3601 ME_SetDefaultCharFormat(editor, &fmt);
3603 ME_CommitUndo(editor);
3604 ME_MarkAllForWrapping(editor);
3605 ME_WrapMarkedParagraphs(editor);
3606 ME_UpdateScrollBar(editor);
3607 if (bRepaint)
3608 ME_Repaint(editor);
3609 return 0;
3611 case WM_SETTEXT:
3613 ME_Cursor cursor;
3614 ME_SetCursorToStart(editor, &cursor);
3615 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3616 if (lParam)
3618 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3619 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3620 !strncmp((char *)lParam, "{\\urtf", 6))
3622 /* Undocumented: WM_SETTEXT supports RTF text */
3623 ME_StreamInRTFString(editor, 0, (char *)lParam);
3625 else
3627 int textLen;
3628 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam, &textLen);
3629 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3630 if (textLen > 0)
3632 int len = -1;
3634 /* uses default style! */
3635 if (!(editor->styleFlags & ES_MULTILINE))
3637 WCHAR * p;
3639 p = wszText;
3640 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3641 len = p - wszText;
3643 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3645 ME_EndToUnicode(unicode, wszText);
3648 else
3649 TRACE("WM_SETTEXT - NULL\n");
3650 ME_SetCursorToStart(editor, &cursor);
3651 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3652 ME_SetSelection(editor, 0, 0);
3653 editor->nModifyStep = 0;
3654 ME_CommitUndo(editor);
3655 ME_EmptyUndoStack(editor);
3656 ME_UpdateRepaint(editor, FALSE);
3657 return 1;
3659 case EM_CANPASTE:
3661 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3662 if (IsClipboardFormatAvailable(nRTFFormat))
3663 return TRUE;
3664 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3665 return TRUE;
3666 return FALSE;
3668 case WM_PASTE:
3669 case WM_MBUTTONDOWN:
3670 ME_Paste(editor);
3671 return 0;
3672 case WM_CUT:
3673 case WM_COPY:
3675 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3676 int nChars = nTo - nFrom;
3677 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3679 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3681 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3682 ME_CommitUndo(editor);
3683 ME_UpdateRepaint(editor, TRUE);
3685 return 0;
3687 case WM_GETTEXTLENGTH:
3689 GETTEXTLENGTHEX how;
3691 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3692 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3693 how.codepage = unicode ? 1200 : CP_ACP;
3694 return ME_GetTextLengthEx(editor, &how);
3696 case EM_GETTEXTLENGTHEX:
3697 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3698 case WM_GETTEXT:
3700 GETTEXTEX ex;
3701 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3702 ex.flags = GT_USECRLF;
3703 ex.codepage = unicode ? 1200 : CP_ACP;
3704 ex.lpDefaultChar = NULL;
3705 ex.lpUsedDefChar = NULL;
3706 return ME_GetTextEx(editor, &ex, lParam);
3708 case EM_GETTEXTEX:
3709 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3710 case EM_GETSELTEXT:
3712 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3713 ME_Cursor *from = &editor->pCursors[nStartCur];
3714 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3715 nTo - nFrom, unicode);
3717 case EM_GETSCROLLPOS:
3719 POINT *point = (POINT *)lParam;
3720 point->x = editor->horz_si.nPos;
3721 point->y = editor->vert_si.nPos;
3722 /* 16-bit scaled value is returned as stored in scrollinfo */
3723 if (editor->horz_si.nMax > 0xffff)
3724 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3725 if (editor->vert_si.nMax > 0xffff)
3726 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3727 return 1;
3729 case EM_GETTEXTRANGE:
3731 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3732 ME_Cursor start;
3733 int nStart = rng->chrg.cpMin;
3734 int nEnd = rng->chrg.cpMax;
3735 int textlength = ME_GetTextLength(editor);
3737 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3738 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3739 if (nStart < 0) return 0;
3740 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3741 nEnd = textlength;
3742 if (nStart >= nEnd) return 0;
3744 ME_CursorFromCharOfs(editor, nStart, &start);
3745 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3747 case EM_GETLINE:
3749 ME_DisplayItem *run;
3750 const unsigned int nMaxChars = *(WORD *) lParam;
3751 unsigned int nCharsLeft = nMaxChars;
3752 char *dest = (char *) lParam;
3753 BOOL wroteNull = FALSE;
3755 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3756 unicode ? "Unicode" : "Ansi");
3758 run = ME_FindRowWithNumber(editor, wParam);
3759 if (run == NULL)
3760 return 0;
3762 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3763 && run->type == diRun)
3765 WCHAR *str = get_text( &run->member.run, 0 );
3766 unsigned int nCopy;
3768 nCopy = min(nCharsLeft, run->member.run.len);
3770 if (unicode)
3771 memcpy(dest, str, nCopy * sizeof(WCHAR));
3772 else
3773 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3774 nCharsLeft, NULL, NULL);
3775 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3776 nCharsLeft -= nCopy;
3779 /* append line termination, space allowing */
3780 if (nCharsLeft > 0)
3782 if (unicode)
3783 *((WCHAR *)dest) = '\0';
3784 else
3785 *dest = '\0';
3786 nCharsLeft--;
3787 wroteNull = TRUE;
3790 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3791 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3793 case EM_GETLINECOUNT:
3795 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3796 int nRows = 0;
3798 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3800 while (item != editor->pBuffer->pLast)
3802 assert(item->type == diParagraph);
3803 prev_para = ME_FindItemBack(item, diRun);
3804 if (prev_para) {
3805 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3807 nRows += item->member.para.nRows;
3808 item = item->member.para.next_para;
3810 last_para = ME_FindItemBack(item, diRun);
3811 assert(last_para);
3812 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3813 if (editor->bEmulateVersion10 && prev_para &&
3814 last_para->member.run.nCharOfs == 0 &&
3815 prev_para->member.run.len == 1 &&
3816 *get_text( &prev_para->member.run, 0 ) == '\r')
3818 /* In 1.0 emulation, the last solitary \r at the very end of the text
3819 (if one exists) is NOT a line break.
3820 FIXME: this is an ugly hack. This should have a more regular model. */
3821 nRows--;
3824 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3825 return max(1, nRows);
3827 case EM_LINEFROMCHAR:
3829 if (wParam == -1)
3830 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3831 else
3832 return ME_RowNumberFromCharOfs(editor, wParam);
3834 case EM_EXLINEFROMCHAR:
3836 if (lParam == -1)
3837 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3838 else
3839 return ME_RowNumberFromCharOfs(editor, lParam);
3841 case EM_LINEINDEX:
3843 ME_DisplayItem *item, *para;
3844 int nCharOfs;
3846 if (wParam == -1)
3847 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3848 else
3849 item = ME_FindRowWithNumber(editor, wParam);
3850 if (!item)
3851 return -1;
3852 para = ME_GetParagraph(item);
3853 item = ME_FindItemFwd(item, diRun);
3854 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3855 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3856 return nCharOfs;
3858 case EM_LINELENGTH:
3860 ME_DisplayItem *item, *item_end;
3861 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3862 ME_DisplayItem *para, *run;
3864 if (wParam > ME_GetTextLength(editor))
3865 return 0;
3866 if (wParam == -1)
3868 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3869 return 0;
3871 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3872 item = ME_RowStart(run);
3873 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3874 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3875 if (item_end->type == diStartRow) {
3876 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3877 } else {
3878 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3879 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3880 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3882 nChars = nNextLineOfs - nThisLineOfs;
3883 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3884 return nChars;
3886 case EM_EXLIMITTEXT:
3888 if ((int)lParam < 0)
3889 return 0;
3890 if (lParam == 0)
3891 editor->nTextLimit = 65536;
3892 else
3893 editor->nTextLimit = (int) lParam;
3894 return 0;
3896 case EM_LIMITTEXT:
3898 if (wParam == 0)
3899 editor->nTextLimit = 65536;
3900 else
3901 editor->nTextLimit = (int) wParam;
3902 return 0;
3904 case EM_GETLIMITTEXT:
3906 return editor->nTextLimit;
3908 case EM_FINDTEXT:
3910 LRESULT r;
3911 if(!unicode){
3912 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3913 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3914 WCHAR *tmp;
3916 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3917 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3918 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3919 FREE_OBJ( tmp );
3920 }else{
3921 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3922 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3924 return r;
3926 case EM_FINDTEXTEX:
3928 LRESULT r;
3929 if(!unicode){
3930 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3931 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3932 WCHAR *tmp;
3934 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3935 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3936 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3937 FREE_OBJ( tmp );
3938 }else{
3939 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3940 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3942 return r;
3944 case EM_FINDTEXTW:
3946 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3947 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3949 case EM_FINDTEXTEXW:
3951 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3952 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3954 case EM_GETZOOM:
3955 if (!wParam || !lParam)
3956 return FALSE;
3957 *(int *)wParam = editor->nZoomNumerator;
3958 *(int *)lParam = editor->nZoomDenominator;
3959 return TRUE;
3960 case EM_SETZOOM:
3961 return ME_SetZoom(editor, wParam, lParam);
3962 case EM_CHARFROMPOS:
3964 ME_Cursor cursor;
3965 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3966 &cursor, NULL))
3967 return ME_GetCursorOfs(&cursor);
3968 else
3969 return -1;
3971 case EM_POSFROMCHAR:
3973 ME_DisplayItem *pPara, *pRun;
3974 int nCharOfs, nOffset, nLength;
3975 POINTL pt = {0,0};
3977 nCharOfs = wParam;
3978 /* detect which API version we're dealing with */
3979 if (wParam >= 0x40000)
3980 nCharOfs = lParam;
3981 nLength = ME_GetTextLength(editor);
3982 nCharOfs = min(nCharOfs, nLength);
3983 nCharOfs = max(nCharOfs, 0);
3985 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3986 assert(pRun->type == diRun);
3987 pt.y = pRun->member.run.pt.y;
3988 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
3989 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3990 pt.x += editor->rcFormat.left;
3992 pt.x -= editor->horz_si.nPos;
3993 pt.y -= editor->vert_si.nPos;
3995 if (wParam >= 0x40000) {
3996 *(POINTL *)wParam = pt;
3998 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4000 case WM_CREATE:
4002 void *text = NULL;
4003 INT max;
4005 ME_SetDefaultFormatRect(editor);
4007 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4008 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4009 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4011 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4012 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4014 if (editor->styleFlags & ES_DISABLENOSCROLL)
4016 if (editor->styleFlags & WS_VSCROLL)
4018 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4019 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4021 if (editor->styleFlags & WS_HSCROLL)
4023 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4024 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4028 if (lParam)
4030 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4031 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4033 if (text)
4035 WCHAR *textW;
4036 int len;
4038 textW = ME_ToUnicode(unicode, text, &len);
4039 if (!(editor->styleFlags & ES_MULTILINE))
4041 len = 0;
4042 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4043 len++;
4045 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4046 ME_EndToUnicode(unicode, textW);
4047 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4048 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4051 ME_CommitUndo(editor);
4052 ME_WrapMarkedParagraphs(editor);
4053 ME_MoveCaret(editor);
4054 return 0;
4056 case WM_DESTROY:
4057 ME_DestroyEditor(editor);
4058 return 0;
4059 case WM_SETCURSOR:
4061 return ME_SetCursor(editor);
4063 case WM_LBUTTONDBLCLK:
4064 case WM_LBUTTONDOWN:
4066 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4067 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4068 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4069 return 0;
4070 ITextHost_TxSetFocus(editor->texthost);
4071 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4072 ME_CalculateClickCount(editor, msg, wParam, lParam));
4073 ITextHost_TxSetCapture(editor->texthost, TRUE);
4074 editor->bMouseCaptured = TRUE;
4075 ME_LinkNotify(editor,msg,wParam,lParam);
4076 if (!ME_SetCursor(editor)) goto do_default;
4077 break;
4079 case WM_MOUSEMOVE:
4080 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4081 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4082 return 0;
4083 if (editor->bMouseCaptured)
4084 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4085 ME_LinkNotify(editor,msg,wParam,lParam);
4086 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4087 if (editor->bMouseCaptured)
4088 ME_SetCursor(editor);
4089 break;
4090 case WM_LBUTTONUP:
4091 if (editor->bMouseCaptured) {
4092 ITextHost_TxSetCapture(editor->texthost, FALSE);
4093 editor->bMouseCaptured = FALSE;
4095 if (editor->nSelectionType == stDocument)
4096 editor->nSelectionType = stPosition;
4097 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4098 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4099 return 0;
4100 else
4102 ME_SetCursor(editor);
4103 ME_LinkNotify(editor,msg,wParam,lParam);
4105 break;
4106 case WM_RBUTTONUP:
4107 case WM_RBUTTONDOWN:
4108 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4109 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4110 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4111 return 0;
4112 goto do_default;
4113 case WM_CONTEXTMENU:
4114 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4115 goto do_default;
4116 break;
4117 case WM_SETFOCUS:
4118 editor->bHaveFocus = TRUE;
4119 ME_ShowCaret(editor);
4120 ME_SendOldNotify(editor, EN_SETFOCUS);
4121 return 0;
4122 case WM_KILLFOCUS:
4123 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4124 editor->bHaveFocus = FALSE;
4125 ME_HideCaret(editor);
4126 ME_SendOldNotify(editor, EN_KILLFOCUS);
4127 return 0;
4128 case WM_COMMAND:
4129 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4130 return 0;
4131 case WM_KEYUP:
4132 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4133 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4134 return 0;
4135 goto do_default;
4136 case WM_KEYDOWN:
4137 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4138 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4139 return 0;
4140 if (ME_KeyDown(editor, LOWORD(wParam)))
4141 return 0;
4142 goto do_default;
4143 case WM_CHAR:
4144 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4145 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4146 return 0;
4147 return ME_Char(editor, wParam, lParam, unicode);
4148 case WM_UNICHAR:
4149 if (unicode)
4151 if(wParam == UNICODE_NOCHAR) return TRUE;
4152 if(wParam <= 0x000fffff)
4154 if(wParam > 0xffff) /* convert to surrogates */
4156 wParam -= 0x10000;
4157 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4158 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4159 } else {
4160 ME_Char(editor, wParam, 0, TRUE);
4163 return 0;
4165 break;
4166 case EM_STOPGROUPTYPING:
4167 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4168 return 0;
4169 case WM_HSCROLL:
4171 const int scrollUnit = 7;
4173 switch(LOWORD(wParam))
4175 case SB_LEFT:
4176 ME_ScrollAbs(editor, 0, 0);
4177 break;
4178 case SB_RIGHT:
4179 ME_ScrollAbs(editor,
4180 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4181 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4182 break;
4183 case SB_LINELEFT:
4184 ME_ScrollLeft(editor, scrollUnit);
4185 break;
4186 case SB_LINERIGHT:
4187 ME_ScrollRight(editor, scrollUnit);
4188 break;
4189 case SB_PAGELEFT:
4190 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4191 break;
4192 case SB_PAGERIGHT:
4193 ME_ScrollRight(editor, editor->sizeWindow.cx);
4194 break;
4195 case SB_THUMBTRACK:
4196 case SB_THUMBPOSITION:
4198 int pos = HIWORD(wParam);
4199 if (editor->horz_si.nMax > 0xffff)
4200 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4201 ME_HScrollAbs(editor, pos);
4202 break;
4205 break;
4207 case EM_SCROLL: /* fall through */
4208 case WM_VSCROLL:
4210 int origNPos;
4211 int lineHeight;
4213 origNPos = editor->vert_si.nPos;
4214 lineHeight = 24;
4216 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4217 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4218 if (lineHeight <= 0) lineHeight = 24;
4220 switch(LOWORD(wParam))
4222 case SB_TOP:
4223 ME_ScrollAbs(editor, 0, 0);
4224 break;
4225 case SB_BOTTOM:
4226 ME_ScrollAbs(editor,
4227 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4228 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4229 break;
4230 case SB_LINEUP:
4231 ME_ScrollUp(editor,lineHeight);
4232 break;
4233 case SB_LINEDOWN:
4234 ME_ScrollDown(editor,lineHeight);
4235 break;
4236 case SB_PAGEUP:
4237 ME_ScrollUp(editor,editor->sizeWindow.cy);
4238 break;
4239 case SB_PAGEDOWN:
4240 ME_ScrollDown(editor,editor->sizeWindow.cy);
4241 break;
4242 case SB_THUMBTRACK:
4243 case SB_THUMBPOSITION:
4245 int pos = HIWORD(wParam);
4246 if (editor->vert_si.nMax > 0xffff)
4247 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4248 ME_VScrollAbs(editor, pos);
4249 break;
4252 if (msg == EM_SCROLL)
4253 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4254 break;
4256 case WM_MOUSEWHEEL:
4258 int gcWheelDelta;
4259 UINT pulScrollLines;
4260 BOOL ctrl_is_down;
4262 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4263 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4264 return 0;
4266 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4268 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4270 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4272 if (ctrl_is_down) {
4273 int numerator;
4274 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4276 numerator = 100;
4277 } else {
4278 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4280 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4281 if (numerator >= 10 && numerator <= 500)
4282 ME_SetZoom(editor, numerator, 100);
4283 } else {
4284 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4285 /* FIXME follow the original */
4286 if (pulScrollLines)
4287 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4290 break;
4292 case EM_GETRECT:
4294 *((RECT *)lParam) = editor->rcFormat;
4295 if (editor->bDefaultFormatRect)
4296 ((RECT *)lParam)->left -= editor->selofs;
4297 return 0;
4299 case EM_SETRECT:
4300 case EM_SETRECTNP:
4302 if (lParam)
4304 int border = 0;
4305 RECT clientRect;
4306 RECT *rc = (RECT *)lParam;
4308 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4309 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4310 if (wParam == 0)
4312 editor->rcFormat.top = max(0, rc->top - border);
4313 editor->rcFormat.left = max(0, rc->left - border);
4314 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4315 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4316 } else if (wParam == 1) {
4317 /* MSDN incorrectly says a wParam value of 1 causes the
4318 * lParam rect to be used as a relative offset,
4319 * however, the tests show it just prevents min/max bound
4320 * checking. */
4321 editor->rcFormat.top = rc->top - border;
4322 editor->rcFormat.left = rc->left - border;
4323 editor->rcFormat.bottom = rc->bottom;
4324 editor->rcFormat.right = rc->right + border;
4325 } else {
4326 return 0;
4328 editor->bDefaultFormatRect = FALSE;
4330 else
4332 ME_SetDefaultFormatRect(editor);
4333 editor->bDefaultFormatRect = TRUE;
4335 ME_MarkAllForWrapping(editor);
4336 ME_WrapMarkedParagraphs(editor);
4337 ME_UpdateScrollBar(editor);
4338 if (msg != EM_SETRECTNP)
4339 ME_Repaint(editor);
4340 return 0;
4342 case EM_REQUESTRESIZE:
4343 ME_SendRequestResize(editor, TRUE);
4344 return 0;
4345 case WM_SETREDRAW:
4346 goto do_default;
4347 case WM_SIZE:
4349 RECT clientRect;
4351 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4352 if (editor->bDefaultFormatRect) {
4353 ME_SetDefaultFormatRect(editor);
4354 } else {
4355 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4356 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4358 editor->prevClientRect = clientRect;
4359 ME_RewrapRepaint(editor);
4360 goto do_default;
4362 /* IME messages to make richedit controls IME aware */
4363 case WM_IME_SETCONTEXT:
4364 case WM_IME_CONTROL:
4365 case WM_IME_SELECT:
4366 case WM_IME_COMPOSITIONFULL:
4367 return 0;
4368 case WM_IME_STARTCOMPOSITION:
4370 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4371 ME_DeleteSelection(editor);
4372 ME_CommitUndo(editor);
4373 ME_UpdateRepaint(editor, FALSE);
4374 return 0;
4376 case WM_IME_COMPOSITION:
4378 HIMC hIMC;
4380 ME_Style *style = ME_GetInsertStyle(editor, 0);
4381 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4382 ME_DeleteSelection(editor);
4383 ME_SaveTempStyle(editor);
4384 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4386 LPWSTR lpCompStr = NULL;
4387 DWORD dwBufLen;
4388 DWORD dwIndex = lParam & GCS_RESULTSTR;
4389 if (!dwIndex)
4390 dwIndex = GCS_COMPSTR;
4392 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4393 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4394 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4395 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4396 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4397 HeapFree(GetProcessHeap(), 0, lpCompStr);
4399 if (dwIndex == GCS_COMPSTR)
4400 ME_SetSelection(editor,editor->imeStartIndex,
4401 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4403 ME_ReleaseStyle(style);
4404 ME_CommitUndo(editor);
4405 ME_UpdateRepaint(editor, FALSE);
4406 return 0;
4408 case WM_IME_ENDCOMPOSITION:
4410 ME_DeleteSelection(editor);
4411 editor->imeStartIndex=-1;
4412 return 0;
4414 case EM_GETOLEINTERFACE:
4416 LPVOID *ppvObj = (LPVOID*) lParam;
4417 return CreateIRichEditOle(editor, ppvObj);
4419 case EM_GETPASSWORDCHAR:
4421 return editor->cPasswordMask;
4423 case EM_SETOLECALLBACK:
4424 if(editor->lpOleCallback)
4425 IRichEditOleCallback_Release(editor->lpOleCallback);
4426 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4427 if(editor->lpOleCallback)
4428 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4429 return TRUE;
4430 case EM_GETWORDBREAKPROC:
4431 return (LRESULT)editor->pfnWordBreak;
4432 case EM_SETWORDBREAKPROC:
4434 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4436 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4437 return (LRESULT)pfnOld;
4439 case EM_GETTEXTMODE:
4440 return editor->mode;
4441 case EM_SETTEXTMODE:
4443 int mask = 0;
4444 int changes = 0;
4446 if (ME_GetTextLength(editor) ||
4447 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4448 return E_UNEXPECTED;
4450 /* Check for mutually exclusive flags in adjacent bits of wParam */
4451 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4452 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4453 return E_INVALIDARG;
4455 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4457 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4458 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4459 if (wParam & TM_PLAINTEXT) {
4460 /* Clear selection since it should be possible to select the
4461 * end of text run for rich text */
4462 ME_InvalidateSelection(editor);
4463 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4464 editor->pCursors[1] = editor->pCursors[0];
4465 /* plain text can only have the default style. */
4466 ME_ClearTempStyle(editor);
4467 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4468 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4469 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4472 /* FIXME: Currently no support for undo level and code page options */
4473 editor->mode = (editor->mode & ~mask) | changes;
4474 return 0;
4476 case EM_SETPASSWORDCHAR:
4478 editor->cPasswordMask = wParam;
4479 ME_RewrapRepaint(editor);
4480 return 0;
4482 case EM_SETTARGETDEVICE:
4483 if (wParam == 0)
4485 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4486 if (editor->nAvailWidth || editor->bWordWrap != new)
4488 editor->bWordWrap = new;
4489 editor->nAvailWidth = 0; /* wrap to client area */
4490 ME_RewrapRepaint(editor);
4492 } else {
4493 int width = max(0, lParam);
4494 if ((editor->styleFlags & ES_MULTILINE) &&
4495 (!editor->bWordWrap || editor->nAvailWidth != width))
4497 editor->nAvailWidth = width;
4498 editor->bWordWrap = TRUE;
4499 ME_RewrapRepaint(editor);
4501 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4503 return TRUE;
4504 default:
4505 do_default:
4506 *phresult = S_FALSE;
4507 break;
4509 return 0L;
4512 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4513 LPARAM lParam, BOOL unicode)
4515 ME_TextEditor *editor;
4516 HRESULT hresult;
4517 LRESULT lresult = 0;
4519 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4520 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4522 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4523 if (!editor)
4525 if (msg == WM_NCCREATE)
4527 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4528 ITextHost *texthost;
4530 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4531 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4532 return texthost != NULL;
4534 else
4536 return DefWindowProcW(hWnd, msg, wParam, lParam);
4540 switch (msg)
4542 case WM_PAINT:
4544 HDC hDC;
4545 RECT rc;
4546 PAINTSTRUCT ps;
4548 hDC = BeginPaint(editor->hWnd, &ps);
4549 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4550 ME_SendOldNotify(editor, EN_UPDATE);
4551 /* Erase area outside of the formatting rectangle */
4552 if (ps.rcPaint.top < editor->rcFormat.top)
4554 rc = ps.rcPaint;
4555 rc.bottom = editor->rcFormat.top;
4556 FillRect(hDC, &rc, editor->hbrBackground);
4557 ps.rcPaint.top = editor->rcFormat.top;
4559 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4560 rc = ps.rcPaint;
4561 rc.top = editor->rcFormat.bottom;
4562 FillRect(hDC, &rc, editor->hbrBackground);
4563 ps.rcPaint.bottom = editor->rcFormat.bottom;
4565 if (ps.rcPaint.left < editor->rcFormat.left) {
4566 rc = ps.rcPaint;
4567 rc.right = editor->rcFormat.left;
4568 FillRect(hDC, &rc, editor->hbrBackground);
4569 ps.rcPaint.left = editor->rcFormat.left;
4571 if (ps.rcPaint.right > editor->rcFormat.right) {
4572 rc = ps.rcPaint;
4573 rc.left = editor->rcFormat.right;
4574 FillRect(hDC, &rc, editor->hbrBackground);
4575 ps.rcPaint.right = editor->rcFormat.right;
4578 ME_PaintContent(editor, hDC, &ps.rcPaint);
4579 EndPaint(editor->hWnd, &ps);
4580 return 0;
4582 case WM_ERASEBKGND:
4584 HDC hDC = (HDC)wParam;
4585 RECT rc;
4587 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4588 FillRect(hDC, &rc, editor->hbrBackground);
4589 return 1;
4591 case EM_SETOPTIONS:
4593 DWORD dwStyle;
4594 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4595 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4596 ECO_SELECTIONBAR;
4597 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4598 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4599 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4600 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4601 return lresult;
4603 case EM_SETREADONLY:
4605 DWORD dwStyle;
4606 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4607 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4608 dwStyle &= ~ES_READONLY;
4609 if (wParam)
4610 dwStyle |= ES_READONLY;
4611 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4612 return lresult;
4614 default:
4615 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4618 if (hresult == S_FALSE)
4619 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4621 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4622 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4624 return lresult;
4627 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4629 BOOL unicode = TRUE;
4631 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4632 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4633 unicode = FALSE;
4635 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4638 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4640 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4643 /******************************************************************
4644 * RichEditANSIWndProc (RICHED20.10)
4646 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4648 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4651 /******************************************************************
4652 * RichEdit10ANSIWndProc (RICHED20.9)
4654 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4656 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4658 ITextHost *texthost;
4659 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4661 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4662 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4663 return texthost != NULL;
4665 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4668 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4670 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4673 /* Fill buffer with srcChars unicode characters from the start cursor.
4675 * buffer: destination buffer
4676 * buflen: length of buffer in characters excluding the NULL terminator.
4677 * start: start of editor text to copy into buffer.
4678 * srcChars: Number of characters to use from the editor text.
4679 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4681 * returns the number of characters written excluding the NULL terminator.
4683 * The written text is always NULL terminated.
4685 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4686 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4688 ME_DisplayItem *pRun, *pNextRun;
4689 const WCHAR *pStart = buffer;
4690 const WCHAR cr_lf[] = {'\r', '\n', 0};
4691 const WCHAR *str;
4692 int nLen;
4694 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4695 if (editor->bEmulateVersion10) bCRLF = 0;
4697 pRun = start->pRun;
4698 assert(pRun);
4699 pNextRun = ME_FindItemFwd(pRun, diRun);
4701 nLen = pRun->member.run.len - start->nOffset;
4702 str = get_text( &pRun->member.run, start->nOffset );
4704 /* No '\r' is appended to the last paragraph. */
4705 while (srcChars && buflen && pNextRun)
4707 int nFlags = pRun->member.run.nFlags;
4709 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4711 if (buflen == 1) break;
4712 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4713 * EM_GETTEXTEX, however, this is done for copying text which
4714 * also uses this function. */
4715 srcChars -= min(nLen, srcChars);
4716 nLen = 2;
4717 str = cr_lf;
4718 } else {
4719 nLen = min(nLen, srcChars);
4720 srcChars -= nLen;
4723 nLen = min(nLen, buflen);
4724 buflen -= nLen;
4726 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4728 buffer += nLen;
4730 pRun = pNextRun;
4731 pNextRun = ME_FindItemFwd(pRun, diRun);
4733 nLen = pRun->member.run.len;
4734 str = get_text( &pRun->member.run, 0 );
4736 *buffer = 0;
4737 return buffer - pStart;
4740 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4742 WNDCLASSW wcW;
4743 WNDCLASSA wcA;
4745 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4746 wcW.lpfnWndProc = RichEditWndProcW;
4747 wcW.cbClsExtra = 0;
4748 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4749 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4750 wcW.hIcon = NULL;
4751 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4752 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4753 wcW.lpszMenuName = NULL;
4755 if (is_version_nt())
4757 wcW.lpszClassName = RICHEDIT_CLASS20W;
4758 if (!RegisterClassW(&wcW)) return FALSE;
4759 wcW.lpszClassName = MSFTEDIT_CLASS;
4760 if (!RegisterClassW(&wcW)) return FALSE;
4762 else
4764 /* WNDCLASSA/W have the same layout */
4765 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4766 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4767 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4768 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4771 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4772 wcA.lpfnWndProc = RichEditWndProcA;
4773 wcA.cbClsExtra = 0;
4774 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4775 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4776 wcA.hIcon = NULL;
4777 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4778 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4779 wcA.lpszMenuName = NULL;
4780 wcA.lpszClassName = RICHEDIT_CLASS20A;
4781 if (!RegisterClassA(&wcA)) return FALSE;
4782 wcA.lpszClassName = "RichEdit50A";
4783 if (!RegisterClassA(&wcA)) return FALSE;
4785 return TRUE;
4788 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4789 /* FIXME: Not implemented */
4790 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4791 hWnd, msg, get_msg_name(msg), wParam, lParam);
4792 return DefWindowProcW(hWnd, msg, wParam, lParam);
4795 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4796 /* FIXME: Not implemented */
4797 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4798 hWnd, msg, get_msg_name(msg), wParam, lParam);
4799 return DefWindowProcW(hWnd, msg, wParam, lParam);
4802 /******************************************************************
4803 * REExtendedRegisterClass (RICHED20.8)
4805 * FIXME undocumented
4806 * Need to check for errors and implement controls and callbacks
4808 LRESULT WINAPI REExtendedRegisterClass(void)
4810 WNDCLASSW wcW;
4811 UINT result;
4813 FIXME("semi stub\n");
4815 wcW.cbClsExtra = 0;
4816 wcW.cbWndExtra = 4;
4817 wcW.hInstance = NULL;
4818 wcW.hIcon = NULL;
4819 wcW.hCursor = NULL;
4820 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4821 wcW.lpszMenuName = NULL;
4823 if (!ME_ListBoxRegistered)
4825 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4826 wcW.lpfnWndProc = REListWndProc;
4827 wcW.lpszClassName = REListBox20W;
4828 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4831 if (!ME_ComboBoxRegistered)
4833 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4834 wcW.lpfnWndProc = REComboWndProc;
4835 wcW.lpszClassName = REComboBox20W;
4836 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4839 result = 0;
4840 if (ME_ListBoxRegistered)
4841 result += 1;
4842 if (ME_ComboBoxRegistered)
4843 result += 2;
4845 return result;
4848 static BOOL isurlspecial(WCHAR c)
4850 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4851 return strchrW( special_chars, c ) != NULL;
4855 * This proc takes a selection, and scans it forward in order to select the span
4856 * of a possible URL candidate. A possible URL candidate must start with isalnum
4857 * or one of the following special characters: *|/\+%#@ and must consist entirely
4858 * of the characters allowed to start the URL, plus : (colon) which may occur
4859 * at most once, and not at either end.
4861 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4862 const ME_Cursor *start,
4863 int nChars,
4864 ME_Cursor *candidate_min,
4865 ME_Cursor *candidate_max)
4867 ME_Cursor cursor = *start;
4868 BOOL foundColon = FALSE;
4869 BOOL candidateStarted = FALSE;
4870 WCHAR lastAcceptedChar = '\0';
4872 while (nChars > 0)
4874 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4875 WCHAR *str = strStart + cursor.nOffset;
4876 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4877 nChars -= nLen;
4879 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4881 /* Find start of candidate */
4882 if (!candidateStarted)
4884 while (nLen)
4886 nLen--;
4887 if (isalnumW(*str) || isurlspecial(*str))
4889 cursor.nOffset = str - strStart;
4890 *candidate_min = cursor;
4891 candidateStarted = TRUE;
4892 lastAcceptedChar = *str++;
4893 break;
4895 str++;
4899 /* Find end of candidate */
4900 if (candidateStarted) {
4901 while (nLen)
4903 nLen--;
4904 if (*str == ':' && !foundColon) {
4905 foundColon = TRUE;
4906 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4907 cursor.nOffset = str - strStart;
4908 if (lastAcceptedChar == ':')
4909 ME_MoveCursorChars(editor, &cursor, -1);
4910 *candidate_max = cursor;
4911 return TRUE;
4913 lastAcceptedChar = *str++;
4916 } else {
4917 /* End of paragraph: skip it if before candidate span, or terminates
4918 current active span */
4919 if (candidateStarted) {
4920 if (lastAcceptedChar == ':')
4921 ME_MoveCursorChars(editor, &cursor, -1);
4922 *candidate_max = cursor;
4923 return TRUE;
4927 /* Reaching this point means no span was found, so get next span */
4928 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4929 if (candidateStarted) {
4930 /* There are no further runs, so take end of text as end of candidate */
4931 cursor.nOffset = str - strStart;
4932 if (lastAcceptedChar == ':')
4933 ME_MoveCursorChars(editor, &cursor, -1);
4934 *candidate_max = cursor;
4935 return TRUE;
4937 *candidate_max = *candidate_min = cursor;
4938 return FALSE;
4940 cursor.nOffset = 0;
4943 if (candidateStarted) {
4944 /* There are no further runs, so take end of text as end of candidate */
4945 if (lastAcceptedChar == ':')
4946 ME_MoveCursorChars(editor, &cursor, -1);
4947 *candidate_max = cursor;
4948 return TRUE;
4950 *candidate_max = *candidate_min = cursor;
4951 return FALSE;
4955 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4957 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4959 #define MAX_PREFIX_LEN 9
4960 struct prefix_s {
4961 const WCHAR text[MAX_PREFIX_LEN];
4962 int length;
4963 }prefixes[] = {
4964 {{'p','r','o','s','p','e','r','o',':'}, 9},
4965 {{'t','e','l','n','e','t',':'}, 7},
4966 {{'g','o','p','h','e','r',':'}, 7},
4967 {{'m','a','i','l','t','o',':'}, 7},
4968 {{'h','t','t','p','s',':'}, 6},
4969 {{'f','i','l','e',':'}, 5},
4970 {{'n','e','w','s',':'}, 5},
4971 {{'w','a','i','s',':'}, 5},
4972 {{'n','n','t','p',':'}, 5},
4973 {{'h','t','t','p',':'}, 5},
4974 {{'w','w','w','.'}, 4},
4975 {{'f','t','p',':'}, 4},
4977 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4978 unsigned int i;
4980 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4981 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4983 if (nChars < prefixes[i].length) continue;
4984 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4985 return TRUE;
4987 return FALSE;
4988 #undef MAX_PREFIX_LEN
4992 * This proc walks through the indicated selection and evaluates whether each
4993 * section identified by ME_FindNextURLCandidate and in-between sections have
4994 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4995 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4997 * Since this function can cause runs to be split, do not depend on the value
4998 * of the start cursor at the end of the function.
5000 * nChars may be set to INT_MAX to update to the end of the text.
5002 * Returns TRUE if at least one section was modified.
5004 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5006 BOOL modified = FALSE;
5007 ME_Cursor startCur = *start;
5009 if (!editor->AutoURLDetect_bEnable) return FALSE;
5013 CHARFORMAT2W link;
5014 ME_Cursor candidateStart, candidateEnd;
5016 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5017 &candidateStart, &candidateEnd))
5019 /* Section before candidate is not an URL */
5020 int cMin = ME_GetCursorOfs(&candidateStart);
5021 int cMax = ME_GetCursorOfs(&candidateEnd);
5023 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5024 candidateStart = candidateEnd;
5025 nChars -= cMax - ME_GetCursorOfs(&startCur);
5027 else
5029 /* No more candidates until end of selection */
5030 nChars = 0;
5033 if (startCur.pRun != candidateStart.pRun ||
5034 startCur.nOffset != candidateStart.nOffset)
5036 /* CFE_LINK effect should be consistently unset */
5037 link.cbSize = sizeof(link);
5038 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5039 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5041 /* CFE_LINK must be unset from this range */
5042 memset(&link, 0, sizeof(CHARFORMAT2W));
5043 link.cbSize = sizeof(link);
5044 link.dwMask = CFM_LINK;
5045 link.dwEffects = 0;
5046 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5047 /* Update candidateEnd since setting character formats may split
5048 * runs, which can cause a cursor to be at an invalid offset within
5049 * a split run. */
5050 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5052 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5053 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5055 modified = TRUE;
5058 if (candidateStart.pRun != candidateEnd.pRun ||
5059 candidateStart.nOffset != candidateEnd.nOffset)
5061 /* CFE_LINK effect should be consistently set */
5062 link.cbSize = sizeof(link);
5063 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5064 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5066 /* CFE_LINK must be set on this range */
5067 memset(&link, 0, sizeof(CHARFORMAT2W));
5068 link.cbSize = sizeof(link);
5069 link.dwMask = CFM_LINK;
5070 link.dwEffects = CFE_LINK;
5071 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5072 modified = TRUE;
5075 startCur = candidateEnd;
5076 } while (nChars > 0);
5077 return modified;