riched20: Consider adjacent runs when computing EN_LINK range.
[wine.git] / dlls / riched20 / editor.c
blob2af2582562e57b616fd2327fc152899ecf6d698e
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 BOOL me_debug = FALSE;
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 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1202 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1203 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1204 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1205 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1206 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1207 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1209 REOBJECT reobject;
1211 reobject.cbStruct = sizeof(reobject);
1212 reobject.cp = REO_CP_SELECTION;
1213 reobject.clsid = clsid;
1214 reobject.poleobj = lpObject;
1215 reobject.pstg = lpStorage;
1216 reobject.polesite = lpClientSite;
1217 /* convert from twips to .01 mm */
1218 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1219 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1220 reobject.dvaspect = DVASPECT_CONTENT;
1221 reobject.dwFlags = 0; /* FIXME */
1222 reobject.dwUser = 0;
1224 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1225 ret = TRUE;
1228 if (lpObject) IOleObject_Release(lpObject);
1229 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1230 if (lpStorage) IStorage_Release(lpStorage);
1231 if (lpDataObject) IDataObject_Release(lpDataObject);
1232 if (lpOleCache) IOleCache_Release(lpOleCache);
1234 return ret;
1237 static void ME_RTFReadPictGroup(RTF_Info *info)
1239 SIZEL sz;
1240 BYTE* buffer = NULL;
1241 unsigned bufsz, bufidx;
1242 BOOL flip;
1243 BYTE val;
1244 METAFILEPICT mfp;
1245 HENHMETAFILE hemf;
1246 HBITMAP hbmp;
1247 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1249 RTFGetToken (info);
1250 if (info->rtfClass == rtfEOF)
1251 return;
1252 mfp.mm = MM_TEXT;
1253 /* fetch picture type */
1254 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1256 mfp.mm = info->rtfParam;
1257 gfx = gfx_metafile;
1259 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1261 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1262 gfx = gfx_dib;
1264 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1266 gfx = gfx_enhmetafile;
1268 else
1270 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1271 goto skip_group;
1273 sz.cx = sz.cy = 0;
1274 /* fetch picture attributes */
1275 for (;;)
1277 RTFGetToken (info);
1278 if (info->rtfClass == rtfEOF)
1279 return;
1280 if (info->rtfClass == rtfText)
1281 break;
1282 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1284 ERR("Expected picture attribute (%d %d)\n",
1285 info->rtfClass, info->rtfMajor);
1286 goto skip_group;
1288 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1290 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1292 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1294 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1296 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1297 sz.cx = info->rtfParam;
1298 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1299 sz.cy = info->rtfParam;
1300 else
1301 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1303 /* fetch picture data */
1304 bufsz = 1024;
1305 bufidx = 0;
1306 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1307 val = info->rtfMajor;
1308 for (flip = TRUE;; flip = !flip)
1310 RTFGetToken (info);
1311 if (info->rtfClass == rtfEOF)
1313 HeapFree(GetProcessHeap(), 0, buffer);
1314 return; /* Warn ?? */
1316 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1317 break;
1318 if (info->rtfClass != rtfText) goto skip_group;
1319 if (flip)
1321 if (bufidx >= bufsz &&
1322 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1323 goto skip_group;
1324 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1326 else
1327 val = info->rtfMajor;
1329 if (flip) FIXME("wrong hex string\n");
1331 switch (gfx)
1333 case gfx_enhmetafile:
1334 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1335 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1336 break;
1337 case gfx_metafile:
1338 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1339 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1340 break;
1341 case gfx_dib:
1343 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1344 HDC hdc = GetDC(0);
1345 unsigned nc = bi->bmiHeader.biClrUsed;
1347 /* not quite right, especially for bitfields type of compression */
1348 if (!nc && bi->bmiHeader.biBitCount <= 8)
1349 nc = 1 << bi->bmiHeader.biBitCount;
1350 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1351 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1352 bi, DIB_RGB_COLORS)))
1353 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1354 ReleaseDC(0, hdc);
1356 break;
1357 default:
1358 break;
1360 HeapFree(GetProcessHeap(), 0, buffer);
1361 RTFRouteToken (info); /* feed "}" back to router */
1362 return;
1363 skip_group:
1364 HeapFree(GetProcessHeap(), 0, buffer);
1365 RTFSkipGroup(info);
1366 RTFRouteToken(info); /* feed "}" back to router */
1369 /* for now, lookup the \result part and use it, whatever the object */
1370 static void ME_RTFReadObjectGroup(RTF_Info *info)
1372 for (;;)
1374 RTFGetToken (info);
1375 if (info->rtfClass == rtfEOF)
1376 return;
1377 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1378 break;
1379 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1381 RTFGetToken (info);
1382 if (info->rtfClass == rtfEOF)
1383 return;
1384 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1386 int level = 1;
1388 while (RTFGetToken (info) != rtfEOF)
1390 if (info->rtfClass == rtfGroup)
1392 if (info->rtfMajor == rtfBeginGroup) level++;
1393 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1395 RTFRouteToken(info);
1398 else RTFSkipGroup(info);
1399 continue;
1401 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1403 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1404 return;
1407 RTFRouteToken(info); /* feed "}" back to router */
1410 static void ME_RTFReadHook(RTF_Info *info)
1412 switch(info->rtfClass)
1414 case rtfGroup:
1415 switch(info->rtfMajor)
1417 case rtfBeginGroup:
1418 if (info->stackTop < maxStack) {
1419 info->stack[info->stackTop].style = info->style;
1420 ME_AddRefStyle(info->style);
1421 info->stack[info->stackTop].codePage = info->codePage;
1422 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1424 info->stackTop++;
1425 info->styleChanged = FALSE;
1426 break;
1427 case rtfEndGroup:
1429 RTFFlushOutputBuffer(info);
1430 info->stackTop--;
1431 if (info->stackTop <= 0)
1432 info->rtfClass = rtfEOF;
1433 if (info->stackTop < 0)
1434 return;
1436 ME_ReleaseStyle(info->style);
1437 info->style = info->stack[info->stackTop].style;
1438 info->codePage = info->stack[info->stackTop].codePage;
1439 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1440 break;
1443 break;
1447 void
1448 ME_StreamInFill(ME_InStream *stream)
1450 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1451 (BYTE *)stream->buffer,
1452 sizeof(stream->buffer),
1453 (LONG *)&stream->dwSize);
1454 stream->dwUsed = 0;
1457 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1459 RTF_Info parser;
1460 ME_Style *style;
1461 int from, to, nUndoMode;
1462 int nEventMask = editor->nEventMask;
1463 ME_InStream inStream;
1464 BOOL invalidRTF = FALSE;
1465 ME_Cursor *selStart, *selEnd;
1466 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1468 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1469 editor->nEventMask = 0;
1471 ME_GetSelectionOfs(editor, &from, &to);
1472 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1474 ME_GetSelection(editor, &selStart, &selEnd);
1475 style = ME_GetSelectionInsertStyle(editor);
1477 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1479 /* Don't insert text at the end of the table row */
1480 if (!editor->bEmulateVersion10) { /* v4.1 */
1481 ME_DisplayItem *para = editor->pCursors->pPara;
1482 if (para->member.para.nFlags & MEPF_ROWEND)
1484 para = para->member.para.next_para;
1485 editor->pCursors[0].pPara = para;
1486 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1487 editor->pCursors[0].nOffset = 0;
1489 if (para->member.para.nFlags & MEPF_ROWSTART)
1491 para = para->member.para.next_para;
1492 editor->pCursors[0].pPara = para;
1493 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1494 editor->pCursors[0].nOffset = 0;
1496 editor->pCursors[1] = editor->pCursors[0];
1497 } else { /* v1.0 - 3.0 */
1498 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1499 ME_IsInTable(editor->pCursors[0].pRun))
1500 return 0;
1502 } else {
1503 style = editor->pBuffer->pDefaultStyle;
1504 ME_AddRefStyle(style);
1505 ME_SetSelection(editor, 0, 0);
1506 ME_InternalDeleteText(editor, &editor->pCursors[1],
1507 ME_GetTextLength(editor), FALSE);
1508 from = to = 0;
1509 ME_ClearTempStyle(editor);
1510 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1514 /* Back up undo mode to a local variable */
1515 nUndoMode = editor->nUndoMode;
1517 /* Only create an undo if SFF_SELECTION is set */
1518 if (!(format & SFF_SELECTION))
1519 editor->nUndoMode = umIgnore;
1521 inStream.editstream = stream;
1522 inStream.editstream->dwError = 0;
1523 inStream.dwSize = 0;
1524 inStream.dwUsed = 0;
1526 if (format & SF_RTF)
1528 /* Check if it's really RTF, and if it is not, use plain text */
1529 ME_StreamInFill(&inStream);
1530 if (!inStream.editstream->dwError)
1532 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1533 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1535 invalidRTF = TRUE;
1536 inStream.editstream->dwError = -16;
1541 if (!invalidRTF && !inStream.editstream->dwError)
1543 if (format & SF_RTF) {
1544 from = ME_GetCursorOfs(&editor->pCursors[0]);
1546 /* setup the RTF parser */
1547 memset(&parser, 0, sizeof parser);
1548 RTFSetEditStream(&parser, &inStream);
1549 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1550 parser.editor = editor;
1551 parser.style = style;
1552 WriterInit(&parser);
1553 RTFInit(&parser);
1554 RTFSetReadHook(&parser, ME_RTFReadHook);
1555 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1556 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1557 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1559 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1560 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1562 BeginFile(&parser);
1564 /* do the parsing */
1565 RTFRead(&parser);
1566 RTFFlushOutputBuffer(&parser);
1567 if (!editor->bEmulateVersion10) { /* v4.1 */
1568 if (parser.tableDef && parser.tableDef->tableRowStart &&
1569 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1571 /* Delete any incomplete table row at the end of the rich text. */
1572 int nOfs, nChars;
1573 ME_DisplayItem *para;
1575 parser.rtfMinor = rtfRow;
1576 /* Complete the table row before deleting it.
1577 * By doing it this way we will have the current paragraph format set
1578 * properly to reflect that is not in the complete table, and undo items
1579 * will be added for this change to the current paragraph format. */
1580 if (parser.nestingLevel > 0)
1582 while (parser.nestingLevel > 1)
1583 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1584 para = parser.tableDef->tableRowStart;
1585 ME_RTFSpecialCharHook(&parser);
1586 } else {
1587 para = parser.tableDef->tableRowStart;
1588 ME_RTFSpecialCharHook(&parser);
1589 assert(para->member.para.nFlags & MEPF_ROWEND);
1590 para = para->member.para.next_para;
1593 editor->pCursors[1].pPara = para;
1594 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1595 editor->pCursors[1].nOffset = 0;
1596 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1597 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1598 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1599 if (parser.tableDef)
1600 parser.tableDef->tableRowStart = NULL;
1603 ME_CheckTablesForCorruption(editor);
1604 RTFDestroy(&parser);
1605 if (parser.lpRichEditOle)
1606 IRichEditOle_Release(parser.lpRichEditOle);
1608 if (parser.stackTop > 0)
1610 while (--parser.stackTop >= 0)
1612 ME_ReleaseStyle(parser.style);
1613 parser.style = parser.stack[parser.stackTop].style;
1615 if (!inStream.editstream->dwError)
1616 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1619 /* Remove last line break, as mandated by tests. This is not affected by
1620 CR/LF counters, since RTF streaming presents only \para tokens, which
1621 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1623 if (stripLastCR && !(format & SFF_SELECTION)) {
1624 int newto;
1625 ME_GetSelection(editor, &selStart, &selEnd);
1626 newto = ME_GetCursorOfs(selEnd);
1627 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1628 WCHAR lastchar[3] = {'\0', '\0'};
1629 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1630 ME_Cursor linebreakCursor = *selEnd;
1632 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1633 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE);
1634 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1635 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1639 to = ME_GetCursorOfs(&editor->pCursors[0]);
1640 num_read = to - from;
1642 style = parser.style;
1644 else if (format & SF_TEXT)
1645 num_read = ME_StreamInText(editor, format, &inStream, style);
1646 else
1647 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1648 /* put the cursor at the top */
1649 if (!(format & SFF_SELECTION))
1650 ME_SetSelection(editor, 0, 0);
1653 /* Restore saved undo mode */
1654 editor->nUndoMode = nUndoMode;
1656 /* even if we didn't add an undo, we need to commit anything on the stack */
1657 ME_CommitUndo(editor);
1659 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1660 if (!(format & SFF_SELECTION))
1661 ME_EmptyUndoStack(editor);
1663 ME_ReleaseStyle(style);
1664 editor->nEventMask = nEventMask;
1665 ME_UpdateRepaint(editor, FALSE);
1666 if (!(format & SFF_SELECTION)) {
1667 ME_ClearTempStyle(editor);
1669 ITextHost_TxShowCaret(editor->texthost, FALSE);
1670 ME_MoveCaret(editor);
1671 ITextHost_TxShowCaret(editor->texthost, TRUE);
1672 ME_SendSelChange(editor);
1673 ME_SendRequestResize(editor, FALSE);
1675 return num_read;
1679 typedef struct tagME_RTFStringStreamStruct
1681 char *string;
1682 int pos;
1683 int length;
1684 } ME_RTFStringStreamStruct;
1686 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1688 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1689 int count;
1691 count = min(cb, pStruct->length - pStruct->pos);
1692 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1693 pStruct->pos += count;
1694 *pcb = count;
1695 return 0;
1698 static void
1699 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1701 EDITSTREAM es;
1702 ME_RTFStringStreamStruct data;
1704 data.string = string;
1705 data.length = strlen(string);
1706 data.pos = 0;
1707 es.dwCookie = (DWORD_PTR)&data;
1708 es.pfnCallback = ME_ReadFromRTFString;
1709 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1713 static int
1714 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1716 const int nLen = lstrlenW(text);
1717 const int nTextLen = ME_GetTextLength(editor);
1718 int nMin, nMax;
1719 ME_Cursor cursor;
1720 WCHAR wLastChar = ' ';
1722 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1723 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1725 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1726 FIXME("Flags 0x%08x not implemented\n",
1727 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1729 nMin = chrg->cpMin;
1730 if (chrg->cpMax == -1)
1731 nMax = nTextLen;
1732 else
1733 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1735 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1736 if (editor->bEmulateVersion10 && nMax == nTextLen)
1738 flags |= FR_DOWN;
1741 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1742 if (editor->bEmulateVersion10 && nMax < nMin)
1744 if (chrgText)
1746 chrgText->cpMin = -1;
1747 chrgText->cpMax = -1;
1749 return -1;
1752 /* when searching up, if cpMin < cpMax, then instead of searching
1753 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1754 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1755 * case, it is always bigger than cpMin.
1757 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1759 int nSwap = nMax;
1761 nMax = nMin > nTextLen ? nTextLen : nMin;
1762 if (nMin < nSwap || chrg->cpMax == -1)
1763 nMin = 0;
1764 else
1765 nMin = nSwap;
1768 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1770 if (chrgText)
1771 chrgText->cpMin = chrgText->cpMax = -1;
1772 return -1;
1775 if (flags & FR_DOWN) /* Forward search */
1777 /* If possible, find the character before where the search starts */
1778 if ((flags & FR_WHOLEWORD) && nMin)
1780 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1781 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1782 ME_MoveCursorChars(editor, &cursor, 1);
1783 } else {
1784 ME_CursorFromCharOfs(editor, nMin, &cursor);
1787 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1789 ME_DisplayItem *pCurItem = cursor.pRun;
1790 int nCurStart = cursor.nOffset;
1791 int nMatched = 0;
1793 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1795 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1796 break;
1798 nMatched++;
1799 if (nMatched == nLen)
1801 ME_DisplayItem *pNextItem = pCurItem;
1802 int nNextStart = nCurStart;
1803 WCHAR wNextChar;
1805 /* Check to see if next character is a whitespace */
1806 if (flags & FR_WHOLEWORD)
1808 if (nCurStart + nMatched == pCurItem->member.run.len)
1810 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1811 nNextStart = -nMatched;
1814 if (pNextItem)
1815 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1816 else
1817 wNextChar = ' ';
1819 if (isalnumW(wNextChar))
1820 break;
1823 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1824 if (chrgText)
1826 chrgText->cpMin = cursor.nOffset;
1827 chrgText->cpMax = cursor.nOffset + nLen;
1829 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1830 return cursor.nOffset;
1832 if (nCurStart + nMatched == pCurItem->member.run.len)
1834 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1835 nCurStart = -nMatched;
1838 if (pCurItem)
1839 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1840 else
1841 wLastChar = ' ';
1843 cursor.nOffset++;
1844 if (cursor.nOffset == cursor.pRun->member.run.len)
1846 ME_NextRun(&cursor.pPara, &cursor.pRun);
1847 cursor.nOffset = 0;
1851 else /* Backward search */
1853 /* If possible, find the character after where the search ends */
1854 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1856 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1857 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1858 ME_MoveCursorChars(editor, &cursor, -1);
1859 } else {
1860 ME_CursorFromCharOfs(editor, nMax, &cursor);
1863 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1865 ME_DisplayItem *pCurItem = cursor.pRun;
1866 ME_DisplayItem *pCurPara = cursor.pPara;
1867 int nCurEnd = cursor.nOffset;
1868 int nMatched = 0;
1870 if (nCurEnd == 0)
1872 ME_PrevRun(&pCurPara, &pCurItem);
1873 nCurEnd = pCurItem->member.run.len + nMatched;
1876 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1877 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1879 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1880 break;
1882 nMatched++;
1883 if (nMatched == nLen)
1885 ME_DisplayItem *pPrevItem = pCurItem;
1886 int nPrevEnd = nCurEnd;
1887 WCHAR wPrevChar;
1888 int nStart;
1890 /* Check to see if previous character is a whitespace */
1891 if (flags & FR_WHOLEWORD)
1893 if (nPrevEnd - nMatched == 0)
1895 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1896 if (pPrevItem)
1897 nPrevEnd = pPrevItem->member.run.len + nMatched;
1900 if (pPrevItem)
1901 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1902 else
1903 wPrevChar = ' ';
1905 if (isalnumW(wPrevChar))
1906 break;
1909 nStart = pCurPara->member.para.nCharOfs
1910 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1911 if (chrgText)
1913 chrgText->cpMin = nStart;
1914 chrgText->cpMax = nStart + nLen;
1916 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1917 return nStart;
1919 if (nCurEnd - nMatched == 0)
1921 ME_PrevRun(&pCurPara, &pCurItem);
1922 /* Don't care about pCurItem becoming NULL here; it's already taken
1923 * care of in the exterior loop condition */
1924 nCurEnd = pCurItem->member.run.len + nMatched;
1927 if (pCurItem)
1928 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1929 else
1930 wLastChar = ' ';
1932 cursor.nOffset--;
1933 if (cursor.nOffset < 0)
1935 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1936 cursor.nOffset = cursor.pRun->member.run.len;
1940 TRACE("not found\n");
1941 if (chrgText)
1942 chrgText->cpMin = chrgText->cpMax = -1;
1943 return -1;
1946 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1948 int nChars;
1949 ME_Cursor start;
1951 if (!ex->cb || !pText) return 0;
1953 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1954 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1956 if (ex->flags & GT_SELECTION)
1958 int from, to;
1959 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1960 start = editor->pCursors[nStartCur];
1961 nChars = to - from;
1963 else
1965 ME_SetCursorToStart(editor, &start);
1966 nChars = INT_MAX;
1968 if (ex->codepage == CP_UNICODE)
1970 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1971 &start, nChars, ex->flags & GT_USECRLF);
1973 else
1975 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1976 we can just take a bigger buffer? :)
1977 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1978 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1980 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1981 DWORD buflen;
1982 LPWSTR buffer;
1983 LRESULT rc;
1985 buflen = min(crlfmul * nChars, ex->cb - 1);
1986 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1988 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1989 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1990 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1991 if (rc) rc--; /* do not count 0 terminator */
1993 heap_free(buffer);
1994 return rc;
1998 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1999 const ME_Cursor *start, int nLen, BOOL unicode)
2001 if (!strText) return 0;
2002 if (unicode) {
2003 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE);
2004 } else {
2005 int nChars;
2006 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2007 if (!p) return 0;
2008 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE);
2009 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2010 nLen+1, NULL, NULL);
2011 FREE_OBJ(p);
2012 return nChars;
2016 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2018 int end;
2020 TRACE("%d - %d\n", to, from );
2022 ME_InvalidateSelection( editor );
2023 end = ME_SetSelection( editor, to, from );
2024 ME_InvalidateSelection( editor );
2025 ITextHost_TxShowCaret( editor->texthost, FALSE );
2026 ME_ShowCaret( editor );
2027 ME_SendSelChange( editor );
2029 return end;
2032 typedef struct tagME_GlobalDestStruct
2034 HGLOBAL hData;
2035 int nLength;
2036 } ME_GlobalDestStruct;
2038 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2040 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2041 int i;
2042 WORD *pSrc, *pDest;
2044 cb = cb >> 1;
2045 pDest = (WORD *)lpBuff;
2046 pSrc = GlobalLock(pData->hData);
2047 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2048 pDest[i] = pSrc[pData->nLength+i];
2050 pData->nLength += i;
2051 *pcb = 2*i;
2052 GlobalUnlock(pData->hData);
2053 return 0;
2056 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2058 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2059 int i;
2060 BYTE *pSrc, *pDest;
2062 pDest = lpBuff;
2063 pSrc = GlobalLock(pData->hData);
2064 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2065 pDest[i] = pSrc[pData->nLength+i];
2067 pData->nLength += i;
2068 *pcb = i;
2069 GlobalUnlock(pData->hData);
2070 return 0;
2073 static BOOL ME_Paste(ME_TextEditor *editor)
2075 DWORD dwFormat = 0;
2076 EDITSTREAM es;
2077 ME_GlobalDestStruct gds;
2078 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2079 UINT cf = 0;
2081 if (IsClipboardFormatAvailable(nRTFFormat))
2082 cf = nRTFFormat, dwFormat = SF_RTF;
2083 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2084 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2085 else
2086 return FALSE;
2088 if (!OpenClipboard(editor->hWnd))
2089 return FALSE;
2090 gds.hData = GetClipboardData(cf);
2091 gds.nLength = 0;
2092 es.dwCookie = (DWORD_PTR)&gds;
2093 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2094 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2096 CloseClipboard();
2097 return TRUE;
2100 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2102 LPDATAOBJECT dataObj = NULL;
2103 HRESULT hr = S_OK;
2105 if (editor->cPasswordMask)
2106 return FALSE; /* Copying or Cutting masked text isn't allowed */
2108 if(editor->lpOleCallback)
2110 CHARRANGE range;
2111 range.cpMin = ME_GetCursorOfs(start);
2112 range.cpMax = range.cpMin + nChars;
2113 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2115 if(FAILED(hr) || !dataObj)
2116 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2117 if(SUCCEEDED(hr)) {
2118 hr = OleSetClipboard(dataObj);
2119 IDataObject_Release(dataObj);
2121 return SUCCEEDED(hr) != 0;
2124 /* helper to send a msg filter notification */
2125 static BOOL
2126 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2128 MSGFILTER msgf;
2130 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2131 msgf.nmhdr.hwndFrom = editor->hWnd;
2132 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2133 msgf.nmhdr.code = EN_MSGFILTER;
2134 msgf.msg = msg;
2135 msgf.wParam = *wParam;
2136 msgf.lParam = *lParam;
2137 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2138 return FALSE;
2139 *wParam = msgf.wParam;
2140 *lParam = msgf.lParam;
2141 msgf.wParam = *wParam;
2143 return TRUE;
2146 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2148 ME_DisplayItem *startPara, *endPara;
2149 ME_DisplayItem *prev_para;
2150 ME_Cursor *from, *to;
2151 ME_Cursor start;
2152 int nChars;
2154 if (!editor->AutoURLDetect_bEnable) return;
2156 ME_GetSelection(editor, &from, &to);
2158 /* Find paragraph previous to the one that contains start cursor */
2159 startPara = from->pPara;
2160 prev_para = startPara->member.para.prev_para;
2161 if (prev_para->type == diParagraph) startPara = prev_para;
2163 /* Find paragraph that contains end cursor */
2164 endPara = to->pPara->member.para.next_para;
2166 start.pPara = startPara;
2167 start.pRun = ME_FindItemFwd(startPara, diRun);
2168 start.nOffset = 0;
2169 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2171 ME_UpdateLinkAttribute(editor, &start, nChars);
2174 static BOOL
2175 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2177 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2178 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2180 if (editor->bMouseCaptured)
2181 return FALSE;
2182 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2183 editor->nSelectionType = stPosition;
2185 switch (nKey)
2187 case VK_LEFT:
2188 case VK_RIGHT:
2189 case VK_HOME:
2190 case VK_END:
2191 editor->nUDArrowX = -1;
2192 /* fall through */
2193 case VK_UP:
2194 case VK_DOWN:
2195 case VK_PRIOR:
2196 case VK_NEXT:
2197 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2198 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2199 return TRUE;
2200 case VK_BACK:
2201 case VK_DELETE:
2202 editor->nUDArrowX = -1;
2203 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2204 if (editor->styleFlags & ES_READONLY)
2205 return FALSE;
2206 if (ME_IsSelection(editor))
2208 ME_DeleteSelection(editor);
2209 ME_CommitUndo(editor);
2211 else if (nKey == VK_DELETE)
2213 /* Delete stops group typing.
2214 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2215 ME_DeleteTextAtCursor(editor, 1, 1);
2216 ME_CommitUndo(editor);
2218 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2220 BOOL bDeletionSucceeded;
2221 /* Backspace can be grouped for a single undo */
2222 ME_ContinueCoalescingTransaction(editor);
2223 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2224 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2225 /* Deletion was prevented so the cursor is moved back to where it was.
2226 * (e.g. this happens when trying to delete cell boundaries)
2228 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2230 ME_CommitCoalescingUndo(editor);
2232 else
2233 return TRUE;
2234 ME_MoveCursorFromTableRowStartParagraph(editor);
2235 ME_UpdateSelectionLinkAttribute(editor);
2236 ME_UpdateRepaint(editor, FALSE);
2237 ME_SendRequestResize(editor, FALSE);
2238 return TRUE;
2239 case VK_RETURN:
2240 if (editor->bDialogMode)
2242 if (ctrl_is_down)
2243 return TRUE;
2245 if (!(editor->styleFlags & ES_WANTRETURN))
2247 if (editor->hwndParent)
2249 DWORD dw;
2250 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2251 if (HIWORD(dw) == DC_HASDEFID)
2253 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2254 if (hwDefCtrl)
2256 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2257 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2261 return TRUE;
2265 if (editor->styleFlags & ES_MULTILINE)
2267 ME_Cursor cursor = editor->pCursors[0];
2268 ME_DisplayItem *para = cursor.pPara;
2269 int from, to;
2270 const WCHAR endl = '\r';
2271 const WCHAR endlv10[] = {'\r','\n'};
2272 ME_Style *style;
2274 if (editor->styleFlags & ES_READONLY) {
2275 MessageBeep(MB_ICONERROR);
2276 return TRUE;
2279 ME_GetSelectionOfs(editor, &from, &to);
2280 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2282 if (!editor->bEmulateVersion10) { /* v4.1 */
2283 if (para->member.para.nFlags & MEPF_ROWEND) {
2284 /* Add a new table row after this row. */
2285 para = ME_AppendTableRow(editor, para);
2286 para = para->member.para.next_para;
2287 editor->pCursors[0].pPara = para;
2288 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2289 editor->pCursors[0].nOffset = 0;
2290 editor->pCursors[1] = editor->pCursors[0];
2291 ME_CommitUndo(editor);
2292 ME_CheckTablesForCorruption(editor);
2293 ME_UpdateRepaint(editor, FALSE);
2294 return TRUE;
2296 else if (para == editor->pCursors[1].pPara &&
2297 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2298 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2299 !para->member.para.prev_para->member.para.nCharOfs)
2301 /* Insert a newline before the table. */
2302 para = para->member.para.prev_para;
2303 para->member.para.nFlags &= ~MEPF_ROWSTART;
2304 editor->pCursors[0].pPara = para;
2305 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2306 editor->pCursors[1] = editor->pCursors[0];
2307 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2308 editor->pCursors[0].pRun->member.run.style);
2309 para = editor->pBuffer->pFirst->member.para.next_para;
2310 ME_SetDefaultParaFormat(para->member.para.pFmt);
2311 para->member.para.nFlags = MEPF_REWRAP;
2312 editor->pCursors[0].pPara = para;
2313 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2314 editor->pCursors[1] = editor->pCursors[0];
2315 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2316 ME_CommitCoalescingUndo(editor);
2317 ME_CheckTablesForCorruption(editor);
2318 ME_UpdateRepaint(editor, FALSE);
2319 return TRUE;
2321 } else { /* v1.0 - 3.0 */
2322 ME_DisplayItem *para = cursor.pPara;
2323 if (ME_IsInTable(para))
2325 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2327 if (from == to) {
2328 ME_ContinueCoalescingTransaction(editor);
2329 para = ME_AppendTableRow(editor, para);
2330 editor->pCursors[0].pPara = para;
2331 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2332 editor->pCursors[0].nOffset = 0;
2333 editor->pCursors[1] = editor->pCursors[0];
2334 ME_CommitCoalescingUndo(editor);
2335 ME_UpdateRepaint(editor, FALSE);
2336 return TRUE;
2338 } else {
2339 ME_ContinueCoalescingTransaction(editor);
2340 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2341 !ME_IsInTable(para->member.para.prev_para))
2343 /* Insert newline before table */
2344 cursor.pRun = ME_FindItemBack(para, diRun);
2345 if (cursor.pRun) {
2346 editor->pCursors[0].pRun = cursor.pRun;
2347 editor->pCursors[0].pPara = para->member.para.prev_para;
2349 editor->pCursors[0].nOffset = 0;
2350 editor->pCursors[1] = editor->pCursors[0];
2351 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2352 editor->pCursors[0].pRun->member.run.style);
2353 } else {
2354 editor->pCursors[1] = editor->pCursors[0];
2355 para = ME_AppendTableRow(editor, para);
2356 editor->pCursors[0].pPara = para;
2357 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2358 editor->pCursors[0].nOffset = 0;
2359 editor->pCursors[1] = editor->pCursors[0];
2361 ME_CommitCoalescingUndo(editor);
2362 ME_UpdateRepaint(editor, FALSE);
2363 return TRUE;
2368 style = ME_GetInsertStyle(editor, 0);
2369 ME_SaveTempStyle(editor);
2370 ME_ContinueCoalescingTransaction(editor);
2371 if (shift_is_down)
2372 ME_InsertEndRowFromCursor(editor, 0);
2373 else
2374 if (!editor->bEmulateVersion10)
2375 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2376 else
2377 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2378 ME_ReleaseStyle(style);
2379 ME_CommitCoalescingUndo(editor);
2380 SetCursor(NULL);
2382 ME_UpdateSelectionLinkAttribute(editor);
2383 ME_UpdateRepaint(editor, FALSE);
2385 return TRUE;
2387 break;
2388 case VK_ESCAPE:
2389 if (editor->bDialogMode && editor->hwndParent)
2390 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2391 return TRUE;
2392 case VK_TAB:
2393 if (editor->bDialogMode && editor->hwndParent)
2394 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2395 return TRUE;
2396 case 'A':
2397 if (ctrl_is_down)
2399 handle_EM_EXSETSEL( editor, 0, -1 );
2400 return TRUE;
2402 break;
2403 case 'V':
2404 if (ctrl_is_down)
2405 return ME_Paste(editor);
2406 break;
2407 case 'C':
2408 case 'X':
2409 if (ctrl_is_down)
2411 BOOL result;
2412 int nOfs, nChars;
2413 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2414 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2416 nChars -= nOfs;
2417 result = ME_Copy(editor, selStart, nChars);
2418 if (result && nKey == 'X')
2420 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2421 ME_CommitUndo(editor);
2422 ME_UpdateRepaint(editor, TRUE);
2424 return result;
2426 break;
2427 case 'Z':
2428 if (ctrl_is_down)
2430 ME_Undo(editor);
2431 return TRUE;
2433 break;
2434 case 'Y':
2435 if (ctrl_is_down)
2437 ME_Redo(editor);
2438 return TRUE;
2440 break;
2442 default:
2443 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2444 editor->nUDArrowX = -1;
2445 if (ctrl_is_down)
2447 if (nKey == 'W')
2449 CHARFORMAT2W chf;
2450 char buf[2048];
2451 chf.cbSize = sizeof(chf);
2453 ME_GetSelectionCharFormat(editor, &chf);
2454 ME_DumpStyleToBuf(&chf, buf);
2455 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2457 if (nKey == 'Q')
2459 ME_CheckCharOffsets(editor);
2463 return FALSE;
2466 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2467 LPARAM flags, BOOL unicode)
2469 WCHAR wstr;
2471 if (editor->bMouseCaptured)
2472 return 0;
2474 if (unicode)
2475 wstr = (WCHAR)charCode;
2476 else
2478 CHAR charA = charCode;
2479 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2482 if (editor->styleFlags & ES_READONLY) {
2483 MessageBeep(MB_ICONERROR);
2484 return 0; /* FIXME really 0 ? */
2487 if ((unsigned)wstr >= ' ' || wstr == '\t')
2489 ME_Cursor cursor = editor->pCursors[0];
2490 ME_DisplayItem *para = cursor.pPara;
2491 int from, to;
2492 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2493 ME_GetSelectionOfs(editor, &from, &to);
2494 if (wstr == '\t' &&
2495 /* v4.1 allows tabs to be inserted with ctrl key down */
2496 !(ctrl_is_down && !editor->bEmulateVersion10))
2498 ME_DisplayItem *para;
2499 BOOL bSelectedRow = FALSE;
2501 para = cursor.pPara;
2502 if (ME_IsSelection(editor) &&
2503 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2504 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2505 para->member.para.prev_para->type == diParagraph)
2507 para = para->member.para.prev_para;
2508 bSelectedRow = TRUE;
2510 if (ME_IsInTable(para))
2512 ME_TabPressedInTable(editor, bSelectedRow);
2513 ME_CommitUndo(editor);
2514 return 0;
2516 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2517 if (para->member.para.nFlags & MEPF_ROWEND) {
2518 if (from == to) {
2519 para = para->member.para.next_para;
2520 if (para->member.para.nFlags & MEPF_ROWSTART)
2521 para = para->member.para.next_para;
2522 editor->pCursors[0].pPara = para;
2523 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2524 editor->pCursors[0].nOffset = 0;
2525 editor->pCursors[1] = editor->pCursors[0];
2528 } else { /* v1.0 - 3.0 */
2529 if (ME_IsInTable(cursor.pRun) &&
2530 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2531 from == to)
2533 /* Text should not be inserted at the end of the table. */
2534 MessageBeep(-1);
2535 return 0;
2538 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2539 /* WM_CHAR is restricted to nTextLimit */
2540 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2542 ME_Style *style = ME_GetInsertStyle(editor, 0);
2543 ME_SaveTempStyle(editor);
2544 ME_ContinueCoalescingTransaction(editor);
2545 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2546 ME_ReleaseStyle(style);
2547 ME_CommitCoalescingUndo(editor);
2548 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2551 ME_UpdateSelectionLinkAttribute(editor);
2552 ME_UpdateRepaint(editor, FALSE);
2554 return 0;
2557 /* Process the message and calculate the new click count.
2559 * returns: The click count if it is mouse down event, else returns 0. */
2560 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2561 LPARAM lParam)
2563 static int clickNum = 0;
2564 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2565 return 0;
2567 if ((msg == WM_LBUTTONDBLCLK) ||
2568 (msg == WM_RBUTTONDBLCLK) ||
2569 (msg == WM_MBUTTONDBLCLK) ||
2570 (msg == WM_XBUTTONDBLCLK))
2572 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2575 if ((msg == WM_LBUTTONDOWN) ||
2576 (msg == WM_RBUTTONDOWN) ||
2577 (msg == WM_MBUTTONDOWN) ||
2578 (msg == WM_XBUTTONDOWN))
2580 static MSG prevClickMsg;
2581 MSG clickMsg;
2582 /* Compare the editor instead of the hwnd so that the this
2583 * can still be done for windowless richedit controls. */
2584 clickMsg.hwnd = (HWND)editor;
2585 clickMsg.message = msg;
2586 clickMsg.wParam = wParam;
2587 clickMsg.lParam = lParam;
2588 clickMsg.time = GetMessageTime();
2589 clickMsg.pt.x = (short)LOWORD(lParam);
2590 clickMsg.pt.y = (short)HIWORD(lParam);
2591 if ((clickNum != 0) &&
2592 (clickMsg.message == prevClickMsg.message) &&
2593 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2594 (clickMsg.wParam == prevClickMsg.wParam) &&
2595 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2596 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2597 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2599 clickNum++;
2600 } else {
2601 clickNum = 1;
2603 prevClickMsg = clickMsg;
2604 } else {
2605 return 0;
2607 return clickNum;
2610 static BOOL ME_SetCursor(ME_TextEditor *editor)
2612 ME_Cursor cursor;
2613 POINT pt;
2614 BOOL isExact;
2615 SCROLLBARINFO sbi;
2616 DWORD messagePos = GetMessagePos();
2617 pt.x = (short)LOWORD(messagePos);
2618 pt.y = (short)HIWORD(messagePos);
2620 if (editor->hWnd)
2622 sbi.cbSize = sizeof(sbi);
2623 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2624 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2625 PtInRect(&sbi.rcScrollBar, pt))
2627 ITextHost_TxSetCursor(editor->texthost,
2628 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2629 return TRUE;
2631 sbi.cbSize = sizeof(sbi);
2632 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2633 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2634 PtInRect(&sbi.rcScrollBar, pt))
2636 ITextHost_TxSetCursor(editor->texthost,
2637 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2638 return TRUE;
2641 ITextHost_TxScreenToClient(editor->texthost, &pt);
2643 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2644 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2645 return TRUE;
2647 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2648 pt.y < editor->rcFormat.top &&
2649 pt.x < editor->rcFormat.left)
2651 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2652 return TRUE;
2654 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2656 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2657 ITextHost_TxSetCursor(editor->texthost,
2658 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2659 else /* v4.1 */
2660 ITextHost_TxSetCursor(editor->texthost,
2661 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2662 return TRUE;
2664 if (pt.x < editor->rcFormat.left)
2666 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2667 return TRUE;
2669 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2670 if (isExact)
2672 ME_Run *run;
2674 run = &cursor.pRun->member.run;
2675 if (run->style->fmt.dwMask & CFM_LINK &&
2676 run->style->fmt.dwEffects & CFE_LINK)
2678 ITextHost_TxSetCursor(editor->texthost,
2679 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2680 FALSE);
2681 return TRUE;
2684 if (ME_IsSelection(editor))
2686 int selStart, selEnd;
2687 int offset = ME_GetCursorOfs(&cursor);
2689 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2690 if (selStart <= offset && selEnd >= offset) {
2691 ITextHost_TxSetCursor(editor->texthost,
2692 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2693 FALSE);
2694 return TRUE;
2698 ITextHost_TxSetCursor(editor->texthost,
2699 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2700 return TRUE;
2703 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2705 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2706 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2707 editor->rcFormat.left += 1 + editor->selofs;
2708 editor->rcFormat.right -= 1;
2711 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2713 CHARRANGE selrange;
2714 HMENU menu;
2715 int seltype = 0;
2716 if(!editor->lpOleCallback || !editor->hWnd)
2717 return FALSE;
2718 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2719 if(selrange.cpMin == selrange.cpMax)
2720 seltype |= SEL_EMPTY;
2721 else
2723 /* FIXME: Handle objects */
2724 seltype |= SEL_TEXT;
2725 if(selrange.cpMax-selrange.cpMin > 1)
2726 seltype |= SEL_MULTICHAR;
2728 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2730 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2731 DestroyMenu(menu);
2733 return TRUE;
2736 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2738 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2739 int i;
2740 DWORD props;
2741 LONG selbarwidth;
2743 ed->hWnd = NULL;
2744 ed->hwndParent = NULL;
2745 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2746 ed->texthost = texthost;
2747 ed->bEmulateVersion10 = bEmulateVersion10;
2748 ed->styleFlags = 0;
2749 ITextHost_TxGetPropertyBits(texthost,
2750 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2751 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2752 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2753 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2754 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2755 &props);
2756 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2757 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2758 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2759 ed->pBuffer = ME_MakeText();
2760 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2761 ed->nAvailWidth = 0; /* wrap to client area */
2762 ME_MakeFirstParagraph(ed);
2763 /* The four cursors are for:
2764 * 0 - The position where the caret is shown
2765 * 1 - The anchored end of the selection (for normal selection)
2766 * 2 & 3 - The anchored start and end respectively for word, line,
2767 * or paragraph selection.
2769 ed->nCursors = 4;
2770 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2771 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2772 ed->pCursors[1] = ed->pCursors[0];
2773 ed->pCursors[2] = ed->pCursors[0];
2774 ed->pCursors[3] = ed->pCursors[1];
2775 ed->nLastTotalLength = ed->nTotalLength = 0;
2776 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2777 ed->nUDArrowX = -1;
2778 ed->rgbBackColor = -1;
2779 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2780 ed->bCaretAtEnd = FALSE;
2781 ed->nEventMask = 0;
2782 ed->nModifyStep = 0;
2783 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2784 list_init( &ed->undo_stack );
2785 list_init( &ed->redo_stack );
2786 ed->nUndoStackSize = 0;
2787 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2788 ed->nUndoMode = umAddToUndo;
2789 ed->nParagraphs = 1;
2790 ed->nLastSelStart = ed->nLastSelEnd = 0;
2791 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2792 ed->bHideSelection = FALSE;
2793 ed->pfnWordBreak = NULL;
2794 ed->lpOleCallback = NULL;
2795 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2796 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2797 ed->AutoURLDetect_bEnable = FALSE;
2798 ed->bHaveFocus = FALSE;
2799 ed->bDialogMode = FALSE;
2800 ed->bMouseCaptured = FALSE;
2801 for (i=0; i<HFONT_CACHE_SIZE; i++)
2803 ed->pFontCache[i].nRefs = 0;
2804 ed->pFontCache[i].nAge = 0;
2805 ed->pFontCache[i].hFont = NULL;
2808 ME_CheckCharOffsets(ed);
2809 ed->bDefaultFormatRect = TRUE;
2810 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2811 if (selbarwidth) {
2812 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2813 ed->selofs = SELECTIONBAR_WIDTH;
2814 ed->styleFlags |= ES_SELECTIONBAR;
2815 } else {
2816 ed->selofs = 0;
2818 ed->nSelectionType = stPosition;
2820 ed->cPasswordMask = 0;
2821 if (props & TXTBIT_USEPASSWORD)
2822 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2824 if (props & TXTBIT_AUTOWORDSEL)
2825 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2826 if (props & TXTBIT_MULTILINE) {
2827 ed->styleFlags |= ES_MULTILINE;
2828 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2829 } else {
2830 ed->bWordWrap = FALSE;
2832 if (props & TXTBIT_READONLY)
2833 ed->styleFlags |= ES_READONLY;
2834 if (!(props & TXTBIT_HIDESELECTION))
2835 ed->styleFlags |= ES_NOHIDESEL;
2836 if (props & TXTBIT_SAVESELECTION)
2837 ed->styleFlags |= ES_SAVESEL;
2838 if (props & TXTBIT_VERTICAL)
2839 ed->styleFlags |= ES_VERTICAL;
2840 if (props & TXTBIT_DISABLEDRAG)
2841 ed->styleFlags |= ES_NOOLEDRAGDROP;
2843 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2845 /* Default scrollbar information */
2846 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2847 ed->vert_si.nMin = 0;
2848 ed->vert_si.nMax = 0;
2849 ed->vert_si.nPage = 0;
2850 ed->vert_si.nPos = 0;
2852 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2853 ed->horz_si.nMin = 0;
2854 ed->horz_si.nMax = 0;
2855 ed->horz_si.nPage = 0;
2856 ed->horz_si.nPos = 0;
2858 ed->wheel_remain = 0;
2860 OleInitialize(NULL);
2862 return ed;
2865 static void ME_DestroyEditor(ME_TextEditor *editor)
2867 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2868 ME_DisplayItem *p = pFirst, *pNext = NULL;
2869 int i;
2871 ME_ClearTempStyle(editor);
2872 ME_EmptyUndoStack(editor);
2873 while(p) {
2874 pNext = p->next;
2875 ME_DestroyDisplayItem(p);
2876 p = pNext;
2878 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2879 for (i=0; i<HFONT_CACHE_SIZE; i++)
2881 if (editor->pFontCache[i].hFont)
2882 DeleteObject(editor->pFontCache[i].hFont);
2884 if (editor->rgbBackColor != -1)
2885 DeleteObject(editor->hbrBackground);
2886 if(editor->lpOleCallback)
2887 IRichEditOleCallback_Release(editor->lpOleCallback);
2888 ITextHost_Release(editor->texthost);
2889 OleUninitialize();
2891 FREE_OBJ(editor->pBuffer);
2892 FREE_OBJ(editor->pCursors);
2894 FREE_OBJ(editor);
2897 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2899 TRACE("\n");
2900 switch (fdwReason)
2902 case DLL_PROCESS_ATTACH:
2903 DisableThreadLibraryCalls(hinstDLL);
2904 me_heap = HeapCreate (0, 0x10000, 0);
2905 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2906 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2907 LookupInit();
2908 break;
2910 case DLL_PROCESS_DETACH:
2911 if (lpvReserved) break;
2912 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2913 UnregisterClassW(MSFTEDIT_CLASS, 0);
2914 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2915 UnregisterClassA("RichEdit50A", 0);
2916 if (ME_ListBoxRegistered)
2917 UnregisterClassW(REListBox20W, 0);
2918 if (ME_ComboBoxRegistered)
2919 UnregisterClassW(REComboBox20W, 0);
2920 LookupCleanup();
2921 HeapDestroy (me_heap);
2922 break;
2924 return TRUE;
2927 static inline int get_default_line_height( ME_TextEditor *editor )
2929 int height = 0;
2931 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2932 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2933 if (height <= 0) height = 24;
2935 return height;
2938 static inline int calc_wheel_change( int *remain, int amount_per_click )
2940 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2941 *remain -= WHEEL_DELTA * change / amount_per_click;
2942 return change;
2945 static const char * const edit_messages[] = {
2946 "EM_GETSEL",
2947 "EM_SETSEL",
2948 "EM_GETRECT",
2949 "EM_SETRECT",
2950 "EM_SETRECTNP",
2951 "EM_SCROLL",
2952 "EM_LINESCROLL",
2953 "EM_SCROLLCARET",
2954 "EM_GETMODIFY",
2955 "EM_SETMODIFY",
2956 "EM_GETLINECOUNT",
2957 "EM_LINEINDEX",
2958 "EM_SETHANDLE",
2959 "EM_GETHANDLE",
2960 "EM_GETTHUMB",
2961 "EM_UNKNOWN_BF",
2962 "EM_UNKNOWN_C0",
2963 "EM_LINELENGTH",
2964 "EM_REPLACESEL",
2965 "EM_UNKNOWN_C3",
2966 "EM_GETLINE",
2967 "EM_LIMITTEXT",
2968 "EM_CANUNDO",
2969 "EM_UNDO",
2970 "EM_FMTLINES",
2971 "EM_LINEFROMCHAR",
2972 "EM_UNKNOWN_CA",
2973 "EM_SETTABSTOPS",
2974 "EM_SETPASSWORDCHAR",
2975 "EM_EMPTYUNDOBUFFER",
2976 "EM_GETFIRSTVISIBLELINE",
2977 "EM_SETREADONLY",
2978 "EM_SETWORDBREAKPROC",
2979 "EM_GETWORDBREAKPROC",
2980 "EM_GETPASSWORDCHAR",
2981 "EM_SETMARGINS",
2982 "EM_GETMARGINS",
2983 "EM_GETLIMITTEXT",
2984 "EM_POSFROMCHAR",
2985 "EM_CHARFROMPOS",
2986 "EM_SETIMESTATUS",
2987 "EM_GETIMESTATUS"
2990 static const char * const richedit_messages[] = {
2991 "EM_CANPASTE",
2992 "EM_DISPLAYBAND",
2993 "EM_EXGETSEL",
2994 "EM_EXLIMITTEXT",
2995 "EM_EXLINEFROMCHAR",
2996 "EM_EXSETSEL",
2997 "EM_FINDTEXT",
2998 "EM_FORMATRANGE",
2999 "EM_GETCHARFORMAT",
3000 "EM_GETEVENTMASK",
3001 "EM_GETOLEINTERFACE",
3002 "EM_GETPARAFORMAT",
3003 "EM_GETSELTEXT",
3004 "EM_HIDESELECTION",
3005 "EM_PASTESPECIAL",
3006 "EM_REQUESTRESIZE",
3007 "EM_SELECTIONTYPE",
3008 "EM_SETBKGNDCOLOR",
3009 "EM_SETCHARFORMAT",
3010 "EM_SETEVENTMASK",
3011 "EM_SETOLECALLBACK",
3012 "EM_SETPARAFORMAT",
3013 "EM_SETTARGETDEVICE",
3014 "EM_STREAMIN",
3015 "EM_STREAMOUT",
3016 "EM_GETTEXTRANGE",
3017 "EM_FINDWORDBREAK",
3018 "EM_SETOPTIONS",
3019 "EM_GETOPTIONS",
3020 "EM_FINDTEXTEX",
3021 "EM_GETWORDBREAKPROCEX",
3022 "EM_SETWORDBREAKPROCEX",
3023 "EM_SETUNDOLIMIT",
3024 "EM_UNKNOWN_USER_83",
3025 "EM_REDO",
3026 "EM_CANREDO",
3027 "EM_GETUNDONAME",
3028 "EM_GETREDONAME",
3029 "EM_STOPGROUPTYPING",
3030 "EM_SETTEXTMODE",
3031 "EM_GETTEXTMODE",
3032 "EM_AUTOURLDETECT",
3033 "EM_GETAUTOURLDETECT",
3034 "EM_SETPALETTE",
3035 "EM_GETTEXTEX",
3036 "EM_GETTEXTLENGTHEX",
3037 "EM_SHOWSCROLLBAR",
3038 "EM_SETTEXTEX",
3039 "EM_UNKNOWN_USER_98",
3040 "EM_UNKNOWN_USER_99",
3041 "EM_SETPUNCTUATION",
3042 "EM_GETPUNCTUATION",
3043 "EM_SETWORDWRAPMODE",
3044 "EM_GETWORDWRAPMODE",
3045 "EM_SETIMECOLOR",
3046 "EM_GETIMECOLOR",
3047 "EM_SETIMEOPTIONS",
3048 "EM_GETIMEOPTIONS",
3049 "EM_CONVPOSITION",
3050 "EM_UNKNOWN_USER_109",
3051 "EM_UNKNOWN_USER_110",
3052 "EM_UNKNOWN_USER_111",
3053 "EM_UNKNOWN_USER_112",
3054 "EM_UNKNOWN_USER_113",
3055 "EM_UNKNOWN_USER_114",
3056 "EM_UNKNOWN_USER_115",
3057 "EM_UNKNOWN_USER_116",
3058 "EM_UNKNOWN_USER_117",
3059 "EM_UNKNOWN_USER_118",
3060 "EM_UNKNOWN_USER_119",
3061 "EM_SETLANGOPTIONS",
3062 "EM_GETLANGOPTIONS",
3063 "EM_GETIMECOMPMODE",
3064 "EM_FINDTEXTW",
3065 "EM_FINDTEXTEXW",
3066 "EM_RECONVERSION",
3067 "EM_SETIMEMODEBIAS",
3068 "EM_GETIMEMODEBIAS"
3071 static const char *
3072 get_msg_name(UINT msg)
3074 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3075 return edit_messages[msg - EM_GETSEL];
3076 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3077 return richedit_messages[msg - EM_CANPASTE];
3078 return "";
3081 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3083 int x,y;
3084 BOOL isExact;
3085 ME_Cursor cursor; /* The start of the clicked text. */
3087 ENLINK info;
3088 x = (short)LOWORD(lParam);
3089 y = (short)HIWORD(lParam);
3090 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3091 if (!isExact) return;
3093 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3094 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3095 { /* The clicked run has CFE_LINK set */
3096 ME_DisplayItem *di;
3098 info.nmhdr.hwndFrom = NULL;
3099 info.nmhdr.idFrom = 0;
3100 info.nmhdr.code = EN_LINK;
3101 info.msg = msg;
3102 info.wParam = wParam;
3103 info.lParam = lParam;
3104 cursor.nOffset = 0;
3106 /* find the first contiguous run with CFE_LINK set */
3107 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3108 for (di = cursor.pRun->prev;
3109 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3110 di = di->prev)
3112 info.chrg.cpMin -= di->member.run.len;
3115 /* find the last contiguous run with CFE_LINK set */
3116 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3117 for (di = cursor.pRun->next;
3118 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3119 di = di->next)
3121 info.chrg.cpMax += di->member.run.len;
3124 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3128 #define UNSUPPORTED_MSG(e) \
3129 case e: \
3130 FIXME(#e ": stub\n"); \
3131 *phresult = S_FALSE; \
3132 return 0;
3134 /* Handle messages for windowless and windoweded richedit controls.
3136 * The LRESULT that is returned is a return value for window procs,
3137 * and the phresult parameter is the COM return code needed by the
3138 * text services interface. */
3139 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3140 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3142 *phresult = S_OK;
3144 switch(msg) {
3146 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3147 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3148 UNSUPPORTED_MSG(EM_FMTLINES)
3149 UNSUPPORTED_MSG(EM_FORMATRANGE)
3150 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3151 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3152 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3153 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3154 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3155 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3156 UNSUPPORTED_MSG(EM_GETREDONAME)
3157 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3158 UNSUPPORTED_MSG(EM_GETUNDONAME)
3159 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3160 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3161 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3162 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3163 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3164 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3165 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3166 UNSUPPORTED_MSG(EM_SETMARGINS)
3167 UNSUPPORTED_MSG(EM_SETPALETTE)
3168 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3169 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3170 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3172 /* Messages specific to Richedit controls */
3174 case EM_STREAMIN:
3175 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3176 case EM_STREAMOUT:
3177 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3178 case WM_GETDLGCODE:
3180 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3182 if (lParam)
3183 editor->bDialogMode = TRUE;
3184 if (editor->styleFlags & ES_MULTILINE)
3185 code |= DLGC_WANTMESSAGE;
3186 if (!(editor->styleFlags & ES_SAVESEL))
3187 code |= DLGC_HASSETSEL;
3188 return code;
3190 case EM_EMPTYUNDOBUFFER:
3191 ME_EmptyUndoStack(editor);
3192 return 0;
3193 case EM_GETSEL:
3195 /* Note: wParam/lParam can be NULL */
3196 UINT from, to;
3197 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3198 PUINT pto = lParam ? (PUINT)lParam : &to;
3199 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3200 if ((*pfrom|*pto) & 0xFFFF0000)
3201 return -1;
3202 return MAKELONG(*pfrom,*pto);
3204 case EM_EXGETSEL:
3206 CHARRANGE *pRange = (CHARRANGE *)lParam;
3207 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3208 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3209 return 0;
3211 case EM_SETUNDOLIMIT:
3213 if ((int)wParam < 0)
3214 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3215 else
3216 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3217 /* Setting a max stack size keeps wine from getting killed
3218 for hogging memory. Windows allocates all this memory at once, so
3219 no program would realistically set a value above our maximum. */
3220 return editor->nUndoLimit;
3222 case EM_CANUNDO:
3223 return !list_empty( &editor->undo_stack );
3224 case EM_CANREDO:
3225 return !list_empty( &editor->redo_stack );
3226 case WM_UNDO: /* FIXME: actually not the same */
3227 case EM_UNDO:
3228 return ME_Undo(editor);
3229 case EM_REDO:
3230 return ME_Redo(editor);
3231 case EM_GETOPTIONS:
3233 /* these flags are equivalent to the ES_* counterparts */
3234 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3235 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3236 DWORD settings = editor->styleFlags & mask;
3238 return settings;
3240 case EM_SETOPTIONS:
3242 /* these flags are equivalent to ES_* counterparts, except for
3243 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3244 * but is still stored in editor->styleFlags. */
3245 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3246 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3247 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3248 DWORD settings = mask & editor->styleFlags;
3249 DWORD oldSettings = settings;
3250 DWORD changedSettings;
3252 switch(wParam)
3254 case ECOOP_SET:
3255 settings = lParam;
3256 break;
3257 case ECOOP_OR:
3258 settings |= lParam;
3259 break;
3260 case ECOOP_AND:
3261 settings &= lParam;
3262 break;
3263 case ECOOP_XOR:
3264 settings ^= lParam;
3266 changedSettings = oldSettings ^ settings;
3268 if (changedSettings) {
3269 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3271 if (changedSettings & ECO_SELECTIONBAR)
3273 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3274 if (settings & ECO_SELECTIONBAR) {
3275 assert(!editor->selofs);
3276 editor->selofs = SELECTIONBAR_WIDTH;
3277 editor->rcFormat.left += editor->selofs;
3278 } else {
3279 editor->rcFormat.left -= editor->selofs;
3280 editor->selofs = 0;
3282 ME_RewrapRepaint(editor);
3285 if (changedSettings & settings & ECO_VERTICAL)
3286 FIXME("ECO_VERTICAL not implemented yet!\n");
3287 if (changedSettings & settings & ECO_AUTOHSCROLL)
3288 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3289 if (changedSettings & settings & ECO_AUTOVSCROLL)
3290 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3291 if (changedSettings & settings & ECO_NOHIDESEL)
3292 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3293 if (changedSettings & settings & ECO_WANTRETURN)
3294 FIXME("ECO_WANTRETURN not implemented yet!\n");
3295 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3296 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3299 return settings;
3301 case EM_SETSEL:
3303 handle_EM_EXSETSEL( editor, wParam, lParam );
3304 return 0;
3306 case EM_SETSCROLLPOS:
3308 POINT *point = (POINT *)lParam;
3309 ME_ScrollAbs(editor, point->x, point->y);
3310 return 0;
3312 case EM_AUTOURLDETECT:
3314 if (wParam==1 || wParam ==0)
3316 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3317 return 0;
3319 return E_INVALIDARG;
3321 case EM_GETAUTOURLDETECT:
3323 return editor->AutoURLDetect_bEnable;
3325 case EM_EXSETSEL:
3327 CHARRANGE range = *(CHARRANGE *)lParam;
3329 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3331 case EM_SHOWSCROLLBAR:
3333 DWORD flags;
3335 switch (wParam)
3337 case SB_HORZ:
3338 flags = WS_HSCROLL;
3339 break;
3340 case SB_VERT:
3341 flags = WS_VSCROLL;
3342 break;
3343 case SB_BOTH:
3344 flags = WS_HSCROLL|WS_VSCROLL;
3345 break;
3346 default:
3347 return 0;
3350 if (lParam) {
3351 editor->styleFlags |= flags;
3352 if (flags & WS_HSCROLL)
3353 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3354 editor->nTotalWidth > editor->sizeWindow.cx);
3355 if (flags & WS_VSCROLL)
3356 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3357 editor->nTotalLength > editor->sizeWindow.cy);
3358 } else {
3359 editor->styleFlags &= ~flags;
3360 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3362 return 0;
3364 case EM_SETTEXTEX:
3366 LPWSTR wszText;
3367 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3368 int from, to, len;
3369 ME_Style *style;
3370 BOOL bRtf, bUnicode, bSelection, bUTF8;
3371 int oldModify = editor->nModifyStep;
3372 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3374 if (!pStruct) return 0;
3376 /* If we detect ascii rtf at the start of the string,
3377 * we know it isn't unicode. */
3378 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3379 !strncmp((char *)lParam, "{\\urtf", 6)));
3380 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3381 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3383 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3384 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3385 pStruct->flags, pStruct->codepage);
3387 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3388 if (bSelection) {
3389 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3390 style = ME_GetSelectionInsertStyle(editor);
3391 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3392 } else {
3393 ME_Cursor start;
3394 ME_SetCursorToStart(editor, &start);
3395 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3396 style = editor->pBuffer->pDefaultStyle;
3399 if (bRtf) {
3400 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3401 if (bSelection) {
3402 /* FIXME: The length returned doesn't include the rtf control
3403 * characters, only the actual text. */
3404 len = lParam ? strlen((char *)lParam) : 0;
3406 } else {
3407 if (bUTF8 && !bUnicode) {
3408 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3409 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3410 ME_EndToUnicode(CP_UTF8, wszText);
3411 } else {
3412 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3413 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3414 ME_EndToUnicode(pStruct->codepage, wszText);
3418 if (bSelection) {
3419 ME_ReleaseStyle(style);
3420 ME_UpdateSelectionLinkAttribute(editor);
3421 } else {
3422 ME_Cursor cursor;
3423 len = 1;
3424 ME_SetCursorToStart(editor, &cursor);
3425 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3427 ME_CommitUndo(editor);
3428 if (!(pStruct->flags & ST_KEEPUNDO))
3430 editor->nModifyStep = oldModify;
3431 ME_EmptyUndoStack(editor);
3433 ME_UpdateRepaint(editor, FALSE);
3434 return len;
3436 case EM_SETBKGNDCOLOR:
3438 LRESULT lColor;
3439 if (editor->rgbBackColor != -1) {
3440 DeleteObject(editor->hbrBackground);
3441 lColor = editor->rgbBackColor;
3443 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3445 if (wParam)
3447 editor->rgbBackColor = -1;
3448 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3450 else
3452 editor->rgbBackColor = lParam;
3453 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3455 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3456 ITextHost_TxViewChange(editor->texthost, TRUE);
3457 return lColor;
3459 case EM_GETMODIFY:
3460 return editor->nModifyStep == 0 ? 0 : -1;
3461 case EM_SETMODIFY:
3463 if (wParam)
3464 editor->nModifyStep = 1;
3465 else
3466 editor->nModifyStep = 0;
3468 return 0;
3470 case EM_SETREADONLY:
3472 if (wParam)
3473 editor->styleFlags |= ES_READONLY;
3474 else
3475 editor->styleFlags &= ~ES_READONLY;
3476 return 0;
3478 case EM_SETEVENTMASK:
3480 DWORD nOldMask = editor->nEventMask;
3482 editor->nEventMask = lParam;
3483 return nOldMask;
3485 case EM_GETEVENTMASK:
3486 return editor->nEventMask;
3487 case EM_SETCHARFORMAT:
3489 CHARFORMAT2W buf, *p;
3490 BOOL bRepaint = TRUE;
3491 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3492 if (p == NULL) return 0;
3493 if (wParam & SCF_ALL) {
3494 if (editor->mode & TM_PLAINTEXT) {
3495 ME_SetDefaultCharFormat(editor, p);
3496 } else {
3497 ME_Cursor start;
3498 ME_SetCursorToStart(editor, &start);
3499 ME_SetCharFormat(editor, &start, NULL, p);
3500 editor->nModifyStep = 1;
3502 } else if (wParam & SCF_SELECTION) {
3503 if (editor->mode & TM_PLAINTEXT)
3504 return 0;
3505 if (wParam & SCF_WORD) {
3506 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3507 return 0;
3509 bRepaint = ME_IsSelection(editor);
3510 ME_SetSelectionCharFormat(editor, p);
3511 if (bRepaint) editor->nModifyStep = 1;
3512 } else { /* SCF_DEFAULT */
3513 ME_SetDefaultCharFormat(editor, p);
3515 ME_CommitUndo(editor);
3516 if (bRepaint)
3518 ME_WrapMarkedParagraphs(editor);
3519 ME_UpdateScrollBar(editor);
3520 ME_Repaint(editor);
3522 return 1;
3524 case EM_GETCHARFORMAT:
3526 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3527 if (dst->cbSize != sizeof(CHARFORMATA) &&
3528 dst->cbSize != sizeof(CHARFORMATW) &&
3529 dst->cbSize != sizeof(CHARFORMAT2A) &&
3530 dst->cbSize != sizeof(CHARFORMAT2W))
3531 return 0;
3532 tmp.cbSize = sizeof(tmp);
3533 if (!wParam)
3534 ME_GetDefaultCharFormat(editor, &tmp);
3535 else
3536 ME_GetSelectionCharFormat(editor, &tmp);
3537 ME_CopyToCFAny(dst, &tmp);
3538 return tmp.dwMask;
3540 case EM_SETPARAFORMAT:
3542 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3543 ME_WrapMarkedParagraphs(editor);
3544 ME_UpdateScrollBar(editor);
3545 ME_Repaint(editor);
3546 ME_CommitUndo(editor);
3547 return result;
3549 case EM_GETPARAFORMAT:
3550 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3551 return ((PARAFORMAT2 *)lParam)->dwMask;
3552 case EM_GETFIRSTVISIBLELINE:
3554 ME_DisplayItem *p = editor->pBuffer->pFirst;
3555 int y = editor->vert_si.nPos;
3556 int ypara = 0;
3557 int count = 0;
3558 int ystart, yend;
3559 while(p) {
3560 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3561 if (p->type == diTextEnd)
3562 break;
3563 if (p->type == diParagraph) {
3564 ypara = p->member.para.pt.y;
3565 continue;
3567 ystart = ypara + p->member.row.pt.y;
3568 yend = ystart + p->member.row.nHeight;
3569 if (y < yend) {
3570 break;
3572 count++;
3574 return count;
3576 case EM_HIDESELECTION:
3578 editor->bHideSelection = (wParam != 0);
3579 ME_InvalidateSelection(editor);
3580 return 0;
3582 case EM_LINESCROLL:
3584 if (!(editor->styleFlags & ES_MULTILINE))
3585 return FALSE;
3586 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3587 return TRUE;
3589 case WM_CLEAR:
3591 int from, to;
3592 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3593 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3594 ME_CommitUndo(editor);
3595 ME_UpdateRepaint(editor, TRUE);
3596 return 0;
3598 case EM_REPLACESEL:
3600 int from, to, nStartCursor;
3601 ME_Style *style;
3602 int len = 0;
3603 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3604 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3605 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3607 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3608 style = ME_GetSelectionInsertStyle(editor);
3609 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3610 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3611 ME_ReleaseStyle(style);
3612 /* drop temporary style if line end */
3614 * FIXME question: does abc\n mean: put abc,
3615 * clear temp style, put \n? (would require a change)
3617 if (len>0 && wszText[len-1] == '\n')
3618 ME_ClearTempStyle(editor);
3619 ME_EndToUnicode(codepage, wszText);
3620 ME_CommitUndo(editor);
3621 ME_UpdateSelectionLinkAttribute(editor);
3622 if (!wParam)
3623 ME_EmptyUndoStack(editor);
3624 ME_UpdateRepaint(editor, FALSE);
3625 return len;
3627 case EM_SCROLLCARET:
3628 ME_EnsureVisible(editor, &editor->pCursors[0]);
3629 return 0;
3630 case WM_SETFONT:
3632 LOGFONTW lf;
3633 CHARFORMAT2W fmt;
3634 HDC hDC;
3635 BOOL bRepaint = LOWORD(lParam);
3637 if (!wParam)
3638 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3639 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3640 hDC = ITextHost_TxGetDC(editor->texthost);
3641 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3642 ITextHost_TxReleaseDC(editor->texthost, hDC);
3643 if (editor->mode & TM_RICHTEXT) {
3644 ME_Cursor start;
3645 ME_SetCursorToStart(editor, &start);
3646 ME_SetCharFormat(editor, &start, NULL, &fmt);
3648 ME_SetDefaultCharFormat(editor, &fmt);
3650 ME_CommitUndo(editor);
3651 ME_MarkAllForWrapping(editor);
3652 ME_WrapMarkedParagraphs(editor);
3653 ME_UpdateScrollBar(editor);
3654 if (bRepaint)
3655 ME_Repaint(editor);
3656 return 0;
3658 case WM_SETTEXT:
3660 ME_Cursor cursor;
3661 ME_SetCursorToStart(editor, &cursor);
3662 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3663 if (lParam)
3665 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3666 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3667 !strncmp((char *)lParam, "{\\urtf", 6))
3669 /* Undocumented: WM_SETTEXT supports RTF text */
3670 ME_StreamInRTFString(editor, 0, (char *)lParam);
3672 else
3674 int textLen;
3675 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3676 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3677 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3678 if (textLen > 0)
3680 int len = -1;
3682 /* uses default style! */
3683 if (!(editor->styleFlags & ES_MULTILINE))
3685 WCHAR * p;
3687 p = wszText;
3688 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3689 len = p - wszText;
3691 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3693 ME_EndToUnicode(codepage, wszText);
3696 else
3697 TRACE("WM_SETTEXT - NULL\n");
3698 ME_SetCursorToStart(editor, &cursor);
3699 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3700 ME_SetSelection(editor, 0, 0);
3701 editor->nModifyStep = 0;
3702 ME_CommitUndo(editor);
3703 ME_EmptyUndoStack(editor);
3704 ME_UpdateRepaint(editor, FALSE);
3705 return 1;
3707 case EM_CANPASTE:
3709 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3710 if (IsClipboardFormatAvailable(nRTFFormat))
3711 return TRUE;
3712 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3713 return TRUE;
3714 return FALSE;
3716 case WM_PASTE:
3717 case WM_MBUTTONDOWN:
3718 ME_Paste(editor);
3719 return 0;
3720 case WM_CUT:
3721 case WM_COPY:
3723 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3724 int nChars = nTo - nFrom;
3725 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3727 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3729 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3730 ME_CommitUndo(editor);
3731 ME_UpdateRepaint(editor, TRUE);
3733 return 0;
3735 case WM_GETTEXTLENGTH:
3737 GETTEXTLENGTHEX how;
3739 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3740 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3741 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3742 return ME_GetTextLengthEx(editor, &how);
3744 case EM_GETTEXTLENGTHEX:
3745 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3746 case WM_GETTEXT:
3748 GETTEXTEX ex;
3749 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3750 ex.flags = GT_USECRLF;
3751 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3752 ex.lpDefaultChar = NULL;
3753 ex.lpUsedDefChar = NULL;
3754 return ME_GetTextEx(editor, &ex, lParam);
3756 case EM_GETTEXTEX:
3757 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3758 case EM_GETSELTEXT:
3760 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3761 ME_Cursor *from = &editor->pCursors[nStartCur];
3762 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3763 nTo - nFrom, unicode);
3765 case EM_GETSCROLLPOS:
3767 POINT *point = (POINT *)lParam;
3768 point->x = editor->horz_si.nPos;
3769 point->y = editor->vert_si.nPos;
3770 /* 16-bit scaled value is returned as stored in scrollinfo */
3771 if (editor->horz_si.nMax > 0xffff)
3772 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3773 if (editor->vert_si.nMax > 0xffff)
3774 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3775 return 1;
3777 case EM_GETTEXTRANGE:
3779 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3780 ME_Cursor start;
3781 int nStart = rng->chrg.cpMin;
3782 int nEnd = rng->chrg.cpMax;
3783 int textlength = ME_GetTextLength(editor);
3785 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3786 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3787 if (nStart < 0) return 0;
3788 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3789 nEnd = textlength;
3790 if (nStart >= nEnd) return 0;
3792 ME_CursorFromCharOfs(editor, nStart, &start);
3793 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3795 case EM_GETLINE:
3797 ME_DisplayItem *run;
3798 const unsigned int nMaxChars = *(WORD *) lParam;
3799 unsigned int nCharsLeft = nMaxChars;
3800 char *dest = (char *) lParam;
3801 BOOL wroteNull = FALSE;
3803 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3804 unicode ? "Unicode" : "Ansi");
3806 run = ME_FindRowWithNumber(editor, wParam);
3807 if (run == NULL)
3808 return 0;
3810 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3811 && run->type == diRun)
3813 WCHAR *str = get_text( &run->member.run, 0 );
3814 unsigned int nCopy;
3816 nCopy = min(nCharsLeft, run->member.run.len);
3818 if (unicode)
3819 memcpy(dest, str, nCopy * sizeof(WCHAR));
3820 else
3821 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3822 nCharsLeft, NULL, NULL);
3823 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3824 nCharsLeft -= nCopy;
3827 /* append line termination, space allowing */
3828 if (nCharsLeft > 0)
3830 if (unicode)
3831 *((WCHAR *)dest) = '\0';
3832 else
3833 *dest = '\0';
3834 nCharsLeft--;
3835 wroteNull = TRUE;
3838 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3839 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3841 case EM_GETLINECOUNT:
3843 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3844 int nRows = 0;
3846 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3848 while (item != editor->pBuffer->pLast)
3850 assert(item->type == diParagraph);
3851 prev_para = ME_FindItemBack(item, diRun);
3852 if (prev_para) {
3853 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3855 nRows += item->member.para.nRows;
3856 item = item->member.para.next_para;
3858 last_para = ME_FindItemBack(item, diRun);
3859 assert(last_para);
3860 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3861 if (editor->bEmulateVersion10 && prev_para &&
3862 last_para->member.run.nCharOfs == 0 &&
3863 prev_para->member.run.len == 1 &&
3864 *get_text( &prev_para->member.run, 0 ) == '\r')
3866 /* In 1.0 emulation, the last solitary \r at the very end of the text
3867 (if one exists) is NOT a line break.
3868 FIXME: this is an ugly hack. This should have a more regular model. */
3869 nRows--;
3872 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3873 return max(1, nRows);
3875 case EM_LINEFROMCHAR:
3877 if (wParam == -1)
3878 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3879 else
3880 return ME_RowNumberFromCharOfs(editor, wParam);
3882 case EM_EXLINEFROMCHAR:
3884 if (lParam == -1)
3885 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3886 else
3887 return ME_RowNumberFromCharOfs(editor, lParam);
3889 case EM_LINEINDEX:
3891 ME_DisplayItem *item, *para;
3892 int nCharOfs;
3894 if (wParam == -1)
3895 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3896 else
3897 item = ME_FindRowWithNumber(editor, wParam);
3898 if (!item)
3899 return -1;
3900 para = ME_GetParagraph(item);
3901 item = ME_FindItemFwd(item, diRun);
3902 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3903 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3904 return nCharOfs;
3906 case EM_LINELENGTH:
3908 ME_DisplayItem *item, *item_end;
3909 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3910 ME_DisplayItem *para, *run;
3912 if (wParam > ME_GetTextLength(editor))
3913 return 0;
3914 if (wParam == -1)
3916 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3917 return 0;
3919 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3920 item = ME_RowStart(run);
3921 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3922 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3923 if (item_end->type == diStartRow) {
3924 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3925 } else {
3926 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3927 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3928 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3930 nChars = nNextLineOfs - nThisLineOfs;
3931 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3932 return nChars;
3934 case EM_EXLIMITTEXT:
3936 if ((int)lParam < 0)
3937 return 0;
3938 if (lParam == 0)
3939 editor->nTextLimit = 65536;
3940 else
3941 editor->nTextLimit = (int) lParam;
3942 return 0;
3944 case EM_LIMITTEXT:
3946 if (wParam == 0)
3947 editor->nTextLimit = 65536;
3948 else
3949 editor->nTextLimit = (int) wParam;
3950 return 0;
3952 case EM_GETLIMITTEXT:
3954 return editor->nTextLimit;
3956 case EM_FINDTEXT:
3958 LRESULT r;
3959 if(!unicode){
3960 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3961 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3962 WCHAR *tmp;
3964 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3965 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3966 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3967 FREE_OBJ( tmp );
3968 }else{
3969 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3970 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3972 return r;
3974 case EM_FINDTEXTEX:
3976 LRESULT r;
3977 if(!unicode){
3978 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3979 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3980 WCHAR *tmp;
3982 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3983 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3984 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3985 FREE_OBJ( tmp );
3986 }else{
3987 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3988 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3990 return r;
3992 case EM_FINDTEXTW:
3994 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3995 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3997 case EM_FINDTEXTEXW:
3999 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4000 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4002 case EM_GETZOOM:
4003 if (!wParam || !lParam)
4004 return FALSE;
4005 *(int *)wParam = editor->nZoomNumerator;
4006 *(int *)lParam = editor->nZoomDenominator;
4007 return TRUE;
4008 case EM_SETZOOM:
4009 return ME_SetZoom(editor, wParam, lParam);
4010 case EM_CHARFROMPOS:
4012 ME_Cursor cursor;
4013 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4014 &cursor, NULL))
4015 return ME_GetCursorOfs(&cursor);
4016 else
4017 return -1;
4019 case EM_POSFROMCHAR:
4021 ME_DisplayItem *pPara, *pRun;
4022 int nCharOfs, nOffset, nLength;
4023 POINTL pt = {0,0};
4025 nCharOfs = wParam;
4026 /* detect which API version we're dealing with */
4027 if (wParam >= 0x40000)
4028 nCharOfs = lParam;
4029 nLength = ME_GetTextLength(editor);
4030 nCharOfs = min(nCharOfs, nLength);
4031 nCharOfs = max(nCharOfs, 0);
4033 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4034 assert(pRun->type == diRun);
4035 pt.y = pRun->member.run.pt.y;
4036 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4037 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4038 pt.x += editor->rcFormat.left;
4040 pt.x -= editor->horz_si.nPos;
4041 pt.y -= editor->vert_si.nPos;
4043 if (wParam >= 0x40000) {
4044 *(POINTL *)wParam = pt;
4046 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4048 case WM_CREATE:
4050 void *text = NULL;
4051 INT max;
4053 ME_SetDefaultFormatRect(editor);
4055 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4056 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4057 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4059 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4060 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4062 if (editor->styleFlags & ES_DISABLENOSCROLL)
4064 if (editor->styleFlags & WS_VSCROLL)
4066 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4067 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4069 if (editor->styleFlags & WS_HSCROLL)
4071 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4072 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4076 if (lParam)
4078 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4079 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4081 if (text)
4083 WCHAR *textW;
4084 int len;
4085 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4086 textW = ME_ToUnicode(codepage, text, &len);
4087 if (!(editor->styleFlags & ES_MULTILINE))
4089 len = 0;
4090 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4091 len++;
4093 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4094 ME_EndToUnicode(codepage, textW);
4095 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4096 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4099 ME_CommitUndo(editor);
4100 ME_WrapMarkedParagraphs(editor);
4101 ME_MoveCaret(editor);
4102 return 0;
4104 case WM_DESTROY:
4105 ME_DestroyEditor(editor);
4106 return 0;
4107 case WM_SETCURSOR:
4109 return ME_SetCursor(editor);
4111 case WM_LBUTTONDBLCLK:
4112 case WM_LBUTTONDOWN:
4114 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4115 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4116 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4117 return 0;
4118 ITextHost_TxSetFocus(editor->texthost);
4119 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4120 ME_CalculateClickCount(editor, msg, wParam, lParam));
4121 ITextHost_TxSetCapture(editor->texthost, TRUE);
4122 editor->bMouseCaptured = TRUE;
4123 ME_LinkNotify(editor,msg,wParam,lParam);
4124 if (!ME_SetCursor(editor)) goto do_default;
4125 break;
4127 case WM_MOUSEMOVE:
4128 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4129 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4130 return 0;
4131 if (editor->bMouseCaptured)
4132 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4133 ME_LinkNotify(editor,msg,wParam,lParam);
4134 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4135 if (editor->bMouseCaptured)
4136 ME_SetCursor(editor);
4137 break;
4138 case WM_LBUTTONUP:
4139 if (editor->bMouseCaptured) {
4140 ITextHost_TxSetCapture(editor->texthost, FALSE);
4141 editor->bMouseCaptured = FALSE;
4143 if (editor->nSelectionType == stDocument)
4144 editor->nSelectionType = stPosition;
4145 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4146 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4147 return 0;
4148 else
4150 ME_SetCursor(editor);
4151 ME_LinkNotify(editor,msg,wParam,lParam);
4153 break;
4154 case WM_RBUTTONUP:
4155 case WM_RBUTTONDOWN:
4156 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4157 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4158 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4159 return 0;
4160 goto do_default;
4161 case WM_CONTEXTMENU:
4162 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4163 goto do_default;
4164 break;
4165 case WM_SETFOCUS:
4166 editor->bHaveFocus = TRUE;
4167 ME_ShowCaret(editor);
4168 ME_SendOldNotify(editor, EN_SETFOCUS);
4169 return 0;
4170 case WM_KILLFOCUS:
4171 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4172 editor->bHaveFocus = FALSE;
4173 editor->wheel_remain = 0;
4174 ME_HideCaret(editor);
4175 ME_SendOldNotify(editor, EN_KILLFOCUS);
4176 return 0;
4177 case WM_COMMAND:
4178 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4179 return 0;
4180 case WM_KEYUP:
4181 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4182 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4183 return 0;
4184 goto do_default;
4185 case WM_KEYDOWN:
4186 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4187 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4188 return 0;
4189 if (ME_KeyDown(editor, LOWORD(wParam)))
4190 return 0;
4191 goto do_default;
4192 case WM_CHAR:
4193 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4194 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4195 return 0;
4196 return ME_Char(editor, wParam, lParam, unicode);
4197 case WM_UNICHAR:
4198 if (unicode)
4200 if(wParam == UNICODE_NOCHAR) return TRUE;
4201 if(wParam <= 0x000fffff)
4203 if(wParam > 0xffff) /* convert to surrogates */
4205 wParam -= 0x10000;
4206 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4207 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4208 } else {
4209 ME_Char(editor, wParam, 0, TRUE);
4212 return 0;
4214 break;
4215 case EM_STOPGROUPTYPING:
4216 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4217 return 0;
4218 case WM_HSCROLL:
4220 const int scrollUnit = 7;
4222 switch(LOWORD(wParam))
4224 case SB_LEFT:
4225 ME_ScrollAbs(editor, 0, 0);
4226 break;
4227 case SB_RIGHT:
4228 ME_ScrollAbs(editor,
4229 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4230 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4231 break;
4232 case SB_LINELEFT:
4233 ME_ScrollLeft(editor, scrollUnit);
4234 break;
4235 case SB_LINERIGHT:
4236 ME_ScrollRight(editor, scrollUnit);
4237 break;
4238 case SB_PAGELEFT:
4239 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4240 break;
4241 case SB_PAGERIGHT:
4242 ME_ScrollRight(editor, editor->sizeWindow.cx);
4243 break;
4244 case SB_THUMBTRACK:
4245 case SB_THUMBPOSITION:
4247 int pos = HIWORD(wParam);
4248 if (editor->horz_si.nMax > 0xffff)
4249 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4250 ME_HScrollAbs(editor, pos);
4251 break;
4254 break;
4256 case EM_SCROLL: /* fall through */
4257 case WM_VSCROLL:
4259 int origNPos;
4260 int lineHeight = get_default_line_height( editor );
4262 origNPos = editor->vert_si.nPos;
4264 switch(LOWORD(wParam))
4266 case SB_TOP:
4267 ME_ScrollAbs(editor, 0, 0);
4268 break;
4269 case SB_BOTTOM:
4270 ME_ScrollAbs(editor,
4271 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4272 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4273 break;
4274 case SB_LINEUP:
4275 ME_ScrollUp(editor,lineHeight);
4276 break;
4277 case SB_LINEDOWN:
4278 ME_ScrollDown(editor,lineHeight);
4279 break;
4280 case SB_PAGEUP:
4281 ME_ScrollUp(editor,editor->sizeWindow.cy);
4282 break;
4283 case SB_PAGEDOWN:
4284 ME_ScrollDown(editor,editor->sizeWindow.cy);
4285 break;
4286 case SB_THUMBTRACK:
4287 case SB_THUMBPOSITION:
4289 int pos = HIWORD(wParam);
4290 if (editor->vert_si.nMax > 0xffff)
4291 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4292 ME_VScrollAbs(editor, pos);
4293 break;
4296 if (msg == EM_SCROLL)
4297 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4298 break;
4300 case WM_MOUSEWHEEL:
4302 int delta;
4303 BOOL ctrl_is_down;
4305 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4306 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4307 return 0;
4309 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4311 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4313 /* if scrolling changes direction, ignore left overs */
4314 if ((delta < 0 && editor->wheel_remain < 0) ||
4315 (delta > 0 && editor->wheel_remain > 0))
4316 editor->wheel_remain += delta;
4317 else
4318 editor->wheel_remain = delta;
4320 if (editor->wheel_remain)
4322 if (ctrl_is_down) {
4323 int numerator;
4324 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4326 numerator = 100;
4327 } else {
4328 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4330 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4331 if (numerator >= 10 && numerator <= 500)
4332 ME_SetZoom(editor, numerator, 100);
4333 } else {
4334 UINT max_lines = 3;
4335 int lines = 0;
4337 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4338 if (max_lines)
4339 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4340 if (lines)
4341 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4344 break;
4346 case EM_GETRECT:
4348 *((RECT *)lParam) = editor->rcFormat;
4349 if (editor->bDefaultFormatRect)
4350 ((RECT *)lParam)->left -= editor->selofs;
4351 return 0;
4353 case EM_SETRECT:
4354 case EM_SETRECTNP:
4356 if (lParam)
4358 int border = 0;
4359 RECT clientRect;
4360 RECT *rc = (RECT *)lParam;
4362 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4363 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4364 if (wParam == 0)
4366 editor->rcFormat.top = max(0, rc->top - border);
4367 editor->rcFormat.left = max(0, rc->left - border);
4368 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4369 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4370 } else if (wParam == 1) {
4371 /* MSDN incorrectly says a wParam value of 1 causes the
4372 * lParam rect to be used as a relative offset,
4373 * however, the tests show it just prevents min/max bound
4374 * checking. */
4375 editor->rcFormat.top = rc->top - border;
4376 editor->rcFormat.left = rc->left - border;
4377 editor->rcFormat.bottom = rc->bottom;
4378 editor->rcFormat.right = rc->right + border;
4379 } else {
4380 return 0;
4382 editor->bDefaultFormatRect = FALSE;
4384 else
4386 ME_SetDefaultFormatRect(editor);
4387 editor->bDefaultFormatRect = TRUE;
4389 ME_MarkAllForWrapping(editor);
4390 ME_WrapMarkedParagraphs(editor);
4391 ME_UpdateScrollBar(editor);
4392 if (msg != EM_SETRECTNP)
4393 ME_Repaint(editor);
4394 return 0;
4396 case EM_REQUESTRESIZE:
4397 ME_SendRequestResize(editor, TRUE);
4398 return 0;
4399 case WM_SETREDRAW:
4400 goto do_default;
4401 case WM_SIZE:
4403 RECT clientRect;
4405 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4406 if (editor->bDefaultFormatRect) {
4407 ME_SetDefaultFormatRect(editor);
4408 } else {
4409 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4410 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4412 editor->prevClientRect = clientRect;
4413 ME_RewrapRepaint(editor);
4414 goto do_default;
4416 /* IME messages to make richedit controls IME aware */
4417 case WM_IME_SETCONTEXT:
4418 case WM_IME_CONTROL:
4419 case WM_IME_SELECT:
4420 case WM_IME_COMPOSITIONFULL:
4421 return 0;
4422 case WM_IME_STARTCOMPOSITION:
4424 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4425 ME_DeleteSelection(editor);
4426 ME_CommitUndo(editor);
4427 ME_UpdateRepaint(editor, FALSE);
4428 return 0;
4430 case WM_IME_COMPOSITION:
4432 HIMC hIMC;
4434 ME_Style *style = ME_GetInsertStyle(editor, 0);
4435 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4436 ME_DeleteSelection(editor);
4437 ME_SaveTempStyle(editor);
4438 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4440 LPWSTR lpCompStr = NULL;
4441 DWORD dwBufLen;
4442 DWORD dwIndex = lParam & GCS_RESULTSTR;
4443 if (!dwIndex)
4444 dwIndex = GCS_COMPSTR;
4446 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4447 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4448 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4449 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4450 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4451 HeapFree(GetProcessHeap(), 0, lpCompStr);
4453 if (dwIndex == GCS_COMPSTR)
4454 ME_SetSelection(editor,editor->imeStartIndex,
4455 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4457 ME_ReleaseStyle(style);
4458 ME_CommitUndo(editor);
4459 ME_UpdateRepaint(editor, FALSE);
4460 return 0;
4462 case WM_IME_ENDCOMPOSITION:
4464 ME_DeleteSelection(editor);
4465 editor->imeStartIndex=-1;
4466 return 0;
4468 case EM_GETOLEINTERFACE:
4470 LPVOID *ppvObj = (LPVOID*) lParam;
4471 return CreateIRichEditOle(editor, ppvObj);
4473 case EM_GETPASSWORDCHAR:
4475 return editor->cPasswordMask;
4477 case EM_SETOLECALLBACK:
4478 if(editor->lpOleCallback)
4479 IRichEditOleCallback_Release(editor->lpOleCallback);
4480 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4481 if(editor->lpOleCallback)
4482 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4483 return TRUE;
4484 case EM_GETWORDBREAKPROC:
4485 return (LRESULT)editor->pfnWordBreak;
4486 case EM_SETWORDBREAKPROC:
4488 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4490 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4491 return (LRESULT)pfnOld;
4493 case EM_GETTEXTMODE:
4494 return editor->mode;
4495 case EM_SETTEXTMODE:
4497 int mask = 0;
4498 int changes = 0;
4500 if (ME_GetTextLength(editor) ||
4501 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4502 return E_UNEXPECTED;
4504 /* Check for mutually exclusive flags in adjacent bits of wParam */
4505 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4506 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4507 return E_INVALIDARG;
4509 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4511 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4512 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4513 if (wParam & TM_PLAINTEXT) {
4514 /* Clear selection since it should be possible to select the
4515 * end of text run for rich text */
4516 ME_InvalidateSelection(editor);
4517 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4518 editor->pCursors[1] = editor->pCursors[0];
4519 /* plain text can only have the default style. */
4520 ME_ClearTempStyle(editor);
4521 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4522 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4523 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4526 /* FIXME: Currently no support for undo level and code page options */
4527 editor->mode = (editor->mode & ~mask) | changes;
4528 return 0;
4530 case EM_SETPASSWORDCHAR:
4532 editor->cPasswordMask = wParam;
4533 ME_RewrapRepaint(editor);
4534 return 0;
4536 case EM_SETTARGETDEVICE:
4537 if (wParam == 0)
4539 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4540 if (editor->nAvailWidth || editor->bWordWrap != new)
4542 editor->bWordWrap = new;
4543 editor->nAvailWidth = 0; /* wrap to client area */
4544 ME_RewrapRepaint(editor);
4546 } else {
4547 int width = max(0, lParam);
4548 if ((editor->styleFlags & ES_MULTILINE) &&
4549 (!editor->bWordWrap || editor->nAvailWidth != width))
4551 editor->nAvailWidth = width;
4552 editor->bWordWrap = TRUE;
4553 ME_RewrapRepaint(editor);
4555 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4557 return TRUE;
4558 default:
4559 do_default:
4560 *phresult = S_FALSE;
4561 break;
4563 return 0L;
4566 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4567 LPARAM lParam, BOOL unicode)
4569 ME_TextEditor *editor;
4570 HRESULT hresult;
4571 LRESULT lresult = 0;
4573 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4574 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4576 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4577 if (!editor)
4579 if (msg == WM_NCCREATE)
4581 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4582 ITextHost *texthost;
4584 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4585 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4586 return texthost != NULL;
4588 else
4590 return DefWindowProcW(hWnd, msg, wParam, lParam);
4594 switch (msg)
4596 case WM_PAINT:
4598 HDC hDC;
4599 RECT rc;
4600 PAINTSTRUCT ps;
4602 hDC = BeginPaint(editor->hWnd, &ps);
4603 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4604 ME_SendOldNotify(editor, EN_UPDATE);
4605 /* Erase area outside of the formatting rectangle */
4606 if (ps.rcPaint.top < editor->rcFormat.top)
4608 rc = ps.rcPaint;
4609 rc.bottom = editor->rcFormat.top;
4610 FillRect(hDC, &rc, editor->hbrBackground);
4611 ps.rcPaint.top = editor->rcFormat.top;
4613 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4614 rc = ps.rcPaint;
4615 rc.top = editor->rcFormat.bottom;
4616 FillRect(hDC, &rc, editor->hbrBackground);
4617 ps.rcPaint.bottom = editor->rcFormat.bottom;
4619 if (ps.rcPaint.left < editor->rcFormat.left) {
4620 rc = ps.rcPaint;
4621 rc.right = editor->rcFormat.left;
4622 FillRect(hDC, &rc, editor->hbrBackground);
4623 ps.rcPaint.left = editor->rcFormat.left;
4625 if (ps.rcPaint.right > editor->rcFormat.right) {
4626 rc = ps.rcPaint;
4627 rc.left = editor->rcFormat.right;
4628 FillRect(hDC, &rc, editor->hbrBackground);
4629 ps.rcPaint.right = editor->rcFormat.right;
4632 ME_PaintContent(editor, hDC, &ps.rcPaint);
4633 EndPaint(editor->hWnd, &ps);
4634 return 0;
4636 case WM_ERASEBKGND:
4638 HDC hDC = (HDC)wParam;
4639 RECT rc;
4641 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4642 FillRect(hDC, &rc, editor->hbrBackground);
4643 return 1;
4645 case EM_SETOPTIONS:
4647 DWORD dwStyle;
4648 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4649 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4650 ECO_SELECTIONBAR;
4651 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4652 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4653 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4654 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4655 return lresult;
4657 case EM_SETREADONLY:
4659 DWORD dwStyle;
4660 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4661 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4662 dwStyle &= ~ES_READONLY;
4663 if (wParam)
4664 dwStyle |= ES_READONLY;
4665 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4666 return lresult;
4668 default:
4669 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4672 if (hresult == S_FALSE)
4673 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4675 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4676 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4678 return lresult;
4681 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4683 BOOL unicode = TRUE;
4685 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4686 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4687 unicode = FALSE;
4689 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4692 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4694 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4697 /******************************************************************
4698 * RichEditANSIWndProc (RICHED20.10)
4700 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4702 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4705 /******************************************************************
4706 * RichEdit10ANSIWndProc (RICHED20.9)
4708 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4710 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4712 ITextHost *texthost;
4713 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4715 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4716 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4717 return texthost != NULL;
4719 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4722 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4724 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4727 /* Fill buffer with srcChars unicode characters from the start cursor.
4729 * buffer: destination buffer
4730 * buflen: length of buffer in characters excluding the NULL terminator.
4731 * start: start of editor text to copy into buffer.
4732 * srcChars: Number of characters to use from the editor text.
4733 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4735 * returns the number of characters written excluding the NULL terminator.
4737 * The written text is always NULL terminated.
4739 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4740 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4742 ME_DisplayItem *pRun, *pNextRun;
4743 const WCHAR *pStart = buffer;
4744 const WCHAR cr_lf[] = {'\r', '\n', 0};
4745 const WCHAR *str;
4746 int nLen;
4748 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4749 if (editor->bEmulateVersion10) bCRLF = FALSE;
4751 pRun = start->pRun;
4752 assert(pRun);
4753 pNextRun = ME_FindItemFwd(pRun, diRun);
4755 nLen = pRun->member.run.len - start->nOffset;
4756 str = get_text( &pRun->member.run, start->nOffset );
4758 /* No '\r' is appended to the last paragraph. */
4759 while (srcChars && buflen && pNextRun)
4761 int nFlags = pRun->member.run.nFlags;
4763 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4765 if (buflen == 1) break;
4766 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4767 * EM_GETTEXTEX, however, this is done for copying text which
4768 * also uses this function. */
4769 srcChars -= min(nLen, srcChars);
4770 nLen = 2;
4771 str = cr_lf;
4772 } else {
4773 nLen = min(nLen, srcChars);
4774 srcChars -= nLen;
4777 nLen = min(nLen, buflen);
4778 buflen -= nLen;
4780 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4782 buffer += nLen;
4784 pRun = pNextRun;
4785 pNextRun = ME_FindItemFwd(pRun, diRun);
4787 nLen = pRun->member.run.len;
4788 str = get_text( &pRun->member.run, 0 );
4790 *buffer = 0;
4791 return buffer - pStart;
4794 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4796 WNDCLASSW wcW;
4797 WNDCLASSA wcA;
4799 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4800 wcW.lpfnWndProc = RichEditWndProcW;
4801 wcW.cbClsExtra = 0;
4802 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4803 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4804 wcW.hIcon = NULL;
4805 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4806 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4807 wcW.lpszMenuName = NULL;
4809 if (is_version_nt())
4811 wcW.lpszClassName = RICHEDIT_CLASS20W;
4812 if (!RegisterClassW(&wcW)) return FALSE;
4813 wcW.lpszClassName = MSFTEDIT_CLASS;
4814 if (!RegisterClassW(&wcW)) return FALSE;
4816 else
4818 /* WNDCLASSA/W have the same layout */
4819 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4820 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4821 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4822 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4825 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4826 wcA.lpfnWndProc = RichEditWndProcA;
4827 wcA.cbClsExtra = 0;
4828 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4829 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4830 wcA.hIcon = NULL;
4831 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4832 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4833 wcA.lpszMenuName = NULL;
4834 wcA.lpszClassName = RICHEDIT_CLASS20A;
4835 if (!RegisterClassA(&wcA)) return FALSE;
4836 wcA.lpszClassName = "RichEdit50A";
4837 if (!RegisterClassA(&wcA)) return FALSE;
4839 return TRUE;
4842 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4843 /* FIXME: Not implemented */
4844 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4845 hWnd, msg, get_msg_name(msg), wParam, lParam);
4846 return DefWindowProcW(hWnd, msg, wParam, lParam);
4849 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4850 /* FIXME: Not implemented */
4851 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4852 hWnd, msg, get_msg_name(msg), wParam, lParam);
4853 return DefWindowProcW(hWnd, msg, wParam, lParam);
4856 /******************************************************************
4857 * REExtendedRegisterClass (RICHED20.8)
4859 * FIXME undocumented
4860 * Need to check for errors and implement controls and callbacks
4862 LRESULT WINAPI REExtendedRegisterClass(void)
4864 WNDCLASSW wcW;
4865 UINT result;
4867 FIXME("semi stub\n");
4869 wcW.cbClsExtra = 0;
4870 wcW.cbWndExtra = 4;
4871 wcW.hInstance = NULL;
4872 wcW.hIcon = NULL;
4873 wcW.hCursor = NULL;
4874 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4875 wcW.lpszMenuName = NULL;
4877 if (!ME_ListBoxRegistered)
4879 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4880 wcW.lpfnWndProc = REListWndProc;
4881 wcW.lpszClassName = REListBox20W;
4882 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4885 if (!ME_ComboBoxRegistered)
4887 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4888 wcW.lpfnWndProc = REComboWndProc;
4889 wcW.lpszClassName = REComboBox20W;
4890 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4893 result = 0;
4894 if (ME_ListBoxRegistered)
4895 result += 1;
4896 if (ME_ComboBoxRegistered)
4897 result += 2;
4899 return result;
4902 static BOOL isurlspecial(WCHAR c)
4904 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4905 return strchrW( special_chars, c ) != NULL;
4909 * This proc takes a selection, and scans it forward in order to select the span
4910 * of a possible URL candidate. A possible URL candidate must start with isalnum
4911 * or one of the following special characters: *|/\+%#@ and must consist entirely
4912 * of the characters allowed to start the URL, plus : (colon) which may occur
4913 * at most once, and not at either end.
4915 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4916 const ME_Cursor *start,
4917 int nChars,
4918 ME_Cursor *candidate_min,
4919 ME_Cursor *candidate_max)
4921 ME_Cursor cursor = *start;
4922 BOOL foundColon = FALSE;
4923 BOOL candidateStarted = FALSE;
4924 WCHAR lastAcceptedChar = '\0';
4926 while (nChars > 0)
4928 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4929 WCHAR *str = strStart + cursor.nOffset;
4930 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4931 nChars -= nLen;
4933 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4935 /* Find start of candidate */
4936 if (!candidateStarted)
4938 while (nLen)
4940 nLen--;
4941 if (isalnumW(*str) || isurlspecial(*str))
4943 cursor.nOffset = str - strStart;
4944 *candidate_min = cursor;
4945 candidateStarted = TRUE;
4946 lastAcceptedChar = *str++;
4947 break;
4949 str++;
4953 /* Find end of candidate */
4954 if (candidateStarted) {
4955 while (nLen)
4957 nLen--;
4958 if (*str == ':' && !foundColon) {
4959 foundColon = TRUE;
4960 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4961 cursor.nOffset = str - strStart;
4962 if (lastAcceptedChar == ':')
4963 ME_MoveCursorChars(editor, &cursor, -1);
4964 *candidate_max = cursor;
4965 return TRUE;
4967 lastAcceptedChar = *str++;
4970 } else {
4971 /* End of paragraph: skip it if before candidate span, or terminates
4972 current active span */
4973 if (candidateStarted) {
4974 if (lastAcceptedChar == ':')
4975 ME_MoveCursorChars(editor, &cursor, -1);
4976 *candidate_max = cursor;
4977 return TRUE;
4981 /* Reaching this point means no span was found, so get next span */
4982 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4983 if (candidateStarted) {
4984 /* There are no further runs, so take end of text as end of candidate */
4985 cursor.nOffset = str - strStart;
4986 if (lastAcceptedChar == ':')
4987 ME_MoveCursorChars(editor, &cursor, -1);
4988 *candidate_max = cursor;
4989 return TRUE;
4991 *candidate_max = *candidate_min = cursor;
4992 return FALSE;
4994 cursor.nOffset = 0;
4997 if (candidateStarted) {
4998 /* There are no further runs, so take end of text as end of candidate */
4999 if (lastAcceptedChar == ':')
5000 ME_MoveCursorChars(editor, &cursor, -1);
5001 *candidate_max = cursor;
5002 return TRUE;
5004 *candidate_max = *candidate_min = cursor;
5005 return FALSE;
5009 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5011 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5013 #define MAX_PREFIX_LEN 9
5014 struct prefix_s {
5015 const WCHAR text[MAX_PREFIX_LEN];
5016 int length;
5017 }prefixes[] = {
5018 {{'p','r','o','s','p','e','r','o',':'}, 9},
5019 {{'t','e','l','n','e','t',':'}, 7},
5020 {{'g','o','p','h','e','r',':'}, 7},
5021 {{'m','a','i','l','t','o',':'}, 7},
5022 {{'h','t','t','p','s',':'}, 6},
5023 {{'f','i','l','e',':'}, 5},
5024 {{'n','e','w','s',':'}, 5},
5025 {{'w','a','i','s',':'}, 5},
5026 {{'n','n','t','p',':'}, 5},
5027 {{'h','t','t','p',':'}, 5},
5028 {{'w','w','w','.'}, 4},
5029 {{'f','t','p',':'}, 4},
5031 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5032 unsigned int i;
5034 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE);
5035 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5037 if (nChars < prefixes[i].length) continue;
5038 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5039 return TRUE;
5041 return FALSE;
5042 #undef MAX_PREFIX_LEN
5046 * This proc walks through the indicated selection and evaluates whether each
5047 * section identified by ME_FindNextURLCandidate and in-between sections have
5048 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5049 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5051 * Since this function can cause runs to be split, do not depend on the value
5052 * of the start cursor at the end of the function.
5054 * nChars may be set to INT_MAX to update to the end of the text.
5056 * Returns TRUE if at least one section was modified.
5058 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5060 BOOL modified = FALSE;
5061 ME_Cursor startCur = *start;
5063 if (!editor->AutoURLDetect_bEnable) return FALSE;
5067 CHARFORMAT2W link;
5068 ME_Cursor candidateStart, candidateEnd;
5070 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5071 &candidateStart, &candidateEnd))
5073 /* Section before candidate is not an URL */
5074 int cMin = ME_GetCursorOfs(&candidateStart);
5075 int cMax = ME_GetCursorOfs(&candidateEnd);
5077 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5078 candidateStart = candidateEnd;
5079 nChars -= cMax - ME_GetCursorOfs(&startCur);
5081 else
5083 /* No more candidates until end of selection */
5084 nChars = 0;
5087 if (startCur.pRun != candidateStart.pRun ||
5088 startCur.nOffset != candidateStart.nOffset)
5090 /* CFE_LINK effect should be consistently unset */
5091 link.cbSize = sizeof(link);
5092 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5093 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5095 /* CFE_LINK must be unset from this range */
5096 memset(&link, 0, sizeof(CHARFORMAT2W));
5097 link.cbSize = sizeof(link);
5098 link.dwMask = CFM_LINK;
5099 link.dwEffects = 0;
5100 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5101 /* Update candidateEnd since setting character formats may split
5102 * runs, which can cause a cursor to be at an invalid offset within
5103 * a split run. */
5104 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5106 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5107 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5109 modified = TRUE;
5112 if (candidateStart.pRun != candidateEnd.pRun ||
5113 candidateStart.nOffset != candidateEnd.nOffset)
5115 /* CFE_LINK effect should be consistently set */
5116 link.cbSize = sizeof(link);
5117 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5118 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5120 /* CFE_LINK must be set on this range */
5121 memset(&link, 0, sizeof(CHARFORMAT2W));
5122 link.cbSize = sizeof(link);
5123 link.dwMask = CFM_LINK;
5124 link.dwEffects = CFE_LINK;
5125 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5126 modified = TRUE;
5129 startCur = candidateEnd;
5130 } while (nChars > 0);
5131 return modified;