dmime: Remove the extraneous IUnknown from DMSegTriggerTrack.
[wine.git] / dlls / riched20 / editor.c
blob276636f091221a348273ee09c4710f1f0667ca18
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, TRUE);
1715 static int
1716 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1718 const int nLen = lstrlenW(text);
1719 const int nTextLen = ME_GetTextLength(editor);
1720 int nMin, nMax;
1721 ME_Cursor cursor;
1722 WCHAR wLastChar = ' ';
1724 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1725 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1727 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1728 FIXME("Flags 0x%08x not implemented\n",
1729 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1731 nMin = chrg->cpMin;
1732 if (chrg->cpMax == -1)
1733 nMax = nTextLen;
1734 else
1735 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1737 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1738 if (editor->bEmulateVersion10 && nMax == nTextLen)
1740 flags |= FR_DOWN;
1743 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1744 if (editor->bEmulateVersion10 && nMax < nMin)
1746 if (chrgText)
1748 chrgText->cpMin = -1;
1749 chrgText->cpMax = -1;
1751 return -1;
1754 /* when searching up, if cpMin < cpMax, then instead of searching
1755 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1756 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1757 * case, it is always bigger than cpMin.
1759 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1761 int nSwap = nMax;
1763 nMax = nMin > nTextLen ? nTextLen : nMin;
1764 if (nMin < nSwap || chrg->cpMax == -1)
1765 nMin = 0;
1766 else
1767 nMin = nSwap;
1770 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1772 if (chrgText)
1773 chrgText->cpMin = chrgText->cpMax = -1;
1774 return -1;
1777 if (flags & FR_DOWN) /* Forward search */
1779 /* If possible, find the character before where the search starts */
1780 if ((flags & FR_WHOLEWORD) && nMin)
1782 ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1783 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1784 ME_MoveCursorChars(editor, &cursor, 1);
1785 } else {
1786 ME_CursorFromCharOfs(editor, nMin, &cursor);
1789 while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1791 ME_DisplayItem *pCurItem = cursor.pRun;
1792 int nCurStart = cursor.nOffset;
1793 int nMatched = 0;
1795 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurStart + nMatched ), text[nMatched], (flags & FR_MATCHCASE)))
1797 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1798 break;
1800 nMatched++;
1801 if (nMatched == nLen)
1803 ME_DisplayItem *pNextItem = pCurItem;
1804 int nNextStart = nCurStart;
1805 WCHAR wNextChar;
1807 /* Check to see if next character is a whitespace */
1808 if (flags & FR_WHOLEWORD)
1810 if (nCurStart + nMatched == pCurItem->member.run.len)
1812 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1813 nNextStart = -nMatched;
1816 if (pNextItem)
1817 wNextChar = *get_text( &pNextItem->member.run, nNextStart + nMatched );
1818 else
1819 wNextChar = ' ';
1821 if (isalnumW(wNextChar))
1822 break;
1825 cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1826 if (chrgText)
1828 chrgText->cpMin = cursor.nOffset;
1829 chrgText->cpMax = cursor.nOffset + nLen;
1831 TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1832 return cursor.nOffset;
1834 if (nCurStart + nMatched == pCurItem->member.run.len)
1836 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1837 nCurStart = -nMatched;
1840 if (pCurItem)
1841 wLastChar = *get_text( &pCurItem->member.run, nCurStart + nMatched );
1842 else
1843 wLastChar = ' ';
1845 cursor.nOffset++;
1846 if (cursor.nOffset == cursor.pRun->member.run.len)
1848 ME_NextRun(&cursor.pPara, &cursor.pRun);
1849 cursor.nOffset = 0;
1853 else /* Backward search */
1855 /* If possible, find the character after where the search ends */
1856 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1858 ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1859 wLastChar = *get_text( &cursor.pRun->member.run, cursor.nOffset );
1860 ME_MoveCursorChars(editor, &cursor, -1);
1861 } else {
1862 ME_CursorFromCharOfs(editor, nMax, &cursor);
1865 while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1867 ME_DisplayItem *pCurItem = cursor.pRun;
1868 ME_DisplayItem *pCurPara = cursor.pPara;
1869 int nCurEnd = cursor.nOffset;
1870 int nMatched = 0;
1872 if (nCurEnd == 0)
1874 ME_PrevRun(&pCurPara, &pCurItem);
1875 nCurEnd = pCurItem->member.run.len;
1878 while (pCurItem && ME_CharCompare( *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 ),
1879 text[nLen - nMatched - 1], (flags & FR_MATCHCASE) ))
1881 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1882 break;
1884 nMatched++;
1885 if (nMatched == nLen)
1887 ME_DisplayItem *pPrevItem = pCurItem;
1888 int nPrevEnd = nCurEnd;
1889 WCHAR wPrevChar;
1890 int nStart;
1892 /* Check to see if previous character is a whitespace */
1893 if (flags & FR_WHOLEWORD)
1895 if (nPrevEnd - nMatched == 0)
1897 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1898 if (pPrevItem)
1899 nPrevEnd = pPrevItem->member.run.len + nMatched;
1902 if (pPrevItem)
1903 wPrevChar = *get_text( &pPrevItem->member.run, nPrevEnd - nMatched - 1 );
1904 else
1905 wPrevChar = ' ';
1907 if (isalnumW(wPrevChar))
1908 break;
1911 nStart = pCurPara->member.para.nCharOfs
1912 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1913 if (chrgText)
1915 chrgText->cpMin = nStart;
1916 chrgText->cpMax = nStart + nLen;
1918 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1919 return nStart;
1921 if (nCurEnd - nMatched == 0)
1923 ME_PrevRun(&pCurPara, &pCurItem);
1924 /* Don't care about pCurItem becoming NULL here; it's already taken
1925 * care of in the exterior loop condition */
1926 nCurEnd = pCurItem->member.run.len + nMatched;
1929 if (pCurItem)
1930 wLastChar = *get_text( &pCurItem->member.run, nCurEnd - nMatched - 1 );
1931 else
1932 wLastChar = ' ';
1934 cursor.nOffset--;
1935 if (cursor.nOffset < 0)
1937 ME_PrevRun(&cursor.pPara, &cursor.pRun);
1938 cursor.nOffset = cursor.pRun->member.run.len;
1942 TRACE("not found\n");
1943 if (chrgText)
1944 chrgText->cpMin = chrgText->cpMax = -1;
1945 return -1;
1948 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1950 int nChars;
1951 ME_Cursor start;
1953 if (!ex->cb || !pText) return 0;
1955 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1956 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1958 if (ex->flags & GT_SELECTION)
1960 int from, to;
1961 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1962 start = editor->pCursors[nStartCur];
1963 nChars = to - from;
1965 else
1967 ME_SetCursorToStart(editor, &start);
1968 nChars = INT_MAX;
1970 if (ex->codepage == CP_UNICODE)
1972 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1973 &start, nChars, ex->flags & GT_USECRLF, FALSE);
1975 else
1977 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1978 we can just take a bigger buffer? :)
1979 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1980 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1982 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1983 DWORD buflen;
1984 LPWSTR buffer;
1985 LRESULT rc;
1987 buflen = min(crlfmul * nChars, ex->cb - 1);
1988 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1990 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF, FALSE);
1991 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1992 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1993 if (rc) rc--; /* do not count 0 terminator */
1995 heap_free(buffer);
1996 return rc;
2000 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
2001 const ME_Cursor *start, int nLen, BOOL unicode)
2003 if (!strText) return 0;
2004 if (unicode) {
2005 return ME_GetTextW(editor, strText, INT_MAX, start, nLen, FALSE, FALSE);
2006 } else {
2007 int nChars;
2008 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2009 if (!p) return 0;
2010 nChars = ME_GetTextW(editor, p, nLen, start, nLen, FALSE, FALSE);
2011 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
2012 nLen+1, NULL, NULL);
2013 FREE_OBJ(p);
2014 return nChars;
2018 static int handle_EM_EXSETSEL( ME_TextEditor *editor, int to, int from )
2020 int end;
2022 TRACE("%d - %d\n", to, from );
2024 ME_InvalidateSelection( editor );
2025 end = ME_SetSelection( editor, to, from );
2026 ME_InvalidateSelection( editor );
2027 ITextHost_TxShowCaret( editor->texthost, FALSE );
2028 ME_ShowCaret( editor );
2029 ME_SendSelChange( editor );
2031 return end;
2034 typedef struct tagME_GlobalDestStruct
2036 HGLOBAL hData;
2037 int nLength;
2038 } ME_GlobalDestStruct;
2040 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2042 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2043 int i;
2044 WORD *pSrc, *pDest;
2046 cb = cb >> 1;
2047 pDest = (WORD *)lpBuff;
2048 pSrc = GlobalLock(pData->hData);
2049 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2050 pDest[i] = pSrc[pData->nLength+i];
2052 pData->nLength += i;
2053 *pcb = 2*i;
2054 GlobalUnlock(pData->hData);
2055 return 0;
2058 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2060 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2061 int i;
2062 BYTE *pSrc, *pDest;
2064 pDest = lpBuff;
2065 pSrc = GlobalLock(pData->hData);
2066 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2067 pDest[i] = pSrc[pData->nLength+i];
2069 pData->nLength += i;
2070 *pcb = i;
2071 GlobalUnlock(pData->hData);
2072 return 0;
2075 static BOOL ME_Paste(ME_TextEditor *editor)
2077 DWORD dwFormat = 0;
2078 EDITSTREAM es;
2079 ME_GlobalDestStruct gds;
2080 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2081 UINT cf = 0;
2083 if (IsClipboardFormatAvailable(nRTFFormat))
2084 cf = nRTFFormat, dwFormat = SF_RTF;
2085 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2086 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2087 else
2088 return FALSE;
2090 if (!OpenClipboard(editor->hWnd))
2091 return FALSE;
2092 gds.hData = GetClipboardData(cf);
2093 gds.nLength = 0;
2094 es.dwCookie = (DWORD_PTR)&gds;
2095 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2096 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2098 CloseClipboard();
2099 return TRUE;
2102 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2104 LPDATAOBJECT dataObj = NULL;
2105 HRESULT hr = S_OK;
2107 if (editor->cPasswordMask)
2108 return FALSE; /* Copying or Cutting masked text isn't allowed */
2110 if(editor->lpOleCallback)
2112 CHARRANGE range;
2113 range.cpMin = ME_GetCursorOfs(start);
2114 range.cpMax = range.cpMin + nChars;
2115 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2117 if(FAILED(hr) || !dataObj)
2118 hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2119 if(SUCCEEDED(hr)) {
2120 hr = OleSetClipboard(dataObj);
2121 IDataObject_Release(dataObj);
2123 return SUCCEEDED(hr);
2126 /* helper to send a msg filter notification */
2127 static BOOL
2128 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2130 MSGFILTER msgf;
2132 if (!editor->hWnd || !editor->hwndParent) return FALSE;
2133 msgf.nmhdr.hwndFrom = editor->hWnd;
2134 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2135 msgf.nmhdr.code = EN_MSGFILTER;
2136 msgf.msg = msg;
2137 msgf.wParam = *wParam;
2138 msgf.lParam = *lParam;
2139 if (SendMessageW(editor->hwndParent, WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2140 return FALSE;
2141 *wParam = msgf.wParam;
2142 *lParam = msgf.lParam;
2143 msgf.wParam = *wParam;
2145 return TRUE;
2148 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2150 ME_DisplayItem *startPara, *endPara;
2151 ME_DisplayItem *prev_para;
2152 ME_Cursor *from, *to;
2153 ME_Cursor start;
2154 int nChars;
2156 if (!editor->AutoURLDetect_bEnable) return;
2158 ME_GetSelection(editor, &from, &to);
2160 /* Find paragraph previous to the one that contains start cursor */
2161 startPara = from->pPara;
2162 prev_para = startPara->member.para.prev_para;
2163 if (prev_para->type == diParagraph) startPara = prev_para;
2165 /* Find paragraph that contains end cursor */
2166 endPara = to->pPara->member.para.next_para;
2168 start.pPara = startPara;
2169 start.pRun = ME_FindItemFwd(startPara, diRun);
2170 start.nOffset = 0;
2171 nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2173 ME_UpdateLinkAttribute(editor, &start, nChars);
2176 static BOOL
2177 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2179 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2180 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2182 if (editor->bMouseCaptured)
2183 return FALSE;
2184 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2185 editor->nSelectionType = stPosition;
2187 switch (nKey)
2189 case VK_LEFT:
2190 case VK_RIGHT:
2191 case VK_HOME:
2192 case VK_END:
2193 editor->nUDArrowX = -1;
2194 /* fall through */
2195 case VK_UP:
2196 case VK_DOWN:
2197 case VK_PRIOR:
2198 case VK_NEXT:
2199 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2200 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2201 return TRUE;
2202 case VK_BACK:
2203 case VK_DELETE:
2204 editor->nUDArrowX = -1;
2205 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2206 if (editor->styleFlags & ES_READONLY)
2207 return FALSE;
2208 if (ME_IsSelection(editor))
2210 ME_DeleteSelection(editor);
2211 ME_CommitUndo(editor);
2213 else if (nKey == VK_DELETE)
2215 /* Delete stops group typing.
2216 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2217 ME_DeleteTextAtCursor(editor, 1, 1);
2218 ME_CommitUndo(editor);
2220 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2222 BOOL bDeletionSucceeded;
2223 /* Backspace can be grouped for a single undo */
2224 ME_ContinueCoalescingTransaction(editor);
2225 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2226 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2227 /* Deletion was prevented so the cursor is moved back to where it was.
2228 * (e.g. this happens when trying to delete cell boundaries)
2230 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2232 ME_CommitCoalescingUndo(editor);
2234 else
2235 return TRUE;
2236 ME_MoveCursorFromTableRowStartParagraph(editor);
2237 ME_UpdateSelectionLinkAttribute(editor);
2238 ME_UpdateRepaint(editor, FALSE);
2239 ME_SendRequestResize(editor, FALSE);
2240 return TRUE;
2241 case VK_RETURN:
2242 if (editor->bDialogMode)
2244 if (ctrl_is_down)
2245 return TRUE;
2247 if (!(editor->styleFlags & ES_WANTRETURN))
2249 if (editor->hwndParent)
2251 DWORD dw;
2252 dw = SendMessageW(editor->hwndParent, DM_GETDEFID, 0, 0);
2253 if (HIWORD(dw) == DC_HASDEFID)
2255 HWND hwDefCtrl = GetDlgItem(editor->hwndParent, LOWORD(dw));
2256 if (hwDefCtrl)
2258 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, (WPARAM)hwDefCtrl, TRUE);
2259 PostMessageW(hwDefCtrl, WM_KEYDOWN, VK_RETURN, 0);
2263 return TRUE;
2267 if (editor->styleFlags & ES_MULTILINE)
2269 ME_Cursor cursor = editor->pCursors[0];
2270 ME_DisplayItem *para = cursor.pPara;
2271 int from, to;
2272 const WCHAR endl = '\r';
2273 const WCHAR endlv10[] = {'\r','\n'};
2274 ME_Style *style;
2276 if (editor->styleFlags & ES_READONLY) {
2277 MessageBeep(MB_ICONERROR);
2278 return TRUE;
2281 ME_GetSelectionOfs(editor, &from, &to);
2282 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2284 if (!editor->bEmulateVersion10) { /* v4.1 */
2285 if (para->member.para.nFlags & MEPF_ROWEND) {
2286 /* Add a new table row after this row. */
2287 para = ME_AppendTableRow(editor, para);
2288 para = para->member.para.next_para;
2289 editor->pCursors[0].pPara = para;
2290 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2291 editor->pCursors[0].nOffset = 0;
2292 editor->pCursors[1] = editor->pCursors[0];
2293 ME_CommitUndo(editor);
2294 ME_CheckTablesForCorruption(editor);
2295 ME_UpdateRepaint(editor, FALSE);
2296 return TRUE;
2298 else if (para == editor->pCursors[1].pPara &&
2299 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2300 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2301 !para->member.para.prev_para->member.para.nCharOfs)
2303 /* Insert a newline before the table. */
2304 para = para->member.para.prev_para;
2305 para->member.para.nFlags &= ~MEPF_ROWSTART;
2306 editor->pCursors[0].pPara = para;
2307 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2308 editor->pCursors[1] = editor->pCursors[0];
2309 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2310 editor->pCursors[0].pRun->member.run.style);
2311 para = editor->pBuffer->pFirst->member.para.next_para;
2312 ME_SetDefaultParaFormat(para->member.para.pFmt);
2313 para->member.para.nFlags = MEPF_REWRAP;
2314 editor->pCursors[0].pPara = para;
2315 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2316 editor->pCursors[1] = editor->pCursors[0];
2317 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2318 ME_CommitCoalescingUndo(editor);
2319 ME_CheckTablesForCorruption(editor);
2320 ME_UpdateRepaint(editor, FALSE);
2321 return TRUE;
2323 } else { /* v1.0 - 3.0 */
2324 ME_DisplayItem *para = cursor.pPara;
2325 if (ME_IsInTable(para))
2327 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2329 if (from == to) {
2330 ME_ContinueCoalescingTransaction(editor);
2331 para = ME_AppendTableRow(editor, para);
2332 editor->pCursors[0].pPara = para;
2333 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2334 editor->pCursors[0].nOffset = 0;
2335 editor->pCursors[1] = editor->pCursors[0];
2336 ME_CommitCoalescingUndo(editor);
2337 ME_UpdateRepaint(editor, FALSE);
2338 return TRUE;
2340 } else {
2341 ME_ContinueCoalescingTransaction(editor);
2342 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2343 !ME_IsInTable(para->member.para.prev_para))
2345 /* Insert newline before table */
2346 cursor.pRun = ME_FindItemBack(para, diRun);
2347 if (cursor.pRun) {
2348 editor->pCursors[0].pRun = cursor.pRun;
2349 editor->pCursors[0].pPara = para->member.para.prev_para;
2351 editor->pCursors[0].nOffset = 0;
2352 editor->pCursors[1] = editor->pCursors[0];
2353 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2354 editor->pCursors[0].pRun->member.run.style);
2355 } else {
2356 editor->pCursors[1] = editor->pCursors[0];
2357 para = ME_AppendTableRow(editor, para);
2358 editor->pCursors[0].pPara = para;
2359 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2360 editor->pCursors[0].nOffset = 0;
2361 editor->pCursors[1] = editor->pCursors[0];
2363 ME_CommitCoalescingUndo(editor);
2364 ME_UpdateRepaint(editor, FALSE);
2365 return TRUE;
2370 style = ME_GetInsertStyle(editor, 0);
2371 ME_SaveTempStyle(editor);
2372 ME_ContinueCoalescingTransaction(editor);
2373 if (shift_is_down)
2374 ME_InsertEndRowFromCursor(editor, 0);
2375 else
2376 if (!editor->bEmulateVersion10)
2377 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2378 else
2379 ME_InsertTextFromCursor(editor, 0, endlv10, 2, style);
2380 ME_ReleaseStyle(style);
2381 ME_CommitCoalescingUndo(editor);
2382 SetCursor(NULL);
2384 ME_UpdateSelectionLinkAttribute(editor);
2385 ME_UpdateRepaint(editor, FALSE);
2387 return TRUE;
2389 break;
2390 case VK_ESCAPE:
2391 if (editor->bDialogMode && editor->hwndParent)
2392 PostMessageW(editor->hwndParent, WM_CLOSE, 0, 0);
2393 return TRUE;
2394 case VK_TAB:
2395 if (editor->bDialogMode && editor->hwndParent)
2396 SendMessageW(editor->hwndParent, WM_NEXTDLGCTL, shift_is_down, 0);
2397 return TRUE;
2398 case 'A':
2399 if (ctrl_is_down)
2401 handle_EM_EXSETSEL( editor, 0, -1 );
2402 return TRUE;
2404 break;
2405 case 'V':
2406 if (ctrl_is_down)
2407 return ME_Paste(editor);
2408 break;
2409 case 'C':
2410 case 'X':
2411 if (ctrl_is_down)
2413 BOOL result;
2414 int nOfs, nChars;
2415 int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2416 ME_Cursor *selStart = &editor->pCursors[nStartCur];
2418 nChars -= nOfs;
2419 result = ME_Copy(editor, selStart, nChars);
2420 if (result && nKey == 'X')
2422 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2423 ME_CommitUndo(editor);
2424 ME_UpdateRepaint(editor, TRUE);
2426 return result;
2428 break;
2429 case 'Z':
2430 if (ctrl_is_down)
2432 ME_Undo(editor);
2433 return TRUE;
2435 break;
2436 case 'Y':
2437 if (ctrl_is_down)
2439 ME_Redo(editor);
2440 return TRUE;
2442 break;
2444 default:
2445 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2446 editor->nUDArrowX = -1;
2447 if (ctrl_is_down)
2449 if (nKey == 'W')
2451 CHARFORMAT2W chf;
2452 char buf[2048];
2453 chf.cbSize = sizeof(chf);
2455 ME_GetSelectionCharFormat(editor, &chf);
2456 ME_DumpStyleToBuf(&chf, buf);
2457 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2459 if (nKey == 'Q')
2461 ME_CheckCharOffsets(editor);
2465 return FALSE;
2468 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2469 LPARAM flags, BOOL unicode)
2471 WCHAR wstr;
2473 if (editor->bMouseCaptured)
2474 return 0;
2476 if (unicode)
2477 wstr = (WCHAR)charCode;
2478 else
2480 CHAR charA = charCode;
2481 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2484 if (editor->styleFlags & ES_READONLY) {
2485 MessageBeep(MB_ICONERROR);
2486 return 0; /* FIXME really 0 ? */
2489 if ((unsigned)wstr >= ' ' || wstr == '\t')
2491 ME_Cursor cursor = editor->pCursors[0];
2492 ME_DisplayItem *para = cursor.pPara;
2493 int from, to;
2494 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2495 ME_GetSelectionOfs(editor, &from, &to);
2496 if (wstr == '\t' &&
2497 /* v4.1 allows tabs to be inserted with ctrl key down */
2498 !(ctrl_is_down && !editor->bEmulateVersion10))
2500 ME_DisplayItem *para;
2501 BOOL bSelectedRow = FALSE;
2503 para = cursor.pPara;
2504 if (ME_IsSelection(editor) &&
2505 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2506 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2507 para->member.para.prev_para->type == diParagraph)
2509 para = para->member.para.prev_para;
2510 bSelectedRow = TRUE;
2512 if (ME_IsInTable(para))
2514 ME_TabPressedInTable(editor, bSelectedRow);
2515 ME_CommitUndo(editor);
2516 return 0;
2518 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2519 if (para->member.para.nFlags & MEPF_ROWEND) {
2520 if (from == to) {
2521 para = para->member.para.next_para;
2522 if (para->member.para.nFlags & MEPF_ROWSTART)
2523 para = para->member.para.next_para;
2524 editor->pCursors[0].pPara = para;
2525 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2526 editor->pCursors[0].nOffset = 0;
2527 editor->pCursors[1] = editor->pCursors[0];
2530 } else { /* v1.0 - 3.0 */
2531 if (ME_IsInTable(cursor.pRun) &&
2532 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2533 from == to)
2535 /* Text should not be inserted at the end of the table. */
2536 MessageBeep(-1);
2537 return 0;
2540 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2541 /* WM_CHAR is restricted to nTextLimit */
2542 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2544 ME_Style *style = ME_GetInsertStyle(editor, 0);
2545 ME_SaveTempStyle(editor);
2546 ME_ContinueCoalescingTransaction(editor);
2547 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2548 ME_ReleaseStyle(style);
2549 ME_CommitCoalescingUndo(editor);
2550 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2553 ME_UpdateSelectionLinkAttribute(editor);
2554 ME_UpdateRepaint(editor, FALSE);
2556 return 0;
2559 /* Process the message and calculate the new click count.
2561 * returns: The click count if it is mouse down event, else returns 0. */
2562 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2563 LPARAM lParam)
2565 static int clickNum = 0;
2566 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2567 return 0;
2569 if ((msg == WM_LBUTTONDBLCLK) ||
2570 (msg == WM_RBUTTONDBLCLK) ||
2571 (msg == WM_MBUTTONDBLCLK) ||
2572 (msg == WM_XBUTTONDBLCLK))
2574 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2577 if ((msg == WM_LBUTTONDOWN) ||
2578 (msg == WM_RBUTTONDOWN) ||
2579 (msg == WM_MBUTTONDOWN) ||
2580 (msg == WM_XBUTTONDOWN))
2582 static MSG prevClickMsg;
2583 MSG clickMsg;
2584 /* Compare the editor instead of the hwnd so that the this
2585 * can still be done for windowless richedit controls. */
2586 clickMsg.hwnd = (HWND)editor;
2587 clickMsg.message = msg;
2588 clickMsg.wParam = wParam;
2589 clickMsg.lParam = lParam;
2590 clickMsg.time = GetMessageTime();
2591 clickMsg.pt.x = (short)LOWORD(lParam);
2592 clickMsg.pt.y = (short)HIWORD(lParam);
2593 if ((clickNum != 0) &&
2594 (clickMsg.message == prevClickMsg.message) &&
2595 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2596 (clickMsg.wParam == prevClickMsg.wParam) &&
2597 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2598 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2599 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2601 clickNum++;
2602 } else {
2603 clickNum = 1;
2605 prevClickMsg = clickMsg;
2606 } else {
2607 return 0;
2609 return clickNum;
2612 static BOOL ME_SetCursor(ME_TextEditor *editor)
2614 ME_Cursor cursor;
2615 POINT pt;
2616 BOOL isExact;
2617 SCROLLBARINFO sbi;
2618 DWORD messagePos = GetMessagePos();
2619 pt.x = (short)LOWORD(messagePos);
2620 pt.y = (short)HIWORD(messagePos);
2622 if (editor->hWnd)
2624 sbi.cbSize = sizeof(sbi);
2625 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2626 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2627 PtInRect(&sbi.rcScrollBar, pt))
2629 ITextHost_TxSetCursor(editor->texthost,
2630 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2631 return TRUE;
2633 sbi.cbSize = sizeof(sbi);
2634 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2635 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2636 PtInRect(&sbi.rcScrollBar, pt))
2638 ITextHost_TxSetCursor(editor->texthost,
2639 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2640 return TRUE;
2643 ITextHost_TxScreenToClient(editor->texthost, &pt);
2645 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2646 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2647 return TRUE;
2649 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2650 pt.y < editor->rcFormat.top &&
2651 pt.x < editor->rcFormat.left)
2653 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2654 return TRUE;
2656 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2658 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2659 ITextHost_TxSetCursor(editor->texthost,
2660 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2661 else /* v4.1 */
2662 ITextHost_TxSetCursor(editor->texthost,
2663 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2664 return TRUE;
2666 if (pt.x < editor->rcFormat.left)
2668 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2669 return TRUE;
2671 ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2672 if (isExact)
2674 ME_Run *run;
2676 run = &cursor.pRun->member.run;
2677 if (run->style->fmt.dwMask & CFM_LINK &&
2678 run->style->fmt.dwEffects & CFE_LINK)
2680 ITextHost_TxSetCursor(editor->texthost,
2681 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2682 FALSE);
2683 return TRUE;
2686 if (ME_IsSelection(editor))
2688 int selStart, selEnd;
2689 int offset = ME_GetCursorOfs(&cursor);
2691 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2692 if (selStart <= offset && selEnd >= offset) {
2693 ITextHost_TxSetCursor(editor->texthost,
2694 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2695 FALSE);
2696 return TRUE;
2700 ITextHost_TxSetCursor(editor->texthost,
2701 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2702 return TRUE;
2705 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2707 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2708 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2709 editor->rcFormat.left += 1 + editor->selofs;
2710 editor->rcFormat.right -= 1;
2713 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2715 CHARRANGE selrange;
2716 HMENU menu;
2717 int seltype = 0;
2718 if(!editor->lpOleCallback || !editor->hWnd)
2719 return FALSE;
2720 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2721 if(selrange.cpMin == selrange.cpMax)
2722 seltype |= SEL_EMPTY;
2723 else
2725 /* FIXME: Handle objects */
2726 seltype |= SEL_TEXT;
2727 if(selrange.cpMax-selrange.cpMin > 1)
2728 seltype |= SEL_MULTICHAR;
2730 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2732 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, editor->hwndParent, NULL);
2733 DestroyMenu(menu);
2735 return TRUE;
2738 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2740 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2741 int i;
2742 DWORD props;
2743 LONG selbarwidth;
2745 ed->hWnd = NULL;
2746 ed->hwndParent = NULL;
2747 ed->sizeWindow.cx = ed->sizeWindow.cy = 0;
2748 ed->texthost = texthost;
2749 ed->reOle = NULL;
2750 ed->bEmulateVersion10 = bEmulateVersion10;
2751 ed->styleFlags = 0;
2752 ITextHost_TxGetPropertyBits(texthost,
2753 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2754 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2755 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2756 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2757 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2758 &props);
2759 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2760 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2761 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2762 ed->pBuffer = ME_MakeText();
2763 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2764 ed->nAvailWidth = 0; /* wrap to client area */
2765 ME_MakeFirstParagraph(ed);
2766 /* The four cursors are for:
2767 * 0 - The position where the caret is shown
2768 * 1 - The anchored end of the selection (for normal selection)
2769 * 2 & 3 - The anchored start and end respectively for word, line,
2770 * or paragraph selection.
2772 ed->nCursors = 4;
2773 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2774 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2775 ed->pCursors[1] = ed->pCursors[0];
2776 ed->pCursors[2] = ed->pCursors[0];
2777 ed->pCursors[3] = ed->pCursors[1];
2778 ed->nLastTotalLength = ed->nTotalLength = 0;
2779 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2780 ed->nUDArrowX = -1;
2781 ed->rgbBackColor = -1;
2782 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2783 ed->bCaretAtEnd = FALSE;
2784 ed->nEventMask = 0;
2785 ed->nModifyStep = 0;
2786 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2787 list_init( &ed->undo_stack );
2788 list_init( &ed->redo_stack );
2789 ed->nUndoStackSize = 0;
2790 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2791 ed->nUndoMode = umAddToUndo;
2792 ed->nParagraphs = 1;
2793 ed->nLastSelStart = ed->nLastSelEnd = 0;
2794 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2795 ed->bHideSelection = FALSE;
2796 ed->pfnWordBreak = NULL;
2797 ed->lpOleCallback = NULL;
2798 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2799 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2800 ed->AutoURLDetect_bEnable = FALSE;
2801 ed->bHaveFocus = FALSE;
2802 ed->bDialogMode = FALSE;
2803 ed->bMouseCaptured = FALSE;
2804 for (i=0; i<HFONT_CACHE_SIZE; i++)
2806 ed->pFontCache[i].nRefs = 0;
2807 ed->pFontCache[i].nAge = 0;
2808 ed->pFontCache[i].hFont = NULL;
2811 ME_CheckCharOffsets(ed);
2812 ed->bDefaultFormatRect = TRUE;
2813 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2814 if (selbarwidth) {
2815 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2816 ed->selofs = SELECTIONBAR_WIDTH;
2817 ed->styleFlags |= ES_SELECTIONBAR;
2818 } else {
2819 ed->selofs = 0;
2821 ed->nSelectionType = stPosition;
2823 ed->cPasswordMask = 0;
2824 if (props & TXTBIT_USEPASSWORD)
2825 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2827 if (props & TXTBIT_AUTOWORDSEL)
2828 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2829 if (props & TXTBIT_MULTILINE) {
2830 ed->styleFlags |= ES_MULTILINE;
2831 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2832 } else {
2833 ed->bWordWrap = FALSE;
2835 if (props & TXTBIT_READONLY)
2836 ed->styleFlags |= ES_READONLY;
2837 if (!(props & TXTBIT_HIDESELECTION))
2838 ed->styleFlags |= ES_NOHIDESEL;
2839 if (props & TXTBIT_SAVESELECTION)
2840 ed->styleFlags |= ES_SAVESEL;
2841 if (props & TXTBIT_VERTICAL)
2842 ed->styleFlags |= ES_VERTICAL;
2843 if (props & TXTBIT_DISABLEDRAG)
2844 ed->styleFlags |= ES_NOOLEDRAGDROP;
2846 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2848 /* Default scrollbar information */
2849 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2850 ed->vert_si.nMin = 0;
2851 ed->vert_si.nMax = 0;
2852 ed->vert_si.nPage = 0;
2853 ed->vert_si.nPos = 0;
2855 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2856 ed->horz_si.nMin = 0;
2857 ed->horz_si.nMax = 0;
2858 ed->horz_si.nPage = 0;
2859 ed->horz_si.nPos = 0;
2861 ed->wheel_remain = 0;
2863 OleInitialize(NULL);
2865 return ed;
2868 void ME_DestroyEditor(ME_TextEditor *editor)
2870 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2871 ME_DisplayItem *p = pFirst, *pNext = NULL;
2872 int i;
2874 ME_ClearTempStyle(editor);
2875 ME_EmptyUndoStack(editor);
2876 while(p) {
2877 pNext = p->next;
2878 ME_DestroyDisplayItem(p);
2879 p = pNext;
2881 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2882 for (i=0; i<HFONT_CACHE_SIZE; i++)
2884 if (editor->pFontCache[i].hFont)
2885 DeleteObject(editor->pFontCache[i].hFont);
2887 if (editor->rgbBackColor != -1)
2888 DeleteObject(editor->hbrBackground);
2889 if(editor->lpOleCallback)
2890 IRichEditOleCallback_Release(editor->lpOleCallback);
2891 ITextHost_Release(editor->texthost);
2892 if (editor->reOle)
2894 IRichEditOle_Release(editor->reOle);
2895 editor->reOle = NULL;
2897 OleUninitialize();
2899 FREE_OBJ(editor->pBuffer);
2900 FREE_OBJ(editor->pCursors);
2902 FREE_OBJ(editor);
2905 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2907 TRACE("\n");
2908 switch (fdwReason)
2910 case DLL_PROCESS_ATTACH:
2911 DisableThreadLibraryCalls(hinstDLL);
2912 me_heap = HeapCreate (0, 0x10000, 0);
2913 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2914 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2915 LookupInit();
2916 break;
2918 case DLL_PROCESS_DETACH:
2919 if (lpvReserved) break;
2920 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2921 UnregisterClassW(MSFTEDIT_CLASS, 0);
2922 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2923 UnregisterClassA("RichEdit50A", 0);
2924 if (ME_ListBoxRegistered)
2925 UnregisterClassW(REListBox20W, 0);
2926 if (ME_ComboBoxRegistered)
2927 UnregisterClassW(REComboBox20W, 0);
2928 LookupCleanup();
2929 HeapDestroy (me_heap);
2930 release_typelib();
2931 break;
2933 return TRUE;
2936 static inline int get_default_line_height( ME_TextEditor *editor )
2938 int height = 0;
2940 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
2941 height = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2942 if (height <= 0) height = 24;
2944 return height;
2947 static inline int calc_wheel_change( int *remain, int amount_per_click )
2949 int change = amount_per_click * (float)*remain / WHEEL_DELTA;
2950 *remain -= WHEEL_DELTA * change / amount_per_click;
2951 return change;
2954 static const char * const edit_messages[] = {
2955 "EM_GETSEL",
2956 "EM_SETSEL",
2957 "EM_GETRECT",
2958 "EM_SETRECT",
2959 "EM_SETRECTNP",
2960 "EM_SCROLL",
2961 "EM_LINESCROLL",
2962 "EM_SCROLLCARET",
2963 "EM_GETMODIFY",
2964 "EM_SETMODIFY",
2965 "EM_GETLINECOUNT",
2966 "EM_LINEINDEX",
2967 "EM_SETHANDLE",
2968 "EM_GETHANDLE",
2969 "EM_GETTHUMB",
2970 "EM_UNKNOWN_BF",
2971 "EM_UNKNOWN_C0",
2972 "EM_LINELENGTH",
2973 "EM_REPLACESEL",
2974 "EM_UNKNOWN_C3",
2975 "EM_GETLINE",
2976 "EM_LIMITTEXT",
2977 "EM_CANUNDO",
2978 "EM_UNDO",
2979 "EM_FMTLINES",
2980 "EM_LINEFROMCHAR",
2981 "EM_UNKNOWN_CA",
2982 "EM_SETTABSTOPS",
2983 "EM_SETPASSWORDCHAR",
2984 "EM_EMPTYUNDOBUFFER",
2985 "EM_GETFIRSTVISIBLELINE",
2986 "EM_SETREADONLY",
2987 "EM_SETWORDBREAKPROC",
2988 "EM_GETWORDBREAKPROC",
2989 "EM_GETPASSWORDCHAR",
2990 "EM_SETMARGINS",
2991 "EM_GETMARGINS",
2992 "EM_GETLIMITTEXT",
2993 "EM_POSFROMCHAR",
2994 "EM_CHARFROMPOS",
2995 "EM_SETIMESTATUS",
2996 "EM_GETIMESTATUS"
2999 static const char * const richedit_messages[] = {
3000 "EM_CANPASTE",
3001 "EM_DISPLAYBAND",
3002 "EM_EXGETSEL",
3003 "EM_EXLIMITTEXT",
3004 "EM_EXLINEFROMCHAR",
3005 "EM_EXSETSEL",
3006 "EM_FINDTEXT",
3007 "EM_FORMATRANGE",
3008 "EM_GETCHARFORMAT",
3009 "EM_GETEVENTMASK",
3010 "EM_GETOLEINTERFACE",
3011 "EM_GETPARAFORMAT",
3012 "EM_GETSELTEXT",
3013 "EM_HIDESELECTION",
3014 "EM_PASTESPECIAL",
3015 "EM_REQUESTRESIZE",
3016 "EM_SELECTIONTYPE",
3017 "EM_SETBKGNDCOLOR",
3018 "EM_SETCHARFORMAT",
3019 "EM_SETEVENTMASK",
3020 "EM_SETOLECALLBACK",
3021 "EM_SETPARAFORMAT",
3022 "EM_SETTARGETDEVICE",
3023 "EM_STREAMIN",
3024 "EM_STREAMOUT",
3025 "EM_GETTEXTRANGE",
3026 "EM_FINDWORDBREAK",
3027 "EM_SETOPTIONS",
3028 "EM_GETOPTIONS",
3029 "EM_FINDTEXTEX",
3030 "EM_GETWORDBREAKPROCEX",
3031 "EM_SETWORDBREAKPROCEX",
3032 "EM_SETUNDOLIMIT",
3033 "EM_UNKNOWN_USER_83",
3034 "EM_REDO",
3035 "EM_CANREDO",
3036 "EM_GETUNDONAME",
3037 "EM_GETREDONAME",
3038 "EM_STOPGROUPTYPING",
3039 "EM_SETTEXTMODE",
3040 "EM_GETTEXTMODE",
3041 "EM_AUTOURLDETECT",
3042 "EM_GETAUTOURLDETECT",
3043 "EM_SETPALETTE",
3044 "EM_GETTEXTEX",
3045 "EM_GETTEXTLENGTHEX",
3046 "EM_SHOWSCROLLBAR",
3047 "EM_SETTEXTEX",
3048 "EM_UNKNOWN_USER_98",
3049 "EM_UNKNOWN_USER_99",
3050 "EM_SETPUNCTUATION",
3051 "EM_GETPUNCTUATION",
3052 "EM_SETWORDWRAPMODE",
3053 "EM_GETWORDWRAPMODE",
3054 "EM_SETIMECOLOR",
3055 "EM_GETIMECOLOR",
3056 "EM_SETIMEOPTIONS",
3057 "EM_GETIMEOPTIONS",
3058 "EM_CONVPOSITION",
3059 "EM_UNKNOWN_USER_109",
3060 "EM_UNKNOWN_USER_110",
3061 "EM_UNKNOWN_USER_111",
3062 "EM_UNKNOWN_USER_112",
3063 "EM_UNKNOWN_USER_113",
3064 "EM_UNKNOWN_USER_114",
3065 "EM_UNKNOWN_USER_115",
3066 "EM_UNKNOWN_USER_116",
3067 "EM_UNKNOWN_USER_117",
3068 "EM_UNKNOWN_USER_118",
3069 "EM_UNKNOWN_USER_119",
3070 "EM_SETLANGOPTIONS",
3071 "EM_GETLANGOPTIONS",
3072 "EM_GETIMECOMPMODE",
3073 "EM_FINDTEXTW",
3074 "EM_FINDTEXTEXW",
3075 "EM_RECONVERSION",
3076 "EM_SETIMEMODEBIAS",
3077 "EM_GETIMEMODEBIAS"
3080 static const char *
3081 get_msg_name(UINT msg)
3083 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
3084 return edit_messages[msg - EM_GETSEL];
3085 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
3086 return richedit_messages[msg - EM_CANPASTE];
3087 return "";
3090 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3092 int x,y;
3093 BOOL isExact;
3094 ME_Cursor cursor; /* The start of the clicked text. */
3096 ENLINK info;
3097 x = (short)LOWORD(lParam);
3098 y = (short)HIWORD(lParam);
3099 ME_CharFromPos(editor, x, y, &cursor, &isExact);
3100 if (!isExact) return;
3102 if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
3103 cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
3104 { /* The clicked run has CFE_LINK set */
3105 ME_DisplayItem *di;
3107 info.nmhdr.hwndFrom = NULL;
3108 info.nmhdr.idFrom = 0;
3109 info.nmhdr.code = EN_LINK;
3110 info.msg = msg;
3111 info.wParam = wParam;
3112 info.lParam = lParam;
3113 cursor.nOffset = 0;
3115 /* find the first contiguous run with CFE_LINK set */
3116 info.chrg.cpMin = ME_GetCursorOfs(&cursor);
3117 for (di = cursor.pRun->prev;
3118 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3119 di = di->prev)
3121 info.chrg.cpMin -= di->member.run.len;
3124 /* find the last contiguous run with CFE_LINK set */
3125 info.chrg.cpMax = ME_GetCursorOfs(&cursor) + cursor.pRun->member.run.len;
3126 for (di = cursor.pRun->next;
3127 di && di->type == diRun && (di->member.run.style->fmt.dwMask & CFM_LINK) && (di->member.run.style->fmt.dwEffects & CFE_LINK);
3128 di = di->next)
3130 info.chrg.cpMax += di->member.run.len;
3133 ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
3137 void ME_ReplaceSel(ME_TextEditor *editor, BOOL can_undo, const WCHAR *str, int len)
3139 int from, to, nStartCursor;
3140 ME_Style *style;
3142 nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3143 style = ME_GetSelectionInsertStyle(editor);
3144 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3145 ME_InsertTextFromCursor(editor, 0, str, len, style);
3146 ME_ReleaseStyle(style);
3147 /* drop temporary style if line end */
3149 * FIXME question: does abc\n mean: put abc,
3150 * clear temp style, put \n? (would require a change)
3152 if (len>0 && str[len-1] == '\n')
3153 ME_ClearTempStyle(editor);
3154 ME_CommitUndo(editor);
3155 ME_UpdateSelectionLinkAttribute(editor);
3156 if (!can_undo)
3157 ME_EmptyUndoStack(editor);
3158 ME_UpdateRepaint(editor, FALSE);
3161 static void ME_SetText(ME_TextEditor *editor, void *text, BOOL unicode)
3163 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3164 int textLen;
3166 LPWSTR wszText = ME_ToUnicode(codepage, text, &textLen);
3168 if (textLen > 0)
3170 int len = -1;
3172 /* uses default style! */
3173 if (!(editor->styleFlags & ES_MULTILINE))
3175 WCHAR *p = wszText;
3177 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3178 len = p - wszText;
3180 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3182 ME_EndToUnicode(codepage, wszText);
3185 static LRESULT ME_WmCreate(ME_TextEditor *editor, LPARAM lParam, BOOL unicode)
3187 CREATESTRUCTW *createW = (CREATESTRUCTW*)lParam;
3188 CREATESTRUCTA *createA = (CREATESTRUCTA*)lParam;
3189 void *text = NULL;
3190 INT max;
3192 if (lParam)
3193 text = unicode ? (void*)createW->lpszName : (void*)createA->lpszName;
3195 ME_SetDefaultFormatRect(editor);
3197 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3198 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3199 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3201 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3202 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3204 if (editor->styleFlags & ES_DISABLENOSCROLL)
3206 if (editor->styleFlags & WS_VSCROLL)
3208 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3209 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3211 if (editor->styleFlags & WS_HSCROLL)
3213 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3214 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3218 if (text)
3220 ME_SetText(editor, text, unicode);
3221 ME_SetCursorToStart(editor, &editor->pCursors[0]);
3222 ME_SetCursorToStart(editor, &editor->pCursors[1]);
3225 ME_CommitUndo(editor);
3226 ME_WrapMarkedParagraphs(editor);
3227 ME_MoveCaret(editor);
3228 return 0;
3232 #define UNSUPPORTED_MSG(e) \
3233 case e: \
3234 FIXME(#e ": stub\n"); \
3235 *phresult = S_FALSE; \
3236 return 0;
3238 /* Handle messages for windowless and windowed richedit controls.
3240 * The LRESULT that is returned is a return value for window procs,
3241 * and the phresult parameter is the COM return code needed by the
3242 * text services interface. */
3243 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
3244 LPARAM lParam, BOOL unicode, HRESULT* phresult)
3246 *phresult = S_OK;
3248 switch(msg) {
3250 UNSUPPORTED_MSG(EM_DISPLAYBAND)
3251 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
3252 UNSUPPORTED_MSG(EM_FMTLINES)
3253 UNSUPPORTED_MSG(EM_FORMATRANGE)
3254 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
3255 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
3256 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
3257 UNSUPPORTED_MSG(EM_GETIMESTATUS)
3258 UNSUPPORTED_MSG(EM_SETIMESTATUS)
3259 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
3260 UNSUPPORTED_MSG(EM_GETREDONAME)
3261 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
3262 UNSUPPORTED_MSG(EM_GETUNDONAME)
3263 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
3264 UNSUPPORTED_MSG(EM_PASTESPECIAL)
3265 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
3266 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
3267 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
3268 UNSUPPORTED_MSG(EM_SETFONTSIZE)
3269 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
3270 UNSUPPORTED_MSG(EM_SETMARGINS)
3271 UNSUPPORTED_MSG(EM_SETPALETTE)
3272 UNSUPPORTED_MSG(EM_SETTABSTOPS)
3273 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
3274 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3276 /* Messages specific to Richedit controls */
3278 case EM_STREAMIN:
3279 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3280 case EM_STREAMOUT:
3281 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3282 case WM_GETDLGCODE:
3284 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS;
3286 if (lParam)
3287 editor->bDialogMode = TRUE;
3288 if (editor->styleFlags & ES_MULTILINE)
3289 code |= DLGC_WANTMESSAGE;
3290 if (!(editor->styleFlags & ES_SAVESEL))
3291 code |= DLGC_HASSETSEL;
3292 return code;
3294 case EM_EMPTYUNDOBUFFER:
3295 ME_EmptyUndoStack(editor);
3296 return 0;
3297 case EM_GETSEL:
3299 /* Note: wParam/lParam can be NULL */
3300 UINT from, to;
3301 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3302 PUINT pto = lParam ? (PUINT)lParam : &to;
3303 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3304 if ((*pfrom|*pto) & 0xFFFF0000)
3305 return -1;
3306 return MAKELONG(*pfrom,*pto);
3308 case EM_EXGETSEL:
3310 CHARRANGE *pRange = (CHARRANGE *)lParam;
3311 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3312 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3313 return 0;
3315 case EM_SETUNDOLIMIT:
3317 if ((int)wParam < 0)
3318 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3319 else
3320 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3321 /* Setting a max stack size keeps wine from getting killed
3322 for hogging memory. Windows allocates all this memory at once, so
3323 no program would realistically set a value above our maximum. */
3324 return editor->nUndoLimit;
3326 case EM_CANUNDO:
3327 return !list_empty( &editor->undo_stack );
3328 case EM_CANREDO:
3329 return !list_empty( &editor->redo_stack );
3330 case WM_UNDO: /* FIXME: actually not the same */
3331 case EM_UNDO:
3332 return ME_Undo(editor);
3333 case EM_REDO:
3334 return ME_Redo(editor);
3335 case EM_GETOPTIONS:
3337 /* these flags are equivalent to the ES_* counterparts */
3338 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3339 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3340 DWORD settings = editor->styleFlags & mask;
3342 return settings;
3344 case EM_SETOPTIONS:
3346 /* these flags are equivalent to ES_* counterparts, except for
3347 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3348 * but is still stored in editor->styleFlags. */
3349 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3350 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3351 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3352 DWORD settings = mask & editor->styleFlags;
3353 DWORD oldSettings = settings;
3354 DWORD changedSettings;
3356 switch(wParam)
3358 case ECOOP_SET:
3359 settings = lParam;
3360 break;
3361 case ECOOP_OR:
3362 settings |= lParam;
3363 break;
3364 case ECOOP_AND:
3365 settings &= lParam;
3366 break;
3367 case ECOOP_XOR:
3368 settings ^= lParam;
3370 changedSettings = oldSettings ^ settings;
3372 if (changedSettings) {
3373 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3375 if (changedSettings & ECO_SELECTIONBAR)
3377 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3378 if (settings & ECO_SELECTIONBAR) {
3379 assert(!editor->selofs);
3380 editor->selofs = SELECTIONBAR_WIDTH;
3381 editor->rcFormat.left += editor->selofs;
3382 } else {
3383 editor->rcFormat.left -= editor->selofs;
3384 editor->selofs = 0;
3386 ME_RewrapRepaint(editor);
3389 if (changedSettings & settings & ECO_VERTICAL)
3390 FIXME("ECO_VERTICAL not implemented yet!\n");
3391 if (changedSettings & settings & ECO_AUTOHSCROLL)
3392 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3393 if (changedSettings & settings & ECO_AUTOVSCROLL)
3394 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3395 if (changedSettings & settings & ECO_NOHIDESEL)
3396 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3397 if (changedSettings & settings & ECO_WANTRETURN)
3398 FIXME("ECO_WANTRETURN not implemented yet!\n");
3399 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3400 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3403 return settings;
3405 case EM_SETSEL:
3407 return handle_EM_EXSETSEL( editor, wParam, lParam );
3409 case EM_SETSCROLLPOS:
3411 POINT *point = (POINT *)lParam;
3412 ME_ScrollAbs(editor, point->x, point->y);
3413 return 0;
3415 case EM_AUTOURLDETECT:
3417 if (wParam==1 || wParam ==0)
3419 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3420 return 0;
3422 return E_INVALIDARG;
3424 case EM_GETAUTOURLDETECT:
3426 return editor->AutoURLDetect_bEnable;
3428 case EM_EXSETSEL:
3430 CHARRANGE range = *(CHARRANGE *)lParam;
3432 return handle_EM_EXSETSEL( editor, range.cpMin, range.cpMax );
3434 case EM_SHOWSCROLLBAR:
3436 DWORD flags;
3438 switch (wParam)
3440 case SB_HORZ:
3441 flags = WS_HSCROLL;
3442 break;
3443 case SB_VERT:
3444 flags = WS_VSCROLL;
3445 break;
3446 case SB_BOTH:
3447 flags = WS_HSCROLL|WS_VSCROLL;
3448 break;
3449 default:
3450 return 0;
3453 if (lParam) {
3454 editor->styleFlags |= flags;
3455 if (flags & WS_HSCROLL)
3456 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3457 editor->nTotalWidth > editor->sizeWindow.cx);
3458 if (flags & WS_VSCROLL)
3459 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3460 editor->nTotalLength > editor->sizeWindow.cy);
3461 } else {
3462 editor->styleFlags &= ~flags;
3463 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3465 return 0;
3467 case EM_SETTEXTEX:
3469 LPWSTR wszText;
3470 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3471 int from, to, len;
3472 ME_Style *style;
3473 BOOL bRtf, bUnicode, bSelection, bUTF8;
3474 int oldModify = editor->nModifyStep;
3475 static const char utf8_bom[] = {0xef, 0xbb, 0xbf};
3477 if (!pStruct) return 0;
3479 /* If we detect ascii rtf at the start of the string,
3480 * we know it isn't unicode. */
3481 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3482 !strncmp((char *)lParam, "{\\urtf", 6)));
3483 bUnicode = !bRtf && pStruct->codepage == CP_UNICODE;
3484 bUTF8 = (lParam && (!strncmp((char *)lParam, utf8_bom, 3)));
3486 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3487 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3488 pStruct->flags, pStruct->codepage);
3490 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3491 if (bSelection) {
3492 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3493 style = ME_GetSelectionInsertStyle(editor);
3494 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3495 } else {
3496 ME_Cursor start;
3497 ME_SetCursorToStart(editor, &start);
3498 ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3499 style = editor->pBuffer->pDefaultStyle;
3502 if (bRtf) {
3503 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3504 if (bSelection) {
3505 /* FIXME: The length returned doesn't include the rtf control
3506 * characters, only the actual text. */
3507 len = lParam ? strlen((char *)lParam) : 0;
3509 } else {
3510 if (bUTF8 && !bUnicode) {
3511 wszText = ME_ToUnicode(CP_UTF8, (void *)(lParam+3), &len);
3512 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3513 ME_EndToUnicode(CP_UTF8, wszText);
3514 } else {
3515 wszText = ME_ToUnicode(pStruct->codepage, (void *)lParam, &len);
3516 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3517 ME_EndToUnicode(pStruct->codepage, wszText);
3521 if (bSelection) {
3522 ME_ReleaseStyle(style);
3523 ME_UpdateSelectionLinkAttribute(editor);
3524 } else {
3525 ME_Cursor cursor;
3526 len = 1;
3527 ME_SetCursorToStart(editor, &cursor);
3528 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3530 ME_CommitUndo(editor);
3531 if (!(pStruct->flags & ST_KEEPUNDO))
3533 editor->nModifyStep = oldModify;
3534 ME_EmptyUndoStack(editor);
3536 ME_UpdateRepaint(editor, FALSE);
3537 return len;
3539 case EM_SETBKGNDCOLOR:
3541 LRESULT lColor;
3542 if (editor->rgbBackColor != -1) {
3543 DeleteObject(editor->hbrBackground);
3544 lColor = editor->rgbBackColor;
3546 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3548 if (wParam)
3550 editor->rgbBackColor = -1;
3551 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3553 else
3555 editor->rgbBackColor = lParam;
3556 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3558 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3559 ITextHost_TxViewChange(editor->texthost, TRUE);
3560 return lColor;
3562 case EM_GETMODIFY:
3563 return editor->nModifyStep == 0 ? 0 : -1;
3564 case EM_SETMODIFY:
3566 if (wParam)
3567 editor->nModifyStep = 1;
3568 else
3569 editor->nModifyStep = 0;
3571 return 0;
3573 case EM_SETREADONLY:
3575 if (wParam)
3576 editor->styleFlags |= ES_READONLY;
3577 else
3578 editor->styleFlags &= ~ES_READONLY;
3579 return 1;
3581 case EM_SETEVENTMASK:
3583 DWORD nOldMask = editor->nEventMask;
3585 editor->nEventMask = lParam;
3586 return nOldMask;
3588 case EM_GETEVENTMASK:
3589 return editor->nEventMask;
3590 case EM_SETCHARFORMAT:
3592 CHARFORMAT2W buf, *p;
3593 BOOL bRepaint = TRUE;
3594 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3595 if (p == NULL) return 0;
3596 if (wParam & SCF_ALL) {
3597 if (editor->mode & TM_PLAINTEXT) {
3598 ME_SetDefaultCharFormat(editor, p);
3599 } else {
3600 ME_Cursor start;
3601 ME_SetCursorToStart(editor, &start);
3602 ME_SetCharFormat(editor, &start, NULL, p);
3603 editor->nModifyStep = 1;
3605 } else if (wParam & SCF_SELECTION) {
3606 if (editor->mode & TM_PLAINTEXT)
3607 return 0;
3608 if (wParam & SCF_WORD) {
3609 ME_Cursor start;
3610 ME_Cursor end = editor->pCursors[0];
3611 ME_MoveCursorWords(editor, &end, +1);
3612 start = end;
3613 ME_MoveCursorWords(editor, &start, -1);
3614 ME_SetCharFormat(editor, &start, &end, p);
3616 bRepaint = ME_IsSelection(editor);
3617 ME_SetSelectionCharFormat(editor, p);
3618 if (bRepaint) editor->nModifyStep = 1;
3619 } else { /* SCF_DEFAULT */
3620 ME_SetDefaultCharFormat(editor, p);
3622 ME_CommitUndo(editor);
3623 if (bRepaint)
3625 ME_WrapMarkedParagraphs(editor);
3626 ME_UpdateScrollBar(editor);
3627 ME_Repaint(editor);
3629 return 1;
3631 case EM_GETCHARFORMAT:
3633 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3634 if (dst->cbSize != sizeof(CHARFORMATA) &&
3635 dst->cbSize != sizeof(CHARFORMATW) &&
3636 dst->cbSize != sizeof(CHARFORMAT2A) &&
3637 dst->cbSize != sizeof(CHARFORMAT2W))
3638 return 0;
3639 tmp.cbSize = sizeof(tmp);
3640 if (!wParam)
3641 ME_GetDefaultCharFormat(editor, &tmp);
3642 else
3643 ME_GetSelectionCharFormat(editor, &tmp);
3644 ME_CopyToCFAny(dst, &tmp);
3645 return tmp.dwMask;
3647 case EM_SETPARAFORMAT:
3649 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3650 ME_WrapMarkedParagraphs(editor);
3651 ME_UpdateScrollBar(editor);
3652 ME_Repaint(editor);
3653 ME_CommitUndo(editor);
3654 return result;
3656 case EM_GETPARAFORMAT:
3657 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3658 return ((PARAFORMAT2 *)lParam)->dwMask;
3659 case EM_GETFIRSTVISIBLELINE:
3661 ME_DisplayItem *p = editor->pBuffer->pFirst;
3662 int y = editor->vert_si.nPos;
3663 int ypara = 0;
3664 int count = 0;
3665 int ystart, yend;
3666 while(p) {
3667 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3668 if (p->type == diTextEnd)
3669 break;
3670 if (p->type == diParagraph) {
3671 ypara = p->member.para.pt.y;
3672 continue;
3674 ystart = ypara + p->member.row.pt.y;
3675 yend = ystart + p->member.row.nHeight;
3676 if (y < yend) {
3677 break;
3679 count++;
3681 return count;
3683 case EM_HIDESELECTION:
3685 editor->bHideSelection = (wParam != 0);
3686 ME_InvalidateSelection(editor);
3687 return 0;
3689 case EM_LINESCROLL:
3691 if (!(editor->styleFlags & ES_MULTILINE))
3692 return FALSE;
3693 ME_ScrollDown( editor, lParam * get_default_line_height( editor ) );
3694 return TRUE;
3696 case WM_CLEAR:
3698 int from, to;
3699 int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3700 ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3701 ME_CommitUndo(editor);
3702 ME_UpdateRepaint(editor, TRUE);
3703 return 0;
3705 case EM_REPLACESEL:
3707 int len = 0;
3708 LONG codepage = unicode ? CP_UNICODE : CP_ACP;
3709 LPWSTR wszText = ME_ToUnicode(codepage, (void *)lParam, &len);
3711 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3713 ME_ReplaceSel(editor, !!wParam, wszText, len);
3714 ME_EndToUnicode(codepage, wszText);
3715 return len;
3717 case EM_SCROLLCARET:
3718 ME_EnsureVisible(editor, &editor->pCursors[0]);
3719 return 0;
3720 case WM_SETFONT:
3722 LOGFONTW lf;
3723 CHARFORMAT2W fmt;
3724 HDC hDC;
3725 BOOL bRepaint = LOWORD(lParam);
3727 if (!wParam)
3728 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3729 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3730 hDC = ITextHost_TxGetDC(editor->texthost);
3731 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3732 ITextHost_TxReleaseDC(editor->texthost, hDC);
3733 if (editor->mode & TM_RICHTEXT) {
3734 ME_Cursor start;
3735 ME_SetCursorToStart(editor, &start);
3736 ME_SetCharFormat(editor, &start, NULL, &fmt);
3738 ME_SetDefaultCharFormat(editor, &fmt);
3740 ME_CommitUndo(editor);
3741 ME_MarkAllForWrapping(editor);
3742 ME_WrapMarkedParagraphs(editor);
3743 ME_UpdateScrollBar(editor);
3744 if (bRepaint)
3745 ME_Repaint(editor);
3746 return 0;
3748 case WM_SETTEXT:
3750 ME_Cursor cursor;
3751 ME_SetCursorToStart(editor, &cursor);
3752 ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3753 if (lParam)
3755 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3756 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3757 !strncmp((char *)lParam, "{\\urtf", 6))
3759 /* Undocumented: WM_SETTEXT supports RTF text */
3760 ME_StreamInRTFString(editor, 0, (char *)lParam);
3762 else
3763 ME_SetText(editor, (void*)lParam, unicode);
3765 else
3766 TRACE("WM_SETTEXT - NULL\n");
3767 ME_SetCursorToStart(editor, &cursor);
3768 ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3769 ME_SetSelection(editor, 0, 0);
3770 editor->nModifyStep = 0;
3771 ME_CommitUndo(editor);
3772 ME_EmptyUndoStack(editor);
3773 ME_UpdateRepaint(editor, FALSE);
3774 return 1;
3776 case EM_CANPASTE:
3778 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3779 if (IsClipboardFormatAvailable(nRTFFormat))
3780 return TRUE;
3781 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3782 return TRUE;
3783 return FALSE;
3785 case WM_PASTE:
3786 case WM_MBUTTONDOWN:
3787 ME_Paste(editor);
3788 return 0;
3789 case WM_CUT:
3790 case WM_COPY:
3792 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3793 int nChars = nTo - nFrom;
3794 ME_Cursor *selStart = &editor->pCursors[nStartCur];
3796 if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3798 ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3799 ME_CommitUndo(editor);
3800 ME_UpdateRepaint(editor, TRUE);
3802 return 0;
3804 case WM_GETTEXTLENGTH:
3806 GETTEXTLENGTHEX how;
3808 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3809 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3810 how.codepage = unicode ? CP_UNICODE : CP_ACP;
3811 return ME_GetTextLengthEx(editor, &how);
3813 case EM_GETTEXTLENGTHEX:
3814 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3815 case WM_GETTEXT:
3817 GETTEXTEX ex;
3818 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3819 ex.flags = GT_USECRLF;
3820 ex.codepage = unicode ? CP_UNICODE : CP_ACP;
3821 ex.lpDefaultChar = NULL;
3822 ex.lpUsedDefChar = NULL;
3823 return ME_GetTextEx(editor, &ex, lParam);
3825 case EM_GETTEXTEX:
3826 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3827 case EM_GETSELTEXT:
3829 int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3830 ME_Cursor *from = &editor->pCursors[nStartCur];
3831 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3832 nTo - nFrom, unicode);
3834 case EM_GETSCROLLPOS:
3836 POINT *point = (POINT *)lParam;
3837 point->x = editor->horz_si.nPos;
3838 point->y = editor->vert_si.nPos;
3839 /* 16-bit scaled value is returned as stored in scrollinfo */
3840 if (editor->horz_si.nMax > 0xffff)
3841 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3842 if (editor->vert_si.nMax > 0xffff)
3843 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3844 return 1;
3846 case EM_GETTEXTRANGE:
3848 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3849 ME_Cursor start;
3850 int nStart = rng->chrg.cpMin;
3851 int nEnd = rng->chrg.cpMax;
3852 int textlength = ME_GetTextLength(editor);
3854 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3855 rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3856 if (nStart < 0) return 0;
3857 if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3858 nEnd = textlength;
3859 if (nStart >= nEnd) return 0;
3861 ME_CursorFromCharOfs(editor, nStart, &start);
3862 return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3864 case EM_GETLINE:
3866 ME_DisplayItem *run;
3867 const unsigned int nMaxChars = *(WORD *) lParam;
3868 unsigned int nCharsLeft = nMaxChars;
3869 char *dest = (char *) lParam;
3870 BOOL wroteNull = FALSE;
3872 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3873 unicode ? "Unicode" : "Ansi");
3875 run = ME_FindRowWithNumber(editor, wParam);
3876 if (run == NULL)
3877 return 0;
3879 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3880 && run->type == diRun)
3882 WCHAR *str = get_text( &run->member.run, 0 );
3883 unsigned int nCopy;
3885 nCopy = min(nCharsLeft, run->member.run.len);
3887 if (unicode)
3888 memcpy(dest, str, nCopy * sizeof(WCHAR));
3889 else
3890 nCopy = WideCharToMultiByte(CP_ACP, 0, str, nCopy, dest,
3891 nCharsLeft, NULL, NULL);
3892 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3893 nCharsLeft -= nCopy;
3896 /* append line termination, space allowing */
3897 if (nCharsLeft > 0)
3899 if (unicode)
3900 *((WCHAR *)dest) = '\0';
3901 else
3902 *dest = '\0';
3903 nCharsLeft--;
3904 wroteNull = TRUE;
3907 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3908 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3910 case EM_GETLINECOUNT:
3912 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3913 int nRows = 0;
3915 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3917 while (item != editor->pBuffer->pLast)
3919 assert(item->type == diParagraph);
3920 prev_para = ME_FindItemBack(item, diRun);
3921 if (prev_para) {
3922 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3924 nRows += item->member.para.nRows;
3925 item = item->member.para.next_para;
3927 last_para = ME_FindItemBack(item, diRun);
3928 assert(last_para);
3929 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3930 if (editor->bEmulateVersion10 && prev_para &&
3931 last_para->member.run.nCharOfs == 0 &&
3932 prev_para->member.run.len == 1 &&
3933 *get_text( &prev_para->member.run, 0 ) == '\r')
3935 /* In 1.0 emulation, the last solitary \r at the very end of the text
3936 (if one exists) is NOT a line break.
3937 FIXME: this is an ugly hack. This should have a more regular model. */
3938 nRows--;
3941 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3942 return max(1, nRows);
3944 case EM_LINEFROMCHAR:
3946 if (wParam == -1)
3947 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3948 else
3949 return ME_RowNumberFromCharOfs(editor, wParam);
3951 case EM_EXLINEFROMCHAR:
3953 if (lParam == -1)
3954 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3955 else
3956 return ME_RowNumberFromCharOfs(editor, lParam);
3958 case EM_LINEINDEX:
3960 ME_DisplayItem *item, *para;
3961 int nCharOfs;
3963 if (wParam == -1)
3964 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3965 else
3966 item = ME_FindRowWithNumber(editor, wParam);
3967 if (!item)
3968 return -1;
3969 para = ME_GetParagraph(item);
3970 item = ME_FindItemFwd(item, diRun);
3971 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3972 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3973 return nCharOfs;
3975 case EM_LINELENGTH:
3977 ME_DisplayItem *item, *item_end;
3978 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3979 ME_DisplayItem *para, *run;
3981 if (wParam > ME_GetTextLength(editor))
3982 return 0;
3983 if (wParam == -1)
3985 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3986 return 0;
3988 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3989 item = ME_RowStart(run);
3990 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3991 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3992 if (item_end->type == diStartRow) {
3993 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3994 } else {
3995 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3996 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3997 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.len;
3999 nChars = nNextLineOfs - nThisLineOfs;
4000 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
4001 return nChars;
4003 case EM_EXLIMITTEXT:
4005 if ((int)lParam < 0)
4006 return 0;
4007 if (lParam == 0)
4008 editor->nTextLimit = 65536;
4009 else
4010 editor->nTextLimit = (int) lParam;
4011 return 0;
4013 case EM_LIMITTEXT:
4015 if (wParam == 0)
4016 editor->nTextLimit = 65536;
4017 else
4018 editor->nTextLimit = (int) wParam;
4019 return 0;
4021 case EM_GETLIMITTEXT:
4023 return editor->nTextLimit;
4025 case EM_FINDTEXT:
4027 LRESULT r;
4028 if(!unicode){
4029 FINDTEXTA *ft = (FINDTEXTA *)lParam;
4030 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
4031 WCHAR *tmp;
4033 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4034 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
4035 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
4036 FREE_OBJ( tmp );
4037 }else{
4038 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4039 r = ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4041 return r;
4043 case EM_FINDTEXTEX:
4045 LRESULT r;
4046 if(!unicode){
4047 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
4048 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
4049 WCHAR *tmp;
4051 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
4052 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
4053 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
4054 FREE_OBJ( tmp );
4055 }else{
4056 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4057 r = ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4059 return r;
4061 case EM_FINDTEXTW:
4063 FINDTEXTW *ft = (FINDTEXTW *)lParam;
4064 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
4066 case EM_FINDTEXTEXW:
4068 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
4069 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
4071 case EM_GETZOOM:
4072 if (!wParam || !lParam)
4073 return FALSE;
4074 *(int *)wParam = editor->nZoomNumerator;
4075 *(int *)lParam = editor->nZoomDenominator;
4076 return TRUE;
4077 case EM_SETZOOM:
4078 return ME_SetZoom(editor, wParam, lParam);
4079 case EM_CHARFROMPOS:
4081 ME_Cursor cursor;
4082 if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
4083 &cursor, NULL))
4084 return ME_GetCursorOfs(&cursor);
4085 else
4086 return -1;
4088 case EM_POSFROMCHAR:
4090 ME_DisplayItem *pPara, *pRun;
4091 int nCharOfs, nOffset, nLength;
4092 POINTL pt = {0,0};
4094 nCharOfs = wParam;
4095 /* detect which API version we're dealing with */
4096 if (wParam >= 0x40000)
4097 nCharOfs = lParam;
4098 nLength = ME_GetTextLength(editor);
4099 nCharOfs = min(nCharOfs, nLength);
4100 nCharOfs = max(nCharOfs, 0);
4102 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
4103 assert(pRun->type == diRun);
4104 pt.y = pRun->member.run.pt.y;
4105 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset, TRUE);
4106 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
4107 pt.x += editor->rcFormat.left;
4109 pt.x -= editor->horz_si.nPos;
4110 pt.y -= editor->vert_si.nPos;
4112 if (wParam >= 0x40000) {
4113 *(POINTL *)wParam = pt;
4115 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
4117 case WM_CREATE:
4118 return ME_WmCreate(editor, lParam, unicode);
4119 case WM_DESTROY:
4120 ME_DestroyEditor(editor);
4121 return 0;
4122 case WM_SETCURSOR:
4124 POINT cursor_pos;
4125 if (wParam == (WPARAM)editor->hWnd && GetCursorPos(&cursor_pos) &&
4126 ScreenToClient(editor->hWnd, &cursor_pos))
4127 ME_LinkNotify(editor, msg, 0, MAKELPARAM(cursor_pos.x, cursor_pos.y));
4128 return ME_SetCursor(editor);
4130 case WM_LBUTTONDBLCLK:
4131 case WM_LBUTTONDOWN:
4133 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4134 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4135 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4136 return 0;
4137 ITextHost_TxSetFocus(editor->texthost);
4138 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
4139 ME_CalculateClickCount(editor, msg, wParam, lParam));
4140 ITextHost_TxSetCapture(editor->texthost, TRUE);
4141 editor->bMouseCaptured = TRUE;
4142 ME_LinkNotify(editor, msg, wParam, lParam);
4143 if (!ME_SetCursor(editor)) goto do_default;
4144 break;
4146 case WM_MOUSEMOVE:
4147 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4148 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4149 return 0;
4150 if (editor->bMouseCaptured)
4151 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
4152 else
4153 ME_LinkNotify(editor, msg, wParam, lParam);
4154 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
4155 if (editor->bMouseCaptured)
4156 ME_SetCursor(editor);
4157 break;
4158 case WM_LBUTTONUP:
4159 if (editor->bMouseCaptured) {
4160 ITextHost_TxSetCapture(editor->texthost, FALSE);
4161 editor->bMouseCaptured = FALSE;
4163 if (editor->nSelectionType == stDocument)
4164 editor->nSelectionType = stPosition;
4165 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4166 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4167 return 0;
4168 else
4170 ME_SetCursor(editor);
4171 ME_LinkNotify(editor, msg, wParam, lParam);
4173 break;
4174 case WM_RBUTTONUP:
4175 case WM_RBUTTONDOWN:
4176 case WM_RBUTTONDBLCLK:
4177 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4178 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4179 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4180 return 0;
4181 ME_LinkNotify(editor, msg, wParam, lParam);
4182 goto do_default;
4183 case WM_CONTEXTMENU:
4184 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
4185 goto do_default;
4186 break;
4187 case WM_SETFOCUS:
4188 editor->bHaveFocus = TRUE;
4189 ME_ShowCaret(editor);
4190 ME_SendOldNotify(editor, EN_SETFOCUS);
4191 return 0;
4192 case WM_KILLFOCUS:
4193 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4194 editor->bHaveFocus = FALSE;
4195 editor->wheel_remain = 0;
4196 ME_HideCaret(editor);
4197 ME_SendOldNotify(editor, EN_KILLFOCUS);
4198 return 0;
4199 case WM_COMMAND:
4200 TRACE("editor wnd command = %d\n", LOWORD(wParam));
4201 return 0;
4202 case WM_KEYUP:
4203 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4204 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4205 return 0;
4206 goto do_default;
4207 case WM_KEYDOWN:
4208 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4209 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4210 return 0;
4211 if (ME_KeyDown(editor, LOWORD(wParam)))
4212 return 0;
4213 goto do_default;
4214 case WM_CHAR:
4215 if ((editor->nEventMask & ENM_KEYEVENTS) &&
4216 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4217 return 0;
4218 return ME_Char(editor, wParam, lParam, unicode);
4219 case WM_UNICHAR:
4220 if (unicode)
4222 if(wParam == UNICODE_NOCHAR) return TRUE;
4223 if(wParam <= 0x000fffff)
4225 if(wParam > 0xffff) /* convert to surrogates */
4227 wParam -= 0x10000;
4228 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
4229 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
4230 } else {
4231 ME_Char(editor, wParam, 0, TRUE);
4234 return 0;
4236 break;
4237 case EM_STOPGROUPTYPING:
4238 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4239 return 0;
4240 case WM_HSCROLL:
4242 const int scrollUnit = 7;
4244 switch(LOWORD(wParam))
4246 case SB_LEFT:
4247 ME_ScrollAbs(editor, 0, 0);
4248 break;
4249 case SB_RIGHT:
4250 ME_ScrollAbs(editor,
4251 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4252 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4253 break;
4254 case SB_LINELEFT:
4255 ME_ScrollLeft(editor, scrollUnit);
4256 break;
4257 case SB_LINERIGHT:
4258 ME_ScrollRight(editor, scrollUnit);
4259 break;
4260 case SB_PAGELEFT:
4261 ME_ScrollLeft(editor, editor->sizeWindow.cx);
4262 break;
4263 case SB_PAGERIGHT:
4264 ME_ScrollRight(editor, editor->sizeWindow.cx);
4265 break;
4266 case SB_THUMBTRACK:
4267 case SB_THUMBPOSITION:
4269 int pos = HIWORD(wParam);
4270 if (editor->horz_si.nMax > 0xffff)
4271 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4272 ME_HScrollAbs(editor, pos);
4273 break;
4276 break;
4278 case EM_SCROLL: /* fall through */
4279 case WM_VSCROLL:
4281 int origNPos;
4282 int lineHeight = get_default_line_height( editor );
4284 origNPos = editor->vert_si.nPos;
4286 switch(LOWORD(wParam))
4288 case SB_TOP:
4289 ME_ScrollAbs(editor, 0, 0);
4290 break;
4291 case SB_BOTTOM:
4292 ME_ScrollAbs(editor,
4293 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4294 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4295 break;
4296 case SB_LINEUP:
4297 ME_ScrollUp(editor,lineHeight);
4298 break;
4299 case SB_LINEDOWN:
4300 ME_ScrollDown(editor,lineHeight);
4301 break;
4302 case SB_PAGEUP:
4303 ME_ScrollUp(editor,editor->sizeWindow.cy);
4304 break;
4305 case SB_PAGEDOWN:
4306 ME_ScrollDown(editor,editor->sizeWindow.cy);
4307 break;
4308 case SB_THUMBTRACK:
4309 case SB_THUMBPOSITION:
4311 int pos = HIWORD(wParam);
4312 if (editor->vert_si.nMax > 0xffff)
4313 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4314 ME_VScrollAbs(editor, pos);
4315 break;
4318 if (msg == EM_SCROLL)
4319 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4320 break;
4322 case WM_MOUSEWHEEL:
4324 int delta;
4325 BOOL ctrl_is_down;
4327 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4328 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4329 return 0;
4331 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4333 delta = GET_WHEEL_DELTA_WPARAM(wParam);
4335 /* if scrolling changes direction, ignore left overs */
4336 if ((delta < 0 && editor->wheel_remain < 0) ||
4337 (delta > 0 && editor->wheel_remain > 0))
4338 editor->wheel_remain += delta;
4339 else
4340 editor->wheel_remain = delta;
4342 if (editor->wheel_remain)
4344 if (ctrl_is_down) {
4345 int numerator;
4346 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4348 numerator = 100;
4349 } else {
4350 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4352 numerator += calc_wheel_change( &editor->wheel_remain, 10 );
4353 if (numerator >= 10 && numerator <= 500)
4354 ME_SetZoom(editor, numerator, 100);
4355 } else {
4356 UINT max_lines = 3;
4357 int lines = 0;
4359 SystemParametersInfoW( SPI_GETWHEELSCROLLLINES, 0, &max_lines, 0 );
4360 if (max_lines)
4361 lines = calc_wheel_change( &editor->wheel_remain, (int)max_lines );
4362 if (lines)
4363 ME_ScrollDown( editor, -lines * get_default_line_height( editor ) );
4366 break;
4368 case EM_GETRECT:
4370 *((RECT *)lParam) = editor->rcFormat;
4371 if (editor->bDefaultFormatRect)
4372 ((RECT *)lParam)->left -= editor->selofs;
4373 return 0;
4375 case EM_SETRECT:
4376 case EM_SETRECTNP:
4378 if (lParam)
4380 int border = 0;
4381 RECT clientRect;
4382 RECT *rc = (RECT *)lParam;
4384 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4385 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4386 if (wParam == 0)
4388 editor->rcFormat.top = max(0, rc->top - border);
4389 editor->rcFormat.left = max(0, rc->left - border);
4390 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4391 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4392 } else if (wParam == 1) {
4393 /* MSDN incorrectly says a wParam value of 1 causes the
4394 * lParam rect to be used as a relative offset,
4395 * however, the tests show it just prevents min/max bound
4396 * checking. */
4397 editor->rcFormat.top = rc->top - border;
4398 editor->rcFormat.left = rc->left - border;
4399 editor->rcFormat.bottom = rc->bottom;
4400 editor->rcFormat.right = rc->right + border;
4401 } else {
4402 return 0;
4404 editor->bDefaultFormatRect = FALSE;
4406 else
4408 ME_SetDefaultFormatRect(editor);
4409 editor->bDefaultFormatRect = TRUE;
4411 ME_MarkAllForWrapping(editor);
4412 ME_WrapMarkedParagraphs(editor);
4413 ME_UpdateScrollBar(editor);
4414 if (msg != EM_SETRECTNP)
4415 ME_Repaint(editor);
4416 return 0;
4418 case EM_REQUESTRESIZE:
4419 ME_SendRequestResize(editor, TRUE);
4420 return 0;
4421 case WM_SETREDRAW:
4422 goto do_default;
4423 case WM_WINDOWPOSCHANGED:
4425 RECT clientRect;
4426 WINDOWPOS *winpos = (WINDOWPOS *)lParam;
4428 if (winpos->flags & SWP_NOCLIENTSIZE) goto do_default;
4429 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4430 if (editor->bDefaultFormatRect) {
4431 ME_SetDefaultFormatRect(editor);
4432 } else {
4433 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4434 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4436 editor->prevClientRect = clientRect;
4437 ME_RewrapRepaint(editor);
4438 goto do_default;
4440 /* IME messages to make richedit controls IME aware */
4441 case WM_IME_SETCONTEXT:
4442 case WM_IME_CONTROL:
4443 case WM_IME_SELECT:
4444 case WM_IME_COMPOSITIONFULL:
4445 return 0;
4446 case WM_IME_STARTCOMPOSITION:
4448 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4449 ME_DeleteSelection(editor);
4450 ME_CommitUndo(editor);
4451 ME_UpdateRepaint(editor, FALSE);
4452 return 0;
4454 case WM_IME_COMPOSITION:
4456 HIMC hIMC;
4458 ME_Style *style = ME_GetInsertStyle(editor, 0);
4459 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4460 ME_DeleteSelection(editor);
4461 ME_SaveTempStyle(editor);
4462 if (lParam & (GCS_RESULTSTR|GCS_COMPSTR))
4464 LPWSTR lpCompStr = NULL;
4465 DWORD dwBufLen;
4466 DWORD dwIndex = lParam & GCS_RESULTSTR;
4467 if (!dwIndex)
4468 dwIndex = GCS_COMPSTR;
4470 dwBufLen = ImmGetCompositionStringW(hIMC, dwIndex, NULL, 0);
4471 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4472 ImmGetCompositionStringW(hIMC, dwIndex, lpCompStr, dwBufLen);
4473 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4474 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4475 HeapFree(GetProcessHeap(), 0, lpCompStr);
4477 if (dwIndex == GCS_COMPSTR)
4478 ME_SetSelection(editor,editor->imeStartIndex,
4479 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4481 ME_ReleaseStyle(style);
4482 ME_CommitUndo(editor);
4483 ME_UpdateRepaint(editor, FALSE);
4484 return 0;
4486 case WM_IME_ENDCOMPOSITION:
4488 ME_DeleteSelection(editor);
4489 editor->imeStartIndex=-1;
4490 return 0;
4492 case EM_GETOLEINTERFACE:
4494 if (!editor->reOle)
4495 if (!CreateIRichEditOle(NULL, editor, (LPVOID *)&editor->reOle))
4496 return 0;
4497 *(LPVOID *)lParam = editor->reOle;
4498 IRichEditOle_AddRef(editor->reOle);
4499 return 1;
4501 case EM_GETPASSWORDCHAR:
4503 return editor->cPasswordMask;
4505 case EM_SETOLECALLBACK:
4506 if(editor->lpOleCallback)
4507 IRichEditOleCallback_Release(editor->lpOleCallback);
4508 editor->lpOleCallback = (IRichEditOleCallback*)lParam;
4509 if(editor->lpOleCallback)
4510 IRichEditOleCallback_AddRef(editor->lpOleCallback);
4511 return TRUE;
4512 case EM_GETWORDBREAKPROC:
4513 return (LRESULT)editor->pfnWordBreak;
4514 case EM_SETWORDBREAKPROC:
4516 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4518 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4519 return (LRESULT)pfnOld;
4521 case EM_GETTEXTMODE:
4522 return editor->mode;
4523 case EM_SETTEXTMODE:
4525 int mask = 0;
4526 int changes = 0;
4528 if (ME_GetTextLength(editor) ||
4529 !list_empty( &editor->undo_stack ) || !list_empty( &editor->redo_stack ))
4530 return E_UNEXPECTED;
4532 /* Check for mutually exclusive flags in adjacent bits of wParam */
4533 if ((wParam & (TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE)) &
4534 (wParam & (TM_PLAINTEXT | TM_SINGLELEVELUNDO | TM_SINGLECODEPAGE)) << 1)
4535 return E_INVALIDARG;
4537 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4539 mask |= TM_RICHTEXT | TM_PLAINTEXT;
4540 changes |= wParam & (TM_RICHTEXT | TM_PLAINTEXT);
4541 if (wParam & TM_PLAINTEXT) {
4542 /* Clear selection since it should be possible to select the
4543 * end of text run for rich text */
4544 ME_InvalidateSelection(editor);
4545 ME_SetCursorToStart(editor, &editor->pCursors[0]);
4546 editor->pCursors[1] = editor->pCursors[0];
4547 /* plain text can only have the default style. */
4548 ME_ClearTempStyle(editor);
4549 ME_AddRefStyle(editor->pBuffer->pDefaultStyle);
4550 ME_ReleaseStyle(editor->pCursors[0].pRun->member.run.style);
4551 editor->pCursors[0].pRun->member.run.style = editor->pBuffer->pDefaultStyle;
4554 /* FIXME: Currently no support for undo level and code page options */
4555 editor->mode = (editor->mode & ~mask) | changes;
4556 return 0;
4558 case EM_SETPASSWORDCHAR:
4560 editor->cPasswordMask = wParam;
4561 ME_RewrapRepaint(editor);
4562 return 0;
4564 case EM_SETTARGETDEVICE:
4565 if (wParam == 0)
4567 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4568 if (editor->nAvailWidth || editor->bWordWrap != new)
4570 editor->bWordWrap = new;
4571 editor->nAvailWidth = 0; /* wrap to client area */
4572 ME_RewrapRepaint(editor);
4574 } else {
4575 int width = max(0, lParam);
4576 if ((editor->styleFlags & ES_MULTILINE) &&
4577 (!editor->bWordWrap || editor->nAvailWidth != width))
4579 editor->nAvailWidth = width;
4580 editor->bWordWrap = TRUE;
4581 ME_RewrapRepaint(editor);
4583 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4585 return TRUE;
4586 default:
4587 do_default:
4588 *phresult = S_FALSE;
4589 break;
4591 return 0L;
4594 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4595 LPARAM lParam, BOOL unicode)
4597 ME_TextEditor *editor;
4598 HRESULT hresult;
4599 LRESULT lresult = 0;
4601 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4602 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4604 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4605 if (!editor)
4607 if (msg == WM_NCCREATE)
4609 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4610 ITextHost *texthost;
4612 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4613 texthost = ME_CreateTextHost(hWnd, pcs, FALSE);
4614 return texthost != NULL;
4616 else
4618 return DefWindowProcW(hWnd, msg, wParam, lParam);
4622 switch (msg)
4624 case WM_PAINT:
4626 HDC hDC;
4627 RECT rc;
4628 PAINTSTRUCT ps;
4630 hDC = BeginPaint(editor->hWnd, &ps);
4631 if (!editor->bEmulateVersion10 || (editor->nEventMask & ENM_UPDATE))
4632 ME_SendOldNotify(editor, EN_UPDATE);
4633 /* Erase area outside of the formatting rectangle */
4634 if (ps.rcPaint.top < editor->rcFormat.top)
4636 rc = ps.rcPaint;
4637 rc.bottom = editor->rcFormat.top;
4638 FillRect(hDC, &rc, editor->hbrBackground);
4639 ps.rcPaint.top = editor->rcFormat.top;
4641 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4642 rc = ps.rcPaint;
4643 rc.top = editor->rcFormat.bottom;
4644 FillRect(hDC, &rc, editor->hbrBackground);
4645 ps.rcPaint.bottom = editor->rcFormat.bottom;
4647 if (ps.rcPaint.left < editor->rcFormat.left) {
4648 rc = ps.rcPaint;
4649 rc.right = editor->rcFormat.left;
4650 FillRect(hDC, &rc, editor->hbrBackground);
4651 ps.rcPaint.left = editor->rcFormat.left;
4653 if (ps.rcPaint.right > editor->rcFormat.right) {
4654 rc = ps.rcPaint;
4655 rc.left = editor->rcFormat.right;
4656 FillRect(hDC, &rc, editor->hbrBackground);
4657 ps.rcPaint.right = editor->rcFormat.right;
4660 ME_PaintContent(editor, hDC, &ps.rcPaint);
4661 EndPaint(editor->hWnd, &ps);
4662 return 0;
4664 case WM_ERASEBKGND:
4666 HDC hDC = (HDC)wParam;
4667 RECT rc;
4669 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4670 FillRect(hDC, &rc, editor->hbrBackground);
4671 return 1;
4673 case EM_SETOPTIONS:
4675 DWORD dwStyle;
4676 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4677 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4678 ECO_SELECTIONBAR;
4679 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4680 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4681 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4682 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4683 return lresult;
4685 case EM_SETREADONLY:
4687 DWORD dwStyle;
4688 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4689 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4690 dwStyle &= ~ES_READONLY;
4691 if (wParam)
4692 dwStyle |= ES_READONLY;
4693 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4694 return lresult;
4696 default:
4697 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4700 if (hresult == S_FALSE)
4701 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4703 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4704 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4706 return lresult;
4709 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4711 BOOL unicode = TRUE;
4713 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4714 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4715 unicode = FALSE;
4717 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4720 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4722 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4725 /******************************************************************
4726 * RichEditANSIWndProc (RICHED20.10)
4728 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4730 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4733 /******************************************************************
4734 * RichEdit10ANSIWndProc (RICHED20.9)
4736 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4738 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4740 ITextHost *texthost;
4741 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4743 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4744 texthost = ME_CreateTextHost(hWnd, pcs, TRUE);
4745 return texthost != NULL;
4747 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4750 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4752 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4755 /* Fill buffer with srcChars unicode characters from the start cursor.
4757 * buffer: destination buffer
4758 * buflen: length of buffer in characters excluding the NULL terminator.
4759 * start: start of editor text to copy into buffer.
4760 * srcChars: Number of characters to use from the editor text.
4761 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4763 * returns the number of characters written excluding the NULL terminator.
4765 * The written text is always NULL terminated.
4767 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4768 const ME_Cursor *start, int srcChars, BOOL bCRLF,
4769 BOOL bEOP)
4771 ME_DisplayItem *pRun, *pNextRun;
4772 const WCHAR *pStart = buffer;
4773 const WCHAR cr_lf[] = {'\r', '\n', 0};
4774 const WCHAR *str;
4775 int nLen;
4777 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4778 if (editor->bEmulateVersion10) bCRLF = FALSE;
4780 pRun = start->pRun;
4781 assert(pRun);
4782 pNextRun = ME_FindItemFwd(pRun, diRun);
4784 nLen = pRun->member.run.len - start->nOffset;
4785 str = get_text( &pRun->member.run, start->nOffset );
4787 while (srcChars && buflen && pNextRun)
4789 int nFlags = pRun->member.run.nFlags;
4791 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4793 if (buflen == 1) break;
4794 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4795 * EM_GETTEXTEX, however, this is done for copying text which
4796 * also uses this function. */
4797 srcChars -= min(nLen, srcChars);
4798 nLen = 2;
4799 str = cr_lf;
4800 } else {
4801 nLen = min(nLen, srcChars);
4802 srcChars -= nLen;
4805 nLen = min(nLen, buflen);
4806 buflen -= nLen;
4808 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4810 buffer += nLen;
4812 pRun = pNextRun;
4813 pNextRun = ME_FindItemFwd(pRun, diRun);
4815 nLen = pRun->member.run.len;
4816 str = get_text( &pRun->member.run, 0 );
4818 /* append '\r' to the last paragraph. */
4819 if (pRun->next->type == diTextEnd && bEOP)
4821 *buffer = '\r';
4822 buffer ++;
4824 *buffer = 0;
4825 return buffer - pStart;
4828 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4830 WNDCLASSW wcW;
4831 WNDCLASSA wcA;
4833 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4834 wcW.lpfnWndProc = RichEditWndProcW;
4835 wcW.cbClsExtra = 0;
4836 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4837 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4838 wcW.hIcon = NULL;
4839 wcW.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4840 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4841 wcW.lpszMenuName = NULL;
4843 if (is_version_nt())
4845 wcW.lpszClassName = RICHEDIT_CLASS20W;
4846 if (!RegisterClassW(&wcW)) return FALSE;
4847 wcW.lpszClassName = MSFTEDIT_CLASS;
4848 if (!RegisterClassW(&wcW)) return FALSE;
4850 else
4852 /* WNDCLASSA/W have the same layout */
4853 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4854 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4855 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4856 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4859 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4860 wcA.lpfnWndProc = RichEditWndProcA;
4861 wcA.cbClsExtra = 0;
4862 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4863 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4864 wcA.hIcon = NULL;
4865 wcA.hCursor = LoadCursorW(NULL, (LPWSTR)IDC_IBEAM);
4866 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4867 wcA.lpszMenuName = NULL;
4868 wcA.lpszClassName = RICHEDIT_CLASS20A;
4869 if (!RegisterClassA(&wcA)) return FALSE;
4870 wcA.lpszClassName = "RichEdit50A";
4871 if (!RegisterClassA(&wcA)) return FALSE;
4873 return TRUE;
4876 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4877 /* FIXME: Not implemented */
4878 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4879 hWnd, msg, get_msg_name(msg), wParam, lParam);
4880 return DefWindowProcW(hWnd, msg, wParam, lParam);
4883 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4884 /* FIXME: Not implemented */
4885 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4886 hWnd, msg, get_msg_name(msg), wParam, lParam);
4887 return DefWindowProcW(hWnd, msg, wParam, lParam);
4890 /******************************************************************
4891 * REExtendedRegisterClass (RICHED20.8)
4893 * FIXME undocumented
4894 * Need to check for errors and implement controls and callbacks
4896 LRESULT WINAPI REExtendedRegisterClass(void)
4898 WNDCLASSW wcW;
4899 UINT result;
4901 FIXME("semi stub\n");
4903 wcW.cbClsExtra = 0;
4904 wcW.cbWndExtra = 4;
4905 wcW.hInstance = NULL;
4906 wcW.hIcon = NULL;
4907 wcW.hCursor = NULL;
4908 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4909 wcW.lpszMenuName = NULL;
4911 if (!ME_ListBoxRegistered)
4913 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4914 wcW.lpfnWndProc = REListWndProc;
4915 wcW.lpszClassName = REListBox20W;
4916 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4919 if (!ME_ComboBoxRegistered)
4921 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4922 wcW.lpfnWndProc = REComboWndProc;
4923 wcW.lpszClassName = REComboBox20W;
4924 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4927 result = 0;
4928 if (ME_ListBoxRegistered)
4929 result += 1;
4930 if (ME_ComboBoxRegistered)
4931 result += 2;
4933 return result;
4936 static BOOL isurlspecial(WCHAR c)
4938 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4939 return strchrW( special_chars, c ) != NULL;
4943 * This proc takes a selection, and scans it forward in order to select the span
4944 * of a possible URL candidate. A possible URL candidate must start with isalnum
4945 * or one of the following special characters: *|/\+%#@ and must consist entirely
4946 * of the characters allowed to start the URL, plus : (colon) which may occur
4947 * at most once, and not at either end.
4949 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4950 const ME_Cursor *start,
4951 int nChars,
4952 ME_Cursor *candidate_min,
4953 ME_Cursor *candidate_max)
4955 ME_Cursor cursor = *start;
4956 BOOL foundColon = FALSE;
4957 BOOL candidateStarted = FALSE;
4958 WCHAR lastAcceptedChar = '\0';
4960 while (nChars > 0)
4962 WCHAR *strStart = get_text( &cursor.pRun->member.run, 0 );
4963 WCHAR *str = strStart + cursor.nOffset;
4964 int nLen = cursor.pRun->member.run.len - cursor.nOffset;
4965 nChars -= nLen;
4967 if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4969 /* Find start of candidate */
4970 if (!candidateStarted)
4972 while (nLen)
4974 nLen--;
4975 if (isalnumW(*str) || isurlspecial(*str))
4977 cursor.nOffset = str - strStart;
4978 *candidate_min = cursor;
4979 candidateStarted = TRUE;
4980 lastAcceptedChar = *str++;
4981 break;
4983 str++;
4987 /* Find end of candidate */
4988 if (candidateStarted) {
4989 while (nLen)
4991 nLen--;
4992 if (*str == ':' && !foundColon) {
4993 foundColon = TRUE;
4994 } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4995 cursor.nOffset = str - strStart;
4996 if (lastAcceptedChar == ':')
4997 ME_MoveCursorChars(editor, &cursor, -1);
4998 *candidate_max = cursor;
4999 return TRUE;
5001 lastAcceptedChar = *str++;
5004 } else {
5005 /* End of paragraph: skip it if before candidate span, or terminates
5006 current active span */
5007 if (candidateStarted) {
5008 if (lastAcceptedChar == ':')
5009 ME_MoveCursorChars(editor, &cursor, -1);
5010 *candidate_max = cursor;
5011 return TRUE;
5015 /* Reaching this point means no span was found, so get next span */
5016 if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
5017 if (candidateStarted) {
5018 /* There are no further runs, so take end of text as end of candidate */
5019 cursor.nOffset = str - strStart;
5020 if (lastAcceptedChar == ':')
5021 ME_MoveCursorChars(editor, &cursor, -1);
5022 *candidate_max = cursor;
5023 return TRUE;
5025 *candidate_max = *candidate_min = cursor;
5026 return FALSE;
5028 cursor.nOffset = 0;
5031 if (candidateStarted) {
5032 /* There are no further runs, so take end of text as end of candidate */
5033 if (lastAcceptedChar == ':')
5034 ME_MoveCursorChars(editor, &cursor, -1);
5035 *candidate_max = cursor;
5036 return TRUE;
5038 *candidate_max = *candidate_min = cursor;
5039 return FALSE;
5043 * This proc evaluates the selection and returns TRUE if it can be considered an URL
5045 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
5047 #define MAX_PREFIX_LEN 9
5048 struct prefix_s {
5049 const WCHAR text[MAX_PREFIX_LEN];
5050 int length;
5051 }prefixes[] = {
5052 {{'p','r','o','s','p','e','r','o',':'}, 9},
5053 {{'t','e','l','n','e','t',':'}, 7},
5054 {{'g','o','p','h','e','r',':'}, 7},
5055 {{'m','a','i','l','t','o',':'}, 7},
5056 {{'h','t','t','p','s',':'}, 6},
5057 {{'f','i','l','e',':'}, 5},
5058 {{'n','e','w','s',':'}, 5},
5059 {{'w','a','i','s',':'}, 5},
5060 {{'n','n','t','p',':'}, 5},
5061 {{'h','t','t','p',':'}, 5},
5062 {{'w','w','w','.'}, 4},
5063 {{'f','t','p',':'}, 4},
5065 WCHAR bufferW[MAX_PREFIX_LEN + 1];
5066 unsigned int i;
5068 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, FALSE, FALSE);
5069 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
5071 if (nChars < prefixes[i].length) continue;
5072 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
5073 return TRUE;
5075 return FALSE;
5076 #undef MAX_PREFIX_LEN
5080 * This proc walks through the indicated selection and evaluates whether each
5081 * section identified by ME_FindNextURLCandidate and in-between sections have
5082 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
5083 * not what it is supposed to be, this proc sets or unsets it as appropriate.
5085 * Since this function can cause runs to be split, do not depend on the value
5086 * of the start cursor at the end of the function.
5088 * nChars may be set to INT_MAX to update to the end of the text.
5090 * Returns TRUE if at least one section was modified.
5092 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
5094 BOOL modified = FALSE;
5095 ME_Cursor startCur = *start;
5097 if (!editor->AutoURLDetect_bEnable) return FALSE;
5101 CHARFORMAT2W link;
5102 ME_Cursor candidateStart, candidateEnd;
5104 if (ME_FindNextURLCandidate(editor, &startCur, nChars,
5105 &candidateStart, &candidateEnd))
5107 /* Section before candidate is not an URL */
5108 int cMin = ME_GetCursorOfs(&candidateStart);
5109 int cMax = ME_GetCursorOfs(&candidateEnd);
5111 if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
5112 candidateStart = candidateEnd;
5113 nChars -= cMax - ME_GetCursorOfs(&startCur);
5115 else
5117 /* No more candidates until end of selection */
5118 nChars = 0;
5121 if (startCur.pRun != candidateStart.pRun ||
5122 startCur.nOffset != candidateStart.nOffset)
5124 /* CFE_LINK effect should be consistently unset */
5125 link.cbSize = sizeof(link);
5126 ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
5127 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
5129 /* CFE_LINK must be unset from this range */
5130 memset(&link, 0, sizeof(CHARFORMAT2W));
5131 link.cbSize = sizeof(link);
5132 link.dwMask = CFM_LINK;
5133 link.dwEffects = 0;
5134 ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
5135 /* Update candidateEnd since setting character formats may split
5136 * runs, which can cause a cursor to be at an invalid offset within
5137 * a split run. */
5138 while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.len)
5140 candidateEnd.nOffset -= candidateEnd.pRun->member.run.len;
5141 candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
5143 modified = TRUE;
5146 if (candidateStart.pRun != candidateEnd.pRun ||
5147 candidateStart.nOffset != candidateEnd.nOffset)
5149 /* CFE_LINK effect should be consistently set */
5150 link.cbSize = sizeof(link);
5151 ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5152 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
5154 /* CFE_LINK must be set on this range */
5155 memset(&link, 0, sizeof(CHARFORMAT2W));
5156 link.cbSize = sizeof(link);
5157 link.dwMask = CFM_LINK;
5158 link.dwEffects = CFE_LINK;
5159 ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
5160 modified = TRUE;
5163 startCur = candidateEnd;
5164 } while (nChars > 0);
5165 return modified;