riched20: Update rectangle on WM_WINDOWPOSCHANGED instead of WM_SIZE.
[wine.git] / dlls / riched20 / editor.c
blobf355f3319caaddd3820a43d079b6adce84609e0f
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 break;
2932 return TRUE;
2935 static inline int get_default_line_height( ME_TextEditor *editor )
2937 int height = 0;
2939 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2940 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2941 if (height <= 0) height = 24;
2943 return height;
2946 static inline int calc_wheel_change( int *remain, int amount_per_click )
2948 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2949 *remain -= WHEEL_DELTA * change / amount_per_click;
2950 return change;
2953 static const char * const edit_messages[] = {
2954 "EM_GETSEL",
2955 "EM_SETSEL",
2956 "EM_GETRECT",
2957 "EM_SETRECT",
2958 "EM_SETRECTNP",
2959 "EM_SCROLL",
2960 "EM_LINESCROLL",
2961 "EM_SCROLLCARET",
2962 "EM_GETMODIFY",
2963 "EM_SETMODIFY",
2964 "EM_GETLINECOUNT",
2965 "EM_LINEINDEX",
2966 "EM_SETHANDLE",
2967 "EM_GETHANDLE",
2968 "EM_GETTHUMB",
2969 "EM_UNKNOWN_BF",
2970 "EM_UNKNOWN_C0",
2971 "EM_LINELENGTH",
2972 "EM_REPLACESEL",
2973 "EM_UNKNOWN_C3",
2974 "EM_GETLINE",
2975 "EM_LIMITTEXT",
2976 "EM_CANUNDO",
2977 "EM_UNDO",
2978 "EM_FMTLINES",
2979 "EM_LINEFROMCHAR",
2980 "EM_UNKNOWN_CA",
2981 "EM_SETTABSTOPS",
2982 "EM_SETPASSWORDCHAR",
2983 "EM_EMPTYUNDOBUFFER",
2984 "EM_GETFIRSTVISIBLELINE",
2985 "EM_SETREADONLY",
2986 "EM_SETWORDBREAKPROC",
2987 "EM_GETWORDBREAKPROC",
2988 "EM_GETPASSWORDCHAR",
2989 "EM_SETMARGINS",
2990 "EM_GETMARGINS",
2991 "EM_GETLIMITTEXT",
2992 "EM_POSFROMCHAR",
2993 "EM_CHARFROMPOS",
2994 "EM_SETIMESTATUS",
2995 "EM_GETIMESTATUS"
2998 static const char * const richedit_messages[] = {
2999 "EM_CANPASTE",
3000 "EM_DISPLAYBAND",
3001 "EM_EXGETSEL",
3002 "EM_EXLIMITTEXT",
3003 "EM_EXLINEFROMCHAR",
3004 "EM_EXSETSEL",
3005 "EM_FINDTEXT",
3006 "EM_FORMATRANGE",
3007 "EM_GETCHARFORMAT",
3008 "EM_GETEVENTMASK",
3009 "EM_GETOLEINTERFACE",
3010 "EM_GETPARAFORMAT",
3011 "EM_GETSELTEXT",
3012 "EM_HIDESELECTION",
3013 "EM_PASTESPECIAL",
3014 "EM_REQUESTRESIZE",
3015 "EM_SELECTIONTYPE",
3016 "EM_SETBKGNDCOLOR",
3017 "EM_SETCHARFORMAT",
3018 "EM_SETEVENTMASK",
3019 "EM_SETOLECALLBACK",
3020 "EM_SETPARAFORMAT",
3021 "EM_SETTARGETDEVICE",
3022 "EM_STREAMIN",
3023 "EM_STREAMOUT",
3024 "EM_GETTEXTRANGE",
3025 "EM_FINDWORDBREAK",
3026 "EM_SETOPTIONS",
3027 "EM_GETOPTIONS",
3028 "EM_FINDTEXTEX",
3029 "EM_GETWORDBREAKPROCEX",
3030 "EM_SETWORDBREAKPROCEX",
3031 "EM_SETUNDOLIMIT",
3032 "EM_UNKNOWN_USER_83",
3033 "EM_REDO",
3034 "EM_CANREDO",
3035 "EM_GETUNDONAME",
3036 "EM_GETREDONAME",
3037 "EM_STOPGROUPTYPING",
3038 "EM_SETTEXTMODE",
3039 "EM_GETTEXTMODE",
3040 "EM_AUTOURLDETECT",
3041 "EM_GETAUTOURLDETECT",
3042 "EM_SETPALETTE",
3043 "EM_GETTEXTEX",
3044 "EM_GETTEXTLENGTHEX",
3045 "EM_SHOWSCROLLBAR",
3046 "EM_SETTEXTEX",
3047 "EM_UNKNOWN_USER_98",
3048 "EM_UNKNOWN_USER_99",
3049 "EM_SETPUNCTUATION",
3050 "EM_GETPUNCTUATION",
3051 "EM_SETWORDWRAPMODE",
3052 "EM_GETWORDWRAPMODE",
3053 "EM_SETIMECOLOR",
3054 "EM_GETIMECOLOR",
3055 "EM_SETIMEOPTIONS",
3056 "EM_GETIMEOPTIONS",
3057 "EM_CONVPOSITION",
3058 "EM_UNKNOWN_USER_109",
3059 "EM_UNKNOWN_USER_110",
3060 "EM_UNKNOWN_USER_111",
3061 "EM_UNKNOWN_USER_112",
3062 "EM_UNKNOWN_USER_113",
3063 "EM_UNKNOWN_USER_114",
3064 "EM_UNKNOWN_USER_115",
3065 "EM_UNKNOWN_USER_116",
3066 "EM_UNKNOWN_USER_117",
3067 "EM_UNKNOWN_USER_118",
3068 "EM_UNKNOWN_USER_119",
3069 "EM_SETLANGOPTIONS",
3070 "EM_GETLANGOPTIONS",
3071 "EM_GETIMECOMPMODE",
3072 "EM_FINDTEXTW",
3073 "EM_FINDTEXTEXW",
3074 "EM_RECONVERSION",
3075 "EM_SETIMEMODEBIAS",
3076 "EM_GETIMEMODEBIAS"
3079 static const char *
3080 get_msg_name(UINT msg)
3082 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3083 return edit_messages[msg - EM_GETSEL];
3084 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3085 return richedit_messages[msg - EM_CANPASTE];
3086 return "";
3089 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3091 int x,y;
3092 BOOL isExact;
3093 ME_Cursor cursor; /* The start of the clicked text. */
3095 ENLINK info;
3096 x = (short)LOWORD(lParam);
3097 y = (short)HIWORD(lParam);
3098 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3099 if (!isExact) return;
3101 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3102 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3103 { /* The clicked run has CFE_LINK set */
3104 ME_DisplayItem *di;
3106 info.nmhdr.hwndFrom = NULL;
3107 info.nmhdr.idFrom = 0;
3108 info.nmhdr.code = EN_LINK;
3109 info.msg = msg;
3110 info.wParam = wParam;
3111 info.lParam = lParam;
3112 cursor.nOffset = 0;
3114 /* find the first contiguous run with CFE_LINK set */
3115 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3116 for (di = cursor.pRun->prev;
3117 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3118 di = di->prev)
3120 info.chrg.cpMin -= di->member.run.len;
3123 /* find the last contiguous run with CFE_LINK set */
3124 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3125 for (di = cursor.pRun->next;
3126 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3127 di = di->next)
3129 info.chrg.cpMax += di->member.run.len;
3132 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3136 #define UNSUPPORTED_MSG(e) \
3137 case e: \
3138 FIXME(#e ": stub\n"); \
3139 *phresult = S_FALSE; \
3140 return 0;
3142 /* Handle messages for windowless and windoweded richedit controls.
3144 * The LRESULT that is returned is a return value for window procs,
3145 * and the phresult parameter is the COM return code needed by the
3146 * text services interface. */
3147 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3148 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3150 *phresult = S_OK;
3152 switch(msg) {
3154 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3155 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3156 UNSUPPORTED_MSG(EM_FMTLINES)
3157 UNSUPPORTED_MSG(EM_FORMATRANGE)
3158 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3159 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3160 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3161 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3162 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3163 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3164 UNSUPPORTED_MSG(EM_GETREDONAME)
3165 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3166 UNSUPPORTED_MSG(EM_GETUNDONAME)
3167 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3168 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3169 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3170 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3171 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3172 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3173 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3174 UNSUPPORTED_MSG(EM_SETMARGINS)
3175 UNSUPPORTED_MSG(EM_SETPALETTE)
3176 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3177 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3178 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3180 /* Messages specific to Richedit controls */
3182 case EM_STREAMIN:
3183 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3184 case EM_STREAMOUT:
3185 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3186 case WM_GETDLGCODE:
3188 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3190 if (lParam)
3191 editor->bDialogMode = TRUE;
3192 if (editor->styleFlags & ES_MULTILINE)
3193 code |= DLGC_WANTMESSAGE;
3194 if (!(editor->styleFlags & ES_SAVESEL))
3195 code |= DLGC_HASSETSEL;
3196 return code;
3198 case EM_EMPTYUNDOBUFFER:
3199 ME_EmptyUndoStack(editor);
3200 return 0;
3201 case EM_GETSEL:
3203 /* Note: wParam/lParam can be NULL */
3204 UINT from, to;
3205 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3206 PUINT pto = lParam ? (PUINT)lParam : &to;
3207 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3208 if ((*pfrom|*pto) & 0xFFFF0000)
3209 return -1;
3210 return MAKELONG(*pfrom,*pto);
3212 case EM_EXGETSEL:
3214 CHARRANGE *pRange = (CHARRANGE *)lParam;
3215 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3216 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3217 return 0;
3219 case EM_SETUNDOLIMIT:
3221 if ((int)wParam < 0)
3222 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3223 else
3224 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3225 /* Setting a max stack size keeps wine from getting killed
3226 for hogging memory. Windows allocates all this memory at once, so
3227 no program would realistically set a value above our maximum. */
3228 return editor->nUndoLimit;
3230 case EM_CANUNDO:
3231 return !list_empty( &editor->undo_stack );
3232 case EM_CANREDO:
3233 return !list_empty( &editor->redo_stack );
3234 case WM_UNDO: /* FIXME: actually not the same */
3235 case EM_UNDO:
3236 return ME_Undo(editor);
3237 case EM_REDO:
3238 return ME_Redo(editor);
3239 case EM_GETOPTIONS:
3241 /* these flags are equivalent to the ES_* counterparts */
3242 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3243 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3244 DWORD settings = editor->styleFlags & mask;
3246 return settings;
3248 case EM_SETOPTIONS:
3250 /* these flags are equivalent to ES_* counterparts, except for
3251 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3252 * but is still stored in editor->styleFlags. */
3253 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3254 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3255 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3256 DWORD settings = mask & editor->styleFlags;
3257 DWORD oldSettings = settings;
3258 DWORD changedSettings;
3260 switch(wParam)
3262 case ECOOP_SET:
3263 settings = lParam;
3264 break;
3265 case ECOOP_OR:
3266 settings |= lParam;
3267 break;
3268 case ECOOP_AND:
3269 settings &= lParam;
3270 break;
3271 case ECOOP_XOR:
3272 settings ^= lParam;
3274 changedSettings = oldSettings ^ settings;
3276 if (changedSettings) {
3277 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3279 if (changedSettings & ECO_SELECTIONBAR)
3281 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3282 if (settings & ECO_SELECTIONBAR) {
3283 assert(!editor->selofs);
3284 editor->selofs = SELECTIONBAR_WIDTH;
3285 editor->rcFormat.left += editor->selofs;
3286 } else {
3287 editor->rcFormat.left -= editor->selofs;
3288 editor->selofs = 0;
3290 ME_RewrapRepaint(editor);
3293 if (changedSettings & settings & ECO_VERTICAL)
3294 FIXME("ECO_VERTICAL not implemented yet!\n");
3295 if (changedSettings & settings & ECO_AUTOHSCROLL)
3296 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3297 if (changedSettings & settings & ECO_AUTOVSCROLL)
3298 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3299 if (changedSettings & settings & ECO_NOHIDESEL)
3300 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3301 if (changedSettings & settings & ECO_WANTRETURN)
3302 FIXME("ECO_WANTRETURN not implemented yet!\n");
3303 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3304 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3307 return settings;
3309 case EM_SETSEL:
3311 return handle_EM_EXSETSEL( editor, wParam, lParam );
3313 case EM_SETSCROLLPOS:
3315 POINT *point = (POINT *)lParam;
3316 ME_ScrollAbs(editor, point->x, point->y);
3317 return 0;
3319 case EM_AUTOURLDETECT:
3321 if (wParam==1 || wParam ==0)
3323 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3324 return 0;
3326 return E_INVALIDARG;
3328 case EM_GETAUTOURLDETECT:
3330 return editor->AutoURLDetect_bEnable;
3332 case EM_EXSETSEL:
3334 CHARRANGE range = *(CHARRANGE *)lParam;
3336 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3338 case EM_SHOWSCROLLBAR:
3340 DWORD flags;
3342 switch (wParam)
3344 case SB_HORZ:
3345 flags = WS_HSCROLL;
3346 break;
3347 case SB_VERT:
3348 flags = WS_VSCROLL;
3349 break;
3350 case SB_BOTH:
3351 flags = WS_HSCROLL|WS_VSCROLL;
3352 break;
3353 default:
3354 return 0;
3357 if (lParam) {
3358 editor->styleFlags |= flags;
3359 if (flags & WS_HSCROLL)
3360 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3361 editor->nTotalWidth > editor->sizeWindow.cx);
3362 if (flags & WS_VSCROLL)
3363 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3364 editor->nTotalLength > editor->sizeWindow.cy);
3365 } else {
3366 editor->styleFlags &= ~flags;
3367 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3369 return 0;
3371 case EM_SETTEXTEX:
3373 LPWSTR wszText;
3374 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3375 int from, to, len;
3376 ME_Style *style;
3377 BOOL bRtf, bUnicode, bSelection, bUTF8;
3378 int oldModify = editor->nModifyStep;
3379 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3381 if (!pStruct) return 0;
3383 /* If we detect ascii rtf at the start of the string,
3384 * we know it isn't unicode. */
3385 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3386 !strncmp((char *)lParam, "{\\urtf", 6)));
3387 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3388 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3390 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3391 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3392 pStruct->flags, pStruct->codepage);
3394 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3395 if (bSelection) {
3396 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3397 style = ME_GetSelectionInsertStyle(editor);
3398 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3399 } else {
3400 ME_Cursor start;
3401 ME_SetCursorToStart(editor, &start);
3402 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3403 style = editor->pBuffer->pDefaultStyle;
3406 if (bRtf) {
3407 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3408 if (bSelection) {
3409 /* FIXME: The length returned doesn't include the rtf control
3410 * characters, only the actual text. */
3411 len = lParam ? strlen((char *)lParam) : 0;
3413 } else {
3414 if (bUTF8 && !bUnicode) {
3415 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3416 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3417 ME_EndToUnicode(CP_UTF8, wszText);
3418 } else {
3419 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3420 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3421 ME_EndToUnicode(pStruct->codepage, wszText);
3425 if (bSelection) {
3426 ME_ReleaseStyle(style);
3427 ME_UpdateSelectionLinkAttribute(editor);
3428 } else {
3429 ME_Cursor cursor;
3430 len = 1;
3431 ME_SetCursorToStart(editor, &cursor);
3432 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3434 ME_CommitUndo(editor);
3435 if (!(pStruct->flags & ST_KEEPUNDO))
3437 editor->nModifyStep = oldModify;
3438 ME_EmptyUndoStack(editor);
3440 ME_UpdateRepaint(editor, FALSE);
3441 return len;
3443 case EM_SETBKGNDCOLOR:
3445 LRESULT lColor;
3446 if (editor->rgbBackColor != -1) {
3447 DeleteObject(editor->hbrBackground);
3448 lColor = editor->rgbBackColor;
3450 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3452 if (wParam)
3454 editor->rgbBackColor = -1;
3455 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3457 else
3459 editor->rgbBackColor = lParam;
3460 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3462 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3463 ITextHost_TxViewChange(editor->texthost, TRUE);
3464 return lColor;
3466 case EM_GETMODIFY:
3467 return editor->nModifyStep == 0 ? 0 : -1;
3468 case EM_SETMODIFY:
3470 if (wParam)
3471 editor->nModifyStep = 1;
3472 else
3473 editor->nModifyStep = 0;
3475 return 0;
3477 case EM_SETREADONLY:
3479 if (wParam)
3480 editor->styleFlags |= ES_READONLY;
3481 else
3482 editor->styleFlags &= ~ES_READONLY;
3483 return 1;
3485 case EM_SETEVENTMASK:
3487 DWORD nOldMask = editor->nEventMask;
3489 editor->nEventMask = lParam;
3490 return nOldMask;
3492 case EM_GETEVENTMASK:
3493 return editor->nEventMask;
3494 case EM_SETCHARFORMAT:
3496 CHARFORMAT2W buf, *p;
3497 BOOL bRepaint = TRUE;
3498 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3499 if (p == NULL) return 0;
3500 if (wParam & SCF_ALL) {
3501 if (editor->mode & TM_PLAINTEXT) {
3502 ME_SetDefaultCharFormat(editor, p);
3503 } else {
3504 ME_Cursor start;
3505 ME_SetCursorToStart(editor, &start);
3506 ME_SetCharFormat(editor, &start, NULL, p);
3507 editor->nModifyStep = 1;
3509 } else if (wParam & SCF_SELECTION) {
3510 if (editor->mode & TM_PLAINTEXT)
3511 return 0;
3512 if (wParam & SCF_WORD) {
3513 ME_Cursor start;
3514 ME_Cursor end = editor->pCursors[0];
3515 ME_MoveCursorWords(editor, &end, +1);
3516 start = end;
3517 ME_MoveCursorWords(editor, &start, -1);
3518 ME_SetCharFormat(editor, &start, &end, p);
3520 bRepaint = ME_IsSelection(editor);
3521 ME_SetSelectionCharFormat(editor, p);
3522 if (bRepaint) editor->nModifyStep = 1;
3523 } else { /* SCF_DEFAULT */
3524 ME_SetDefaultCharFormat(editor, p);
3526 ME_CommitUndo(editor);
3527 if (bRepaint)
3529 ME_WrapMarkedParagraphs(editor);
3530 ME_UpdateScrollBar(editor);
3531 ME_Repaint(editor);
3533 return 1;
3535 case EM_GETCHARFORMAT:
3537 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3538 if (dst->cbSize != sizeof(CHARFORMATA) &&
3539 dst->cbSize != sizeof(CHARFORMATW) &&
3540 dst->cbSize != sizeof(CHARFORMAT2A) &&
3541 dst->cbSize != sizeof(CHARFORMAT2W))
3542 return 0;
3543 tmp.cbSize = sizeof(tmp);
3544 if (!wParam)
3545 ME_GetDefaultCharFormat(editor, &tmp);
3546 else
3547 ME_GetSelectionCharFormat(editor, &tmp);
3548 ME_CopyToCFAny(dst, &tmp);
3549 return tmp.dwMask;
3551 case EM_SETPARAFORMAT:
3553 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3554 ME_WrapMarkedParagraphs(editor);
3555 ME_UpdateScrollBar(editor);
3556 ME_Repaint(editor);
3557 ME_CommitUndo(editor);
3558 return result;
3560 case EM_GETPARAFORMAT:
3561 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3562 return ((PARAFORMAT2 *)lParam)->dwMask;
3563 case EM_GETFIRSTVISIBLELINE:
3565 ME_DisplayItem *p = editor->pBuffer->pFirst;
3566 int y = editor->vert_si.nPos;
3567 int ypara = 0;
3568 int count = 0;
3569 int ystart, yend;
3570 while(p) {
3571 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3572 if (p->type == diTextEnd)
3573 break;
3574 if (p->type == diParagraph) {
3575 ypara = p->member.para.pt.y;
3576 continue;
3578 ystart = ypara + p->member.row.pt.y;
3579 yend = ystart + p->member.row.nHeight;
3580 if (y < yend) {
3581 break;
3583 count++;
3585 return count;
3587 case EM_HIDESELECTION:
3589 editor->bHideSelection = (wParam != 0);
3590 ME_InvalidateSelection(editor);
3591 return 0;
3593 case EM_LINESCROLL:
3595 if (!(editor->styleFlags & ES_MULTILINE))
3596 return FALSE;
3597 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3598 return TRUE;
3600 case WM_CLEAR:
3602 int from, to;
3603 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3604 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3605 ME_CommitUndo(editor);
3606 ME_UpdateRepaint(editor, TRUE);
3607 return 0;
3609 case EM_REPLACESEL:
3611 int from, to, nStartCursor;
3612 ME_Style *style;
3613 int len = 0;
3614 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3615 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3616 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3618 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3619 style = ME_GetSelectionInsertStyle(editor);
3620 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3621 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3622 ME_ReleaseStyle(style);
3623 /* drop temporary style if line end */
3625 * FIXME question: does abc\n mean: put abc,
3626 * clear temp style, put \n? (would require a change)
3628 if (len>0 && wszText[len-1] == '\n')
3629 ME_ClearTempStyle(editor);
3630 ME_EndToUnicode(codepage, wszText);
3631 ME_CommitUndo(editor);
3632 ME_UpdateSelectionLinkAttribute(editor);
3633 if (!wParam)
3634 ME_EmptyUndoStack(editor);
3635 ME_UpdateRepaint(editor, FALSE);
3636 return len;
3638 case EM_SCROLLCARET:
3639 ME_EnsureVisible(editor, &editor->pCursors[0]);
3640 return 0;
3641 case WM_SETFONT:
3643 LOGFONTW lf;
3644 CHARFORMAT2W fmt;
3645 HDC hDC;
3646 BOOL bRepaint = LOWORD(lParam);
3648 if (!wParam)
3649 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3650 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3651 hDC = ITextHost_TxGetDC(editor->texthost);
3652 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3653 ITextHost_TxReleaseDC(editor->texthost, hDC);
3654 if (editor->mode & TM_RICHTEXT) {
3655 ME_Cursor start;
3656 ME_SetCursorToStart(editor, &start);
3657 ME_SetCharFormat(editor, &start, NULL, &fmt);
3659 ME_SetDefaultCharFormat(editor, &fmt);
3661 ME_CommitUndo(editor);
3662 ME_MarkAllForWrapping(editor);
3663 ME_WrapMarkedParagraphs(editor);
3664 ME_UpdateScrollBar(editor);
3665 if (bRepaint)
3666 ME_Repaint(editor);
3667 return 0;
3669 case WM_SETTEXT:
3671 ME_Cursor cursor;
3672 ME_SetCursorToStart(editor, &cursor);
3673 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3674 if (lParam)
3676 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3677 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3678 !strncmp((char *)lParam, "{\\urtf", 6))
3680 /* Undocumented: WM_SETTEXT supports RTF text */
3681 ME_StreamInRTFString(editor, 0, (char *)lParam);
3683 else
3685 int textLen;
3686 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3687 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &textLen);
3688 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3689 if (textLen > 0)
3691 int len = -1;
3693 /* uses default style! */
3694 if (!(editor->styleFlags & ES_MULTILINE))
3696 WCHAR * p;
3698 p = wszText;
3699 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3700 len = p - wszText;
3702 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3704 ME_EndToUnicode(codepage, wszText);
3707 else
3708 TRACE("WM_SETTEXT - NULL\n");
3709 ME_SetCursorToStart(editor, &cursor);
3710 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3711 ME_SetSelection(editor, 0, 0);
3712 editor->nModifyStep = 0;
3713 ME_CommitUndo(editor);
3714 ME_EmptyUndoStack(editor);
3715 ME_UpdateRepaint(editor, FALSE);
3716 return 1;
3718 case EM_CANPASTE:
3720 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3721 if (IsClipboardFormatAvailable(nRTFFormat))
3722 return TRUE;
3723 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3724 return TRUE;
3725 return FALSE;
3727 case WM_PASTE:
3728 case WM_MBUTTONDOWN:
3729 ME_Paste(editor);
3730 return 0;
3731 case WM_CUT:
3732 case WM_COPY:
3734 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3735 int nChars = nTo - nFrom;
3736 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3738 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3740 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3741 ME_CommitUndo(editor);
3742 ME_UpdateRepaint(editor, TRUE);
3744 return 0;
3746 case WM_GETTEXTLENGTH:
3748 GETTEXTLENGTHEX how;
3750 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3751 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3752 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3753 return ME_GetTextLengthEx(editor, &how);
3755 case EM_GETTEXTLENGTHEX:
3756 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3757 case WM_GETTEXT:
3759 GETTEXTEX ex;
3760 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3761 ex.flags = GT_USECRLF;
3762 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3763 ex.lpDefaultChar = NULL;
3764 ex.lpUsedDefChar = NULL;
3765 return ME_GetTextEx(editor, &ex, lParam);
3767 case EM_GETTEXTEX:
3768 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3769 case EM_GETSELTEXT:
3771 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3772 ME_Cursor *from = &editor->pCursors[nStartCur];
3773 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3774 nTo - nFrom, unicode);
3776 case EM_GETSCROLLPOS:
3778 POINT *point = (POINT *)lParam;
3779 point->x = editor->horz_si.nPos;
3780 point->y = editor->vert_si.nPos;
3781 /* 16-bit scaled value is returned as stored in scrollinfo */
3782 if (editor->horz_si.nMax > 0xffff)
3783 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3784 if (editor->vert_si.nMax > 0xffff)
3785 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3786 return 1;
3788 case EM_GETTEXTRANGE:
3790 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3791 ME_Cursor start;
3792 int nStart = rng->chrg.cpMin;
3793 int nEnd = rng->chrg.cpMax;
3794 int textlength = ME_GetTextLength(editor);
3796 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3797 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3798 if (nStart < 0) return 0;
3799 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3800 nEnd = textlength;
3801 if (nStart >= nEnd) return 0;
3803 ME_CursorFromCharOfs(editor, nStart, &start);
3804 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3806 case EM_GETLINE:
3808 ME_DisplayItem *run;
3809 const unsigned int nMaxChars = *(WORD *) lParam;
3810 unsigned int nCharsLeft = nMaxChars;
3811 char *dest = (char *) lParam;
3812 BOOL wroteNull = FALSE;
3814 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3815 unicode ? "Unicode" : "Ansi");
3817 run = ME_FindRowWithNumber(editor, wParam);
3818 if (run == NULL)
3819 return 0;
3821 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3822 && run->type == diRun)
3824 WCHAR *str = get_text( &run->member.run, 0 );
3825 unsigned int nCopy;
3827 nCopy = min(nCharsLeft, run->member.run.len);
3829 if (unicode)
3830 memcpy(dest, str, nCopy * sizeof(WCHAR));
3831 else
3832 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3833 nCharsLeft, NULL, NULL);
3834 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3835 nCharsLeft -= nCopy;
3838 /* append line termination, space allowing */
3839 if (nCharsLeft > 0)
3841 if (unicode)
3842 *((WCHAR *)dest) = '\0';
3843 else
3844 *dest = '\0';
3845 nCharsLeft--;
3846 wroteNull = TRUE;
3849 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3850 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3852 case EM_GETLINECOUNT:
3854 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3855 int nRows = 0;
3857 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3859 while (item != editor->pBuffer->pLast)
3861 assert(item->type == diParagraph);
3862 prev_para = ME_FindItemBack(item, diRun);
3863 if (prev_para) {
3864 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3866 nRows += item->member.para.nRows;
3867 item = item->member.para.next_para;
3869 last_para = ME_FindItemBack(item, diRun);
3870 assert(last_para);
3871 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3872 if (editor->bEmulateVersion10 && prev_para &&
3873 last_para->member.run.nCharOfs == 0 &&
3874 prev_para->member.run.len == 1 &&
3875 *get_text( &prev_para->member.run, 0 ) == '\r')
3877 /* In 1.0 emulation, the last solitary \r at the very end of the text
3878 (if one exists) is NOT a line break.
3879 FIXME: this is an ugly hack. This should have a more regular model. */
3880 nRows--;
3883 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3884 return max(1, nRows);
3886 case EM_LINEFROMCHAR:
3888 if (wParam == -1)
3889 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3890 else
3891 return ME_RowNumberFromCharOfs(editor, wParam);
3893 case EM_EXLINEFROMCHAR:
3895 if (lParam == -1)
3896 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3897 else
3898 return ME_RowNumberFromCharOfs(editor, lParam);
3900 case EM_LINEINDEX:
3902 ME_DisplayItem *item, *para;
3903 int nCharOfs;
3905 if (wParam == -1)
3906 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3907 else
3908 item = ME_FindRowWithNumber(editor, wParam);
3909 if (!item)
3910 return -1;
3911 para = ME_GetParagraph(item);
3912 item = ME_FindItemFwd(item, diRun);
3913 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3914 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3915 return nCharOfs;
3917 case EM_LINELENGTH:
3919 ME_DisplayItem *item, *item_end;
3920 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3921 ME_DisplayItem *para, *run;
3923 if (wParam > ME_GetTextLength(editor))
3924 return 0;
3925 if (wParam == -1)
3927 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3928 return 0;
3930 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3931 item = ME_RowStart(run);
3932 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3933 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3934 if (item_end->type == diStartRow) {
3935 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3936 } else {
3937 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3938 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3939 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3941 nChars = nNextLineOfs - nThisLineOfs;
3942 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3943 return nChars;
3945 case EM_EXLIMITTEXT:
3947 if ((int)lParam < 0)
3948 return 0;
3949 if (lParam == 0)
3950 editor->nTextLimit = 65536;
3951 else
3952 editor->nTextLimit = (int) lParam;
3953 return 0;
3955 case EM_LIMITTEXT:
3957 if (wParam == 0)
3958 editor->nTextLimit = 65536;
3959 else
3960 editor->nTextLimit = (int) wParam;
3961 return 0;
3963 case EM_GETLIMITTEXT:
3965 return editor->nTextLimit;
3967 case EM_FINDTEXT:
3969 LRESULT r;
3970 if(!unicode){
3971 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3972 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3973 WCHAR *tmp;
3975 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3976 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3977 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3978 FREE_OBJ( tmp );
3979 }else{
3980 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3981 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3983 return r;
3985 case EM_FINDTEXTEX:
3987 LRESULT r;
3988 if(!unicode){
3989 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3990 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3991 WCHAR *tmp;
3993 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3994 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3995 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3996 FREE_OBJ( tmp );
3997 }else{
3998 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3999 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4001 return r;
4003 case EM_FINDTEXTW:
4005 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4006 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4008 case EM_FINDTEXTEXW:
4010 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4011 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4013 case EM_GETZOOM:
4014 if (!wParam || !lParam)
4015 return FALSE;
4016 *(int *)wParam = editor->nZoomNumerator;
4017 *(int *)lParam = editor->nZoomDenominator;
4018 return TRUE;
4019 case EM_SETZOOM:
4020 return ME_SetZoom(editor, wParam, lParam);
4021 case EM_CHARFROMPOS:
4023 ME_Cursor cursor;
4024 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4025 &cursor, NULL))
4026 return ME_GetCursorOfs(&cursor);
4027 else
4028 return -1;
4030 case EM_POSFROMCHAR:
4032 ME_DisplayItem *pPara, *pRun;
4033 int nCharOfs, nOffset, nLength;
4034 POINTL pt = {0,0};
4036 nCharOfs = wParam;
4037 /* detect which API version we're dealing with */
4038 if (wParam >= 0x40000)
4039 nCharOfs = lParam;
4040 nLength = ME_GetTextLength(editor);
4041 nCharOfs = min(nCharOfs, nLength);
4042 nCharOfs = max(nCharOfs, 0);
4044 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4045 assert(pRun->type == diRun);
4046 pt.y = pRun->member.run.pt.y;
4047 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4048 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4049 pt.x += editor->rcFormat.left;
4051 pt.x -= editor->horz_si.nPos;
4052 pt.y -= editor->vert_si.nPos;
4054 if (wParam >= 0x40000) {
4055 *(POINTL *)wParam = pt;
4057 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4059 case WM_CREATE:
4061 void *text = NULL;
4062 INT max;
4064 ME_SetDefaultFormatRect(editor);
4066 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
4067 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
4068 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
4070 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
4071 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
4073 if (editor->styleFlags & ES_DISABLENOSCROLL)
4075 if (editor->styleFlags & WS_VSCROLL)
4077 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
4078 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
4080 if (editor->styleFlags & WS_HSCROLL)
4082 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
4083 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
4087 if (lParam)
4089 text = (unicode ? (void*)((CREATESTRUCTW*)lParam)->lpszName
4090 : (void*)((CREATESTRUCTA*)lParam)->lpszName);
4092 if (text)
4094 WCHAR *textW;
4095 int len;
4096 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
4097 textW = ME_ToUnicode(codepage, text, &len);
4098 if (!(editor->styleFlags & ES_MULTILINE))
4100 len = 0;
4101 while(textW[len] != '\0' && textW[len] != '\r' && textW[len] != '\n')
4102 len++;
4104 ME_InsertTextFromCursor(editor, 0, textW, len, editor->pBuffer->pDefaultStyle);
4105 ME_EndToUnicode(codepage, textW);
4106 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4107 ME_SetCursorToStart(editor, &editor->pCursors[1]);
4110 ME_CommitUndo(editor);
4111 ME_WrapMarkedParagraphs(editor);
4112 ME_MoveCaret(editor);
4113 return 0;
4115 case WM_DESTROY:
4116 ME_DestroyEditor(editor);
4117 return 0;
4118 case WM_SETCURSOR:
4120 return ME_SetCursor(editor);
4122 case WM_LBUTTONDBLCLK:
4123 case WM_LBUTTONDOWN:
4125 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4126 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4127 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4128 return 0;
4129 ITextHost_TxSetFocus(editor->texthost);
4130 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4131 ME_CalculateClickCount(editor, msg, wParam, lParam));
4132 ITextHost_TxSetCapture(editor->texthost, TRUE);
4133 editor->bMouseCaptured = TRUE;
4134 ME_LinkNotify(editor,msg,wParam,lParam);
4135 if (!ME_SetCursor(editor)) goto do_default;
4136 break;
4138 case WM_MOUSEMOVE:
4139 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4140 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4141 return 0;
4142 if (editor->bMouseCaptured)
4143 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4144 ME_LinkNotify(editor,msg,wParam,lParam);
4145 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4146 if (editor->bMouseCaptured)
4147 ME_SetCursor(editor);
4148 break;
4149 case WM_LBUTTONUP:
4150 if (editor->bMouseCaptured) {
4151 ITextHost_TxSetCapture(editor->texthost, FALSE);
4152 editor->bMouseCaptured = FALSE;
4154 if (editor->nSelectionType == stDocument)
4155 editor->nSelectionType = stPosition;
4156 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4157 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4158 return 0;
4159 else
4161 ME_SetCursor(editor);
4162 ME_LinkNotify(editor,msg,wParam,lParam);
4164 break;
4165 case WM_RBUTTONUP:
4166 case WM_RBUTTONDOWN:
4167 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4168 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4169 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4170 return 0;
4171 goto do_default;
4172 case WM_CONTEXTMENU:
4173 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4174 goto do_default;
4175 break;
4176 case WM_SETFOCUS:
4177 editor->bHaveFocus = TRUE;
4178 ME_ShowCaret(editor);
4179 ME_SendOldNotify(editor, EN_SETFOCUS);
4180 return 0;
4181 case WM_KILLFOCUS:
4182 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4183 editor->bHaveFocus = FALSE;
4184 editor->wheel_remain = 0;
4185 ME_HideCaret(editor);
4186 ME_SendOldNotify(editor, EN_KILLFOCUS);
4187 return 0;
4188 case WM_COMMAND:
4189 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4190 return 0;
4191 case WM_KEYUP:
4192 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4193 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4194 return 0;
4195 goto do_default;
4196 case WM_KEYDOWN:
4197 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4198 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4199 return 0;
4200 if (ME_KeyDown(editor, LOWORD(wParam)))
4201 return 0;
4202 goto do_default;
4203 case WM_CHAR:
4204 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4205 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4206 return 0;
4207 return ME_Char(editor, wParam, lParam, unicode);
4208 case WM_UNICHAR:
4209 if (unicode)
4211 if(wParam == UNICODE_NOCHAR) return TRUE;
4212 if(wParam <= 0x000fffff)
4214 if(wParam > 0xffff) /* convert to surrogates */
4216 wParam -= 0x10000;
4217 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4218 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4219 } else {
4220 ME_Char(editor, wParam, 0, TRUE);
4223 return 0;
4225 break;
4226 case EM_STOPGROUPTYPING:
4227 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4228 return 0;
4229 case WM_HSCROLL:
4231 const int scrollUnit = 7;
4233 switch(LOWORD(wParam))
4235 case SB_LEFT:
4236 ME_ScrollAbs(editor, 0, 0);
4237 break;
4238 case SB_RIGHT:
4239 ME_ScrollAbs(editor,
4240 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4241 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4242 break;
4243 case SB_LINELEFT:
4244 ME_ScrollLeft(editor, scrollUnit);
4245 break;
4246 case SB_LINERIGHT:
4247 ME_ScrollRight(editor, scrollUnit);
4248 break;
4249 case SB_PAGELEFT:
4250 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4251 break;
4252 case SB_PAGERIGHT:
4253 ME_ScrollRight(editor, editor->sizeWindow.cx);
4254 break;
4255 case SB_THUMBTRACK:
4256 case SB_THUMBPOSITION:
4258 int pos = HIWORD(wParam);
4259 if (editor->horz_si.nMax > 0xffff)
4260 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4261 ME_HScrollAbs(editor, pos);
4262 break;
4265 break;
4267 case EM_SCROLL: /* fall through */
4268 case WM_VSCROLL:
4270 int origNPos;
4271 int lineHeight = get_default_line_height( editor );
4273 origNPos = editor->vert_si.nPos;
4275 switch(LOWORD(wParam))
4277 case SB_TOP:
4278 ME_ScrollAbs(editor, 0, 0);
4279 break;
4280 case SB_BOTTOM:
4281 ME_ScrollAbs(editor,
4282 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4283 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4284 break;
4285 case SB_LINEUP:
4286 ME_ScrollUp(editor,lineHeight);
4287 break;
4288 case SB_LINEDOWN:
4289 ME_ScrollDown(editor,lineHeight);
4290 break;
4291 case SB_PAGEUP:
4292 ME_ScrollUp(editor,editor->sizeWindow.cy);
4293 break;
4294 case SB_PAGEDOWN:
4295 ME_ScrollDown(editor,editor->sizeWindow.cy);
4296 break;
4297 case SB_THUMBTRACK:
4298 case SB_THUMBPOSITION:
4300 int pos = HIWORD(wParam);
4301 if (editor->vert_si.nMax > 0xffff)
4302 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4303 ME_VScrollAbs(editor, pos);
4304 break;
4307 if (msg == EM_SCROLL)
4308 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4309 break;
4311 case WM_MOUSEWHEEL:
4313 int delta;
4314 BOOL ctrl_is_down;
4316 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4317 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4318 return 0;
4320 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4322 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4324 /* if scrolling changes direction, ignore left overs */
4325 if ((delta < 0 && editor->wheel_remain < 0) ||
4326 (delta > 0 && editor->wheel_remain > 0))
4327 editor->wheel_remain += delta;
4328 else
4329 editor->wheel_remain = delta;
4331 if (editor->wheel_remain)
4333 if (ctrl_is_down) {
4334 int numerator;
4335 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4337 numerator = 100;
4338 } else {
4339 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4341 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4342 if (numerator >= 10 && numerator <= 500)
4343 ME_SetZoom(editor, numerator, 100);
4344 } else {
4345 UINT max_lines = 3;
4346 int lines = 0;
4348 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4349 if (max_lines)
4350 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4351 if (lines)
4352 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4355 break;
4357 case EM_GETRECT:
4359 *((RECT *)lParam) = editor->rcFormat;
4360 if (editor->bDefaultFormatRect)
4361 ((RECT *)lParam)->left -= editor->selofs;
4362 return 0;
4364 case EM_SETRECT:
4365 case EM_SETRECTNP:
4367 if (lParam)
4369 int border = 0;
4370 RECT clientRect;
4371 RECT *rc = (RECT *)lParam;
4373 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4374 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4375 if (wParam == 0)
4377 editor->rcFormat.top = max(0, rc->top - border);
4378 editor->rcFormat.left = max(0, rc->left - border);
4379 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4380 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4381 } else if (wParam == 1) {
4382 /* MSDN incorrectly says a wParam value of 1 causes the
4383 * lParam rect to be used as a relative offset,
4384 * however, the tests show it just prevents min/max bound
4385 * checking. */
4386 editor->rcFormat.top = rc->top - border;
4387 editor->rcFormat.left = rc->left - border;
4388 editor->rcFormat.bottom = rc->bottom;
4389 editor->rcFormat.right = rc->right + border;
4390 } else {
4391 return 0;
4393 editor->bDefaultFormatRect = FALSE;
4395 else
4397 ME_SetDefaultFormatRect(editor);
4398 editor->bDefaultFormatRect = TRUE;
4400 ME_MarkAllForWrapping(editor);
4401 ME_WrapMarkedParagraphs(editor);
4402 ME_UpdateScrollBar(editor);
4403 if (msg != EM_SETRECTNP)
4404 ME_Repaint(editor);
4405 return 0;
4407 case EM_REQUESTRESIZE:
4408 ME_SendRequestResize(editor, TRUE);
4409 return 0;
4410 case WM_SETREDRAW:
4411 goto do_default;
4412 case WM_WINDOWPOSCHANGED:
4414 RECT clientRect;
4415 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4417 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4418 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4419 if (editor->bDefaultFormatRect) {
4420 ME_SetDefaultFormatRect(editor);
4421 } else {
4422 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4423 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4425 editor->prevClientRect = clientRect;
4426 ME_RewrapRepaint(editor);
4427 goto do_default;
4429 /* IME messages to make richedit controls IME aware */
4430 case WM_IME_SETCONTEXT:
4431 case WM_IME_CONTROL:
4432 case WM_IME_SELECT:
4433 case WM_IME_COMPOSITIONFULL:
4434 return 0;
4435 case WM_IME_STARTCOMPOSITION:
4437 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4438 ME_DeleteSelection(editor);
4439 ME_CommitUndo(editor);
4440 ME_UpdateRepaint(editor, FALSE);
4441 return 0;
4443 case WM_IME_COMPOSITION:
4445 HIMC hIMC;
4447 ME_Style *style = ME_GetInsertStyle(editor, 0);
4448 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4449 ME_DeleteSelection(editor);
4450 ME_SaveTempStyle(editor);
4451 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4453 LPWSTR lpCompStr = NULL;
4454 DWORD dwBufLen;
4455 DWORD dwIndex = lParam & GCS_RESULTSTR;
4456 if (!dwIndex)
4457 dwIndex = GCS_COMPSTR;
4459 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4460 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4461 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4462 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4463 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4464 HeapFree(GetProcessHeap(), 0, lpCompStr);
4466 if (dwIndex == GCS_COMPSTR)
4467 ME_SetSelection(editor,editor->imeStartIndex,
4468 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4470 ME_ReleaseStyle(style);
4471 ME_CommitUndo(editor);
4472 ME_UpdateRepaint(editor, FALSE);
4473 return 0;
4475 case WM_IME_ENDCOMPOSITION:
4477 ME_DeleteSelection(editor);
4478 editor->imeStartIndex=-1;
4479 return 0;
4481 case EM_GETOLEINTERFACE:
4483 if (!editor->reOle)
4484 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4485 return 0;
4486 *(LPVOID *)lParam = editor->reOle;
4487 IRichEditOle_AddRef(editor->reOle);
4488 return 1;
4490 case EM_GETPASSWORDCHAR:
4492 return editor->cPasswordMask;
4494 case EM_SETOLECALLBACK:
4495 if(editor->lpOleCallback)
4496 IRichEditOleCallback_Release(editor->lpOleCallback);
4497 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4498 if(editor->lpOleCallback)
4499 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4500 return TRUE;
4501 case EM_GETWORDBREAKPROC:
4502 return (LRESULT)editor->pfnWordBreak;
4503 case EM_SETWORDBREAKPROC:
4505 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4507 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4508 return (LRESULT)pfnOld;
4510 case EM_GETTEXTMODE:
4511 return editor->mode;
4512 case EM_SETTEXTMODE:
4514 int mask = 0;
4515 int changes = 0;
4517 if (ME_GetTextLength(editor) ||
4518 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4519 return E_UNEXPECTED;
4521 /* Check for mutually exclusive flags in adjacent bits of wParam */
4522 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4523 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4524 return E_INVALIDARG;
4526 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4528 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4529 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4530 if (wParam & TM_PLAINTEXT) {
4531 /* Clear selection since it should be possible to select the
4532 * end of text run for rich text */
4533 ME_InvalidateSelection(editor);
4534 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4535 editor->pCursors[1] = editor->pCursors[0];
4536 /* plain text can only have the default style. */
4537 ME_ClearTempStyle(editor);
4538 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4539 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4540 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4543 /* FIXME: Currently no support for undo level and code page options */
4544 editor->mode = (editor->mode & ~mask) | changes;
4545 return 0;
4547 case EM_SETPASSWORDCHAR:
4549 editor->cPasswordMask = wParam;
4550 ME_RewrapRepaint(editor);
4551 return 0;
4553 case EM_SETTARGETDEVICE:
4554 if (wParam == 0)
4556 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4557 if (editor->nAvailWidth || editor->bWordWrap != new)
4559 editor->bWordWrap = new;
4560 editor->nAvailWidth = 0; /* wrap to client area */
4561 ME_RewrapRepaint(editor);
4563 } else {
4564 int width = max(0, lParam);
4565 if ((editor->styleFlags & ES_MULTILINE) &&
4566 (!editor->bWordWrap || editor->nAvailWidth != width))
4568 editor->nAvailWidth = width;
4569 editor->bWordWrap = TRUE;
4570 ME_RewrapRepaint(editor);
4572 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4574 return TRUE;
4575 default:
4576 do_default:
4577 *phresult = S_FALSE;
4578 break;
4580 return 0L;
4583 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4584 LPARAM lParam, BOOL unicode)
4586 ME_TextEditor *editor;
4587 HRESULT hresult;
4588 LRESULT lresult = 0;
4590 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4591 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4593 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4594 if (!editor)
4596 if (msg == WM_NCCREATE)
4598 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4599 ITextHost *texthost;
4601 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4602 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4603 return texthost != NULL;
4605 else
4607 return DefWindowProcW(hWnd, msg, wParam, lParam);
4611 switch (msg)
4613 case WM_PAINT:
4615 HDC hDC;
4616 RECT rc;
4617 PAINTSTRUCT ps;
4619 hDC = BeginPaint(editor->hWnd, &ps);
4620 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4621 ME_SendOldNotify(editor, EN_UPDATE);
4622 /* Erase area outside of the formatting rectangle */
4623 if (ps.rcPaint.top < editor->rcFormat.top)
4625 rc = ps.rcPaint;
4626 rc.bottom = editor->rcFormat.top;
4627 FillRect(hDC, &rc, editor->hbrBackground);
4628 ps.rcPaint.top = editor->rcFormat.top;
4630 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4631 rc = ps.rcPaint;
4632 rc.top = editor->rcFormat.bottom;
4633 FillRect(hDC, &rc, editor->hbrBackground);
4634 ps.rcPaint.bottom = editor->rcFormat.bottom;
4636 if (ps.rcPaint.left < editor->rcFormat.left) {
4637 rc = ps.rcPaint;
4638 rc.right = editor->rcFormat.left;
4639 FillRect(hDC, &rc, editor->hbrBackground);
4640 ps.rcPaint.left = editor->rcFormat.left;
4642 if (ps.rcPaint.right > editor->rcFormat.right) {
4643 rc = ps.rcPaint;
4644 rc.left = editor->rcFormat.right;
4645 FillRect(hDC, &rc, editor->hbrBackground);
4646 ps.rcPaint.right = editor->rcFormat.right;
4649 ME_PaintContent(editor, hDC, &ps.rcPaint);
4650 EndPaint(editor->hWnd, &ps);
4651 return 0;
4653 case WM_ERASEBKGND:
4655 HDC hDC = (HDC)wParam;
4656 RECT rc;
4658 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4659 FillRect(hDC, &rc, editor->hbrBackground);
4660 return 1;
4662 case EM_SETOPTIONS:
4664 DWORD dwStyle;
4665 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4666 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4667 ECO_SELECTIONBAR;
4668 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4669 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4670 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4671 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4672 return lresult;
4674 case EM_SETREADONLY:
4676 DWORD dwStyle;
4677 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4678 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4679 dwStyle &= ~ES_READONLY;
4680 if (wParam)
4681 dwStyle |= ES_READONLY;
4682 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4683 return lresult;
4685 default:
4686 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4689 if (hresult == S_FALSE)
4690 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4692 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4693 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4695 return lresult;
4698 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4700 BOOL unicode = TRUE;
4702 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4703 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4704 unicode = FALSE;
4706 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4709 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4711 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4714 /******************************************************************
4715 * RichEditANSIWndProc (RICHED20.10)
4717 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4719 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4722 /******************************************************************
4723 * RichEdit10ANSIWndProc (RICHED20.9)
4725 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4727 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4729 ITextHost *texthost;
4730 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4732 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4733 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4734 return texthost != NULL;
4736 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4739 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4741 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4744 /* Fill buffer with srcChars unicode characters from the start cursor.
4746 * buffer: destination buffer
4747 * buflen: length of buffer in characters excluding the NULL terminator.
4748 * start: start of editor text to copy into buffer.
4749 * srcChars: Number of characters to use from the editor text.
4750 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4752 * returns the number of characters written excluding the NULL terminator.
4754 * The written text is always NULL terminated.
4756 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4757 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4758 BOOL bEOP)
4760 ME_DisplayItem *pRun, *pNextRun;
4761 const WCHAR *pStart = buffer;
4762 const WCHAR cr_lf[] = {'\r', '\n', 0};
4763 const WCHAR *str;
4764 int nLen;
4766 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4767 if (editor->bEmulateVersion10) bCRLF = FALSE;
4769 pRun = start->pRun;
4770 assert(pRun);
4771 pNextRun = ME_FindItemFwd(pRun, diRun);
4773 nLen = pRun->member.run.len - start->nOffset;
4774 str = get_text( &pRun->member.run, start->nOffset );
4776 while (srcChars && buflen && pNextRun)
4778 int nFlags = pRun->member.run.nFlags;
4780 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4782 if (buflen == 1) break;
4783 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4784 * EM_GETTEXTEX, however, this is done for copying text which
4785 * also uses this function. */
4786 srcChars -= min(nLen, srcChars);
4787 nLen = 2;
4788 str = cr_lf;
4789 } else {
4790 nLen = min(nLen, srcChars);
4791 srcChars -= nLen;
4794 nLen = min(nLen, buflen);
4795 buflen -= nLen;
4797 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4799 buffer += nLen;
4801 pRun = pNextRun;
4802 pNextRun = ME_FindItemFwd(pRun, diRun);
4804 nLen = pRun->member.run.len;
4805 str = get_text( &pRun->member.run, 0 );
4807 /* append '\r' to the last paragraph. */
4808 if (pRun->next->type == diTextEnd && bEOP)
4810 *buffer = '\r';
4811 buffer ++;
4813 *buffer = 0;
4814 return buffer - pStart;
4817 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4819 WNDCLASSW wcW;
4820 WNDCLASSA wcA;
4822 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4823 wcW.lpfnWndProc = RichEditWndProcW;
4824 wcW.cbClsExtra = 0;
4825 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4826 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4827 wcW.hIcon = NULL;
4828 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4829 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4830 wcW.lpszMenuName = NULL;
4832 if (is_version_nt())
4834 wcW.lpszClassName = RICHEDIT_CLASS20W;
4835 if (!RegisterClassW(&wcW)) return FALSE;
4836 wcW.lpszClassName = MSFTEDIT_CLASS;
4837 if (!RegisterClassW(&wcW)) return FALSE;
4839 else
4841 /* WNDCLASSA/W have the same layout */
4842 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4843 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4844 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4845 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4848 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4849 wcA.lpfnWndProc = RichEditWndProcA;
4850 wcA.cbClsExtra = 0;
4851 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4852 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4853 wcA.hIcon = NULL;
4854 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4855 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4856 wcA.lpszMenuName = NULL;
4857 wcA.lpszClassName = RICHEDIT_CLASS20A;
4858 if (!RegisterClassA(&wcA)) return FALSE;
4859 wcA.lpszClassName = "RichEdit50A";
4860 if (!RegisterClassA(&wcA)) return FALSE;
4862 return TRUE;
4865 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4866 /* FIXME: Not implemented */
4867 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4868 hWnd, msg, get_msg_name(msg), wParam, lParam);
4869 return DefWindowProcW(hWnd, msg, wParam, lParam);
4872 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4873 /* FIXME: Not implemented */
4874 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4875 hWnd, msg, get_msg_name(msg), wParam, lParam);
4876 return DefWindowProcW(hWnd, msg, wParam, lParam);
4879 /******************************************************************
4880 * REExtendedRegisterClass (RICHED20.8)
4882 * FIXME undocumented
4883 * Need to check for errors and implement controls and callbacks
4885 LRESULT WINAPI REExtendedRegisterClass(void)
4887 WNDCLASSW wcW;
4888 UINT result;
4890 FIXME("semi stub\n");
4892 wcW.cbClsExtra = 0;
4893 wcW.cbWndExtra = 4;
4894 wcW.hInstance = NULL;
4895 wcW.hIcon = NULL;
4896 wcW.hCursor = NULL;
4897 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4898 wcW.lpszMenuName = NULL;
4900 if (!ME_ListBoxRegistered)
4902 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4903 wcW.lpfnWndProc = REListWndProc;
4904 wcW.lpszClassName = REListBox20W;
4905 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4908 if (!ME_ComboBoxRegistered)
4910 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4911 wcW.lpfnWndProc = REComboWndProc;
4912 wcW.lpszClassName = REComboBox20W;
4913 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4916 result = 0;
4917 if (ME_ListBoxRegistered)
4918 result += 1;
4919 if (ME_ComboBoxRegistered)
4920 result += 2;
4922 return result;
4925 static BOOL isurlspecial(WCHAR c)
4927 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4928 return strchrW( special_chars, c ) != NULL;
4932 * This proc takes a selection, and scans it forward in order to select the span
4933 * of a possible URL candidate. A possible URL candidate must start with isalnum
4934 * or one of the following special characters: *|/\+%#@ and must consist entirely
4935 * of the characters allowed to start the URL, plus : (colon) which may occur
4936 * at most once, and not at either end.
4938 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4939 const ME_Cursor *start,
4940 int nChars,
4941 ME_Cursor *candidate_min,
4942 ME_Cursor *candidate_max)
4944 ME_Cursor cursor = *start;
4945 BOOL foundColon = FALSE;
4946 BOOL candidateStarted = FALSE;
4947 WCHAR lastAcceptedChar = '\0';
4949 while (nChars > 0)
4951 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4952 WCHAR *str = strStart + cursor.nOffset;
4953 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4954 nChars -= nLen;
4956 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4958 /* Find start of candidate */
4959 if (!candidateStarted)
4961 while (nLen)
4963 nLen--;
4964 if (isalnumW(*str) || isurlspecial(*str))
4966 cursor.nOffset = str - strStart;
4967 *candidate_min = cursor;
4968 candidateStarted = TRUE;
4969 lastAcceptedChar = *str++;
4970 break;
4972 str++;
4976 /* Find end of candidate */
4977 if (candidateStarted) {
4978 while (nLen)
4980 nLen--;
4981 if (*str == ':' && !foundColon) {
4982 foundColon = TRUE;
4983 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4984 cursor.nOffset = str - strStart;
4985 if (lastAcceptedChar == ':')
4986 ME_MoveCursorChars(editor, &cursor, -1);
4987 *candidate_max = cursor;
4988 return TRUE;
4990 lastAcceptedChar = *str++;
4993 } else {
4994 /* End of paragraph: skip it if before candidate span, or terminates
4995 current active span */
4996 if (candidateStarted) {
4997 if (lastAcceptedChar == ':')
4998 ME_MoveCursorChars(editor, &cursor, -1);
4999 *candidate_max = cursor;
5000 return TRUE;
5004 /* Reaching this point means no span was found, so get next span */
5005 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
5006 if (candidateStarted) {
5007 /* There are no further runs, so take end of text as end of candidate */
5008 cursor.nOffset = str - strStart;
5009 if (lastAcceptedChar == ':')
5010 ME_MoveCursorChars(editor, &cursor, -1);
5011 *candidate_max = cursor;
5012 return TRUE;
5014 *candidate_max = *candidate_min = cursor;
5015 return FALSE;
5017 cursor.nOffset = 0;
5020 if (candidateStarted) {
5021 /* There are no further runs, so take end of text as end of candidate */
5022 if (lastAcceptedChar == ':')
5023 ME_MoveCursorChars(editor, &cursor, -1);
5024 *candidate_max = cursor;
5025 return TRUE;
5027 *candidate_max = *candidate_min = cursor;
5028 return FALSE;
5032 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5034 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5036 #define MAX_PREFIX_LEN 9
5037 struct prefix_s {
5038 const WCHAR text[MAX_PREFIX_LEN];
5039 int length;
5040 }prefixes[] = {
5041 {{'p','r','o','s','p','e','r','o',':'}, 9},
5042 {{'t','e','l','n','e','t',':'}, 7},
5043 {{'g','o','p','h','e','r',':'}, 7},
5044 {{'m','a','i','l','t','o',':'}, 7},
5045 {{'h','t','t','p','s',':'}, 6},
5046 {{'f','i','l','e',':'}, 5},
5047 {{'n','e','w','s',':'}, 5},
5048 {{'w','a','i','s',':'}, 5},
5049 {{'n','n','t','p',':'}, 5},
5050 {{'h','t','t','p',':'}, 5},
5051 {{'w','w','w','.'}, 4},
5052 {{'f','t','p',':'}, 4},
5054 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5055 unsigned int i;
5057 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5058 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5060 if (nChars < prefixes[i].length) continue;
5061 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5062 return TRUE;
5064 return FALSE;
5065 #undef MAX_PREFIX_LEN
5069 * This proc walks through the indicated selection and evaluates whether each
5070 * section identified by ME_FindNextURLCandidate and in-between sections have
5071 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5072 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5074 * Since this function can cause runs to be split, do not depend on the value
5075 * of the start cursor at the end of the function.
5077 * nChars may be set to INT_MAX to update to the end of the text.
5079 * Returns TRUE if at least one section was modified.
5081 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5083 BOOL modified = FALSE;
5084 ME_Cursor startCur = *start;
5086 if (!editor->AutoURLDetect_bEnable) return FALSE;
5090 CHARFORMAT2W link;
5091 ME_Cursor candidateStart, candidateEnd;
5093 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5094 &candidateStart, &candidateEnd))
5096 /* Section before candidate is not an URL */
5097 int cMin = ME_GetCursorOfs(&candidateStart);
5098 int cMax = ME_GetCursorOfs(&candidateEnd);
5100 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5101 candidateStart = candidateEnd;
5102 nChars -= cMax - ME_GetCursorOfs(&startCur);
5104 else
5106 /* No more candidates until end of selection */
5107 nChars = 0;
5110 if (startCur.pRun != candidateStart.pRun ||
5111 startCur.nOffset != candidateStart.nOffset)
5113 /* CFE_LINK effect should be consistently unset */
5114 link.cbSize = sizeof(link);
5115 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5116 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5118 /* CFE_LINK must be unset from this range */
5119 memset(&link, 0, sizeof(CHARFORMAT2W));
5120 link.cbSize = sizeof(link);
5121 link.dwMask = CFM_LINK;
5122 link.dwEffects = 0;
5123 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5124 /* Update candidateEnd since setting character formats may split
5125 * runs, which can cause a cursor to be at an invalid offset within
5126 * a split run. */
5127 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5129 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5130 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5132 modified = TRUE;
5135 if (candidateStart.pRun != candidateEnd.pRun ||
5136 candidateStart.nOffset != candidateEnd.nOffset)
5138 /* CFE_LINK effect should be consistently set */
5139 link.cbSize = sizeof(link);
5140 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5141 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5143 /* CFE_LINK must be set on this range */
5144 memset(&link, 0, sizeof(CHARFORMAT2W));
5145 link.cbSize = sizeof(link);
5146 link.dwMask = CFM_LINK;
5147 link.dwEffects = CFE_LINK;
5148 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5149 modified = TRUE;
5152 startCur = candidateEnd;
5153 } while (nChars > 0);
5154 return modified;