msvcrt/tests: Make qsort_comp() static.
[wine/multimedia.git] / dlls / riched20 / editor.c
blobbc5bc0849d7fccd02c98a71ec58d5686505917d6
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) {
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 info.nmhdr.hwndFrom = NULL;
3097 info.nmhdr.idFrom = 0;
3098 info.nmhdr.code = EN_LINK;
3099 info.msg = msg;
3100 info.wParam = wParam;
3101 info.lParam = lParam;
3102 cursor.nOffset = 0;
3103 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3104 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3105 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3109 #define UNSUPPORTED_MSG(e) \
3110 case e: \
3111 FIXME(#e ": stub\n"); \
3112 *phresult = S_FALSE; \
3113 return 0;
3115 /* Handle messages for windowless and windoweded richedit controls.
3117 * The LRESULT that is returned is a return value for window procs,
3118 * and the phresult parameter is the COM return code needed by the
3119 * text services interface. */
3120 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3121 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3123 *phresult = S_OK;
3125 switch(msg) {
3127 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3128 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3129 UNSUPPORTED_MSG(EM_FMTLINES)
3130 UNSUPPORTED_MSG(EM_FORMATRANGE)
3131 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3132 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3133 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3134 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3135 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3136 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3137 UNSUPPORTED_MSG(EM_GETREDONAME)
3138 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3139 UNSUPPORTED_MSG(EM_GETUNDONAME)
3140 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3141 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3142 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3143 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3144 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3145 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3146 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3147 UNSUPPORTED_MSG(EM_SETMARGINS)
3148 UNSUPPORTED_MSG(EM_SETPALETTE)
3149 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3150 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3151 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3153 /* Messages specific to Richedit controls */
3155 case EM_STREAMIN:
3156 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3157 case EM_STREAMOUT:
3158 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3159 case WM_GETDLGCODE:
3161 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3163 if (lParam)
3164 editor->bDialogMode = TRUE;
3165 if (editor->styleFlags & ES_MULTILINE)
3166 code |= DLGC_WANTMESSAGE;
3167 if (!(editor->styleFlags & ES_SAVESEL))
3168 code |= DLGC_HASSETSEL;
3169 return code;
3171 case EM_EMPTYUNDOBUFFER:
3172 ME_EmptyUndoStack(editor);
3173 return 0;
3174 case EM_GETSEL:
3176 /* Note: wParam/lParam can be NULL */
3177 UINT from, to;
3178 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3179 PUINT pto = lParam ? (PUINT)lParam : &to;
3180 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3181 if ((*pfrom|*pto) & 0xFFFF0000)
3182 return -1;
3183 return MAKELONG(*pfrom,*pto);
3185 case EM_EXGETSEL:
3187 CHARRANGE *pRange = (CHARRANGE *)lParam;
3188 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3189 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3190 return 0;
3192 case EM_SETUNDOLIMIT:
3194 if ((int)wParam < 0)
3195 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3196 else
3197 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3198 /* Setting a max stack size keeps wine from getting killed
3199 for hogging memory. Windows allocates all this memory at once, so
3200 no program would realistically set a value above our maximum. */
3201 return editor->nUndoLimit;
3203 case EM_CANUNDO:
3204 return !list_empty( &editor->undo_stack );
3205 case EM_CANREDO:
3206 return !list_empty( &editor->redo_stack );
3207 case WM_UNDO: /* FIXME: actually not the same */
3208 case EM_UNDO:
3209 return ME_Undo(editor);
3210 case EM_REDO:
3211 return ME_Redo(editor);
3212 case EM_GETOPTIONS:
3214 /* these flags are equivalent to the ES_* counterparts */
3215 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3216 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3217 DWORD settings = editor->styleFlags & mask;
3219 return settings;
3221 case EM_SETOPTIONS:
3223 /* these flags are equivalent to ES_* counterparts, except for
3224 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3225 * but is still stored in editor->styleFlags. */
3226 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3227 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3228 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3229 DWORD settings = mask & editor->styleFlags;
3230 DWORD oldSettings = settings;
3231 DWORD changedSettings;
3233 switch(wParam)
3235 case ECOOP_SET:
3236 settings = lParam;
3237 break;
3238 case ECOOP_OR:
3239 settings |= lParam;
3240 break;
3241 case ECOOP_AND:
3242 settings &= lParam;
3243 break;
3244 case ECOOP_XOR:
3245 settings ^= lParam;
3247 changedSettings = oldSettings ^ settings;
3249 if (changedSettings) {
3250 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3252 if (changedSettings & ECO_SELECTIONBAR)
3254 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3255 if (settings & ECO_SELECTIONBAR) {
3256 assert(!editor->selofs);
3257 editor->selofs = SELECTIONBAR_WIDTH;
3258 editor->rcFormat.left += editor->selofs;
3259 } else {
3260 editor->rcFormat.left -= editor->selofs;
3261 editor->selofs = 0;
3263 ME_RewrapRepaint(editor);
3266 if (changedSettings & settings & ECO_VERTICAL)
3267 FIXME("ECO_VERTICAL not implemented yet!\n");
3268 if (changedSettings & settings & ECO_AUTOHSCROLL)
3269 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3270 if (changedSettings & settings & ECO_AUTOVSCROLL)
3271 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3272 if (changedSettings & settings & ECO_NOHIDESEL)
3273 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3274 if (changedSettings & settings & ECO_WANTRETURN)
3275 FIXME("ECO_WANTRETURN not implemented yet!\n");
3276 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3277 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3280 return settings;
3282 case EM_SETSEL:
3284 handle_EM_EXSETSEL( editor, wParam, lParam );
3285 return 0;
3287 case EM_SETSCROLLPOS:
3289 POINT *point = (POINT *)lParam;
3290 ME_ScrollAbs(editor, point->x, point->y);
3291 return 0;
3293 case EM_AUTOURLDETECT:
3295 if (wParam==1 || wParam ==0)
3297 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3298 return 0;
3300 return E_INVALIDARG;
3302 case EM_GETAUTOURLDETECT:
3304 return editor->AutoURLDetect_bEnable;
3306 case EM_EXSETSEL:
3308 CHARRANGE range = *(CHARRANGE *)lParam;
3310 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3312 case EM_SHOWSCROLLBAR:
3314 DWORD flags;
3316 switch (wParam)
3318 case SB_HORZ:
3319 flags = WS_HSCROLL;
3320 break;
3321 case SB_VERT:
3322 flags = WS_VSCROLL;
3323 break;
3324 case SB_BOTH:
3325 flags = WS_HSCROLL|WS_VSCROLL;
3326 break;
3327 default:
3328 return 0;
3331 if (lParam) {
3332 editor->styleFlags |= flags;
3333 if (flags & WS_HSCROLL)
3334 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3335 editor->nTotalWidth > editor->sizeWindow.cx);
3336 if (flags & WS_VSCROLL)
3337 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3338 editor->nTotalLength > editor->sizeWindow.cy);
3339 } else {
3340 editor->styleFlags &= ~flags;
3341 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3343 return 0;
3345 case EM_SETTEXTEX:
3347 LPWSTR wszText;
3348 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3349 int from, to, len;
3350 ME_Style *style;
3351 BOOL bRtf, bUnicode, bSelection, bUTF8;
3352 int oldModify = editor->nModifyStep;
3353 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3355 if (!pStruct) return 0;
3357 /* If we detect ascii rtf at the start of the string,
3358 * we know it isn't unicode. */
3359 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3360 !strncmp((char *)lParam, "{\\urtf", 6)));
3361 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3362 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3364 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3365 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3366 pStruct->flags, pStruct->codepage);
3368 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3369 if (bSelection) {
3370 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3371 style = ME_GetSelectionInsertStyle(editor);
3372 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3373 } else {
3374 ME_Cursor start;
3375 ME_SetCursorToStart(editor, &start);
3376 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3377 style = editor->pBuffer->pDefaultStyle;
3380 if (bRtf) {
3381 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3382 if (bSelection) {
3383 /* FIXME: The length returned doesn't include the rtf control
3384 * characters, only the actual text. */
3385 len = lParam ? strlen((char *)lParam) : 0;
3387 } else {
3388 if (bUTF8 && !bUnicode) {
3389 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3390 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3391 ME_EndToUnicode(CP_UTF8, wszText);
3392 } else {
3393 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3394 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3395 ME_EndToUnicode(pStruct->codepage, wszText);
3399 if (bSelection) {
3400 ME_ReleaseStyle(style);
3401 ME_UpdateSelectionLinkAttribute(editor);
3402 } else {
3403 ME_Cursor cursor;
3404 len = 1;
3405 ME_SetCursorToStart(editor, &cursor);
3406 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3408 ME_CommitUndo(editor);
3409 if (!(pStruct->flags & ST_KEEPUNDO))
3411 editor->nModifyStep = oldModify;
3412 ME_EmptyUndoStack(editor);
3414 ME_UpdateRepaint(editor, FALSE);
3415 return len;
3417 case EM_SETBKGNDCOLOR:
3419 LRESULT lColor;
3420 if (editor->rgbBackColor != -1) {
3421 DeleteObject(editor->hbrBackground);
3422 lColor = editor->rgbBackColor;
3424 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3426 if (wParam)
3428 editor->rgbBackColor = -1;
3429 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3431 else
3433 editor->rgbBackColor = lParam;
3434 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3436 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3437 ITextHost_TxViewChange(editor->texthost, TRUE);
3438 return lColor;
3440 case EM_GETMODIFY:
3441 return editor->nModifyStep == 0 ? 0 : -1;
3442 case EM_SETMODIFY:
3444 if (wParam)
3445 editor->nModifyStep = 1;
3446 else
3447 editor->nModifyStep = 0;
3449 return 0;
3451 case EM_SETREADONLY:
3453 if (wParam)
3454 editor->styleFlags |= ES_READONLY;
3455 else
3456 editor->styleFlags &= ~ES_READONLY;
3457 return 0;
3459 case EM_SETEVENTMASK:
3461 DWORD nOldMask = editor->nEventMask;
3463 editor->nEventMask = lParam;
3464 return nOldMask;
3466 case EM_GETEVENTMASK:
3467 return editor->nEventMask;
3468 case EM_SETCHARFORMAT:
3470 CHARFORMAT2W buf, *p;
3471 BOOL bRepaint = TRUE;
3472 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3473 if (p == NULL) return 0;
3474 if (wParam & SCF_ALL) {
3475 if (editor->mode & TM_PLAINTEXT) {
3476 ME_SetDefaultCharFormat(editor, p);
3477 } else {
3478 ME_Cursor start;
3479 ME_SetCursorToStart(editor, &start);
3480 ME_SetCharFormat(editor, &start, NULL, p);
3481 editor->nModifyStep = 1;
3483 } else if (wParam & SCF_SELECTION) {
3484 if (editor->mode & TM_PLAINTEXT)
3485 return 0;
3486 if (wParam & SCF_WORD) {
3487 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3488 return 0;
3490 bRepaint = ME_IsSelection(editor);
3491 ME_SetSelectionCharFormat(editor, p);
3492 if (bRepaint) editor->nModifyStep = 1;
3493 } else { /* SCF_DEFAULT */
3494 ME_SetDefaultCharFormat(editor, p);
3496 ME_CommitUndo(editor);
3497 if (bRepaint)
3499 ME_WrapMarkedParagraphs(editor);
3500 ME_UpdateScrollBar(editor);
3501 ME_Repaint(editor);
3503 return 1;
3505 case EM_GETCHARFORMAT:
3507 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3508 if (dst->cbSize != sizeof(CHARFORMATA) &&
3509 dst->cbSize != sizeof(CHARFORMATW) &&
3510 dst->cbSize != sizeof(CHARFORMAT2A) &&
3511 dst->cbSize != sizeof(CHARFORMAT2W))
3512 return 0;
3513 tmp.cbSize = sizeof(tmp);
3514 if (!wParam)
3515 ME_GetDefaultCharFormat(editor, &tmp);
3516 else
3517 ME_GetSelectionCharFormat(editor, &tmp);
3518 ME_CopyToCFAny(dst, &tmp);
3519 return tmp.dwMask;
3521 case EM_SETPARAFORMAT:
3523 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3524 ME_WrapMarkedParagraphs(editor);
3525 ME_UpdateScrollBar(editor);
3526 ME_Repaint(editor);
3527 ME_CommitUndo(editor);
3528 return result;
3530 case EM_GETPARAFORMAT:
3531 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3532 return ((PARAFORMAT2 *)lParam)->dwMask;
3533 case EM_GETFIRSTVISIBLELINE:
3535 ME_DisplayItem *p = editor->pBuffer->pFirst;
3536 int y = editor->vert_si.nPos;
3537 int ypara = 0;
3538 int count = 0;
3539 int ystart, yend;
3540 while(p) {
3541 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3542 if (p->type == diTextEnd)
3543 break;
3544 if (p->type == diParagraph) {
3545 ypara = p->member.para.pt.y;
3546 continue;
3548 ystart = ypara + p->member.row.pt.y;
3549 yend = ystart + p->member.row.nHeight;
3550 if (y < yend) {
3551 break;
3553 count++;
3555 return count;
3557 case EM_HIDESELECTION:
3559 editor->bHideSelection = (wParam != 0);
3560 ME_InvalidateSelection(editor);
3561 return 0;
3563 case EM_LINESCROLL:
3565 if (!(editor->styleFlags & ES_MULTILINE))
3566 return FALSE;
3567 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3568 return TRUE;
3570 case WM_CLEAR:
3572 int from, to;
3573 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3574 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3575 ME_CommitUndo(editor);
3576 ME_UpdateRepaint(editor, TRUE);
3577 return 0;
3579 case EM_REPLACESEL:
3581 int from, to, nStartCursor;
3582 ME_Style *style;
3583 int len = 0;
3584 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3585 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3586 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3588 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3589 style = ME_GetSelectionInsertStyle(editor);
3590 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3591 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3592 ME_ReleaseStyle(style);
3593 /* drop temporary style if line end */
3595 * FIXME question: does abc\n mean: put abc,
3596 * clear temp style, put \n? (would require a change)
3598 if (len>0 && wszText[len-1] == '\n')
3599 ME_ClearTempStyle(editor);
3600 ME_EndToUnicode(codepage, wszText);
3601 ME_CommitUndo(editor);
3602 ME_UpdateSelectionLinkAttribute(editor);
3603 if (!wParam)
3604 ME_EmptyUndoStack(editor);
3605 ME_UpdateRepaint(editor, FALSE);
3606 return len;
3608 case EM_SCROLLCARET:
3609 ME_EnsureVisible(editor, &editor->pCursors[0]);
3610 return 0;
3611 case WM_SETFONT:
3613 LOGFONTW lf;
3614 CHARFORMAT2W fmt;
3615 HDC hDC;
3616 BOOL bRepaint = LOWORD(lParam);
3618 if (!wParam)
3619 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3620 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3621 hDC = ITextHost_TxGetDC(editor->texthost);
3622 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3623 ITextHost_TxReleaseDC(editor->texthost, hDC);
3624 if (editor->mode & TM_RICHTEXT) {
3625 ME_Cursor start;
3626 ME_SetCursorToStart(editor, &start);
3627 ME_SetCharFormat(editor, &start, NULL, &fmt);
3629 ME_SetDefaultCharFormat(editor, &fmt);
3631 ME_CommitUndo(editor);
3632 ME_MarkAllForWrapping(editor);
3633 ME_WrapMarkedParagraphs(editor);
3634 ME_UpdateScrollBar(editor);
3635 if (bRepaint)
3636 ME_Repaint(editor);
3637 return 0;
3639 case WM_SETTEXT:
3641 ME_Cursor cursor;
3642 ME_SetCursorToStart(editor, &cursor);
3643 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3644 if (lParam)
3646 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3647 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3648 !strncmp((char *)lParam, "{\\urtf", 6))
3650 /* Undocumented: WM_SETTEXT supports RTF text */
3651 ME_StreamInRTFString(editor, 0, (char *)lParam);
3653 else
3655 int textLen;
3656 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3657 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3658 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3659 if (textLen > 0)
3661 int len = -1;
3663 /* uses default style! */
3664 if (!(editor->styleFlags & ES_MULTILINE))
3666 WCHAR * p;
3668 p = wszText;
3669 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3670 len = p - wszText;
3672 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3674 ME_EndToUnicode(codepage, wszText);
3677 else
3678 TRACE("WM_SETTEXT - NULL\n");
3679 ME_SetCursorToStart(editor, &cursor);
3680 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3681 ME_SetSelection(editor, 0, 0);
3682 editor->nModifyStep = 0;
3683 ME_CommitUndo(editor);
3684 ME_EmptyUndoStack(editor);
3685 ME_UpdateRepaint(editor, FALSE);
3686 return 1;
3688 case EM_CANPASTE:
3690 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3691 if (IsClipboardFormatAvailable(nRTFFormat))
3692 return TRUE;
3693 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3694 return TRUE;
3695 return FALSE;
3697 case WM_PASTE:
3698 case WM_MBUTTONDOWN:
3699 ME_Paste(editor);
3700 return 0;
3701 case WM_CUT:
3702 case WM_COPY:
3704 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3705 int nChars = nTo - nFrom;
3706 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3708 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3710 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3711 ME_CommitUndo(editor);
3712 ME_UpdateRepaint(editor, TRUE);
3714 return 0;
3716 case WM_GETTEXTLENGTH:
3718 GETTEXTLENGTHEX how;
3720 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3721 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3722 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3723 return ME_GetTextLengthEx(editor, &how);
3725 case EM_GETTEXTLENGTHEX:
3726 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3727 case WM_GETTEXT:
3729 GETTEXTEX ex;
3730 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3731 ex.flags = GT_USECRLF;
3732 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3733 ex.lpDefaultChar = NULL;
3734 ex.lpUsedDefChar = NULL;
3735 return ME_GetTextEx(editor, &ex, lParam);
3737 case EM_GETTEXTEX:
3738 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3739 case EM_GETSELTEXT:
3741 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3742 ME_Cursor *from = &editor->pCursors[nStartCur];
3743 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3744 nTo - nFrom, unicode);
3746 case EM_GETSCROLLPOS:
3748 POINT *point = (POINT *)lParam;
3749 point->x = editor->horz_si.nPos;
3750 point->y = editor->vert_si.nPos;
3751 /* 16-bit scaled value is returned as stored in scrollinfo */
3752 if (editor->horz_si.nMax > 0xffff)
3753 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3754 if (editor->vert_si.nMax > 0xffff)
3755 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3756 return 1;
3758 case EM_GETTEXTRANGE:
3760 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3761 ME_Cursor start;
3762 int nStart = rng->chrg.cpMin;
3763 int nEnd = rng->chrg.cpMax;
3764 int textlength = ME_GetTextLength(editor);
3766 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3767 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3768 if (nStart < 0) return 0;
3769 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3770 nEnd = textlength;
3771 if (nStart >= nEnd) return 0;
3773 ME_CursorFromCharOfs(editor, nStart, &start);
3774 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3776 case EM_GETLINE:
3778 ME_DisplayItem *run;
3779 const unsigned int nMaxChars = *(WORD *) lParam;
3780 unsigned int nCharsLeft = nMaxChars;
3781 char *dest = (char *) lParam;
3782 BOOL wroteNull = FALSE;
3784 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3785 unicode ? "Unicode" : "Ansi");
3787 run = ME_FindRowWithNumber(editor, wParam);
3788 if (run == NULL)
3789 return 0;
3791 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3792 && run->type == diRun)
3794 WCHAR *str = get_text( &run->member.run, 0 );
3795 unsigned int nCopy;
3797 nCopy = min(nCharsLeft, run->member.run.len);
3799 if (unicode)
3800 memcpy(dest, str, nCopy * sizeof(WCHAR));
3801 else
3802 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3803 nCharsLeft, NULL, NULL);
3804 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3805 nCharsLeft -= nCopy;
3808 /* append line termination, space allowing */
3809 if (nCharsLeft > 0)
3811 if (unicode)
3812 *((WCHAR *)dest) = '\0';
3813 else
3814 *dest = '\0';
3815 nCharsLeft--;
3816 wroteNull = TRUE;
3819 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3820 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3822 case EM_GETLINECOUNT:
3824 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3825 int nRows = 0;
3827 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3829 while (item != editor->pBuffer->pLast)
3831 assert(item->type == diParagraph);
3832 prev_para = ME_FindItemBack(item, diRun);
3833 if (prev_para) {
3834 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3836 nRows += item->member.para.nRows;
3837 item = item->member.para.next_para;
3839 last_para = ME_FindItemBack(item, diRun);
3840 assert(last_para);
3841 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3842 if (editor->bEmulateVersion10 && prev_para &&
3843 last_para->member.run.nCharOfs == 0 &&
3844 prev_para->member.run.len == 1 &&
3845 *get_text( &prev_para->member.run, 0 ) == '\r')
3847 /* In 1.0 emulation, the last solitary \r at the very end of the text
3848 (if one exists) is NOT a line break.
3849 FIXME: this is an ugly hack. This should have a more regular model. */
3850 nRows--;
3853 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3854 return max(1, nRows);
3856 case EM_LINEFROMCHAR:
3858 if (wParam == -1)
3859 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3860 else
3861 return ME_RowNumberFromCharOfs(editor, wParam);
3863 case EM_EXLINEFROMCHAR:
3865 if (lParam == -1)
3866 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3867 else
3868 return ME_RowNumberFromCharOfs(editor, lParam);
3870 case EM_LINEINDEX:
3872 ME_DisplayItem *item, *para;
3873 int nCharOfs;
3875 if (wParam == -1)
3876 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3877 else
3878 item = ME_FindRowWithNumber(editor, wParam);
3879 if (!item)
3880 return -1;
3881 para = ME_GetParagraph(item);
3882 item = ME_FindItemFwd(item, diRun);
3883 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3884 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3885 return nCharOfs;
3887 case EM_LINELENGTH:
3889 ME_DisplayItem *item, *item_end;
3890 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3891 ME_DisplayItem *para, *run;
3893 if (wParam > ME_GetTextLength(editor))
3894 return 0;
3895 if (wParam == -1)
3897 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3898 return 0;
3900 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3901 item = ME_RowStart(run);
3902 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3903 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3904 if (item_end->type == diStartRow) {
3905 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3906 } else {
3907 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3908 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3909 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3911 nChars = nNextLineOfs - nThisLineOfs;
3912 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3913 return nChars;
3915 case EM_EXLIMITTEXT:
3917 if ((int)lParam < 0)
3918 return 0;
3919 if (lParam == 0)
3920 editor->nTextLimit = 65536;
3921 else
3922 editor->nTextLimit = (int) lParam;
3923 return 0;
3925 case EM_LIMITTEXT:
3927 if (wParam == 0)
3928 editor->nTextLimit = 65536;
3929 else
3930 editor->nTextLimit = (int) wParam;
3931 return 0;
3933 case EM_GETLIMITTEXT:
3935 return editor->nTextLimit;
3937 case EM_FINDTEXT:
3939 LRESULT r;
3940 if(!unicode){
3941 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3942 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3943 WCHAR *tmp;
3945 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3946 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3947 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3948 FREE_OBJ( tmp );
3949 }else{
3950 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3951 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3953 return r;
3955 case EM_FINDTEXTEX:
3957 LRESULT r;
3958 if(!unicode){
3959 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3960 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3961 WCHAR *tmp;
3963 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3964 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3965 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3966 FREE_OBJ( tmp );
3967 }else{
3968 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3969 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3971 return r;
3973 case EM_FINDTEXTW:
3975 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3976 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3978 case EM_FINDTEXTEXW:
3980 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3981 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3983 case EM_GETZOOM:
3984 if (!wParam || !lParam)
3985 return FALSE;
3986 *(int *)wParam = editor->nZoomNumerator;
3987 *(int *)lParam = editor->nZoomDenominator;
3988 return TRUE;
3989 case EM_SETZOOM:
3990 return ME_SetZoom(editor, wParam, lParam);
3991 case EM_CHARFROMPOS:
3993 ME_Cursor cursor;
3994 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3995 &cursor, NULL))
3996 return ME_GetCursorOfs(&cursor);
3997 else
3998 return -1;
4000 case EM_POSFROMCHAR:
4002 ME_DisplayItem *pPara, *pRun;
4003 int nCharOfs, nOffset, nLength;
4004 POINTL pt = {0,0};
4006 nCharOfs = wParam;
4007 /* detect which API version we're dealing with */
4008 if (wParam >= 0x40000)
4009 nCharOfs = lParam;
4010 nLength = ME_GetTextLength(editor);
4011 nCharOfs = min(nCharOfs, nLength);
4012 nCharOfs = max(nCharOfs, 0);
4014 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4015 assert(pRun->type == diRun);
4016 pt.y = pRun->member.run.pt.y;
4017 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4018 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4019 pt.x += editor->rcFormat.left;
4021 pt.x -= editor->horz_si.nPos;
4022 pt.y -= editor->vert_si.nPos;
4024 if (wParam >= 0x40000) {
4025 *(POINTL *)wParam = pt;
4027 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4029 case WM_CREATE:
4031 void *text = NULL;
4032 INT max;
4034 ME_SetDefaultFormatRect(editor);
4036 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4037 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4038 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4040 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4041 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4043 if (editor->styleFlags & ES_DISABLENOSCROLL)
4045 if (editor->styleFlags & WS_VSCROLL)
4047 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4048 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4050 if (editor->styleFlags & WS_HSCROLL)
4052 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4053 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4057 if (lParam)
4059 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4060 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4062 if (text)
4064 WCHAR *textW;
4065 int len;
4066 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4067 textW = ME_ToUnicode(codepage, text, &len);
4068 if (!(editor->styleFlags & ES_MULTILINE))
4070 len = 0;
4071 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4072 len++;
4074 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4075 ME_EndToUnicode(codepage, textW);
4076 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4077 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4080 ME_CommitUndo(editor);
4081 ME_WrapMarkedParagraphs(editor);
4082 ME_MoveCaret(editor);
4083 return 0;
4085 case WM_DESTROY:
4086 ME_DestroyEditor(editor);
4087 return 0;
4088 case WM_SETCURSOR:
4090 return ME_SetCursor(editor);
4092 case WM_LBUTTONDBLCLK:
4093 case WM_LBUTTONDOWN:
4095 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4096 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4097 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4098 return 0;
4099 ITextHost_TxSetFocus(editor->texthost);
4100 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4101 ME_CalculateClickCount(editor, msg, wParam, lParam));
4102 ITextHost_TxSetCapture(editor->texthost, TRUE);
4103 editor->bMouseCaptured = TRUE;
4104 ME_LinkNotify(editor,msg,wParam,lParam);
4105 if (!ME_SetCursor(editor)) goto do_default;
4106 break;
4108 case WM_MOUSEMOVE:
4109 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4110 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4111 return 0;
4112 if (editor->bMouseCaptured)
4113 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4114 ME_LinkNotify(editor,msg,wParam,lParam);
4115 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4116 if (editor->bMouseCaptured)
4117 ME_SetCursor(editor);
4118 break;
4119 case WM_LBUTTONUP:
4120 if (editor->bMouseCaptured) {
4121 ITextHost_TxSetCapture(editor->texthost, FALSE);
4122 editor->bMouseCaptured = FALSE;
4124 if (editor->nSelectionType == stDocument)
4125 editor->nSelectionType = stPosition;
4126 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4127 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4128 return 0;
4129 else
4131 ME_SetCursor(editor);
4132 ME_LinkNotify(editor,msg,wParam,lParam);
4134 break;
4135 case WM_RBUTTONUP:
4136 case WM_RBUTTONDOWN:
4137 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4138 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4139 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4140 return 0;
4141 goto do_default;
4142 case WM_CONTEXTMENU:
4143 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4144 goto do_default;
4145 break;
4146 case WM_SETFOCUS:
4147 editor->bHaveFocus = TRUE;
4148 ME_ShowCaret(editor);
4149 ME_SendOldNotify(editor, EN_SETFOCUS);
4150 return 0;
4151 case WM_KILLFOCUS:
4152 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4153 editor->bHaveFocus = FALSE;
4154 editor->wheel_remain = 0;
4155 ME_HideCaret(editor);
4156 ME_SendOldNotify(editor, EN_KILLFOCUS);
4157 return 0;
4158 case WM_COMMAND:
4159 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4160 return 0;
4161 case WM_KEYUP:
4162 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4163 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4164 return 0;
4165 goto do_default;
4166 case WM_KEYDOWN:
4167 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4168 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4169 return 0;
4170 if (ME_KeyDown(editor, LOWORD(wParam)))
4171 return 0;
4172 goto do_default;
4173 case WM_CHAR:
4174 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4175 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4176 return 0;
4177 return ME_Char(editor, wParam, lParam, unicode);
4178 case WM_UNICHAR:
4179 if (unicode)
4181 if(wParam == UNICODE_NOCHAR) return TRUE;
4182 if(wParam <= 0x000fffff)
4184 if(wParam > 0xffff) /* convert to surrogates */
4186 wParam -= 0x10000;
4187 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4188 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4189 } else {
4190 ME_Char(editor, wParam, 0, TRUE);
4193 return 0;
4195 break;
4196 case EM_STOPGROUPTYPING:
4197 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4198 return 0;
4199 case WM_HSCROLL:
4201 const int scrollUnit = 7;
4203 switch(LOWORD(wParam))
4205 case SB_LEFT:
4206 ME_ScrollAbs(editor, 0, 0);
4207 break;
4208 case SB_RIGHT:
4209 ME_ScrollAbs(editor,
4210 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4211 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4212 break;
4213 case SB_LINELEFT:
4214 ME_ScrollLeft(editor, scrollUnit);
4215 break;
4216 case SB_LINERIGHT:
4217 ME_ScrollRight(editor, scrollUnit);
4218 break;
4219 case SB_PAGELEFT:
4220 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4221 break;
4222 case SB_PAGERIGHT:
4223 ME_ScrollRight(editor, editor->sizeWindow.cx);
4224 break;
4225 case SB_THUMBTRACK:
4226 case SB_THUMBPOSITION:
4228 int pos = HIWORD(wParam);
4229 if (editor->horz_si.nMax > 0xffff)
4230 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4231 ME_HScrollAbs(editor, pos);
4232 break;
4235 break;
4237 case EM_SCROLL: /* fall through */
4238 case WM_VSCROLL:
4240 int origNPos;
4241 int lineHeight = get_default_line_height( editor );
4243 origNPos = editor->vert_si.nPos;
4245 switch(LOWORD(wParam))
4247 case SB_TOP:
4248 ME_ScrollAbs(editor, 0, 0);
4249 break;
4250 case SB_BOTTOM:
4251 ME_ScrollAbs(editor,
4252 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4253 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4254 break;
4255 case SB_LINEUP:
4256 ME_ScrollUp(editor,lineHeight);
4257 break;
4258 case SB_LINEDOWN:
4259 ME_ScrollDown(editor,lineHeight);
4260 break;
4261 case SB_PAGEUP:
4262 ME_ScrollUp(editor,editor->sizeWindow.cy);
4263 break;
4264 case SB_PAGEDOWN:
4265 ME_ScrollDown(editor,editor->sizeWindow.cy);
4266 break;
4267 case SB_THUMBTRACK:
4268 case SB_THUMBPOSITION:
4270 int pos = HIWORD(wParam);
4271 if (editor->vert_si.nMax > 0xffff)
4272 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4273 ME_VScrollAbs(editor, pos);
4274 break;
4277 if (msg == EM_SCROLL)
4278 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4279 break;
4281 case WM_MOUSEWHEEL:
4283 int delta;
4284 BOOL ctrl_is_down;
4286 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4287 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4288 return 0;
4290 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4292 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4294 /* if scrolling changes direction, ignore left overs */
4295 if ((delta < 0 && editor->wheel_remain < 0) ||
4296 (delta > 0 && editor->wheel_remain > 0))
4297 editor->wheel_remain += delta;
4298 else
4299 editor->wheel_remain = delta;
4301 if (editor->wheel_remain)
4303 if (ctrl_is_down) {
4304 int numerator;
4305 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4307 numerator = 100;
4308 } else {
4309 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4311 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4312 if (numerator >= 10 && numerator <= 500)
4313 ME_SetZoom(editor, numerator, 100);
4314 } else {
4315 UINT max_lines = 3;
4316 int lines = 0;
4318 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4319 if (max_lines)
4320 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4321 if (lines)
4322 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4325 break;
4327 case EM_GETRECT:
4329 *((RECT *)lParam) = editor->rcFormat;
4330 if (editor->bDefaultFormatRect)
4331 ((RECT *)lParam)->left -= editor->selofs;
4332 return 0;
4334 case EM_SETRECT:
4335 case EM_SETRECTNP:
4337 if (lParam)
4339 int border = 0;
4340 RECT clientRect;
4341 RECT *rc = (RECT *)lParam;
4343 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4344 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4345 if (wParam == 0)
4347 editor->rcFormat.top = max(0, rc->top - border);
4348 editor->rcFormat.left = max(0, rc->left - border);
4349 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4350 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4351 } else if (wParam == 1) {
4352 /* MSDN incorrectly says a wParam value of 1 causes the
4353 * lParam rect to be used as a relative offset,
4354 * however, the tests show it just prevents min/max bound
4355 * checking. */
4356 editor->rcFormat.top = rc->top - border;
4357 editor->rcFormat.left = rc->left - border;
4358 editor->rcFormat.bottom = rc->bottom;
4359 editor->rcFormat.right = rc->right + border;
4360 } else {
4361 return 0;
4363 editor->bDefaultFormatRect = FALSE;
4365 else
4367 ME_SetDefaultFormatRect(editor);
4368 editor->bDefaultFormatRect = TRUE;
4370 ME_MarkAllForWrapping(editor);
4371 ME_WrapMarkedParagraphs(editor);
4372 ME_UpdateScrollBar(editor);
4373 if (msg != EM_SETRECTNP)
4374 ME_Repaint(editor);
4375 return 0;
4377 case EM_REQUESTRESIZE:
4378 ME_SendRequestResize(editor, TRUE);
4379 return 0;
4380 case WM_SETREDRAW:
4381 goto do_default;
4382 case WM_SIZE:
4384 RECT clientRect;
4386 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4387 if (editor->bDefaultFormatRect) {
4388 ME_SetDefaultFormatRect(editor);
4389 } else {
4390 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4391 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4393 editor->prevClientRect = clientRect;
4394 ME_RewrapRepaint(editor);
4395 goto do_default;
4397 /* IME messages to make richedit controls IME aware */
4398 case WM_IME_SETCONTEXT:
4399 case WM_IME_CONTROL:
4400 case WM_IME_SELECT:
4401 case WM_IME_COMPOSITIONFULL:
4402 return 0;
4403 case WM_IME_STARTCOMPOSITION:
4405 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4406 ME_DeleteSelection(editor);
4407 ME_CommitUndo(editor);
4408 ME_UpdateRepaint(editor, FALSE);
4409 return 0;
4411 case WM_IME_COMPOSITION:
4413 HIMC hIMC;
4415 ME_Style *style = ME_GetInsertStyle(editor, 0);
4416 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4417 ME_DeleteSelection(editor);
4418 ME_SaveTempStyle(editor);
4419 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4421 LPWSTR lpCompStr = NULL;
4422 DWORD dwBufLen;
4423 DWORD dwIndex = lParam & GCS_RESULTSTR;
4424 if (!dwIndex)
4425 dwIndex = GCS_COMPSTR;
4427 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4428 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4429 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4430 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4431 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4432 HeapFree(GetProcessHeap(), 0, lpCompStr);
4434 if (dwIndex == GCS_COMPSTR)
4435 ME_SetSelection(editor,editor->imeStartIndex,
4436 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4438 ME_ReleaseStyle(style);
4439 ME_CommitUndo(editor);
4440 ME_UpdateRepaint(editor, FALSE);
4441 return 0;
4443 case WM_IME_ENDCOMPOSITION:
4445 ME_DeleteSelection(editor);
4446 editor->imeStartIndex=-1;
4447 return 0;
4449 case EM_GETOLEINTERFACE:
4451 LPVOID *ppvObj = (LPVOID*) lParam;
4452 return CreateIRichEditOle(editor, ppvObj);
4454 case EM_GETPASSWORDCHAR:
4456 return editor->cPasswordMask;
4458 case EM_SETOLECALLBACK:
4459 if(editor->lpOleCallback)
4460 IRichEditOleCallback_Release(editor->lpOleCallback);
4461 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4462 if(editor->lpOleCallback)
4463 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4464 return TRUE;
4465 case EM_GETWORDBREAKPROC:
4466 return (LRESULT)editor->pfnWordBreak;
4467 case EM_SETWORDBREAKPROC:
4469 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4471 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4472 return (LRESULT)pfnOld;
4474 case EM_GETTEXTMODE:
4475 return editor->mode;
4476 case EM_SETTEXTMODE:
4478 int mask = 0;
4479 int changes = 0;
4481 if (ME_GetTextLength(editor) ||
4482 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4483 return E_UNEXPECTED;
4485 /* Check for mutually exclusive flags in adjacent bits of wParam */
4486 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4487 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4488 return E_INVALIDARG;
4490 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4492 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4493 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4494 if (wParam & TM_PLAINTEXT) {
4495 /* Clear selection since it should be possible to select the
4496 * end of text run for rich text */
4497 ME_InvalidateSelection(editor);
4498 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4499 editor->pCursors[1] = editor->pCursors[0];
4500 /* plain text can only have the default style. */
4501 ME_ClearTempStyle(editor);
4502 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4503 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4504 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4507 /* FIXME: Currently no support for undo level and code page options */
4508 editor->mode = (editor->mode & ~mask) | changes;
4509 return 0;
4511 case EM_SETPASSWORDCHAR:
4513 editor->cPasswordMask = wParam;
4514 ME_RewrapRepaint(editor);
4515 return 0;
4517 case EM_SETTARGETDEVICE:
4518 if (wParam == 0)
4520 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4521 if (editor->nAvailWidth || editor->bWordWrap != new)
4523 editor->bWordWrap = new;
4524 editor->nAvailWidth = 0; /* wrap to client area */
4525 ME_RewrapRepaint(editor);
4527 } else {
4528 int width = max(0, lParam);
4529 if ((editor->styleFlags & ES_MULTILINE) &&
4530 (!editor->bWordWrap || editor->nAvailWidth != width))
4532 editor->nAvailWidth = width;
4533 editor->bWordWrap = TRUE;
4534 ME_RewrapRepaint(editor);
4536 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4538 return TRUE;
4539 default:
4540 do_default:
4541 *phresult = S_FALSE;
4542 break;
4544 return 0L;
4547 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4548 LPARAM lParam, BOOL unicode)
4550 ME_TextEditor *editor;
4551 HRESULT hresult;
4552 LRESULT lresult = 0;
4554 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4555 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4557 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4558 if (!editor)
4560 if (msg == WM_NCCREATE)
4562 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4563 ITextHost *texthost;
4565 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4566 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4567 return texthost != NULL;
4569 else
4571 return DefWindowProcW(hWnd, msg, wParam, lParam);
4575 switch (msg)
4577 case WM_PAINT:
4579 HDC hDC;
4580 RECT rc;
4581 PAINTSTRUCT ps;
4583 hDC = BeginPaint(editor->hWnd, &ps);
4584 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4585 ME_SendOldNotify(editor, EN_UPDATE);
4586 /* Erase area outside of the formatting rectangle */
4587 if (ps.rcPaint.top < editor->rcFormat.top)
4589 rc = ps.rcPaint;
4590 rc.bottom = editor->rcFormat.top;
4591 FillRect(hDC, &rc, editor->hbrBackground);
4592 ps.rcPaint.top = editor->rcFormat.top;
4594 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4595 rc = ps.rcPaint;
4596 rc.top = editor->rcFormat.bottom;
4597 FillRect(hDC, &rc, editor->hbrBackground);
4598 ps.rcPaint.bottom = editor->rcFormat.bottom;
4600 if (ps.rcPaint.left < editor->rcFormat.left) {
4601 rc = ps.rcPaint;
4602 rc.right = editor->rcFormat.left;
4603 FillRect(hDC, &rc, editor->hbrBackground);
4604 ps.rcPaint.left = editor->rcFormat.left;
4606 if (ps.rcPaint.right > editor->rcFormat.right) {
4607 rc = ps.rcPaint;
4608 rc.left = editor->rcFormat.right;
4609 FillRect(hDC, &rc, editor->hbrBackground);
4610 ps.rcPaint.right = editor->rcFormat.right;
4613 ME_PaintContent(editor, hDC, &ps.rcPaint);
4614 EndPaint(editor->hWnd, &ps);
4615 return 0;
4617 case WM_ERASEBKGND:
4619 HDC hDC = (HDC)wParam;
4620 RECT rc;
4622 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4623 FillRect(hDC, &rc, editor->hbrBackground);
4624 return 1;
4626 case EM_SETOPTIONS:
4628 DWORD dwStyle;
4629 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4630 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4631 ECO_SELECTIONBAR;
4632 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4633 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4634 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4635 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4636 return lresult;
4638 case EM_SETREADONLY:
4640 DWORD dwStyle;
4641 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4642 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4643 dwStyle &= ~ES_READONLY;
4644 if (wParam)
4645 dwStyle |= ES_READONLY;
4646 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4647 return lresult;
4649 default:
4650 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4653 if (hresult == S_FALSE)
4654 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4656 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4657 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4659 return lresult;
4662 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4664 BOOL unicode = TRUE;
4666 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4667 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4668 unicode = FALSE;
4670 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4673 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4675 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4678 /******************************************************************
4679 * RichEditANSIWndProc (RICHED20.10)
4681 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4683 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4686 /******************************************************************
4687 * RichEdit10ANSIWndProc (RICHED20.9)
4689 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4691 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4693 ITextHost *texthost;
4694 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4696 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4697 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4698 return texthost != NULL;
4700 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4703 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4705 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4708 /* Fill buffer with srcChars unicode characters from the start cursor.
4710 * buffer: destination buffer
4711 * buflen: length of buffer in characters excluding the NULL terminator.
4712 * start: start of editor text to copy into buffer.
4713 * srcChars: Number of characters to use from the editor text.
4714 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4716 * returns the number of characters written excluding the NULL terminator.
4718 * The written text is always NULL terminated.
4720 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4721 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4723 ME_DisplayItem *pRun, *pNextRun;
4724 const WCHAR *pStart = buffer;
4725 const WCHAR cr_lf[] = {'\r', '\n', 0};
4726 const WCHAR *str;
4727 int nLen;
4729 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4730 if (editor->bEmulateVersion10) bCRLF = FALSE;
4732 pRun = start->pRun;
4733 assert(pRun);
4734 pNextRun = ME_FindItemFwd(pRun, diRun);
4736 nLen = pRun->member.run.len - start->nOffset;
4737 str = get_text( &pRun->member.run, start->nOffset );
4739 /* No '\r' is appended to the last paragraph. */
4740 while (srcChars && buflen && pNextRun)
4742 int nFlags = pRun->member.run.nFlags;
4744 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4746 if (buflen == 1) break;
4747 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4748 * EM_GETTEXTEX, however, this is done for copying text which
4749 * also uses this function. */
4750 srcChars -= min(nLen, srcChars);
4751 nLen = 2;
4752 str = cr_lf;
4753 } else {
4754 nLen = min(nLen, srcChars);
4755 srcChars -= nLen;
4758 nLen = min(nLen, buflen);
4759 buflen -= nLen;
4761 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4763 buffer += nLen;
4765 pRun = pNextRun;
4766 pNextRun = ME_FindItemFwd(pRun, diRun);
4768 nLen = pRun->member.run.len;
4769 str = get_text( &pRun->member.run, 0 );
4771 *buffer = 0;
4772 return buffer - pStart;
4775 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4777 WNDCLASSW wcW;
4778 WNDCLASSA wcA;
4780 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4781 wcW.lpfnWndProc = RichEditWndProcW;
4782 wcW.cbClsExtra = 0;
4783 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4784 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4785 wcW.hIcon = NULL;
4786 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4787 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4788 wcW.lpszMenuName = NULL;
4790 if (is_version_nt())
4792 wcW.lpszClassName = RICHEDIT_CLASS20W;
4793 if (!RegisterClassW(&wcW)) return FALSE;
4794 wcW.lpszClassName = MSFTEDIT_CLASS;
4795 if (!RegisterClassW(&wcW)) return FALSE;
4797 else
4799 /* WNDCLASSA/W have the same layout */
4800 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4801 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4802 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4803 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4806 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4807 wcA.lpfnWndProc = RichEditWndProcA;
4808 wcA.cbClsExtra = 0;
4809 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4810 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4811 wcA.hIcon = NULL;
4812 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4813 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4814 wcA.lpszMenuName = NULL;
4815 wcA.lpszClassName = RICHEDIT_CLASS20A;
4816 if (!RegisterClassA(&wcA)) return FALSE;
4817 wcA.lpszClassName = "RichEdit50A";
4818 if (!RegisterClassA(&wcA)) return FALSE;
4820 return TRUE;
4823 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4824 /* FIXME: Not implemented */
4825 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4826 hWnd, msg, get_msg_name(msg), wParam, lParam);
4827 return DefWindowProcW(hWnd, msg, wParam, lParam);
4830 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4831 /* FIXME: Not implemented */
4832 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4833 hWnd, msg, get_msg_name(msg), wParam, lParam);
4834 return DefWindowProcW(hWnd, msg, wParam, lParam);
4837 /******************************************************************
4838 * REExtendedRegisterClass (RICHED20.8)
4840 * FIXME undocumented
4841 * Need to check for errors and implement controls and callbacks
4843 LRESULT WINAPI REExtendedRegisterClass(void)
4845 WNDCLASSW wcW;
4846 UINT result;
4848 FIXME("semi stub\n");
4850 wcW.cbClsExtra = 0;
4851 wcW.cbWndExtra = 4;
4852 wcW.hInstance = NULL;
4853 wcW.hIcon = NULL;
4854 wcW.hCursor = NULL;
4855 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4856 wcW.lpszMenuName = NULL;
4858 if (!ME_ListBoxRegistered)
4860 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4861 wcW.lpfnWndProc = REListWndProc;
4862 wcW.lpszClassName = REListBox20W;
4863 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4866 if (!ME_ComboBoxRegistered)
4868 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4869 wcW.lpfnWndProc = REComboWndProc;
4870 wcW.lpszClassName = REComboBox20W;
4871 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4874 result = 0;
4875 if (ME_ListBoxRegistered)
4876 result += 1;
4877 if (ME_ComboBoxRegistered)
4878 result += 2;
4880 return result;
4883 static BOOL isurlspecial(WCHAR c)
4885 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4886 return strchrW( special_chars, c ) != NULL;
4890 * This proc takes a selection, and scans it forward in order to select the span
4891 * of a possible URL candidate. A possible URL candidate must start with isalnum
4892 * or one of the following special characters: *|/\+%#@ and must consist entirely
4893 * of the characters allowed to start the URL, plus : (colon) which may occur
4894 * at most once, and not at either end.
4896 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4897 const ME_Cursor *start,
4898 int nChars,
4899 ME_Cursor *candidate_min,
4900 ME_Cursor *candidate_max)
4902 ME_Cursor cursor = *start;
4903 BOOL foundColon = FALSE;
4904 BOOL candidateStarted = FALSE;
4905 WCHAR lastAcceptedChar = '\0';
4907 while (nChars > 0)
4909 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4910 WCHAR *str = strStart + cursor.nOffset;
4911 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4912 nChars -= nLen;
4914 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4916 /* Find start of candidate */
4917 if (!candidateStarted)
4919 while (nLen)
4921 nLen--;
4922 if (isalnumW(*str) || isurlspecial(*str))
4924 cursor.nOffset = str - strStart;
4925 *candidate_min = cursor;
4926 candidateStarted = TRUE;
4927 lastAcceptedChar = *str++;
4928 break;
4930 str++;
4934 /* Find end of candidate */
4935 if (candidateStarted) {
4936 while (nLen)
4938 nLen--;
4939 if (*str == ':' && !foundColon) {
4940 foundColon = TRUE;
4941 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4942 cursor.nOffset = str - strStart;
4943 if (lastAcceptedChar == ':')
4944 ME_MoveCursorChars(editor, &cursor, -1);
4945 *candidate_max = cursor;
4946 return TRUE;
4948 lastAcceptedChar = *str++;
4951 } else {
4952 /* End of paragraph: skip it if before candidate span, or terminates
4953 current active span */
4954 if (candidateStarted) {
4955 if (lastAcceptedChar == ':')
4956 ME_MoveCursorChars(editor, &cursor, -1);
4957 *candidate_max = cursor;
4958 return TRUE;
4962 /* Reaching this point means no span was found, so get next span */
4963 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4964 if (candidateStarted) {
4965 /* There are no further runs, so take end of text as end of candidate */
4966 cursor.nOffset = str - strStart;
4967 if (lastAcceptedChar == ':')
4968 ME_MoveCursorChars(editor, &cursor, -1);
4969 *candidate_max = cursor;
4970 return TRUE;
4972 *candidate_max = *candidate_min = cursor;
4973 return FALSE;
4975 cursor.nOffset = 0;
4978 if (candidateStarted) {
4979 /* There are no further runs, so take end of text as end of candidate */
4980 if (lastAcceptedChar == ':')
4981 ME_MoveCursorChars(editor, &cursor, -1);
4982 *candidate_max = cursor;
4983 return TRUE;
4985 *candidate_max = *candidate_min = cursor;
4986 return FALSE;
4990 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4992 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4994 #define MAX_PREFIX_LEN 9
4995 struct prefix_s {
4996 const WCHAR text[MAX_PREFIX_LEN];
4997 int length;
4998 }prefixes[] = {
4999 {{'p','r','o','s','p','e','r','o',':'}, 9},
5000 {{'t','e','l','n','e','t',':'}, 7},
5001 {{'g','o','p','h','e','r',':'}, 7},
5002 {{'m','a','i','l','t','o',':'}, 7},
5003 {{'h','t','t','p','s',':'}, 6},
5004 {{'f','i','l','e',':'}, 5},
5005 {{'n','e','w','s',':'}, 5},
5006 {{'w','a','i','s',':'}, 5},
5007 {{'n','n','t','p',':'}, 5},
5008 {{'h','t','t','p',':'}, 5},
5009 {{'w','w','w','.'}, 4},
5010 {{'f','t','p',':'}, 4},
5012 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5013 unsigned int i;
5015 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE);
5016 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5018 if (nChars < prefixes[i].length) continue;
5019 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5020 return TRUE;
5022 return FALSE;
5023 #undef MAX_PREFIX_LEN
5027 * This proc walks through the indicated selection and evaluates whether each
5028 * section identified by ME_FindNextURLCandidate and in-between sections have
5029 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5030 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5032 * Since this function can cause runs to be split, do not depend on the value
5033 * of the start cursor at the end of the function.
5035 * nChars may be set to INT_MAX to update to the end of the text.
5037 * Returns TRUE if at least one section was modified.
5039 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5041 BOOL modified = FALSE;
5042 ME_Cursor startCur = *start;
5044 if (!editor->AutoURLDetect_bEnable) return FALSE;
5048 CHARFORMAT2W link;
5049 ME_Cursor candidateStart, candidateEnd;
5051 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5052 &candidateStart, &candidateEnd))
5054 /* Section before candidate is not an URL */
5055 int cMin = ME_GetCursorOfs(&candidateStart);
5056 int cMax = ME_GetCursorOfs(&candidateEnd);
5058 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5059 candidateStart = candidateEnd;
5060 nChars -= cMax - ME_GetCursorOfs(&startCur);
5062 else
5064 /* No more candidates until end of selection */
5065 nChars = 0;
5068 if (startCur.pRun != candidateStart.pRun ||
5069 startCur.nOffset != candidateStart.nOffset)
5071 /* CFE_LINK effect should be consistently unset */
5072 link.cbSize = sizeof(link);
5073 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5074 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5076 /* CFE_LINK must be unset from this range */
5077 memset(&link, 0, sizeof(CHARFORMAT2W));
5078 link.cbSize = sizeof(link);
5079 link.dwMask = CFM_LINK;
5080 link.dwEffects = 0;
5081 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5082 /* Update candidateEnd since setting character formats may split
5083 * runs, which can cause a cursor to be at an invalid offset within
5084 * a split run. */
5085 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5087 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5088 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5090 modified = TRUE;
5093 if (candidateStart.pRun != candidateEnd.pRun ||
5094 candidateStart.nOffset != candidateEnd.nOffset)
5096 /* CFE_LINK effect should be consistently set */
5097 link.cbSize = sizeof(link);
5098 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5099 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5101 /* CFE_LINK must be set on this range */
5102 memset(&link, 0, sizeof(CHARFORMAT2W));
5103 link.cbSize = sizeof(link);
5104 link.dwMask = CFM_LINK;
5105 link.dwEffects = CFE_LINK;
5106 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5107 modified = TRUE;
5110 startCur = candidateEnd;
5111 } while (nChars > 0);
5112 return modified;