riched20: Implement ITextSelection::Collapse.
[wine/multimedia.git] / dlls / riched20 / editor.c
blob3c0d970e2bc132fa43922ba86b4a2f366abba30a
1 /*
2 * RichEdit - functions dealing with editor object
4 * Copyright 2004 by Krzysztof Foltman
5 * Copyright 2005 by Cihan Altinay
6 * Copyright 2005 by Phil Krylov
7 * Copyright 2008 Eric Pouech
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 /*
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
29 + EM_CANPASTE
30 + EM_CANREDO 2.0
31 + EM_CANUNDO
32 + EM_CHARFROMPOS
33 - EM_DISPLAYBAND
34 + EM_EMPTYUNDOBUFFER
35 + EM_EXGETSEL
36 + EM_EXLIMITTEXT
37 + EM_EXLINEFROMCHAR
38 + EM_EXSETSEL
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41 - EM_FINDWORDBREAK
42 - EM_FMTLINES
43 - EM_FORMATRANGE
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
47 - EM_GETEDITSTYLE
48 + EM_GETEVENTMASK
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
53 - EM_GETIMESTATUS
54 - EM_GETLANGOPTIONS 2.0
55 + EM_GETLIMITTEXT
56 + EM_GETLINE
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
58 + EM_GETMODIFY
59 + EM_GETOLEINTERFACE
60 + EM_GETOPTIONS
61 + EM_GETPARAFORMAT
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
64 + EM_GETRECT
65 - EM_GETREDONAME 2.0
66 + EM_GETSEL
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0
69 ! - EM_GETTHUMB
70 + EM_GETTEXTEX 2.0
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72 + EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
75 - EM_GETUNDONAME
76 + EM_GETWORDBREAKPROC
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
79 + EM_GETZOOM 3.0
80 + EM_HIDESELECTION
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82 + EM_LINEFROMCHAR
83 + EM_LINEINDEX
84 + EM_LINELENGTH
85 + EM_LINESCROLL
86 - EM_PASTESPECIAL
87 + EM_POSFROMCHAR
88 + EM_REDO 2.0
89 + EM_REQUESTRESIZE
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
91 + EM_SCROLL
92 + EM_SCROLLCARET
93 - EM_SELECTIONTYPE
94 - EM_SETBIDIOPTIONS 3.0
95 + EM_SETBKGNDCOLOR
96 + EM_SETCHARFORMAT (partly done, no ANSI)
97 - EM_SETEDITSTYLE
98 + EM_SETEVENTMASK (few notifications supported)
99 - EM_SETFONTSIZE
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETIMESTATUS
103 - EM_SETLANGOPTIONS 2.0
104 - EM_SETLIMITTEXT
105 - EM_SETMARGINS
106 + EM_SETMODIFY (not sure if implementation is correct)
107 - EM_SETOLECALLBACK
108 + EM_SETOPTIONS (partially implemented)
109 - EM_SETPALETTE 2.0
110 + EM_SETPARAFORMAT
111 + EM_SETPASSWORDCHAR 2.0
112 - EM_SETPUNCTUATION 1.0asian
113 + EM_SETREADONLY no beep on modification attempt
114 + EM_SETRECT
115 + EM_SETRECTNP (EM_SETRECT without repainting)
116 + EM_SETSEL
117 + EM_SETSCROLLPOS 3.0
118 - EM_SETTABSTOPS 3.0
119 - EM_SETTARGETDEVICE (partial)
120 + EM_SETTEXTEX 3.0 (proper style?)
121 - EM_SETTEXTMODE 2.0
122 - EM_SETTYPOGRAPHYOPTIONS 3.0
123 + EM_SETUNDOLIMIT 2.0
124 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
125 - EM_SETWORDBREAKPROCEX
126 - EM_SETWORDWRAPMODE 1.0asian
127 + EM_SETZOOM 3.0
128 + EM_SHOWSCROLLBAR 2.0
129 + EM_STOPGROUPTYPING 2.0
130 + EM_STREAMIN
131 + EM_STREAMOUT
132 + EM_UNDO
133 + WM_CHAR
134 + WM_CLEAR
135 + WM_COPY
136 + WM_CUT
137 + WM_GETDLGCODE (the current implementation is incomplete)
138 + WM_GETTEXT (ANSI&Unicode)
139 + WM_GETTEXTLENGTH (ANSI version sucks)
140 + WM_HSCROLL
141 + WM_PASTE
142 + WM_SETFONT
143 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144 + WM_STYLECHANGING (seems to do nothing)
145 + WM_STYLECHANGED (seems to do nothing)
146 + WM_UNICHAR
147 + WM_VSCROLL
149 Notifications
151 * EN_CHANGE (sent from the wrong place)
152 - EN_CORRECTTEXT
153 - EN_DROPFILES
154 - EN_ERRSPACE
155 - EN_HSCROLL
156 - EN_IMECHANGE
157 + EN_KILLFOCUS
158 - EN_LINK
159 - EN_MAXTEXT
160 - EN_MSGFILTER
161 - EN_OLEOPFAILED
162 - EN_PROTECTED
163 + EN_REQUESTRESIZE
164 - EN_SAVECLIPBOARD
165 + EN_SELCHANGE
166 + EN_SETFOCUS
167 - EN_STOPNOUNDO
168 * EN_UPDATE (sent from the wrong place)
169 - EN_VSCROLL
171 Styles
173 - ES_AUTOHSCROLL
174 - ES_AUTOVSCROLL
175 - ES_CENTER
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
178 - ES_LEFT
179 - ES_MULTILINE (currently single line controls aren't supported)
180 - ES_NOIME
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182 - ES_RIGHT
183 - ES_SAVESEL
184 - ES_SELFIME
185 - ES_SUNKEN
186 - ES_VERTICAL
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188 - WS_SETFONT
189 + WS_HSCROLL
190 + WS_VSCROLL
194 * RICHED20 TODO (incomplete):
196 * - messages/styles/notifications listed above
197 * - add remaining CHARFORMAT/PARAFORMAT fields
198 * - right/center align should strip spaces from the beginning
199 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200 * - COM interface (looks like a major pain in the TODO list)
201 * - calculate heights of pictures (half-done)
202 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203 * - find/replace
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
206 * - IME
207 * - most notifications aren't sent at all (the most important ones are)
208 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211 * - full justification
212 * - hyphenation
213 * - tables
214 * - ListBox & ComboBox not implemented
216 * Bugs that are probably fixed, but not so easy to verify:
217 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220 * - caret shouldn't be displayed when selection isn't empty
221 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222 * - undo for setting default format (done, might be buggy)
223 * - styles might be not released properly (looks like they work like charm, but who knows?
227 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
236 #define STACK_SIZE_DEFAULT 100
237 #define STACK_SIZE_MAX 1000
239 #define TEXT_LIMIT_DEFAULT 32767
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
250 BOOL me_debug = FALSE;
251 HANDLE me_heap = NULL;
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
256 static inline BOOL is_version_nt(void)
258 return !(GetVersion() & 0x80000000);
261 static ME_TextBuffer *ME_MakeText(void) {
263 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
265 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
268 p1->prev = NULL;
269 p1->next = p2;
270 p2->prev = p1;
271 p2->next = NULL;
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
276 buf->pFirst = p1;
277 buf->pLast = p2;
278 buf->pCharStyle = NULL;
280 return buf;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR *pText;
287 LRESULT total_bytes_read = 0;
288 BOOL is_read = FALSE;
289 DWORD cp = CP_ACP, copy = 0;
290 char conv_buf[4 + STREAMIN_BUFFER_SIZE]; /* up to 4 additional UTF-8 bytes */
292 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
294 TRACE("%08x %p\n", dwFormat, stream);
296 do {
297 LONG nWideChars = 0;
298 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
300 if (!stream->dwSize)
302 ME_StreamInFill(stream);
303 if (stream->editstream->dwError)
304 break;
305 if (!stream->dwSize)
306 break;
307 total_bytes_read += stream->dwSize;
310 if (!(dwFormat & SF_UNICODE))
312 char * buf = stream->buffer;
313 DWORD size = stream->dwSize, end;
315 if (!is_read)
317 is_read = TRUE;
318 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
320 cp = CP_UTF8;
321 buf += 3;
322 size -= 3;
326 if (cp == CP_UTF8)
328 if (copy)
330 memcpy(conv_buf + copy, buf, size);
331 buf = conv_buf;
332 size += copy;
334 end = size;
335 while ((buf[end-1] & 0xC0) == 0x80)
337 --end;
338 --total_bytes_read; /* strange, but seems to match windows */
340 if (buf[end-1] & 0x80)
342 DWORD need = 0;
343 if ((buf[end-1] & 0xE0) == 0xC0)
344 need = 1;
345 if ((buf[end-1] & 0xF0) == 0xE0)
346 need = 2;
347 if ((buf[end-1] & 0xF8) == 0xF0)
348 need = 3;
350 if (size - end >= need)
352 /* we have enough bytes for this sequence */
353 end = size;
355 else
357 /* need more bytes, so don't transcode this sequence */
358 --end;
362 else
363 end = size;
365 nWideChars = MultiByteToWideChar(cp, 0, buf, end, wszText, STREAMIN_BUFFER_SIZE);
366 pText = wszText;
368 if (cp == CP_UTF8)
370 if (end != size)
372 memcpy(conv_buf, buf + end, size - end);
373 copy = size - end;
377 else
379 nWideChars = stream->dwSize >> 1;
380 pText = (WCHAR *)stream->buffer;
383 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
384 if (stream->dwSize == 0)
385 break;
386 stream->dwSize = 0;
387 } while(1);
388 return total_bytes_read;
391 static void ME_ApplyBorderProperties(RTF_Info *info,
392 ME_BorderRect *borderRect,
393 RTFBorder *borderDef)
395 int i, colorNum;
396 ME_Border *pBorders[] = {&borderRect->top,
397 &borderRect->left,
398 &borderRect->bottom,
399 &borderRect->right};
400 for (i = 0; i < 4; i++)
402 RTFColor *colorDef = info->colorList;
403 pBorders[i]->width = borderDef[i].width;
404 colorNum = borderDef[i].color;
405 while (colorDef && colorDef->rtfCNum != colorNum)
406 colorDef = colorDef->rtfNextColor;
407 if (colorDef)
408 pBorders[i]->colorRef = RGB(
409 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
410 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
411 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
412 else
413 pBorders[i]->colorRef = RGB(0, 0, 0);
417 void ME_RTFCharAttrHook(RTF_Info *info)
419 CHARFORMAT2W fmt;
420 fmt.cbSize = sizeof(fmt);
421 fmt.dwMask = 0;
422 fmt.dwEffects = 0;
424 switch(info->rtfMinor)
426 case rtfPlain:
427 /* FIXME add more flags once they're implemented */
428 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
429 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
430 fmt.yHeight = 12*20; /* 12pt */
431 fmt.wWeight = FW_NORMAL;
432 fmt.bUnderlineType = CFU_UNDERLINENONE;
433 break;
434 case rtfBold:
435 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
436 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
437 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
438 break;
439 case rtfItalic:
440 fmt.dwMask = CFM_ITALIC;
441 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
442 break;
443 case rtfUnderline:
444 fmt.dwMask = CFM_UNDERLINETYPE;
445 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
446 break;
447 case rtfDotUnderline:
448 fmt.dwMask = CFM_UNDERLINETYPE;
449 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
450 break;
451 case rtfDbUnderline:
452 fmt.dwMask = CFM_UNDERLINETYPE;
453 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
454 break;
455 case rtfWordUnderline:
456 fmt.dwMask = CFM_UNDERLINETYPE;
457 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
458 break;
459 case rtfNoUnderline:
460 fmt.dwMask = CFM_UNDERLINETYPE;
461 fmt.bUnderlineType = CFU_UNDERLINENONE;
462 break;
463 case rtfStrikeThru:
464 fmt.dwMask = CFM_STRIKEOUT;
465 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
466 break;
467 case rtfSubScript:
468 case rtfSuperScript:
469 case rtfSubScrShrink:
470 case rtfSuperScrShrink:
471 case rtfNoSuperSub:
472 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
473 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
474 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
475 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
476 break;
477 case rtfInvisible:
478 fmt.dwMask = CFM_HIDDEN;
479 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
480 break;
481 case rtfBackColor:
482 fmt.dwMask = CFM_BACKCOLOR;
483 fmt.dwEffects = 0;
484 if (info->rtfParam == 0)
485 fmt.dwEffects = CFE_AUTOBACKCOLOR;
486 else if (info->rtfParam != rtfNoParam)
488 RTFColor *c = RTFGetColor(info, info->rtfParam);
489 if (c && c->rtfCBlue >= 0)
490 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
491 else
492 fmt.dwEffects = CFE_AUTOBACKCOLOR;
494 break;
495 case rtfForeColor:
496 fmt.dwMask = CFM_COLOR;
497 fmt.dwEffects = 0;
498 if (info->rtfParam == 0)
499 fmt.dwEffects = CFE_AUTOCOLOR;
500 else if (info->rtfParam != rtfNoParam)
502 RTFColor *c = RTFGetColor(info, info->rtfParam);
503 if (c && c->rtfCBlue >= 0)
504 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
505 else {
506 fmt.dwEffects = CFE_AUTOCOLOR;
509 break;
510 case rtfFontNum:
511 if (info->rtfParam != rtfNoParam)
513 RTFFont *f = RTFGetFont(info, info->rtfParam);
514 if (f)
516 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
517 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
518 fmt.bCharSet = f->rtfFCharSet;
519 fmt.dwMask = CFM_FACE | CFM_CHARSET;
520 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
523 break;
524 case rtfFontSize:
525 fmt.dwMask = CFM_SIZE;
526 if (info->rtfParam != rtfNoParam)
527 fmt.yHeight = info->rtfParam*10;
528 break;
530 if (fmt.dwMask) {
531 ME_Style *style2;
532 RTFFlushOutputBuffer(info);
533 /* FIXME too slow ? how come ? */
534 style2 = ME_ApplyStyle(info->style, &fmt);
535 ME_ReleaseStyle(info->style);
536 info->style = style2;
537 info->styleChanged = TRUE;
541 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
542 the same tags mean different things in different contexts */
543 void ME_RTFParAttrHook(RTF_Info *info)
545 PARAFORMAT2 fmt;
546 fmt.cbSize = sizeof(fmt);
547 fmt.dwMask = 0;
549 switch(info->rtfMinor)
551 case rtfParDef: /* restores default paragraph attributes */
552 if (!info->editor->bEmulateVersion10) /* v4.1 */
553 info->borderType = RTFBorderParaLeft;
554 else /* v1.0 - 3.0 */
555 info->borderType = RTFBorderParaTop;
556 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
557 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
558 PFM_STARTINDENT;
559 /* TODO: numbering, shading */
560 fmt.wAlignment = PFA_LEFT;
561 fmt.cTabCount = 0;
562 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
563 fmt.wBorderWidth = fmt.wBorders = 0;
564 fmt.wBorderSpace = 0;
565 fmt.bLineSpacingRule = 0;
566 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
567 fmt.dyLineSpacing = 0;
568 if (!info->editor->bEmulateVersion10) /* v4.1 */
570 if (info->tableDef && info->tableDef->tableRowStart &&
571 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
573 ME_Cursor cursor;
574 ME_DisplayItem *para;
575 /* We are just after a table row. */
576 RTFFlushOutputBuffer(info);
577 cursor = info->editor->pCursors[0];
578 para = cursor.pPara;
579 if (para == info->tableDef->tableRowStart->member.para.next_para
580 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
582 /* Since the table row end, no text has been inserted, and the \intbl
583 * control word has not be used. We can confirm that we are not in a
584 * table anymore.
586 info->tableDef->tableRowStart = NULL;
587 info->canInheritInTbl = FALSE;
590 } else { /* v1.0 - v3.0 */
591 fmt.dwMask |= PFM_TABLE;
592 fmt.wEffects &= ~PFE_TABLE;
594 break;
595 case rtfNestLevel:
596 if (!info->editor->bEmulateVersion10) /* v4.1 */
598 while (info->rtfParam > info->nestingLevel) {
599 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
600 ZeroMemory(tableDef, sizeof(RTFTable));
601 tableDef->parent = info->tableDef;
602 info->tableDef = tableDef;
604 RTFFlushOutputBuffer(info);
605 if (tableDef->tableRowStart &&
606 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
608 ME_DisplayItem *para = tableDef->tableRowStart;
609 para = para->member.para.next_para;
610 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
611 tableDef->tableRowStart = para;
612 } else {
613 ME_Cursor cursor;
614 WCHAR endl = '\r';
615 cursor = info->editor->pCursors[0];
616 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
617 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
618 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
621 info->nestingLevel++;
623 info->canInheritInTbl = FALSE;
625 break;
626 case rtfInTable:
628 if (!info->editor->bEmulateVersion10) /* v4.1 */
630 if (info->nestingLevel < 1)
632 RTFTable *tableDef;
633 if (!info->tableDef)
635 info->tableDef = ALLOC_OBJ(RTFTable);
636 ZeroMemory(info->tableDef, sizeof(RTFTable));
638 tableDef = info->tableDef;
639 RTFFlushOutputBuffer(info);
640 if (tableDef->tableRowStart &&
641 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
643 ME_DisplayItem *para = tableDef->tableRowStart;
644 para = para->member.para.next_para;
645 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
646 tableDef->tableRowStart = para;
647 } else {
648 ME_Cursor cursor;
649 WCHAR endl = '\r';
650 cursor = info->editor->pCursors[0];
651 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
652 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
653 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
655 info->nestingLevel = 1;
656 info->canInheritInTbl = TRUE;
658 return;
659 } else { /* v1.0 - v3.0 */
660 fmt.dwMask |= PFM_TABLE;
661 fmt.wEffects |= PFE_TABLE;
663 break;
665 case rtfFirstIndent:
666 ME_GetSelectionParaFormat(info->editor, &fmt);
667 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
668 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
669 fmt.dxOffset = -info->rtfParam;
670 break;
671 case rtfLeftIndent:
672 ME_GetSelectionParaFormat(info->editor, &fmt);
673 fmt.dwMask = PFM_STARTINDENT;
674 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
675 break;
676 case rtfRightIndent:
677 fmt.dwMask = PFM_RIGHTINDENT;
678 fmt.dxRightIndent = info->rtfParam;
679 break;
680 case rtfQuadLeft:
681 case rtfQuadJust:
682 fmt.dwMask = PFM_ALIGNMENT;
683 fmt.wAlignment = PFA_LEFT;
684 break;
685 case rtfQuadRight:
686 fmt.dwMask = PFM_ALIGNMENT;
687 fmt.wAlignment = PFA_RIGHT;
688 break;
689 case rtfQuadCenter:
690 fmt.dwMask = PFM_ALIGNMENT;
691 fmt.wAlignment = PFA_CENTER;
692 break;
693 case rtfTabPos:
694 ME_GetSelectionParaFormat(info->editor, &fmt);
695 if (!(fmt.dwMask & PFM_TABSTOPS))
697 fmt.cTabCount = 0;
699 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
700 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
701 fmt.dwMask = PFM_TABSTOPS;
702 break;
703 case rtfKeep:
704 fmt.dwMask = PFM_KEEP;
705 fmt.wEffects = PFE_KEEP;
706 break;
707 case rtfNoWidowControl:
708 fmt.dwMask = PFM_NOWIDOWCONTROL;
709 fmt.wEffects = PFE_NOWIDOWCONTROL;
710 break;
711 case rtfKeepNext:
712 fmt.dwMask = PFM_KEEPNEXT;
713 fmt.wEffects = PFE_KEEPNEXT;
714 break;
715 case rtfSpaceAfter:
716 fmt.dwMask = PFM_SPACEAFTER;
717 fmt.dySpaceAfter = info->rtfParam;
718 break;
719 case rtfSpaceBefore:
720 fmt.dwMask = PFM_SPACEBEFORE;
721 fmt.dySpaceBefore = info->rtfParam;
722 break;
723 case rtfSpaceBetween:
724 fmt.dwMask = PFM_LINESPACING;
725 if ((int)info->rtfParam > 0)
727 fmt.dyLineSpacing = info->rtfParam;
728 fmt.bLineSpacingRule = 3;
730 else
732 fmt.dyLineSpacing = info->rtfParam;
733 fmt.bLineSpacingRule = 4;
735 break;
736 case rtfSpaceMultiply:
737 fmt.dwMask = PFM_LINESPACING;
738 fmt.dyLineSpacing = info->rtfParam * 20;
739 fmt.bLineSpacingRule = 5;
740 break;
741 case rtfParBullet:
742 fmt.dwMask = PFM_NUMBERING;
743 fmt.wNumbering = PFN_BULLET;
744 break;
745 case rtfParSimple:
746 fmt.dwMask = PFM_NUMBERING;
747 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
748 break;
749 case rtfParNumDecimal:
750 fmt.dwMask = PFM_NUMBERING;
751 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
752 break;
753 case rtfParNumIndent:
754 fmt.dwMask = PFM_NUMBERINGTAB;
755 fmt.wNumberingTab = info->rtfParam;
756 break;
757 case rtfParNumStartAt:
758 fmt.dwMask = PFM_NUMBERINGSTART;
759 fmt.wNumberingStart = info->rtfParam;
760 break;
761 case rtfBorderLeft:
762 info->borderType = RTFBorderParaLeft;
763 ME_GetSelectionParaFormat(info->editor, &fmt);
764 if (!(fmt.dwMask & PFM_BORDER))
766 fmt.wBorderSpace = 0;
767 fmt.wBorderWidth = 1;
768 fmt.wBorders = 0;
770 fmt.wBorders |= 1;
771 fmt.dwMask = PFM_BORDER;
772 break;
773 case rtfBorderRight:
774 info->borderType = RTFBorderParaRight;
775 ME_GetSelectionParaFormat(info->editor, &fmt);
776 if (!(fmt.dwMask & PFM_BORDER))
778 fmt.wBorderSpace = 0;
779 fmt.wBorderWidth = 1;
780 fmt.wBorders = 0;
782 fmt.wBorders |= 2;
783 fmt.dwMask = PFM_BORDER;
784 break;
785 case rtfBorderTop:
786 info->borderType = RTFBorderParaTop;
787 ME_GetSelectionParaFormat(info->editor, &fmt);
788 if (!(fmt.dwMask & PFM_BORDER))
790 fmt.wBorderSpace = 0;
791 fmt.wBorderWidth = 1;
792 fmt.wBorders = 0;
794 fmt.wBorders |= 4;
795 fmt.dwMask = PFM_BORDER;
796 break;
797 case rtfBorderBottom:
798 info->borderType = RTFBorderParaBottom;
799 ME_GetSelectionParaFormat(info->editor, &fmt);
800 if (!(fmt.dwMask & PFM_BORDER))
802 fmt.wBorderSpace = 0;
803 fmt.wBorderWidth = 1;
804 fmt.wBorders = 0;
806 fmt.wBorders |= 8;
807 fmt.dwMask = PFM_BORDER;
808 break;
809 case rtfBorderSingle:
810 ME_GetSelectionParaFormat(info->editor, &fmt);
811 /* we assume that borders have been created before (RTF spec) */
812 fmt.wBorders &= ~0x700;
813 fmt.wBorders |= 1 << 8;
814 fmt.dwMask = PFM_BORDER;
815 break;
816 case rtfBorderThick:
817 ME_GetSelectionParaFormat(info->editor, &fmt);
818 /* we assume that borders have been created before (RTF spec) */
819 fmt.wBorders &= ~0x700;
820 fmt.wBorders |= 2 << 8;
821 fmt.dwMask = PFM_BORDER;
822 break;
823 case rtfBorderShadow:
824 ME_GetSelectionParaFormat(info->editor, &fmt);
825 /* we assume that borders have been created before (RTF spec) */
826 fmt.wBorders &= ~0x700;
827 fmt.wBorders |= 10 << 8;
828 fmt.dwMask = PFM_BORDER;
829 break;
830 case rtfBorderDouble:
831 ME_GetSelectionParaFormat(info->editor, &fmt);
832 /* we assume that borders have been created before (RTF spec) */
833 fmt.wBorders &= ~0x700;
834 fmt.wBorders |= 7 << 8;
835 fmt.dwMask = PFM_BORDER;
836 break;
837 case rtfBorderDot:
838 ME_GetSelectionParaFormat(info->editor, &fmt);
839 /* we assume that borders have been created before (RTF spec) */
840 fmt.wBorders &= ~0x700;
841 fmt.wBorders |= 11 << 8;
842 fmt.dwMask = PFM_BORDER;
843 break;
844 case rtfBorderWidth:
846 int borderSide = info->borderType & RTFBorderSideMask;
847 RTFTable *tableDef = info->tableDef;
848 ME_GetSelectionParaFormat(info->editor, &fmt);
849 /* we assume that borders have been created before (RTF spec) */
850 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
851 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
853 RTFBorder *border;
854 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
855 break;
856 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
857 border->width = info->rtfParam;
858 break;
860 fmt.dwMask = PFM_BORDER;
861 break;
863 case rtfBorderSpace:
864 ME_GetSelectionParaFormat(info->editor, &fmt);
865 /* we assume that borders have been created before (RTF spec) */
866 fmt.wBorderSpace = info->rtfParam;
867 fmt.dwMask = PFM_BORDER;
868 break;
869 case rtfBorderColor:
871 RTFTable *tableDef = info->tableDef;
872 int borderSide = info->borderType & RTFBorderSideMask;
873 int borderType = info->borderType & RTFBorderTypeMask;
874 switch(borderType)
876 case RTFBorderTypePara:
877 if (!info->editor->bEmulateVersion10) /* v4.1 */
878 break;
879 /* v1.0 - 3.0 treat paragraph and row borders the same. */
880 case RTFBorderTypeRow:
881 if (tableDef) {
882 tableDef->border[borderSide].color = info->rtfParam;
884 break;
885 case RTFBorderTypeCell:
886 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
887 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
889 break;
891 break;
893 case rtfRTLPar:
894 fmt.dwMask = PFM_RTLPARA;
895 fmt.wEffects = PFE_RTLPARA;
896 break;
897 case rtfLTRPar:
898 fmt.dwMask = PFM_RTLPARA;
899 fmt.wEffects = 0;
900 break;
902 if (fmt.dwMask) {
903 RTFFlushOutputBuffer(info);
904 /* FIXME too slow ? how come ?*/
905 ME_SetSelectionParaFormat(info->editor, &fmt);
909 void ME_RTFTblAttrHook(RTF_Info *info)
911 switch (info->rtfMinor)
913 case rtfRowDef:
915 if (!info->editor->bEmulateVersion10) /* v4.1 */
916 info->borderType = 0; /* Not sure */
917 else /* v1.0 - 3.0 */
918 info->borderType = RTFBorderRowTop;
919 if (!info->tableDef) {
920 info->tableDef = ME_MakeTableDef(info->editor);
921 } else {
922 ME_InitTableDef(info->editor, info->tableDef);
924 break;
926 case rtfCellPos:
928 int cellNum;
929 if (!info->tableDef)
931 info->tableDef = ME_MakeTableDef(info->editor);
933 cellNum = info->tableDef->numCellsDefined;
934 if (cellNum >= MAX_TABLE_CELLS)
935 break;
936 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
937 if (cellNum < MAX_TAB_STOPS) {
938 /* Tab stops were used to store cell positions before v4.1 but v4.1
939 * still seems to set the tabstops without using them. */
940 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
941 PARAFORMAT2 *pFmt = para->member.para.pFmt;
942 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
943 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
945 info->tableDef->numCellsDefined++;
946 break;
948 case rtfRowBordTop:
949 info->borderType = RTFBorderRowTop;
950 break;
951 case rtfRowBordLeft:
952 info->borderType = RTFBorderRowLeft;
953 break;
954 case rtfRowBordBottom:
955 info->borderType = RTFBorderRowBottom;
956 break;
957 case rtfRowBordRight:
958 info->borderType = RTFBorderRowRight;
959 break;
960 case rtfCellBordTop:
961 info->borderType = RTFBorderCellTop;
962 break;
963 case rtfCellBordLeft:
964 info->borderType = RTFBorderCellLeft;
965 break;
966 case rtfCellBordBottom:
967 info->borderType = RTFBorderCellBottom;
968 break;
969 case rtfCellBordRight:
970 info->borderType = RTFBorderCellRight;
971 break;
972 case rtfRowGapH:
973 if (info->tableDef)
974 info->tableDef->gapH = info->rtfParam;
975 break;
976 case rtfRowLeftEdge:
977 if (info->tableDef)
978 info->tableDef->leftEdge = info->rtfParam;
979 break;
983 void ME_RTFSpecialCharHook(RTF_Info *info)
985 RTFTable *tableDef = info->tableDef;
986 switch (info->rtfMinor)
988 case rtfNestCell:
989 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
990 break;
991 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
992 case rtfCell:
993 if (!tableDef)
994 break;
995 RTFFlushOutputBuffer(info);
996 if (!info->editor->bEmulateVersion10) { /* v4.1 */
997 if (tableDef->tableRowStart)
999 if (!info->nestingLevel &&
1000 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1002 ME_DisplayItem *para = tableDef->tableRowStart;
1003 para = para->member.para.next_para;
1004 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1005 tableDef->tableRowStart = para;
1006 info->nestingLevel = 1;
1008 ME_InsertTableCellFromCursor(info->editor);
1010 } else { /* v1.0 - v3.0 */
1011 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1012 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1013 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
1014 tableDef->numCellsInserted < tableDef->numCellsDefined)
1016 WCHAR tab = '\t';
1017 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1018 tableDef->numCellsInserted++;
1021 break;
1022 case rtfNestRow:
1023 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
1024 break;
1025 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
1026 case rtfRow:
1028 ME_DisplayItem *para, *cell, *run;
1029 int i;
1031 if (!tableDef)
1032 break;
1033 RTFFlushOutputBuffer(info);
1034 if (!info->editor->bEmulateVersion10) { /* v4.1 */
1035 if (!tableDef->tableRowStart)
1036 break;
1037 if (!info->nestingLevel &&
1038 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1040 para = tableDef->tableRowStart;
1041 para = para->member.para.next_para;
1042 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1043 tableDef->tableRowStart = para;
1044 info->nestingLevel++;
1046 para = tableDef->tableRowStart;
1047 cell = ME_FindItemFwd(para, diCell);
1048 assert(cell && !cell->member.cell.prev_cell);
1049 if (tableDef->numCellsDefined < 1)
1051 /* 2000 twips appears to be the cell size that native richedit uses
1052 * when no cell sizes are specified. */
1053 const int defaultCellSize = 2000;
1054 int nRightBoundary = defaultCellSize;
1055 cell->member.cell.nRightBoundary = nRightBoundary;
1056 while (cell->member.cell.next_cell) {
1057 cell = cell->member.cell.next_cell;
1058 nRightBoundary += defaultCellSize;
1059 cell->member.cell.nRightBoundary = nRightBoundary;
1061 para = ME_InsertTableCellFromCursor(info->editor);
1062 cell = para->member.para.pCell;
1063 cell->member.cell.nRightBoundary = nRightBoundary;
1064 } else {
1065 for (i = 0; i < tableDef->numCellsDefined; i++)
1067 RTFCell *cellDef = &tableDef->cells[i];
1068 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1069 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1070 cellDef->border);
1071 cell = cell->member.cell.next_cell;
1072 if (!cell)
1074 para = ME_InsertTableCellFromCursor(info->editor);
1075 cell = para->member.para.pCell;
1078 /* Cell for table row delimiter is empty */
1079 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1082 run = ME_FindItemFwd(cell, diRun);
1083 if (info->editor->pCursors[0].pRun != run ||
1084 info->editor->pCursors[0].nOffset)
1086 int nOfs, nChars;
1087 /* Delete inserted cells that aren't defined. */
1088 info->editor->pCursors[1].pRun = run;
1089 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1090 info->editor->pCursors[1].nOffset = 0;
1091 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1092 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1093 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1094 nChars, TRUE);
1097 para = ME_InsertTableRowEndFromCursor(info->editor);
1098 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1099 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1100 ME_ApplyBorderProperties(info, &para->member.para.border,
1101 tableDef->border);
1102 info->nestingLevel--;
1103 if (!info->nestingLevel)
1105 if (info->canInheritInTbl) {
1106 tableDef->tableRowStart = para;
1107 } else {
1108 while (info->tableDef) {
1109 tableDef = info->tableDef;
1110 info->tableDef = tableDef->parent;
1111 heap_free(tableDef);
1114 } else {
1115 info->tableDef = tableDef->parent;
1116 heap_free(tableDef);
1118 } else { /* v1.0 - v3.0 */
1119 WCHAR endl = '\r';
1120 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1121 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1122 pFmt->dxOffset = info->tableDef->gapH;
1123 pFmt->dxStartIndent = info->tableDef->leftEdge;
1125 ME_ApplyBorderProperties(info, &para->member.para.border,
1126 tableDef->border);
1127 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1129 WCHAR tab = '\t';
1130 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1131 tableDef->numCellsInserted++;
1133 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1134 if (!tableDef->numCellsDefined)
1135 pFmt->wEffects &= ~PFE_TABLE;
1136 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1137 tableDef->numCellsInserted = 0;
1139 break;
1141 case rtfTab:
1142 case rtfPar:
1143 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1144 ME_DisplayItem *para;
1145 PARAFORMAT2 *pFmt;
1146 RTFFlushOutputBuffer(info);
1147 para = info->editor->pCursors[0].pPara;
1148 pFmt = para->member.para.pFmt;
1149 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1151 /* rtfPar is treated like a space within a table. */
1152 info->rtfClass = rtfText;
1153 info->rtfMajor = ' ';
1155 else if (info->rtfMinor == rtfPar && tableDef)
1156 tableDef->numCellsInserted = 0;
1158 break;
1162 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1163 const SIZEL* sz)
1165 LPOLEOBJECT lpObject = NULL;
1166 LPSTORAGE lpStorage = NULL;
1167 LPOLECLIENTSITE lpClientSite = NULL;
1168 LPDATAOBJECT lpDataObject = NULL;
1169 LPOLECACHE lpOleCache = NULL;
1170 STGMEDIUM stgm;
1171 FORMATETC fm;
1172 CLSID clsid;
1173 BOOL ret = FALSE;
1174 DWORD conn;
1176 if (hemf)
1178 stgm.tymed = TYMED_ENHMF;
1179 stgm.u.hEnhMetaFile = hemf;
1180 fm.cfFormat = CF_ENHMETAFILE;
1182 else if (hbmp)
1184 stgm.tymed = TYMED_GDI;
1185 stgm.u.hBitmap = hbmp;
1186 fm.cfFormat = CF_BITMAP;
1188 stgm.pUnkForRelease = NULL;
1190 fm.ptd = NULL;
1191 fm.dwAspect = DVASPECT_CONTENT;
1192 fm.lindex = -1;
1193 fm.tymed = stgm.tymed;
1195 if (!info->lpRichEditOle)
1197 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1200 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1201 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1202 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1203 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1204 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1205 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1206 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1207 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1209 REOBJECT reobject;
1211 reobject.cbStruct = sizeof(reobject);
1212 reobject.cp = REO_CP_SELECTION;
1213 reobject.clsid = clsid;
1214 reobject.poleobj = lpObject;
1215 reobject.pstg = lpStorage;
1216 reobject.polesite = lpClientSite;
1217 /* convert from twips to .01 mm */
1218 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1219 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1220 reobject.dvaspect = DVASPECT_CONTENT;
1221 reobject.dwFlags = 0; /* FIXME */
1222 reobject.dwUser = 0;
1224 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1225 ret = TRUE;
1228 if (lpObject) IOleObject_Release(lpObject);
1229 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1230 if (lpStorage) IStorage_Release(lpStorage);
1231 if (lpDataObject) IDataObject_Release(lpDataObject);
1232 if (lpOleCache) IOleCache_Release(lpOleCache);
1234 return ret;
1237 static void ME_RTFReadPictGroup(RTF_Info *info)
1239 SIZEL sz;
1240 BYTE* buffer = NULL;
1241 unsigned bufsz, bufidx;
1242 BOOL flip;
1243 BYTE val;
1244 METAFILEPICT mfp;
1245 HENHMETAFILE hemf;
1246 HBITMAP hbmp;
1247 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1249 RTFGetToken (info);
1250 if (info->rtfClass == rtfEOF)
1251 return;
1252 mfp.mm = MM_TEXT;
1253 /* fetch picture type */
1254 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1256 mfp.mm = info->rtfParam;
1257 gfx = gfx_metafile;
1259 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1261 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1262 gfx = gfx_dib;
1264 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1266 gfx = gfx_enhmetafile;
1268 else
1270 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1271 goto skip_group;
1273 sz.cx = sz.cy = 0;
1274 /* fetch picture attributes */
1275 for (;;)
1277 RTFGetToken (info);
1278 if (info->rtfClass == rtfEOF)
1279 return;
1280 if (info->rtfClass == rtfText)
1281 break;
1282 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1284 ERR("Expected picture attribute (%d %d)\n",
1285 info->rtfClass, info->rtfMajor);
1286 goto skip_group;
1288 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1290 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1292 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1294 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1296 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1297 sz.cx = info->rtfParam;
1298 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1299 sz.cy = info->rtfParam;
1300 else
1301 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1303 /* fetch picture data */
1304 bufsz = 1024;
1305 bufidx = 0;
1306 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1307 val = info->rtfMajor;
1308 for (flip = TRUE;; flip = !flip)
1310 RTFGetToken (info);
1311 if (info->rtfClass == rtfEOF)
1313 HeapFree(GetProcessHeap(), 0, buffer);
1314 return; /* Warn ?? */
1316 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1317 break;
1318 if (info->rtfClass != rtfText) goto skip_group;
1319 if (flip)
1321 if (bufidx >= bufsz &&
1322 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1323 goto skip_group;
1324 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1326 else
1327 val = info->rtfMajor;
1329 if (flip) FIXME("wrong hex string\n");
1331 switch (gfx)
1333 case gfx_enhmetafile:
1334 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1335 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1336 break;
1337 case gfx_metafile:
1338 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1339 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1340 break;
1341 case gfx_dib:
1343 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1344 HDC hdc = GetDC(0);
1345 unsigned nc = bi->bmiHeader.biClrUsed;
1347 /* not quite right, especially for bitfields type of compression */
1348 if (!nc && bi->bmiHeader.biBitCount <= 8)
1349 nc = 1 << bi->bmiHeader.biBitCount;
1350 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1351 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1352 bi, DIB_RGB_COLORS)))
1353 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1354 ReleaseDC(0, hdc);
1356 break;
1357 default:
1358 break;
1360 HeapFree(GetProcessHeap(), 0, buffer);
1361 RTFRouteToken (info); /* feed "}" back to router */
1362 return;
1363 skip_group:
1364 HeapFree(GetProcessHeap(), 0, buffer);
1365 RTFSkipGroup(info);
1366 RTFRouteToken(info); /* feed "}" back to router */
1369 /* for now, lookup the \result part and use it, whatever the object */
1370 static void ME_RTFReadObjectGroup(RTF_Info *info)
1372 for (;;)
1374 RTFGetToken (info);
1375 if (info->rtfClass == rtfEOF)
1376 return;
1377 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1378 break;
1379 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1381 RTFGetToken (info);
1382 if (info->rtfClass == rtfEOF)
1383 return;
1384 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1386 int level = 1;
1388 while (RTFGetToken (info) != rtfEOF)
1390 if (info->rtfClass == rtfGroup)
1392 if (info->rtfMajor == rtfBeginGroup) level++;
1393 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1395 RTFRouteToken(info);
1398 else RTFSkipGroup(info);
1399 continue;
1401 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1403 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1404 return;
1407 RTFRouteToken(info); /* feed "}" back to router */
1410 static void ME_RTFReadHook(RTF_Info *info)
1412 switch(info->rtfClass)
1414 case rtfGroup:
1415 switch(info->rtfMajor)
1417 case rtfBeginGroup:
1418 if (info->stackTop < maxStack) {
1419 info->stack[info->stackTop].style = info->style;
1420 ME_AddRefStyle(info->style);
1421 info->stack[info->stackTop].codePage = info->codePage;
1422 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1424 info->stackTop++;
1425 info->styleChanged = FALSE;
1426 break;
1427 case rtfEndGroup:
1429 RTFFlushOutputBuffer(info);
1430 info->stackTop--;
1431 if (info->stackTop <= 0)
1432 info->rtfClass = rtfEOF;
1433 if (info->stackTop < 0)
1434 return;
1436 ME_ReleaseStyle(info->style);
1437 info->style = info->stack[info->stackTop].style;
1438 info->codePage = info->stack[info->stackTop].codePage;
1439 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1440 break;
1443 break;
1447 void
1448 ME_StreamInFill(ME_InStream *stream)
1450 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1451 (BYTE *)stream->buffer,
1452 sizeof(stream->buffer),
1453 (LONG *)&stream->dwSize);
1454 stream->dwUsed = 0;
1457 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1459 RTF_Info parser;
1460 ME_Style *style;
1461 int from, to, nUndoMode;
1462 int nEventMask = editor->nEventMask;
1463 ME_InStream inStream;
1464 BOOL invalidRTF = FALSE;
1465 ME_Cursor *selStart, *selEnd;
1466 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1468 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1469 editor->nEventMask = 0;
1471 ME_GetSelectionOfs(editor, &from, &to);
1472 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1474 ME_GetSelection(editor, &selStart, &selEnd);
1475 style = ME_GetSelectionInsertStyle(editor);
1477 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1479 /* Don't insert text at the end of the table row */
1480 if (!editor->bEmulateVersion10) { /* v4.1 */
1481 ME_DisplayItem *para = editor->pCursors->pPara;
1482 if (para->member.para.nFlags & MEPF_ROWEND)
1484 para = para->member.para.next_para;
1485 editor->pCursors[0].pPara = para;
1486 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1487 editor->pCursors[0].nOffset = 0;
1489 if (para->member.para.nFlags & MEPF_ROWSTART)
1491 para = para->member.para.next_para;
1492 editor->pCursors[0].pPara = para;
1493 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1494 editor->pCursors[0].nOffset = 0;
1496 editor->pCursors[1] = editor->pCursors[0];
1497 } else { /* v1.0 - 3.0 */
1498 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1499 ME_IsInTable(editor->pCursors[0].pRun))
1500 return 0;
1502 } else {
1503 style = editor->pBuffer->pDefaultStyle;
1504 ME_AddRefStyle(style);
1505 ME_SetSelection(editor, 0, 0);
1506 ME_InternalDeleteText(editor, &editor->pCursors[1],
1507 ME_GetTextLength(editor), FALSE);
1508 from = to = 0;
1509 ME_ClearTempStyle(editor);
1510 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1514 /* Back up undo mode to a local variable */
1515 nUndoMode = editor->nUndoMode;
1517 /* Only create an undo if SFF_SELECTION is set */
1518 if (!(format & SFF_SELECTION))
1519 editor->nUndoMode = umIgnore;
1521 inStream.editstream = stream;
1522 inStream.editstream->dwError = 0;
1523 inStream.dwSize = 0;
1524 inStream.dwUsed = 0;
1526 if (format & SF_RTF)
1528 /* Check if it's really RTF, and if it is not, use plain text */
1529 ME_StreamInFill(&inStream);
1530 if (!inStream.editstream->dwError)
1532 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1533 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1535 invalidRTF = TRUE;
1536 inStream.editstream->dwError = -16;
1541 if (!invalidRTF && !inStream.editstream->dwError)
1543 if (format & SF_RTF) {
1544 from = ME_GetCursorOfs(&editor->pCursors[0]);
1546 /* setup the RTF parser */
1547 memset(&parser, 0, sizeof parser);
1548 RTFSetEditStream(&parser, &inStream);
1549 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1550 parser.editor = editor;
1551 parser.style = style;
1552 WriterInit(&parser);
1553 RTFInit(&parser);
1554 RTFSetReadHook(&parser, ME_RTFReadHook);
1555 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1556 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1557 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1559 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1560 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1562 BeginFile(&parser);
1564 /* do the parsing */
1565 RTFRead(&parser);
1566 RTFFlushOutputBuffer(&parser);
1567 if (!editor->bEmulateVersion10) { /* v4.1 */
1568 if (parser.tableDef && parser.tableDef->tableRowStart &&
1569 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1571 /* Delete any incomplete table row at the end of the rich text. */
1572 int nOfs, nChars;
1573 ME_DisplayItem *para;
1575 parser.rtfMinor = rtfRow;
1576 /* Complete the table row before deleting it.
1577 * By doing it this way we will have the current paragraph format set
1578 * properly to reflect that is not in the complete table, and undo items
1579 * will be added for this change to the current paragraph format. */
1580 if (parser.nestingLevel > 0)
1582 while (parser.nestingLevel > 1)
1583 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1584 para = parser.tableDef->tableRowStart;
1585 ME_RTFSpecialCharHook(&parser);
1586 } else {
1587 para = parser.tableDef->tableRowStart;
1588 ME_RTFSpecialCharHook(&parser);
1589 assert(para->member.para.nFlags & MEPF_ROWEND);
1590 para = para->member.para.next_para;
1593 editor->pCursors[1].pPara = para;
1594 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1595 editor->pCursors[1].nOffset = 0;
1596 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1597 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1598 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1599 if (parser.tableDef)
1600 parser.tableDef->tableRowStart = NULL;
1603 ME_CheckTablesForCorruption(editor);
1604 RTFDestroy(&parser);
1605 if (parser.lpRichEditOle)
1606 IRichEditOle_Release(parser.lpRichEditOle);
1608 if (parser.stackTop > 0)
1610 while (--parser.stackTop >= 0)
1612 ME_ReleaseStyle(parser.style);
1613 parser.style = parser.stack[parser.stackTop].style;
1615 if (!inStream.editstream->dwError)
1616 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1619 /* Remove last line break, as mandated by tests. This is not affected by
1620 CR/LF counters, since RTF streaming presents only \para tokens, which
1621 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1623 if (stripLastCR && !(format & SFF_SELECTION)) {
1624 int newto;
1625 ME_GetSelection(editor, &selStart, &selEnd);
1626 newto = ME_GetCursorOfs(selEnd);
1627 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1628 WCHAR lastchar[3] = {'\0', '\0'};
1629 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1630 ME_Cursor linebreakCursor = *selEnd;
1632 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1633 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE, 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, FALSE);
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, FALSE);
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, 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, 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->reOle = NULL;
2748 ed->bEmulateVersion10 = bEmulateVersion10;
2749 ed->styleFlags = 0;
2750 ITextHost_TxGetPropertyBits(texthost,
2751 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2752 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2753 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2754 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2755 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2756 &props);
2757 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2758 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2759 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2760 ed->pBuffer = ME_MakeText();
2761 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2762 ed->nAvailWidth = 0; /* wrap to client area */
2763 ME_MakeFirstParagraph(ed);
2764 /* The four cursors are for:
2765 * 0 - The position where the caret is shown
2766 * 1 - The anchored end of the selection (for normal selection)
2767 * 2 & 3 - The anchored start and end respectively for word, line,
2768 * or paragraph selection.
2770 ed->nCursors = 4;
2771 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2772 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2773 ed->pCursors[1] = ed->pCursors[0];
2774 ed->pCursors[2] = ed->pCursors[0];
2775 ed->pCursors[3] = ed->pCursors[1];
2776 ed->nLastTotalLength = ed->nTotalLength = 0;
2777 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2778 ed->nUDArrowX = -1;
2779 ed->rgbBackColor = -1;
2780 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2781 ed->bCaretAtEnd = FALSE;
2782 ed->nEventMask = 0;
2783 ed->nModifyStep = 0;
2784 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2785 list_init( &ed->undo_stack );
2786 list_init( &ed->redo_stack );
2787 ed->nUndoStackSize = 0;
2788 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2789 ed->nUndoMode = umAddToUndo;
2790 ed->nParagraphs = 1;
2791 ed->nLastSelStart = ed->nLastSelEnd = 0;
2792 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2793 ed->bHideSelection = FALSE;
2794 ed->pfnWordBreak = NULL;
2795 ed->lpOleCallback = NULL;
2796 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2797 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2798 ed->AutoURLDetect_bEnable = FALSE;
2799 ed->bHaveFocus = FALSE;
2800 ed->bDialogMode = FALSE;
2801 ed->bMouseCaptured = FALSE;
2802 for (i=0; i<HFONT_CACHE_SIZE; i++)
2804 ed->pFontCache[i].nRefs = 0;
2805 ed->pFontCache[i].nAge = 0;
2806 ed->pFontCache[i].hFont = NULL;
2809 ME_CheckCharOffsets(ed);
2810 ed->bDefaultFormatRect = TRUE;
2811 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2812 if (selbarwidth) {
2813 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2814 ed->selofs = SELECTIONBAR_WIDTH;
2815 ed->styleFlags |= ES_SELECTIONBAR;
2816 } else {
2817 ed->selofs = 0;
2819 ed->nSelectionType = stPosition;
2821 ed->cPasswordMask = 0;
2822 if (props & TXTBIT_USEPASSWORD)
2823 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2825 if (props & TXTBIT_AUTOWORDSEL)
2826 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2827 if (props & TXTBIT_MULTILINE) {
2828 ed->styleFlags |= ES_MULTILINE;
2829 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2830 } else {
2831 ed->bWordWrap = FALSE;
2833 if (props & TXTBIT_READONLY)
2834 ed->styleFlags |= ES_READONLY;
2835 if (!(props & TXTBIT_HIDESELECTION))
2836 ed->styleFlags |= ES_NOHIDESEL;
2837 if (props & TXTBIT_SAVESELECTION)
2838 ed->styleFlags |= ES_SAVESEL;
2839 if (props & TXTBIT_VERTICAL)
2840 ed->styleFlags |= ES_VERTICAL;
2841 if (props & TXTBIT_DISABLEDRAG)
2842 ed->styleFlags |= ES_NOOLEDRAGDROP;
2844 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2846 /* Default scrollbar information */
2847 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2848 ed->vert_si.nMin = 0;
2849 ed->vert_si.nMax = 0;
2850 ed->vert_si.nPage = 0;
2851 ed->vert_si.nPos = 0;
2853 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2854 ed->horz_si.nMin = 0;
2855 ed->horz_si.nMax = 0;
2856 ed->horz_si.nPage = 0;
2857 ed->horz_si.nPos = 0;
2859 ed->wheel_remain = 0;
2861 OleInitialize(NULL);
2863 return ed;
2866 static void ME_DestroyEditor(ME_TextEditor *editor)
2868 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2869 ME_DisplayItem *p = pFirst, *pNext = NULL;
2870 int i;
2872 ME_ClearTempStyle(editor);
2873 ME_EmptyUndoStack(editor);
2874 while(p) {
2875 pNext = p->next;
2876 ME_DestroyDisplayItem(p);
2877 p = pNext;
2879 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2880 for (i=0; i<HFONT_CACHE_SIZE; i++)
2882 if (editor->pFontCache[i].hFont)
2883 DeleteObject(editor->pFontCache[i].hFont);
2885 if (editor->rgbBackColor != -1)
2886 DeleteObject(editor->hbrBackground);
2887 if(editor->lpOleCallback)
2888 IRichEditOleCallback_Release(editor->lpOleCallback);
2889 ITextHost_Release(editor->texthost);
2890 if (editor->reOle)
2892 IRichEditOle_Release(editor->reOle);
2893 editor->reOle = NULL;
2895 OleUninitialize();
2897 FREE_OBJ(editor->pBuffer);
2898 FREE_OBJ(editor->pCursors);
2900 FREE_OBJ(editor);
2903 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2905 TRACE("\n");
2906 switch (fdwReason)
2908 case DLL_PROCESS_ATTACH:
2909 DisableThreadLibraryCalls(hinstDLL);
2910 me_heap = HeapCreate (0, 0x10000, 0);
2911 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2912 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2913 LookupInit();
2914 break;
2916 case DLL_PROCESS_DETACH:
2917 if (lpvReserved) break;
2918 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2919 UnregisterClassW(MSFTEDIT_CLASS, 0);
2920 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2921 UnregisterClassA("RichEdit50A", 0);
2922 if (ME_ListBoxRegistered)
2923 UnregisterClassW(REListBox20W, 0);
2924 if (ME_ComboBoxRegistered)
2925 UnregisterClassW(REComboBox20W, 0);
2926 LookupCleanup();
2927 HeapDestroy (me_heap);
2928 break;
2930 return TRUE;
2933 static inline int get_default_line_height( ME_TextEditor *editor )
2935 int height = 0;
2937 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2938 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2939 if (height <= 0) height = 24;
2941 return height;
2944 static inline int calc_wheel_change( int *remain, int amount_per_click )
2946 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2947 *remain -= WHEEL_DELTA * change / amount_per_click;
2948 return change;
2951 static const char * const edit_messages[] = {
2952 "EM_GETSEL",
2953 "EM_SETSEL",
2954 "EM_GETRECT",
2955 "EM_SETRECT",
2956 "EM_SETRECTNP",
2957 "EM_SCROLL",
2958 "EM_LINESCROLL",
2959 "EM_SCROLLCARET",
2960 "EM_GETMODIFY",
2961 "EM_SETMODIFY",
2962 "EM_GETLINECOUNT",
2963 "EM_LINEINDEX",
2964 "EM_SETHANDLE",
2965 "EM_GETHANDLE",
2966 "EM_GETTHUMB",
2967 "EM_UNKNOWN_BF",
2968 "EM_UNKNOWN_C0",
2969 "EM_LINELENGTH",
2970 "EM_REPLACESEL",
2971 "EM_UNKNOWN_C3",
2972 "EM_GETLINE",
2973 "EM_LIMITTEXT",
2974 "EM_CANUNDO",
2975 "EM_UNDO",
2976 "EM_FMTLINES",
2977 "EM_LINEFROMCHAR",
2978 "EM_UNKNOWN_CA",
2979 "EM_SETTABSTOPS",
2980 "EM_SETPASSWORDCHAR",
2981 "EM_EMPTYUNDOBUFFER",
2982 "EM_GETFIRSTVISIBLELINE",
2983 "EM_SETREADONLY",
2984 "EM_SETWORDBREAKPROC",
2985 "EM_GETWORDBREAKPROC",
2986 "EM_GETPASSWORDCHAR",
2987 "EM_SETMARGINS",
2988 "EM_GETMARGINS",
2989 "EM_GETLIMITTEXT",
2990 "EM_POSFROMCHAR",
2991 "EM_CHARFROMPOS",
2992 "EM_SETIMESTATUS",
2993 "EM_GETIMESTATUS"
2996 static const char * const richedit_messages[] = {
2997 "EM_CANPASTE",
2998 "EM_DISPLAYBAND",
2999 "EM_EXGETSEL",
3000 "EM_EXLIMITTEXT",
3001 "EM_EXLINEFROMCHAR",
3002 "EM_EXSETSEL",
3003 "EM_FINDTEXT",
3004 "EM_FORMATRANGE",
3005 "EM_GETCHARFORMAT",
3006 "EM_GETEVENTMASK",
3007 "EM_GETOLEINTERFACE",
3008 "EM_GETPARAFORMAT",
3009 "EM_GETSELTEXT",
3010 "EM_HIDESELECTION",
3011 "EM_PASTESPECIAL",
3012 "EM_REQUESTRESIZE",
3013 "EM_SELECTIONTYPE",
3014 "EM_SETBKGNDCOLOR",
3015 "EM_SETCHARFORMAT",
3016 "EM_SETEVENTMASK",
3017 "EM_SETOLECALLBACK",
3018 "EM_SETPARAFORMAT",
3019 "EM_SETTARGETDEVICE",
3020 "EM_STREAMIN",
3021 "EM_STREAMOUT",
3022 "EM_GETTEXTRANGE",
3023 "EM_FINDWORDBREAK",
3024 "EM_SETOPTIONS",
3025 "EM_GETOPTIONS",
3026 "EM_FINDTEXTEX",
3027 "EM_GETWORDBREAKPROCEX",
3028 "EM_SETWORDBREAKPROCEX",
3029 "EM_SETUNDOLIMIT",
3030 "EM_UNKNOWN_USER_83",
3031 "EM_REDO",
3032 "EM_CANREDO",
3033 "EM_GETUNDONAME",
3034 "EM_GETREDONAME",
3035 "EM_STOPGROUPTYPING",
3036 "EM_SETTEXTMODE",
3037 "EM_GETTEXTMODE",
3038 "EM_AUTOURLDETECT",
3039 "EM_GETAUTOURLDETECT",
3040 "EM_SETPALETTE",
3041 "EM_GETTEXTEX",
3042 "EM_GETTEXTLENGTHEX",
3043 "EM_SHOWSCROLLBAR",
3044 "EM_SETTEXTEX",
3045 "EM_UNKNOWN_USER_98",
3046 "EM_UNKNOWN_USER_99",
3047 "EM_SETPUNCTUATION",
3048 "EM_GETPUNCTUATION",
3049 "EM_SETWORDWRAPMODE",
3050 "EM_GETWORDWRAPMODE",
3051 "EM_SETIMECOLOR",
3052 "EM_GETIMECOLOR",
3053 "EM_SETIMEOPTIONS",
3054 "EM_GETIMEOPTIONS",
3055 "EM_CONVPOSITION",
3056 "EM_UNKNOWN_USER_109",
3057 "EM_UNKNOWN_USER_110",
3058 "EM_UNKNOWN_USER_111",
3059 "EM_UNKNOWN_USER_112",
3060 "EM_UNKNOWN_USER_113",
3061 "EM_UNKNOWN_USER_114",
3062 "EM_UNKNOWN_USER_115",
3063 "EM_UNKNOWN_USER_116",
3064 "EM_UNKNOWN_USER_117",
3065 "EM_UNKNOWN_USER_118",
3066 "EM_UNKNOWN_USER_119",
3067 "EM_SETLANGOPTIONS",
3068 "EM_GETLANGOPTIONS",
3069 "EM_GETIMECOMPMODE",
3070 "EM_FINDTEXTW",
3071 "EM_FINDTEXTEXW",
3072 "EM_RECONVERSION",
3073 "EM_SETIMEMODEBIAS",
3074 "EM_GETIMEMODEBIAS"
3077 static const char *
3078 get_msg_name(UINT msg)
3080 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3081 return edit_messages[msg - EM_GETSEL];
3082 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3083 return richedit_messages[msg - EM_CANPASTE];
3084 return "";
3087 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3089 int x,y;
3090 BOOL isExact;
3091 ME_Cursor cursor; /* The start of the clicked text. */
3093 ENLINK info;
3094 x = (short)LOWORD(lParam);
3095 y = (short)HIWORD(lParam);
3096 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3097 if (!isExact) return;
3099 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3100 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3101 { /* The clicked run has CFE_LINK set */
3102 ME_DisplayItem *di;
3104 info.nmhdr.hwndFrom = NULL;
3105 info.nmhdr.idFrom = 0;
3106 info.nmhdr.code = EN_LINK;
3107 info.msg = msg;
3108 info.wParam = wParam;
3109 info.lParam = lParam;
3110 cursor.nOffset = 0;
3112 /* find the first contiguous run with CFE_LINK set */
3113 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3114 for (di = cursor.pRun->prev;
3115 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3116 di = di->prev)
3118 info.chrg.cpMin -= di->member.run.len;
3121 /* find the last contiguous run with CFE_LINK set */
3122 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3123 for (di = cursor.pRun->next;
3124 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3125 di = di->next)
3127 info.chrg.cpMax += di->member.run.len;
3130 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3134 #define UNSUPPORTED_MSG(e) \
3135 case e: \
3136 FIXME(#e ": stub\n"); \
3137 *phresult = S_FALSE; \
3138 return 0;
3140 /* Handle messages for windowless and windoweded richedit controls.
3142 * The LRESULT that is returned is a return value for window procs,
3143 * and the phresult parameter is the COM return code needed by the
3144 * text services interface. */
3145 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3146 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3148 *phresult = S_OK;
3150 switch(msg) {
3152 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3153 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3154 UNSUPPORTED_MSG(EM_FMTLINES)
3155 UNSUPPORTED_MSG(EM_FORMATRANGE)
3156 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3157 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3158 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3159 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3160 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3161 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3162 UNSUPPORTED_MSG(EM_GETREDONAME)
3163 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3164 UNSUPPORTED_MSG(EM_GETUNDONAME)
3165 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3166 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3167 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3168 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3169 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3170 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3171 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3172 UNSUPPORTED_MSG(EM_SETMARGINS)
3173 UNSUPPORTED_MSG(EM_SETPALETTE)
3174 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3175 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3176 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3178 /* Messages specific to Richedit controls */
3180 case EM_STREAMIN:
3181 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3182 case EM_STREAMOUT:
3183 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3184 case WM_GETDLGCODE:
3186 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3188 if (lParam)
3189 editor->bDialogMode = TRUE;
3190 if (editor->styleFlags & ES_MULTILINE)
3191 code |= DLGC_WANTMESSAGE;
3192 if (!(editor->styleFlags & ES_SAVESEL))
3193 code |= DLGC_HASSETSEL;
3194 return code;
3196 case EM_EMPTYUNDOBUFFER:
3197 ME_EmptyUndoStack(editor);
3198 return 0;
3199 case EM_GETSEL:
3201 /* Note: wParam/lParam can be NULL */
3202 UINT from, to;
3203 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3204 PUINT pto = lParam ? (PUINT)lParam : &to;
3205 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3206 if ((*pfrom|*pto) & 0xFFFF0000)
3207 return -1;
3208 return MAKELONG(*pfrom,*pto);
3210 case EM_EXGETSEL:
3212 CHARRANGE *pRange = (CHARRANGE *)lParam;
3213 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3214 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3215 return 0;
3217 case EM_SETUNDOLIMIT:
3219 if ((int)wParam < 0)
3220 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3221 else
3222 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3223 /* Setting a max stack size keeps wine from getting killed
3224 for hogging memory. Windows allocates all this memory at once, so
3225 no program would realistically set a value above our maximum. */
3226 return editor->nUndoLimit;
3228 case EM_CANUNDO:
3229 return !list_empty( &editor->undo_stack );
3230 case EM_CANREDO:
3231 return !list_empty( &editor->redo_stack );
3232 case WM_UNDO: /* FIXME: actually not the same */
3233 case EM_UNDO:
3234 return ME_Undo(editor);
3235 case EM_REDO:
3236 return ME_Redo(editor);
3237 case EM_GETOPTIONS:
3239 /* these flags are equivalent to the ES_* counterparts */
3240 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3241 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3242 DWORD settings = editor->styleFlags & mask;
3244 return settings;
3246 case EM_SETOPTIONS:
3248 /* these flags are equivalent to ES_* counterparts, except for
3249 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3250 * but is still stored in editor->styleFlags. */
3251 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3252 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3253 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3254 DWORD settings = mask & editor->styleFlags;
3255 DWORD oldSettings = settings;
3256 DWORD changedSettings;
3258 switch(wParam)
3260 case ECOOP_SET:
3261 settings = lParam;
3262 break;
3263 case ECOOP_OR:
3264 settings |= lParam;
3265 break;
3266 case ECOOP_AND:
3267 settings &= lParam;
3268 break;
3269 case ECOOP_XOR:
3270 settings ^= lParam;
3272 changedSettings = oldSettings ^ settings;
3274 if (changedSettings) {
3275 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3277 if (changedSettings & ECO_SELECTIONBAR)
3279 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3280 if (settings & ECO_SELECTIONBAR) {
3281 assert(!editor->selofs);
3282 editor->selofs = SELECTIONBAR_WIDTH;
3283 editor->rcFormat.left += editor->selofs;
3284 } else {
3285 editor->rcFormat.left -= editor->selofs;
3286 editor->selofs = 0;
3288 ME_RewrapRepaint(editor);
3291 if (changedSettings & settings & ECO_VERTICAL)
3292 FIXME("ECO_VERTICAL not implemented yet!\n");
3293 if (changedSettings & settings & ECO_AUTOHSCROLL)
3294 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3295 if (changedSettings & settings & ECO_AUTOVSCROLL)
3296 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3297 if (changedSettings & settings & ECO_NOHIDESEL)
3298 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3299 if (changedSettings & settings & ECO_WANTRETURN)
3300 FIXME("ECO_WANTRETURN not implemented yet!\n");
3301 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3302 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3305 return settings;
3307 case EM_SETSEL:
3309 handle_EM_EXSETSEL( editor, wParam, lParam );
3310 return 0;
3312 case EM_SETSCROLLPOS:
3314 POINT *point = (POINT *)lParam;
3315 ME_ScrollAbs(editor, point->x, point->y);
3316 return 0;
3318 case EM_AUTOURLDETECT:
3320 if (wParam==1 || wParam ==0)
3322 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3323 return 0;
3325 return E_INVALIDARG;
3327 case EM_GETAUTOURLDETECT:
3329 return editor->AutoURLDetect_bEnable;
3331 case EM_EXSETSEL:
3333 CHARRANGE range = *(CHARRANGE *)lParam;
3335 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3337 case EM_SHOWSCROLLBAR:
3339 DWORD flags;
3341 switch (wParam)
3343 case SB_HORZ:
3344 flags = WS_HSCROLL;
3345 break;
3346 case SB_VERT:
3347 flags = WS_VSCROLL;
3348 break;
3349 case SB_BOTH:
3350 flags = WS_HSCROLL|WS_VSCROLL;
3351 break;
3352 default:
3353 return 0;
3356 if (lParam) {
3357 editor->styleFlags |= flags;
3358 if (flags & WS_HSCROLL)
3359 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3360 editor->nTotalWidth > editor->sizeWindow.cx);
3361 if (flags & WS_VSCROLL)
3362 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3363 editor->nTotalLength > editor->sizeWindow.cy);
3364 } else {
3365 editor->styleFlags &= ~flags;
3366 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3368 return 0;
3370 case EM_SETTEXTEX:
3372 LPWSTR wszText;
3373 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3374 int from, to, len;
3375 ME_Style *style;
3376 BOOL bRtf, bUnicode, bSelection, bUTF8;
3377 int oldModify = editor->nModifyStep;
3378 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3380 if (!pStruct) return 0;
3382 /* If we detect ascii rtf at the start of the string,
3383 * we know it isn't unicode. */
3384 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3385 !strncmp((char *)lParam, "{\\urtf", 6)));
3386 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3387 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3389 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3390 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3391 pStruct->flags, pStruct->codepage);
3393 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3394 if (bSelection) {
3395 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3396 style = ME_GetSelectionInsertStyle(editor);
3397 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3398 } else {
3399 ME_Cursor start;
3400 ME_SetCursorToStart(editor, &start);
3401 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3402 style = editor->pBuffer->pDefaultStyle;
3405 if (bRtf) {
3406 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3407 if (bSelection) {
3408 /* FIXME: The length returned doesn't include the rtf control
3409 * characters, only the actual text. */
3410 len = lParam ? strlen((char *)lParam) : 0;
3412 } else {
3413 if (bUTF8 && !bUnicode) {
3414 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3415 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3416 ME_EndToUnicode(CP_UTF8, wszText);
3417 } else {
3418 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3419 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3420 ME_EndToUnicode(pStruct->codepage, wszText);
3424 if (bSelection) {
3425 ME_ReleaseStyle(style);
3426 ME_UpdateSelectionLinkAttribute(editor);
3427 } else {
3428 ME_Cursor cursor;
3429 len = 1;
3430 ME_SetCursorToStart(editor, &cursor);
3431 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3433 ME_CommitUndo(editor);
3434 if (!(pStruct->flags & ST_KEEPUNDO))
3436 editor->nModifyStep = oldModify;
3437 ME_EmptyUndoStack(editor);
3439 ME_UpdateRepaint(editor, FALSE);
3440 return len;
3442 case EM_SETBKGNDCOLOR:
3444 LRESULT lColor;
3445 if (editor->rgbBackColor != -1) {
3446 DeleteObject(editor->hbrBackground);
3447 lColor = editor->rgbBackColor;
3449 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3451 if (wParam)
3453 editor->rgbBackColor = -1;
3454 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3456 else
3458 editor->rgbBackColor = lParam;
3459 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3461 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3462 ITextHost_TxViewChange(editor->texthost, TRUE);
3463 return lColor;
3465 case EM_GETMODIFY:
3466 return editor->nModifyStep == 0 ? 0 : -1;
3467 case EM_SETMODIFY:
3469 if (wParam)
3470 editor->nModifyStep = 1;
3471 else
3472 editor->nModifyStep = 0;
3474 return 0;
3476 case EM_SETREADONLY:
3478 if (wParam)
3479 editor->styleFlags |= ES_READONLY;
3480 else
3481 editor->styleFlags &= ~ES_READONLY;
3482 return 1;
3484 case EM_SETEVENTMASK:
3486 DWORD nOldMask = editor->nEventMask;
3488 editor->nEventMask = lParam;
3489 return nOldMask;
3491 case EM_GETEVENTMASK:
3492 return editor->nEventMask;
3493 case EM_SETCHARFORMAT:
3495 CHARFORMAT2W buf, *p;
3496 BOOL bRepaint = TRUE;
3497 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3498 if (p == NULL) return 0;
3499 if (wParam & SCF_ALL) {
3500 if (editor->mode & TM_PLAINTEXT) {
3501 ME_SetDefaultCharFormat(editor, p);
3502 } else {
3503 ME_Cursor start;
3504 ME_SetCursorToStart(editor, &start);
3505 ME_SetCharFormat(editor, &start, NULL, p);
3506 editor->nModifyStep = 1;
3508 } else if (wParam & SCF_SELECTION) {
3509 if (editor->mode & TM_PLAINTEXT)
3510 return 0;
3511 if (wParam & SCF_WORD) {
3512 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3513 return 0;
3515 bRepaint = ME_IsSelection(editor);
3516 ME_SetSelectionCharFormat(editor, p);
3517 if (bRepaint) editor->nModifyStep = 1;
3518 } else { /* SCF_DEFAULT */
3519 ME_SetDefaultCharFormat(editor, p);
3521 ME_CommitUndo(editor);
3522 if (bRepaint)
3524 ME_WrapMarkedParagraphs(editor);
3525 ME_UpdateScrollBar(editor);
3526 ME_Repaint(editor);
3528 return 1;
3530 case EM_GETCHARFORMAT:
3532 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3533 if (dst->cbSize != sizeof(CHARFORMATA) &&
3534 dst->cbSize != sizeof(CHARFORMATW) &&
3535 dst->cbSize != sizeof(CHARFORMAT2A) &&
3536 dst->cbSize != sizeof(CHARFORMAT2W))
3537 return 0;
3538 tmp.cbSize = sizeof(tmp);
3539 if (!wParam)
3540 ME_GetDefaultCharFormat(editor, &tmp);
3541 else
3542 ME_GetSelectionCharFormat(editor, &tmp);
3543 ME_CopyToCFAny(dst, &tmp);
3544 return tmp.dwMask;
3546 case EM_SETPARAFORMAT:
3548 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3549 ME_WrapMarkedParagraphs(editor);
3550 ME_UpdateScrollBar(editor);
3551 ME_Repaint(editor);
3552 ME_CommitUndo(editor);
3553 return result;
3555 case EM_GETPARAFORMAT:
3556 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3557 return ((PARAFORMAT2 *)lParam)->dwMask;
3558 case EM_GETFIRSTVISIBLELINE:
3560 ME_DisplayItem *p = editor->pBuffer->pFirst;
3561 int y = editor->vert_si.nPos;
3562 int ypara = 0;
3563 int count = 0;
3564 int ystart, yend;
3565 while(p) {
3566 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3567 if (p->type == diTextEnd)
3568 break;
3569 if (p->type == diParagraph) {
3570 ypara = p->member.para.pt.y;
3571 continue;
3573 ystart = ypara + p->member.row.pt.y;
3574 yend = ystart + p->member.row.nHeight;
3575 if (y < yend) {
3576 break;
3578 count++;
3580 return count;
3582 case EM_HIDESELECTION:
3584 editor->bHideSelection = (wParam != 0);
3585 ME_InvalidateSelection(editor);
3586 return 0;
3588 case EM_LINESCROLL:
3590 if (!(editor->styleFlags & ES_MULTILINE))
3591 return FALSE;
3592 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3593 return TRUE;
3595 case WM_CLEAR:
3597 int from, to;
3598 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3599 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3600 ME_CommitUndo(editor);
3601 ME_UpdateRepaint(editor, TRUE);
3602 return 0;
3604 case EM_REPLACESEL:
3606 int from, to, nStartCursor;
3607 ME_Style *style;
3608 int len = 0;
3609 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3610 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3611 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3613 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3614 style = ME_GetSelectionInsertStyle(editor);
3615 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3616 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3617 ME_ReleaseStyle(style);
3618 /* drop temporary style if line end */
3620 * FIXME question: does abc\n mean: put abc,
3621 * clear temp style, put \n? (would require a change)
3623 if (len>0 && wszText[len-1] == '\n')
3624 ME_ClearTempStyle(editor);
3625 ME_EndToUnicode(codepage, wszText);
3626 ME_CommitUndo(editor);
3627 ME_UpdateSelectionLinkAttribute(editor);
3628 if (!wParam)
3629 ME_EmptyUndoStack(editor);
3630 ME_UpdateRepaint(editor, FALSE);
3631 return len;
3633 case EM_SCROLLCARET:
3634 ME_EnsureVisible(editor, &editor->pCursors[0]);
3635 return 0;
3636 case WM_SETFONT:
3638 LOGFONTW lf;
3639 CHARFORMAT2W fmt;
3640 HDC hDC;
3641 BOOL bRepaint = LOWORD(lParam);
3643 if (!wParam)
3644 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3645 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3646 hDC = ITextHost_TxGetDC(editor->texthost);
3647 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3648 ITextHost_TxReleaseDC(editor->texthost, hDC);
3649 if (editor->mode & TM_RICHTEXT) {
3650 ME_Cursor start;
3651 ME_SetCursorToStart(editor, &start);
3652 ME_SetCharFormat(editor, &start, NULL, &fmt);
3654 ME_SetDefaultCharFormat(editor, &fmt);
3656 ME_CommitUndo(editor);
3657 ME_MarkAllForWrapping(editor);
3658 ME_WrapMarkedParagraphs(editor);
3659 ME_UpdateScrollBar(editor);
3660 if (bRepaint)
3661 ME_Repaint(editor);
3662 return 0;
3664 case WM_SETTEXT:
3666 ME_Cursor cursor;
3667 ME_SetCursorToStart(editor, &cursor);
3668 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3669 if (lParam)
3671 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3672 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3673 !strncmp((char *)lParam, "{\\urtf", 6))
3675 /* Undocumented: WM_SETTEXT supports RTF text */
3676 ME_StreamInRTFString(editor, 0, (char *)lParam);
3678 else
3680 int textLen;
3681 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3682 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3683 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3684 if (textLen > 0)
3686 int len = -1;
3688 /* uses default style! */
3689 if (!(editor->styleFlags & ES_MULTILINE))
3691 WCHAR * p;
3693 p = wszText;
3694 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3695 len = p - wszText;
3697 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3699 ME_EndToUnicode(codepage, wszText);
3702 else
3703 TRACE("WM_SETTEXT - NULL\n");
3704 ME_SetCursorToStart(editor, &cursor);
3705 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3706 ME_SetSelection(editor, 0, 0);
3707 editor->nModifyStep = 0;
3708 ME_CommitUndo(editor);
3709 ME_EmptyUndoStack(editor);
3710 ME_UpdateRepaint(editor, FALSE);
3711 return 1;
3713 case EM_CANPASTE:
3715 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3716 if (IsClipboardFormatAvailable(nRTFFormat))
3717 return TRUE;
3718 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3719 return TRUE;
3720 return FALSE;
3722 case WM_PASTE:
3723 case WM_MBUTTONDOWN:
3724 ME_Paste(editor);
3725 return 0;
3726 case WM_CUT:
3727 case WM_COPY:
3729 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3730 int nChars = nTo - nFrom;
3731 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3733 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3735 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3736 ME_CommitUndo(editor);
3737 ME_UpdateRepaint(editor, TRUE);
3739 return 0;
3741 case WM_GETTEXTLENGTH:
3743 GETTEXTLENGTHEX how;
3745 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3746 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3747 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3748 return ME_GetTextLengthEx(editor, &how);
3750 case EM_GETTEXTLENGTHEX:
3751 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3752 case WM_GETTEXT:
3754 GETTEXTEX ex;
3755 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3756 ex.flags = GT_USECRLF;
3757 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3758 ex.lpDefaultChar = NULL;
3759 ex.lpUsedDefChar = NULL;
3760 return ME_GetTextEx(editor, &ex, lParam);
3762 case EM_GETTEXTEX:
3763 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3764 case EM_GETSELTEXT:
3766 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3767 ME_Cursor *from = &editor->pCursors[nStartCur];
3768 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3769 nTo - nFrom, unicode);
3771 case EM_GETSCROLLPOS:
3773 POINT *point = (POINT *)lParam;
3774 point->x = editor->horz_si.nPos;
3775 point->y = editor->vert_si.nPos;
3776 /* 16-bit scaled value is returned as stored in scrollinfo */
3777 if (editor->horz_si.nMax > 0xffff)
3778 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3779 if (editor->vert_si.nMax > 0xffff)
3780 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3781 return 1;
3783 case EM_GETTEXTRANGE:
3785 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3786 ME_Cursor start;
3787 int nStart = rng->chrg.cpMin;
3788 int nEnd = rng->chrg.cpMax;
3789 int textlength = ME_GetTextLength(editor);
3791 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3792 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3793 if (nStart < 0) return 0;
3794 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3795 nEnd = textlength;
3796 if (nStart >= nEnd) return 0;
3798 ME_CursorFromCharOfs(editor, nStart, &start);
3799 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3801 case EM_GETLINE:
3803 ME_DisplayItem *run;
3804 const unsigned int nMaxChars = *(WORD *) lParam;
3805 unsigned int nCharsLeft = nMaxChars;
3806 char *dest = (char *) lParam;
3807 BOOL wroteNull = FALSE;
3809 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3810 unicode ? "Unicode" : "Ansi");
3812 run = ME_FindRowWithNumber(editor, wParam);
3813 if (run == NULL)
3814 return 0;
3816 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3817 && run->type == diRun)
3819 WCHAR *str = get_text( &run->member.run, 0 );
3820 unsigned int nCopy;
3822 nCopy = min(nCharsLeft, run->member.run.len);
3824 if (unicode)
3825 memcpy(dest, str, nCopy * sizeof(WCHAR));
3826 else
3827 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3828 nCharsLeft, NULL, NULL);
3829 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3830 nCharsLeft -= nCopy;
3833 /* append line termination, space allowing */
3834 if (nCharsLeft > 0)
3836 if (unicode)
3837 *((WCHAR *)dest) = '\0';
3838 else
3839 *dest = '\0';
3840 nCharsLeft--;
3841 wroteNull = TRUE;
3844 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3845 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3847 case EM_GETLINECOUNT:
3849 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3850 int nRows = 0;
3852 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3854 while (item != editor->pBuffer->pLast)
3856 assert(item->type == diParagraph);
3857 prev_para = ME_FindItemBack(item, diRun);
3858 if (prev_para) {
3859 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3861 nRows += item->member.para.nRows;
3862 item = item->member.para.next_para;
3864 last_para = ME_FindItemBack(item, diRun);
3865 assert(last_para);
3866 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3867 if (editor->bEmulateVersion10 && prev_para &&
3868 last_para->member.run.nCharOfs == 0 &&
3869 prev_para->member.run.len == 1 &&
3870 *get_text( &prev_para->member.run, 0 ) == '\r')
3872 /* In 1.0 emulation, the last solitary \r at the very end of the text
3873 (if one exists) is NOT a line break.
3874 FIXME: this is an ugly hack. This should have a more regular model. */
3875 nRows--;
3878 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3879 return max(1, nRows);
3881 case EM_LINEFROMCHAR:
3883 if (wParam == -1)
3884 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3885 else
3886 return ME_RowNumberFromCharOfs(editor, wParam);
3888 case EM_EXLINEFROMCHAR:
3890 if (lParam == -1)
3891 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3892 else
3893 return ME_RowNumberFromCharOfs(editor, lParam);
3895 case EM_LINEINDEX:
3897 ME_DisplayItem *item, *para;
3898 int nCharOfs;
3900 if (wParam == -1)
3901 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3902 else
3903 item = ME_FindRowWithNumber(editor, wParam);
3904 if (!item)
3905 return -1;
3906 para = ME_GetParagraph(item);
3907 item = ME_FindItemFwd(item, diRun);
3908 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3909 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3910 return nCharOfs;
3912 case EM_LINELENGTH:
3914 ME_DisplayItem *item, *item_end;
3915 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3916 ME_DisplayItem *para, *run;
3918 if (wParam > ME_GetTextLength(editor))
3919 return 0;
3920 if (wParam == -1)
3922 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3923 return 0;
3925 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3926 item = ME_RowStart(run);
3927 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3928 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3929 if (item_end->type == diStartRow) {
3930 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3931 } else {
3932 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3933 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3934 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3936 nChars = nNextLineOfs - nThisLineOfs;
3937 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3938 return nChars;
3940 case EM_EXLIMITTEXT:
3942 if ((int)lParam < 0)
3943 return 0;
3944 if (lParam == 0)
3945 editor->nTextLimit = 65536;
3946 else
3947 editor->nTextLimit = (int) lParam;
3948 return 0;
3950 case EM_LIMITTEXT:
3952 if (wParam == 0)
3953 editor->nTextLimit = 65536;
3954 else
3955 editor->nTextLimit = (int) wParam;
3956 return 0;
3958 case EM_GETLIMITTEXT:
3960 return editor->nTextLimit;
3962 case EM_FINDTEXT:
3964 LRESULT r;
3965 if(!unicode){
3966 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3967 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3968 WCHAR *tmp;
3970 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3971 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3972 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3973 FREE_OBJ( tmp );
3974 }else{
3975 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3976 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3978 return r;
3980 case EM_FINDTEXTEX:
3982 LRESULT r;
3983 if(!unicode){
3984 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3985 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3986 WCHAR *tmp;
3988 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3989 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3990 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3991 FREE_OBJ( tmp );
3992 }else{
3993 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3994 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3996 return r;
3998 case EM_FINDTEXTW:
4000 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4001 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4003 case EM_FINDTEXTEXW:
4005 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4006 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4008 case EM_GETZOOM:
4009 if (!wParam || !lParam)
4010 return FALSE;
4011 *(int *)wParam = editor->nZoomNumerator;
4012 *(int *)lParam = editor->nZoomDenominator;
4013 return TRUE;
4014 case EM_SETZOOM:
4015 return ME_SetZoom(editor, wParam, lParam);
4016 case EM_CHARFROMPOS:
4018 ME_Cursor cursor;
4019 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4020 &cursor, NULL))
4021 return ME_GetCursorOfs(&cursor);
4022 else
4023 return -1;
4025 case EM_POSFROMCHAR:
4027 ME_DisplayItem *pPara, *pRun;
4028 int nCharOfs, nOffset, nLength;
4029 POINTL pt = {0,0};
4031 nCharOfs = wParam;
4032 /* detect which API version we're dealing with */
4033 if (wParam >= 0x40000)
4034 nCharOfs = lParam;
4035 nLength = ME_GetTextLength(editor);
4036 nCharOfs = min(nCharOfs, nLength);
4037 nCharOfs = max(nCharOfs, 0);
4039 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4040 assert(pRun->type == diRun);
4041 pt.y = pRun->member.run.pt.y;
4042 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4043 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4044 pt.x += editor->rcFormat.left;
4046 pt.x -= editor->horz_si.nPos;
4047 pt.y -= editor->vert_si.nPos;
4049 if (wParam >= 0x40000) {
4050 *(POINTL *)wParam = pt;
4052 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4054 case WM_CREATE:
4056 void *text = NULL;
4057 INT max;
4059 ME_SetDefaultFormatRect(editor);
4061 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4062 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4063 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4065 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4066 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4068 if (editor->styleFlags & ES_DISABLENOSCROLL)
4070 if (editor->styleFlags & WS_VSCROLL)
4072 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4073 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4075 if (editor->styleFlags & WS_HSCROLL)
4077 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4078 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4082 if (lParam)
4084 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4085 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4087 if (text)
4089 WCHAR *textW;
4090 int len;
4091 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4092 textW = ME_ToUnicode(codepage, text, &len);
4093 if (!(editor->styleFlags & ES_MULTILINE))
4095 len = 0;
4096 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4097 len++;
4099 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4100 ME_EndToUnicode(codepage, textW);
4101 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4102 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4105 ME_CommitUndo(editor);
4106 ME_WrapMarkedParagraphs(editor);
4107 ME_MoveCaret(editor);
4108 return 0;
4110 case WM_DESTROY:
4111 ME_DestroyEditor(editor);
4112 return 0;
4113 case WM_SETCURSOR:
4115 return ME_SetCursor(editor);
4117 case WM_LBUTTONDBLCLK:
4118 case WM_LBUTTONDOWN:
4120 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4121 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4122 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4123 return 0;
4124 ITextHost_TxSetFocus(editor->texthost);
4125 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4126 ME_CalculateClickCount(editor, msg, wParam, lParam));
4127 ITextHost_TxSetCapture(editor->texthost, TRUE);
4128 editor->bMouseCaptured = TRUE;
4129 ME_LinkNotify(editor,msg,wParam,lParam);
4130 if (!ME_SetCursor(editor)) goto do_default;
4131 break;
4133 case WM_MOUSEMOVE:
4134 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4135 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4136 return 0;
4137 if (editor->bMouseCaptured)
4138 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4139 ME_LinkNotify(editor,msg,wParam,lParam);
4140 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4141 if (editor->bMouseCaptured)
4142 ME_SetCursor(editor);
4143 break;
4144 case WM_LBUTTONUP:
4145 if (editor->bMouseCaptured) {
4146 ITextHost_TxSetCapture(editor->texthost, FALSE);
4147 editor->bMouseCaptured = FALSE;
4149 if (editor->nSelectionType == stDocument)
4150 editor->nSelectionType = stPosition;
4151 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4152 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4153 return 0;
4154 else
4156 ME_SetCursor(editor);
4157 ME_LinkNotify(editor,msg,wParam,lParam);
4159 break;
4160 case WM_RBUTTONUP:
4161 case WM_RBUTTONDOWN:
4162 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4163 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4164 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4165 return 0;
4166 goto do_default;
4167 case WM_CONTEXTMENU:
4168 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4169 goto do_default;
4170 break;
4171 case WM_SETFOCUS:
4172 editor->bHaveFocus = TRUE;
4173 ME_ShowCaret(editor);
4174 ME_SendOldNotify(editor, EN_SETFOCUS);
4175 return 0;
4176 case WM_KILLFOCUS:
4177 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4178 editor->bHaveFocus = FALSE;
4179 editor->wheel_remain = 0;
4180 ME_HideCaret(editor);
4181 ME_SendOldNotify(editor, EN_KILLFOCUS);
4182 return 0;
4183 case WM_COMMAND:
4184 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4185 return 0;
4186 case WM_KEYUP:
4187 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4188 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4189 return 0;
4190 goto do_default;
4191 case WM_KEYDOWN:
4192 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4193 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4194 return 0;
4195 if (ME_KeyDown(editor, LOWORD(wParam)))
4196 return 0;
4197 goto do_default;
4198 case WM_CHAR:
4199 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4200 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4201 return 0;
4202 return ME_Char(editor, wParam, lParam, unicode);
4203 case WM_UNICHAR:
4204 if (unicode)
4206 if(wParam == UNICODE_NOCHAR) return TRUE;
4207 if(wParam <= 0x000fffff)
4209 if(wParam > 0xffff) /* convert to surrogates */
4211 wParam -= 0x10000;
4212 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4213 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4214 } else {
4215 ME_Char(editor, wParam, 0, TRUE);
4218 return 0;
4220 break;
4221 case EM_STOPGROUPTYPING:
4222 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4223 return 0;
4224 case WM_HSCROLL:
4226 const int scrollUnit = 7;
4228 switch(LOWORD(wParam))
4230 case SB_LEFT:
4231 ME_ScrollAbs(editor, 0, 0);
4232 break;
4233 case SB_RIGHT:
4234 ME_ScrollAbs(editor,
4235 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4236 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4237 break;
4238 case SB_LINELEFT:
4239 ME_ScrollLeft(editor, scrollUnit);
4240 break;
4241 case SB_LINERIGHT:
4242 ME_ScrollRight(editor, scrollUnit);
4243 break;
4244 case SB_PAGELEFT:
4245 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4246 break;
4247 case SB_PAGERIGHT:
4248 ME_ScrollRight(editor, editor->sizeWindow.cx);
4249 break;
4250 case SB_THUMBTRACK:
4251 case SB_THUMBPOSITION:
4253 int pos = HIWORD(wParam);
4254 if (editor->horz_si.nMax > 0xffff)
4255 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4256 ME_HScrollAbs(editor, pos);
4257 break;
4260 break;
4262 case EM_SCROLL: /* fall through */
4263 case WM_VSCROLL:
4265 int origNPos;
4266 int lineHeight = get_default_line_height( editor );
4268 origNPos = editor->vert_si.nPos;
4270 switch(LOWORD(wParam))
4272 case SB_TOP:
4273 ME_ScrollAbs(editor, 0, 0);
4274 break;
4275 case SB_BOTTOM:
4276 ME_ScrollAbs(editor,
4277 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4278 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4279 break;
4280 case SB_LINEUP:
4281 ME_ScrollUp(editor,lineHeight);
4282 break;
4283 case SB_LINEDOWN:
4284 ME_ScrollDown(editor,lineHeight);
4285 break;
4286 case SB_PAGEUP:
4287 ME_ScrollUp(editor,editor->sizeWindow.cy);
4288 break;
4289 case SB_PAGEDOWN:
4290 ME_ScrollDown(editor,editor->sizeWindow.cy);
4291 break;
4292 case SB_THUMBTRACK:
4293 case SB_THUMBPOSITION:
4295 int pos = HIWORD(wParam);
4296 if (editor->vert_si.nMax > 0xffff)
4297 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4298 ME_VScrollAbs(editor, pos);
4299 break;
4302 if (msg == EM_SCROLL)
4303 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4304 break;
4306 case WM_MOUSEWHEEL:
4308 int delta;
4309 BOOL ctrl_is_down;
4311 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4312 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4313 return 0;
4315 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4317 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4319 /* if scrolling changes direction, ignore left overs */
4320 if ((delta < 0 && editor->wheel_remain < 0) ||
4321 (delta > 0 && editor->wheel_remain > 0))
4322 editor->wheel_remain += delta;
4323 else
4324 editor->wheel_remain = delta;
4326 if (editor->wheel_remain)
4328 if (ctrl_is_down) {
4329 int numerator;
4330 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4332 numerator = 100;
4333 } else {
4334 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4336 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4337 if (numerator >= 10 && numerator <= 500)
4338 ME_SetZoom(editor, numerator, 100);
4339 } else {
4340 UINT max_lines = 3;
4341 int lines = 0;
4343 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4344 if (max_lines)
4345 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4346 if (lines)
4347 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4350 break;
4352 case EM_GETRECT:
4354 *((RECT *)lParam) = editor->rcFormat;
4355 if (editor->bDefaultFormatRect)
4356 ((RECT *)lParam)->left -= editor->selofs;
4357 return 0;
4359 case EM_SETRECT:
4360 case EM_SETRECTNP:
4362 if (lParam)
4364 int border = 0;
4365 RECT clientRect;
4366 RECT *rc = (RECT *)lParam;
4368 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4369 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4370 if (wParam == 0)
4372 editor->rcFormat.top = max(0, rc->top - border);
4373 editor->rcFormat.left = max(0, rc->left - border);
4374 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4375 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4376 } else if (wParam == 1) {
4377 /* MSDN incorrectly says a wParam value of 1 causes the
4378 * lParam rect to be used as a relative offset,
4379 * however, the tests show it just prevents min/max bound
4380 * checking. */
4381 editor->rcFormat.top = rc->top - border;
4382 editor->rcFormat.left = rc->left - border;
4383 editor->rcFormat.bottom = rc->bottom;
4384 editor->rcFormat.right = rc->right + border;
4385 } else {
4386 return 0;
4388 editor->bDefaultFormatRect = FALSE;
4390 else
4392 ME_SetDefaultFormatRect(editor);
4393 editor->bDefaultFormatRect = TRUE;
4395 ME_MarkAllForWrapping(editor);
4396 ME_WrapMarkedParagraphs(editor);
4397 ME_UpdateScrollBar(editor);
4398 if (msg != EM_SETRECTNP)
4399 ME_Repaint(editor);
4400 return 0;
4402 case EM_REQUESTRESIZE:
4403 ME_SendRequestResize(editor, TRUE);
4404 return 0;
4405 case WM_SETREDRAW:
4406 goto do_default;
4407 case WM_SIZE:
4409 RECT clientRect;
4411 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4412 if (editor->bDefaultFormatRect) {
4413 ME_SetDefaultFormatRect(editor);
4414 } else {
4415 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4416 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4418 editor->prevClientRect = clientRect;
4419 ME_RewrapRepaint(editor);
4420 goto do_default;
4422 /* IME messages to make richedit controls IME aware */
4423 case WM_IME_SETCONTEXT:
4424 case WM_IME_CONTROL:
4425 case WM_IME_SELECT:
4426 case WM_IME_COMPOSITIONFULL:
4427 return 0;
4428 case WM_IME_STARTCOMPOSITION:
4430 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4431 ME_DeleteSelection(editor);
4432 ME_CommitUndo(editor);
4433 ME_UpdateRepaint(editor, FALSE);
4434 return 0;
4436 case WM_IME_COMPOSITION:
4438 HIMC hIMC;
4440 ME_Style *style = ME_GetInsertStyle(editor, 0);
4441 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4442 ME_DeleteSelection(editor);
4443 ME_SaveTempStyle(editor);
4444 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4446 LPWSTR lpCompStr = NULL;
4447 DWORD dwBufLen;
4448 DWORD dwIndex = lParam & GCS_RESULTSTR;
4449 if (!dwIndex)
4450 dwIndex = GCS_COMPSTR;
4452 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4453 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4454 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4455 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4456 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4457 HeapFree(GetProcessHeap(), 0, lpCompStr);
4459 if (dwIndex == GCS_COMPSTR)
4460 ME_SetSelection(editor,editor->imeStartIndex,
4461 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4463 ME_ReleaseStyle(style);
4464 ME_CommitUndo(editor);
4465 ME_UpdateRepaint(editor, FALSE);
4466 return 0;
4468 case WM_IME_ENDCOMPOSITION:
4470 ME_DeleteSelection(editor);
4471 editor->imeStartIndex=-1;
4472 return 0;
4474 case EM_GETOLEINTERFACE:
4476 if (!editor->reOle)
4477 if (!CreateIRichEditOle(editor, (LPVOID *)&editor->reOle))
4478 return 0;
4479 *(LPVOID *)lParam = editor->reOle;
4480 IRichEditOle_AddRef(editor->reOle);
4481 return 1;
4483 case EM_GETPASSWORDCHAR:
4485 return editor->cPasswordMask;
4487 case EM_SETOLECALLBACK:
4488 if(editor->lpOleCallback)
4489 IRichEditOleCallback_Release(editor->lpOleCallback);
4490 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4491 if(editor->lpOleCallback)
4492 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4493 return TRUE;
4494 case EM_GETWORDBREAKPROC:
4495 return (LRESULT)editor->pfnWordBreak;
4496 case EM_SETWORDBREAKPROC:
4498 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4500 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4501 return (LRESULT)pfnOld;
4503 case EM_GETTEXTMODE:
4504 return editor->mode;
4505 case EM_SETTEXTMODE:
4507 int mask = 0;
4508 int changes = 0;
4510 if (ME_GetTextLength(editor) ||
4511 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4512 return E_UNEXPECTED;
4514 /* Check for mutually exclusive flags in adjacent bits of wParam */
4515 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4516 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4517 return E_INVALIDARG;
4519 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4521 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4522 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4523 if (wParam & TM_PLAINTEXT) {
4524 /* Clear selection since it should be possible to select the
4525 * end of text run for rich text */
4526 ME_InvalidateSelection(editor);
4527 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4528 editor->pCursors[1] = editor->pCursors[0];
4529 /* plain text can only have the default style. */
4530 ME_ClearTempStyle(editor);
4531 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4532 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4533 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4536 /* FIXME: Currently no support for undo level and code page options */
4537 editor->mode = (editor->mode & ~mask) | changes;
4538 return 0;
4540 case EM_SETPASSWORDCHAR:
4542 editor->cPasswordMask = wParam;
4543 ME_RewrapRepaint(editor);
4544 return 0;
4546 case EM_SETTARGETDEVICE:
4547 if (wParam == 0)
4549 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4550 if (editor->nAvailWidth || editor->bWordWrap != new)
4552 editor->bWordWrap = new;
4553 editor->nAvailWidth = 0; /* wrap to client area */
4554 ME_RewrapRepaint(editor);
4556 } else {
4557 int width = max(0, lParam);
4558 if ((editor->styleFlags & ES_MULTILINE) &&
4559 (!editor->bWordWrap || editor->nAvailWidth != width))
4561 editor->nAvailWidth = width;
4562 editor->bWordWrap = TRUE;
4563 ME_RewrapRepaint(editor);
4565 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4567 return TRUE;
4568 default:
4569 do_default:
4570 *phresult = S_FALSE;
4571 break;
4573 return 0L;
4576 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4577 LPARAM lParam, BOOL unicode)
4579 ME_TextEditor *editor;
4580 HRESULT hresult;
4581 LRESULT lresult = 0;
4583 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4584 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4586 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4587 if (!editor)
4589 if (msg == WM_NCCREATE)
4591 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4592 ITextHost *texthost;
4594 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4595 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4596 return texthost != NULL;
4598 else
4600 return DefWindowProcW(hWnd, msg, wParam, lParam);
4604 switch (msg)
4606 case WM_PAINT:
4608 HDC hDC;
4609 RECT rc;
4610 PAINTSTRUCT ps;
4612 hDC = BeginPaint(editor->hWnd, &ps);
4613 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4614 ME_SendOldNotify(editor, EN_UPDATE);
4615 /* Erase area outside of the formatting rectangle */
4616 if (ps.rcPaint.top < editor->rcFormat.top)
4618 rc = ps.rcPaint;
4619 rc.bottom = editor->rcFormat.top;
4620 FillRect(hDC, &rc, editor->hbrBackground);
4621 ps.rcPaint.top = editor->rcFormat.top;
4623 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4624 rc = ps.rcPaint;
4625 rc.top = editor->rcFormat.bottom;
4626 FillRect(hDC, &rc, editor->hbrBackground);
4627 ps.rcPaint.bottom = editor->rcFormat.bottom;
4629 if (ps.rcPaint.left < editor->rcFormat.left) {
4630 rc = ps.rcPaint;
4631 rc.right = editor->rcFormat.left;
4632 FillRect(hDC, &rc, editor->hbrBackground);
4633 ps.rcPaint.left = editor->rcFormat.left;
4635 if (ps.rcPaint.right > editor->rcFormat.right) {
4636 rc = ps.rcPaint;
4637 rc.left = editor->rcFormat.right;
4638 FillRect(hDC, &rc, editor->hbrBackground);
4639 ps.rcPaint.right = editor->rcFormat.right;
4642 ME_PaintContent(editor, hDC, &ps.rcPaint);
4643 EndPaint(editor->hWnd, &ps);
4644 return 0;
4646 case WM_ERASEBKGND:
4648 HDC hDC = (HDC)wParam;
4649 RECT rc;
4651 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4652 FillRect(hDC, &rc, editor->hbrBackground);
4653 return 1;
4655 case EM_SETOPTIONS:
4657 DWORD dwStyle;
4658 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4659 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4660 ECO_SELECTIONBAR;
4661 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4662 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4663 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4664 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4665 return lresult;
4667 case EM_SETREADONLY:
4669 DWORD dwStyle;
4670 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4671 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4672 dwStyle &= ~ES_READONLY;
4673 if (wParam)
4674 dwStyle |= ES_READONLY;
4675 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4676 return lresult;
4678 default:
4679 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4682 if (hresult == S_FALSE)
4683 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4685 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4686 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4688 return lresult;
4691 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4693 BOOL unicode = TRUE;
4695 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4696 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4697 unicode = FALSE;
4699 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4702 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4704 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4707 /******************************************************************
4708 * RichEditANSIWndProc (RICHED20.10)
4710 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4712 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4715 /******************************************************************
4716 * RichEdit10ANSIWndProc (RICHED20.9)
4718 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4720 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4722 ITextHost *texthost;
4723 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4725 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4726 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4727 return texthost != NULL;
4729 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4732 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4734 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4737 /* Fill buffer with srcChars unicode characters from the start cursor.
4739 * buffer: destination buffer
4740 * buflen: length of buffer in characters excluding the NULL terminator.
4741 * start: start of editor text to copy into buffer.
4742 * srcChars: Number of characters to use from the editor text.
4743 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4745 * returns the number of characters written excluding the NULL terminator.
4747 * The written text is always NULL terminated.
4749 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4750 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4751 BOOL bEOP)
4753 ME_DisplayItem *pRun, *pNextRun;
4754 const WCHAR *pStart = buffer;
4755 const WCHAR cr_lf[] = {'\r', '\n', 0};
4756 const WCHAR *str;
4757 int nLen;
4759 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4760 if (editor->bEmulateVersion10) bCRLF = FALSE;
4762 pRun = start->pRun;
4763 assert(pRun);
4764 pNextRun = ME_FindItemFwd(pRun, diRun);
4766 nLen = pRun->member.run.len - start->nOffset;
4767 str = get_text( &pRun->member.run, start->nOffset );
4769 while (srcChars && buflen && pNextRun)
4771 int nFlags = pRun->member.run.nFlags;
4773 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4775 if (buflen == 1) break;
4776 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4777 * EM_GETTEXTEX, however, this is done for copying text which
4778 * also uses this function. */
4779 srcChars -= min(nLen, srcChars);
4780 nLen = 2;
4781 str = cr_lf;
4782 } else {
4783 nLen = min(nLen, srcChars);
4784 srcChars -= nLen;
4787 nLen = min(nLen, buflen);
4788 buflen -= nLen;
4790 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4792 buffer += nLen;
4794 pRun = pNextRun;
4795 pNextRun = ME_FindItemFwd(pRun, diRun);
4797 nLen = pRun->member.run.len;
4798 str = get_text( &pRun->member.run, 0 );
4800 /* append '\r' to the last paragraph. */
4801 if (pRun->next->type == diTextEnd && bEOP)
4803 *buffer = '\r';
4804 buffer ++;
4806 *buffer = 0;
4807 return buffer - pStart;
4810 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4812 WNDCLASSW wcW;
4813 WNDCLASSA wcA;
4815 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4816 wcW.lpfnWndProc = RichEditWndProcW;
4817 wcW.cbClsExtra = 0;
4818 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4819 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4820 wcW.hIcon = NULL;
4821 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4822 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4823 wcW.lpszMenuName = NULL;
4825 if (is_version_nt())
4827 wcW.lpszClassName = RICHEDIT_CLASS20W;
4828 if (!RegisterClassW(&wcW)) return FALSE;
4829 wcW.lpszClassName = MSFTEDIT_CLASS;
4830 if (!RegisterClassW(&wcW)) return FALSE;
4832 else
4834 /* WNDCLASSA/W have the same layout */
4835 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4836 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4837 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4838 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4841 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4842 wcA.lpfnWndProc = RichEditWndProcA;
4843 wcA.cbClsExtra = 0;
4844 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4845 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4846 wcA.hIcon = NULL;
4847 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4848 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4849 wcA.lpszMenuName = NULL;
4850 wcA.lpszClassName = RICHEDIT_CLASS20A;
4851 if (!RegisterClassA(&wcA)) return FALSE;
4852 wcA.lpszClassName = "RichEdit50A";
4853 if (!RegisterClassA(&wcA)) return FALSE;
4855 return TRUE;
4858 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4859 /* FIXME: Not implemented */
4860 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4861 hWnd, msg, get_msg_name(msg), wParam, lParam);
4862 return DefWindowProcW(hWnd, msg, wParam, lParam);
4865 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4866 /* FIXME: Not implemented */
4867 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4868 hWnd, msg, get_msg_name(msg), wParam, lParam);
4869 return DefWindowProcW(hWnd, msg, wParam, lParam);
4872 /******************************************************************
4873 * REExtendedRegisterClass (RICHED20.8)
4875 * FIXME undocumented
4876 * Need to check for errors and implement controls and callbacks
4878 LRESULT WINAPI REExtendedRegisterClass(void)
4880 WNDCLASSW wcW;
4881 UINT result;
4883 FIXME("semi stub\n");
4885 wcW.cbClsExtra = 0;
4886 wcW.cbWndExtra = 4;
4887 wcW.hInstance = NULL;
4888 wcW.hIcon = NULL;
4889 wcW.hCursor = NULL;
4890 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4891 wcW.lpszMenuName = NULL;
4893 if (!ME_ListBoxRegistered)
4895 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4896 wcW.lpfnWndProc = REListWndProc;
4897 wcW.lpszClassName = REListBox20W;
4898 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4901 if (!ME_ComboBoxRegistered)
4903 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4904 wcW.lpfnWndProc = REComboWndProc;
4905 wcW.lpszClassName = REComboBox20W;
4906 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4909 result = 0;
4910 if (ME_ListBoxRegistered)
4911 result += 1;
4912 if (ME_ComboBoxRegistered)
4913 result += 2;
4915 return result;
4918 static BOOL isurlspecial(WCHAR c)
4920 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4921 return strchrW( special_chars, c ) != NULL;
4925 * This proc takes a selection, and scans it forward in order to select the span
4926 * of a possible URL candidate. A possible URL candidate must start with isalnum
4927 * or one of the following special characters: *|/\+%#@ and must consist entirely
4928 * of the characters allowed to start the URL, plus : (colon) which may occur
4929 * at most once, and not at either end.
4931 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4932 const ME_Cursor *start,
4933 int nChars,
4934 ME_Cursor *candidate_min,
4935 ME_Cursor *candidate_max)
4937 ME_Cursor cursor = *start;
4938 BOOL foundColon = FALSE;
4939 BOOL candidateStarted = FALSE;
4940 WCHAR lastAcceptedChar = '\0';
4942 while (nChars > 0)
4944 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4945 WCHAR *str = strStart + cursor.nOffset;
4946 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4947 nChars -= nLen;
4949 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4951 /* Find start of candidate */
4952 if (!candidateStarted)
4954 while (nLen)
4956 nLen--;
4957 if (isalnumW(*str) || isurlspecial(*str))
4959 cursor.nOffset = str - strStart;
4960 *candidate_min = cursor;
4961 candidateStarted = TRUE;
4962 lastAcceptedChar = *str++;
4963 break;
4965 str++;
4969 /* Find end of candidate */
4970 if (candidateStarted) {
4971 while (nLen)
4973 nLen--;
4974 if (*str == ':' && !foundColon) {
4975 foundColon = TRUE;
4976 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4977 cursor.nOffset = str - strStart;
4978 if (lastAcceptedChar == ':')
4979 ME_MoveCursorChars(editor, &cursor, -1);
4980 *candidate_max = cursor;
4981 return TRUE;
4983 lastAcceptedChar = *str++;
4986 } else {
4987 /* End of paragraph: skip it if before candidate span, or terminates
4988 current active span */
4989 if (candidateStarted) {
4990 if (lastAcceptedChar == ':')
4991 ME_MoveCursorChars(editor, &cursor, -1);
4992 *candidate_max = cursor;
4993 return TRUE;
4997 /* Reaching this point means no span was found, so get next span */
4998 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4999 if (candidateStarted) {
5000 /* There are no further runs, so take end of text as end of candidate */
5001 cursor.nOffset = str - strStart;
5002 if (lastAcceptedChar == ':')
5003 ME_MoveCursorChars(editor, &cursor, -1);
5004 *candidate_max = cursor;
5005 return TRUE;
5007 *candidate_max = *candidate_min = cursor;
5008 return FALSE;
5010 cursor.nOffset = 0;
5013 if (candidateStarted) {
5014 /* There are no further runs, so take end of text as end of candidate */
5015 if (lastAcceptedChar == ':')
5016 ME_MoveCursorChars(editor, &cursor, -1);
5017 *candidate_max = cursor;
5018 return TRUE;
5020 *candidate_max = *candidate_min = cursor;
5021 return FALSE;
5025 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5027 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5029 #define MAX_PREFIX_LEN 9
5030 struct prefix_s {
5031 const WCHAR text[MAX_PREFIX_LEN];
5032 int length;
5033 }prefixes[] = {
5034 {{'p','r','o','s','p','e','r','o',':'}, 9},
5035 {{'t','e','l','n','e','t',':'}, 7},
5036 {{'g','o','p','h','e','r',':'}, 7},
5037 {{'m','a','i','l','t','o',':'}, 7},
5038 {{'h','t','t','p','s',':'}, 6},
5039 {{'f','i','l','e',':'}, 5},
5040 {{'n','e','w','s',':'}, 5},
5041 {{'w','a','i','s',':'}, 5},
5042 {{'n','n','t','p',':'}, 5},
5043 {{'h','t','t','p',':'}, 5},
5044 {{'w','w','w','.'}, 4},
5045 {{'f','t','p',':'}, 4},
5047 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5048 unsigned int i;
5050 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5051 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5053 if (nChars < prefixes[i].length) continue;
5054 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5055 return TRUE;
5057 return FALSE;
5058 #undef MAX_PREFIX_LEN
5062 * This proc walks through the indicated selection and evaluates whether each
5063 * section identified by ME_FindNextURLCandidate and in-between sections have
5064 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5065 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5067 * Since this function can cause runs to be split, do not depend on the value
5068 * of the start cursor at the end of the function.
5070 * nChars may be set to INT_MAX to update to the end of the text.
5072 * Returns TRUE if at least one section was modified.
5074 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5076 BOOL modified = FALSE;
5077 ME_Cursor startCur = *start;
5079 if (!editor->AutoURLDetect_bEnable) return FALSE;
5083 CHARFORMAT2W link;
5084 ME_Cursor candidateStart, candidateEnd;
5086 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5087 &candidateStart, &candidateEnd))
5089 /* Section before candidate is not an URL */
5090 int cMin = ME_GetCursorOfs(&candidateStart);
5091 int cMax = ME_GetCursorOfs(&candidateEnd);
5093 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5094 candidateStart = candidateEnd;
5095 nChars -= cMax - ME_GetCursorOfs(&startCur);
5097 else
5099 /* No more candidates until end of selection */
5100 nChars = 0;
5103 if (startCur.pRun != candidateStart.pRun ||
5104 startCur.nOffset != candidateStart.nOffset)
5106 /* CFE_LINK effect should be consistently unset */
5107 link.cbSize = sizeof(link);
5108 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5109 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5111 /* CFE_LINK must be unset from this range */
5112 memset(&link, 0, sizeof(CHARFORMAT2W));
5113 link.cbSize = sizeof(link);
5114 link.dwMask = CFM_LINK;
5115 link.dwEffects = 0;
5116 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5117 /* Update candidateEnd since setting character formats may split
5118 * runs, which can cause a cursor to be at an invalid offset within
5119 * a split run. */
5120 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5122 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5123 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5125 modified = TRUE;
5128 if (candidateStart.pRun != candidateEnd.pRun ||
5129 candidateStart.nOffset != candidateEnd.nOffset)
5131 /* CFE_LINK effect should be consistently set */
5132 link.cbSize = sizeof(link);
5133 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5134 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5136 /* CFE_LINK must be set on this range */
5137 memset(&link, 0, sizeof(CHARFORMAT2W));
5138 link.cbSize = sizeof(link);
5139 link.dwMask = CFM_LINK;
5140 link.dwEffects = CFE_LINK;
5141 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5142 modified = TRUE;
5145 startCur = candidateEnd;
5146 } while (nChars > 0);
5147 return modified;