riched20: Don't return DLGC_HASSETSEL from WM_GETDLGCODE if the control style include...
[wine/wine-gecko.git] / dlls / riched20 / editor.c
blob1d17ef015b54b2741522907b35adeae05710834c
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 #if 0
1202 /* FIXME: enable it when rich-edit properly implements this method */
1203 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1204 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1205 #endif
1206 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1207 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1208 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1209 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1210 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1212 REOBJECT reobject;
1214 reobject.cbStruct = sizeof(reobject);
1215 reobject.cp = REO_CP_SELECTION;
1216 reobject.clsid = clsid;
1217 reobject.poleobj = lpObject;
1218 reobject.pstg = lpStorage;
1219 reobject.polesite = lpClientSite;
1220 /* convert from twips to .01 mm */
1221 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1222 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1223 reobject.dvaspect = DVASPECT_CONTENT;
1224 reobject.dwFlags = 0; /* FIXME */
1225 reobject.dwUser = 0;
1227 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1228 ret = TRUE;
1231 if (lpObject) IOleObject_Release(lpObject);
1232 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1233 if (lpStorage) IStorage_Release(lpStorage);
1234 if (lpDataObject) IDataObject_Release(lpDataObject);
1235 if (lpOleCache) IOleCache_Release(lpOleCache);
1237 return ret;
1240 static void ME_RTFReadPictGroup(RTF_Info *info)
1242 SIZEL sz;
1243 BYTE* buffer = NULL;
1244 unsigned bufsz, bufidx;
1245 BOOL flip;
1246 BYTE val;
1247 METAFILEPICT mfp;
1248 HENHMETAFILE hemf;
1249 HBITMAP hbmp;
1250 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1252 RTFGetToken (info);
1253 if (info->rtfClass == rtfEOF)
1254 return;
1255 mfp.mm = MM_TEXT;
1256 /* fetch picture type */
1257 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1259 mfp.mm = info->rtfParam;
1260 gfx = gfx_metafile;
1262 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1264 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1265 gfx = gfx_dib;
1267 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1269 gfx = gfx_enhmetafile;
1271 else
1273 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1274 goto skip_group;
1276 sz.cx = sz.cy = 0;
1277 /* fetch picture attributes */
1278 for (;;)
1280 RTFGetToken (info);
1281 if (info->rtfClass == rtfEOF)
1282 return;
1283 if (info->rtfClass == rtfText)
1284 break;
1285 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1287 ERR("Expected picture attribute (%d %d)\n",
1288 info->rtfClass, info->rtfMajor);
1289 goto skip_group;
1291 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1293 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1295 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1297 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1299 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1300 sz.cx = info->rtfParam;
1301 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1302 sz.cy = info->rtfParam;
1303 else
1304 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1306 /* fetch picture data */
1307 bufsz = 1024;
1308 bufidx = 0;
1309 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1310 val = info->rtfMajor;
1311 for (flip = TRUE;; flip = !flip)
1313 RTFGetToken (info);
1314 if (info->rtfClass == rtfEOF)
1316 HeapFree(GetProcessHeap(), 0, buffer);
1317 return; /* Warn ?? */
1319 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1320 break;
1321 if (info->rtfClass != rtfText) goto skip_group;
1322 if (flip)
1324 if (bufidx >= bufsz &&
1325 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1326 goto skip_group;
1327 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1329 else
1330 val = info->rtfMajor;
1332 if (flip) FIXME("wrong hex string\n");
1334 switch (gfx)
1336 case gfx_enhmetafile:
1337 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1338 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1339 break;
1340 case gfx_metafile:
1341 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1342 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1343 break;
1344 case gfx_dib:
1346 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1347 HDC hdc = GetDC(0);
1348 unsigned nc = bi->bmiHeader.biClrUsed;
1350 /* not quite right, especially for bitfields type of compression */
1351 if (!nc && bi->bmiHeader.biBitCount <= 8)
1352 nc = 1 << bi->bmiHeader.biBitCount;
1353 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1354 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1355 bi, DIB_RGB_COLORS)))
1356 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1357 ReleaseDC(0, hdc);
1359 break;
1360 default:
1361 break;
1363 HeapFree(GetProcessHeap(), 0, buffer);
1364 RTFRouteToken (info); /* feed "}" back to router */
1365 return;
1366 skip_group:
1367 HeapFree(GetProcessHeap(), 0, buffer);
1368 RTFSkipGroup(info);
1369 RTFRouteToken(info); /* feed "}" back to router */
1372 /* for now, lookup the \result part and use it, whatever the object */
1373 static void ME_RTFReadObjectGroup(RTF_Info *info)
1375 for (;;)
1377 RTFGetToken (info);
1378 if (info->rtfClass == rtfEOF)
1379 return;
1380 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1381 break;
1382 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1384 RTFGetToken (info);
1385 if (info->rtfClass == rtfEOF)
1386 return;
1387 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1389 int level = 1;
1391 while (RTFGetToken (info) != rtfEOF)
1393 if (info->rtfClass == rtfGroup)
1395 if (info->rtfMajor == rtfBeginGroup) level++;
1396 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1398 RTFRouteToken(info);
1401 else RTFSkipGroup(info);
1402 continue;
1404 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1406 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1407 return;
1410 RTFRouteToken(info); /* feed "}" back to router */
1413 static void ME_RTFReadHook(RTF_Info *info)
1415 switch(info->rtfClass)
1417 case rtfGroup:
1418 switch(info->rtfMajor)
1420 case rtfBeginGroup:
1421 if (info->stackTop < maxStack) {
1422 info->stack[info->stackTop].style = info->style;
1423 ME_AddRefStyle(info->style);
1424 info->stack[info->stackTop].codePage = info->codePage;
1425 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1427 info->stackTop++;
1428 info->styleChanged = FALSE;
1429 break;
1430 case rtfEndGroup:
1432 RTFFlushOutputBuffer(info);
1433 info->stackTop--;
1434 if (info->stackTop <= 0)
1435 info->rtfClass = rtfEOF;
1436 if (info->stackTop < 0)
1437 return;
1439 ME_ReleaseStyle(info->style);
1440 info->style = info->stack[info->stackTop].style;
1441 info->codePage = info->stack[info->stackTop].codePage;
1442 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1443 break;
1446 break;
1450 void
1451 ME_StreamInFill(ME_InStream *stream)
1453 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1454 (BYTE *)stream->buffer,
1455 sizeof(stream->buffer),
1456 (LONG *)&stream->dwSize);
1457 stream->dwUsed = 0;
1460 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1462 RTF_Info parser;
1463 ME_Style *style;
1464 int from, to, nUndoMode;
1465 int nEventMask = editor->nEventMask;
1466 ME_InStream inStream;
1467 BOOL invalidRTF = FALSE;
1468 ME_Cursor *selStart, *selEnd;
1469 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1471 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1472 editor->nEventMask = 0;
1474 ME_GetSelectionOfs(editor, &from, &to);
1475 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1477 ME_GetSelection(editor, &selStart, &selEnd);
1478 style = ME_GetSelectionInsertStyle(editor);
1480 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1482 /* Don't insert text at the end of the table row */
1483 if (!editor->bEmulateVersion10) { /* v4.1 */
1484 ME_DisplayItem *para = editor->pCursors->pPara;
1485 if (para->member.para.nFlags & MEPF_ROWEND)
1487 para = para->member.para.next_para;
1488 editor->pCursors[0].pPara = para;
1489 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1490 editor->pCursors[0].nOffset = 0;
1492 if (para->member.para.nFlags & MEPF_ROWSTART)
1494 para = para->member.para.next_para;
1495 editor->pCursors[0].pPara = para;
1496 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1497 editor->pCursors[0].nOffset = 0;
1499 editor->pCursors[1] = editor->pCursors[0];
1500 } else { /* v1.0 - 3.0 */
1501 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1502 ME_IsInTable(editor->pCursors[0].pRun))
1503 return 0;
1505 } else {
1506 style = editor->pBuffer->pDefaultStyle;
1507 ME_AddRefStyle(style);
1508 ME_SetSelection(editor, 0, 0);
1509 ME_InternalDeleteText(editor, &editor->pCursors[1],
1510 ME_GetTextLength(editor), FALSE);
1511 from = to = 0;
1512 ME_ClearTempStyle(editor);
1513 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1517 /* Back up undo mode to a local variable */
1518 nUndoMode = editor->nUndoMode;
1520 /* Only create an undo if SFF_SELECTION is set */
1521 if (!(format & SFF_SELECTION))
1522 editor->nUndoMode = umIgnore;
1524 inStream.editstream = stream;
1525 inStream.editstream->dwError = 0;
1526 inStream.dwSize = 0;
1527 inStream.dwUsed = 0;
1529 if (format & SF_RTF)
1531 /* Check if it's really RTF, and if it is not, use plain text */
1532 ME_StreamInFill(&inStream);
1533 if (!inStream.editstream->dwError)
1535 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1536 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1538 invalidRTF = TRUE;
1539 inStream.editstream->dwError = -16;
1544 if (!invalidRTF && !inStream.editstream->dwError)
1546 if (format & SF_RTF) {
1547 from = ME_GetCursorOfs(&editor->pCursors[0]);
1549 /* setup the RTF parser */
1550 memset(&parser, 0, sizeof parser);
1551 RTFSetEditStream(&parser, &inStream);
1552 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1553 parser.editor = editor;
1554 parser.style = style;
1555 WriterInit(&parser);
1556 RTFInit(&parser);
1557 RTFSetReadHook(&parser, ME_RTFReadHook);
1558 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1559 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1560 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1562 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1563 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1565 BeginFile(&parser);
1567 /* do the parsing */
1568 RTFRead(&parser);
1569 RTFFlushOutputBuffer(&parser);
1570 if (!editor->bEmulateVersion10) { /* v4.1 */
1571 if (parser.tableDef && parser.tableDef->tableRowStart &&
1572 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1574 /* Delete any incomplete table row at the end of the rich text. */
1575 int nOfs, nChars;
1576 ME_DisplayItem *para;
1578 parser.rtfMinor = rtfRow;
1579 /* Complete the table row before deleting it.
1580 * By doing it this way we will have the current paragraph format set
1581 * properly to reflect that is not in the complete table, and undo items
1582 * will be added for this change to the current paragraph format. */
1583 if (parser.nestingLevel > 0)
1585 while (parser.nestingLevel > 1)
1586 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1587 para = parser.tableDef->tableRowStart;
1588 ME_RTFSpecialCharHook(&parser);
1589 } else {
1590 para = parser.tableDef->tableRowStart;
1591 ME_RTFSpecialCharHook(&parser);
1592 assert(para->member.para.nFlags & MEPF_ROWEND);
1593 para = para->member.para.next_para;
1596 editor->pCursors[1].pPara = para;
1597 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1598 editor->pCursors[1].nOffset = 0;
1599 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1600 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1601 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1602 if (parser.tableDef)
1603 parser.tableDef->tableRowStart = NULL;
1606 ME_CheckTablesForCorruption(editor);
1607 RTFDestroy(&parser);
1608 if (parser.lpRichEditOle)
1609 IRichEditOle_Release(parser.lpRichEditOle);
1611 if (parser.stackTop > 0)
1613 while (--parser.stackTop >= 0)
1615 ME_ReleaseStyle(parser.style);
1616 parser.style = parser.stack[parser.stackTop].style;
1618 if (!inStream.editstream->dwError)
1619 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1622 /* Remove last line break, as mandated by tests. This is not affected by
1623 CR/LF counters, since RTF streaming presents only \para tokens, which
1624 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1626 if (stripLastCR) {
1627 int newto;
1628 ME_GetSelection(editor, &selStart, &selEnd);
1629 newto = ME_GetCursorOfs(selEnd);
1630 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1631 WCHAR lastchar[3] = {'\0', '\0'};
1632 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1633 ME_Cursor linebreakCursor = *selEnd;
1635 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1636 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE);
1637 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1638 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1642 to = ME_GetCursorOfs(&editor->pCursors[0]);
1643 num_read = to - from;
1645 style = parser.style;
1647 else if (format & SF_TEXT)
1648 num_read = ME_StreamInText(editor, format, &inStream, style);
1649 else
1650 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1651 /* put the cursor at the top */
1652 if (!(format & SFF_SELECTION))
1653 ME_SetSelection(editor, 0, 0);
1656 /* Restore saved undo mode */
1657 editor->nUndoMode = nUndoMode;
1659 /* even if we didn't add an undo, we need to commit anything on the stack */
1660 ME_CommitUndo(editor);
1662 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1663 if (!(format & SFF_SELECTION))
1664 ME_EmptyUndoStack(editor);
1666 ME_ReleaseStyle(style);
1667 editor->nEventMask = nEventMask;
1668 ME_UpdateRepaint(editor, FALSE);
1669 if (!(format & SFF_SELECTION)) {
1670 ME_ClearTempStyle(editor);
1672 ITextHost_TxShowCaret(editor->texthost, FALSE);
1673 ME_MoveCaret(editor);
1674 ITextHost_TxShowCaret(editor->texthost, TRUE);
1675 ME_SendSelChange(editor);
1676 ME_SendRequestResize(editor, FALSE);
1678 return num_read;
1682 typedef struct tagME_RTFStringStreamStruct
1684 char *string;
1685 int pos;
1686 int length;
1687 } ME_RTFStringStreamStruct;
1689 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1691 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1692 int count;
1694 count = min(cb, pStruct->length - pStruct->pos);
1695 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1696 pStruct->pos += count;
1697 *pcb = count;
1698 return 0;
1701 static void
1702 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1704 EDITSTREAM es;
1705 ME_RTFStringStreamStruct data;
1707 data.string = string;
1708 data.length = strlen(string);
1709 data.pos = 0;
1710 es.dwCookie = (DWORD_PTR)&data;
1711 es.pfnCallback = ME_ReadFromRTFString;
1712 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1716 static int
1717 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1719 const int nLen = lstrlenW(text);
1720 const int nTextLen = ME_GetTextLength(editor);
1721 int nMin, nMax;
1722 ME_Cursor cursor;
1723 WCHAR wLastChar = ' ';
1725 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1726 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1728 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1729 FIXME("Flags 0x%08x not implemented\n",
1730 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1732 nMin = chrg->cpMin;
1733 if (chrg->cpMax == -1)
1734 nMax = nTextLen;
1735 else
1736 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1738 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1739 if (editor->bEmulateVersion10 && nMax == nTextLen)
1741 flags |= FR_DOWN;
1744 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1745 if (editor->bEmulateVersion10 && nMax < nMin)
1747 if (chrgText)
1749 chrgText->cpMin = -1;
1750 chrgText->cpMax = -1;
1752 return -1;
1755 /* when searching up, if cpMin < cpMax, then instead of searching
1756 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1757 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1758 * case, it is always bigger than cpMin.
1760 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1762 int nSwap = nMax;
1764 nMax = nMin > nTextLen ? nTextLen : nMin;
1765 if (nMin < nSwap || chrg->cpMax == -1)
1766 nMin = 0;
1767 else
1768 nMin = nSwap;
1771 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1773 if (chrgText)
1774 chrgText->cpMin = chrgText->cpMax = -1;
1775 return -1;
1778 if (flags & FR_DOWN) /* Forward search */
1780 /* If possible, find the character before where the search starts */
1781 if ((flags & FR_WHOLEWORD) && nMin)
1783 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1784 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1785 ME_MoveCursorChars(editor, &cursor, 1);
1786 } else {
1787 ME_CursorFromCharOfs(editor, nMin, &cursor);
1790 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1792 ME_DisplayItem *pCurItem = cursor.pRun;
1793 int nCurStart = cursor.nOffset;
1794 int nMatched = 0;
1796 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1798 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1799 break;
1801 nMatched++;
1802 if (nMatched == nLen)
1804 ME_DisplayItem *pNextItem = pCurItem;
1805 int nNextStart = nCurStart;
1806 WCHAR wNextChar;
1808 /* Check to see if next character is a whitespace */
1809 if (flags & FR_WHOLEWORD)
1811 if (nCurStart + nMatched == pCurItem->member.run.len)
1813 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1814 nNextStart = -nMatched;
1817 if (pNextItem)
1818 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1819 else
1820 wNextChar = ' ';
1822 if (isalnumW(wNextChar))
1823 break;
1826 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1827 if (chrgText)
1829 chrgText->cpMin = cursor.nOffset;
1830 chrgText->cpMax = cursor.nOffset + nLen;
1832 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1833 return cursor.nOffset;
1835 if (nCurStart + nMatched == pCurItem->member.run.len)
1837 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1838 nCurStart = -nMatched;
1841 if (pCurItem)
1842 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1843 else
1844 wLastChar = ' ';
1846 cursor.nOffset++;
1847 if (cursor.nOffset == cursor.pRun->member.run.len)
1849 ME_NextRun(&cursor.pPara, &cursor.pRun);
1850 cursor.nOffset = 0;
1854 else /* Backward search */
1856 /* If possible, find the character after where the search ends */
1857 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1859 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1860 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1861 ME_MoveCursorChars(editor, &cursor, -1);
1862 } else {
1863 ME_CursorFromCharOfs(editor, nMax, &cursor);
1866 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1868 ME_DisplayItem *pCurItem = cursor.pRun;
1869 ME_DisplayItem *pCurPara = cursor.pPara;
1870 int nCurEnd = cursor.nOffset;
1871 int nMatched = 0;
1873 if (nCurEnd == 0)
1875 ME_PrevRun(&pCurPara, &pCurItem);
1876 nCurEnd = pCurItem->member.run.len + nMatched;
1879 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1880 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1882 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1883 break;
1885 nMatched++;
1886 if (nMatched == nLen)
1888 ME_DisplayItem *pPrevItem = pCurItem;
1889 int nPrevEnd = nCurEnd;
1890 WCHAR wPrevChar;
1891 int nStart;
1893 /* Check to see if previous character is a whitespace */
1894 if (flags & FR_WHOLEWORD)
1896 if (nPrevEnd - nMatched == 0)
1898 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1899 if (pPrevItem)
1900 nPrevEnd = pPrevItem->member.run.len + nMatched;
1903 if (pPrevItem)
1904 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1905 else
1906 wPrevChar = ' ';
1908 if (isalnumW(wPrevChar))
1909 break;
1912 nStart = pCurPara->member.para.nCharOfs
1913 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1914 if (chrgText)
1916 chrgText->cpMin = nStart;
1917 chrgText->cpMax = nStart + nLen;
1919 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1920 return nStart;
1922 if (nCurEnd - nMatched == 0)
1924 ME_PrevRun(&pCurPara, &pCurItem);
1925 /* Don't care about pCurItem becoming NULL here; it's already taken
1926 * care of in the exterior loop condition */
1927 nCurEnd = pCurItem->member.run.len + nMatched;
1930 if (pCurItem)
1931 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1932 else
1933 wLastChar = ' ';
1935 cursor.nOffset--;
1936 if (cursor.nOffset < 0)
1938 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1939 cursor.nOffset = cursor.pRun->member.run.len;
1943 TRACE("not found\n");
1944 if (chrgText)
1945 chrgText->cpMin = chrgText->cpMax = -1;
1946 return -1;
1949 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1951 int nChars;
1952 ME_Cursor start;
1954 if (!ex->cb || !pText) return 0;
1956 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1957 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1959 if (ex->flags & GT_SELECTION)
1961 int from, to;
1962 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1963 start = editor->pCursors[nStartCur];
1964 nChars = to - from;
1966 else
1968 ME_SetCursorToStart(editor, &start);
1969 nChars = INT_MAX;
1971 if (ex->codepage == CP_UNICODE)
1973 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1974 &start, nChars, ex->flags & GT_USECRLF);
1976 else
1978 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1979 we can just take a bigger buffer? :)
1980 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1981 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1983 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1984 DWORD buflen;
1985 LPWSTR buffer;
1986 LRESULT rc;
1988 buflen = min(crlfmul * nChars, ex->cb - 1);
1989 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1991 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1992 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1993 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1994 if (rc) rc--; /* do not count 0 terminator */
1996 heap_free(buffer);
1997 return rc;
2001 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2002 const ME_Cursor *start, int nLen, BOOL unicode)
2004 if (!strText) return 0;
2005 if (unicode) {
2006 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE);
2007 } else {
2008 int nChars;
2009 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2010 if (!p) return 0;
2011 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE);
2012 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2013 nLen+1, NULL, NULL);
2014 FREE_OBJ(p);
2015 return nChars;
2019 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2021 int end;
2023 TRACE("%d - %d\n", to, from );
2025 ME_InvalidateSelection( editor );
2026 end = ME_SetSelection( editor, to, from );
2027 ME_InvalidateSelection( editor );
2028 ITextHost_TxShowCaret( editor->texthost, FALSE );
2029 ME_ShowCaret( editor );
2030 ME_SendSelChange( editor );
2032 return end;
2035 typedef struct tagME_GlobalDestStruct
2037 HGLOBAL hData;
2038 int nLength;
2039 } ME_GlobalDestStruct;
2041 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2043 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2044 int i;
2045 WORD *pSrc, *pDest;
2047 cb = cb >> 1;
2048 pDest = (WORD *)lpBuff;
2049 pSrc = GlobalLock(pData->hData);
2050 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2051 pDest[i] = pSrc[pData->nLength+i];
2053 pData->nLength += i;
2054 *pcb = 2*i;
2055 GlobalUnlock(pData->hData);
2056 return 0;
2059 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2061 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2062 int i;
2063 BYTE *pSrc, *pDest;
2065 pDest = lpBuff;
2066 pSrc = GlobalLock(pData->hData);
2067 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2068 pDest[i] = pSrc[pData->nLength+i];
2070 pData->nLength += i;
2071 *pcb = i;
2072 GlobalUnlock(pData->hData);
2073 return 0;
2076 static BOOL ME_Paste(ME_TextEditor *editor)
2078 DWORD dwFormat = 0;
2079 EDITSTREAM es;
2080 ME_GlobalDestStruct gds;
2081 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2082 UINT cf = 0;
2084 if (IsClipboardFormatAvailable(nRTFFormat))
2085 cf = nRTFFormat, dwFormat = SF_RTF;
2086 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2087 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2088 else
2089 return FALSE;
2091 if (!OpenClipboard(editor->hWnd))
2092 return FALSE;
2093 gds.hData = GetClipboardData(cf);
2094 gds.nLength = 0;
2095 es.dwCookie = (DWORD_PTR)&gds;
2096 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2097 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2099 CloseClipboard();
2100 return TRUE;
2103 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2105 LPDATAOBJECT dataObj = NULL;
2106 HRESULT hr = S_OK;
2108 if (editor->cPasswordMask)
2109 return FALSE; /* Copying or Cutting masked text isn't allowed */
2111 if(editor->lpOleCallback)
2113 CHARRANGE range;
2114 range.cpMin = ME_GetCursorOfs(start);
2115 range.cpMax = range.cpMin + nChars;
2116 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2118 if(FAILED(hr) || !dataObj)
2119 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2120 if(SUCCEEDED(hr)) {
2121 hr = OleSetClipboard(dataObj);
2122 IDataObject_Release(dataObj);
2124 return SUCCEEDED(hr) != 0;
2127 /* helper to send a msg filter notification */
2128 static BOOL
2129 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2131 MSGFILTER msgf;
2133 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2134 msgf.nmhdr.hwndFrom = editor->hWnd;
2135 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2136 msgf.nmhdr.code = EN_MSGFILTER;
2137 msgf.msg = msg;
2138 msgf.wParam = *wParam;
2139 msgf.lParam = *lParam;
2140 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2141 return FALSE;
2142 *wParam = msgf.wParam;
2143 *lParam = msgf.lParam;
2144 msgf.wParam = *wParam;
2146 return TRUE;
2149 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2151 ME_DisplayItem *startPara, *endPara;
2152 ME_DisplayItem *prev_para;
2153 ME_Cursor *from, *to;
2154 ME_Cursor start;
2155 int nChars;
2157 if (!editor->AutoURLDetect_bEnable) return;
2159 ME_GetSelection(editor, &from, &to);
2161 /* Find paragraph previous to the one that contains start cursor */
2162 startPara = from->pPara;
2163 prev_para = startPara->member.para.prev_para;
2164 if (prev_para->type == diParagraph) startPara = prev_para;
2166 /* Find paragraph that contains end cursor */
2167 endPara = to->pPara->member.para.next_para;
2169 start.pPara = startPara;
2170 start.pRun = ME_FindItemFwd(startPara, diRun);
2171 start.nOffset = 0;
2172 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2174 ME_UpdateLinkAttribute(editor, &start, nChars);
2177 static BOOL
2178 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2180 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2181 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2183 if (editor->bMouseCaptured)
2184 return FALSE;
2185 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2186 editor->nSelectionType = stPosition;
2188 switch (nKey)
2190 case VK_LEFT:
2191 case VK_RIGHT:
2192 case VK_HOME:
2193 case VK_END:
2194 editor->nUDArrowX = -1;
2195 /* fall through */
2196 case VK_UP:
2197 case VK_DOWN:
2198 case VK_PRIOR:
2199 case VK_NEXT:
2200 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2201 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2202 return TRUE;
2203 case VK_BACK:
2204 case VK_DELETE:
2205 editor->nUDArrowX = -1;
2206 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2207 if (editor->styleFlags & ES_READONLY)
2208 return FALSE;
2209 if (ME_IsSelection(editor))
2211 ME_DeleteSelection(editor);
2212 ME_CommitUndo(editor);
2214 else if (nKey == VK_DELETE)
2216 /* Delete stops group typing.
2217 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2218 ME_DeleteTextAtCursor(editor, 1, 1);
2219 ME_CommitUndo(editor);
2221 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2223 BOOL bDeletionSucceeded;
2224 /* Backspace can be grouped for a single undo */
2225 ME_ContinueCoalescingTransaction(editor);
2226 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2227 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2228 /* Deletion was prevented so the cursor is moved back to where it was.
2229 * (e.g. this happens when trying to delete cell boundaries)
2231 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2233 ME_CommitCoalescingUndo(editor);
2235 else
2236 return TRUE;
2237 ME_MoveCursorFromTableRowStartParagraph(editor);
2238 ME_UpdateSelectionLinkAttribute(editor);
2239 ME_UpdateRepaint(editor, FALSE);
2240 ME_SendRequestResize(editor, FALSE);
2241 return TRUE;
2242 case VK_RETURN:
2243 if (editor->bDialogMode)
2245 if (ctrl_is_down)
2246 return TRUE;
2248 if (!(editor->styleFlags & ES_WANTRETURN))
2250 if (editor->hwndParent)
2252 DWORD dw;
2253 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2254 if (HIWORD(dw) == DC_HASDEFID)
2256 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2257 if (hwDefCtrl)
2259 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2260 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2264 return TRUE;
2268 if (editor->styleFlags & ES_MULTILINE)
2270 ME_Cursor cursor = editor->pCursors[0];
2271 ME_DisplayItem *para = cursor.pPara;
2272 int from, to;
2273 const WCHAR endl = '\r';
2274 const WCHAR endlv10[] = {'\r','\n'};
2275 ME_Style *style;
2277 if (editor->styleFlags & ES_READONLY) {
2278 MessageBeep(MB_ICONERROR);
2279 return TRUE;
2282 ME_GetSelectionOfs(editor, &from, &to);
2283 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2285 if (!editor->bEmulateVersion10) { /* v4.1 */
2286 if (para->member.para.nFlags & MEPF_ROWEND) {
2287 /* Add a new table row after this row. */
2288 para = ME_AppendTableRow(editor, para);
2289 para = para->member.para.next_para;
2290 editor->pCursors[0].pPara = para;
2291 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2292 editor->pCursors[0].nOffset = 0;
2293 editor->pCursors[1] = editor->pCursors[0];
2294 ME_CommitUndo(editor);
2295 ME_CheckTablesForCorruption(editor);
2296 ME_UpdateRepaint(editor, FALSE);
2297 return TRUE;
2299 else if (para == editor->pCursors[1].pPara &&
2300 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2301 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2302 !para->member.para.prev_para->member.para.nCharOfs)
2304 /* Insert a newline before the table. */
2305 para = para->member.para.prev_para;
2306 para->member.para.nFlags &= ~MEPF_ROWSTART;
2307 editor->pCursors[0].pPara = para;
2308 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2309 editor->pCursors[1] = editor->pCursors[0];
2310 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2311 editor->pCursors[0].pRun->member.run.style);
2312 para = editor->pBuffer->pFirst->member.para.next_para;
2313 ME_SetDefaultParaFormat(para->member.para.pFmt);
2314 para->member.para.nFlags = MEPF_REWRAP;
2315 editor->pCursors[0].pPara = para;
2316 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2317 editor->pCursors[1] = editor->pCursors[0];
2318 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2319 ME_CommitCoalescingUndo(editor);
2320 ME_CheckTablesForCorruption(editor);
2321 ME_UpdateRepaint(editor, FALSE);
2322 return TRUE;
2324 } else { /* v1.0 - 3.0 */
2325 ME_DisplayItem *para = cursor.pPara;
2326 if (ME_IsInTable(para))
2328 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2330 if (from == to) {
2331 ME_ContinueCoalescingTransaction(editor);
2332 para = ME_AppendTableRow(editor, para);
2333 editor->pCursors[0].pPara = para;
2334 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2335 editor->pCursors[0].nOffset = 0;
2336 editor->pCursors[1] = editor->pCursors[0];
2337 ME_CommitCoalescingUndo(editor);
2338 ME_UpdateRepaint(editor, FALSE);
2339 return TRUE;
2341 } else {
2342 ME_ContinueCoalescingTransaction(editor);
2343 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2344 !ME_IsInTable(para->member.para.prev_para))
2346 /* Insert newline before table */
2347 cursor.pRun = ME_FindItemBack(para, diRun);
2348 if (cursor.pRun) {
2349 editor->pCursors[0].pRun = cursor.pRun;
2350 editor->pCursors[0].pPara = para->member.para.prev_para;
2352 editor->pCursors[0].nOffset = 0;
2353 editor->pCursors[1] = editor->pCursors[0];
2354 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2355 editor->pCursors[0].pRun->member.run.style);
2356 } else {
2357 editor->pCursors[1] = editor->pCursors[0];
2358 para = ME_AppendTableRow(editor, para);
2359 editor->pCursors[0].pPara = para;
2360 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2361 editor->pCursors[0].nOffset = 0;
2362 editor->pCursors[1] = editor->pCursors[0];
2364 ME_CommitCoalescingUndo(editor);
2365 ME_UpdateRepaint(editor, FALSE);
2366 return TRUE;
2371 style = ME_GetInsertStyle(editor, 0);
2372 ME_SaveTempStyle(editor);
2373 ME_ContinueCoalescingTransaction(editor);
2374 if (shift_is_down)
2375 ME_InsertEndRowFromCursor(editor, 0);
2376 else
2377 if (!editor->bEmulateVersion10)
2378 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2379 else
2380 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2381 ME_ReleaseStyle(style);
2382 ME_CommitCoalescingUndo(editor);
2383 SetCursor(NULL);
2385 ME_UpdateSelectionLinkAttribute(editor);
2386 ME_UpdateRepaint(editor, FALSE);
2388 return TRUE;
2390 break;
2391 case VK_ESCAPE:
2392 if (editor->bDialogMode && editor->hwndParent)
2393 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2394 return TRUE;
2395 case VK_TAB:
2396 if (editor->bDialogMode && editor->hwndParent)
2397 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2398 return TRUE;
2399 case 'A':
2400 if (ctrl_is_down)
2402 handle_EM_EXSETSEL( editor, 0, -1 );
2403 return TRUE;
2405 break;
2406 case 'V':
2407 if (ctrl_is_down)
2408 return ME_Paste(editor);
2409 break;
2410 case 'C':
2411 case 'X':
2412 if (ctrl_is_down)
2414 BOOL result;
2415 int nOfs, nChars;
2416 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2417 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2419 nChars -= nOfs;
2420 result = ME_Copy(editor, selStart, nChars);
2421 if (result && nKey == 'X')
2423 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2424 ME_CommitUndo(editor);
2425 ME_UpdateRepaint(editor, TRUE);
2427 return result;
2429 break;
2430 case 'Z':
2431 if (ctrl_is_down)
2433 ME_Undo(editor);
2434 return TRUE;
2436 break;
2437 case 'Y':
2438 if (ctrl_is_down)
2440 ME_Redo(editor);
2441 return TRUE;
2443 break;
2445 default:
2446 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2447 editor->nUDArrowX = -1;
2448 if (ctrl_is_down)
2450 if (nKey == 'W')
2452 CHARFORMAT2W chf;
2453 char buf[2048];
2454 chf.cbSize = sizeof(chf);
2456 ME_GetSelectionCharFormat(editor, &chf);
2457 ME_DumpStyleToBuf(&chf, buf);
2458 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2460 if (nKey == 'Q')
2462 ME_CheckCharOffsets(editor);
2466 return FALSE;
2469 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2470 LPARAM flags, BOOL unicode)
2472 WCHAR wstr;
2474 if (editor->bMouseCaptured)
2475 return 0;
2477 if (unicode)
2478 wstr = (WCHAR)charCode;
2479 else
2481 CHAR charA = charCode;
2482 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2485 if (editor->styleFlags & ES_READONLY) {
2486 MessageBeep(MB_ICONERROR);
2487 return 0; /* FIXME really 0 ? */
2490 if ((unsigned)wstr >= ' ' || wstr == '\t')
2492 ME_Cursor cursor = editor->pCursors[0];
2493 ME_DisplayItem *para = cursor.pPara;
2494 int from, to;
2495 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2496 ME_GetSelectionOfs(editor, &from, &to);
2497 if (wstr == '\t' &&
2498 /* v4.1 allows tabs to be inserted with ctrl key down */
2499 !(ctrl_is_down && !editor->bEmulateVersion10))
2501 ME_DisplayItem *para;
2502 BOOL bSelectedRow = FALSE;
2504 para = cursor.pPara;
2505 if (ME_IsSelection(editor) &&
2506 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2507 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2508 para->member.para.prev_para->type == diParagraph)
2510 para = para->member.para.prev_para;
2511 bSelectedRow = TRUE;
2513 if (ME_IsInTable(para))
2515 ME_TabPressedInTable(editor, bSelectedRow);
2516 ME_CommitUndo(editor);
2517 return 0;
2519 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2520 if (para->member.para.nFlags & MEPF_ROWEND) {
2521 if (from == to) {
2522 para = para->member.para.next_para;
2523 if (para->member.para.nFlags & MEPF_ROWSTART)
2524 para = para->member.para.next_para;
2525 editor->pCursors[0].pPara = para;
2526 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2527 editor->pCursors[0].nOffset = 0;
2528 editor->pCursors[1] = editor->pCursors[0];
2531 } else { /* v1.0 - 3.0 */
2532 if (ME_IsInTable(cursor.pRun) &&
2533 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2534 from == to)
2536 /* Text should not be inserted at the end of the table. */
2537 MessageBeep(-1);
2538 return 0;
2541 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2542 /* WM_CHAR is restricted to nTextLimit */
2543 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2545 ME_Style *style = ME_GetInsertStyle(editor, 0);
2546 ME_SaveTempStyle(editor);
2547 ME_ContinueCoalescingTransaction(editor);
2548 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2549 ME_ReleaseStyle(style);
2550 ME_CommitCoalescingUndo(editor);
2551 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2554 ME_UpdateSelectionLinkAttribute(editor);
2555 ME_UpdateRepaint(editor, FALSE);
2557 return 0;
2560 /* Process the message and calculate the new click count.
2562 * returns: The click count if it is mouse down event, else returns 0. */
2563 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2564 LPARAM lParam)
2566 static int clickNum = 0;
2567 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2568 return 0;
2570 if ((msg == WM_LBUTTONDBLCLK) ||
2571 (msg == WM_RBUTTONDBLCLK) ||
2572 (msg == WM_MBUTTONDBLCLK) ||
2573 (msg == WM_XBUTTONDBLCLK))
2575 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2578 if ((msg == WM_LBUTTONDOWN) ||
2579 (msg == WM_RBUTTONDOWN) ||
2580 (msg == WM_MBUTTONDOWN) ||
2581 (msg == WM_XBUTTONDOWN))
2583 static MSG prevClickMsg;
2584 MSG clickMsg;
2585 /* Compare the editor instead of the hwnd so that the this
2586 * can still be done for windowless richedit controls. */
2587 clickMsg.hwnd = (HWND)editor;
2588 clickMsg.message = msg;
2589 clickMsg.wParam = wParam;
2590 clickMsg.lParam = lParam;
2591 clickMsg.time = GetMessageTime();
2592 clickMsg.pt.x = (short)LOWORD(lParam);
2593 clickMsg.pt.y = (short)HIWORD(lParam);
2594 if ((clickNum != 0) &&
2595 (clickMsg.message == prevClickMsg.message) &&
2596 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2597 (clickMsg.wParam == prevClickMsg.wParam) &&
2598 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2599 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2600 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2602 clickNum++;
2603 } else {
2604 clickNum = 1;
2606 prevClickMsg = clickMsg;
2607 } else {
2608 return 0;
2610 return clickNum;
2613 static BOOL ME_SetCursor(ME_TextEditor *editor)
2615 ME_Cursor cursor;
2616 POINT pt;
2617 BOOL isExact;
2618 SCROLLBARINFO sbi;
2619 DWORD messagePos = GetMessagePos();
2620 pt.x = (short)LOWORD(messagePos);
2621 pt.y = (short)HIWORD(messagePos);
2623 if (editor->hWnd)
2625 sbi.cbSize = sizeof(sbi);
2626 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2627 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2628 PtInRect(&sbi.rcScrollBar, pt))
2630 ITextHost_TxSetCursor(editor->texthost,
2631 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2632 return TRUE;
2634 sbi.cbSize = sizeof(sbi);
2635 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2636 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2637 PtInRect(&sbi.rcScrollBar, pt))
2639 ITextHost_TxSetCursor(editor->texthost,
2640 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2641 return TRUE;
2644 ITextHost_TxScreenToClient(editor->texthost, &pt);
2646 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2647 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2648 return TRUE;
2650 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2651 pt.y < editor->rcFormat.top &&
2652 pt.x < editor->rcFormat.left)
2654 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2655 return TRUE;
2657 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2659 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2660 ITextHost_TxSetCursor(editor->texthost,
2661 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2662 else /* v4.1 */
2663 ITextHost_TxSetCursor(editor->texthost,
2664 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2665 return TRUE;
2667 if (pt.x < editor->rcFormat.left)
2669 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2670 return TRUE;
2672 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2673 if (isExact)
2675 ME_Run *run;
2677 run = &cursor.pRun->member.run;
2678 if (run->style->fmt.dwMask & CFM_LINK &&
2679 run->style->fmt.dwEffects & CFE_LINK)
2681 ITextHost_TxSetCursor(editor->texthost,
2682 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2683 FALSE);
2684 return TRUE;
2687 if (ME_IsSelection(editor))
2689 int selStart, selEnd;
2690 int offset = ME_GetCursorOfs(&cursor);
2692 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2693 if (selStart <= offset && selEnd >= offset) {
2694 ITextHost_TxSetCursor(editor->texthost,
2695 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2696 FALSE);
2697 return TRUE;
2701 ITextHost_TxSetCursor(editor->texthost,
2702 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2703 return TRUE;
2706 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2708 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2709 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2710 editor->rcFormat.left += 1 + editor->selofs;
2711 editor->rcFormat.right -= 1;
2714 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2716 CHARRANGE selrange;
2717 HMENU menu;
2718 int seltype = 0;
2719 if(!editor->lpOleCallback || !editor->hWnd)
2720 return FALSE;
2721 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2722 if(selrange.cpMin == selrange.cpMax)
2723 seltype |= SEL_EMPTY;
2724 else
2726 /* FIXME: Handle objects */
2727 seltype |= SEL_TEXT;
2728 if(selrange.cpMax-selrange.cpMin > 1)
2729 seltype |= SEL_MULTICHAR;
2731 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2733 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2734 DestroyMenu(menu);
2736 return TRUE;
2739 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2741 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2742 int i;
2743 DWORD props;
2744 LONG selbarwidth;
2746 ed->hWnd = NULL;
2747 ed->hwndParent = NULL;
2748 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2749 ed->texthost = texthost;
2750 ed->bEmulateVersion10 = bEmulateVersion10;
2751 ed->styleFlags = 0;
2752 ITextHost_TxGetPropertyBits(texthost,
2753 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2754 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2755 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2756 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2757 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2758 &props);
2759 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2760 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2761 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2762 ed->pBuffer = ME_MakeText();
2763 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2764 ed->nAvailWidth = 0; /* wrap to client area */
2765 ME_MakeFirstParagraph(ed);
2766 /* The four cursors are for:
2767 * 0 - The position where the caret is shown
2768 * 1 - The anchored end of the selection (for normal selection)
2769 * 2 & 3 - The anchored start and end respectively for word, line,
2770 * or paragraph selection.
2772 ed->nCursors = 4;
2773 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2774 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2775 ed->pCursors[1] = ed->pCursors[0];
2776 ed->pCursors[2] = ed->pCursors[0];
2777 ed->pCursors[3] = ed->pCursors[1];
2778 ed->nLastTotalLength = ed->nTotalLength = 0;
2779 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2780 ed->nUDArrowX = -1;
2781 ed->rgbBackColor = -1;
2782 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2783 ed->bCaretAtEnd = FALSE;
2784 ed->nEventMask = 0;
2785 ed->nModifyStep = 0;
2786 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2787 list_init( &ed->undo_stack );
2788 list_init( &ed->redo_stack );
2789 ed->nUndoStackSize = 0;
2790 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2791 ed->nUndoMode = umAddToUndo;
2792 ed->nParagraphs = 1;
2793 ed->nLastSelStart = ed->nLastSelEnd = 0;
2794 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2795 ed->bHideSelection = FALSE;
2796 ed->pfnWordBreak = NULL;
2797 ed->lpOleCallback = NULL;
2798 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2799 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2800 ed->AutoURLDetect_bEnable = FALSE;
2801 ed->bHaveFocus = FALSE;
2802 ed->bDialogMode = FALSE;
2803 ed->bMouseCaptured = FALSE;
2804 for (i=0; i<HFONT_CACHE_SIZE; i++)
2806 ed->pFontCache[i].nRefs = 0;
2807 ed->pFontCache[i].nAge = 0;
2808 ed->pFontCache[i].hFont = NULL;
2811 ME_CheckCharOffsets(ed);
2812 ed->bDefaultFormatRect = TRUE;
2813 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2814 if (selbarwidth) {
2815 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2816 ed->selofs = SELECTIONBAR_WIDTH;
2817 ed->styleFlags |= ES_SELECTIONBAR;
2818 } else {
2819 ed->selofs = 0;
2821 ed->nSelectionType = stPosition;
2823 ed->cPasswordMask = 0;
2824 if (props & TXTBIT_USEPASSWORD)
2825 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2827 if (props & TXTBIT_AUTOWORDSEL)
2828 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2829 if (props & TXTBIT_MULTILINE) {
2830 ed->styleFlags |= ES_MULTILINE;
2831 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2832 } else {
2833 ed->bWordWrap = FALSE;
2835 if (props & TXTBIT_READONLY)
2836 ed->styleFlags |= ES_READONLY;
2837 if (!(props & TXTBIT_HIDESELECTION))
2838 ed->styleFlags |= ES_NOHIDESEL;
2839 if (props & TXTBIT_SAVESELECTION)
2840 ed->styleFlags |= ES_SAVESEL;
2841 if (props & TXTBIT_VERTICAL)
2842 ed->styleFlags |= ES_VERTICAL;
2843 if (props & TXTBIT_DISABLEDRAG)
2844 ed->styleFlags |= ES_NOOLEDRAGDROP;
2846 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2848 /* Default scrollbar information */
2849 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2850 ed->vert_si.nMin = 0;
2851 ed->vert_si.nMax = 0;
2852 ed->vert_si.nPage = 0;
2853 ed->vert_si.nPos = 0;
2855 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2856 ed->horz_si.nMin = 0;
2857 ed->horz_si.nMax = 0;
2858 ed->horz_si.nPage = 0;
2859 ed->horz_si.nPos = 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 OleUninitialize();
2892 FREE_OBJ(editor->pBuffer);
2893 FREE_OBJ(editor->pCursors);
2895 FREE_OBJ(editor);
2898 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2900 TRACE("\n");
2901 switch (fdwReason)
2903 case DLL_PROCESS_ATTACH:
2904 DisableThreadLibraryCalls(hinstDLL);
2905 me_heap = HeapCreate (0, 0x10000, 0);
2906 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2907 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2908 LookupInit();
2909 break;
2911 case DLL_PROCESS_DETACH:
2912 if (lpvReserved) break;
2913 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2914 UnregisterClassW(MSFTEDIT_CLASS, 0);
2915 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2916 UnregisterClassA("RichEdit50A", 0);
2917 if (ME_ListBoxRegistered)
2918 UnregisterClassW(REListBox20W, 0);
2919 if (ME_ComboBoxRegistered)
2920 UnregisterClassW(REComboBox20W, 0);
2921 LookupCleanup();
2922 HeapDestroy (me_heap);
2923 break;
2925 return TRUE;
2929 static const char * const edit_messages[] = {
2930 "EM_GETSEL",
2931 "EM_SETSEL",
2932 "EM_GETRECT",
2933 "EM_SETRECT",
2934 "EM_SETRECTNP",
2935 "EM_SCROLL",
2936 "EM_LINESCROLL",
2937 "EM_SCROLLCARET",
2938 "EM_GETMODIFY",
2939 "EM_SETMODIFY",
2940 "EM_GETLINECOUNT",
2941 "EM_LINEINDEX",
2942 "EM_SETHANDLE",
2943 "EM_GETHANDLE",
2944 "EM_GETTHUMB",
2945 "EM_UNKNOWN_BF",
2946 "EM_UNKNOWN_C0",
2947 "EM_LINELENGTH",
2948 "EM_REPLACESEL",
2949 "EM_UNKNOWN_C3",
2950 "EM_GETLINE",
2951 "EM_LIMITTEXT",
2952 "EM_CANUNDO",
2953 "EM_UNDO",
2954 "EM_FMTLINES",
2955 "EM_LINEFROMCHAR",
2956 "EM_UNKNOWN_CA",
2957 "EM_SETTABSTOPS",
2958 "EM_SETPASSWORDCHAR",
2959 "EM_EMPTYUNDOBUFFER",
2960 "EM_GETFIRSTVISIBLELINE",
2961 "EM_SETREADONLY",
2962 "EM_SETWORDBREAKPROC",
2963 "EM_GETWORDBREAKPROC",
2964 "EM_GETPASSWORDCHAR",
2965 "EM_SETMARGINS",
2966 "EM_GETMARGINS",
2967 "EM_GETLIMITTEXT",
2968 "EM_POSFROMCHAR",
2969 "EM_CHARFROMPOS",
2970 "EM_SETIMESTATUS",
2971 "EM_GETIMESTATUS"
2974 static const char * const richedit_messages[] = {
2975 "EM_CANPASTE",
2976 "EM_DISPLAYBAND",
2977 "EM_EXGETSEL",
2978 "EM_EXLIMITTEXT",
2979 "EM_EXLINEFROMCHAR",
2980 "EM_EXSETSEL",
2981 "EM_FINDTEXT",
2982 "EM_FORMATRANGE",
2983 "EM_GETCHARFORMAT",
2984 "EM_GETEVENTMASK",
2985 "EM_GETOLEINTERFACE",
2986 "EM_GETPARAFORMAT",
2987 "EM_GETSELTEXT",
2988 "EM_HIDESELECTION",
2989 "EM_PASTESPECIAL",
2990 "EM_REQUESTRESIZE",
2991 "EM_SELECTIONTYPE",
2992 "EM_SETBKGNDCOLOR",
2993 "EM_SETCHARFORMAT",
2994 "EM_SETEVENTMASK",
2995 "EM_SETOLECALLBACK",
2996 "EM_SETPARAFORMAT",
2997 "EM_SETTARGETDEVICE",
2998 "EM_STREAMIN",
2999 "EM_STREAMOUT",
3000 "EM_GETTEXTRANGE",
3001 "EM_FINDWORDBREAK",
3002 "EM_SETOPTIONS",
3003 "EM_GETOPTIONS",
3004 "EM_FINDTEXTEX",
3005 "EM_GETWORDBREAKPROCEX",
3006 "EM_SETWORDBREAKPROCEX",
3007 "EM_SETUNDOLIMIT",
3008 "EM_UNKNOWN_USER_83",
3009 "EM_REDO",
3010 "EM_CANREDO",
3011 "EM_GETUNDONAME",
3012 "EM_GETREDONAME",
3013 "EM_STOPGROUPTYPING",
3014 "EM_SETTEXTMODE",
3015 "EM_GETTEXTMODE",
3016 "EM_AUTOURLDETECT",
3017 "EM_GETAUTOURLDETECT",
3018 "EM_SETPALETTE",
3019 "EM_GETTEXTEX",
3020 "EM_GETTEXTLENGTHEX",
3021 "EM_SHOWSCROLLBAR",
3022 "EM_SETTEXTEX",
3023 "EM_UNKNOWN_USER_98",
3024 "EM_UNKNOWN_USER_99",
3025 "EM_SETPUNCTUATION",
3026 "EM_GETPUNCTUATION",
3027 "EM_SETWORDWRAPMODE",
3028 "EM_GETWORDWRAPMODE",
3029 "EM_SETIMECOLOR",
3030 "EM_GETIMECOLOR",
3031 "EM_SETIMEOPTIONS",
3032 "EM_GETIMEOPTIONS",
3033 "EM_CONVPOSITION",
3034 "EM_UNKNOWN_USER_109",
3035 "EM_UNKNOWN_USER_110",
3036 "EM_UNKNOWN_USER_111",
3037 "EM_UNKNOWN_USER_112",
3038 "EM_UNKNOWN_USER_113",
3039 "EM_UNKNOWN_USER_114",
3040 "EM_UNKNOWN_USER_115",
3041 "EM_UNKNOWN_USER_116",
3042 "EM_UNKNOWN_USER_117",
3043 "EM_UNKNOWN_USER_118",
3044 "EM_UNKNOWN_USER_119",
3045 "EM_SETLANGOPTIONS",
3046 "EM_GETLANGOPTIONS",
3047 "EM_GETIMECOMPMODE",
3048 "EM_FINDTEXTW",
3049 "EM_FINDTEXTEXW",
3050 "EM_RECONVERSION",
3051 "EM_SETIMEMODEBIAS",
3052 "EM_GETIMEMODEBIAS"
3055 static const char *
3056 get_msg_name(UINT msg)
3058 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3059 return edit_messages[msg - EM_GETSEL];
3060 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3061 return richedit_messages[msg - EM_CANPASTE];
3062 return "";
3065 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3067 int x,y;
3068 BOOL isExact;
3069 ME_Cursor cursor; /* The start of the clicked text. */
3071 ENLINK info;
3072 x = (short)LOWORD(lParam);
3073 y = (short)HIWORD(lParam);
3074 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3075 if (!isExact) return;
3077 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3078 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3079 { /* The clicked run has CFE_LINK set */
3080 info.nmhdr.hwndFrom = NULL;
3081 info.nmhdr.idFrom = 0;
3082 info.nmhdr.code = EN_LINK;
3083 info.msg = msg;
3084 info.wParam = wParam;
3085 info.lParam = lParam;
3086 cursor.nOffset = 0;
3087 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3088 info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.len;
3089 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3093 #define UNSUPPORTED_MSG(e) \
3094 case e: \
3095 FIXME(#e ": stub\n"); \
3096 *phresult = S_FALSE; \
3097 return 0;
3099 /* Handle messages for windowless and windoweded richedit controls.
3101 * The LRESULT that is returned is a return value for window procs,
3102 * and the phresult parameter is the COM return code needed by the
3103 * text services interface. */
3104 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3105 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3107 *phresult = S_OK;
3109 switch(msg) {
3111 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3112 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3113 UNSUPPORTED_MSG(EM_FMTLINES)
3114 UNSUPPORTED_MSG(EM_FORMATRANGE)
3115 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3116 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3117 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3118 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3119 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3120 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3121 UNSUPPORTED_MSG(EM_GETREDONAME)
3122 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3123 UNSUPPORTED_MSG(EM_GETUNDONAME)
3124 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3125 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3126 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3127 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3128 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3129 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3130 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3131 UNSUPPORTED_MSG(EM_SETMARGINS)
3132 UNSUPPORTED_MSG(EM_SETPALETTE)
3133 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3134 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3135 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3137 /* Messages specific to Richedit controls */
3139 case EM_STREAMIN:
3140 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3141 case EM_STREAMOUT:
3142 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3143 case WM_GETDLGCODE:
3145 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3147 if (lParam)
3148 editor->bDialogMode = TRUE;
3149 if (editor->styleFlags & ES_MULTILINE)
3150 code |= DLGC_WANTMESSAGE;
3151 if (!(editor->styleFlags & ES_SAVESEL))
3152 code |= DLGC_HASSETSEL;
3153 return code;
3155 case EM_EMPTYUNDOBUFFER:
3156 ME_EmptyUndoStack(editor);
3157 return 0;
3158 case EM_GETSEL:
3160 /* Note: wParam/lParam can be NULL */
3161 UINT from, to;
3162 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3163 PUINT pto = lParam ? (PUINT)lParam : &to;
3164 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3165 if ((*pfrom|*pto) & 0xFFFF0000)
3166 return -1;
3167 return MAKELONG(*pfrom,*pto);
3169 case EM_EXGETSEL:
3171 CHARRANGE *pRange = (CHARRANGE *)lParam;
3172 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3173 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3174 return 0;
3176 case EM_SETUNDOLIMIT:
3178 if ((int)wParam < 0)
3179 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3180 else
3181 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3182 /* Setting a max stack size keeps wine from getting killed
3183 for hogging memory. Windows allocates all this memory at once, so
3184 no program would realistically set a value above our maximum. */
3185 return editor->nUndoLimit;
3187 case EM_CANUNDO:
3188 return !list_empty( &editor->undo_stack );
3189 case EM_CANREDO:
3190 return !list_empty( &editor->redo_stack );
3191 case WM_UNDO: /* FIXME: actually not the same */
3192 case EM_UNDO:
3193 return ME_Undo(editor);
3194 case EM_REDO:
3195 return ME_Redo(editor);
3196 case EM_GETOPTIONS:
3198 /* these flags are equivalent to the ES_* counterparts */
3199 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3200 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3201 DWORD settings = editor->styleFlags & mask;
3203 return settings;
3205 case EM_SETOPTIONS:
3207 /* these flags are equivalent to ES_* counterparts, except for
3208 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3209 * but is still stored in editor->styleFlags. */
3210 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3211 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3212 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3213 DWORD settings = mask & editor->styleFlags;
3214 DWORD oldSettings = settings;
3215 DWORD changedSettings;
3217 switch(wParam)
3219 case ECOOP_SET:
3220 settings = lParam;
3221 break;
3222 case ECOOP_OR:
3223 settings |= lParam;
3224 break;
3225 case ECOOP_AND:
3226 settings &= lParam;
3227 break;
3228 case ECOOP_XOR:
3229 settings ^= lParam;
3231 changedSettings = oldSettings ^ settings;
3233 if (changedSettings) {
3234 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3236 if (changedSettings & ECO_SELECTIONBAR)
3238 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3239 if (settings & ECO_SELECTIONBAR) {
3240 assert(!editor->selofs);
3241 editor->selofs = SELECTIONBAR_WIDTH;
3242 editor->rcFormat.left += editor->selofs;
3243 } else {
3244 editor->rcFormat.left -= editor->selofs;
3245 editor->selofs = 0;
3247 ME_RewrapRepaint(editor);
3250 if (changedSettings & settings & ECO_VERTICAL)
3251 FIXME("ECO_VERTICAL not implemented yet!\n");
3252 if (changedSettings & settings & ECO_AUTOHSCROLL)
3253 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3254 if (changedSettings & settings & ECO_AUTOVSCROLL)
3255 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3256 if (changedSettings & settings & ECO_NOHIDESEL)
3257 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3258 if (changedSettings & settings & ECO_WANTRETURN)
3259 FIXME("ECO_WANTRETURN not implemented yet!\n");
3260 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3261 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3264 return settings;
3266 case EM_SETSEL:
3268 handle_EM_EXSETSEL( editor, wParam, lParam );
3269 return 0;
3271 case EM_SETSCROLLPOS:
3273 POINT *point = (POINT *)lParam;
3274 ME_ScrollAbs(editor, point->x, point->y);
3275 return 0;
3277 case EM_AUTOURLDETECT:
3279 if (wParam==1 || wParam ==0)
3281 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3282 return 0;
3284 return E_INVALIDARG;
3286 case EM_GETAUTOURLDETECT:
3288 return editor->AutoURLDetect_bEnable;
3290 case EM_EXSETSEL:
3292 CHARRANGE range = *(CHARRANGE *)lParam;
3294 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3296 case EM_SHOWSCROLLBAR:
3298 DWORD flags;
3300 switch (wParam)
3302 case SB_HORZ:
3303 flags = WS_HSCROLL;
3304 break;
3305 case SB_VERT:
3306 flags = WS_VSCROLL;
3307 break;
3308 case SB_BOTH:
3309 flags = WS_HSCROLL|WS_VSCROLL;
3310 break;
3311 default:
3312 return 0;
3315 if (lParam) {
3316 editor->styleFlags |= flags;
3317 if (flags & WS_HSCROLL)
3318 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3319 editor->nTotalWidth > editor->sizeWindow.cx);
3320 if (flags & WS_VSCROLL)
3321 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3322 editor->nTotalLength > editor->sizeWindow.cy);
3323 } else {
3324 editor->styleFlags &= ~flags;
3325 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3327 return 0;
3329 case EM_SETTEXTEX:
3331 LPWSTR wszText;
3332 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3333 int from, to, len;
3334 ME_Style *style;
3335 BOOL bRtf, bUnicode, bSelection, bUTF8;
3336 int oldModify = editor->nModifyStep;
3337 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3339 if (!pStruct) return 0;
3341 /* If we detect ascii rtf at the start of the string,
3342 * we know it isn't unicode. */
3343 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3344 !strncmp((char *)lParam, "{\\urtf", 6)));
3345 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3346 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3348 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3349 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3350 pStruct->flags, pStruct->codepage);
3352 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3353 if (bSelection) {
3354 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3355 style = ME_GetSelectionInsertStyle(editor);
3356 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3357 } else {
3358 ME_Cursor start;
3359 ME_SetCursorToStart(editor, &start);
3360 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3361 style = editor->pBuffer->pDefaultStyle;
3364 if (bRtf) {
3365 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3366 if (bSelection) {
3367 /* FIXME: The length returned doesn't include the rtf control
3368 * characters, only the actual text. */
3369 len = lParam ? strlen((char *)lParam) : 0;
3371 } else {
3372 if (bUTF8 && !bUnicode) {
3373 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3374 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3375 ME_EndToUnicode(CP_UTF8, wszText);
3376 } else {
3377 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3378 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3379 ME_EndToUnicode(pStruct->codepage, wszText);
3383 if (bSelection) {
3384 ME_ReleaseStyle(style);
3385 ME_UpdateSelectionLinkAttribute(editor);
3386 } else {
3387 ME_Cursor cursor;
3388 len = 1;
3389 ME_SetCursorToStart(editor, &cursor);
3390 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3392 ME_CommitUndo(editor);
3393 if (!(pStruct->flags & ST_KEEPUNDO))
3395 editor->nModifyStep = oldModify;
3396 ME_EmptyUndoStack(editor);
3398 ME_UpdateRepaint(editor, FALSE);
3399 return len;
3401 case EM_SETBKGNDCOLOR:
3403 LRESULT lColor;
3404 if (editor->rgbBackColor != -1) {
3405 DeleteObject(editor->hbrBackground);
3406 lColor = editor->rgbBackColor;
3408 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3410 if (wParam)
3412 editor->rgbBackColor = -1;
3413 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3415 else
3417 editor->rgbBackColor = lParam;
3418 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3420 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3421 ITextHost_TxViewChange(editor->texthost, TRUE);
3422 return lColor;
3424 case EM_GETMODIFY:
3425 return editor->nModifyStep == 0 ? 0 : -1;
3426 case EM_SETMODIFY:
3428 if (wParam)
3429 editor->nModifyStep = 1;
3430 else
3431 editor->nModifyStep = 0;
3433 return 0;
3435 case EM_SETREADONLY:
3437 if (wParam)
3438 editor->styleFlags |= ES_READONLY;
3439 else
3440 editor->styleFlags &= ~ES_READONLY;
3441 return 0;
3443 case EM_SETEVENTMASK:
3445 DWORD nOldMask = editor->nEventMask;
3447 editor->nEventMask = lParam;
3448 return nOldMask;
3450 case EM_GETEVENTMASK:
3451 return editor->nEventMask;
3452 case EM_SETCHARFORMAT:
3454 CHARFORMAT2W buf, *p;
3455 BOOL bRepaint = TRUE;
3456 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3457 if (p == NULL) return 0;
3458 if (wParam & SCF_ALL) {
3459 if (editor->mode & TM_PLAINTEXT) {
3460 ME_SetDefaultCharFormat(editor, p);
3461 } else {
3462 ME_Cursor start;
3463 ME_SetCursorToStart(editor, &start);
3464 ME_SetCharFormat(editor, &start, NULL, p);
3465 editor->nModifyStep = 1;
3467 } else if (wParam & SCF_SELECTION) {
3468 if (editor->mode & TM_PLAINTEXT)
3469 return 0;
3470 if (wParam & SCF_WORD) {
3471 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3472 return 0;
3474 bRepaint = ME_IsSelection(editor);
3475 ME_SetSelectionCharFormat(editor, p);
3476 if (bRepaint) editor->nModifyStep = 1;
3477 } else { /* SCF_DEFAULT */
3478 ME_SetDefaultCharFormat(editor, p);
3480 ME_CommitUndo(editor);
3481 if (bRepaint)
3483 ME_WrapMarkedParagraphs(editor);
3484 ME_UpdateScrollBar(editor);
3485 ME_Repaint(editor);
3487 return 1;
3489 case EM_GETCHARFORMAT:
3491 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3492 if (dst->cbSize != sizeof(CHARFORMATA) &&
3493 dst->cbSize != sizeof(CHARFORMATW) &&
3494 dst->cbSize != sizeof(CHARFORMAT2A) &&
3495 dst->cbSize != sizeof(CHARFORMAT2W))
3496 return 0;
3497 tmp.cbSize = sizeof(tmp);
3498 if (!wParam)
3499 ME_GetDefaultCharFormat(editor, &tmp);
3500 else
3501 ME_GetSelectionCharFormat(editor, &tmp);
3502 ME_CopyToCFAny(dst, &tmp);
3503 return tmp.dwMask;
3505 case EM_SETPARAFORMAT:
3507 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3508 ME_WrapMarkedParagraphs(editor);
3509 ME_UpdateScrollBar(editor);
3510 ME_Repaint(editor);
3511 ME_CommitUndo(editor);
3512 return result;
3514 case EM_GETPARAFORMAT:
3515 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3516 return ((PARAFORMAT2 *)lParam)->dwMask;
3517 case EM_GETFIRSTVISIBLELINE:
3519 ME_DisplayItem *p = editor->pBuffer->pFirst;
3520 int y = editor->vert_si.nPos;
3521 int ypara = 0;
3522 int count = 0;
3523 int ystart, yend;
3524 while(p) {
3525 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3526 if (p->type == diTextEnd)
3527 break;
3528 if (p->type == diParagraph) {
3529 ypara = p->member.para.pt.y;
3530 continue;
3532 ystart = ypara + p->member.row.pt.y;
3533 yend = ystart + p->member.row.nHeight;
3534 if (y < yend) {
3535 break;
3537 count++;
3539 return count;
3541 case EM_HIDESELECTION:
3543 editor->bHideSelection = (wParam != 0);
3544 ME_InvalidateSelection(editor);
3545 return 0;
3547 case EM_LINESCROLL:
3549 if (!(editor->styleFlags & ES_MULTILINE))
3550 return FALSE;
3551 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3552 return TRUE;
3554 case WM_CLEAR:
3556 int from, to;
3557 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3558 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3559 ME_CommitUndo(editor);
3560 ME_UpdateRepaint(editor, TRUE);
3561 return 0;
3563 case EM_REPLACESEL:
3565 int from, to, nStartCursor;
3566 ME_Style *style;
3567 int len = 0;
3568 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3569 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3570 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3572 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3573 style = ME_GetSelectionInsertStyle(editor);
3574 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3575 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3576 ME_ReleaseStyle(style);
3577 /* drop temporary style if line end */
3579 * FIXME question: does abc\n mean: put abc,
3580 * clear temp style, put \n? (would require a change)
3582 if (len>0 && wszText[len-1] == '\n')
3583 ME_ClearTempStyle(editor);
3584 ME_EndToUnicode(codepage, wszText);
3585 ME_CommitUndo(editor);
3586 ME_UpdateSelectionLinkAttribute(editor);
3587 if (!wParam)
3588 ME_EmptyUndoStack(editor);
3589 ME_UpdateRepaint(editor, FALSE);
3590 return len;
3592 case EM_SCROLLCARET:
3593 ME_EnsureVisible(editor, &editor->pCursors[0]);
3594 return 0;
3595 case WM_SETFONT:
3597 LOGFONTW lf;
3598 CHARFORMAT2W fmt;
3599 HDC hDC;
3600 BOOL bRepaint = LOWORD(lParam);
3602 if (!wParam)
3603 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3604 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3605 hDC = ITextHost_TxGetDC(editor->texthost);
3606 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3607 ITextHost_TxReleaseDC(editor->texthost, hDC);
3608 if (editor->mode & TM_RICHTEXT) {
3609 ME_Cursor start;
3610 ME_SetCursorToStart(editor, &start);
3611 ME_SetCharFormat(editor, &start, NULL, &fmt);
3613 ME_SetDefaultCharFormat(editor, &fmt);
3615 ME_CommitUndo(editor);
3616 ME_MarkAllForWrapping(editor);
3617 ME_WrapMarkedParagraphs(editor);
3618 ME_UpdateScrollBar(editor);
3619 if (bRepaint)
3620 ME_Repaint(editor);
3621 return 0;
3623 case WM_SETTEXT:
3625 ME_Cursor cursor;
3626 ME_SetCursorToStart(editor, &cursor);
3627 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3628 if (lParam)
3630 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3631 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3632 !strncmp((char *)lParam, "{\\urtf", 6))
3634 /* Undocumented: WM_SETTEXT supports RTF text */
3635 ME_StreamInRTFString(editor, 0, (char *)lParam);
3637 else
3639 int textLen;
3640 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3641 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3642 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3643 if (textLen > 0)
3645 int len = -1;
3647 /* uses default style! */
3648 if (!(editor->styleFlags & ES_MULTILINE))
3650 WCHAR * p;
3652 p = wszText;
3653 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3654 len = p - wszText;
3656 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3658 ME_EndToUnicode(codepage, wszText);
3661 else
3662 TRACE("WM_SETTEXT - NULL\n");
3663 ME_SetCursorToStart(editor, &cursor);
3664 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3665 ME_SetSelection(editor, 0, 0);
3666 editor->nModifyStep = 0;
3667 ME_CommitUndo(editor);
3668 ME_EmptyUndoStack(editor);
3669 ME_UpdateRepaint(editor, FALSE);
3670 return 1;
3672 case EM_CANPASTE:
3674 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3675 if (IsClipboardFormatAvailable(nRTFFormat))
3676 return TRUE;
3677 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3678 return TRUE;
3679 return FALSE;
3681 case WM_PASTE:
3682 case WM_MBUTTONDOWN:
3683 ME_Paste(editor);
3684 return 0;
3685 case WM_CUT:
3686 case WM_COPY:
3688 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3689 int nChars = nTo - nFrom;
3690 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3692 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3694 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3695 ME_CommitUndo(editor);
3696 ME_UpdateRepaint(editor, TRUE);
3698 return 0;
3700 case WM_GETTEXTLENGTH:
3702 GETTEXTLENGTHEX how;
3704 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3705 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3706 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3707 return ME_GetTextLengthEx(editor, &how);
3709 case EM_GETTEXTLENGTHEX:
3710 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3711 case WM_GETTEXT:
3713 GETTEXTEX ex;
3714 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3715 ex.flags = GT_USECRLF;
3716 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3717 ex.lpDefaultChar = NULL;
3718 ex.lpUsedDefChar = NULL;
3719 return ME_GetTextEx(editor, &ex, lParam);
3721 case EM_GETTEXTEX:
3722 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3723 case EM_GETSELTEXT:
3725 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3726 ME_Cursor *from = &editor->pCursors[nStartCur];
3727 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3728 nTo - nFrom, unicode);
3730 case EM_GETSCROLLPOS:
3732 POINT *point = (POINT *)lParam;
3733 point->x = editor->horz_si.nPos;
3734 point->y = editor->vert_si.nPos;
3735 /* 16-bit scaled value is returned as stored in scrollinfo */
3736 if (editor->horz_si.nMax > 0xffff)
3737 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3738 if (editor->vert_si.nMax > 0xffff)
3739 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3740 return 1;
3742 case EM_GETTEXTRANGE:
3744 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3745 ME_Cursor start;
3746 int nStart = rng->chrg.cpMin;
3747 int nEnd = rng->chrg.cpMax;
3748 int textlength = ME_GetTextLength(editor);
3750 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3751 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3752 if (nStart < 0) return 0;
3753 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3754 nEnd = textlength;
3755 if (nStart >= nEnd) return 0;
3757 ME_CursorFromCharOfs(editor, nStart, &start);
3758 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3760 case EM_GETLINE:
3762 ME_DisplayItem *run;
3763 const unsigned int nMaxChars = *(WORD *) lParam;
3764 unsigned int nCharsLeft = nMaxChars;
3765 char *dest = (char *) lParam;
3766 BOOL wroteNull = FALSE;
3768 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3769 unicode ? "Unicode" : "Ansi");
3771 run = ME_FindRowWithNumber(editor, wParam);
3772 if (run == NULL)
3773 return 0;
3775 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3776 && run->type == diRun)
3778 WCHAR *str = get_text( &run->member.run, 0 );
3779 unsigned int nCopy;
3781 nCopy = min(nCharsLeft, run->member.run.len);
3783 if (unicode)
3784 memcpy(dest, str, nCopy * sizeof(WCHAR));
3785 else
3786 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3787 nCharsLeft, NULL, NULL);
3788 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3789 nCharsLeft -= nCopy;
3792 /* append line termination, space allowing */
3793 if (nCharsLeft > 0)
3795 if (unicode)
3796 *((WCHAR *)dest) = '\0';
3797 else
3798 *dest = '\0';
3799 nCharsLeft--;
3800 wroteNull = TRUE;
3803 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3804 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3806 case EM_GETLINECOUNT:
3808 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3809 int nRows = 0;
3811 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3813 while (item != editor->pBuffer->pLast)
3815 assert(item->type == diParagraph);
3816 prev_para = ME_FindItemBack(item, diRun);
3817 if (prev_para) {
3818 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3820 nRows += item->member.para.nRows;
3821 item = item->member.para.next_para;
3823 last_para = ME_FindItemBack(item, diRun);
3824 assert(last_para);
3825 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3826 if (editor->bEmulateVersion10 && prev_para &&
3827 last_para->member.run.nCharOfs == 0 &&
3828 prev_para->member.run.len == 1 &&
3829 *get_text( &prev_para->member.run, 0 ) == '\r')
3831 /* In 1.0 emulation, the last solitary \r at the very end of the text
3832 (if one exists) is NOT a line break.
3833 FIXME: this is an ugly hack. This should have a more regular model. */
3834 nRows--;
3837 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3838 return max(1, nRows);
3840 case EM_LINEFROMCHAR:
3842 if (wParam == -1)
3843 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3844 else
3845 return ME_RowNumberFromCharOfs(editor, wParam);
3847 case EM_EXLINEFROMCHAR:
3849 if (lParam == -1)
3850 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3851 else
3852 return ME_RowNumberFromCharOfs(editor, lParam);
3854 case EM_LINEINDEX:
3856 ME_DisplayItem *item, *para;
3857 int nCharOfs;
3859 if (wParam == -1)
3860 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3861 else
3862 item = ME_FindRowWithNumber(editor, wParam);
3863 if (!item)
3864 return -1;
3865 para = ME_GetParagraph(item);
3866 item = ME_FindItemFwd(item, diRun);
3867 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3868 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3869 return nCharOfs;
3871 case EM_LINELENGTH:
3873 ME_DisplayItem *item, *item_end;
3874 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3875 ME_DisplayItem *para, *run;
3877 if (wParam > ME_GetTextLength(editor))
3878 return 0;
3879 if (wParam == -1)
3881 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3882 return 0;
3884 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3885 item = ME_RowStart(run);
3886 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3887 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3888 if (item_end->type == diStartRow) {
3889 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3890 } else {
3891 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3892 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3893 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3895 nChars = nNextLineOfs - nThisLineOfs;
3896 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3897 return nChars;
3899 case EM_EXLIMITTEXT:
3901 if ((int)lParam < 0)
3902 return 0;
3903 if (lParam == 0)
3904 editor->nTextLimit = 65536;
3905 else
3906 editor->nTextLimit = (int) lParam;
3907 return 0;
3909 case EM_LIMITTEXT:
3911 if (wParam == 0)
3912 editor->nTextLimit = 65536;
3913 else
3914 editor->nTextLimit = (int) wParam;
3915 return 0;
3917 case EM_GETLIMITTEXT:
3919 return editor->nTextLimit;
3921 case EM_FINDTEXT:
3923 LRESULT r;
3924 if(!unicode){
3925 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3926 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3927 WCHAR *tmp;
3929 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3930 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3931 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3932 FREE_OBJ( tmp );
3933 }else{
3934 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3935 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3937 return r;
3939 case EM_FINDTEXTEX:
3941 LRESULT r;
3942 if(!unicode){
3943 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3944 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3945 WCHAR *tmp;
3947 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3948 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3949 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3950 FREE_OBJ( tmp );
3951 }else{
3952 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3953 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3955 return r;
3957 case EM_FINDTEXTW:
3959 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3960 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3962 case EM_FINDTEXTEXW:
3964 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3965 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3967 case EM_GETZOOM:
3968 if (!wParam || !lParam)
3969 return FALSE;
3970 *(int *)wParam = editor->nZoomNumerator;
3971 *(int *)lParam = editor->nZoomDenominator;
3972 return TRUE;
3973 case EM_SETZOOM:
3974 return ME_SetZoom(editor, wParam, lParam);
3975 case EM_CHARFROMPOS:
3977 ME_Cursor cursor;
3978 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3979 &cursor, NULL))
3980 return ME_GetCursorOfs(&cursor);
3981 else
3982 return -1;
3984 case EM_POSFROMCHAR:
3986 ME_DisplayItem *pPara, *pRun;
3987 int nCharOfs, nOffset, nLength;
3988 POINTL pt = {0,0};
3990 nCharOfs = wParam;
3991 /* detect which API version we're dealing with */
3992 if (wParam >= 0x40000)
3993 nCharOfs = lParam;
3994 nLength = ME_GetTextLength(editor);
3995 nCharOfs = min(nCharOfs, nLength);
3996 nCharOfs = max(nCharOfs, 0);
3998 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3999 assert(pRun->type == diRun);
4000 pt.y = pRun->member.run.pt.y;
4001 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4002 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4003 pt.x += editor->rcFormat.left;
4005 pt.x -= editor->horz_si.nPos;
4006 pt.y -= editor->vert_si.nPos;
4008 if (wParam >= 0x40000) {
4009 *(POINTL *)wParam = pt;
4011 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4013 case WM_CREATE:
4015 void *text = NULL;
4016 INT max;
4018 ME_SetDefaultFormatRect(editor);
4020 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4021 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4022 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4024 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4025 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4027 if (editor->styleFlags & ES_DISABLENOSCROLL)
4029 if (editor->styleFlags & WS_VSCROLL)
4031 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4032 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4034 if (editor->styleFlags & WS_HSCROLL)
4036 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4037 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4041 if (lParam)
4043 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4044 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4046 if (text)
4048 WCHAR *textW;
4049 int len;
4050 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4051 textW = ME_ToUnicode(codepage, text, &len);
4052 if (!(editor->styleFlags & ES_MULTILINE))
4054 len = 0;
4055 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4056 len++;
4058 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4059 ME_EndToUnicode(codepage, textW);
4060 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4061 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4064 ME_CommitUndo(editor);
4065 ME_WrapMarkedParagraphs(editor);
4066 ME_MoveCaret(editor);
4067 return 0;
4069 case WM_DESTROY:
4070 ME_DestroyEditor(editor);
4071 return 0;
4072 case WM_SETCURSOR:
4074 return ME_SetCursor(editor);
4076 case WM_LBUTTONDBLCLK:
4077 case WM_LBUTTONDOWN:
4079 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4080 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4081 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4082 return 0;
4083 ITextHost_TxSetFocus(editor->texthost);
4084 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4085 ME_CalculateClickCount(editor, msg, wParam, lParam));
4086 ITextHost_TxSetCapture(editor->texthost, TRUE);
4087 editor->bMouseCaptured = TRUE;
4088 ME_LinkNotify(editor,msg,wParam,lParam);
4089 if (!ME_SetCursor(editor)) goto do_default;
4090 break;
4092 case WM_MOUSEMOVE:
4093 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4094 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4095 return 0;
4096 if (editor->bMouseCaptured)
4097 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4098 ME_LinkNotify(editor,msg,wParam,lParam);
4099 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4100 if (editor->bMouseCaptured)
4101 ME_SetCursor(editor);
4102 break;
4103 case WM_LBUTTONUP:
4104 if (editor->bMouseCaptured) {
4105 ITextHost_TxSetCapture(editor->texthost, FALSE);
4106 editor->bMouseCaptured = FALSE;
4108 if (editor->nSelectionType == stDocument)
4109 editor->nSelectionType = stPosition;
4110 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4111 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4112 return 0;
4113 else
4115 ME_SetCursor(editor);
4116 ME_LinkNotify(editor,msg,wParam,lParam);
4118 break;
4119 case WM_RBUTTONUP:
4120 case WM_RBUTTONDOWN:
4121 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4122 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4123 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4124 return 0;
4125 goto do_default;
4126 case WM_CONTEXTMENU:
4127 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4128 goto do_default;
4129 break;
4130 case WM_SETFOCUS:
4131 editor->bHaveFocus = TRUE;
4132 ME_ShowCaret(editor);
4133 ME_SendOldNotify(editor, EN_SETFOCUS);
4134 return 0;
4135 case WM_KILLFOCUS:
4136 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4137 editor->bHaveFocus = FALSE;
4138 ME_HideCaret(editor);
4139 ME_SendOldNotify(editor, EN_KILLFOCUS);
4140 return 0;
4141 case WM_COMMAND:
4142 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4143 return 0;
4144 case WM_KEYUP:
4145 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4146 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4147 return 0;
4148 goto do_default;
4149 case WM_KEYDOWN:
4150 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4151 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4152 return 0;
4153 if (ME_KeyDown(editor, LOWORD(wParam)))
4154 return 0;
4155 goto do_default;
4156 case WM_CHAR:
4157 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4158 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4159 return 0;
4160 return ME_Char(editor, wParam, lParam, unicode);
4161 case WM_UNICHAR:
4162 if (unicode)
4164 if(wParam == UNICODE_NOCHAR) return TRUE;
4165 if(wParam <= 0x000fffff)
4167 if(wParam > 0xffff) /* convert to surrogates */
4169 wParam -= 0x10000;
4170 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4171 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4172 } else {
4173 ME_Char(editor, wParam, 0, TRUE);
4176 return 0;
4178 break;
4179 case EM_STOPGROUPTYPING:
4180 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4181 return 0;
4182 case WM_HSCROLL:
4184 const int scrollUnit = 7;
4186 switch(LOWORD(wParam))
4188 case SB_LEFT:
4189 ME_ScrollAbs(editor, 0, 0);
4190 break;
4191 case SB_RIGHT:
4192 ME_ScrollAbs(editor,
4193 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4194 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4195 break;
4196 case SB_LINELEFT:
4197 ME_ScrollLeft(editor, scrollUnit);
4198 break;
4199 case SB_LINERIGHT:
4200 ME_ScrollRight(editor, scrollUnit);
4201 break;
4202 case SB_PAGELEFT:
4203 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4204 break;
4205 case SB_PAGERIGHT:
4206 ME_ScrollRight(editor, editor->sizeWindow.cx);
4207 break;
4208 case SB_THUMBTRACK:
4209 case SB_THUMBPOSITION:
4211 int pos = HIWORD(wParam);
4212 if (editor->horz_si.nMax > 0xffff)
4213 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4214 ME_HScrollAbs(editor, pos);
4215 break;
4218 break;
4220 case EM_SCROLL: /* fall through */
4221 case WM_VSCROLL:
4223 int origNPos;
4224 int lineHeight;
4226 origNPos = editor->vert_si.nPos;
4227 lineHeight = 24;
4229 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4230 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4231 if (lineHeight <= 0) lineHeight = 24;
4233 switch(LOWORD(wParam))
4235 case SB_TOP:
4236 ME_ScrollAbs(editor, 0, 0);
4237 break;
4238 case SB_BOTTOM:
4239 ME_ScrollAbs(editor,
4240 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4241 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4242 break;
4243 case SB_LINEUP:
4244 ME_ScrollUp(editor,lineHeight);
4245 break;
4246 case SB_LINEDOWN:
4247 ME_ScrollDown(editor,lineHeight);
4248 break;
4249 case SB_PAGEUP:
4250 ME_ScrollUp(editor,editor->sizeWindow.cy);
4251 break;
4252 case SB_PAGEDOWN:
4253 ME_ScrollDown(editor,editor->sizeWindow.cy);
4254 break;
4255 case SB_THUMBTRACK:
4256 case SB_THUMBPOSITION:
4258 int pos = HIWORD(wParam);
4259 if (editor->vert_si.nMax > 0xffff)
4260 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4261 ME_VScrollAbs(editor, pos);
4262 break;
4265 if (msg == EM_SCROLL)
4266 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4267 break;
4269 case WM_MOUSEWHEEL:
4271 int gcWheelDelta;
4272 UINT pulScrollLines;
4273 BOOL ctrl_is_down;
4275 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4276 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4277 return 0;
4279 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4281 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4283 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4285 if (ctrl_is_down) {
4286 int numerator;
4287 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4289 numerator = 100;
4290 } else {
4291 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4293 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4294 if (numerator >= 10 && numerator <= 500)
4295 ME_SetZoom(editor, numerator, 100);
4296 } else {
4297 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4298 /* FIXME follow the original */
4299 if (pulScrollLines)
4300 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4303 break;
4305 case EM_GETRECT:
4307 *((RECT *)lParam) = editor->rcFormat;
4308 if (editor->bDefaultFormatRect)
4309 ((RECT *)lParam)->left -= editor->selofs;
4310 return 0;
4312 case EM_SETRECT:
4313 case EM_SETRECTNP:
4315 if (lParam)
4317 int border = 0;
4318 RECT clientRect;
4319 RECT *rc = (RECT *)lParam;
4321 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4322 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4323 if (wParam == 0)
4325 editor->rcFormat.top = max(0, rc->top - border);
4326 editor->rcFormat.left = max(0, rc->left - border);
4327 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4328 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4329 } else if (wParam == 1) {
4330 /* MSDN incorrectly says a wParam value of 1 causes the
4331 * lParam rect to be used as a relative offset,
4332 * however, the tests show it just prevents min/max bound
4333 * checking. */
4334 editor->rcFormat.top = rc->top - border;
4335 editor->rcFormat.left = rc->left - border;
4336 editor->rcFormat.bottom = rc->bottom;
4337 editor->rcFormat.right = rc->right + border;
4338 } else {
4339 return 0;
4341 editor->bDefaultFormatRect = FALSE;
4343 else
4345 ME_SetDefaultFormatRect(editor);
4346 editor->bDefaultFormatRect = TRUE;
4348 ME_MarkAllForWrapping(editor);
4349 ME_WrapMarkedParagraphs(editor);
4350 ME_UpdateScrollBar(editor);
4351 if (msg != EM_SETRECTNP)
4352 ME_Repaint(editor);
4353 return 0;
4355 case EM_REQUESTRESIZE:
4356 ME_SendRequestResize(editor, TRUE);
4357 return 0;
4358 case WM_SETREDRAW:
4359 goto do_default;
4360 case WM_SIZE:
4362 RECT clientRect;
4364 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4365 if (editor->bDefaultFormatRect) {
4366 ME_SetDefaultFormatRect(editor);
4367 } else {
4368 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4369 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4371 editor->prevClientRect = clientRect;
4372 ME_RewrapRepaint(editor);
4373 goto do_default;
4375 /* IME messages to make richedit controls IME aware */
4376 case WM_IME_SETCONTEXT:
4377 case WM_IME_CONTROL:
4378 case WM_IME_SELECT:
4379 case WM_IME_COMPOSITIONFULL:
4380 return 0;
4381 case WM_IME_STARTCOMPOSITION:
4383 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4384 ME_DeleteSelection(editor);
4385 ME_CommitUndo(editor);
4386 ME_UpdateRepaint(editor, FALSE);
4387 return 0;
4389 case WM_IME_COMPOSITION:
4391 HIMC hIMC;
4393 ME_Style *style = ME_GetInsertStyle(editor, 0);
4394 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4395 ME_DeleteSelection(editor);
4396 ME_SaveTempStyle(editor);
4397 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4399 LPWSTR lpCompStr = NULL;
4400 DWORD dwBufLen;
4401 DWORD dwIndex = lParam & GCS_RESULTSTR;
4402 if (!dwIndex)
4403 dwIndex = GCS_COMPSTR;
4405 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4406 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4407 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4408 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4409 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4410 HeapFree(GetProcessHeap(), 0, lpCompStr);
4412 if (dwIndex == GCS_COMPSTR)
4413 ME_SetSelection(editor,editor->imeStartIndex,
4414 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4416 ME_ReleaseStyle(style);
4417 ME_CommitUndo(editor);
4418 ME_UpdateRepaint(editor, FALSE);
4419 return 0;
4421 case WM_IME_ENDCOMPOSITION:
4423 ME_DeleteSelection(editor);
4424 editor->imeStartIndex=-1;
4425 return 0;
4427 case EM_GETOLEINTERFACE:
4429 LPVOID *ppvObj = (LPVOID*) lParam;
4430 return CreateIRichEditOle(editor, ppvObj);
4432 case EM_GETPASSWORDCHAR:
4434 return editor->cPasswordMask;
4436 case EM_SETOLECALLBACK:
4437 if(editor->lpOleCallback)
4438 IRichEditOleCallback_Release(editor->lpOleCallback);
4439 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4440 if(editor->lpOleCallback)
4441 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4442 return TRUE;
4443 case EM_GETWORDBREAKPROC:
4444 return (LRESULT)editor->pfnWordBreak;
4445 case EM_SETWORDBREAKPROC:
4447 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4449 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4450 return (LRESULT)pfnOld;
4452 case EM_GETTEXTMODE:
4453 return editor->mode;
4454 case EM_SETTEXTMODE:
4456 int mask = 0;
4457 int changes = 0;
4459 if (ME_GetTextLength(editor) ||
4460 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4461 return E_UNEXPECTED;
4463 /* Check for mutually exclusive flags in adjacent bits of wParam */
4464 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4465 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4466 return E_INVALIDARG;
4468 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4470 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4471 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4472 if (wParam & TM_PLAINTEXT) {
4473 /* Clear selection since it should be possible to select the
4474 * end of text run for rich text */
4475 ME_InvalidateSelection(editor);
4476 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4477 editor->pCursors[1] = editor->pCursors[0];
4478 /* plain text can only have the default style. */
4479 ME_ClearTempStyle(editor);
4480 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4481 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4482 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4485 /* FIXME: Currently no support for undo level and code page options */
4486 editor->mode = (editor->mode & ~mask) | changes;
4487 return 0;
4489 case EM_SETPASSWORDCHAR:
4491 editor->cPasswordMask = wParam;
4492 ME_RewrapRepaint(editor);
4493 return 0;
4495 case EM_SETTARGETDEVICE:
4496 if (wParam == 0)
4498 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4499 if (editor->nAvailWidth || editor->bWordWrap != new)
4501 editor->bWordWrap = new;
4502 editor->nAvailWidth = 0; /* wrap to client area */
4503 ME_RewrapRepaint(editor);
4505 } else {
4506 int width = max(0, lParam);
4507 if ((editor->styleFlags & ES_MULTILINE) &&
4508 (!editor->bWordWrap || editor->nAvailWidth != width))
4510 editor->nAvailWidth = width;
4511 editor->bWordWrap = TRUE;
4512 ME_RewrapRepaint(editor);
4514 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4516 return TRUE;
4517 default:
4518 do_default:
4519 *phresult = S_FALSE;
4520 break;
4522 return 0L;
4525 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4526 LPARAM lParam, BOOL unicode)
4528 ME_TextEditor *editor;
4529 HRESULT hresult;
4530 LRESULT lresult = 0;
4532 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4533 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4535 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4536 if (!editor)
4538 if (msg == WM_NCCREATE)
4540 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4541 ITextHost *texthost;
4543 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4544 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4545 return texthost != NULL;
4547 else
4549 return DefWindowProcW(hWnd, msg, wParam, lParam);
4553 switch (msg)
4555 case WM_PAINT:
4557 HDC hDC;
4558 RECT rc;
4559 PAINTSTRUCT ps;
4561 hDC = BeginPaint(editor->hWnd, &ps);
4562 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4563 ME_SendOldNotify(editor, EN_UPDATE);
4564 /* Erase area outside of the formatting rectangle */
4565 if (ps.rcPaint.top < editor->rcFormat.top)
4567 rc = ps.rcPaint;
4568 rc.bottom = editor->rcFormat.top;
4569 FillRect(hDC, &rc, editor->hbrBackground);
4570 ps.rcPaint.top = editor->rcFormat.top;
4572 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4573 rc = ps.rcPaint;
4574 rc.top = editor->rcFormat.bottom;
4575 FillRect(hDC, &rc, editor->hbrBackground);
4576 ps.rcPaint.bottom = editor->rcFormat.bottom;
4578 if (ps.rcPaint.left < editor->rcFormat.left) {
4579 rc = ps.rcPaint;
4580 rc.right = editor->rcFormat.left;
4581 FillRect(hDC, &rc, editor->hbrBackground);
4582 ps.rcPaint.left = editor->rcFormat.left;
4584 if (ps.rcPaint.right > editor->rcFormat.right) {
4585 rc = ps.rcPaint;
4586 rc.left = editor->rcFormat.right;
4587 FillRect(hDC, &rc, editor->hbrBackground);
4588 ps.rcPaint.right = editor->rcFormat.right;
4591 ME_PaintContent(editor, hDC, &ps.rcPaint);
4592 EndPaint(editor->hWnd, &ps);
4593 return 0;
4595 case WM_ERASEBKGND:
4597 HDC hDC = (HDC)wParam;
4598 RECT rc;
4600 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4601 FillRect(hDC, &rc, editor->hbrBackground);
4602 return 1;
4604 case EM_SETOPTIONS:
4606 DWORD dwStyle;
4607 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4608 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4609 ECO_SELECTIONBAR;
4610 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4611 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4612 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4613 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4614 return lresult;
4616 case EM_SETREADONLY:
4618 DWORD dwStyle;
4619 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4620 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4621 dwStyle &= ~ES_READONLY;
4622 if (wParam)
4623 dwStyle |= ES_READONLY;
4624 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4625 return lresult;
4627 default:
4628 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4631 if (hresult == S_FALSE)
4632 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4634 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4635 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4637 return lresult;
4640 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4642 BOOL unicode = TRUE;
4644 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4645 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4646 unicode = FALSE;
4648 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4651 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4653 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4656 /******************************************************************
4657 * RichEditANSIWndProc (RICHED20.10)
4659 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4661 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4664 /******************************************************************
4665 * RichEdit10ANSIWndProc (RICHED20.9)
4667 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4669 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4671 ITextHost *texthost;
4672 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4674 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4675 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4676 return texthost != NULL;
4678 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4681 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4683 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4686 /* Fill buffer with srcChars unicode characters from the start cursor.
4688 * buffer: destination buffer
4689 * buflen: length of buffer in characters excluding the NULL terminator.
4690 * start: start of editor text to copy into buffer.
4691 * srcChars: Number of characters to use from the editor text.
4692 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4694 * returns the number of characters written excluding the NULL terminator.
4696 * The written text is always NULL terminated.
4698 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4699 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4701 ME_DisplayItem *pRun, *pNextRun;
4702 const WCHAR *pStart = buffer;
4703 const WCHAR cr_lf[] = {'\r', '\n', 0};
4704 const WCHAR *str;
4705 int nLen;
4707 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4708 if (editor->bEmulateVersion10) bCRLF = FALSE;
4710 pRun = start->pRun;
4711 assert(pRun);
4712 pNextRun = ME_FindItemFwd(pRun, diRun);
4714 nLen = pRun->member.run.len - start->nOffset;
4715 str = get_text( &pRun->member.run, start->nOffset );
4717 /* No '\r' is appended to the last paragraph. */
4718 while (srcChars && buflen && pNextRun)
4720 int nFlags = pRun->member.run.nFlags;
4722 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4724 if (buflen == 1) break;
4725 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4726 * EM_GETTEXTEX, however, this is done for copying text which
4727 * also uses this function. */
4728 srcChars -= min(nLen, srcChars);
4729 nLen = 2;
4730 str = cr_lf;
4731 } else {
4732 nLen = min(nLen, srcChars);
4733 srcChars -= nLen;
4736 nLen = min(nLen, buflen);
4737 buflen -= nLen;
4739 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4741 buffer += nLen;
4743 pRun = pNextRun;
4744 pNextRun = ME_FindItemFwd(pRun, diRun);
4746 nLen = pRun->member.run.len;
4747 str = get_text( &pRun->member.run, 0 );
4749 *buffer = 0;
4750 return buffer - pStart;
4753 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4755 WNDCLASSW wcW;
4756 WNDCLASSA wcA;
4758 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4759 wcW.lpfnWndProc = RichEditWndProcW;
4760 wcW.cbClsExtra = 0;
4761 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4762 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4763 wcW.hIcon = NULL;
4764 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4765 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4766 wcW.lpszMenuName = NULL;
4768 if (is_version_nt())
4770 wcW.lpszClassName = RICHEDIT_CLASS20W;
4771 if (!RegisterClassW(&wcW)) return FALSE;
4772 wcW.lpszClassName = MSFTEDIT_CLASS;
4773 if (!RegisterClassW(&wcW)) return FALSE;
4775 else
4777 /* WNDCLASSA/W have the same layout */
4778 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4779 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4780 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4781 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4784 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4785 wcA.lpfnWndProc = RichEditWndProcA;
4786 wcA.cbClsExtra = 0;
4787 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4788 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4789 wcA.hIcon = NULL;
4790 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4791 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4792 wcA.lpszMenuName = NULL;
4793 wcA.lpszClassName = RICHEDIT_CLASS20A;
4794 if (!RegisterClassA(&wcA)) return FALSE;
4795 wcA.lpszClassName = "RichEdit50A";
4796 if (!RegisterClassA(&wcA)) return FALSE;
4798 return TRUE;
4801 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4802 /* FIXME: Not implemented */
4803 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4804 hWnd, msg, get_msg_name(msg), wParam, lParam);
4805 return DefWindowProcW(hWnd, msg, wParam, lParam);
4808 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4809 /* FIXME: Not implemented */
4810 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4811 hWnd, msg, get_msg_name(msg), wParam, lParam);
4812 return DefWindowProcW(hWnd, msg, wParam, lParam);
4815 /******************************************************************
4816 * REExtendedRegisterClass (RICHED20.8)
4818 * FIXME undocumented
4819 * Need to check for errors and implement controls and callbacks
4821 LRESULT WINAPI REExtendedRegisterClass(void)
4823 WNDCLASSW wcW;
4824 UINT result;
4826 FIXME("semi stub\n");
4828 wcW.cbClsExtra = 0;
4829 wcW.cbWndExtra = 4;
4830 wcW.hInstance = NULL;
4831 wcW.hIcon = NULL;
4832 wcW.hCursor = NULL;
4833 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4834 wcW.lpszMenuName = NULL;
4836 if (!ME_ListBoxRegistered)
4838 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4839 wcW.lpfnWndProc = REListWndProc;
4840 wcW.lpszClassName = REListBox20W;
4841 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4844 if (!ME_ComboBoxRegistered)
4846 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4847 wcW.lpfnWndProc = REComboWndProc;
4848 wcW.lpszClassName = REComboBox20W;
4849 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4852 result = 0;
4853 if (ME_ListBoxRegistered)
4854 result += 1;
4855 if (ME_ComboBoxRegistered)
4856 result += 2;
4858 return result;
4861 static BOOL isurlspecial(WCHAR c)
4863 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4864 return strchrW( special_chars, c ) != NULL;
4868 * This proc takes a selection, and scans it forward in order to select the span
4869 * of a possible URL candidate. A possible URL candidate must start with isalnum
4870 * or one of the following special characters: *|/\+%#@ and must consist entirely
4871 * of the characters allowed to start the URL, plus : (colon) which may occur
4872 * at most once, and not at either end.
4874 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4875 const ME_Cursor *start,
4876 int nChars,
4877 ME_Cursor *candidate_min,
4878 ME_Cursor *candidate_max)
4880 ME_Cursor cursor = *start;
4881 BOOL foundColon = FALSE;
4882 BOOL candidateStarted = FALSE;
4883 WCHAR lastAcceptedChar = '\0';
4885 while (nChars > 0)
4887 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4888 WCHAR *str = strStart + cursor.nOffset;
4889 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4890 nChars -= nLen;
4892 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4894 /* Find start of candidate */
4895 if (!candidateStarted)
4897 while (nLen)
4899 nLen--;
4900 if (isalnumW(*str) || isurlspecial(*str))
4902 cursor.nOffset = str - strStart;
4903 *candidate_min = cursor;
4904 candidateStarted = TRUE;
4905 lastAcceptedChar = *str++;
4906 break;
4908 str++;
4912 /* Find end of candidate */
4913 if (candidateStarted) {
4914 while (nLen)
4916 nLen--;
4917 if (*str == ':' && !foundColon) {
4918 foundColon = TRUE;
4919 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4920 cursor.nOffset = str - strStart;
4921 if (lastAcceptedChar == ':')
4922 ME_MoveCursorChars(editor, &cursor, -1);
4923 *candidate_max = cursor;
4924 return TRUE;
4926 lastAcceptedChar = *str++;
4929 } else {
4930 /* End of paragraph: skip it if before candidate span, or terminates
4931 current active span */
4932 if (candidateStarted) {
4933 if (lastAcceptedChar == ':')
4934 ME_MoveCursorChars(editor, &cursor, -1);
4935 *candidate_max = cursor;
4936 return TRUE;
4940 /* Reaching this point means no span was found, so get next span */
4941 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4942 if (candidateStarted) {
4943 /* There are no further runs, so take end of text as end of candidate */
4944 cursor.nOffset = str - strStart;
4945 if (lastAcceptedChar == ':')
4946 ME_MoveCursorChars(editor, &cursor, -1);
4947 *candidate_max = cursor;
4948 return TRUE;
4950 *candidate_max = *candidate_min = cursor;
4951 return FALSE;
4953 cursor.nOffset = 0;
4956 if (candidateStarted) {
4957 /* There are no further runs, so take end of text as end of candidate */
4958 if (lastAcceptedChar == ':')
4959 ME_MoveCursorChars(editor, &cursor, -1);
4960 *candidate_max = cursor;
4961 return TRUE;
4963 *candidate_max = *candidate_min = cursor;
4964 return FALSE;
4968 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4970 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4972 #define MAX_PREFIX_LEN 9
4973 struct prefix_s {
4974 const WCHAR text[MAX_PREFIX_LEN];
4975 int length;
4976 }prefixes[] = {
4977 {{'p','r','o','s','p','e','r','o',':'}, 9},
4978 {{'t','e','l','n','e','t',':'}, 7},
4979 {{'g','o','p','h','e','r',':'}, 7},
4980 {{'m','a','i','l','t','o',':'}, 7},
4981 {{'h','t','t','p','s',':'}, 6},
4982 {{'f','i','l','e',':'}, 5},
4983 {{'n','e','w','s',':'}, 5},
4984 {{'w','a','i','s',':'}, 5},
4985 {{'n','n','t','p',':'}, 5},
4986 {{'h','t','t','p',':'}, 5},
4987 {{'w','w','w','.'}, 4},
4988 {{'f','t','p',':'}, 4},
4990 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4991 unsigned int i;
4993 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE);
4994 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4996 if (nChars < prefixes[i].length) continue;
4997 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4998 return TRUE;
5000 return FALSE;
5001 #undef MAX_PREFIX_LEN
5005 * This proc walks through the indicated selection and evaluates whether each
5006 * section identified by ME_FindNextURLCandidate and in-between sections have
5007 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5008 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5010 * Since this function can cause runs to be split, do not depend on the value
5011 * of the start cursor at the end of the function.
5013 * nChars may be set to INT_MAX to update to the end of the text.
5015 * Returns TRUE if at least one section was modified.
5017 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5019 BOOL modified = FALSE;
5020 ME_Cursor startCur = *start;
5022 if (!editor->AutoURLDetect_bEnable) return FALSE;
5026 CHARFORMAT2W link;
5027 ME_Cursor candidateStart, candidateEnd;
5029 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5030 &candidateStart, &candidateEnd))
5032 /* Section before candidate is not an URL */
5033 int cMin = ME_GetCursorOfs(&candidateStart);
5034 int cMax = ME_GetCursorOfs(&candidateEnd);
5036 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5037 candidateStart = candidateEnd;
5038 nChars -= cMax - ME_GetCursorOfs(&startCur);
5040 else
5042 /* No more candidates until end of selection */
5043 nChars = 0;
5046 if (startCur.pRun != candidateStart.pRun ||
5047 startCur.nOffset != candidateStart.nOffset)
5049 /* CFE_LINK effect should be consistently unset */
5050 link.cbSize = sizeof(link);
5051 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5052 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5054 /* CFE_LINK must be unset from this range */
5055 memset(&link, 0, sizeof(CHARFORMAT2W));
5056 link.cbSize = sizeof(link);
5057 link.dwMask = CFM_LINK;
5058 link.dwEffects = 0;
5059 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5060 /* Update candidateEnd since setting character formats may split
5061 * runs, which can cause a cursor to be at an invalid offset within
5062 * a split run. */
5063 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5065 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5066 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5068 modified = TRUE;
5071 if (candidateStart.pRun != candidateEnd.pRun ||
5072 candidateStart.nOffset != candidateEnd.nOffset)
5074 /* CFE_LINK effect should be consistently set */
5075 link.cbSize = sizeof(link);
5076 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5077 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5079 /* CFE_LINK must be set on this range */
5080 memset(&link, 0, sizeof(CHARFORMAT2W));
5081 link.cbSize = sizeof(link);
5082 link.dwMask = CFM_LINK;
5083 link.dwEffects = CFE_LINK;
5084 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5085 modified = TRUE;
5088 startCur = candidateEnd;
5089 } while (nChars > 0);
5090 return modified;