riched20: Initial support for changing font properties.
[wine/multimedia.git] / dlls / riched20 / editor.c
blob3ed06efeff52eb44e9085f5efe709f2b9f602a28
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 #define NONAMELESSUNION
229 #include "editor.h"
230 #include "commdlg.h"
231 #include "winreg.h"
232 #define NO_SHLWAPI_STREAM
233 #include "shlwapi.h"
234 #include "rtf.h"
235 #include "imm.h"
236 #include "res.h"
238 #define STACK_SIZE_DEFAULT 100
239 #define STACK_SIZE_MAX 1000
241 #define TEXT_LIMIT_DEFAULT 32767
243 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
245 static BOOL ME_RegisterEditorClass(HINSTANCE);
246 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
248 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
249 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
250 static HCURSOR hLeft;
252 BOOL me_debug = FALSE;
253 HANDLE me_heap = NULL;
255 static BOOL ME_ListBoxRegistered = FALSE;
256 static BOOL ME_ComboBoxRegistered = FALSE;
258 static inline BOOL is_version_nt(void)
260 return !(GetVersion() & 0x80000000);
263 static ME_TextBuffer *ME_MakeText(void) {
265 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
267 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
268 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
270 p1->prev = NULL;
271 p1->next = p2;
272 p2->prev = p1;
273 p2->next = NULL;
274 p1->member.para.next_para = p2;
275 p2->member.para.prev_para = p1;
276 p2->member.para.nCharOfs = 0;
278 buf->pFirst = p1;
279 buf->pLast = p2;
280 buf->pCharStyle = NULL;
282 return buf;
286 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
288 WCHAR *pText;
289 LRESULT total_bytes_read = 0;
290 BOOL is_read = FALSE;
291 DWORD cp = CP_ACP, copy = 0;
292 char conv_buf[4 + STREAMIN_BUFFER_SIZE]; /* up to 4 additional UTF-8 bytes */
294 static const char bom_utf8[] = {0xEF, 0xBB, 0xBF};
296 TRACE("%08x %p\n", dwFormat, stream);
298 do {
299 LONG nWideChars = 0;
300 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
302 if (!stream->dwSize)
304 ME_StreamInFill(stream);
305 if (stream->editstream->dwError)
306 break;
307 if (!stream->dwSize)
308 break;
309 total_bytes_read += stream->dwSize;
312 if (!(dwFormat & SF_UNICODE))
314 char * buf = stream->buffer;
315 DWORD size = stream->dwSize, end;
317 if (!is_read)
319 is_read = TRUE;
320 if (stream->dwSize >= 3 && !memcmp(stream->buffer, bom_utf8, 3))
322 cp = CP_UTF8;
323 buf += 3;
324 size -= 3;
328 if (cp == CP_UTF8)
330 if (copy)
332 memcpy(conv_buf + copy, buf, size);
333 buf = conv_buf;
334 size += copy;
336 end = size;
337 while ((buf[end-1] & 0xC0) == 0x80)
339 --end;
340 --total_bytes_read; /* strange, but seems to match windows */
342 if (buf[end-1] & 0x80)
344 DWORD need = 0;
345 if ((buf[end-1] & 0xE0) == 0xC0)
346 need = 1;
347 if ((buf[end-1] & 0xF0) == 0xE0)
348 need = 2;
349 if ((buf[end-1] & 0xF8) == 0xF0)
350 need = 3;
352 if (size - end >= need)
354 /* we have enough bytes for this sequence */
355 end = size;
357 else
359 /* need more bytes, so don't transcode this sequence */
360 --end;
364 else
365 end = size;
367 nWideChars = MultiByteToWideChar(cp, 0, buf, end, wszText, STREAMIN_BUFFER_SIZE);
368 pText = wszText;
370 if (cp == CP_UTF8)
372 if (end != size)
374 memcpy(conv_buf, buf + end, size - end);
375 copy = size - end;
379 else
381 nWideChars = stream->dwSize >> 1;
382 pText = (WCHAR *)stream->buffer;
385 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
386 if (stream->dwSize == 0)
387 break;
388 stream->dwSize = 0;
389 } while(1);
390 return total_bytes_read;
393 static void ME_ApplyBorderProperties(RTF_Info *info,
394 ME_BorderRect *borderRect,
395 RTFBorder *borderDef)
397 int i, colorNum;
398 ME_Border *pBorders[] = {&borderRect->top,
399 &borderRect->left,
400 &borderRect->bottom,
401 &borderRect->right};
402 for (i = 0; i < 4; i++)
404 RTFColor *colorDef = info->colorList;
405 pBorders[i]->width = borderDef[i].width;
406 colorNum = borderDef[i].color;
407 while (colorDef && colorDef->rtfCNum != colorNum)
408 colorDef = colorDef->rtfNextColor;
409 if (colorDef)
410 pBorders[i]->colorRef = RGB(
411 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
412 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
413 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
414 else
415 pBorders[i]->colorRef = RGB(0, 0, 0);
419 void ME_RTFCharAttrHook(RTF_Info *info)
421 CHARFORMAT2W fmt;
422 fmt.cbSize = sizeof(fmt);
423 fmt.dwMask = 0;
424 fmt.dwEffects = 0;
426 switch(info->rtfMinor)
428 case rtfPlain:
429 /* FIXME add more flags once they're implemented */
430 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
431 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
432 fmt.yHeight = 12*20; /* 12pt */
433 fmt.wWeight = FW_NORMAL;
434 fmt.bUnderlineType = CFU_UNDERLINENONE;
435 break;
436 case rtfBold:
437 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
438 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
439 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
440 break;
441 case rtfItalic:
442 fmt.dwMask = CFM_ITALIC;
443 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
444 break;
445 case rtfUnderline:
446 fmt.dwMask = CFM_UNDERLINETYPE;
447 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
448 break;
449 case rtfDotUnderline:
450 fmt.dwMask = CFM_UNDERLINETYPE;
451 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
452 break;
453 case rtfDbUnderline:
454 fmt.dwMask = CFM_UNDERLINETYPE;
455 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
456 break;
457 case rtfWordUnderline:
458 fmt.dwMask = CFM_UNDERLINETYPE;
459 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
460 break;
461 case rtfNoUnderline:
462 fmt.dwMask = CFM_UNDERLINETYPE;
463 fmt.bUnderlineType = CFU_UNDERLINENONE;
464 break;
465 case rtfStrikeThru:
466 fmt.dwMask = CFM_STRIKEOUT;
467 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
468 break;
469 case rtfSubScript:
470 case rtfSuperScript:
471 case rtfSubScrShrink:
472 case rtfSuperScrShrink:
473 case rtfNoSuperSub:
474 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
475 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
476 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
477 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
478 break;
479 case rtfInvisible:
480 fmt.dwMask = CFM_HIDDEN;
481 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
482 break;
483 case rtfBackColor:
484 fmt.dwMask = CFM_BACKCOLOR;
485 fmt.dwEffects = 0;
486 if (info->rtfParam == 0)
487 fmt.dwEffects = CFE_AUTOBACKCOLOR;
488 else if (info->rtfParam != rtfNoParam)
490 RTFColor *c = RTFGetColor(info, info->rtfParam);
491 if (c && c->rtfCBlue >= 0)
492 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
493 else
494 fmt.dwEffects = CFE_AUTOBACKCOLOR;
496 break;
497 case rtfForeColor:
498 fmt.dwMask = CFM_COLOR;
499 fmt.dwEffects = 0;
500 if (info->rtfParam == 0)
501 fmt.dwEffects = CFE_AUTOCOLOR;
502 else if (info->rtfParam != rtfNoParam)
504 RTFColor *c = RTFGetColor(info, info->rtfParam);
505 if (c && c->rtfCBlue >= 0)
506 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
507 else {
508 fmt.dwEffects = CFE_AUTOCOLOR;
511 break;
512 case rtfFontNum:
513 if (info->rtfParam != rtfNoParam)
515 RTFFont *f = RTFGetFont(info, info->rtfParam);
516 if (f)
518 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
519 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
520 fmt.bCharSet = f->rtfFCharSet;
521 fmt.dwMask = CFM_FACE | CFM_CHARSET;
522 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
525 break;
526 case rtfFontSize:
527 fmt.dwMask = CFM_SIZE;
528 if (info->rtfParam != rtfNoParam)
529 fmt.yHeight = info->rtfParam*10;
530 break;
532 if (fmt.dwMask) {
533 ME_Style *style2;
534 RTFFlushOutputBuffer(info);
535 /* FIXME too slow ? how come ? */
536 style2 = ME_ApplyStyle(info->style, &fmt);
537 ME_ReleaseStyle(info->style);
538 info->style = style2;
539 info->styleChanged = TRUE;
543 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
544 the same tags mean different things in different contexts */
545 void ME_RTFParAttrHook(RTF_Info *info)
547 PARAFORMAT2 fmt;
548 fmt.cbSize = sizeof(fmt);
549 fmt.dwMask = 0;
551 switch(info->rtfMinor)
553 case rtfParDef: /* restores default paragraph attributes */
554 if (!info->editor->bEmulateVersion10) /* v4.1 */
555 info->borderType = RTFBorderParaLeft;
556 else /* v1.0 - 3.0 */
557 info->borderType = RTFBorderParaTop;
558 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
559 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
560 PFM_STARTINDENT;
561 /* TODO: numbering, shading */
562 fmt.wAlignment = PFA_LEFT;
563 fmt.cTabCount = 0;
564 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
565 fmt.wBorderWidth = fmt.wBorders = 0;
566 fmt.wBorderSpace = 0;
567 fmt.bLineSpacingRule = 0;
568 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
569 fmt.dyLineSpacing = 0;
570 if (!info->editor->bEmulateVersion10) /* v4.1 */
572 if (info->tableDef && info->tableDef->tableRowStart &&
573 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
575 ME_Cursor cursor;
576 ME_DisplayItem *para;
577 /* We are just after a table row. */
578 RTFFlushOutputBuffer(info);
579 cursor = info->editor->pCursors[0];
580 para = cursor.pPara;
581 if (para == info->tableDef->tableRowStart->member.para.next_para
582 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
584 /* Since the table row end, no text has been inserted, and the \intbl
585 * control word has not be used. We can confirm that we are not in a
586 * table anymore.
588 info->tableDef->tableRowStart = NULL;
589 info->canInheritInTbl = FALSE;
592 } else { /* v1.0 - v3.0 */
593 fmt.dwMask |= PFM_TABLE;
594 fmt.wEffects &= ~PFE_TABLE;
596 break;
597 case rtfNestLevel:
598 if (!info->editor->bEmulateVersion10) /* v4.1 */
600 while (info->rtfParam > info->nestingLevel) {
601 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
602 ZeroMemory(tableDef, sizeof(RTFTable));
603 tableDef->parent = info->tableDef;
604 info->tableDef = tableDef;
606 RTFFlushOutputBuffer(info);
607 if (tableDef->tableRowStart &&
608 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
610 ME_DisplayItem *para = tableDef->tableRowStart;
611 para = para->member.para.next_para;
612 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
613 tableDef->tableRowStart = para;
614 } else {
615 ME_Cursor cursor;
616 WCHAR endl = '\r';
617 cursor = info->editor->pCursors[0];
618 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
619 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
620 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
623 info->nestingLevel++;
625 info->canInheritInTbl = FALSE;
627 break;
628 case rtfInTable:
630 if (!info->editor->bEmulateVersion10) /* v4.1 */
632 if (info->nestingLevel < 1)
634 RTFTable *tableDef;
635 if (!info->tableDef)
637 info->tableDef = ALLOC_OBJ(RTFTable);
638 ZeroMemory(info->tableDef, sizeof(RTFTable));
640 tableDef = info->tableDef;
641 RTFFlushOutputBuffer(info);
642 if (tableDef->tableRowStart &&
643 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
645 ME_DisplayItem *para = tableDef->tableRowStart;
646 para = para->member.para.next_para;
647 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
648 tableDef->tableRowStart = para;
649 } else {
650 ME_Cursor cursor;
651 WCHAR endl = '\r';
652 cursor = info->editor->pCursors[0];
653 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
654 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
655 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
657 info->nestingLevel = 1;
658 info->canInheritInTbl = TRUE;
660 return;
661 } else { /* v1.0 - v3.0 */
662 fmt.dwMask |= PFM_TABLE;
663 fmt.wEffects |= PFE_TABLE;
665 break;
667 case rtfFirstIndent:
668 ME_GetSelectionParaFormat(info->editor, &fmt);
669 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
670 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
671 fmt.dxOffset = -info->rtfParam;
672 break;
673 case rtfLeftIndent:
674 ME_GetSelectionParaFormat(info->editor, &fmt);
675 fmt.dwMask = PFM_STARTINDENT;
676 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
677 break;
678 case rtfRightIndent:
679 fmt.dwMask = PFM_RIGHTINDENT;
680 fmt.dxRightIndent = info->rtfParam;
681 break;
682 case rtfQuadLeft:
683 case rtfQuadJust:
684 fmt.dwMask = PFM_ALIGNMENT;
685 fmt.wAlignment = PFA_LEFT;
686 break;
687 case rtfQuadRight:
688 fmt.dwMask = PFM_ALIGNMENT;
689 fmt.wAlignment = PFA_RIGHT;
690 break;
691 case rtfQuadCenter:
692 fmt.dwMask = PFM_ALIGNMENT;
693 fmt.wAlignment = PFA_CENTER;
694 break;
695 case rtfTabPos:
696 ME_GetSelectionParaFormat(info->editor, &fmt);
697 if (!(fmt.dwMask & PFM_TABSTOPS))
699 fmt.cTabCount = 0;
701 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
702 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
703 fmt.dwMask = PFM_TABSTOPS;
704 break;
705 case rtfKeep:
706 fmt.dwMask = PFM_KEEP;
707 fmt.wEffects = PFE_KEEP;
708 break;
709 case rtfNoWidowControl:
710 fmt.dwMask = PFM_NOWIDOWCONTROL;
711 fmt.wEffects = PFE_NOWIDOWCONTROL;
712 break;
713 case rtfKeepNext:
714 fmt.dwMask = PFM_KEEPNEXT;
715 fmt.wEffects = PFE_KEEPNEXT;
716 break;
717 case rtfSpaceAfter:
718 fmt.dwMask = PFM_SPACEAFTER;
719 fmt.dySpaceAfter = info->rtfParam;
720 break;
721 case rtfSpaceBefore:
722 fmt.dwMask = PFM_SPACEBEFORE;
723 fmt.dySpaceBefore = info->rtfParam;
724 break;
725 case rtfSpaceBetween:
726 fmt.dwMask = PFM_LINESPACING;
727 if ((int)info->rtfParam > 0)
729 fmt.dyLineSpacing = info->rtfParam;
730 fmt.bLineSpacingRule = 3;
732 else
734 fmt.dyLineSpacing = info->rtfParam;
735 fmt.bLineSpacingRule = 4;
737 break;
738 case rtfSpaceMultiply:
739 fmt.dwMask = PFM_LINESPACING;
740 fmt.dyLineSpacing = info->rtfParam * 20;
741 fmt.bLineSpacingRule = 5;
742 break;
743 case rtfParBullet:
744 fmt.dwMask = PFM_NUMBERING;
745 fmt.wNumbering = PFN_BULLET;
746 break;
747 case rtfParSimple:
748 fmt.dwMask = PFM_NUMBERING;
749 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
750 break;
751 case rtfParNumDecimal:
752 fmt.dwMask = PFM_NUMBERING;
753 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
754 break;
755 case rtfParNumIndent:
756 fmt.dwMask = PFM_NUMBERINGTAB;
757 fmt.wNumberingTab = info->rtfParam;
758 break;
759 case rtfParNumStartAt:
760 fmt.dwMask = PFM_NUMBERINGSTART;
761 fmt.wNumberingStart = info->rtfParam;
762 break;
763 case rtfBorderLeft:
764 info->borderType = RTFBorderParaLeft;
765 ME_GetSelectionParaFormat(info->editor, &fmt);
766 if (!(fmt.dwMask & PFM_BORDER))
768 fmt.wBorderSpace = 0;
769 fmt.wBorderWidth = 1;
770 fmt.wBorders = 0;
772 fmt.wBorders |= 1;
773 fmt.dwMask = PFM_BORDER;
774 break;
775 case rtfBorderRight:
776 info->borderType = RTFBorderParaRight;
777 ME_GetSelectionParaFormat(info->editor, &fmt);
778 if (!(fmt.dwMask & PFM_BORDER))
780 fmt.wBorderSpace = 0;
781 fmt.wBorderWidth = 1;
782 fmt.wBorders = 0;
784 fmt.wBorders |= 2;
785 fmt.dwMask = PFM_BORDER;
786 break;
787 case rtfBorderTop:
788 info->borderType = RTFBorderParaTop;
789 ME_GetSelectionParaFormat(info->editor, &fmt);
790 if (!(fmt.dwMask & PFM_BORDER))
792 fmt.wBorderSpace = 0;
793 fmt.wBorderWidth = 1;
794 fmt.wBorders = 0;
796 fmt.wBorders |= 4;
797 fmt.dwMask = PFM_BORDER;
798 break;
799 case rtfBorderBottom:
800 info->borderType = RTFBorderParaBottom;
801 ME_GetSelectionParaFormat(info->editor, &fmt);
802 if (!(fmt.dwMask & PFM_BORDER))
804 fmt.wBorderSpace = 0;
805 fmt.wBorderWidth = 1;
806 fmt.wBorders = 0;
808 fmt.wBorders |= 8;
809 fmt.dwMask = PFM_BORDER;
810 break;
811 case rtfBorderSingle:
812 ME_GetSelectionParaFormat(info->editor, &fmt);
813 /* we assume that borders have been created before (RTF spec) */
814 fmt.wBorders &= ~0x700;
815 fmt.wBorders |= 1 << 8;
816 fmt.dwMask = PFM_BORDER;
817 break;
818 case rtfBorderThick:
819 ME_GetSelectionParaFormat(info->editor, &fmt);
820 /* we assume that borders have been created before (RTF spec) */
821 fmt.wBorders &= ~0x700;
822 fmt.wBorders |= 2 << 8;
823 fmt.dwMask = PFM_BORDER;
824 break;
825 case rtfBorderShadow:
826 ME_GetSelectionParaFormat(info->editor, &fmt);
827 /* we assume that borders have been created before (RTF spec) */
828 fmt.wBorders &= ~0x700;
829 fmt.wBorders |= 10 << 8;
830 fmt.dwMask = PFM_BORDER;
831 break;
832 case rtfBorderDouble:
833 ME_GetSelectionParaFormat(info->editor, &fmt);
834 /* we assume that borders have been created before (RTF spec) */
835 fmt.wBorders &= ~0x700;
836 fmt.wBorders |= 7 << 8;
837 fmt.dwMask = PFM_BORDER;
838 break;
839 case rtfBorderDot:
840 ME_GetSelectionParaFormat(info->editor, &fmt);
841 /* we assume that borders have been created before (RTF spec) */
842 fmt.wBorders &= ~0x700;
843 fmt.wBorders |= 11 << 8;
844 fmt.dwMask = PFM_BORDER;
845 break;
846 case rtfBorderWidth:
848 int borderSide = info->borderType & RTFBorderSideMask;
849 RTFTable *tableDef = info->tableDef;
850 ME_GetSelectionParaFormat(info->editor, &fmt);
851 /* we assume that borders have been created before (RTF spec) */
852 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
853 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
855 RTFBorder *border;
856 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
857 break;
858 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
859 border->width = info->rtfParam;
860 break;
862 fmt.dwMask = PFM_BORDER;
863 break;
865 case rtfBorderSpace:
866 ME_GetSelectionParaFormat(info->editor, &fmt);
867 /* we assume that borders have been created before (RTF spec) */
868 fmt.wBorderSpace = info->rtfParam;
869 fmt.dwMask = PFM_BORDER;
870 break;
871 case rtfBorderColor:
873 RTFTable *tableDef = info->tableDef;
874 int borderSide = info->borderType & RTFBorderSideMask;
875 int borderType = info->borderType & RTFBorderTypeMask;
876 switch(borderType)
878 case RTFBorderTypePara:
879 if (!info->editor->bEmulateVersion10) /* v4.1 */
880 break;
881 /* v1.0 - 3.0 treat paragraph and row borders the same. */
882 case RTFBorderTypeRow:
883 if (tableDef) {
884 tableDef->border[borderSide].color = info->rtfParam;
886 break;
887 case RTFBorderTypeCell:
888 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
889 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
891 break;
893 break;
895 case rtfRTLPar:
896 fmt.dwMask = PFM_RTLPARA;
897 fmt.wEffects = PFE_RTLPARA;
898 break;
899 case rtfLTRPar:
900 fmt.dwMask = PFM_RTLPARA;
901 fmt.wEffects = 0;
902 break;
904 if (fmt.dwMask) {
905 RTFFlushOutputBuffer(info);
906 /* FIXME too slow ? how come ?*/
907 ME_SetSelectionParaFormat(info->editor, &fmt);
911 void ME_RTFTblAttrHook(RTF_Info *info)
913 switch (info->rtfMinor)
915 case rtfRowDef:
917 if (!info->editor->bEmulateVersion10) /* v4.1 */
918 info->borderType = 0; /* Not sure */
919 else /* v1.0 - 3.0 */
920 info->borderType = RTFBorderRowTop;
921 if (!info->tableDef) {
922 info->tableDef = ME_MakeTableDef(info->editor);
923 } else {
924 ME_InitTableDef(info->editor, info->tableDef);
926 break;
928 case rtfCellPos:
930 int cellNum;
931 if (!info->tableDef)
933 info->tableDef = ME_MakeTableDef(info->editor);
935 cellNum = info->tableDef->numCellsDefined;
936 if (cellNum >= MAX_TABLE_CELLS)
937 break;
938 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
939 if (cellNum < MAX_TAB_STOPS) {
940 /* Tab stops were used to store cell positions before v4.1 but v4.1
941 * still seems to set the tabstops without using them. */
942 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
943 PARAFORMAT2 *pFmt = para->member.para.pFmt;
944 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
945 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
947 info->tableDef->numCellsDefined++;
948 break;
950 case rtfRowBordTop:
951 info->borderType = RTFBorderRowTop;
952 break;
953 case rtfRowBordLeft:
954 info->borderType = RTFBorderRowLeft;
955 break;
956 case rtfRowBordBottom:
957 info->borderType = RTFBorderRowBottom;
958 break;
959 case rtfRowBordRight:
960 info->borderType = RTFBorderRowRight;
961 break;
962 case rtfCellBordTop:
963 info->borderType = RTFBorderCellTop;
964 break;
965 case rtfCellBordLeft:
966 info->borderType = RTFBorderCellLeft;
967 break;
968 case rtfCellBordBottom:
969 info->borderType = RTFBorderCellBottom;
970 break;
971 case rtfCellBordRight:
972 info->borderType = RTFBorderCellRight;
973 break;
974 case rtfRowGapH:
975 if (info->tableDef)
976 info->tableDef->gapH = info->rtfParam;
977 break;
978 case rtfRowLeftEdge:
979 if (info->tableDef)
980 info->tableDef->leftEdge = info->rtfParam;
981 break;
985 void ME_RTFSpecialCharHook(RTF_Info *info)
987 RTFTable *tableDef = info->tableDef;
988 switch (info->rtfMinor)
990 case rtfNestCell:
991 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
992 break;
993 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
994 case rtfCell:
995 if (!tableDef)
996 break;
997 RTFFlushOutputBuffer(info);
998 if (!info->editor->bEmulateVersion10) { /* v4.1 */
999 if (tableDef->tableRowStart)
1001 if (!info->nestingLevel &&
1002 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1004 ME_DisplayItem *para = tableDef->tableRowStart;
1005 para = para->member.para.next_para;
1006 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1007 tableDef->tableRowStart = para;
1008 info->nestingLevel = 1;
1010 ME_InsertTableCellFromCursor(info->editor);
1012 } else { /* v1.0 - v3.0 */
1013 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1014 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1015 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
1016 tableDef->numCellsInserted < tableDef->numCellsDefined)
1018 WCHAR tab = '\t';
1019 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1020 tableDef->numCellsInserted++;
1023 break;
1024 case rtfNestRow:
1025 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
1026 break;
1027 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
1028 case rtfRow:
1030 ME_DisplayItem *para, *cell, *run;
1031 int i;
1033 if (!tableDef)
1034 break;
1035 RTFFlushOutputBuffer(info);
1036 if (!info->editor->bEmulateVersion10) { /* v4.1 */
1037 if (!tableDef->tableRowStart)
1038 break;
1039 if (!info->nestingLevel &&
1040 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
1042 para = tableDef->tableRowStart;
1043 para = para->member.para.next_para;
1044 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
1045 tableDef->tableRowStart = para;
1046 info->nestingLevel++;
1048 para = tableDef->tableRowStart;
1049 cell = ME_FindItemFwd(para, diCell);
1050 assert(cell && !cell->member.cell.prev_cell);
1051 if (tableDef->numCellsDefined < 1)
1053 /* 2000 twips appears to be the cell size that native richedit uses
1054 * when no cell sizes are specified. */
1055 const int defaultCellSize = 2000;
1056 int nRightBoundary = defaultCellSize;
1057 cell->member.cell.nRightBoundary = nRightBoundary;
1058 while (cell->member.cell.next_cell) {
1059 cell = cell->member.cell.next_cell;
1060 nRightBoundary += defaultCellSize;
1061 cell->member.cell.nRightBoundary = nRightBoundary;
1063 para = ME_InsertTableCellFromCursor(info->editor);
1064 cell = para->member.para.pCell;
1065 cell->member.cell.nRightBoundary = nRightBoundary;
1066 } else {
1067 for (i = 0; i < tableDef->numCellsDefined; i++)
1069 RTFCell *cellDef = &tableDef->cells[i];
1070 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
1071 ME_ApplyBorderProperties(info, &cell->member.cell.border,
1072 cellDef->border);
1073 cell = cell->member.cell.next_cell;
1074 if (!cell)
1076 para = ME_InsertTableCellFromCursor(info->editor);
1077 cell = para->member.para.pCell;
1080 /* Cell for table row delimiter is empty */
1081 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1084 run = ME_FindItemFwd(cell, diRun);
1085 if (info->editor->pCursors[0].pRun != run ||
1086 info->editor->pCursors[0].nOffset)
1088 int nOfs, nChars;
1089 /* Delete inserted cells that aren't defined. */
1090 info->editor->pCursors[1].pRun = run;
1091 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1092 info->editor->pCursors[1].nOffset = 0;
1093 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1094 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1095 ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1096 nChars, TRUE);
1099 para = ME_InsertTableRowEndFromCursor(info->editor);
1100 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1101 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1102 ME_ApplyBorderProperties(info, &para->member.para.border,
1103 tableDef->border);
1104 info->nestingLevel--;
1105 if (!info->nestingLevel)
1107 if (info->canInheritInTbl) {
1108 tableDef->tableRowStart = para;
1109 } else {
1110 while (info->tableDef) {
1111 tableDef = info->tableDef;
1112 info->tableDef = tableDef->parent;
1113 heap_free(tableDef);
1116 } else {
1117 info->tableDef = tableDef->parent;
1118 heap_free(tableDef);
1120 } else { /* v1.0 - v3.0 */
1121 WCHAR endl = '\r';
1122 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1123 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1124 pFmt->dxOffset = info->tableDef->gapH;
1125 pFmt->dxStartIndent = info->tableDef->leftEdge;
1127 ME_ApplyBorderProperties(info, &para->member.para.border,
1128 tableDef->border);
1129 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1131 WCHAR tab = '\t';
1132 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1133 tableDef->numCellsInserted++;
1135 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1136 if (!tableDef->numCellsDefined)
1137 pFmt->wEffects &= ~PFE_TABLE;
1138 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1139 tableDef->numCellsInserted = 0;
1141 break;
1143 case rtfTab:
1144 case rtfPar:
1145 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1146 ME_DisplayItem *para;
1147 PARAFORMAT2 *pFmt;
1148 RTFFlushOutputBuffer(info);
1149 para = info->editor->pCursors[0].pPara;
1150 pFmt = para->member.para.pFmt;
1151 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1153 /* rtfPar is treated like a space within a table. */
1154 info->rtfClass = rtfText;
1155 info->rtfMajor = ' ';
1157 else if (info->rtfMinor == rtfPar && tableDef)
1158 tableDef->numCellsInserted = 0;
1160 break;
1164 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1165 const SIZEL* sz)
1167 LPOLEOBJECT lpObject = NULL;
1168 LPSTORAGE lpStorage = NULL;
1169 LPOLECLIENTSITE lpClientSite = NULL;
1170 LPDATAOBJECT lpDataObject = NULL;
1171 LPOLECACHE lpOleCache = NULL;
1172 STGMEDIUM stgm;
1173 FORMATETC fm;
1174 CLSID clsid;
1175 BOOL ret = FALSE;
1176 DWORD conn;
1178 if (hemf)
1180 stgm.tymed = TYMED_ENHMF;
1181 stgm.u.hEnhMetaFile = hemf;
1182 fm.cfFormat = CF_ENHMETAFILE;
1184 else if (hbmp)
1186 stgm.tymed = TYMED_GDI;
1187 stgm.u.hBitmap = hbmp;
1188 fm.cfFormat = CF_BITMAP;
1190 stgm.pUnkForRelease = NULL;
1192 fm.ptd = NULL;
1193 fm.dwAspect = DVASPECT_CONTENT;
1194 fm.lindex = -1;
1195 fm.tymed = stgm.tymed;
1197 if (!info->lpRichEditOle)
1199 CreateIRichEditOle(NULL, info->editor, (VOID**)&info->lpRichEditOle);
1202 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1203 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1204 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1205 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1206 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1207 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1208 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1209 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1211 REOBJECT reobject;
1213 reobject.cbStruct = sizeof(reobject);
1214 reobject.cp = REO_CP_SELECTION;
1215 reobject.clsid = clsid;
1216 reobject.poleobj = lpObject;
1217 reobject.pstg = lpStorage;
1218 reobject.polesite = lpClientSite;
1219 /* convert from twips to .01 mm */
1220 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1221 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1222 reobject.dvaspect = DVASPECT_CONTENT;
1223 reobject.dwFlags = 0; /* FIXME */
1224 reobject.dwUser = 0;
1226 ME_InsertOLEFromCursor(info->editor, &reobject, 0);
1227 ret = TRUE;
1230 if (lpObject) IOleObject_Release(lpObject);
1231 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1232 if (lpStorage) IStorage_Release(lpStorage);
1233 if (lpDataObject) IDataObject_Release(lpDataObject);
1234 if (lpOleCache) IOleCache_Release(lpOleCache);
1236 return ret;
1239 static void ME_RTFReadPictGroup(RTF_Info *info)
1241 SIZEL sz;
1242 BYTE* buffer = NULL;
1243 unsigned bufsz, bufidx;
1244 BOOL flip;
1245 BYTE val;
1246 METAFILEPICT mfp;
1247 HENHMETAFILE hemf;
1248 HBITMAP hbmp;
1249 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1251 RTFGetToken (info);
1252 if (info->rtfClass == rtfEOF)
1253 return;
1254 mfp.mm = MM_TEXT;
1255 /* fetch picture type */
1256 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1258 mfp.mm = info->rtfParam;
1259 gfx = gfx_metafile;
1261 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1263 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1264 gfx = gfx_dib;
1266 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1268 gfx = gfx_enhmetafile;
1270 else
1272 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1273 goto skip_group;
1275 sz.cx = sz.cy = 0;
1276 /* fetch picture attributes */
1277 for (;;)
1279 RTFGetToken (info);
1280 if (info->rtfClass == rtfEOF)
1281 return;
1282 if (info->rtfClass == rtfText)
1283 break;
1284 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1286 ERR("Expected picture attribute (%d %d)\n",
1287 info->rtfClass, info->rtfMajor);
1288 goto skip_group;
1290 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1292 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1294 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1296 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1298 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1299 sz.cx = info->rtfParam;
1300 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1301 sz.cy = info->rtfParam;
1302 else
1303 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1305 /* fetch picture data */
1306 bufsz = 1024;
1307 bufidx = 0;
1308 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1309 val = info->rtfMajor;
1310 for (flip = TRUE;; flip = !flip)
1312 RTFGetToken (info);
1313 if (info->rtfClass == rtfEOF)
1315 HeapFree(GetProcessHeap(), 0, buffer);
1316 return; /* Warn ?? */
1318 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1319 break;
1320 if (info->rtfClass != rtfText) goto skip_group;
1321 if (flip)
1323 if (bufidx >= bufsz &&
1324 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1325 goto skip_group;
1326 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1328 else
1329 val = info->rtfMajor;
1331 if (flip) FIXME("wrong hex string\n");
1333 switch (gfx)
1335 case gfx_enhmetafile:
1336 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1337 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1338 break;
1339 case gfx_metafile:
1340 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1341 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1342 break;
1343 case gfx_dib:
1345 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1346 HDC hdc = GetDC(0);
1347 unsigned nc = bi->bmiHeader.biClrUsed;
1349 /* not quite right, especially for bitfields type of compression */
1350 if (!nc && bi->bmiHeader.biBitCount <= 8)
1351 nc = 1 << bi->bmiHeader.biBitCount;
1352 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1353 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1354 bi, DIB_RGB_COLORS)))
1355 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1356 ReleaseDC(0, hdc);
1358 break;
1359 default:
1360 break;
1362 HeapFree(GetProcessHeap(), 0, buffer);
1363 RTFRouteToken (info); /* feed "}" back to router */
1364 return;
1365 skip_group:
1366 HeapFree(GetProcessHeap(), 0, buffer);
1367 RTFSkipGroup(info);
1368 RTFRouteToken(info); /* feed "}" back to router */
1371 /* for now, lookup the \result part and use it, whatever the object */
1372 static void ME_RTFReadObjectGroup(RTF_Info *info)
1374 for (;;)
1376 RTFGetToken (info);
1377 if (info->rtfClass == rtfEOF)
1378 return;
1379 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1380 break;
1381 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1383 RTFGetToken (info);
1384 if (info->rtfClass == rtfEOF)
1385 return;
1386 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1388 int level = 1;
1390 while (RTFGetToken (info) != rtfEOF)
1392 if (info->rtfClass == rtfGroup)
1394 if (info->rtfMajor == rtfBeginGroup) level++;
1395 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1397 RTFRouteToken(info);
1400 else RTFSkipGroup(info);
1401 continue;
1403 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1405 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1406 return;
1409 RTFRouteToken(info); /* feed "}" back to router */
1412 static void ME_RTFReadHook(RTF_Info *info)
1414 switch(info->rtfClass)
1416 case rtfGroup:
1417 switch(info->rtfMajor)
1419 case rtfBeginGroup:
1420 if (info->stackTop < maxStack) {
1421 info->stack[info->stackTop].style = info->style;
1422 ME_AddRefStyle(info->style);
1423 info->stack[info->stackTop].codePage = info->codePage;
1424 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1426 info->stackTop++;
1427 info->styleChanged = FALSE;
1428 break;
1429 case rtfEndGroup:
1431 RTFFlushOutputBuffer(info);
1432 info->stackTop--;
1433 if (info->stackTop <= 0)
1434 info->rtfClass = rtfEOF;
1435 if (info->stackTop < 0)
1436 return;
1438 ME_ReleaseStyle(info->style);
1439 info->style = info->stack[info->stackTop].style;
1440 info->codePage = info->stack[info->stackTop].codePage;
1441 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1442 break;
1445 break;
1449 void
1450 ME_StreamInFill(ME_InStream *stream)
1452 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1453 (BYTE *)stream->buffer,
1454 sizeof(stream->buffer),
1455 (LONG *)&stream->dwSize);
1456 stream->dwUsed = 0;
1459 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1461 RTF_Info parser;
1462 ME_Style *style;
1463 int from, to, nUndoMode;
1464 int nEventMask = editor->nEventMask;
1465 ME_InStream inStream;
1466 BOOL invalidRTF = FALSE;
1467 ME_Cursor *selStart, *selEnd;
1468 LRESULT num_read = 0; /* bytes read for SF_TEXT, non-control chars inserted for SF_RTF */
1470 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1471 editor->nEventMask = 0;
1473 ME_GetSelectionOfs(editor, &from, &to);
1474 if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1476 ME_GetSelection(editor, &selStart, &selEnd);
1477 style = ME_GetSelectionInsertStyle(editor);
1479 ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1481 /* Don't insert text at the end of the table row */
1482 if (!editor->bEmulateVersion10) { /* v4.1 */
1483 ME_DisplayItem *para = editor->pCursors->pPara;
1484 if (para->member.para.nFlags & MEPF_ROWEND)
1486 para = para->member.para.next_para;
1487 editor->pCursors[0].pPara = para;
1488 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1489 editor->pCursors[0].nOffset = 0;
1491 if (para->member.para.nFlags & MEPF_ROWSTART)
1493 para = para->member.para.next_para;
1494 editor->pCursors[0].pPara = para;
1495 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1496 editor->pCursors[0].nOffset = 0;
1498 editor->pCursors[1] = editor->pCursors[0];
1499 } else { /* v1.0 - 3.0 */
1500 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1501 ME_IsInTable(editor->pCursors[0].pRun))
1502 return 0;
1504 } else {
1505 style = editor->pBuffer->pDefaultStyle;
1506 ME_AddRefStyle(style);
1507 ME_SetSelection(editor, 0, 0);
1508 ME_InternalDeleteText(editor, &editor->pCursors[1],
1509 ME_GetTextLength(editor), FALSE);
1510 from = to = 0;
1511 ME_ClearTempStyle(editor);
1512 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1516 /* Back up undo mode to a local variable */
1517 nUndoMode = editor->nUndoMode;
1519 /* Only create an undo if SFF_SELECTION is set */
1520 if (!(format & SFF_SELECTION))
1521 editor->nUndoMode = umIgnore;
1523 inStream.editstream = stream;
1524 inStream.editstream->dwError = 0;
1525 inStream.dwSize = 0;
1526 inStream.dwUsed = 0;
1528 if (format & SF_RTF)
1530 /* Check if it's really RTF, and if it is not, use plain text */
1531 ME_StreamInFill(&inStream);
1532 if (!inStream.editstream->dwError)
1534 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1535 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1537 invalidRTF = TRUE;
1538 inStream.editstream->dwError = -16;
1543 if (!invalidRTF && !inStream.editstream->dwError)
1545 if (format & SF_RTF) {
1546 from = ME_GetCursorOfs(&editor->pCursors[0]);
1548 /* setup the RTF parser */
1549 memset(&parser, 0, sizeof parser);
1550 RTFSetEditStream(&parser, &inStream);
1551 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1552 parser.editor = editor;
1553 parser.style = style;
1554 WriterInit(&parser);
1555 RTFInit(&parser);
1556 RTFSetReadHook(&parser, ME_RTFReadHook);
1557 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1558 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1559 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1561 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1562 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1564 BeginFile(&parser);
1566 /* do the parsing */
1567 RTFRead(&parser);
1568 RTFFlushOutputBuffer(&parser);
1569 if (!editor->bEmulateVersion10) { /* v4.1 */
1570 if (parser.tableDef && parser.tableDef->tableRowStart &&
1571 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1573 /* Delete any incomplete table row at the end of the rich text. */
1574 int nOfs, nChars;
1575 ME_DisplayItem *para;
1577 parser.rtfMinor = rtfRow;
1578 /* Complete the table row before deleting it.
1579 * By doing it this way we will have the current paragraph format set
1580 * properly to reflect that is not in the complete table, and undo items
1581 * will be added for this change to the current paragraph format. */
1582 if (parser.nestingLevel > 0)
1584 while (parser.nestingLevel > 1)
1585 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1586 para = parser.tableDef->tableRowStart;
1587 ME_RTFSpecialCharHook(&parser);
1588 } else {
1589 para = parser.tableDef->tableRowStart;
1590 ME_RTFSpecialCharHook(&parser);
1591 assert(para->member.para.nFlags & MEPF_ROWEND);
1592 para = para->member.para.next_para;
1595 editor->pCursors[1].pPara = para;
1596 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1597 editor->pCursors[1].nOffset = 0;
1598 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1599 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1600 ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1601 if (parser.tableDef)
1602 parser.tableDef->tableRowStart = NULL;
1605 ME_CheckTablesForCorruption(editor);
1606 RTFDestroy(&parser);
1607 if (parser.lpRichEditOle)
1608 IRichEditOle_Release(parser.lpRichEditOle);
1610 if (parser.stackTop > 0)
1612 while (--parser.stackTop >= 0)
1614 ME_ReleaseStyle(parser.style);
1615 parser.style = parser.stack[parser.stackTop].style;
1617 if (!inStream.editstream->dwError)
1618 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1621 /* Remove last line break, as mandated by tests. This is not affected by
1622 CR/LF counters, since RTF streaming presents only \para tokens, which
1623 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1625 if (stripLastCR && !(format & SFF_SELECTION)) {
1626 int newto;
1627 ME_GetSelection(editor, &selStart, &selEnd);
1628 newto = ME_GetCursorOfs(selEnd);
1629 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1630 WCHAR lastchar[3] = {'\0', '\0'};
1631 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1632 ME_Cursor linebreakCursor = *selEnd;
1634 ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1635 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, FALSE, FALSE);
1636 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1637 ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1641 to = ME_GetCursorOfs(&editor->pCursors[0]);
1642 num_read = to - from;
1644 style = parser.style;
1646 else if (format & SF_TEXT)
1647 num_read = ME_StreamInText(editor, format, &inStream, style);
1648 else
1649 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1650 /* put the cursor at the top */
1651 if (!(format & SFF_SELECTION))
1652 ME_SetSelection(editor, 0, 0);
1655 /* Restore saved undo mode */
1656 editor->nUndoMode = nUndoMode;
1658 /* even if we didn't add an undo, we need to commit anything on the stack */
1659 ME_CommitUndo(editor);
1661 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1662 if (!(format & SFF_SELECTION))
1663 ME_EmptyUndoStack(editor);
1665 ME_ReleaseStyle(style);
1666 editor->nEventMask = nEventMask;
1667 ME_UpdateRepaint(editor, FALSE);
1668 if (!(format & SFF_SELECTION)) {
1669 ME_ClearTempStyle(editor);
1671 ITextHost_TxShowCaret(editor->texthost, FALSE);
1672 ME_MoveCaret(editor);
1673 ITextHost_TxShowCaret(editor->texthost, TRUE);
1674 ME_SendSelChange(editor);
1675 ME_SendRequestResize(editor, FALSE);
1677 return num_read;
1681 typedef struct tagME_RTFStringStreamStruct
1683 char *string;
1684 int pos;
1685 int length;
1686 } ME_RTFStringStreamStruct;
1688 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1690 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1691 int count;
1693 count = min(cb, pStruct->length - pStruct->pos);
1694 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1695 pStruct->pos += count;
1696 *pcb = count;
1697 return 0;
1700 static void
1701 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1703 EDITSTREAM es;
1704 ME_RTFStringStreamStruct data;
1706 data.string = string;
1707 data.length = strlen(string);
1708 data.pos = 0;
1709 es.dwCookie = (DWORD_PTR)&data;
1710 es.pfnCallback = ME_ReadFromRTFString;
1711 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1715 static int
1716 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1718 const int nLen = lstrlenW(text);
1719 const int nTextLen = ME_GetTextLength(editor);
1720 int nMin, nMax;
1721 ME_Cursor cursor;
1722 WCHAR wLastChar = ' ';
1724 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1725 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1727 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1728 FIXME("Flags 0x%08x not implemented\n",
1729 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1731 nMin = chrg->cpMin;
1732 if (chrg->cpMax == -1)
1733 nMax = nTextLen;
1734 else
1735 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1737 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1738 if (editor->bEmulateVersion10 && nMax == nTextLen)
1740 flags |= FR_DOWN;
1743 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1744 if (editor->bEmulateVersion10 && nMax < nMin)
1746 if (chrgText)
1748 chrgText->cpMin = -1;
1749 chrgText->cpMax = -1;
1751 return -1;
1754 /* when searching up, if cpMin < cpMax, then instead of searching
1755 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1756 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1757 * case, it is always bigger than cpMin.
1759 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1761 int nSwap = nMax;
1763 nMax = nMin > nTextLen ? nTextLen : nMin;
1764 if (nMin < nSwap || chrg->cpMax == -1)
1765 nMin = 0;
1766 else
1767 nMin = nSwap;
1770 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1772 if (chrgText)
1773 chrgText->cpMin = chrgText->cpMax = -1;
1774 return -1;
1777 if (flags & FR_DOWN) /* Forward search */
1779 /* If possible, find the character before where the search starts */
1780 if ((flags & FR_WHOLEWORD) && nMin)
1782 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1783 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1784 ME_MoveCursorChars(editor, &cursor, 1);
1785 } else {
1786 ME_CursorFromCharOfs(editor, nMin, &cursor);
1789 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1791 ME_DisplayItem *pCurItem = cursor.pRun;
1792 int nCurStart = cursor.nOffset;
1793 int nMatched = 0;
1795 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1797 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1798 break;
1800 nMatched++;
1801 if (nMatched == nLen)
1803 ME_DisplayItem *pNextItem = pCurItem;
1804 int nNextStart = nCurStart;
1805 WCHAR wNextChar;
1807 /* Check to see if next character is a whitespace */
1808 if (flags & FR_WHOLEWORD)
1810 if (nCurStart + nMatched == pCurItem->member.run.len)
1812 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1813 nNextStart = -nMatched;
1816 if (pNextItem)
1817 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1818 else
1819 wNextChar = ' ';
1821 if (isalnumW(wNextChar))
1822 break;
1825 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1826 if (chrgText)
1828 chrgText->cpMin = cursor.nOffset;
1829 chrgText->cpMax = cursor.nOffset + nLen;
1831 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1832 return cursor.nOffset;
1834 if (nCurStart + nMatched == pCurItem->member.run.len)
1836 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1837 nCurStart = -nMatched;
1840 if (pCurItem)
1841 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1842 else
1843 wLastChar = ' ';
1845 cursor.nOffset++;
1846 if (cursor.nOffset == cursor.pRun->member.run.len)
1848 ME_NextRun(&cursor.pPara, &cursor.pRun);
1849 cursor.nOffset = 0;
1853 else /* Backward search */
1855 /* If possible, find the character after where the search ends */
1856 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1858 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1859 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1860 ME_MoveCursorChars(editor, &cursor, -1);
1861 } else {
1862 ME_CursorFromCharOfs(editor, nMax, &cursor);
1865 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1867 ME_DisplayItem *pCurItem = cursor.pRun;
1868 ME_DisplayItem *pCurPara = cursor.pPara;
1869 int nCurEnd = cursor.nOffset;
1870 int nMatched = 0;
1872 if (nCurEnd == 0)
1874 ME_PrevRun(&pCurPara, &pCurItem);
1875 nCurEnd = pCurItem->member.run.len;
1878 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1879 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1881 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1882 break;
1884 nMatched++;
1885 if (nMatched == nLen)
1887 ME_DisplayItem *pPrevItem = pCurItem;
1888 int nPrevEnd = nCurEnd;
1889 WCHAR wPrevChar;
1890 int nStart;
1892 /* Check to see if previous character is a whitespace */
1893 if (flags & FR_WHOLEWORD)
1895 if (nPrevEnd - nMatched == 0)
1897 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1898 if (pPrevItem)
1899 nPrevEnd = pPrevItem->member.run.len + nMatched;
1902 if (pPrevItem)
1903 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1904 else
1905 wPrevChar = ' ';
1907 if (isalnumW(wPrevChar))
1908 break;
1911 nStart = pCurPara->member.para.nCharOfs
1912 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1913 if (chrgText)
1915 chrgText->cpMin = nStart;
1916 chrgText->cpMax = nStart + nLen;
1918 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1919 return nStart;
1921 if (nCurEnd - nMatched == 0)
1923 ME_PrevRun(&pCurPara, &pCurItem);
1924 /* Don't care about pCurItem becoming NULL here; it's already taken
1925 * care of in the exterior loop condition */
1926 nCurEnd = pCurItem->member.run.len + nMatched;
1929 if (pCurItem)
1930 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1931 else
1932 wLastChar = ' ';
1934 cursor.nOffset--;
1935 if (cursor.nOffset < 0)
1937 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1938 cursor.nOffset = cursor.pRun->member.run.len;
1942 TRACE("not found\n");
1943 if (chrgText)
1944 chrgText->cpMin = chrgText->cpMax = -1;
1945 return -1;
1948 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1950 int nChars;
1951 ME_Cursor start;
1953 if (!ex->cb || !pText) return 0;
1955 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1956 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1958 if (ex->flags & GT_SELECTION)
1960 int from, to;
1961 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1962 start = editor->pCursors[nStartCur];
1963 nChars = to - from;
1965 else
1967 ME_SetCursorToStart(editor, &start);
1968 nChars = INT_MAX;
1970 if (ex->codepage == CP_UNICODE)
1972 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1973 &start, nChars, ex->flags & GT_USECRLF, FALSE);
1975 else
1977 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1978 we can just take a bigger buffer? :)
1979 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1980 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1982 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1983 DWORD buflen;
1984 LPWSTR buffer;
1985 LRESULT rc;
1987 buflen = min(crlfmul * nChars, ex->cb - 1);
1988 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1990 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF, FALSE);
1991 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1992 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1993 if (rc) rc--; /* do not count 0 terminator */
1995 heap_free(buffer);
1996 return rc;
2000 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2001 const ME_Cursor *start, int nLen, BOOL unicode)
2003 if (!strText) return 0;
2004 if (unicode) {
2005 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE, FALSE);
2006 } else {
2007 int nChars;
2008 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2009 if (!p) return 0;
2010 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE, FALSE);
2011 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2012 nLen+1, NULL, NULL);
2013 FREE_OBJ(p);
2014 return nChars;
2018 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2020 int end;
2022 TRACE("%d - %d\n", to, from );
2024 ME_InvalidateSelection( editor );
2025 end = ME_SetSelection( editor, to, from );
2026 ME_InvalidateSelection( editor );
2027 ITextHost_TxShowCaret( editor->texthost, FALSE );
2028 ME_ShowCaret( editor );
2029 ME_SendSelChange( editor );
2031 return end;
2034 typedef struct tagME_GlobalDestStruct
2036 HGLOBAL hData;
2037 int nLength;
2038 } ME_GlobalDestStruct;
2040 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2042 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2043 int i;
2044 WORD *pSrc, *pDest;
2046 cb = cb >> 1;
2047 pDest = (WORD *)lpBuff;
2048 pSrc = GlobalLock(pData->hData);
2049 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2050 pDest[i] = pSrc[pData->nLength+i];
2052 pData->nLength += i;
2053 *pcb = 2*i;
2054 GlobalUnlock(pData->hData);
2055 return 0;
2058 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2060 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2061 int i;
2062 BYTE *pSrc, *pDest;
2064 pDest = lpBuff;
2065 pSrc = GlobalLock(pData->hData);
2066 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2067 pDest[i] = pSrc[pData->nLength+i];
2069 pData->nLength += i;
2070 *pcb = i;
2071 GlobalUnlock(pData->hData);
2072 return 0;
2075 static BOOL ME_Paste(ME_TextEditor *editor)
2077 DWORD dwFormat = 0;
2078 EDITSTREAM es;
2079 ME_GlobalDestStruct gds;
2080 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2081 UINT cf = 0;
2083 if (IsClipboardFormatAvailable(nRTFFormat))
2084 cf = nRTFFormat, dwFormat = SF_RTF;
2085 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2086 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2087 else
2088 return FALSE;
2090 if (!OpenClipboard(editor->hWnd))
2091 return FALSE;
2092 gds.hData = GetClipboardData(cf);
2093 gds.nLength = 0;
2094 es.dwCookie = (DWORD_PTR)&gds;
2095 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2096 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2098 CloseClipboard();
2099 return TRUE;
2102 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2104 LPDATAOBJECT dataObj = NULL;
2105 HRESULT hr = S_OK;
2107 if (editor->cPasswordMask)
2108 return FALSE; /* Copying or Cutting masked text isn't allowed */
2110 if(editor->lpOleCallback)
2112 CHARRANGE range;
2113 range.cpMin = ME_GetCursorOfs(start);
2114 range.cpMax = range.cpMin + nChars;
2115 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2117 if(FAILED(hr) || !dataObj)
2118 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2119 if(SUCCEEDED(hr)) {
2120 hr = OleSetClipboard(dataObj);
2121 IDataObject_Release(dataObj);
2123 return SUCCEEDED(hr);
2126 /* helper to send a msg filter notification */
2127 static BOOL
2128 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2130 MSGFILTER msgf;
2132 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2133 msgf.nmhdr.hwndFrom = editor->hWnd;
2134 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2135 msgf.nmhdr.code = EN_MSGFILTER;
2136 msgf.msg = msg;
2137 msgf.wParam = *wParam;
2138 msgf.lParam = *lParam;
2139 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2140 return FALSE;
2141 *wParam = msgf.wParam;
2142 *lParam = msgf.lParam;
2143 msgf.wParam = *wParam;
2145 return TRUE;
2148 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2150 ME_DisplayItem *startPara, *endPara;
2151 ME_DisplayItem *prev_para;
2152 ME_Cursor *from, *to;
2153 ME_Cursor start;
2154 int nChars;
2156 if (!editor->AutoURLDetect_bEnable) return;
2158 ME_GetSelection(editor, &from, &to);
2160 /* Find paragraph previous to the one that contains start cursor */
2161 startPara = from->pPara;
2162 prev_para = startPara->member.para.prev_para;
2163 if (prev_para->type == diParagraph) startPara = prev_para;
2165 /* Find paragraph that contains end cursor */
2166 endPara = to->pPara->member.para.next_para;
2168 start.pPara = startPara;
2169 start.pRun = ME_FindItemFwd(startPara, diRun);
2170 start.nOffset = 0;
2171 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2173 ME_UpdateLinkAttribute(editor, &start, nChars);
2176 static BOOL
2177 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2179 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2180 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2182 if (editor->bMouseCaptured)
2183 return FALSE;
2184 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2185 editor->nSelectionType = stPosition;
2187 switch (nKey)
2189 case VK_LEFT:
2190 case VK_RIGHT:
2191 case VK_HOME:
2192 case VK_END:
2193 editor->nUDArrowX = -1;
2194 /* fall through */
2195 case VK_UP:
2196 case VK_DOWN:
2197 case VK_PRIOR:
2198 case VK_NEXT:
2199 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2200 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2201 return TRUE;
2202 case VK_BACK:
2203 case VK_DELETE:
2204 editor->nUDArrowX = -1;
2205 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2206 if (editor->styleFlags & ES_READONLY)
2207 return FALSE;
2208 if (ME_IsSelection(editor))
2210 ME_DeleteSelection(editor);
2211 ME_CommitUndo(editor);
2213 else if (nKey == VK_DELETE)
2215 /* Delete stops group typing.
2216 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2217 ME_DeleteTextAtCursor(editor, 1, 1);
2218 ME_CommitUndo(editor);
2220 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2222 BOOL bDeletionSucceeded;
2223 /* Backspace can be grouped for a single undo */
2224 ME_ContinueCoalescingTransaction(editor);
2225 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2226 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2227 /* Deletion was prevented so the cursor is moved back to where it was.
2228 * (e.g. this happens when trying to delete cell boundaries)
2230 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2232 ME_CommitCoalescingUndo(editor);
2234 else
2235 return TRUE;
2236 ME_MoveCursorFromTableRowStartParagraph(editor);
2237 ME_UpdateSelectionLinkAttribute(editor);
2238 ME_UpdateRepaint(editor, FALSE);
2239 ME_SendRequestResize(editor, FALSE);
2240 return TRUE;
2241 case VK_RETURN:
2242 if (editor->bDialogMode)
2244 if (ctrl_is_down)
2245 return TRUE;
2247 if (!(editor->styleFlags & ES_WANTRETURN))
2249 if (editor->hwndParent)
2251 DWORD dw;
2252 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2253 if (HIWORD(dw) == DC_HASDEFID)
2255 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2256 if (hwDefCtrl)
2258 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2259 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2263 return TRUE;
2267 if (editor->styleFlags & ES_MULTILINE)
2269 ME_Cursor cursor = editor->pCursors[0];
2270 ME_DisplayItem *para = cursor.pPara;
2271 int from, to;
2272 const WCHAR endl = '\r';
2273 const WCHAR endlv10[] = {'\r','\n'};
2274 ME_Style *style;
2276 if (editor->styleFlags & ES_READONLY) {
2277 MessageBeep(MB_ICONERROR);
2278 return TRUE;
2281 ME_GetSelectionOfs(editor, &from, &to);
2282 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2284 if (!editor->bEmulateVersion10) { /* v4.1 */
2285 if (para->member.para.nFlags & MEPF_ROWEND) {
2286 /* Add a new table row after this row. */
2287 para = ME_AppendTableRow(editor, para);
2288 para = para->member.para.next_para;
2289 editor->pCursors[0].pPara = para;
2290 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2291 editor->pCursors[0].nOffset = 0;
2292 editor->pCursors[1] = editor->pCursors[0];
2293 ME_CommitUndo(editor);
2294 ME_CheckTablesForCorruption(editor);
2295 ME_UpdateRepaint(editor, FALSE);
2296 return TRUE;
2298 else if (para == editor->pCursors[1].pPara &&
2299 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2300 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2301 !para->member.para.prev_para->member.para.nCharOfs)
2303 /* Insert a newline before the table. */
2304 para = para->member.para.prev_para;
2305 para->member.para.nFlags &= ~MEPF_ROWSTART;
2306 editor->pCursors[0].pPara = para;
2307 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2308 editor->pCursors[1] = editor->pCursors[0];
2309 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2310 editor->pCursors[0].pRun->member.run.style);
2311 para = editor->pBuffer->pFirst->member.para.next_para;
2312 ME_SetDefaultParaFormat(para->member.para.pFmt);
2313 para->member.para.nFlags = MEPF_REWRAP;
2314 editor->pCursors[0].pPara = para;
2315 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2316 editor->pCursors[1] = editor->pCursors[0];
2317 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2318 ME_CommitCoalescingUndo(editor);
2319 ME_CheckTablesForCorruption(editor);
2320 ME_UpdateRepaint(editor, FALSE);
2321 return TRUE;
2323 } else { /* v1.0 - 3.0 */
2324 ME_DisplayItem *para = cursor.pPara;
2325 if (ME_IsInTable(para))
2327 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2329 if (from == to) {
2330 ME_ContinueCoalescingTransaction(editor);
2331 para = ME_AppendTableRow(editor, para);
2332 editor->pCursors[0].pPara = para;
2333 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2334 editor->pCursors[0].nOffset = 0;
2335 editor->pCursors[1] = editor->pCursors[0];
2336 ME_CommitCoalescingUndo(editor);
2337 ME_UpdateRepaint(editor, FALSE);
2338 return TRUE;
2340 } else {
2341 ME_ContinueCoalescingTransaction(editor);
2342 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2343 !ME_IsInTable(para->member.para.prev_para))
2345 /* Insert newline before table */
2346 cursor.pRun = ME_FindItemBack(para, diRun);
2347 if (cursor.pRun) {
2348 editor->pCursors[0].pRun = cursor.pRun;
2349 editor->pCursors[0].pPara = para->member.para.prev_para;
2351 editor->pCursors[0].nOffset = 0;
2352 editor->pCursors[1] = editor->pCursors[0];
2353 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2354 editor->pCursors[0].pRun->member.run.style);
2355 } else {
2356 editor->pCursors[1] = editor->pCursors[0];
2357 para = ME_AppendTableRow(editor, para);
2358 editor->pCursors[0].pPara = para;
2359 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2360 editor->pCursors[0].nOffset = 0;
2361 editor->pCursors[1] = editor->pCursors[0];
2363 ME_CommitCoalescingUndo(editor);
2364 ME_UpdateRepaint(editor, FALSE);
2365 return TRUE;
2370 style = ME_GetInsertStyle(editor, 0);
2371 ME_SaveTempStyle(editor);
2372 ME_ContinueCoalescingTransaction(editor);
2373 if (shift_is_down)
2374 ME_InsertEndRowFromCursor(editor, 0);
2375 else
2376 if (!editor->bEmulateVersion10)
2377 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2378 else
2379 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2380 ME_ReleaseStyle(style);
2381 ME_CommitCoalescingUndo(editor);
2382 SetCursor(NULL);
2384 ME_UpdateSelectionLinkAttribute(editor);
2385 ME_UpdateRepaint(editor, FALSE);
2387 return TRUE;
2389 break;
2390 case VK_ESCAPE:
2391 if (editor->bDialogMode && editor->hwndParent)
2392 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2393 return TRUE;
2394 case VK_TAB:
2395 if (editor->bDialogMode && editor->hwndParent)
2396 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2397 return TRUE;
2398 case 'A':
2399 if (ctrl_is_down)
2401 handle_EM_EXSETSEL( editor, 0, -1 );
2402 return TRUE;
2404 break;
2405 case 'V':
2406 if (ctrl_is_down)
2407 return ME_Paste(editor);
2408 break;
2409 case 'C':
2410 case 'X':
2411 if (ctrl_is_down)
2413 BOOL result;
2414 int nOfs, nChars;
2415 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2416 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2418 nChars -= nOfs;
2419 result = ME_Copy(editor, selStart, nChars);
2420 if (result && nKey == 'X')
2422 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2423 ME_CommitUndo(editor);
2424 ME_UpdateRepaint(editor, TRUE);
2426 return result;
2428 break;
2429 case 'Z':
2430 if (ctrl_is_down)
2432 ME_Undo(editor);
2433 return TRUE;
2435 break;
2436 case 'Y':
2437 if (ctrl_is_down)
2439 ME_Redo(editor);
2440 return TRUE;
2442 break;
2444 default:
2445 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2446 editor->nUDArrowX = -1;
2447 if (ctrl_is_down)
2449 if (nKey == 'W')
2451 CHARFORMAT2W chf;
2452 char buf[2048];
2453 chf.cbSize = sizeof(chf);
2455 ME_GetSelectionCharFormat(editor, &chf);
2456 ME_DumpStyleToBuf(&chf, buf);
2457 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2459 if (nKey == 'Q')
2461 ME_CheckCharOffsets(editor);
2465 return FALSE;
2468 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2469 LPARAM flags, BOOL unicode)
2471 WCHAR wstr;
2473 if (editor->bMouseCaptured)
2474 return 0;
2476 if (unicode)
2477 wstr = (WCHAR)charCode;
2478 else
2480 CHAR charA = charCode;
2481 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2484 if (editor->styleFlags & ES_READONLY) {
2485 MessageBeep(MB_ICONERROR);
2486 return 0; /* FIXME really 0 ? */
2489 if ((unsigned)wstr >= ' ' || wstr == '\t')
2491 ME_Cursor cursor = editor->pCursors[0];
2492 ME_DisplayItem *para = cursor.pPara;
2493 int from, to;
2494 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2495 ME_GetSelectionOfs(editor, &from, &to);
2496 if (wstr == '\t' &&
2497 /* v4.1 allows tabs to be inserted with ctrl key down */
2498 !(ctrl_is_down && !editor->bEmulateVersion10))
2500 ME_DisplayItem *para;
2501 BOOL bSelectedRow = FALSE;
2503 para = cursor.pPara;
2504 if (ME_IsSelection(editor) &&
2505 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2506 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2507 para->member.para.prev_para->type == diParagraph)
2509 para = para->member.para.prev_para;
2510 bSelectedRow = TRUE;
2512 if (ME_IsInTable(para))
2514 ME_TabPressedInTable(editor, bSelectedRow);
2515 ME_CommitUndo(editor);
2516 return 0;
2518 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2519 if (para->member.para.nFlags & MEPF_ROWEND) {
2520 if (from == to) {
2521 para = para->member.para.next_para;
2522 if (para->member.para.nFlags & MEPF_ROWSTART)
2523 para = para->member.para.next_para;
2524 editor->pCursors[0].pPara = para;
2525 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2526 editor->pCursors[0].nOffset = 0;
2527 editor->pCursors[1] = editor->pCursors[0];
2530 } else { /* v1.0 - 3.0 */
2531 if (ME_IsInTable(cursor.pRun) &&
2532 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2533 from == to)
2535 /* Text should not be inserted at the end of the table. */
2536 MessageBeep(-1);
2537 return 0;
2540 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2541 /* WM_CHAR is restricted to nTextLimit */
2542 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2544 ME_Style *style = ME_GetInsertStyle(editor, 0);
2545 ME_SaveTempStyle(editor);
2546 ME_ContinueCoalescingTransaction(editor);
2547 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2548 ME_ReleaseStyle(style);
2549 ME_CommitCoalescingUndo(editor);
2550 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2553 ME_UpdateSelectionLinkAttribute(editor);
2554 ME_UpdateRepaint(editor, FALSE);
2556 return 0;
2559 /* Process the message and calculate the new click count.
2561 * returns: The click count if it is mouse down event, else returns 0. */
2562 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2563 LPARAM lParam)
2565 static int clickNum = 0;
2566 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2567 return 0;
2569 if ((msg == WM_LBUTTONDBLCLK) ||
2570 (msg == WM_RBUTTONDBLCLK) ||
2571 (msg == WM_MBUTTONDBLCLK) ||
2572 (msg == WM_XBUTTONDBLCLK))
2574 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2577 if ((msg == WM_LBUTTONDOWN) ||
2578 (msg == WM_RBUTTONDOWN) ||
2579 (msg == WM_MBUTTONDOWN) ||
2580 (msg == WM_XBUTTONDOWN))
2582 static MSG prevClickMsg;
2583 MSG clickMsg;
2584 /* Compare the editor instead of the hwnd so that the this
2585 * can still be done for windowless richedit controls. */
2586 clickMsg.hwnd = (HWND)editor;
2587 clickMsg.message = msg;
2588 clickMsg.wParam = wParam;
2589 clickMsg.lParam = lParam;
2590 clickMsg.time = GetMessageTime();
2591 clickMsg.pt.x = (short)LOWORD(lParam);
2592 clickMsg.pt.y = (short)HIWORD(lParam);
2593 if ((clickNum != 0) &&
2594 (clickMsg.message == prevClickMsg.message) &&
2595 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2596 (clickMsg.wParam == prevClickMsg.wParam) &&
2597 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2598 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2599 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2601 clickNum++;
2602 } else {
2603 clickNum = 1;
2605 prevClickMsg = clickMsg;
2606 } else {
2607 return 0;
2609 return clickNum;
2612 static BOOL ME_SetCursor(ME_TextEditor *editor)
2614 ME_Cursor cursor;
2615 POINT pt;
2616 BOOL isExact;
2617 SCROLLBARINFO sbi;
2618 DWORD messagePos = GetMessagePos();
2619 pt.x = (short)LOWORD(messagePos);
2620 pt.y = (short)HIWORD(messagePos);
2622 if (editor->hWnd)
2624 sbi.cbSize = sizeof(sbi);
2625 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2626 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2627 PtInRect(&sbi.rcScrollBar, pt))
2629 ITextHost_TxSetCursor(editor->texthost,
2630 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2631 return TRUE;
2633 sbi.cbSize = sizeof(sbi);
2634 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2635 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2636 PtInRect(&sbi.rcScrollBar, pt))
2638 ITextHost_TxSetCursor(editor->texthost,
2639 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2640 return TRUE;
2643 ITextHost_TxScreenToClient(editor->texthost, &pt);
2645 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2646 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2647 return TRUE;
2649 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2650 pt.y < editor->rcFormat.top &&
2651 pt.x < editor->rcFormat.left)
2653 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2654 return TRUE;
2656 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2658 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2659 ITextHost_TxSetCursor(editor->texthost,
2660 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2661 else /* v4.1 */
2662 ITextHost_TxSetCursor(editor->texthost,
2663 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2664 return TRUE;
2666 if (pt.x < editor->rcFormat.left)
2668 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2669 return TRUE;
2671 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2672 if (isExact)
2674 ME_Run *run;
2676 run = &cursor.pRun->member.run;
2677 if (run->style->fmt.dwMask & CFM_LINK &&
2678 run->style->fmt.dwEffects & CFE_LINK)
2680 ITextHost_TxSetCursor(editor->texthost,
2681 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2682 FALSE);
2683 return TRUE;
2686 if (ME_IsSelection(editor))
2688 int selStart, selEnd;
2689 int offset = ME_GetCursorOfs(&cursor);
2691 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2692 if (selStart <= offset && selEnd >= offset) {
2693 ITextHost_TxSetCursor(editor->texthost,
2694 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2695 FALSE);
2696 return TRUE;
2700 ITextHost_TxSetCursor(editor->texthost,
2701 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2702 return TRUE;
2705 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2707 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2708 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2709 editor->rcFormat.left += 1 + editor->selofs;
2710 editor->rcFormat.right -= 1;
2713 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2715 CHARRANGE selrange;
2716 HMENU menu;
2717 int seltype = 0;
2718 if(!editor->lpOleCallback || !editor->hWnd)
2719 return FALSE;
2720 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2721 if(selrange.cpMin == selrange.cpMax)
2722 seltype |= SEL_EMPTY;
2723 else
2725 /* FIXME: Handle objects */
2726 seltype |= SEL_TEXT;
2727 if(selrange.cpMax-selrange.cpMin > 1)
2728 seltype |= SEL_MULTICHAR;
2730 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2732 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2733 DestroyMenu(menu);
2735 return TRUE;
2738 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2740 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2741 int i;
2742 DWORD props;
2743 LONG selbarwidth;
2745 ed->hWnd = NULL;
2746 ed->hwndParent = NULL;
2747 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2748 ed->texthost = texthost;
2749 ed->reOle = NULL;
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 ed->wheel_remain = 0;
2863 OleInitialize(NULL);
2865 return ed;
2868 void ME_DestroyEditor(ME_TextEditor *editor)
2870 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2871 ME_DisplayItem *p = pFirst, *pNext = NULL;
2872 int i;
2874 ME_ClearTempStyle(editor);
2875 ME_EmptyUndoStack(editor);
2876 while(p) {
2877 pNext = p->next;
2878 ME_DestroyDisplayItem(p);
2879 p = pNext;
2881 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2882 for (i=0; i<HFONT_CACHE_SIZE; i++)
2884 if (editor->pFontCache[i].hFont)
2885 DeleteObject(editor->pFontCache[i].hFont);
2887 if (editor->rgbBackColor != -1)
2888 DeleteObject(editor->hbrBackground);
2889 if(editor->lpOleCallback)
2890 IRichEditOleCallback_Release(editor->lpOleCallback);
2891 ITextHost_Release(editor->texthost);
2892 if (editor->reOle)
2894 IRichEditOle_Release(editor->reOle);
2895 editor->reOle = NULL;
2897 OleUninitialize();
2899 FREE_OBJ(editor->pBuffer);
2900 FREE_OBJ(editor->pCursors);
2902 FREE_OBJ(editor);
2905 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2907 TRACE("\n");
2908 switch (fdwReason)
2910 case DLL_PROCESS_ATTACH:
2911 DisableThreadLibraryCalls(hinstDLL);
2912 me_heap = HeapCreate (0, 0x10000, 0);
2913 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2914 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2915 LookupInit();
2916 break;
2918 case DLL_PROCESS_DETACH:
2919 if (lpvReserved) break;
2920 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2921 UnregisterClassW(MSFTEDIT_CLASS, 0);
2922 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2923 UnregisterClassA("RichEdit50A", 0);
2924 if (ME_ListBoxRegistered)
2925 UnregisterClassW(REListBox20W, 0);
2926 if (ME_ComboBoxRegistered)
2927 UnregisterClassW(REComboBox20W, 0);
2928 LookupCleanup();
2929 HeapDestroy (me_heap);
2930 release_typelib();
2931 break;
2933 return TRUE;
2936 static inline int get_default_line_height( ME_TextEditor *editor )
2938 int height = 0;
2940 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2941 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2942 if (height <= 0) height = 24;
2944 return height;
2947 static inline int calc_wheel_change( int *remain, int amount_per_click )
2949 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2950 *remain -= WHEEL_DELTA * change / amount_per_click;
2951 return change;
2954 static const char * const edit_messages[] = {
2955 "EM_GETSEL",
2956 "EM_SETSEL",
2957 "EM_GETRECT",
2958 "EM_SETRECT",
2959 "EM_SETRECTNP",
2960 "EM_SCROLL",
2961 "EM_LINESCROLL",
2962 "EM_SCROLLCARET",
2963 "EM_GETMODIFY",
2964 "EM_SETMODIFY",
2965 "EM_GETLINECOUNT",
2966 "EM_LINEINDEX",
2967 "EM_SETHANDLE",
2968 "EM_GETHANDLE",
2969 "EM_GETTHUMB",
2970 "EM_UNKNOWN_BF",
2971 "EM_UNKNOWN_C0",
2972 "EM_LINELENGTH",
2973 "EM_REPLACESEL",
2974 "EM_UNKNOWN_C3",
2975 "EM_GETLINE",
2976 "EM_LIMITTEXT",
2977 "EM_CANUNDO",
2978 "EM_UNDO",
2979 "EM_FMTLINES",
2980 "EM_LINEFROMCHAR",
2981 "EM_UNKNOWN_CA",
2982 "EM_SETTABSTOPS",
2983 "EM_SETPASSWORDCHAR",
2984 "EM_EMPTYUNDOBUFFER",
2985 "EM_GETFIRSTVISIBLELINE",
2986 "EM_SETREADONLY",
2987 "EM_SETWORDBREAKPROC",
2988 "EM_GETWORDBREAKPROC",
2989 "EM_GETPASSWORDCHAR",
2990 "EM_SETMARGINS",
2991 "EM_GETMARGINS",
2992 "EM_GETLIMITTEXT",
2993 "EM_POSFROMCHAR",
2994 "EM_CHARFROMPOS",
2995 "EM_SETIMESTATUS",
2996 "EM_GETIMESTATUS"
2999 static const char * const richedit_messages[] = {
3000 "EM_CANPASTE",
3001 "EM_DISPLAYBAND",
3002 "EM_EXGETSEL",
3003 "EM_EXLIMITTEXT",
3004 "EM_EXLINEFROMCHAR",
3005 "EM_EXSETSEL",
3006 "EM_FINDTEXT",
3007 "EM_FORMATRANGE",
3008 "EM_GETCHARFORMAT",
3009 "EM_GETEVENTMASK",
3010 "EM_GETOLEINTERFACE",
3011 "EM_GETPARAFORMAT",
3012 "EM_GETSELTEXT",
3013 "EM_HIDESELECTION",
3014 "EM_PASTESPECIAL",
3015 "EM_REQUESTRESIZE",
3016 "EM_SELECTIONTYPE",
3017 "EM_SETBKGNDCOLOR",
3018 "EM_SETCHARFORMAT",
3019 "EM_SETEVENTMASK",
3020 "EM_SETOLECALLBACK",
3021 "EM_SETPARAFORMAT",
3022 "EM_SETTARGETDEVICE",
3023 "EM_STREAMIN",
3024 "EM_STREAMOUT",
3025 "EM_GETTEXTRANGE",
3026 "EM_FINDWORDBREAK",
3027 "EM_SETOPTIONS",
3028 "EM_GETOPTIONS",
3029 "EM_FINDTEXTEX",
3030 "EM_GETWORDBREAKPROCEX",
3031 "EM_SETWORDBREAKPROCEX",
3032 "EM_SETUNDOLIMIT",
3033 "EM_UNKNOWN_USER_83",
3034 "EM_REDO",
3035 "EM_CANREDO",
3036 "EM_GETUNDONAME",
3037 "EM_GETREDONAME",
3038 "EM_STOPGROUPTYPING",
3039 "EM_SETTEXTMODE",
3040 "EM_GETTEXTMODE",
3041 "EM_AUTOURLDETECT",
3042 "EM_GETAUTOURLDETECT",
3043 "EM_SETPALETTE",
3044 "EM_GETTEXTEX",
3045 "EM_GETTEXTLENGTHEX",
3046 "EM_SHOWSCROLLBAR",
3047 "EM_SETTEXTEX",
3048 "EM_UNKNOWN_USER_98",
3049 "EM_UNKNOWN_USER_99",
3050 "EM_SETPUNCTUATION",
3051 "EM_GETPUNCTUATION",
3052 "EM_SETWORDWRAPMODE",
3053 "EM_GETWORDWRAPMODE",
3054 "EM_SETIMECOLOR",
3055 "EM_GETIMECOLOR",
3056 "EM_SETIMEOPTIONS",
3057 "EM_GETIMEOPTIONS",
3058 "EM_CONVPOSITION",
3059 "EM_UNKNOWN_USER_109",
3060 "EM_UNKNOWN_USER_110",
3061 "EM_UNKNOWN_USER_111",
3062 "EM_UNKNOWN_USER_112",
3063 "EM_UNKNOWN_USER_113",
3064 "EM_UNKNOWN_USER_114",
3065 "EM_UNKNOWN_USER_115",
3066 "EM_UNKNOWN_USER_116",
3067 "EM_UNKNOWN_USER_117",
3068 "EM_UNKNOWN_USER_118",
3069 "EM_UNKNOWN_USER_119",
3070 "EM_SETLANGOPTIONS",
3071 "EM_GETLANGOPTIONS",
3072 "EM_GETIMECOMPMODE",
3073 "EM_FINDTEXTW",
3074 "EM_FINDTEXTEXW",
3075 "EM_RECONVERSION",
3076 "EM_SETIMEMODEBIAS",
3077 "EM_GETIMEMODEBIAS"
3080 static const char *
3081 get_msg_name(UINT msg)
3083 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3084 return edit_messages[msg - EM_GETSEL];
3085 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3086 return richedit_messages[msg - EM_CANPASTE];
3087 return "";
3090 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3092 int x,y;
3093 BOOL isExact;
3094 ME_Cursor cursor; /* The start of the clicked text. */
3096 ENLINK info;
3097 x = (short)LOWORD(lParam);
3098 y = (short)HIWORD(lParam);
3099 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3100 if (!isExact) return;
3102 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3103 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3104 { /* The clicked run has CFE_LINK set */
3105 ME_DisplayItem *di;
3107 info.nmhdr.hwndFrom = NULL;
3108 info.nmhdr.idFrom = 0;
3109 info.nmhdr.code = EN_LINK;
3110 info.msg = msg;
3111 info.wParam = wParam;
3112 info.lParam = lParam;
3113 cursor.nOffset = 0;
3115 /* find the first contiguous run with CFE_LINK set */
3116 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3117 for (di = cursor.pRun->prev;
3118 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3119 di = di->prev)
3121 info.chrg.cpMin -= di->member.run.len;
3124 /* find the last contiguous run with CFE_LINK set */
3125 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3126 for (di = cursor.pRun->next;
3127 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3128 di = di->next)
3130 info.chrg.cpMax += di->member.run.len;
3133 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3137 #define UNSUPPORTED_MSG(e) \
3138 case e: \
3139 FIXME(#e ": stub\n"); \
3140 *phresult = S_FALSE; \
3141 return 0;
3143 /* Handle messages for windowless and windoweded richedit controls.
3145 * The LRESULT that is returned is a return value for window procs,
3146 * and the phresult parameter is the COM return code needed by the
3147 * text services interface. */
3148 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3149 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3151 *phresult = S_OK;
3153 switch(msg) {
3155 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3156 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3157 UNSUPPORTED_MSG(EM_FMTLINES)
3158 UNSUPPORTED_MSG(EM_FORMATRANGE)
3159 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3160 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3161 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3162 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3163 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3164 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3165 UNSUPPORTED_MSG(EM_GETREDONAME)
3166 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3167 UNSUPPORTED_MSG(EM_GETUNDONAME)
3168 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3169 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3170 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3171 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3172 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3173 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3174 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3175 UNSUPPORTED_MSG(EM_SETMARGINS)
3176 UNSUPPORTED_MSG(EM_SETPALETTE)
3177 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3178 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3179 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3181 /* Messages specific to Richedit controls */
3183 case EM_STREAMIN:
3184 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3185 case EM_STREAMOUT:
3186 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3187 case WM_GETDLGCODE:
3189 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3191 if (lParam)
3192 editor->bDialogMode = TRUE;
3193 if (editor->styleFlags & ES_MULTILINE)
3194 code |= DLGC_WANTMESSAGE;
3195 if (!(editor->styleFlags & ES_SAVESEL))
3196 code |= DLGC_HASSETSEL;
3197 return code;
3199 case EM_EMPTYUNDOBUFFER:
3200 ME_EmptyUndoStack(editor);
3201 return 0;
3202 case EM_GETSEL:
3204 /* Note: wParam/lParam can be NULL */
3205 UINT from, to;
3206 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3207 PUINT pto = lParam ? (PUINT)lParam : &to;
3208 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3209 if ((*pfrom|*pto) & 0xFFFF0000)
3210 return -1;
3211 return MAKELONG(*pfrom,*pto);
3213 case EM_EXGETSEL:
3215 CHARRANGE *pRange = (CHARRANGE *)lParam;
3216 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3217 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3218 return 0;
3220 case EM_SETUNDOLIMIT:
3222 if ((int)wParam < 0)
3223 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3224 else
3225 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3226 /* Setting a max stack size keeps wine from getting killed
3227 for hogging memory. Windows allocates all this memory at once, so
3228 no program would realistically set a value above our maximum. */
3229 return editor->nUndoLimit;
3231 case EM_CANUNDO:
3232 return !list_empty( &editor->undo_stack );
3233 case EM_CANREDO:
3234 return !list_empty( &editor->redo_stack );
3235 case WM_UNDO: /* FIXME: actually not the same */
3236 case EM_UNDO:
3237 return ME_Undo(editor);
3238 case EM_REDO:
3239 return ME_Redo(editor);
3240 case EM_GETOPTIONS:
3242 /* these flags are equivalent to the ES_* counterparts */
3243 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3244 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3245 DWORD settings = editor->styleFlags & mask;
3247 return settings;
3249 case EM_SETOPTIONS:
3251 /* these flags are equivalent to ES_* counterparts, except for
3252 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3253 * but is still stored in editor->styleFlags. */
3254 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3255 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3256 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3257 DWORD settings = mask & editor->styleFlags;
3258 DWORD oldSettings = settings;
3259 DWORD changedSettings;
3261 switch(wParam)
3263 case ECOOP_SET:
3264 settings = lParam;
3265 break;
3266 case ECOOP_OR:
3267 settings |= lParam;
3268 break;
3269 case ECOOP_AND:
3270 settings &= lParam;
3271 break;
3272 case ECOOP_XOR:
3273 settings ^= lParam;
3275 changedSettings = oldSettings ^ settings;
3277 if (changedSettings) {
3278 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3280 if (changedSettings & ECO_SELECTIONBAR)
3282 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3283 if (settings & ECO_SELECTIONBAR) {
3284 assert(!editor->selofs);
3285 editor->selofs = SELECTIONBAR_WIDTH;
3286 editor->rcFormat.left += editor->selofs;
3287 } else {
3288 editor->rcFormat.left -= editor->selofs;
3289 editor->selofs = 0;
3291 ME_RewrapRepaint(editor);
3294 if (changedSettings & settings & ECO_VERTICAL)
3295 FIXME("ECO_VERTICAL not implemented yet!\n");
3296 if (changedSettings & settings & ECO_AUTOHSCROLL)
3297 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3298 if (changedSettings & settings & ECO_AUTOVSCROLL)
3299 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3300 if (changedSettings & settings & ECO_NOHIDESEL)
3301 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3302 if (changedSettings & settings & ECO_WANTRETURN)
3303 FIXME("ECO_WANTRETURN not implemented yet!\n");
3304 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3305 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3308 return settings;
3310 case EM_SETSEL:
3312 return handle_EM_EXSETSEL( editor, wParam, lParam );
3314 case EM_SETSCROLLPOS:
3316 POINT *point = (POINT *)lParam;
3317 ME_ScrollAbs(editor, point->x, point->y);
3318 return 0;
3320 case EM_AUTOURLDETECT:
3322 if (wParam==1 || wParam ==0)
3324 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3325 return 0;
3327 return E_INVALIDARG;
3329 case EM_GETAUTOURLDETECT:
3331 return editor->AutoURLDetect_bEnable;
3333 case EM_EXSETSEL:
3335 CHARRANGE range = *(CHARRANGE *)lParam;
3337 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3339 case EM_SHOWSCROLLBAR:
3341 DWORD flags;
3343 switch (wParam)
3345 case SB_HORZ:
3346 flags = WS_HSCROLL;
3347 break;
3348 case SB_VERT:
3349 flags = WS_VSCROLL;
3350 break;
3351 case SB_BOTH:
3352 flags = WS_HSCROLL|WS_VSCROLL;
3353 break;
3354 default:
3355 return 0;
3358 if (lParam) {
3359 editor->styleFlags |= flags;
3360 if (flags & WS_HSCROLL)
3361 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3362 editor->nTotalWidth > editor->sizeWindow.cx);
3363 if (flags & WS_VSCROLL)
3364 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3365 editor->nTotalLength > editor->sizeWindow.cy);
3366 } else {
3367 editor->styleFlags &= ~flags;
3368 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3370 return 0;
3372 case EM_SETTEXTEX:
3374 LPWSTR wszText;
3375 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3376 int from, to, len;
3377 ME_Style *style;
3378 BOOL bRtf, bUnicode, bSelection, bUTF8;
3379 int oldModify = editor->nModifyStep;
3380 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3382 if (!pStruct) return 0;
3384 /* If we detect ascii rtf at the start of the string,
3385 * we know it isn't unicode. */
3386 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3387 !strncmp((char *)lParam, "{\\urtf", 6)));
3388 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3389 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3391 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3392 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3393 pStruct->flags, pStruct->codepage);
3395 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3396 if (bSelection) {
3397 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3398 style = ME_GetSelectionInsertStyle(editor);
3399 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3400 } else {
3401 ME_Cursor start;
3402 ME_SetCursorToStart(editor, &start);
3403 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3404 style = editor->pBuffer->pDefaultStyle;
3407 if (bRtf) {
3408 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3409 if (bSelection) {
3410 /* FIXME: The length returned doesn't include the rtf control
3411 * characters, only the actual text. */
3412 len = lParam ? strlen((char *)lParam) : 0;
3414 } else {
3415 if (bUTF8 && !bUnicode) {
3416 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3417 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3418 ME_EndToUnicode(CP_UTF8, wszText);
3419 } else {
3420 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3421 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3422 ME_EndToUnicode(pStruct->codepage, wszText);
3426 if (bSelection) {
3427 ME_ReleaseStyle(style);
3428 ME_UpdateSelectionLinkAttribute(editor);
3429 } else {
3430 ME_Cursor cursor;
3431 len = 1;
3432 ME_SetCursorToStart(editor, &cursor);
3433 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3435 ME_CommitUndo(editor);
3436 if (!(pStruct->flags & ST_KEEPUNDO))
3438 editor->nModifyStep = oldModify;
3439 ME_EmptyUndoStack(editor);
3441 ME_UpdateRepaint(editor, FALSE);
3442 return len;
3444 case EM_SETBKGNDCOLOR:
3446 LRESULT lColor;
3447 if (editor->rgbBackColor != -1) {
3448 DeleteObject(editor->hbrBackground);
3449 lColor = editor->rgbBackColor;
3451 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3453 if (wParam)
3455 editor->rgbBackColor = -1;
3456 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3458 else
3460 editor->rgbBackColor = lParam;
3461 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3463 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3464 ITextHost_TxViewChange(editor->texthost, TRUE);
3465 return lColor;
3467 case EM_GETMODIFY:
3468 return editor->nModifyStep == 0 ? 0 : -1;
3469 case EM_SETMODIFY:
3471 if (wParam)
3472 editor->nModifyStep = 1;
3473 else
3474 editor->nModifyStep = 0;
3476 return 0;
3478 case EM_SETREADONLY:
3480 if (wParam)
3481 editor->styleFlags |= ES_READONLY;
3482 else
3483 editor->styleFlags &= ~ES_READONLY;
3484 return 1;
3486 case EM_SETEVENTMASK:
3488 DWORD nOldMask = editor->nEventMask;
3490 editor->nEventMask = lParam;
3491 return nOldMask;
3493 case EM_GETEVENTMASK:
3494 return editor->nEventMask;
3495 case EM_SETCHARFORMAT:
3497 CHARFORMAT2W buf, *p;
3498 BOOL bRepaint = TRUE;
3499 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3500 if (p == NULL) return 0;
3501 if (wParam & SCF_ALL) {
3502 if (editor->mode & TM_PLAINTEXT) {
3503 ME_SetDefaultCharFormat(editor, p);
3504 } else {
3505 ME_Cursor start;
3506 ME_SetCursorToStart(editor, &start);
3507 ME_SetCharFormat(editor, &start, NULL, p);
3508 editor->nModifyStep = 1;
3510 } else if (wParam & SCF_SELECTION) {
3511 if (editor->mode & TM_PLAINTEXT)
3512 return 0;
3513 if (wParam & SCF_WORD) {
3514 ME_Cursor start;
3515 ME_Cursor end = editor->pCursors[0];
3516 ME_MoveCursorWords(editor, &end, +1);
3517 start = end;
3518 ME_MoveCursorWords(editor, &start, -1);
3519 ME_SetCharFormat(editor, &start, &end, p);
3521 bRepaint = ME_IsSelection(editor);
3522 ME_SetSelectionCharFormat(editor, p);
3523 if (bRepaint) editor->nModifyStep = 1;
3524 } else { /* SCF_DEFAULT */
3525 ME_SetDefaultCharFormat(editor, p);
3527 ME_CommitUndo(editor);
3528 if (bRepaint)
3530 ME_WrapMarkedParagraphs(editor);
3531 ME_UpdateScrollBar(editor);
3532 ME_Repaint(editor);
3534 return 1;
3536 case EM_GETCHARFORMAT:
3538 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3539 if (dst->cbSize != sizeof(CHARFORMATA) &&
3540 dst->cbSize != sizeof(CHARFORMATW) &&
3541 dst->cbSize != sizeof(CHARFORMAT2A) &&
3542 dst->cbSize != sizeof(CHARFORMAT2W))
3543 return 0;
3544 tmp.cbSize = sizeof(tmp);
3545 if (!wParam)
3546 ME_GetDefaultCharFormat(editor, &tmp);
3547 else
3548 ME_GetSelectionCharFormat(editor, &tmp);
3549 ME_CopyToCFAny(dst, &tmp);
3550 return tmp.dwMask;
3552 case EM_SETPARAFORMAT:
3554 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3555 ME_WrapMarkedParagraphs(editor);
3556 ME_UpdateScrollBar(editor);
3557 ME_Repaint(editor);
3558 ME_CommitUndo(editor);
3559 return result;
3561 case EM_GETPARAFORMAT:
3562 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3563 return ((PARAFORMAT2 *)lParam)->dwMask;
3564 case EM_GETFIRSTVISIBLELINE:
3566 ME_DisplayItem *p = editor->pBuffer->pFirst;
3567 int y = editor->vert_si.nPos;
3568 int ypara = 0;
3569 int count = 0;
3570 int ystart, yend;
3571 while(p) {
3572 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3573 if (p->type == diTextEnd)
3574 break;
3575 if (p->type == diParagraph) {
3576 ypara = p->member.para.pt.y;
3577 continue;
3579 ystart = ypara + p->member.row.pt.y;
3580 yend = ystart + p->member.row.nHeight;
3581 if (y < yend) {
3582 break;
3584 count++;
3586 return count;
3588 case EM_HIDESELECTION:
3590 editor->bHideSelection = (wParam != 0);
3591 ME_InvalidateSelection(editor);
3592 return 0;
3594 case EM_LINESCROLL:
3596 if (!(editor->styleFlags & ES_MULTILINE))
3597 return FALSE;
3598 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3599 return TRUE;
3601 case WM_CLEAR:
3603 int from, to;
3604 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3605 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3606 ME_CommitUndo(editor);
3607 ME_UpdateRepaint(editor, TRUE);
3608 return 0;
3610 case EM_REPLACESEL:
3612 int from, to, nStartCursor;
3613 ME_Style *style;
3614 int len = 0;
3615 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3616 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3617 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3619 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3620 style = ME_GetSelectionInsertStyle(editor);
3621 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3622 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3623 ME_ReleaseStyle(style);
3624 /* drop temporary style if line end */
3626 * FIXME question: does abc\n mean: put abc,
3627 * clear temp style, put \n? (would require a change)
3629 if (len>0 && wszText[len-1] == '\n')
3630 ME_ClearTempStyle(editor);
3631 ME_EndToUnicode(codepage, wszText);
3632 ME_CommitUndo(editor);
3633 ME_UpdateSelectionLinkAttribute(editor);
3634 if (!wParam)
3635 ME_EmptyUndoStack(editor);
3636 ME_UpdateRepaint(editor, FALSE);
3637 return len;
3639 case EM_SCROLLCARET:
3640 ME_EnsureVisible(editor, &editor->pCursors[0]);
3641 return 0;
3642 case WM_SETFONT:
3644 LOGFONTW lf;
3645 CHARFORMAT2W fmt;
3646 HDC hDC;
3647 BOOL bRepaint = LOWORD(lParam);
3649 if (!wParam)
3650 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3651 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3652 hDC = ITextHost_TxGetDC(editor->texthost);
3653 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3654 ITextHost_TxReleaseDC(editor->texthost, hDC);
3655 if (editor->mode & TM_RICHTEXT) {
3656 ME_Cursor start;
3657 ME_SetCursorToStart(editor, &start);
3658 ME_SetCharFormat(editor, &start, NULL, &fmt);
3660 ME_SetDefaultCharFormat(editor, &fmt);
3662 ME_CommitUndo(editor);
3663 ME_MarkAllForWrapping(editor);
3664 ME_WrapMarkedParagraphs(editor);
3665 ME_UpdateScrollBar(editor);
3666 if (bRepaint)
3667 ME_Repaint(editor);
3668 return 0;
3670 case WM_SETTEXT:
3672 ME_Cursor cursor;
3673 ME_SetCursorToStart(editor, &cursor);
3674 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3675 if (lParam)
3677 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3678 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3679 !strncmp((char *)lParam, "{\\urtf", 6))
3681 /* Undocumented: WM_SETTEXT supports RTF text */
3682 ME_StreamInRTFString(editor, 0, (char *)lParam);
3684 else
3686 int textLen;
3687 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3688 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3689 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3690 if (textLen > 0)
3692 int len = -1;
3694 /* uses default style! */
3695 if (!(editor->styleFlags & ES_MULTILINE))
3697 WCHAR * p;
3699 p = wszText;
3700 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3701 len = p - wszText;
3703 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3705 ME_EndToUnicode(codepage, wszText);
3708 else
3709 TRACE("WM_SETTEXT - NULL\n");
3710 ME_SetCursorToStart(editor, &cursor);
3711 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3712 ME_SetSelection(editor, 0, 0);
3713 editor->nModifyStep = 0;
3714 ME_CommitUndo(editor);
3715 ME_EmptyUndoStack(editor);
3716 ME_UpdateRepaint(editor, FALSE);
3717 return 1;
3719 case EM_CANPASTE:
3721 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3722 if (IsClipboardFormatAvailable(nRTFFormat))
3723 return TRUE;
3724 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3725 return TRUE;
3726 return FALSE;
3728 case WM_PASTE:
3729 case WM_MBUTTONDOWN:
3730 ME_Paste(editor);
3731 return 0;
3732 case WM_CUT:
3733 case WM_COPY:
3735 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3736 int nChars = nTo - nFrom;
3737 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3739 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3741 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3742 ME_CommitUndo(editor);
3743 ME_UpdateRepaint(editor, TRUE);
3745 return 0;
3747 case WM_GETTEXTLENGTH:
3749 GETTEXTLENGTHEX how;
3751 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3752 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3753 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3754 return ME_GetTextLengthEx(editor, &how);
3756 case EM_GETTEXTLENGTHEX:
3757 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3758 case WM_GETTEXT:
3760 GETTEXTEX ex;
3761 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3762 ex.flags = GT_USECRLF;
3763 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3764 ex.lpDefaultChar = NULL;
3765 ex.lpUsedDefChar = NULL;
3766 return ME_GetTextEx(editor, &ex, lParam);
3768 case EM_GETTEXTEX:
3769 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3770 case EM_GETSELTEXT:
3772 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3773 ME_Cursor *from = &editor->pCursors[nStartCur];
3774 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3775 nTo - nFrom, unicode);
3777 case EM_GETSCROLLPOS:
3779 POINT *point = (POINT *)lParam;
3780 point->x = editor->horz_si.nPos;
3781 point->y = editor->vert_si.nPos;
3782 /* 16-bit scaled value is returned as stored in scrollinfo */
3783 if (editor->horz_si.nMax > 0xffff)
3784 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3785 if (editor->vert_si.nMax > 0xffff)
3786 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3787 return 1;
3789 case EM_GETTEXTRANGE:
3791 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3792 ME_Cursor start;
3793 int nStart = rng->chrg.cpMin;
3794 int nEnd = rng->chrg.cpMax;
3795 int textlength = ME_GetTextLength(editor);
3797 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3798 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3799 if (nStart < 0) return 0;
3800 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3801 nEnd = textlength;
3802 if (nStart >= nEnd) return 0;
3804 ME_CursorFromCharOfs(editor, nStart, &start);
3805 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3807 case EM_GETLINE:
3809 ME_DisplayItem *run;
3810 const unsigned int nMaxChars = *(WORD *) lParam;
3811 unsigned int nCharsLeft = nMaxChars;
3812 char *dest = (char *) lParam;
3813 BOOL wroteNull = FALSE;
3815 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3816 unicode ? "Unicode" : "Ansi");
3818 run = ME_FindRowWithNumber(editor, wParam);
3819 if (run == NULL)
3820 return 0;
3822 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3823 && run->type == diRun)
3825 WCHAR *str = get_text( &run->member.run, 0 );
3826 unsigned int nCopy;
3828 nCopy = min(nCharsLeft, run->member.run.len);
3830 if (unicode)
3831 memcpy(dest, str, nCopy * sizeof(WCHAR));
3832 else
3833 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3834 nCharsLeft, NULL, NULL);
3835 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3836 nCharsLeft -= nCopy;
3839 /* append line termination, space allowing */
3840 if (nCharsLeft > 0)
3842 if (unicode)
3843 *((WCHAR *)dest) = '\0';
3844 else
3845 *dest = '\0';
3846 nCharsLeft--;
3847 wroteNull = TRUE;
3850 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3851 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3853 case EM_GETLINECOUNT:
3855 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3856 int nRows = 0;
3858 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3860 while (item != editor->pBuffer->pLast)
3862 assert(item->type == diParagraph);
3863 prev_para = ME_FindItemBack(item, diRun);
3864 if (prev_para) {
3865 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3867 nRows += item->member.para.nRows;
3868 item = item->member.para.next_para;
3870 last_para = ME_FindItemBack(item, diRun);
3871 assert(last_para);
3872 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3873 if (editor->bEmulateVersion10 && prev_para &&
3874 last_para->member.run.nCharOfs == 0 &&
3875 prev_para->member.run.len == 1 &&
3876 *get_text( &prev_para->member.run, 0 ) == '\r')
3878 /* In 1.0 emulation, the last solitary \r at the very end of the text
3879 (if one exists) is NOT a line break.
3880 FIXME: this is an ugly hack. This should have a more regular model. */
3881 nRows--;
3884 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3885 return max(1, nRows);
3887 case EM_LINEFROMCHAR:
3889 if (wParam == -1)
3890 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3891 else
3892 return ME_RowNumberFromCharOfs(editor, wParam);
3894 case EM_EXLINEFROMCHAR:
3896 if (lParam == -1)
3897 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3898 else
3899 return ME_RowNumberFromCharOfs(editor, lParam);
3901 case EM_LINEINDEX:
3903 ME_DisplayItem *item, *para;
3904 int nCharOfs;
3906 if (wParam == -1)
3907 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3908 else
3909 item = ME_FindRowWithNumber(editor, wParam);
3910 if (!item)
3911 return -1;
3912 para = ME_GetParagraph(item);
3913 item = ME_FindItemFwd(item, diRun);
3914 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3915 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3916 return nCharOfs;
3918 case EM_LINELENGTH:
3920 ME_DisplayItem *item, *item_end;
3921 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3922 ME_DisplayItem *para, *run;
3924 if (wParam > ME_GetTextLength(editor))
3925 return 0;
3926 if (wParam == -1)
3928 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3929 return 0;
3931 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3932 item = ME_RowStart(run);
3933 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3934 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3935 if (item_end->type == diStartRow) {
3936 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3937 } else {
3938 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3939 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3940 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3942 nChars = nNextLineOfs - nThisLineOfs;
3943 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3944 return nChars;
3946 case EM_EXLIMITTEXT:
3948 if ((int)lParam < 0)
3949 return 0;
3950 if (lParam == 0)
3951 editor->nTextLimit = 65536;
3952 else
3953 editor->nTextLimit = (int) lParam;
3954 return 0;
3956 case EM_LIMITTEXT:
3958 if (wParam == 0)
3959 editor->nTextLimit = 65536;
3960 else
3961 editor->nTextLimit = (int) wParam;
3962 return 0;
3964 case EM_GETLIMITTEXT:
3966 return editor->nTextLimit;
3968 case EM_FINDTEXT:
3970 LRESULT r;
3971 if(!unicode){
3972 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3973 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3974 WCHAR *tmp;
3976 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3977 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3978 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3979 FREE_OBJ( tmp );
3980 }else{
3981 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3982 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3984 return r;
3986 case EM_FINDTEXTEX:
3988 LRESULT r;
3989 if(!unicode){
3990 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3991 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3992 WCHAR *tmp;
3994 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3995 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3996 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3997 FREE_OBJ( tmp );
3998 }else{
3999 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4000 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4002 return r;
4004 case EM_FINDTEXTW:
4006 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4007 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4009 case EM_FINDTEXTEXW:
4011 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4012 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4014 case EM_GETZOOM:
4015 if (!wParam || !lParam)
4016 return FALSE;
4017 *(int *)wParam = editor->nZoomNumerator;
4018 *(int *)lParam = editor->nZoomDenominator;
4019 return TRUE;
4020 case EM_SETZOOM:
4021 return ME_SetZoom(editor, wParam, lParam);
4022 case EM_CHARFROMPOS:
4024 ME_Cursor cursor;
4025 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4026 &cursor, NULL))
4027 return ME_GetCursorOfs(&cursor);
4028 else
4029 return -1;
4031 case EM_POSFROMCHAR:
4033 ME_DisplayItem *pPara, *pRun;
4034 int nCharOfs, nOffset, nLength;
4035 POINTL pt = {0,0};
4037 nCharOfs = wParam;
4038 /* detect which API version we're dealing with */
4039 if (wParam >= 0x40000)
4040 nCharOfs = lParam;
4041 nLength = ME_GetTextLength(editor);
4042 nCharOfs = min(nCharOfs, nLength);
4043 nCharOfs = max(nCharOfs, 0);
4045 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4046 assert(pRun->type == diRun);
4047 pt.y = pRun->member.run.pt.y;
4048 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4049 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4050 pt.x += editor->rcFormat.left;
4052 pt.x -= editor->horz_si.nPos;
4053 pt.y -= editor->vert_si.nPos;
4055 if (wParam >= 0x40000) {
4056 *(POINTL *)wParam = pt;
4058 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4060 case WM_CREATE:
4062 void *text = NULL;
4063 INT max;
4065 ME_SetDefaultFormatRect(editor);
4067 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4068 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4069 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4071 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4072 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4074 if (editor->styleFlags & ES_DISABLENOSCROLL)
4076 if (editor->styleFlags & WS_VSCROLL)
4078 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4079 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4081 if (editor->styleFlags & WS_HSCROLL)
4083 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4084 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4088 if (lParam)
4090 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4091 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4093 if (text)
4095 WCHAR *textW;
4096 int len;
4097 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4098 textW = ME_ToUnicode(codepage, text, &len);
4099 if (!(editor->styleFlags & ES_MULTILINE))
4101 len = 0;
4102 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4103 len++;
4105 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4106 ME_EndToUnicode(codepage, textW);
4107 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4108 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4111 ME_CommitUndo(editor);
4112 ME_WrapMarkedParagraphs(editor);
4113 ME_MoveCaret(editor);
4114 return 0;
4116 case WM_DESTROY:
4117 ME_DestroyEditor(editor);
4118 return 0;
4119 case WM_SETCURSOR:
4121 return ME_SetCursor(editor);
4123 case WM_LBUTTONDBLCLK:
4124 case WM_LBUTTONDOWN:
4126 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4127 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4128 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4129 return 0;
4130 ITextHost_TxSetFocus(editor->texthost);
4131 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4132 ME_CalculateClickCount(editor, msg, wParam, lParam));
4133 ITextHost_TxSetCapture(editor->texthost, TRUE);
4134 editor->bMouseCaptured = TRUE;
4135 ME_LinkNotify(editor,msg,wParam,lParam);
4136 if (!ME_SetCursor(editor)) goto do_default;
4137 break;
4139 case WM_MOUSEMOVE:
4140 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4141 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4142 return 0;
4143 if (editor->bMouseCaptured)
4144 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4145 ME_LinkNotify(editor,msg,wParam,lParam);
4146 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4147 if (editor->bMouseCaptured)
4148 ME_SetCursor(editor);
4149 break;
4150 case WM_LBUTTONUP:
4151 if (editor->bMouseCaptured) {
4152 ITextHost_TxSetCapture(editor->texthost, FALSE);
4153 editor->bMouseCaptured = FALSE;
4155 if (editor->nSelectionType == stDocument)
4156 editor->nSelectionType = stPosition;
4157 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4158 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4159 return 0;
4160 else
4162 ME_SetCursor(editor);
4163 ME_LinkNotify(editor,msg,wParam,lParam);
4165 break;
4166 case WM_RBUTTONUP:
4167 case WM_RBUTTONDOWN:
4168 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4169 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4170 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4171 return 0;
4172 goto do_default;
4173 case WM_CONTEXTMENU:
4174 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4175 goto do_default;
4176 break;
4177 case WM_SETFOCUS:
4178 editor->bHaveFocus = TRUE;
4179 ME_ShowCaret(editor);
4180 ME_SendOldNotify(editor, EN_SETFOCUS);
4181 return 0;
4182 case WM_KILLFOCUS:
4183 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4184 editor->bHaveFocus = FALSE;
4185 editor->wheel_remain = 0;
4186 ME_HideCaret(editor);
4187 ME_SendOldNotify(editor, EN_KILLFOCUS);
4188 return 0;
4189 case WM_COMMAND:
4190 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4191 return 0;
4192 case WM_KEYUP:
4193 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4194 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4195 return 0;
4196 goto do_default;
4197 case WM_KEYDOWN:
4198 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4199 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4200 return 0;
4201 if (ME_KeyDown(editor, LOWORD(wParam)))
4202 return 0;
4203 goto do_default;
4204 case WM_CHAR:
4205 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4206 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4207 return 0;
4208 return ME_Char(editor, wParam, lParam, unicode);
4209 case WM_UNICHAR:
4210 if (unicode)
4212 if(wParam == UNICODE_NOCHAR) return TRUE;
4213 if(wParam <= 0x000fffff)
4215 if(wParam > 0xffff) /* convert to surrogates */
4217 wParam -= 0x10000;
4218 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4219 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4220 } else {
4221 ME_Char(editor, wParam, 0, TRUE);
4224 return 0;
4226 break;
4227 case EM_STOPGROUPTYPING:
4228 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4229 return 0;
4230 case WM_HSCROLL:
4232 const int scrollUnit = 7;
4234 switch(LOWORD(wParam))
4236 case SB_LEFT:
4237 ME_ScrollAbs(editor, 0, 0);
4238 break;
4239 case SB_RIGHT:
4240 ME_ScrollAbs(editor,
4241 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4242 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4243 break;
4244 case SB_LINELEFT:
4245 ME_ScrollLeft(editor, scrollUnit);
4246 break;
4247 case SB_LINERIGHT:
4248 ME_ScrollRight(editor, scrollUnit);
4249 break;
4250 case SB_PAGELEFT:
4251 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4252 break;
4253 case SB_PAGERIGHT:
4254 ME_ScrollRight(editor, editor->sizeWindow.cx);
4255 break;
4256 case SB_THUMBTRACK:
4257 case SB_THUMBPOSITION:
4259 int pos = HIWORD(wParam);
4260 if (editor->horz_si.nMax > 0xffff)
4261 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4262 ME_HScrollAbs(editor, pos);
4263 break;
4266 break;
4268 case EM_SCROLL: /* fall through */
4269 case WM_VSCROLL:
4271 int origNPos;
4272 int lineHeight = get_default_line_height( editor );
4274 origNPos = editor->vert_si.nPos;
4276 switch(LOWORD(wParam))
4278 case SB_TOP:
4279 ME_ScrollAbs(editor, 0, 0);
4280 break;
4281 case SB_BOTTOM:
4282 ME_ScrollAbs(editor,
4283 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4284 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4285 break;
4286 case SB_LINEUP:
4287 ME_ScrollUp(editor,lineHeight);
4288 break;
4289 case SB_LINEDOWN:
4290 ME_ScrollDown(editor,lineHeight);
4291 break;
4292 case SB_PAGEUP:
4293 ME_ScrollUp(editor,editor->sizeWindow.cy);
4294 break;
4295 case SB_PAGEDOWN:
4296 ME_ScrollDown(editor,editor->sizeWindow.cy);
4297 break;
4298 case SB_THUMBTRACK:
4299 case SB_THUMBPOSITION:
4301 int pos = HIWORD(wParam);
4302 if (editor->vert_si.nMax > 0xffff)
4303 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4304 ME_VScrollAbs(editor, pos);
4305 break;
4308 if (msg == EM_SCROLL)
4309 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4310 break;
4312 case WM_MOUSEWHEEL:
4314 int delta;
4315 BOOL ctrl_is_down;
4317 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4318 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4319 return 0;
4321 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4323 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4325 /* if scrolling changes direction, ignore left overs */
4326 if ((delta < 0 && editor->wheel_remain < 0) ||
4327 (delta > 0 && editor->wheel_remain > 0))
4328 editor->wheel_remain += delta;
4329 else
4330 editor->wheel_remain = delta;
4332 if (editor->wheel_remain)
4334 if (ctrl_is_down) {
4335 int numerator;
4336 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4338 numerator = 100;
4339 } else {
4340 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4342 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4343 if (numerator >= 10 && numerator <= 500)
4344 ME_SetZoom(editor, numerator, 100);
4345 } else {
4346 UINT max_lines = 3;
4347 int lines = 0;
4349 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4350 if (max_lines)
4351 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4352 if (lines)
4353 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4356 break;
4358 case EM_GETRECT:
4360 *((RECT *)lParam) = editor->rcFormat;
4361 if (editor->bDefaultFormatRect)
4362 ((RECT *)lParam)->left -= editor->selofs;
4363 return 0;
4365 case EM_SETRECT:
4366 case EM_SETRECTNP:
4368 if (lParam)
4370 int border = 0;
4371 RECT clientRect;
4372 RECT *rc = (RECT *)lParam;
4374 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4375 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4376 if (wParam == 0)
4378 editor->rcFormat.top = max(0, rc->top - border);
4379 editor->rcFormat.left = max(0, rc->left - border);
4380 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4381 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4382 } else if (wParam == 1) {
4383 /* MSDN incorrectly says a wParam value of 1 causes the
4384 * lParam rect to be used as a relative offset,
4385 * however, the tests show it just prevents min/max bound
4386 * checking. */
4387 editor->rcFormat.top = rc->top - border;
4388 editor->rcFormat.left = rc->left - border;
4389 editor->rcFormat.bottom = rc->bottom;
4390 editor->rcFormat.right = rc->right + border;
4391 } else {
4392 return 0;
4394 editor->bDefaultFormatRect = FALSE;
4396 else
4398 ME_SetDefaultFormatRect(editor);
4399 editor->bDefaultFormatRect = TRUE;
4401 ME_MarkAllForWrapping(editor);
4402 ME_WrapMarkedParagraphs(editor);
4403 ME_UpdateScrollBar(editor);
4404 if (msg != EM_SETRECTNP)
4405 ME_Repaint(editor);
4406 return 0;
4408 case EM_REQUESTRESIZE:
4409 ME_SendRequestResize(editor, TRUE);
4410 return 0;
4411 case WM_SETREDRAW:
4412 goto do_default;
4413 case WM_WINDOWPOSCHANGED:
4415 RECT clientRect;
4416 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4418 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4419 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4420 if (editor->bDefaultFormatRect) {
4421 ME_SetDefaultFormatRect(editor);
4422 } else {
4423 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4424 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4426 editor->prevClientRect = clientRect;
4427 ME_RewrapRepaint(editor);
4428 goto do_default;
4430 /* IME messages to make richedit controls IME aware */
4431 case WM_IME_SETCONTEXT:
4432 case WM_IME_CONTROL:
4433 case WM_IME_SELECT:
4434 case WM_IME_COMPOSITIONFULL:
4435 return 0;
4436 case WM_IME_STARTCOMPOSITION:
4438 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4439 ME_DeleteSelection(editor);
4440 ME_CommitUndo(editor);
4441 ME_UpdateRepaint(editor, FALSE);
4442 return 0;
4444 case WM_IME_COMPOSITION:
4446 HIMC hIMC;
4448 ME_Style *style = ME_GetInsertStyle(editor, 0);
4449 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4450 ME_DeleteSelection(editor);
4451 ME_SaveTempStyle(editor);
4452 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4454 LPWSTR lpCompStr = NULL;
4455 DWORD dwBufLen;
4456 DWORD dwIndex = lParam & GCS_RESULTSTR;
4457 if (!dwIndex)
4458 dwIndex = GCS_COMPSTR;
4460 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4461 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4462 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4463 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4464 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4465 HeapFree(GetProcessHeap(), 0, lpCompStr);
4467 if (dwIndex == GCS_COMPSTR)
4468 ME_SetSelection(editor,editor->imeStartIndex,
4469 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4471 ME_ReleaseStyle(style);
4472 ME_CommitUndo(editor);
4473 ME_UpdateRepaint(editor, FALSE);
4474 return 0;
4476 case WM_IME_ENDCOMPOSITION:
4478 ME_DeleteSelection(editor);
4479 editor->imeStartIndex=-1;
4480 return 0;
4482 case EM_GETOLEINTERFACE:
4484 if (!editor->reOle)
4485 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4486 return 0;
4487 *(LPVOID *)lParam = editor->reOle;
4488 IRichEditOle_AddRef(editor->reOle);
4489 return 1;
4491 case EM_GETPASSWORDCHAR:
4493 return editor->cPasswordMask;
4495 case EM_SETOLECALLBACK:
4496 if(editor->lpOleCallback)
4497 IRichEditOleCallback_Release(editor->lpOleCallback);
4498 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4499 if(editor->lpOleCallback)
4500 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4501 return TRUE;
4502 case EM_GETWORDBREAKPROC:
4503 return (LRESULT)editor->pfnWordBreak;
4504 case EM_SETWORDBREAKPROC:
4506 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4508 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4509 return (LRESULT)pfnOld;
4511 case EM_GETTEXTMODE:
4512 return editor->mode;
4513 case EM_SETTEXTMODE:
4515 int mask = 0;
4516 int changes = 0;
4518 if (ME_GetTextLength(editor) ||
4519 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4520 return E_UNEXPECTED;
4522 /* Check for mutually exclusive flags in adjacent bits of wParam */
4523 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4524 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4525 return E_INVALIDARG;
4527 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4529 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4530 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4531 if (wParam & TM_PLAINTEXT) {
4532 /* Clear selection since it should be possible to select the
4533 * end of text run for rich text */
4534 ME_InvalidateSelection(editor);
4535 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4536 editor->pCursors[1] = editor->pCursors[0];
4537 /* plain text can only have the default style. */
4538 ME_ClearTempStyle(editor);
4539 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4540 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4541 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4544 /* FIXME: Currently no support for undo level and code page options */
4545 editor->mode = (editor->mode & ~mask) | changes;
4546 return 0;
4548 case EM_SETPASSWORDCHAR:
4550 editor->cPasswordMask = wParam;
4551 ME_RewrapRepaint(editor);
4552 return 0;
4554 case EM_SETTARGETDEVICE:
4555 if (wParam == 0)
4557 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4558 if (editor->nAvailWidth || editor->bWordWrap != new)
4560 editor->bWordWrap = new;
4561 editor->nAvailWidth = 0; /* wrap to client area */
4562 ME_RewrapRepaint(editor);
4564 } else {
4565 int width = max(0, lParam);
4566 if ((editor->styleFlags & ES_MULTILINE) &&
4567 (!editor->bWordWrap || editor->nAvailWidth != width))
4569 editor->nAvailWidth = width;
4570 editor->bWordWrap = TRUE;
4571 ME_RewrapRepaint(editor);
4573 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4575 return TRUE;
4576 default:
4577 do_default:
4578 *phresult = S_FALSE;
4579 break;
4581 return 0L;
4584 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4585 LPARAM lParam, BOOL unicode)
4587 ME_TextEditor *editor;
4588 HRESULT hresult;
4589 LRESULT lresult = 0;
4591 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4592 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4594 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4595 if (!editor)
4597 if (msg == WM_NCCREATE)
4599 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4600 ITextHost *texthost;
4602 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4603 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4604 return texthost != NULL;
4606 else
4608 return DefWindowProcW(hWnd, msg, wParam, lParam);
4612 switch (msg)
4614 case WM_PAINT:
4616 HDC hDC;
4617 RECT rc;
4618 PAINTSTRUCT ps;
4620 hDC = BeginPaint(editor->hWnd, &ps);
4621 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4622 ME_SendOldNotify(editor, EN_UPDATE);
4623 /* Erase area outside of the formatting rectangle */
4624 if (ps.rcPaint.top < editor->rcFormat.top)
4626 rc = ps.rcPaint;
4627 rc.bottom = editor->rcFormat.top;
4628 FillRect(hDC, &rc, editor->hbrBackground);
4629 ps.rcPaint.top = editor->rcFormat.top;
4631 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4632 rc = ps.rcPaint;
4633 rc.top = editor->rcFormat.bottom;
4634 FillRect(hDC, &rc, editor->hbrBackground);
4635 ps.rcPaint.bottom = editor->rcFormat.bottom;
4637 if (ps.rcPaint.left < editor->rcFormat.left) {
4638 rc = ps.rcPaint;
4639 rc.right = editor->rcFormat.left;
4640 FillRect(hDC, &rc, editor->hbrBackground);
4641 ps.rcPaint.left = editor->rcFormat.left;
4643 if (ps.rcPaint.right > editor->rcFormat.right) {
4644 rc = ps.rcPaint;
4645 rc.left = editor->rcFormat.right;
4646 FillRect(hDC, &rc, editor->hbrBackground);
4647 ps.rcPaint.right = editor->rcFormat.right;
4650 ME_PaintContent(editor, hDC, &ps.rcPaint);
4651 EndPaint(editor->hWnd, &ps);
4652 return 0;
4654 case WM_ERASEBKGND:
4656 HDC hDC = (HDC)wParam;
4657 RECT rc;
4659 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4660 FillRect(hDC, &rc, editor->hbrBackground);
4661 return 1;
4663 case EM_SETOPTIONS:
4665 DWORD dwStyle;
4666 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4667 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4668 ECO_SELECTIONBAR;
4669 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4670 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4671 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4672 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4673 return lresult;
4675 case EM_SETREADONLY:
4677 DWORD dwStyle;
4678 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4679 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4680 dwStyle &= ~ES_READONLY;
4681 if (wParam)
4682 dwStyle |= ES_READONLY;
4683 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4684 return lresult;
4686 default:
4687 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4690 if (hresult == S_FALSE)
4691 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4693 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4694 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4696 return lresult;
4699 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4701 BOOL unicode = TRUE;
4703 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4704 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4705 unicode = FALSE;
4707 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4710 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4712 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4715 /******************************************************************
4716 * RichEditANSIWndProc (RICHED20.10)
4718 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4720 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4723 /******************************************************************
4724 * RichEdit10ANSIWndProc (RICHED20.9)
4726 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4728 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4730 ITextHost *texthost;
4731 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4733 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4734 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4735 return texthost != NULL;
4737 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4740 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4742 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4745 /* Fill buffer with srcChars unicode characters from the start cursor.
4747 * buffer: destination buffer
4748 * buflen: length of buffer in characters excluding the NULL terminator.
4749 * start: start of editor text to copy into buffer.
4750 * srcChars: Number of characters to use from the editor text.
4751 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4753 * returns the number of characters written excluding the NULL terminator.
4755 * The written text is always NULL terminated.
4757 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4758 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4759 BOOL bEOP)
4761 ME_DisplayItem *pRun, *pNextRun;
4762 const WCHAR *pStart = buffer;
4763 const WCHAR cr_lf[] = {'\r', '\n', 0};
4764 const WCHAR *str;
4765 int nLen;
4767 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4768 if (editor->bEmulateVersion10) bCRLF = FALSE;
4770 pRun = start->pRun;
4771 assert(pRun);
4772 pNextRun = ME_FindItemFwd(pRun, diRun);
4774 nLen = pRun->member.run.len - start->nOffset;
4775 str = get_text( &pRun->member.run, start->nOffset );
4777 while (srcChars && buflen && pNextRun)
4779 int nFlags = pRun->member.run.nFlags;
4781 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4783 if (buflen == 1) break;
4784 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4785 * EM_GETTEXTEX, however, this is done for copying text which
4786 * also uses this function. */
4787 srcChars -= min(nLen, srcChars);
4788 nLen = 2;
4789 str = cr_lf;
4790 } else {
4791 nLen = min(nLen, srcChars);
4792 srcChars -= nLen;
4795 nLen = min(nLen, buflen);
4796 buflen -= nLen;
4798 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4800 buffer += nLen;
4802 pRun = pNextRun;
4803 pNextRun = ME_FindItemFwd(pRun, diRun);
4805 nLen = pRun->member.run.len;
4806 str = get_text( &pRun->member.run, 0 );
4808 /* append '\r' to the last paragraph. */
4809 if (pRun->next->type == diTextEnd && bEOP)
4811 *buffer = '\r';
4812 buffer ++;
4814 *buffer = 0;
4815 return buffer - pStart;
4818 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4820 WNDCLASSW wcW;
4821 WNDCLASSA wcA;
4823 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4824 wcW.lpfnWndProc = RichEditWndProcW;
4825 wcW.cbClsExtra = 0;
4826 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4827 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4828 wcW.hIcon = NULL;
4829 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4830 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4831 wcW.lpszMenuName = NULL;
4833 if (is_version_nt())
4835 wcW.lpszClassName = RICHEDIT_CLASS20W;
4836 if (!RegisterClassW(&wcW)) return FALSE;
4837 wcW.lpszClassName = MSFTEDIT_CLASS;
4838 if (!RegisterClassW(&wcW)) return FALSE;
4840 else
4842 /* WNDCLASSA/W have the same layout */
4843 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4844 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4845 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4846 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4849 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4850 wcA.lpfnWndProc = RichEditWndProcA;
4851 wcA.cbClsExtra = 0;
4852 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4853 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4854 wcA.hIcon = NULL;
4855 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4856 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4857 wcA.lpszMenuName = NULL;
4858 wcA.lpszClassName = RICHEDIT_CLASS20A;
4859 if (!RegisterClassA(&wcA)) return FALSE;
4860 wcA.lpszClassName = "RichEdit50A";
4861 if (!RegisterClassA(&wcA)) return FALSE;
4863 return TRUE;
4866 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4867 /* FIXME: Not implemented */
4868 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4869 hWnd, msg, get_msg_name(msg), wParam, lParam);
4870 return DefWindowProcW(hWnd, msg, wParam, lParam);
4873 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4874 /* FIXME: Not implemented */
4875 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4876 hWnd, msg, get_msg_name(msg), wParam, lParam);
4877 return DefWindowProcW(hWnd, msg, wParam, lParam);
4880 /******************************************************************
4881 * REExtendedRegisterClass (RICHED20.8)
4883 * FIXME undocumented
4884 * Need to check for errors and implement controls and callbacks
4886 LRESULT WINAPI REExtendedRegisterClass(void)
4888 WNDCLASSW wcW;
4889 UINT result;
4891 FIXME("semi stub\n");
4893 wcW.cbClsExtra = 0;
4894 wcW.cbWndExtra = 4;
4895 wcW.hInstance = NULL;
4896 wcW.hIcon = NULL;
4897 wcW.hCursor = NULL;
4898 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4899 wcW.lpszMenuName = NULL;
4901 if (!ME_ListBoxRegistered)
4903 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4904 wcW.lpfnWndProc = REListWndProc;
4905 wcW.lpszClassName = REListBox20W;
4906 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4909 if (!ME_ComboBoxRegistered)
4911 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4912 wcW.lpfnWndProc = REComboWndProc;
4913 wcW.lpszClassName = REComboBox20W;
4914 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4917 result = 0;
4918 if (ME_ListBoxRegistered)
4919 result += 1;
4920 if (ME_ComboBoxRegistered)
4921 result += 2;
4923 return result;
4926 static BOOL isurlspecial(WCHAR c)
4928 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4929 return strchrW( special_chars, c ) != NULL;
4933 * This proc takes a selection, and scans it forward in order to select the span
4934 * of a possible URL candidate. A possible URL candidate must start with isalnum
4935 * or one of the following special characters: *|/\+%#@ and must consist entirely
4936 * of the characters allowed to start the URL, plus : (colon) which may occur
4937 * at most once, and not at either end.
4939 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4940 const ME_Cursor *start,
4941 int nChars,
4942 ME_Cursor *candidate_min,
4943 ME_Cursor *candidate_max)
4945 ME_Cursor cursor = *start;
4946 BOOL foundColon = FALSE;
4947 BOOL candidateStarted = FALSE;
4948 WCHAR lastAcceptedChar = '\0';
4950 while (nChars > 0)
4952 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4953 WCHAR *str = strStart + cursor.nOffset;
4954 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4955 nChars -= nLen;
4957 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4959 /* Find start of candidate */
4960 if (!candidateStarted)
4962 while (nLen)
4964 nLen--;
4965 if (isalnumW(*str) || isurlspecial(*str))
4967 cursor.nOffset = str - strStart;
4968 *candidate_min = cursor;
4969 candidateStarted = TRUE;
4970 lastAcceptedChar = *str++;
4971 break;
4973 str++;
4977 /* Find end of candidate */
4978 if (candidateStarted) {
4979 while (nLen)
4981 nLen--;
4982 if (*str == ':' && !foundColon) {
4983 foundColon = TRUE;
4984 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4985 cursor.nOffset = str - strStart;
4986 if (lastAcceptedChar == ':')
4987 ME_MoveCursorChars(editor, &cursor, -1);
4988 *candidate_max = cursor;
4989 return TRUE;
4991 lastAcceptedChar = *str++;
4994 } else {
4995 /* End of paragraph: skip it if before candidate span, or terminates
4996 current active span */
4997 if (candidateStarted) {
4998 if (lastAcceptedChar == ':')
4999 ME_MoveCursorChars(editor, &cursor, -1);
5000 *candidate_max = cursor;
5001 return TRUE;
5005 /* Reaching this point means no span was found, so get next span */
5006 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
5007 if (candidateStarted) {
5008 /* There are no further runs, so take end of text as end of candidate */
5009 cursor.nOffset = str - strStart;
5010 if (lastAcceptedChar == ':')
5011 ME_MoveCursorChars(editor, &cursor, -1);
5012 *candidate_max = cursor;
5013 return TRUE;
5015 *candidate_max = *candidate_min = cursor;
5016 return FALSE;
5018 cursor.nOffset = 0;
5021 if (candidateStarted) {
5022 /* There are no further runs, so take end of text as end of candidate */
5023 if (lastAcceptedChar == ':')
5024 ME_MoveCursorChars(editor, &cursor, -1);
5025 *candidate_max = cursor;
5026 return TRUE;
5028 *candidate_max = *candidate_min = cursor;
5029 return FALSE;
5033 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5035 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5037 #define MAX_PREFIX_LEN 9
5038 struct prefix_s {
5039 const WCHAR text[MAX_PREFIX_LEN];
5040 int length;
5041 }prefixes[] = {
5042 {{'p','r','o','s','p','e','r','o',':'}, 9},
5043 {{'t','e','l','n','e','t',':'}, 7},
5044 {{'g','o','p','h','e','r',':'}, 7},
5045 {{'m','a','i','l','t','o',':'}, 7},
5046 {{'h','t','t','p','s',':'}, 6},
5047 {{'f','i','l','e',':'}, 5},
5048 {{'n','e','w','s',':'}, 5},
5049 {{'w','a','i','s',':'}, 5},
5050 {{'n','n','t','p',':'}, 5},
5051 {{'h','t','t','p',':'}, 5},
5052 {{'w','w','w','.'}, 4},
5053 {{'f','t','p',':'}, 4},
5055 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5056 unsigned int i;
5058 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5059 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5061 if (nChars < prefixes[i].length) continue;
5062 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5063 return TRUE;
5065 return FALSE;
5066 #undef MAX_PREFIX_LEN
5070 * This proc walks through the indicated selection and evaluates whether each
5071 * section identified by ME_FindNextURLCandidate and in-between sections have
5072 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5073 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5075 * Since this function can cause runs to be split, do not depend on the value
5076 * of the start cursor at the end of the function.
5078 * nChars may be set to INT_MAX to update to the end of the text.
5080 * Returns TRUE if at least one section was modified.
5082 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5084 BOOL modified = FALSE;
5085 ME_Cursor startCur = *start;
5087 if (!editor->AutoURLDetect_bEnable) return FALSE;
5091 CHARFORMAT2W link;
5092 ME_Cursor candidateStart, candidateEnd;
5094 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5095 &candidateStart, &candidateEnd))
5097 /* Section before candidate is not an URL */
5098 int cMin = ME_GetCursorOfs(&candidateStart);
5099 int cMax = ME_GetCursorOfs(&candidateEnd);
5101 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5102 candidateStart = candidateEnd;
5103 nChars -= cMax - ME_GetCursorOfs(&startCur);
5105 else
5107 /* No more candidates until end of selection */
5108 nChars = 0;
5111 if (startCur.pRun != candidateStart.pRun ||
5112 startCur.nOffset != candidateStart.nOffset)
5114 /* CFE_LINK effect should be consistently unset */
5115 link.cbSize = sizeof(link);
5116 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5117 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5119 /* CFE_LINK must be unset from this range */
5120 memset(&link, 0, sizeof(CHARFORMAT2W));
5121 link.cbSize = sizeof(link);
5122 link.dwMask = CFM_LINK;
5123 link.dwEffects = 0;
5124 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5125 /* Update candidateEnd since setting character formats may split
5126 * runs, which can cause a cursor to be at an invalid offset within
5127 * a split run. */
5128 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5130 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5131 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5133 modified = TRUE;
5136 if (candidateStart.pRun != candidateEnd.pRun ||
5137 candidateStart.nOffset != candidateEnd.nOffset)
5139 /* CFE_LINK effect should be consistently set */
5140 link.cbSize = sizeof(link);
5141 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5142 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5144 /* CFE_LINK must be set on this range */
5145 memset(&link, 0, sizeof(CHARFORMAT2W));
5146 link.cbSize = sizeof(link);
5147 link.dwMask = CFM_LINK;
5148 link.dwEffects = CFE_LINK;
5149 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5150 modified = TRUE;
5153 startCur = candidateEnd;
5154 } while (nChars > 0);
5155 return modified;