richedit: Add helpers for setting cursor to start/end of text.
[wine.git] / dlls / riched20 / editor.c
blobfcfd3c4712abd98388384f07f538dbca20547f9f
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
145 - WM_STYLECHANGED (things like read-only flag)
146 + WM_UNICHAR
147 + WM_VSCROLL
149 Notifications
151 * EN_CHANGE (sent from the wrong place)
152 - EN_CORRECTTEXT
153 - EN_DROPFILES
154 - EN_ERRSPACE
155 - EN_HSCROLL
156 - EN_IMECHANGE
157 + EN_KILLFOCUS
158 - EN_LINK
159 - EN_MAXTEXT
160 - EN_MSGFILTER
161 - EN_OLEOPFAILED
162 - EN_PROTECTED
163 + EN_REQUESTRESIZE
164 - EN_SAVECLIPBOARD
165 + EN_SELCHANGE
166 + EN_SETFOCUS
167 - EN_STOPNOUNDO
168 * EN_UPDATE (sent from the wrong place)
169 - EN_VSCROLL
171 Styles
173 - ES_AUTOHSCROLL
174 - ES_AUTOVSCROLL
175 - ES_CENTER
176 + ES_DISABLENOSCROLL (scrollbar is always visible)
177 - ES_EX_NOCALLOLEINIT
178 - ES_LEFT
179 - ES_MULTILINE (currently single line controls aren't supported)
180 - ES_NOIME
181 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182 - ES_RIGHT
183 - ES_SAVESEL
184 - ES_SELFIME
185 - ES_SUNKEN
186 - ES_VERTICAL
187 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188 - WS_SETFONT
189 + WS_HSCROLL
190 + WS_VSCROLL
194 * RICHED20 TODO (incomplete):
196 * - messages/styles/notifications listed above
197 * - add remaining CHARFORMAT/PARAFORMAT fields
198 * - right/center align should strip spaces from the beginning
199 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200 * - COM interface (looks like a major pain in the TODO list)
201 * - calculate heights of pictures (half-done)
202 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203 * - find/replace
204 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205 * - italic caret with italic fonts
206 * - IME
207 * - most notifications aren't sent at all (the most important ones are)
208 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211 * - full justification
212 * - hyphenation
213 * - tables
214 * - ListBox & ComboBox not implemented
216 * Bugs that are probably fixed, but not so easy to verify:
217 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220 * - caret shouldn't be displayed when selection isn't empty
221 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222 * - undo for setting default format (done, might be buggy)
223 * - styles might be not released properly (looks like they work like charm, but who knows?
227 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
236 #define STACK_SIZE_DEFAULT 100
237 #define STACK_SIZE_MAX 1000
239 #define TEXT_LIMIT_DEFAULT 32767
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max);
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
250 int me_debug = 0;
251 HANDLE me_heap = NULL;
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
256 static inline int is_version_nt(void)
258 return !(GetVersion() & 0x80000000);
261 static ME_TextBuffer *ME_MakeText(void) {
263 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
265 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
268 p1->prev = NULL;
269 p1->next = p2;
270 p2->prev = p1;
271 p2->next = NULL;
272 p1->member.para.next_para = p2;
273 p2->member.para.prev_para = p1;
274 p2->member.para.nCharOfs = 0;
276 buf->pFirst = p1;
277 buf->pLast = p2;
278 buf->pCharStyle = NULL;
280 return buf;
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
286 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
287 WCHAR *pText;
289 TRACE("%08x %p\n", dwFormat, stream);
291 do {
292 long nWideChars = 0;
294 if (!stream->dwSize)
296 ME_StreamInFill(stream);
297 if (stream->editstream->dwError)
298 break;
299 if (!stream->dwSize)
300 break;
303 if (!(dwFormat & SF_UNICODE))
305 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
306 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
307 pText = wszText;
309 else
311 nWideChars = stream->dwSize >> 1;
312 pText = (WCHAR *)stream->buffer;
315 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
316 if (stream->dwSize == 0)
317 break;
318 stream->dwSize = 0;
319 } while(1);
320 ME_CommitUndo(editor);
321 ME_UpdateRepaint(editor);
322 return 0;
325 static void ME_ApplyBorderProperties(RTF_Info *info,
326 ME_BorderRect *borderRect,
327 RTFBorder *borderDef)
329 int i, colorNum;
330 ME_Border *pBorders[] = {&borderRect->top,
331 &borderRect->left,
332 &borderRect->bottom,
333 &borderRect->right};
334 for (i = 0; i < 4; i++)
336 RTFColor *colorDef = info->colorList;
337 pBorders[i]->width = borderDef[i].width;
338 colorNum = borderDef[i].color;
339 while (colorDef && colorDef->rtfCNum != colorNum)
340 colorDef = colorDef->rtfNextColor;
341 if (colorDef)
342 pBorders[i]->colorRef = RGB(
343 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
344 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
345 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
346 else
347 pBorders[i]->colorRef = RGB(0, 0, 0);
351 void ME_RTFCharAttrHook(RTF_Info *info)
353 CHARFORMAT2W fmt;
354 fmt.cbSize = sizeof(fmt);
355 fmt.dwMask = 0;
356 fmt.dwEffects = 0;
358 switch(info->rtfMinor)
360 case rtfPlain:
361 /* FIXME add more flags once they're implemented */
362 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
363 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
364 fmt.yHeight = 12*20; /* 12pt */
365 fmt.wWeight = FW_NORMAL;
366 fmt.bUnderlineType = CFU_UNDERLINENONE;
367 break;
368 case rtfBold:
369 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
370 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
371 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
372 break;
373 case rtfItalic:
374 fmt.dwMask = CFM_ITALIC;
375 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
376 break;
377 case rtfUnderline:
378 fmt.dwMask = CFM_UNDERLINETYPE;
379 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
380 break;
381 case rtfDotUnderline:
382 fmt.dwMask = CFM_UNDERLINETYPE;
383 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
384 break;
385 case rtfDbUnderline:
386 fmt.dwMask = CFM_UNDERLINETYPE;
387 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
388 break;
389 case rtfWordUnderline:
390 fmt.dwMask = CFM_UNDERLINETYPE;
391 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
392 break;
393 case rtfNoUnderline:
394 fmt.dwMask = CFM_UNDERLINETYPE;
395 fmt.bUnderlineType = CFU_UNDERLINENONE;
396 break;
397 case rtfStrikeThru:
398 fmt.dwMask = CFM_STRIKEOUT;
399 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
400 break;
401 case rtfSubScript:
402 case rtfSuperScript:
403 case rtfSubScrShrink:
404 case rtfSuperScrShrink:
405 case rtfNoSuperSub:
406 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
407 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
408 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
409 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
410 break;
411 case rtfInvisible:
412 fmt.dwMask = CFM_HIDDEN;
413 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
414 break;
415 case rtfBackColor:
416 fmt.dwMask = CFM_BACKCOLOR;
417 fmt.dwEffects = 0;
418 if (info->rtfParam == 0)
419 fmt.dwEffects = CFE_AUTOBACKCOLOR;
420 else if (info->rtfParam != rtfNoParam)
422 RTFColor *c = RTFGetColor(info, info->rtfParam);
423 if (c && c->rtfCBlue >= 0)
424 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
425 else
426 fmt.dwEffects = CFE_AUTOBACKCOLOR;
428 break;
429 case rtfForeColor:
430 fmt.dwMask = CFM_COLOR;
431 fmt.dwEffects = 0;
432 if (info->rtfParam == 0)
433 fmt.dwEffects = CFE_AUTOCOLOR;
434 else if (info->rtfParam != rtfNoParam)
436 RTFColor *c = RTFGetColor(info, info->rtfParam);
437 if (c && c->rtfCBlue >= 0)
438 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
439 else {
440 fmt.dwEffects = CFE_AUTOCOLOR;
443 break;
444 case rtfFontNum:
445 if (info->rtfParam != rtfNoParam)
447 RTFFont *f = RTFGetFont(info, info->rtfParam);
448 if (f)
450 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
451 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
452 fmt.bCharSet = f->rtfFCharSet;
453 fmt.dwMask = CFM_FACE | CFM_CHARSET;
454 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
457 break;
458 case rtfFontSize:
459 fmt.dwMask = CFM_SIZE;
460 if (info->rtfParam != rtfNoParam)
461 fmt.yHeight = info->rtfParam*10;
462 break;
464 if (fmt.dwMask) {
465 ME_Style *style2;
466 RTFFlushOutputBuffer(info);
467 /* FIXME too slow ? how come ? */
468 style2 = ME_ApplyStyle(info->style, &fmt);
469 ME_ReleaseStyle(info->style);
470 info->style = style2;
471 info->styleChanged = TRUE;
475 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
476 the same tags mean different things in different contexts */
477 void ME_RTFParAttrHook(RTF_Info *info)
479 PARAFORMAT2 fmt;
480 fmt.cbSize = sizeof(fmt);
481 fmt.dwMask = 0;
483 switch(info->rtfMinor)
485 case rtfParDef: /* restores default paragraph attributes */
486 if (!info->editor->bEmulateVersion10) /* v4.1 */
487 info->borderType = RTFBorderParaLeft;
488 else /* v1.0 - 3.0 */
489 info->borderType = RTFBorderParaTop;
490 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
491 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
492 PFM_STARTINDENT;
493 /* TODO: numbering, shading */
494 fmt.wAlignment = PFA_LEFT;
495 fmt.cTabCount = 0;
496 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
497 fmt.wBorderWidth = fmt.wBorders = 0;
498 fmt.wBorderSpace = 0;
499 fmt.bLineSpacingRule = 0;
500 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
501 fmt.dyLineSpacing = 0;
502 if (!info->editor->bEmulateVersion10) /* v4.1 */
504 if (info->tableDef && info->tableDef->tableRowStart &&
505 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
507 ME_Cursor cursor;
508 ME_DisplayItem *para;
509 /* We are just after a table row. */
510 RTFFlushOutputBuffer(info);
511 cursor = info->editor->pCursors[0];
512 para = cursor.pPara;
513 if (para == info->tableDef->tableRowStart->member.para.next_para
514 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
516 /* Since the table row end, no text has been inserted, and the \intbl
517 * control word has not be used. We can confirm that we are not in a
518 * table anymore.
520 info->tableDef->tableRowStart = NULL;
521 info->canInheritInTbl = FALSE;
524 } else { /* v1.0 - v3.0 */
525 fmt.dwMask |= PFM_TABLE;
526 fmt.wEffects &= ~PFE_TABLE;
528 break;
529 case rtfNestLevel:
530 if (!info->editor->bEmulateVersion10) /* v4.1 */
532 while (info->rtfParam > info->nestingLevel) {
533 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
534 ZeroMemory(tableDef, sizeof(RTFTable));
535 tableDef->parent = info->tableDef;
536 info->tableDef = tableDef;
538 RTFFlushOutputBuffer(info);
539 if (tableDef->tableRowStart &&
540 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
542 ME_DisplayItem *para = tableDef->tableRowStart;
543 para = para->member.para.next_para;
544 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
545 tableDef->tableRowStart = para;
546 } else {
547 ME_Cursor cursor;
548 WCHAR endl = '\r';
549 cursor = info->editor->pCursors[0];
550 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
551 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
552 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
555 info->nestingLevel++;
557 info->canInheritInTbl = FALSE;
559 break;
560 case rtfInTable:
562 if (!info->editor->bEmulateVersion10) /* v4.1 */
564 if (info->nestingLevel < 1)
566 RTFTable *tableDef;
567 if (!info->tableDef)
569 info->tableDef = ALLOC_OBJ(RTFTable);
570 ZeroMemory(info->tableDef, sizeof(RTFTable));
572 tableDef = info->tableDef;
573 RTFFlushOutputBuffer(info);
574 if (tableDef->tableRowStart &&
575 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
577 ME_DisplayItem *para = tableDef->tableRowStart;
578 para = para->member.para.next_para;
579 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
580 tableDef->tableRowStart = para;
581 } else {
582 ME_Cursor cursor;
583 WCHAR endl = '\r';
584 cursor = info->editor->pCursors[0];
585 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
586 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
587 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
589 info->nestingLevel = 1;
590 info->canInheritInTbl = TRUE;
592 return;
593 } else { /* v1.0 - v3.0 */
594 fmt.dwMask |= PFM_TABLE;
595 fmt.wEffects |= PFE_TABLE;
597 break;
599 case rtfFirstIndent:
600 ME_GetSelectionParaFormat(info->editor, &fmt);
601 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
602 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
603 fmt.dxOffset = -info->rtfParam;
604 break;
605 case rtfLeftIndent:
606 ME_GetSelectionParaFormat(info->editor, &fmt);
607 fmt.dwMask = PFM_STARTINDENT;
608 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
609 break;
610 case rtfRightIndent:
611 fmt.dwMask = PFM_RIGHTINDENT;
612 fmt.dxRightIndent = info->rtfParam;
613 break;
614 case rtfQuadLeft:
615 case rtfQuadJust:
616 fmt.dwMask = PFM_ALIGNMENT;
617 fmt.wAlignment = PFA_LEFT;
618 break;
619 case rtfQuadRight:
620 fmt.dwMask = PFM_ALIGNMENT;
621 fmt.wAlignment = PFA_RIGHT;
622 break;
623 case rtfQuadCenter:
624 fmt.dwMask = PFM_ALIGNMENT;
625 fmt.wAlignment = PFA_CENTER;
626 break;
627 case rtfTabPos:
628 ME_GetSelectionParaFormat(info->editor, &fmt);
629 if (!(fmt.dwMask & PFM_TABSTOPS))
631 fmt.cTabCount = 0;
633 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
634 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
635 fmt.dwMask = PFM_TABSTOPS;
636 break;
637 case rtfKeep:
638 fmt.dwMask = PFM_KEEP;
639 fmt.wEffects = PFE_KEEP;
640 break;
641 case rtfNoWidowControl:
642 fmt.dwMask = PFM_NOWIDOWCONTROL;
643 fmt.wEffects = PFE_NOWIDOWCONTROL;
644 break;
645 case rtfKeepNext:
646 fmt.dwMask = PFM_KEEPNEXT;
647 fmt.wEffects = PFE_KEEPNEXT;
648 break;
649 case rtfSpaceAfter:
650 fmt.dwMask = PFM_SPACEAFTER;
651 fmt.dySpaceAfter = info->rtfParam;
652 break;
653 case rtfSpaceBefore:
654 fmt.dwMask = PFM_SPACEBEFORE;
655 fmt.dySpaceBefore = info->rtfParam;
656 break;
657 case rtfSpaceBetween:
658 fmt.dwMask = PFM_LINESPACING;
659 if ((int)info->rtfParam > 0)
661 fmt.dyLineSpacing = info->rtfParam;
662 fmt.bLineSpacingRule = 3;
664 else
666 fmt.dyLineSpacing = info->rtfParam;
667 fmt.bLineSpacingRule = 4;
669 case rtfSpaceMultiply:
670 fmt.dwMask = PFM_LINESPACING;
671 fmt.dyLineSpacing = info->rtfParam * 20;
672 fmt.bLineSpacingRule = 5;
673 break;
674 case rtfParBullet:
675 fmt.dwMask = PFM_NUMBERING;
676 fmt.wNumbering = PFN_BULLET;
677 break;
678 case rtfParSimple:
679 fmt.dwMask = PFM_NUMBERING;
680 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
681 break;
682 case rtfParNumDecimal:
683 fmt.dwMask = PFM_NUMBERING;
684 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
685 break;
686 case rtfParNumIndent:
687 fmt.dwMask = PFM_NUMBERINGTAB;
688 fmt.wNumberingTab = info->rtfParam;
689 break;
690 case rtfParNumStartAt:
691 fmt.dwMask = PFM_NUMBERINGSTART;
692 fmt.wNumberingStart = info->rtfParam;
693 break;
694 case rtfBorderLeft:
695 info->borderType = RTFBorderParaLeft;
696 ME_GetSelectionParaFormat(info->editor, &fmt);
697 if (!(fmt.dwMask & PFM_BORDER))
699 fmt.wBorderSpace = 0;
700 fmt.wBorderWidth = 1;
701 fmt.wBorders = 0;
703 fmt.wBorders |= 1;
704 fmt.dwMask = PFM_BORDER;
705 break;
706 case rtfBorderRight:
707 info->borderType = RTFBorderParaRight;
708 ME_GetSelectionParaFormat(info->editor, &fmt);
709 if (!(fmt.dwMask & PFM_BORDER))
711 fmt.wBorderSpace = 0;
712 fmt.wBorderWidth = 1;
713 fmt.wBorders = 0;
715 fmt.wBorders |= 2;
716 fmt.dwMask = PFM_BORDER;
717 break;
718 case rtfBorderTop:
719 info->borderType = RTFBorderParaTop;
720 ME_GetSelectionParaFormat(info->editor, &fmt);
721 if (!(fmt.dwMask & PFM_BORDER))
723 fmt.wBorderSpace = 0;
724 fmt.wBorderWidth = 1;
725 fmt.wBorders = 0;
727 fmt.wBorders |= 4;
728 fmt.dwMask = PFM_BORDER;
729 break;
730 case rtfBorderBottom:
731 info->borderType = RTFBorderParaBottom;
732 ME_GetSelectionParaFormat(info->editor, &fmt);
733 if (!(fmt.dwMask & PFM_BORDER))
735 fmt.wBorderSpace = 0;
736 fmt.wBorderWidth = 1;
737 fmt.wBorders = 0;
739 fmt.wBorders |= 8;
740 fmt.dwMask = PFM_BORDER;
741 break;
742 case rtfBorderSingle:
743 ME_GetSelectionParaFormat(info->editor, &fmt);
744 /* we assume that borders have been created before (RTF spec) */
745 fmt.wBorders &= ~0x700;
746 fmt.wBorders |= 1 << 8;
747 fmt.dwMask = PFM_BORDER;
748 break;
749 case rtfBorderThick:
750 ME_GetSelectionParaFormat(info->editor, &fmt);
751 /* we assume that borders have been created before (RTF spec) */
752 fmt.wBorders &= ~0x700;
753 fmt.wBorders |= 2 << 8;
754 fmt.dwMask = PFM_BORDER;
755 break;
756 case rtfBorderShadow:
757 ME_GetSelectionParaFormat(info->editor, &fmt);
758 /* we assume that borders have been created before (RTF spec) */
759 fmt.wBorders &= ~0x700;
760 fmt.wBorders |= 10 << 8;
761 fmt.dwMask = PFM_BORDER;
762 break;
763 case rtfBorderDouble:
764 ME_GetSelectionParaFormat(info->editor, &fmt);
765 /* we assume that borders have been created before (RTF spec) */
766 fmt.wBorders &= ~0x700;
767 fmt.wBorders |= 7 << 8;
768 fmt.dwMask = PFM_BORDER;
769 break;
770 case rtfBorderDot:
771 ME_GetSelectionParaFormat(info->editor, &fmt);
772 /* we assume that borders have been created before (RTF spec) */
773 fmt.wBorders &= ~0x700;
774 fmt.wBorders |= 11 << 8;
775 fmt.dwMask = PFM_BORDER;
776 break;
777 case rtfBorderWidth:
779 int borderSide = info->borderType & RTFBorderSideMask;
780 RTFTable *tableDef = info->tableDef;
781 ME_GetSelectionParaFormat(info->editor, &fmt);
782 /* we assume that borders have been created before (RTF spec) */
783 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
784 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
786 RTFBorder *border;
787 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
788 break;
789 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
790 border->width = info->rtfParam;
791 break;
793 fmt.dwMask = PFM_BORDER;
794 break;
796 case rtfBorderSpace:
797 ME_GetSelectionParaFormat(info->editor, &fmt);
798 /* we assume that borders have been created before (RTF spec) */
799 fmt.wBorderSpace = info->rtfParam;
800 fmt.dwMask = PFM_BORDER;
801 break;
802 case rtfBorderColor:
804 RTFTable *tableDef = info->tableDef;
805 int borderSide = info->borderType & RTFBorderSideMask;
806 int borderType = info->borderType & RTFBorderTypeMask;
807 switch(borderType)
809 case RTFBorderTypePara:
810 if (!info->editor->bEmulateVersion10) /* v4.1 */
811 break;
812 /* v1.0 - 3.0 treat paragraph and row borders the same. */
813 case RTFBorderTypeRow:
814 if (tableDef) {
815 tableDef->border[borderSide].color = info->rtfParam;
817 break;
818 case RTFBorderTypeCell:
819 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
820 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
822 break;
824 break;
827 if (fmt.dwMask) {
828 RTFFlushOutputBuffer(info);
829 /* FIXME too slow ? how come ?*/
830 ME_SetSelectionParaFormat(info->editor, &fmt);
834 void ME_RTFTblAttrHook(RTF_Info *info)
836 switch (info->rtfMinor)
838 case rtfRowDef:
840 if (!info->editor->bEmulateVersion10) /* v4.1 */
841 info->borderType = 0; /* Not sure */
842 else /* v1.0 - 3.0 */
843 info->borderType = RTFBorderRowTop;
844 if (!info->tableDef) {
845 info->tableDef = ME_MakeTableDef(info->editor);
846 } else {
847 ME_InitTableDef(info->editor, info->tableDef);
849 break;
851 case rtfCellPos:
853 int cellNum;
854 if (!info->tableDef)
856 info->tableDef = ME_MakeTableDef(info->editor);
858 cellNum = info->tableDef->numCellsDefined;
859 if (cellNum >= MAX_TABLE_CELLS)
860 break;
861 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
862 if (cellNum < MAX_TAB_STOPS) {
863 /* Tab stops were used to store cell positions before v4.1 but v4.1
864 * still seems to set the tabstops without using them. */
865 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
866 PARAFORMAT2 *pFmt = para->member.para.pFmt;
867 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
868 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
870 info->tableDef->numCellsDefined++;
871 break;
873 case rtfRowBordTop:
874 info->borderType = RTFBorderRowTop;
875 break;
876 case rtfRowBordLeft:
877 info->borderType = RTFBorderRowLeft;
878 break;
879 case rtfRowBordBottom:
880 info->borderType = RTFBorderRowBottom;
881 break;
882 case rtfRowBordRight:
883 info->borderType = RTFBorderRowRight;
884 break;
885 case rtfCellBordTop:
886 info->borderType = RTFBorderCellTop;
887 break;
888 case rtfCellBordLeft:
889 info->borderType = RTFBorderCellLeft;
890 break;
891 case rtfCellBordBottom:
892 info->borderType = RTFBorderCellBottom;
893 break;
894 case rtfCellBordRight:
895 info->borderType = RTFBorderCellRight;
896 break;
897 case rtfRowGapH:
898 if (info->tableDef)
899 info->tableDef->gapH = info->rtfParam;
900 break;
901 case rtfRowLeftEdge:
902 if (info->tableDef)
903 info->tableDef->leftEdge = info->rtfParam;
904 break;
908 void ME_RTFSpecialCharHook(RTF_Info *info)
910 RTFTable *tableDef = info->tableDef;
911 switch (info->rtfMinor)
913 case rtfNestCell:
914 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
915 break;
916 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
917 case rtfCell:
918 if (!tableDef)
919 break;
920 RTFFlushOutputBuffer(info);
921 if (!info->editor->bEmulateVersion10) { /* v4.1 */
922 if (tableDef->tableRowStart)
924 if (!info->nestingLevel &&
925 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
927 ME_DisplayItem *para = tableDef->tableRowStart;
928 para = para->member.para.next_para;
929 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
930 tableDef->tableRowStart = para;
931 info->nestingLevel = 1;
933 ME_InsertTableCellFromCursor(info->editor);
935 } else { /* v1.0 - v3.0 */
936 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
937 PARAFORMAT2 *pFmt = para->member.para.pFmt;
938 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
939 tableDef->numCellsInserted < tableDef->numCellsDefined)
941 WCHAR tab = '\t';
942 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
943 tableDef->numCellsInserted++;
946 break;
947 case rtfNestRow:
948 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
949 break;
950 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
951 case rtfRow:
953 ME_DisplayItem *para, *cell, *run;
954 int i;
956 if (!tableDef)
957 break;
958 RTFFlushOutputBuffer(info);
959 if (!info->editor->bEmulateVersion10) { /* v4.1 */
960 if (!tableDef->tableRowStart)
961 break;
962 if (!info->nestingLevel &&
963 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
965 para = tableDef->tableRowStart;
966 para = para->member.para.next_para;
967 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
968 tableDef->tableRowStart = para;
969 info->nestingLevel++;
971 para = tableDef->tableRowStart;
972 cell = ME_FindItemFwd(para, diCell);
973 assert(cell && !cell->member.cell.prev_cell);
974 if (tableDef->numCellsDefined < 1)
976 /* 2000 twips appears to be the cell size that native richedit uses
977 * when no cell sizes are specified. */
978 const int defaultCellSize = 2000;
979 int nRightBoundary = defaultCellSize;
980 cell->member.cell.nRightBoundary = nRightBoundary;
981 while (cell->member.cell.next_cell) {
982 cell = cell->member.cell.next_cell;
983 nRightBoundary += defaultCellSize;
984 cell->member.cell.nRightBoundary = nRightBoundary;
986 para = ME_InsertTableCellFromCursor(info->editor);
987 cell = para->member.para.pCell;
988 cell->member.cell.nRightBoundary = nRightBoundary;
989 } else {
990 for (i = 0; i < tableDef->numCellsDefined; i++)
992 RTFCell *cellDef = &tableDef->cells[i];
993 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
994 ME_ApplyBorderProperties(info, &cell->member.cell.border,
995 cellDef->border);
996 cell = cell->member.cell.next_cell;
997 if (!cell)
999 para = ME_InsertTableCellFromCursor(info->editor);
1000 cell = para->member.para.pCell;
1003 /* Cell for table row delimiter is empty */
1004 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1007 run = ME_FindItemFwd(cell, diRun);
1008 if (info->editor->pCursors[0].pRun != run ||
1009 info->editor->pCursors[0].nOffset)
1011 int nOfs, nChars;
1012 /* Delete inserted cells that aren't defined. */
1013 info->editor->pCursors[1].pRun = run;
1014 info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1015 info->editor->pCursors[1].nOffset = 0;
1016 nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1017 nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1018 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
1021 para = ME_InsertTableRowEndFromCursor(info->editor);
1022 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1023 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1024 ME_ApplyBorderProperties(info, &para->member.para.border,
1025 tableDef->border);
1026 info->nestingLevel--;
1027 if (!info->nestingLevel)
1029 if (info->canInheritInTbl) {
1030 tableDef->tableRowStart = para;
1031 } else {
1032 while (info->tableDef) {
1033 tableDef = info->tableDef;
1034 info->tableDef = tableDef->parent;
1035 heap_free(tableDef);
1038 } else {
1039 info->tableDef = tableDef->parent;
1040 heap_free(tableDef);
1042 } else { /* v1.0 - v3.0 */
1043 WCHAR endl = '\r';
1044 ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1045 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1046 pFmt->dxOffset = info->tableDef->gapH;
1047 pFmt->dxStartIndent = info->tableDef->leftEdge;
1049 ME_ApplyBorderProperties(info, &para->member.para.border,
1050 tableDef->border);
1051 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1053 WCHAR tab = '\t';
1054 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1055 tableDef->numCellsInserted++;
1057 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1058 if (!tableDef->numCellsDefined)
1059 pFmt->wEffects &= ~PFE_TABLE;
1060 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1061 tableDef->numCellsInserted = 0;
1063 break;
1065 case rtfTab:
1066 case rtfPar:
1067 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1068 ME_DisplayItem *para;
1069 PARAFORMAT2 *pFmt;
1070 RTFFlushOutputBuffer(info);
1071 para = info->editor->pCursors[0].pPara;
1072 pFmt = para->member.para.pFmt;
1073 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1075 /* rtfPar is treated like a space within a table. */
1076 info->rtfClass = rtfText;
1077 info->rtfMajor = ' ';
1079 else if (info->rtfMinor == rtfPar && tableDef)
1080 tableDef->numCellsInserted = 0;
1082 break;
1086 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1087 const SIZEL* sz)
1089 LPOLEOBJECT lpObject = NULL;
1090 LPSTORAGE lpStorage = NULL;
1091 LPOLECLIENTSITE lpClientSite = NULL;
1092 LPDATAOBJECT lpDataObject = NULL;
1093 LPOLECACHE lpOleCache = NULL;
1094 STGMEDIUM stgm;
1095 FORMATETC fm;
1096 CLSID clsid;
1097 BOOL ret = FALSE;
1098 DWORD conn;
1100 if (hemf)
1102 stgm.tymed = TYMED_ENHMF;
1103 stgm.u.hEnhMetaFile = hemf;
1104 fm.cfFormat = CF_ENHMETAFILE;
1106 else if (hbmp)
1108 stgm.tymed = TYMED_GDI;
1109 stgm.u.hBitmap = hbmp;
1110 fm.cfFormat = CF_BITMAP;
1112 stgm.pUnkForRelease = NULL;
1114 fm.ptd = NULL;
1115 fm.dwAspect = DVASPECT_CONTENT;
1116 fm.lindex = -1;
1117 fm.tymed = stgm.tymed;
1119 if (!info->lpRichEditOle)
1121 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1124 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1125 #if 0
1126 /* FIXME: enable it when rich-edit properly implements this method */
1127 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1128 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1129 #endif
1130 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1131 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1132 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1133 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1134 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1136 REOBJECT reobject;
1138 reobject.cbStruct = sizeof(reobject);
1139 reobject.cp = REO_CP_SELECTION;
1140 reobject.clsid = clsid;
1141 reobject.poleobj = lpObject;
1142 reobject.pstg = lpStorage;
1143 reobject.polesite = lpClientSite;
1144 /* convert from twips to .01 mm */
1145 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1146 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1147 reobject.dvaspect = DVASPECT_CONTENT;
1148 reobject.dwFlags = 0; /* FIXME */
1149 reobject.dwUser = 0;
1151 /* FIXME: could be simpler */
1152 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1155 if (lpObject) IOleObject_Release(lpObject);
1156 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1157 if (lpStorage) IStorage_Release(lpStorage);
1158 if (lpDataObject) IDataObject_Release(lpDataObject);
1159 if (lpOleCache) IOleCache_Release(lpOleCache);
1161 return ret;
1164 static void ME_RTFReadPictGroup(RTF_Info *info)
1166 SIZEL sz;
1167 BYTE* buffer = NULL;
1168 unsigned bufsz, bufidx;
1169 BOOL flip;
1170 BYTE val;
1171 METAFILEPICT mfp;
1172 HENHMETAFILE hemf;
1173 HBITMAP hbmp;
1174 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1176 RTFGetToken (info);
1177 if (info->rtfClass == rtfEOF)
1178 return;
1179 mfp.mm = MM_TEXT;
1180 /* fetch picture type */
1181 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1183 mfp.mm = info->rtfParam;
1184 gfx = gfx_metafile;
1186 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1188 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1189 gfx = gfx_dib;
1191 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1193 gfx = gfx_enhmetafile;
1195 else
1197 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1198 goto skip_group;
1200 sz.cx = sz.cy = 0;
1201 /* fetch picture attributes */
1202 for (;;)
1204 RTFGetToken (info);
1205 if (info->rtfClass == rtfEOF)
1206 return;
1207 if (info->rtfClass == rtfText)
1208 break;
1209 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1211 ERR("Expected picture attribute (%d %d)\n",
1212 info->rtfClass, info->rtfMajor);
1213 goto skip_group;
1215 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1217 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1219 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1221 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1223 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1224 sz.cx = info->rtfParam;
1225 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1226 sz.cy = info->rtfParam;
1227 else
1228 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1230 /* fetch picture data */
1231 bufsz = 1024;
1232 bufidx = 0;
1233 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1234 val = info->rtfMajor;
1235 for (flip = TRUE;; flip = !flip)
1237 RTFGetToken (info);
1238 if (info->rtfClass == rtfEOF)
1240 HeapFree(GetProcessHeap(), 0, buffer);
1241 return; /* Warn ?? */
1243 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1244 break;
1245 if (info->rtfClass != rtfText) goto skip_group;
1246 if (flip)
1248 if (bufidx >= bufsz &&
1249 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1250 goto skip_group;
1251 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1253 else
1254 val = info->rtfMajor;
1256 if (flip) FIXME("wrong hex string\n");
1258 switch (gfx)
1260 case gfx_enhmetafile:
1261 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1262 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1263 break;
1264 case gfx_metafile:
1265 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1266 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1267 break;
1268 case gfx_dib:
1270 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1271 HDC hdc = GetDC(0);
1272 unsigned nc = bi->bmiHeader.biClrUsed;
1274 /* not quite right, especially for bitfields type of compression */
1275 if (!nc && bi->bmiHeader.biBitCount <= 8)
1276 nc = 1 << bi->bmiHeader.biBitCount;
1277 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1278 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1279 bi, DIB_RGB_COLORS)))
1280 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1281 ReleaseDC(0, hdc);
1283 break;
1284 default:
1285 break;
1287 HeapFree(GetProcessHeap(), 0, buffer);
1288 RTFRouteToken (info); /* feed "}" back to router */
1289 return;
1290 skip_group:
1291 HeapFree(GetProcessHeap(), 0, buffer);
1292 RTFSkipGroup(info);
1293 RTFRouteToken(info); /* feed "}" back to router */
1296 /* for now, lookup the \result part and use it, whatever the object */
1297 static void ME_RTFReadObjectGroup(RTF_Info *info)
1299 for (;;)
1301 RTFGetToken (info);
1302 if (info->rtfClass == rtfEOF)
1303 return;
1304 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1305 break;
1306 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1308 RTFGetToken (info);
1309 if (info->rtfClass == rtfEOF)
1310 return;
1311 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1313 int level = 1;
1315 while (RTFGetToken (info) != rtfEOF)
1317 if (info->rtfClass == rtfGroup)
1319 if (info->rtfMajor == rtfBeginGroup) level++;
1320 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1322 RTFRouteToken(info);
1325 else RTFSkipGroup(info);
1326 continue;
1328 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1330 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1331 return;
1334 RTFRouteToken(info); /* feed "}" back to router */
1337 static void ME_RTFReadHook(RTF_Info *info)
1339 switch(info->rtfClass)
1341 case rtfGroup:
1342 switch(info->rtfMajor)
1344 case rtfBeginGroup:
1345 if (info->stackTop < maxStack) {
1346 info->stack[info->stackTop].style = info->style;
1347 ME_AddRefStyle(info->style);
1348 info->stack[info->stackTop].codePage = info->codePage;
1349 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1351 info->stackTop++;
1352 info->styleChanged = FALSE;
1353 break;
1354 case rtfEndGroup:
1356 RTFFlushOutputBuffer(info);
1357 info->stackTop--;
1358 if (info->stackTop <= 0)
1359 info->rtfClass = rtfEOF;
1360 if (info->stackTop < 0)
1361 return;
1363 ME_ReleaseStyle(info->style);
1364 info->style = info->stack[info->stackTop].style;
1365 info->codePage = info->stack[info->stackTop].codePage;
1366 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1367 break;
1370 break;
1374 void
1375 ME_StreamInFill(ME_InStream *stream)
1377 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1378 (BYTE *)stream->buffer,
1379 sizeof(stream->buffer),
1380 (LONG *)&stream->dwSize);
1381 stream->dwUsed = 0;
1384 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1386 RTF_Info parser;
1387 ME_Style *style;
1388 int from, to, nUndoMode;
1389 int nEventMask = editor->nEventMask;
1390 ME_InStream inStream;
1391 BOOL invalidRTF = FALSE;
1393 TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1394 editor->nEventMask = 0;
1396 ME_GetSelectionOfs(editor, &from, &to);
1397 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1398 style = ME_GetSelectionInsertStyle(editor);
1400 ME_InternalDeleteText(editor, from, to-from, FALSE);
1402 /* Don't insert text at the end of the table row */
1403 if (!editor->bEmulateVersion10) { /* v4.1 */
1404 ME_DisplayItem *para = editor->pCursors->pPara;
1405 if (para->member.para.nFlags & MEPF_ROWEND)
1407 para = para->member.para.next_para;
1408 editor->pCursors[0].pPara = para;
1409 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1410 editor->pCursors[0].nOffset = 0;
1412 if (para->member.para.nFlags & MEPF_ROWSTART)
1414 para = para->member.para.next_para;
1415 editor->pCursors[0].pPara = para;
1416 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1417 editor->pCursors[0].nOffset = 0;
1419 editor->pCursors[1] = editor->pCursors[0];
1420 } else { /* v1.0 - 3.0 */
1421 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1422 ME_IsInTable(editor->pCursors[0].pRun))
1423 return 0;
1426 else {
1427 style = editor->pBuffer->pDefaultStyle;
1428 ME_AddRefStyle(style);
1429 ME_SetSelection(editor, 0, 0);
1430 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1431 from = to = 0;
1432 ME_ClearTempStyle(editor);
1433 ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1437 /* Back up undo mode to a local variable */
1438 nUndoMode = editor->nUndoMode;
1440 /* Only create an undo if SFF_SELECTION is set */
1441 if (!(format & SFF_SELECTION))
1442 editor->nUndoMode = umIgnore;
1444 inStream.editstream = stream;
1445 inStream.editstream->dwError = 0;
1446 inStream.dwSize = 0;
1447 inStream.dwUsed = 0;
1449 if (format & SF_RTF)
1451 /* Check if it's really RTF, and if it is not, use plain text */
1452 ME_StreamInFill(&inStream);
1453 if (!inStream.editstream->dwError)
1455 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1456 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1458 invalidRTF = TRUE;
1459 inStream.editstream->dwError = -16;
1464 if (!invalidRTF && !inStream.editstream->dwError)
1466 if (format & SF_RTF) {
1467 /* setup the RTF parser */
1468 memset(&parser, 0, sizeof parser);
1469 RTFSetEditStream(&parser, &inStream);
1470 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1471 parser.editor = editor;
1472 parser.style = style;
1473 WriterInit(&parser);
1474 RTFInit(&parser);
1475 RTFSetReadHook(&parser, ME_RTFReadHook);
1476 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1477 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1478 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1480 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1481 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1483 BeginFile(&parser);
1485 /* do the parsing */
1486 RTFRead(&parser);
1487 RTFFlushOutputBuffer(&parser);
1488 if (!editor->bEmulateVersion10) { /* v4.1 */
1489 if (parser.tableDef && parser.tableDef->tableRowStart &&
1490 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1492 /* Delete any incomplete table row at the end of the rich text. */
1493 int nOfs, nChars;
1494 ME_DisplayItem *pCell;
1495 ME_DisplayItem *para;
1497 parser.rtfMinor = rtfRow;
1498 /* Complete the table row before deleting it.
1499 * By doing it this way we will have the current paragraph format set
1500 * properly to reflect that is not in the complete table, and undo items
1501 * will be added for this change to the current paragraph format. */
1502 if (parser.nestingLevel > 0)
1504 while (parser.nestingLevel > 1)
1505 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1506 para = parser.tableDef->tableRowStart;
1507 ME_RTFSpecialCharHook(&parser);
1508 } else {
1509 para = parser.tableDef->tableRowStart;
1510 ME_RTFSpecialCharHook(&parser);
1511 assert(para->member.para.nFlags & MEPF_ROWEND);
1512 para = para->member.para.next_para;
1514 pCell = para->member.para.pCell;
1516 editor->pCursors[1].pPara = para;
1517 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1518 editor->pCursors[1].nOffset = 0;
1519 nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1520 nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1521 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1522 if (parser.tableDef)
1523 parser.tableDef->tableRowStart = NULL;
1526 ME_CheckTablesForCorruption(editor);
1527 RTFDestroy(&parser);
1528 if (parser.lpRichEditOle)
1529 IRichEditOle_Release(parser.lpRichEditOle);
1531 if (parser.stackTop > 0)
1533 while (--parser.stackTop >= 0)
1535 ME_ReleaseStyle(parser.style);
1536 parser.style = parser.stack[parser.stackTop].style;
1538 if (!inStream.editstream->dwError)
1539 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1542 /* Remove last line break, as mandated by tests. This is not affected by
1543 CR/LF counters, since RTF streaming presents only \para tokens, which
1544 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1546 if (stripLastCR) {
1547 int newfrom, newto;
1548 ME_GetSelectionOfs(editor, &newfrom, &newto);
1549 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1550 WCHAR lastchar[3] = {'\0', '\0'};
1551 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1552 ME_Cursor linebreakCursor;
1554 ME_CursorFromCharOfs(editor, newto - linebreakSize, &linebreakCursor);
1555 ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1556 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1557 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1562 style = parser.style;
1564 else if (format & SF_TEXT)
1565 ME_StreamInText(editor, format, &inStream, style);
1566 else
1567 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1568 /* put the cursor at the top */
1569 if (!(format & SFF_SELECTION))
1570 ME_SetSelection(editor, 0, 0);
1573 /* Restore saved undo mode */
1574 editor->nUndoMode = nUndoMode;
1576 /* even if we didn't add an undo, we need to commit anything on the stack */
1577 ME_CommitUndo(editor);
1579 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1580 if (!(format & SFF_SELECTION))
1581 ME_EmptyUndoStack(editor);
1583 ME_ReleaseStyle(style);
1584 editor->nEventMask = nEventMask;
1585 ME_UpdateRepaint(editor);
1586 if (!(format & SFF_SELECTION)) {
1587 ME_ClearTempStyle(editor);
1589 ITextHost_TxShowCaret(editor->texthost, FALSE);
1590 ME_MoveCaret(editor);
1591 ITextHost_TxShowCaret(editor->texthost, TRUE);
1592 ME_SendSelChange(editor);
1593 ME_SendRequestResize(editor, FALSE);
1595 return 0;
1599 typedef struct tagME_RTFStringStreamStruct
1601 char *string;
1602 int pos;
1603 int length;
1604 } ME_RTFStringStreamStruct;
1606 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1608 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1609 int count;
1611 count = min(cb, pStruct->length - pStruct->pos);
1612 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1613 pStruct->pos += count;
1614 *pcb = count;
1615 return 0;
1618 static void
1619 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1621 EDITSTREAM es;
1622 ME_RTFStringStreamStruct data;
1624 data.string = string;
1625 data.length = strlen(string);
1626 data.pos = 0;
1627 es.dwCookie = (DWORD_PTR)&data;
1628 es.pfnCallback = ME_ReadFromRTFString;
1629 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1633 static int
1634 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1636 const int nLen = lstrlenW(text);
1637 const int nTextLen = ME_GetTextLength(editor);
1638 int nStart, nEnd;
1639 int nMin, nMax;
1640 ME_DisplayItem *item;
1641 ME_DisplayItem *para;
1642 WCHAR wLastChar = ' ';
1644 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1645 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1647 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1648 FIXME("Flags 0x%08x not implemented\n",
1649 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1651 nMin = chrg->cpMin;
1652 if (chrg->cpMax == -1)
1653 nMax = nTextLen;
1654 else
1655 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1657 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1658 if (editor->bEmulateVersion10 && nMax == nTextLen)
1660 flags |= FR_DOWN;
1663 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1664 if (editor->bEmulateVersion10 && nMax < nMin)
1666 if (chrgText)
1668 chrgText->cpMin = -1;
1669 chrgText->cpMax = -1;
1671 return -1;
1674 /* when searching up, if cpMin < cpMax, then instead of searching
1675 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1676 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1677 * case, it is always bigger than cpMin.
1679 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1681 int nSwap = nMax;
1683 nMax = nMin > nTextLen ? nTextLen : nMin;
1684 if (nMin < nSwap || chrg->cpMax == -1)
1685 nMin = 0;
1686 else
1687 nMin = nSwap;
1690 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1692 if (chrgText)
1693 chrgText->cpMin = chrgText->cpMax = -1;
1694 return -1;
1697 if (flags & FR_DOWN) /* Forward search */
1699 /* If possible, find the character before where the search starts */
1700 if ((flags & FR_WHOLEWORD) && nMin)
1702 ME_RunOfsFromCharOfs(editor, nMin - 1, NULL, &item, &nStart);
1703 wLastChar = item->member.run.strText->szData[nStart];
1706 ME_RunOfsFromCharOfs(editor, nMin, &para, &item, &nStart);
1708 while (item
1709 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1711 ME_DisplayItem *pCurItem = item;
1712 int nCurStart = nStart;
1713 int nMatched = 0;
1715 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1717 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1718 break;
1720 nMatched++;
1721 if (nMatched == nLen)
1723 ME_DisplayItem *pNextItem = pCurItem;
1724 int nNextStart = nCurStart;
1725 WCHAR wNextChar;
1727 /* Check to see if next character is a whitespace */
1728 if (flags & FR_WHOLEWORD)
1730 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1732 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1733 nNextStart = -nMatched;
1736 if (pNextItem)
1737 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1738 else
1739 wNextChar = ' ';
1741 if (isalnumW(wNextChar))
1742 break;
1745 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1746 if (chrgText)
1748 chrgText->cpMin = nStart;
1749 chrgText->cpMax = nStart + nLen;
1751 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1752 return nStart;
1754 if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1756 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1757 nCurStart = -nMatched;
1760 if (pCurItem)
1761 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1762 else
1763 wLastChar = ' ';
1765 nStart++;
1766 if (nStart == item->member.run.strText->nLen)
1768 ME_NextRun(&para, &item);
1769 nStart = 0;
1773 else /* Backward search */
1775 /* If possible, find the character after where the search ends */
1776 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1778 ME_RunOfsFromCharOfs(editor, nMax + 1, NULL, &item, &nEnd);
1779 wLastChar = item->member.run.strText->szData[nEnd];
1782 ME_RunOfsFromCharOfs(editor, nMax, &para, &item, &nEnd);
1784 while (item
1785 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1787 ME_DisplayItem *pCurItem = item;
1788 ME_DisplayItem *pCurPara = para;
1789 int nCurEnd = nEnd;
1790 int nMatched = 0;
1792 if (nCurEnd == 0)
1794 ME_PrevRun(&pCurPara, &pCurItem);
1795 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1798 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1800 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1801 break;
1803 nMatched++;
1804 if (nMatched == nLen)
1806 ME_DisplayItem *pPrevItem = pCurItem;
1807 int nPrevEnd = nCurEnd;
1808 WCHAR wPrevChar;
1810 /* Check to see if previous character is a whitespace */
1811 if (flags & FR_WHOLEWORD)
1813 if (nPrevEnd - nMatched == 0)
1815 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1816 if (pPrevItem)
1817 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1820 if (pPrevItem)
1821 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1822 else
1823 wPrevChar = ' ';
1825 if (isalnumW(wPrevChar))
1826 break;
1829 nStart = pCurPara->member.para.nCharOfs
1830 + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1831 if (chrgText)
1833 chrgText->cpMin = nStart;
1834 chrgText->cpMax = nStart + nLen;
1836 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1837 return nStart;
1839 if (nCurEnd - nMatched == 0)
1841 ME_PrevRun(&pCurPara, &pCurItem);
1842 /* Don't care about pCurItem becoming NULL here; it's already taken
1843 * care of in the exterior loop condition */
1844 nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1847 if (pCurItem)
1848 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1849 else
1850 wLastChar = ' ';
1852 nEnd--;
1853 if (nEnd < 0)
1855 ME_PrevRun(&para, &item);
1856 nEnd = item->member.run.strText->nLen;
1860 TRACE("not found\n");
1861 if (chrgText)
1862 chrgText->cpMin = chrgText->cpMax = -1;
1863 return -1;
1866 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1868 int nChars;
1869 ME_Cursor start;
1871 if (!ex->cb || !pText) return 0;
1873 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1874 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1876 if (ex->flags & GT_SELECTION)
1878 int from, to;
1879 int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1880 start = editor->pCursors[nStartCur];
1881 nChars = to - from;
1883 else
1885 ME_SetCursorToStart(editor, &start);
1886 nChars = INT_MAX;
1888 if (ex->codepage == 1200)
1890 return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1891 &start, nChars, ex->flags & GT_USECRLF);
1893 else
1895 /* potentially each char may be a CR, why calculate the exact value with O(N) when
1896 we can just take a bigger buffer? :)
1897 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1898 occurs only in richedit 2.0 mode, in which line breaks have only one CR
1900 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1901 DWORD buflen;
1902 LPWSTR buffer;
1903 LRESULT rc;
1905 buflen = min(crlfmul * nChars, ex->cb - 1);
1906 buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1908 nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1909 rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1910 (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1911 if (rc) rc--; /* do not count 0 terminator */
1913 heap_free(buffer);
1914 return rc;
1918 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1919 int nStart, int nLen, BOOL unicode)
1921 ME_Cursor start;
1922 if (!strText) return 0;
1923 ME_CursorFromCharOfs(editor, nStart, &start);
1924 if (unicode) {
1925 return ME_GetTextW(editor, strText, INT_MAX, &start, nLen, 0);
1926 } else {
1927 int nChars;
1928 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1929 if (!p) return 0;
1930 nChars = ME_GetTextW(editor, p, nLen, &start, nLen, 0);
1931 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1932 nLen+1, NULL, NULL);
1933 FREE_OBJ(p);
1934 return nChars;
1938 typedef struct tagME_GlobalDestStruct
1940 HGLOBAL hData;
1941 int nLength;
1942 } ME_GlobalDestStruct;
1944 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1946 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1947 int i;
1948 WORD *pSrc, *pDest;
1950 cb = cb >> 1;
1951 pDest = (WORD *)lpBuff;
1952 pSrc = GlobalLock(pData->hData);
1953 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1954 pDest[i] = pSrc[pData->nLength+i];
1956 pData->nLength += i;
1957 *pcb = 2*i;
1958 GlobalUnlock(pData->hData);
1959 return 0;
1962 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1964 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1965 int i;
1966 BYTE *pSrc, *pDest;
1968 pDest = lpBuff;
1969 pSrc = GlobalLock(pData->hData);
1970 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1971 pDest[i] = pSrc[pData->nLength+i];
1973 pData->nLength += i;
1974 *pcb = i;
1975 GlobalUnlock(pData->hData);
1976 return 0;
1979 static BOOL ME_Paste(ME_TextEditor *editor)
1981 DWORD dwFormat = 0;
1982 EDITSTREAM es;
1983 ME_GlobalDestStruct gds;
1984 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1985 UINT cf = 0;
1987 if (IsClipboardFormatAvailable(nRTFFormat))
1988 cf = nRTFFormat, dwFormat = SF_RTF;
1989 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1990 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1991 else
1992 return FALSE;
1994 if (!OpenClipboard(editor->hWnd))
1995 return FALSE;
1996 gds.hData = GetClipboardData(cf);
1997 gds.nLength = 0;
1998 es.dwCookie = (DWORD_PTR)&gds;
1999 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2000 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2002 CloseClipboard();
2003 return TRUE;
2006 static BOOL ME_Copy(ME_TextEditor *editor, CHARRANGE *range)
2008 LPDATAOBJECT dataObj = NULL;
2009 HRESULT hr = S_OK;
2011 if (editor->cPasswordMask)
2012 return FALSE; /* Copying or Cutting masked text isn't allowed */
2014 if(editor->lpOleCallback)
2015 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, range, RECO_COPY, &dataObj);
2016 if(FAILED(hr) || !dataObj)
2017 hr = ME_GetDataObject(editor, range, &dataObj);
2018 if(SUCCEEDED(hr)) {
2019 hr = OleSetClipboard(dataObj);
2020 IDataObject_Release(dataObj);
2022 return SUCCEEDED(hr) != 0;
2025 /* helper to send a msg filter notification */
2026 static BOOL
2027 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2029 MSGFILTER msgf;
2031 if (!editor->hWnd) return FALSE;
2032 msgf.nmhdr.hwndFrom = editor->hWnd;
2033 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2034 msgf.nmhdr.code = EN_MSGFILTER;
2035 msgf.msg = msg;
2036 msgf.wParam = *wParam;
2037 msgf.lParam = *lParam;
2038 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2039 return FALSE;
2040 *wParam = msgf.wParam;
2041 *lParam = msgf.lParam;
2042 msgf.wParam = *wParam;
2044 return TRUE;
2047 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2049 ME_DisplayItem *startPara, *endPara;
2050 ME_DisplayItem *prev_para;
2051 ME_Cursor *from, *to;
2053 if (!editor->AutoURLDetect_bEnable) return;
2055 ME_GetSelection(editor, &from, &to);
2057 /* Find paragraph previous to the one that contains start cursor */
2058 startPara = from->pPara;
2059 prev_para = startPara->member.para.prev_para;
2060 if (prev_para->type == diParagraph) startPara = prev_para;
2062 /* Find paragraph that contains end cursor */
2063 endPara = to->pPara->member.para.next_para;
2065 ME_UpdateLinkAttribute(editor,
2066 startPara->member.para.nCharOfs,
2067 endPara->member.para.nCharOfs);
2070 static BOOL
2071 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2073 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2074 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2076 if (editor->bMouseCaptured)
2077 return FALSE;
2078 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2079 editor->nSelectionType = stPosition;
2081 switch (nKey)
2083 case VK_LEFT:
2084 case VK_RIGHT:
2085 case VK_HOME:
2086 case VK_END:
2087 editor->nUDArrowX = -1;
2088 /* fall through */
2089 case VK_UP:
2090 case VK_DOWN:
2091 case VK_PRIOR:
2092 case VK_NEXT:
2093 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2094 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2095 return TRUE;
2096 case VK_BACK:
2097 case VK_DELETE:
2098 editor->nUDArrowX = -1;
2099 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2100 if (editor->styleFlags & ES_READONLY)
2101 return FALSE;
2102 if (ME_IsSelection(editor))
2104 ME_DeleteSelection(editor);
2105 ME_CommitUndo(editor);
2107 else if (nKey == VK_DELETE)
2109 /* Delete stops group typing.
2110 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2111 ME_DeleteTextAtCursor(editor, 1, 1);
2112 ME_CommitUndo(editor);
2114 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2116 BOOL bDeletionSucceeded;
2117 /* Backspace can be grouped for a single undo */
2118 ME_ContinueCoalescingTransaction(editor);
2119 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2120 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2121 /* Deletion was prevented so the cursor is moved back to where it was.
2122 * (e.g. this happens when trying to delete cell boundaries)
2124 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2126 ME_CommitCoalescingUndo(editor);
2128 else
2129 return TRUE;
2130 ME_MoveCursorFromTableRowStartParagraph(editor);
2131 ME_UpdateSelectionLinkAttribute(editor);
2132 ME_UpdateRepaint(editor);
2133 ME_SendRequestResize(editor, FALSE);
2134 return TRUE;
2135 case VK_RETURN:
2136 if (editor->styleFlags & ES_MULTILINE)
2138 ME_Cursor cursor = editor->pCursors[0];
2139 ME_DisplayItem *para = cursor.pPara;
2140 int from, to;
2141 const WCHAR endl = '\r';
2142 ME_Style *style;
2144 if (editor->styleFlags & ES_READONLY) {
2145 MessageBeep(MB_ICONERROR);
2146 return TRUE;
2149 ME_GetSelectionOfs(editor, &from, &to);
2150 if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2152 if (!editor->bEmulateVersion10) { /* v4.1 */
2153 if (para->member.para.nFlags & MEPF_ROWEND) {
2154 /* Add a new table row after this row. */
2155 para = ME_AppendTableRow(editor, para);
2156 para = para->member.para.next_para;
2157 editor->pCursors[0].pPara = para;
2158 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2159 editor->pCursors[0].nOffset = 0;
2160 editor->pCursors[1] = editor->pCursors[0];
2161 ME_CommitUndo(editor);
2162 ME_CheckTablesForCorruption(editor);
2163 ME_UpdateRepaint(editor);
2164 return TRUE;
2166 else if (para == editor->pCursors[1].pPara &&
2167 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2168 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2169 !para->member.para.prev_para->member.para.nCharOfs)
2171 /* Insert a newline before the table. */
2172 para = para->member.para.prev_para;
2173 para->member.para.nFlags &= ~MEPF_ROWSTART;
2174 editor->pCursors[0].pPara = para;
2175 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2176 editor->pCursors[1] = editor->pCursors[0];
2177 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2178 editor->pCursors[0].pRun->member.run.style);
2179 para = editor->pBuffer->pFirst->member.para.next_para;
2180 ME_SetDefaultParaFormat(para->member.para.pFmt);
2181 para->member.para.nFlags = MEPF_REWRAP;
2182 editor->pCursors[0].pPara = para;
2183 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2184 editor->pCursors[1] = editor->pCursors[0];
2185 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2186 ME_CommitCoalescingUndo(editor);
2187 ME_CheckTablesForCorruption(editor);
2188 ME_UpdateRepaint(editor);
2189 return TRUE;
2191 } else { /* v1.0 - 3.0 */
2192 ME_DisplayItem *para = cursor.pPara;
2193 if (ME_IsInTable(para))
2195 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2197 if (from == to) {
2198 ME_ContinueCoalescingTransaction(editor);
2199 para = ME_AppendTableRow(editor, para);
2200 editor->pCursors[0].pPara = para;
2201 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2202 editor->pCursors[0].nOffset = 0;
2203 editor->pCursors[1] = editor->pCursors[0];
2204 ME_CommitCoalescingUndo(editor);
2205 ME_UpdateRepaint(editor);
2206 return TRUE;
2208 } else {
2209 ME_ContinueCoalescingTransaction(editor);
2210 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2211 !ME_IsInTable(para->member.para.prev_para))
2213 /* Insert newline before table */
2214 cursor.pRun = ME_FindItemBack(para, diRun);
2215 if (cursor.pRun) {
2216 editor->pCursors[0].pRun = cursor.pRun;
2217 editor->pCursors[0].pPara = para->member.para.prev_para;
2219 editor->pCursors[0].nOffset = 0;
2220 editor->pCursors[1] = editor->pCursors[0];
2221 ME_InsertTextFromCursor(editor, 0, &endl, 1,
2222 editor->pCursors[0].pRun->member.run.style);
2223 } else {
2224 editor->pCursors[1] = editor->pCursors[0];
2225 para = ME_AppendTableRow(editor, para);
2226 editor->pCursors[0].pPara = para;
2227 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2228 editor->pCursors[0].nOffset = 0;
2229 editor->pCursors[1] = editor->pCursors[0];
2231 ME_CommitCoalescingUndo(editor);
2232 ME_UpdateRepaint(editor);
2233 return TRUE;
2238 style = ME_GetInsertStyle(editor, 0);
2239 ME_SaveTempStyle(editor);
2240 ME_ContinueCoalescingTransaction(editor);
2241 if (shift_is_down)
2242 ME_InsertEndRowFromCursor(editor, 0);
2243 else
2244 ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2245 ME_ReleaseStyle(style);
2246 ME_CommitCoalescingUndo(editor);
2247 SetCursor(NULL);
2249 ME_UpdateSelectionLinkAttribute(editor);
2250 ME_UpdateRepaint(editor);
2252 return TRUE;
2254 break;
2255 case 'A':
2256 if (ctrl_is_down)
2258 ME_SetSelection(editor, 0, -1);
2259 return TRUE;
2261 break;
2262 case 'V':
2263 if (ctrl_is_down)
2264 return ME_Paste(editor);
2265 break;
2266 case 'C':
2267 case 'X':
2268 if (ctrl_is_down)
2270 CHARRANGE range;
2271 BOOL result;
2273 ME_GetSelectionOfs(editor, &range.cpMin, &range.cpMax);
2274 result = ME_Copy(editor, &range);
2275 if (result && nKey == 'X')
2277 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
2278 ME_CommitUndo(editor);
2279 ME_UpdateRepaint(editor);
2281 return result;
2283 break;
2284 case 'Z':
2285 if (ctrl_is_down)
2287 ME_Undo(editor);
2288 return TRUE;
2290 break;
2291 case 'Y':
2292 if (ctrl_is_down)
2294 ME_Redo(editor);
2295 return TRUE;
2297 break;
2299 default:
2300 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2301 editor->nUDArrowX = -1;
2302 if (ctrl_is_down)
2304 if (nKey == 'W')
2306 CHARFORMAT2W chf;
2307 char buf[2048];
2308 chf.cbSize = sizeof(chf);
2310 ME_GetSelectionCharFormat(editor, &chf);
2311 ME_DumpStyleToBuf(&chf, buf);
2312 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2314 if (nKey == 'Q')
2316 ME_CheckCharOffsets(editor);
2320 return FALSE;
2323 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2324 LPARAM flags, BOOL unicode)
2326 WCHAR wstr;
2328 if (editor->bMouseCaptured)
2329 return 0;
2331 if (unicode)
2332 wstr = (WCHAR)charCode;
2333 else
2335 CHAR charA = charCode;
2336 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2339 if (editor->styleFlags & ES_READONLY) {
2340 MessageBeep(MB_ICONERROR);
2341 return 0; /* FIXME really 0 ? */
2344 if ((unsigned)wstr >= ' ' || wstr == '\t')
2346 ME_Cursor cursor = editor->pCursors[0];
2347 ME_DisplayItem *para = cursor.pPara;
2348 int from, to;
2349 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2350 ME_GetSelectionOfs(editor, &from, &to);
2351 if (wstr == '\t' &&
2352 /* v4.1 allows tabs to be inserted with ctrl key down */
2353 !(ctrl_is_down && !editor->bEmulateVersion10))
2355 ME_DisplayItem *para;
2356 BOOL bSelectedRow = FALSE;
2358 para = cursor.pPara;
2359 if (ME_IsSelection(editor) &&
2360 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2361 to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2362 para->member.para.prev_para->type == diParagraph)
2364 para = para->member.para.prev_para;
2365 bSelectedRow = TRUE;
2367 if (ME_IsInTable(para))
2369 ME_TabPressedInTable(editor, bSelectedRow);
2370 ME_CommitUndo(editor);
2371 return 0;
2373 } else if (!editor->bEmulateVersion10) { /* v4.1 */
2374 if (para->member.para.nFlags & MEPF_ROWEND) {
2375 if (from == to) {
2376 para = para->member.para.next_para;
2377 if (para->member.para.nFlags & MEPF_ROWSTART)
2378 para = para->member.para.next_para;
2379 editor->pCursors[0].pPara = para;
2380 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2381 editor->pCursors[0].nOffset = 0;
2382 editor->pCursors[1] = editor->pCursors[0];
2385 } else { /* v1.0 - 3.0 */
2386 if (ME_IsInTable(cursor.pRun) &&
2387 cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2388 from == to)
2390 /* Text should not be inserted at the end of the table. */
2391 MessageBeep(-1);
2392 return 0;
2395 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2396 /* WM_CHAR is restricted to nTextLimit */
2397 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2399 ME_Style *style = ME_GetInsertStyle(editor, 0);
2400 ME_SaveTempStyle(editor);
2401 ME_ContinueCoalescingTransaction(editor);
2402 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2403 ME_ReleaseStyle(style);
2404 ME_CommitCoalescingUndo(editor);
2405 ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2408 ME_UpdateSelectionLinkAttribute(editor);
2409 ME_UpdateRepaint(editor);
2411 return 0;
2414 /* Process the message and calculate the new click count.
2416 * returns: The click count if it is mouse down event, else returns 0. */
2417 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2418 LPARAM lParam)
2420 static int clickNum = 0;
2421 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2422 return 0;
2424 if ((msg == WM_LBUTTONDBLCLK) ||
2425 (msg == WM_RBUTTONDBLCLK) ||
2426 (msg == WM_MBUTTONDBLCLK) ||
2427 (msg == WM_XBUTTONDBLCLK))
2429 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2432 if ((msg == WM_LBUTTONDOWN) ||
2433 (msg == WM_RBUTTONDOWN) ||
2434 (msg == WM_MBUTTONDOWN) ||
2435 (msg == WM_XBUTTONDOWN))
2437 static MSG prevClickMsg;
2438 MSG clickMsg;
2439 /* Compare the editor instead of the hwnd so that the this
2440 * can still be done for windowless richedit controls. */
2441 clickMsg.hwnd = (HWND)editor;
2442 clickMsg.message = msg;
2443 clickMsg.wParam = wParam;
2444 clickMsg.lParam = lParam;
2445 clickMsg.time = GetMessageTime();
2446 clickMsg.pt.x = (short)LOWORD(lParam);
2447 clickMsg.pt.y = (short)HIWORD(lParam);
2448 if ((clickNum != 0) &&
2449 (clickMsg.message == prevClickMsg.message) &&
2450 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2451 (clickMsg.wParam == prevClickMsg.wParam) &&
2452 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2453 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2454 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2456 clickNum++;
2457 } else {
2458 clickNum = 1;
2460 prevClickMsg = clickMsg;
2461 } else {
2462 return 0;
2464 return clickNum;
2467 static BOOL ME_SetCursor(ME_TextEditor *editor)
2469 POINT pt;
2470 BOOL isExact;
2471 int offset;
2472 SCROLLBARINFO sbi;
2473 DWORD messagePos = GetMessagePos();
2474 pt.x = (short)LOWORD(messagePos);
2475 pt.y = (short)HIWORD(messagePos);
2477 if (editor->hWnd)
2479 sbi.cbSize = sizeof(sbi);
2480 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2481 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2482 PtInRect(&sbi.rcScrollBar, pt))
2484 ITextHost_TxSetCursor(editor->texthost,
2485 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2486 return TRUE;
2488 sbi.cbSize = sizeof(sbi);
2489 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2490 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2491 PtInRect(&sbi.rcScrollBar, pt))
2493 ITextHost_TxSetCursor(editor->texthost,
2494 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2495 return TRUE;
2498 ITextHost_TxScreenToClient(editor->texthost, &pt);
2500 if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2501 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2502 return TRUE;
2504 if (!editor->bEmulateVersion10 /* v4.1 */ &&
2505 pt.y < editor->rcFormat.top &&
2506 pt.x < editor->rcFormat.left)
2508 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2509 return TRUE;
2511 if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2513 if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2514 ITextHost_TxSetCursor(editor->texthost,
2515 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2516 else /* v4.1 */
2517 ITextHost_TxSetCursor(editor->texthost,
2518 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2519 return TRUE;
2521 if (pt.x < editor->rcFormat.left)
2523 ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2524 return TRUE;
2526 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2527 if (isExact)
2529 ME_Cursor cursor;
2530 ME_Run *run;
2532 ME_CursorFromCharOfs(editor, offset, &cursor);
2533 run = &cursor.pRun->member.run;
2534 if (run->style->fmt.dwMask & CFM_LINK &&
2535 run->style->fmt.dwEffects & CFE_LINK)
2537 ITextHost_TxSetCursor(editor->texthost,
2538 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2539 FALSE);
2540 return TRUE;
2543 if (ME_IsSelection(editor))
2545 int selStart, selEnd;
2547 ME_GetSelectionOfs(editor, &selStart, &selEnd);
2548 if (selStart <= offset && selEnd >= offset) {
2549 ITextHost_TxSetCursor(editor->texthost,
2550 LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2551 FALSE);
2552 return TRUE;
2556 ITextHost_TxSetCursor(editor->texthost,
2557 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2558 return TRUE;
2561 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2563 ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2564 editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2565 editor->rcFormat.left += 1 + editor->selofs;
2566 editor->rcFormat.right -= 1;
2569 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2571 CHARRANGE selrange;
2572 HMENU menu;
2573 int seltype = 0;
2574 if(!editor->lpOleCallback || !editor->hWnd)
2575 return FALSE;
2576 ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2577 if(selrange.cpMin == selrange.cpMax)
2578 seltype |= SEL_EMPTY;
2579 else
2581 /* FIXME: Handle objects */
2582 seltype |= SEL_TEXT;
2583 if(selrange.cpMax-selrange.cpMin > 1)
2584 seltype |= SEL_MULTICHAR;
2586 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2588 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2589 DestroyMenu(menu);
2591 return TRUE;
2594 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2596 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2597 int i;
2598 DWORD props;
2599 LONG selbarwidth;
2601 ed->hWnd = NULL;
2602 ed->texthost = texthost;
2603 ed->bEmulateVersion10 = bEmulateVersion10;
2604 ITextHost_TxGetPropertyBits(texthost,
2605 (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2606 TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2607 TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2608 TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2609 TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2610 &props);
2611 ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2612 ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2613 ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2614 ed->pBuffer = ME_MakeText();
2615 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2616 ed->nAvailWidth = 0; /* wrap to client area */
2617 ME_MakeFirstParagraph(ed);
2618 /* The four cursors are for:
2619 * 0 - The position where the caret is shown
2620 * 1 - The anchored end of the selection (for normal selection)
2621 * 2 & 3 - The anchored start and end respectively for word, line,
2622 * or paragraph selection.
2624 ed->nCursors = 4;
2625 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2626 ME_SetCursorToStart(ed, &ed->pCursors[0]);
2627 ed->pCursors[1] = ed->pCursors[0];
2628 ed->pCursors[2] = ed->pCursors[0];
2629 ed->pCursors[3] = ed->pCursors[1];
2630 ed->nLastTotalLength = ed->nTotalLength = 0;
2631 ed->nLastTotalWidth = ed->nTotalWidth = 0;
2632 ed->nUDArrowX = -1;
2633 ed->nSequence = 0;
2634 ed->rgbBackColor = -1;
2635 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2636 ed->bCaretAtEnd = FALSE;
2637 ed->nEventMask = 0;
2638 ed->nModifyStep = 0;
2639 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2640 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2641 ed->nUndoStackSize = 0;
2642 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2643 ed->nUndoMode = umAddToUndo;
2644 ed->nParagraphs = 1;
2645 ed->nLastSelStart = ed->nLastSelEnd = 0;
2646 ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2647 ed->bHideSelection = FALSE;
2648 ed->pfnWordBreak = NULL;
2649 ed->lpOleCallback = NULL;
2650 ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2651 ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2652 ed->AutoURLDetect_bEnable = FALSE;
2653 ed->bHaveFocus = FALSE;
2654 ed->bMouseCaptured = FALSE;
2655 for (i=0; i<HFONT_CACHE_SIZE; i++)
2657 ed->pFontCache[i].nRefs = 0;
2658 ed->pFontCache[i].nAge = 0;
2659 ed->pFontCache[i].hFont = NULL;
2662 ME_CheckCharOffsets(ed);
2663 ed->bDefaultFormatRect = TRUE;
2664 ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2665 if (selbarwidth) {
2666 /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2667 ed->selofs = SELECTIONBAR_WIDTH;
2668 ed->styleFlags |= ES_SELECTIONBAR;
2669 } else {
2670 ed->selofs = 0;
2672 ed->nSelectionType = stPosition;
2674 ed->cPasswordMask = 0;
2675 if (props & TXTBIT_USEPASSWORD)
2676 ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2678 if (props & TXTBIT_AUTOWORDSEL)
2679 ed->styleFlags |= ECO_AUTOWORDSELECTION;
2680 if (props & TXTBIT_MULTILINE) {
2681 ed->styleFlags |= ES_MULTILINE;
2682 ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2683 } else {
2684 ed->bWordWrap = FALSE;
2686 if (props & TXTBIT_READONLY)
2687 ed->styleFlags |= ES_READONLY;
2688 if (!(props & TXTBIT_HIDESELECTION))
2689 ed->styleFlags |= ES_NOHIDESEL;
2690 if (props & TXTBIT_SAVESELECTION)
2691 ed->styleFlags |= ES_SAVESEL;
2692 if (props & TXTBIT_VERTICAL)
2693 ed->styleFlags |= ES_VERTICAL;
2694 if (props & TXTBIT_DISABLEDRAG)
2695 ed->styleFlags |= ES_NOOLEDRAGDROP;
2697 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2699 /* Default scrollbar information */
2700 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2701 ed->vert_si.nMin = 0;
2702 ed->vert_si.nMax = 0;
2703 ed->vert_si.nPage = 0;
2704 ed->vert_si.nPos = 0;
2706 ed->horz_si.cbSize = sizeof(SCROLLINFO);
2707 ed->horz_si.nMin = 0;
2708 ed->horz_si.nMax = 0;
2709 ed->horz_si.nPage = 0;
2710 ed->horz_si.nPos = 0;
2712 OleInitialize(NULL);
2714 return ed;
2717 static void ME_DestroyEditor(ME_TextEditor *editor)
2719 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2720 ME_DisplayItem *p = pFirst, *pNext = NULL;
2721 int i;
2723 ME_ClearTempStyle(editor);
2724 ME_EmptyUndoStack(editor);
2725 while(p) {
2726 pNext = p->next;
2727 ME_DestroyDisplayItem(p);
2728 p = pNext;
2730 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2731 for (i=0; i<HFONT_CACHE_SIZE; i++)
2733 if (editor->pFontCache[i].hFont)
2734 DeleteObject(editor->pFontCache[i].hFont);
2736 if (editor->rgbBackColor != -1)
2737 DeleteObject(editor->hbrBackground);
2738 if(editor->lpOleCallback)
2739 IUnknown_Release(editor->lpOleCallback);
2740 IUnknown_Release(editor->texthost);
2741 OleUninitialize();
2743 FREE_OBJ(editor->pBuffer);
2744 FREE_OBJ(editor->pCursors);
2746 FREE_OBJ(editor);
2749 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2751 TRACE("\n");
2752 switch (fdwReason)
2754 case DLL_PROCESS_ATTACH:
2755 DisableThreadLibraryCalls(hinstDLL);
2756 me_heap = HeapCreate (0, 0x10000, 0);
2757 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2758 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2759 LookupInit();
2760 break;
2762 case DLL_PROCESS_DETACH:
2763 UnregisterClassW(RICHEDIT_CLASS20W, 0);
2764 UnregisterClassW(MSFTEDIT_CLASS, 0);
2765 UnregisterClassA(RICHEDIT_CLASS20A, 0);
2766 UnregisterClassA("RichEdit50A", 0);
2767 if (ME_ListBoxRegistered)
2768 UnregisterClassW(REListBox20W, 0);
2769 if (ME_ComboBoxRegistered)
2770 UnregisterClassW(REComboBox20W, 0);
2771 LookupCleanup();
2772 HeapDestroy (me_heap);
2773 me_heap = NULL;
2774 break;
2776 return TRUE;
2780 static const char * const edit_messages[] = {
2781 "EM_GETSEL",
2782 "EM_SETSEL",
2783 "EM_GETRECT",
2784 "EM_SETRECT",
2785 "EM_SETRECTNP",
2786 "EM_SCROLL",
2787 "EM_LINESCROLL",
2788 "EM_SCROLLCARET",
2789 "EM_GETMODIFY",
2790 "EM_SETMODIFY",
2791 "EM_GETLINECOUNT",
2792 "EM_LINEINDEX",
2793 "EM_SETHANDLE",
2794 "EM_GETHANDLE",
2795 "EM_GETTHUMB",
2796 "EM_UNKNOWN_BF",
2797 "EM_UNKNOWN_C0",
2798 "EM_LINELENGTH",
2799 "EM_REPLACESEL",
2800 "EM_UNKNOWN_C3",
2801 "EM_GETLINE",
2802 "EM_LIMITTEXT",
2803 "EM_CANUNDO",
2804 "EM_UNDO",
2805 "EM_FMTLINES",
2806 "EM_LINEFROMCHAR",
2807 "EM_UNKNOWN_CA",
2808 "EM_SETTABSTOPS",
2809 "EM_SETPASSWORDCHAR",
2810 "EM_EMPTYUNDOBUFFER",
2811 "EM_GETFIRSTVISIBLELINE",
2812 "EM_SETREADONLY",
2813 "EM_SETWORDBREAKPROC",
2814 "EM_GETWORDBREAKPROC",
2815 "EM_GETPASSWORDCHAR",
2816 "EM_SETMARGINS",
2817 "EM_GETMARGINS",
2818 "EM_GETLIMITTEXT",
2819 "EM_POSFROMCHAR",
2820 "EM_CHARFROMPOS",
2821 "EM_SETIMESTATUS",
2822 "EM_GETIMESTATUS"
2825 static const char * const richedit_messages[] = {
2826 "EM_CANPASTE",
2827 "EM_DISPLAYBAND",
2828 "EM_EXGETSEL",
2829 "EM_EXLIMITTEXT",
2830 "EM_EXLINEFROMCHAR",
2831 "EM_EXSETSEL",
2832 "EM_FINDTEXT",
2833 "EM_FORMATRANGE",
2834 "EM_GETCHARFORMAT",
2835 "EM_GETEVENTMASK",
2836 "EM_GETOLEINTERFACE",
2837 "EM_GETPARAFORMAT",
2838 "EM_GETSELTEXT",
2839 "EM_HIDESELECTION",
2840 "EM_PASTESPECIAL",
2841 "EM_REQUESTRESIZE",
2842 "EM_SELECTIONTYPE",
2843 "EM_SETBKGNDCOLOR",
2844 "EM_SETCHARFORMAT",
2845 "EM_SETEVENTMASK",
2846 "EM_SETOLECALLBACK",
2847 "EM_SETPARAFORMAT",
2848 "EM_SETTARGETDEVICE",
2849 "EM_STREAMIN",
2850 "EM_STREAMOUT",
2851 "EM_GETTEXTRANGE",
2852 "EM_FINDWORDBREAK",
2853 "EM_SETOPTIONS",
2854 "EM_GETOPTIONS",
2855 "EM_FINDTEXTEX",
2856 "EM_GETWORDBREAKPROCEX",
2857 "EM_SETWORDBREAKPROCEX",
2858 "EM_SETUNDOLIMIT",
2859 "EM_UNKNOWN_USER_83",
2860 "EM_REDO",
2861 "EM_CANREDO",
2862 "EM_GETUNDONAME",
2863 "EM_GETREDONAME",
2864 "EM_STOPGROUPTYPING",
2865 "EM_SETTEXTMODE",
2866 "EM_GETTEXTMODE",
2867 "EM_AUTOURLDETECT",
2868 "EM_GETAUTOURLDETECT",
2869 "EM_SETPALETTE",
2870 "EM_GETTEXTEX",
2871 "EM_GETTEXTLENGTHEX",
2872 "EM_SHOWSCROLLBAR",
2873 "EM_SETTEXTEX",
2874 "EM_UNKNOWN_USER_98",
2875 "EM_UNKNOWN_USER_99",
2876 "EM_SETPUNCTUATION",
2877 "EM_GETPUNCTUATION",
2878 "EM_SETWORDWRAPMODE",
2879 "EM_GETWORDWRAPMODE",
2880 "EM_SETIMECOLOR",
2881 "EM_GETIMECOLOR",
2882 "EM_SETIMEOPTIONS",
2883 "EM_GETIMEOPTIONS",
2884 "EM_CONVPOSITION",
2885 "EM_UNKNOWN_USER_109",
2886 "EM_UNKNOWN_USER_110",
2887 "EM_UNKNOWN_USER_111",
2888 "EM_UNKNOWN_USER_112",
2889 "EM_UNKNOWN_USER_113",
2890 "EM_UNKNOWN_USER_114",
2891 "EM_UNKNOWN_USER_115",
2892 "EM_UNKNOWN_USER_116",
2893 "EM_UNKNOWN_USER_117",
2894 "EM_UNKNOWN_USER_118",
2895 "EM_UNKNOWN_USER_119",
2896 "EM_SETLANGOPTIONS",
2897 "EM_GETLANGOPTIONS",
2898 "EM_GETIMECOMPMODE",
2899 "EM_FINDTEXTW",
2900 "EM_FINDTEXTEXW",
2901 "EM_RECONVERSION",
2902 "EM_SETIMEMODEBIAS",
2903 "EM_GETIMEMODEBIAS"
2906 static const char *
2907 get_msg_name(UINT msg)
2909 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2910 return edit_messages[msg - EM_GETSEL];
2911 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2912 return richedit_messages[msg - EM_CANPASTE];
2913 return "";
2916 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2918 int x,y;
2919 ME_DisplayItem *para, *run;
2920 BOOL isExact;
2921 int nCharOfs; /* The start of the clicked text. Absolute character offset */
2923 ENLINK info;
2924 x = (short)LOWORD(lParam);
2925 y = (short)HIWORD(lParam);
2926 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
2927 if (!isExact) return;
2929 ME_RunOfsFromCharOfs(editor, nCharOfs, &para, &run, NULL);
2931 if ((run->member.run.style->fmt.dwMask & CFM_LINK)
2932 && (run->member.run.style->fmt.dwEffects & CFE_LINK))
2933 { /* The clicked run has CFE_LINK set */
2934 info.nmhdr.hwndFrom = editor->hWnd;
2935 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2936 info.nmhdr.code = EN_LINK;
2937 info.msg = msg;
2938 info.wParam = wParam;
2939 info.lParam = lParam;
2940 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor, para, run, 0);
2941 info.chrg.cpMax = info.chrg.cpMin + run->member.run.strText->nLen;
2942 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2946 #define UNSUPPORTED_MSG(e) \
2947 case e: \
2948 FIXME(#e ": stub\n"); \
2949 *phresult = S_FALSE; \
2950 return 0;
2952 /* Handle messages for windowless and windoweded richedit controls.
2954 * The LRESULT that is returned is a return value for window procs,
2955 * and the phresult parameter is the COM return code needed by the
2956 * text services interface. */
2957 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2958 LPARAM lParam, BOOL unicode, HRESULT* phresult)
2960 *phresult = S_OK;
2962 switch(msg) {
2964 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2965 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2966 UNSUPPORTED_MSG(EM_FMTLINES)
2967 UNSUPPORTED_MSG(EM_FORMATRANGE)
2968 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2969 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2970 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2971 UNSUPPORTED_MSG(EM_GETIMESTATUS)
2972 UNSUPPORTED_MSG(EM_SETIMESTATUS)
2973 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2974 UNSUPPORTED_MSG(EM_GETREDONAME)
2975 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2976 UNSUPPORTED_MSG(EM_GETUNDONAME)
2977 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2978 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2979 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2980 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2981 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2982 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2983 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2984 UNSUPPORTED_MSG(EM_SETMARGINS)
2985 UNSUPPORTED_MSG(EM_SETPALETTE)
2986 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2987 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2988 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2989 UNSUPPORTED_MSG(WM_STYLECHANGING)
2990 UNSUPPORTED_MSG(WM_STYLECHANGED)
2992 /* Messages specific to Richedit controls */
2994 case EM_STREAMIN:
2995 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2996 case EM_STREAMOUT:
2997 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2998 case WM_GETDLGCODE:
3000 UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3001 if (editor->styleFlags & ES_MULTILINE)
3002 code |= DLGC_WANTMESSAGE;
3003 return code;
3005 case EM_EMPTYUNDOBUFFER:
3006 ME_EmptyUndoStack(editor);
3007 return 0;
3008 case EM_GETSEL:
3010 /* Note: wParam/lParam can be NULL */
3011 UINT from, to;
3012 PUINT pfrom = wParam ? (PUINT)wParam : &from;
3013 PUINT pto = lParam ? (PUINT)lParam : &to;
3014 ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3015 if ((*pfrom|*pto) & 0xFFFF0000)
3016 return -1;
3017 return MAKELONG(*pfrom,*pto);
3019 case EM_EXGETSEL:
3021 CHARRANGE *pRange = (CHARRANGE *)lParam;
3022 ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3023 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3024 return 0;
3026 case EM_SETUNDOLIMIT:
3028 if ((int)wParam < 0)
3029 editor->nUndoLimit = STACK_SIZE_DEFAULT;
3030 else
3031 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3032 /* Setting a max stack size keeps wine from getting killed
3033 for hogging memory. Windows allocates all this memory at once, so
3034 no program would realistically set a value above our maximum. */
3035 return editor->nUndoLimit;
3037 case EM_CANUNDO:
3038 return editor->pUndoStack != NULL;
3039 case EM_CANREDO:
3040 return editor->pRedoStack != NULL;
3041 case WM_UNDO: /* FIXME: actually not the same */
3042 case EM_UNDO:
3043 return ME_Undo(editor);
3044 case EM_REDO:
3045 return ME_Redo(editor);
3046 case EM_GETOPTIONS:
3048 /* these flags are equivalent to the ES_* counterparts */
3049 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3050 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3051 DWORD settings = editor->styleFlags & mask;
3053 return settings;
3055 case EM_SETOPTIONS:
3057 /* these flags are equivalent to ES_* counterparts, except for
3058 * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3059 * but is still stored in editor->styleFlags. */
3060 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3061 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3062 ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3063 DWORD settings = mask & editor->styleFlags;
3064 DWORD oldSettings = settings;
3065 DWORD changedSettings;
3067 switch(wParam)
3069 case ECOOP_SET:
3070 settings = lParam;
3071 break;
3072 case ECOOP_OR:
3073 settings |= lParam;
3074 break;
3075 case ECOOP_AND:
3076 settings &= lParam;
3077 break;
3078 case ECOOP_XOR:
3079 settings ^= lParam;
3081 changedSettings = oldSettings ^ settings;
3083 if (changedSettings) {
3084 editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3086 if (changedSettings & ECO_SELECTIONBAR)
3088 ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3089 if (settings & ECO_SELECTIONBAR) {
3090 assert(!editor->selofs);
3091 editor->selofs = SELECTIONBAR_WIDTH;
3092 editor->rcFormat.left += editor->selofs;
3093 } else {
3094 editor->rcFormat.left -= editor->selofs;
3095 editor->selofs = 0;
3097 ME_RewrapRepaint(editor);
3100 if (changedSettings & settings & ECO_VERTICAL)
3101 FIXME("ECO_VERTICAL not implemented yet!\n");
3102 if (changedSettings & settings & ECO_AUTOHSCROLL)
3103 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3104 if (changedSettings & settings & ECO_AUTOVSCROLL)
3105 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3106 if (changedSettings & settings & ECO_NOHIDESEL)
3107 FIXME("ECO_NOHIDESEL not implemented yet!\n");
3108 if (changedSettings & settings & ECO_WANTRETURN)
3109 FIXME("ECO_WANTRETURN not implemented yet!\n");
3110 if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3111 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3114 return settings;
3116 case EM_SETSEL:
3118 ME_InvalidateSelection(editor);
3119 ME_SetSelection(editor, wParam, lParam);
3120 ME_InvalidateSelection(editor);
3121 ITextHost_TxShowCaret(editor->texthost, FALSE);
3122 ME_ShowCaret(editor);
3123 ME_SendSelChange(editor);
3124 return 0;
3126 case EM_SETSCROLLPOS:
3128 POINT *point = (POINT *)lParam;
3129 ME_ScrollAbs(editor, point->x, point->y);
3130 return 0;
3132 case EM_AUTOURLDETECT:
3134 if (wParam==1 || wParam ==0)
3136 editor->AutoURLDetect_bEnable = (BOOL)wParam;
3137 return 0;
3139 return E_INVALIDARG;
3141 case EM_GETAUTOURLDETECT:
3143 return editor->AutoURLDetect_bEnable;
3145 case EM_EXSETSEL:
3147 int end;
3148 CHARRANGE range = *(CHARRANGE *)lParam;
3150 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3152 ME_InvalidateSelection(editor);
3153 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3154 ME_InvalidateSelection(editor);
3155 ITextHost_TxShowCaret(editor->texthost, FALSE);
3156 ME_ShowCaret(editor);
3157 ME_SendSelChange(editor);
3159 return end;
3161 case EM_SHOWSCROLLBAR:
3163 DWORD flags;
3165 switch (wParam)
3167 case SB_HORZ:
3168 flags = WS_HSCROLL;
3169 break;
3170 case SB_VERT:
3171 flags = WS_VSCROLL;
3172 break;
3173 case SB_BOTH:
3174 flags = WS_HSCROLL|WS_VSCROLL;
3175 break;
3176 default:
3177 return 0;
3180 if (lParam) {
3181 editor->styleFlags |= flags;
3182 if (flags & WS_HSCROLL)
3183 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3184 editor->nTotalWidth > editor->sizeWindow.cx);
3185 if (flags & WS_VSCROLL)
3186 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3187 editor->nTotalLength > editor->sizeWindow.cy);
3188 } else {
3189 editor->styleFlags &= ~flags;
3190 ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3192 return 0;
3194 case EM_SETTEXTEX:
3196 LPWSTR wszText;
3197 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3198 size_t len = 0;
3199 int from, to;
3200 ME_Style *style;
3201 BOOL bRtf, bUnicode, bSelection;
3202 int oldModify = editor->nModifyStep;
3204 if (!pStruct) return 0;
3206 /* If we detect ascii rtf at the start of the string,
3207 * we know it isn't unicode. */
3208 bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3209 !strncmp((char *)lParam, "{\\urtf", 6)));
3210 bUnicode = !bRtf && pStruct->codepage == 1200;
3212 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3213 bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3214 pStruct->flags, pStruct->codepage);
3216 bSelection = (pStruct->flags & ST_SELECTION) != 0;
3217 if (bSelection) {
3218 ME_GetSelectionOfs(editor, &from, &to);
3219 style = ME_GetSelectionInsertStyle(editor);
3220 ME_InternalDeleteText(editor, from, to - from, FALSE);
3221 } else {
3222 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3223 style = editor->pBuffer->pDefaultStyle;
3226 if (bRtf) {
3227 ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3228 if (bSelection) {
3229 /* FIXME: The length returned is doesn't include the rtf control
3230 * characters, only the actual text. */
3231 len = lParam ? strlen((char *)lParam) : 0;
3233 } else {
3234 /* FIXME: make use of pStruct->codepage in the to unicode translation */
3235 wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3236 len = wszText ? lstrlenW(wszText) : 0;
3237 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3240 if (bSelection) {
3241 ME_ReleaseStyle(style);
3242 ME_UpdateSelectionLinkAttribute(editor);
3243 } else {
3244 len = 1;
3245 ME_UpdateLinkAttribute(editor, 0, -1);
3247 ME_CommitUndo(editor);
3248 if (!(pStruct->flags & ST_KEEPUNDO))
3250 editor->nModifyStep = oldModify;
3251 ME_EmptyUndoStack(editor);
3253 ME_UpdateRepaint(editor);
3254 return len;
3256 case EM_SETBKGNDCOLOR:
3258 LRESULT lColor;
3259 if (editor->rgbBackColor != -1) {
3260 DeleteObject(editor->hbrBackground);
3261 lColor = editor->rgbBackColor;
3263 else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3265 if (wParam)
3267 editor->rgbBackColor = -1;
3268 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3270 else
3272 editor->rgbBackColor = lParam;
3273 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3275 ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3276 ITextHost_TxViewChange(editor->texthost, TRUE);
3277 return lColor;
3279 case EM_GETMODIFY:
3280 return editor->nModifyStep == 0 ? 0 : -1;
3281 case EM_SETMODIFY:
3283 if (wParam)
3284 editor->nModifyStep = 1;
3285 else
3286 editor->nModifyStep = 0;
3288 return 0;
3290 case EM_SETREADONLY:
3292 if (wParam)
3293 editor->styleFlags |= ES_READONLY;
3294 else
3295 editor->styleFlags &= ~ES_READONLY;
3296 return 0;
3298 case EM_SETEVENTMASK:
3300 DWORD nOldMask = editor->nEventMask;
3302 editor->nEventMask = lParam;
3303 return nOldMask;
3305 case EM_GETEVENTMASK:
3306 return editor->nEventMask;
3307 case EM_SETCHARFORMAT:
3309 CHARFORMAT2W buf, *p;
3310 BOOL bRepaint = TRUE;
3311 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3312 if (p == NULL) return 0;
3313 if (!wParam)
3314 ME_SetDefaultCharFormat(editor, p);
3315 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
3316 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3317 return 0;
3318 } else if (wParam == SCF_ALL) {
3319 if (editor->mode & TM_PLAINTEXT)
3320 ME_SetDefaultCharFormat(editor, p);
3321 else {
3322 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
3323 editor->nModifyStep = 1;
3325 } else if (editor->mode & TM_PLAINTEXT) {
3326 return 0;
3327 } else {
3328 bRepaint = ME_IsSelection(editor);
3329 ME_SetSelectionCharFormat(editor, p);
3330 if (bRepaint) editor->nModifyStep = 1;
3332 ME_CommitUndo(editor);
3333 if (bRepaint)
3335 ME_WrapMarkedParagraphs(editor);
3336 ME_UpdateScrollBar(editor);
3337 ME_Repaint(editor);
3339 return 1;
3341 case EM_GETCHARFORMAT:
3343 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3344 if (dst->cbSize != sizeof(CHARFORMATA) &&
3345 dst->cbSize != sizeof(CHARFORMATW) &&
3346 dst->cbSize != sizeof(CHARFORMAT2A) &&
3347 dst->cbSize != sizeof(CHARFORMAT2W))
3348 return 0;
3349 tmp.cbSize = sizeof(tmp);
3350 if (!wParam)
3351 ME_GetDefaultCharFormat(editor, &tmp);
3352 else
3353 ME_GetSelectionCharFormat(editor, &tmp);
3354 ME_CopyToCFAny(dst, &tmp);
3355 return tmp.dwMask;
3357 case EM_SETPARAFORMAT:
3359 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3360 ME_WrapMarkedParagraphs(editor);
3361 ME_UpdateScrollBar(editor);
3362 ME_Repaint(editor);
3363 ME_CommitUndo(editor);
3364 return result;
3366 case EM_GETPARAFORMAT:
3367 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3368 return ((PARAFORMAT2 *)lParam)->dwMask;
3369 case EM_GETFIRSTVISIBLELINE:
3371 ME_DisplayItem *p = editor->pBuffer->pFirst;
3372 int y = editor->vert_si.nPos;
3373 int ypara = 0;
3374 int count = 0;
3375 int ystart, yend;
3376 while(p) {
3377 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3378 if (p->type == diTextEnd)
3379 break;
3380 if (p->type == diParagraph) {
3381 ypara = p->member.para.pt.y;
3382 continue;
3384 ystart = ypara + p->member.row.pt.y;
3385 yend = ystart + p->member.row.nHeight;
3386 if (y < yend) {
3387 break;
3389 count++;
3391 return count;
3393 case EM_HIDESELECTION:
3395 editor->bHideSelection = (wParam != 0);
3396 ME_InvalidateSelection(editor);
3397 return 0;
3399 case EM_LINESCROLL:
3401 if (!(editor->styleFlags & ES_MULTILINE))
3402 return FALSE;
3403 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3404 return TRUE;
3406 case WM_CLEAR:
3408 int from, to;
3409 ME_GetSelectionOfs(editor, &from, &to);
3410 ME_InternalDeleteText(editor, from, to-from, FALSE);
3411 ME_CommitUndo(editor);
3412 ME_UpdateRepaint(editor);
3413 return 0;
3415 case EM_REPLACESEL:
3417 int from, to;
3418 ME_Style *style;
3419 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3420 size_t len = wszText ? lstrlenW(wszText) : 0;
3421 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3423 ME_GetSelectionOfs(editor, &from, &to);
3424 style = ME_GetSelectionInsertStyle(editor);
3425 ME_InternalDeleteText(editor, from, to-from, FALSE);
3426 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3427 ME_ReleaseStyle(style);
3428 /* drop temporary style if line end */
3430 * FIXME question: does abc\n mean: put abc,
3431 * clear temp style, put \n? (would require a change)
3433 if (len>0 && wszText[len-1] == '\n')
3434 ME_ClearTempStyle(editor);
3435 ME_EndToUnicode(unicode, wszText);
3436 ME_CommitUndo(editor);
3437 ME_UpdateSelectionLinkAttribute(editor);
3438 if (!wParam)
3439 ME_EmptyUndoStack(editor);
3440 ME_UpdateRepaint(editor);
3441 return len;
3443 case EM_SCROLLCARET:
3444 ME_EnsureVisible(editor, &editor->pCursors[0]);
3445 return 0;
3446 case WM_SETFONT:
3448 LOGFONTW lf;
3449 CHARFORMAT2W fmt;
3450 HDC hDC;
3451 BOOL bRepaint = LOWORD(lParam);
3453 if (!wParam)
3454 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3455 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3456 hDC = ITextHost_TxGetDC(editor->texthost);
3457 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3458 ITextHost_TxReleaseDC(editor->texthost, hDC);
3459 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
3460 ME_SetDefaultCharFormat(editor, &fmt);
3462 ME_CommitUndo(editor);
3463 ME_MarkAllForWrapping(editor);
3464 ME_WrapMarkedParagraphs(editor);
3465 ME_UpdateScrollBar(editor);
3466 if (bRepaint)
3467 ME_Repaint(editor);
3468 return 0;
3470 case WM_SETTEXT:
3472 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3473 if (lParam)
3475 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3476 if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3477 !strncmp((char *)lParam, "{\\urtf", 6))
3479 /* Undocumented: WM_SETTEXT supports RTF text */
3480 ME_StreamInRTFString(editor, 0, (char *)lParam);
3482 else
3484 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3485 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3486 if (lstrlenW(wszText) > 0)
3488 int len = -1;
3490 /* uses default style! */
3491 if (!(editor->styleFlags & ES_MULTILINE))
3493 WCHAR * p;
3495 p = wszText;
3496 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3497 len = p - wszText;
3499 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3501 ME_EndToUnicode(unicode, wszText);
3504 else
3505 TRACE("WM_SETTEXT - NULL\n");
3506 ME_UpdateLinkAttribute(editor, 0, -1);
3507 ME_SetSelection(editor, 0, 0);
3508 editor->nModifyStep = 0;
3509 ME_CommitUndo(editor);
3510 ME_EmptyUndoStack(editor);
3511 ME_UpdateRepaint(editor);
3512 return 1;
3514 case EM_CANPASTE:
3516 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3517 if (IsClipboardFormatAvailable(nRTFFormat))
3518 return TRUE;
3519 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3520 return TRUE;
3521 return FALSE;
3523 case WM_PASTE:
3524 ME_Paste(editor);
3525 return 0;
3526 case WM_CUT:
3527 case WM_COPY:
3529 CHARRANGE range;
3530 ME_GetSelectionOfs(editor, &range.cpMin, &range.cpMax);
3532 if (ME_Copy(editor, &range) && msg == WM_CUT)
3534 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3535 ME_CommitUndo(editor);
3536 ME_UpdateRepaint(editor);
3538 return 0;
3540 case WM_GETTEXTLENGTH:
3542 GETTEXTLENGTHEX how;
3544 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3545 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3546 how.codepage = unicode ? 1200 : CP_ACP;
3547 return ME_GetTextLengthEx(editor, &how);
3549 case EM_GETTEXTLENGTHEX:
3550 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3551 case WM_GETTEXT:
3553 GETTEXTEX ex;
3554 ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3555 ex.flags = GT_USECRLF;
3556 ex.codepage = unicode ? 1200 : CP_ACP;
3557 ex.lpDefaultChar = NULL;
3558 ex.lpUsedDefChar = NULL;
3559 return ME_GetTextEx(editor, &ex, lParam);
3561 case EM_GETTEXTEX:
3562 return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3563 case EM_GETSELTEXT:
3565 int from, to;
3566 ME_GetSelectionOfs(editor, &from, &to);
3567 return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3568 to - from, unicode);
3570 case EM_GETSCROLLPOS:
3572 POINT *point = (POINT *)lParam;
3573 point->x = editor->horz_si.nPos;
3574 point->y = editor->vert_si.nPos;
3575 /* 16-bit scaled value is returned as stored in scrollinfo */
3576 if (editor->horz_si.nMax > 0xffff)
3577 point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3578 if (editor->vert_si.nMax > 0xffff)
3579 point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3580 return 1;
3582 case EM_GETTEXTRANGE:
3584 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3585 int start = rng->chrg.cpMin;
3586 int end = rng->chrg.cpMax;
3587 int textlength = ME_GetTextLength(editor);
3588 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3589 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3590 editor->bEmulateVersion10, ME_GetTextLength(editor));
3591 if (start < 0) return 0;
3592 if ((start == 0 && end == -1) || end > textlength)
3593 end = textlength;
3594 if (start >= end) return 0;
3595 return ME_GetTextRange(editor, rng->lpstrText, start, end - start, unicode);
3597 case EM_GETLINE:
3599 ME_DisplayItem *run;
3600 const unsigned int nMaxChars = *(WORD *) lParam;
3601 unsigned int nCharsLeft = nMaxChars;
3602 char *dest = (char *) lParam;
3603 BOOL wroteNull = FALSE;
3605 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3606 unicode ? "Unicode" : "Ansi");
3608 run = ME_FindRowWithNumber(editor, wParam);
3609 if (run == NULL)
3610 return 0;
3612 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3613 && run->type == diRun)
3615 unsigned int nCopy;
3616 ME_String *strText;
3618 strText = run->member.run.strText;
3619 nCopy = min(nCharsLeft, strText->nLen);
3621 if (unicode)
3622 memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3623 else
3624 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3625 nCharsLeft, NULL, NULL);
3626 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3627 nCharsLeft -= nCopy;
3630 /* append line termination, space allowing */
3631 if (nCharsLeft > 0)
3633 if (unicode)
3634 *((WCHAR *)dest) = '\0';
3635 else
3636 *dest = '\0';
3637 nCharsLeft--;
3638 wroteNull = TRUE;
3641 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3642 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3644 case EM_GETLINECOUNT:
3646 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3647 int nRows = 0;
3649 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3651 while (item != editor->pBuffer->pLast)
3653 assert(item->type == diParagraph);
3654 prev_para = ME_FindItemBack(item, diRun);
3655 if (prev_para) {
3656 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3658 nRows += item->member.para.nRows;
3659 item = item->member.para.next_para;
3661 last_para = ME_FindItemBack(item, diRun);
3662 assert(last_para);
3663 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3664 if (editor->bEmulateVersion10 && prev_para &&
3665 last_para->member.run.nCharOfs == 0 &&
3666 prev_para->member.run.strText->nLen == 1 &&
3667 prev_para->member.run.strText->szData[0] == '\r')
3669 /* In 1.0 emulation, the last solitary \r at the very end of the text
3670 (if one exists) is NOT a line break.
3671 FIXME: this is an ugly hack. This should have a more regular model. */
3672 nRows--;
3675 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3676 return max(1, nRows);
3678 case EM_LINEFROMCHAR:
3680 if (wParam == -1)
3681 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3682 else
3683 return ME_RowNumberFromCharOfs(editor, wParam);
3685 case EM_EXLINEFROMCHAR:
3687 if (lParam == -1)
3688 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3689 else
3690 return ME_RowNumberFromCharOfs(editor, lParam);
3692 case EM_LINEINDEX:
3694 ME_DisplayItem *item, *para;
3695 int nCharOfs;
3697 if (wParam == -1)
3698 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3699 else
3700 item = ME_FindRowWithNumber(editor, wParam);
3701 if (!item)
3702 return -1;
3703 para = ME_GetParagraph(item);
3704 item = ME_FindItemFwd(item, diRun);
3705 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3706 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3707 return nCharOfs;
3709 case EM_LINELENGTH:
3711 ME_DisplayItem *item, *item_end;
3712 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3713 ME_DisplayItem *para, *run;
3715 if (wParam > ME_GetTextLength(editor))
3716 return 0;
3717 if (wParam == -1)
3719 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3720 return 0;
3722 ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3723 item = ME_RowStart(run);
3724 nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3725 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3726 if (item_end->type == diStartRow) {
3727 nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3728 } else {
3729 ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3730 assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3731 nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3733 nChars = nNextLineOfs - nThisLineOfs;
3734 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3735 return nChars;
3737 case EM_EXLIMITTEXT:
3739 if ((int)lParam < 0)
3740 return 0;
3741 if (lParam == 0)
3742 editor->nTextLimit = 65536;
3743 else
3744 editor->nTextLimit = (int) lParam;
3745 return 0;
3747 case EM_LIMITTEXT:
3749 if (wParam == 0)
3750 editor->nTextLimit = 65536;
3751 else
3752 editor->nTextLimit = (int) wParam;
3753 return 0;
3755 case EM_GETLIMITTEXT:
3757 return editor->nTextLimit;
3759 case EM_FINDTEXT:
3761 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3762 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3763 WCHAR *tmp;
3764 LRESULT r;
3766 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3767 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3768 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3769 FREE_OBJ( tmp );
3770 return r;
3772 case EM_FINDTEXTEX:
3774 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3775 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3776 WCHAR *tmp;
3777 LRESULT r;
3779 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3780 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3781 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3782 FREE_OBJ( tmp );
3783 return r;
3785 case EM_FINDTEXTW:
3787 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3788 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3790 case EM_FINDTEXTEXW:
3792 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3793 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3795 case EM_GETZOOM:
3796 if (!wParam || !lParam)
3797 return FALSE;
3798 *(int *)wParam = editor->nZoomNumerator;
3799 *(int *)lParam = editor->nZoomDenominator;
3800 return TRUE;
3801 case EM_SETZOOM:
3802 return ME_SetZoom(editor, wParam, lParam);
3803 case EM_CHARFROMPOS:
3804 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3805 case EM_POSFROMCHAR:
3807 ME_DisplayItem *pPara, *pRun;
3808 int nCharOfs, nOffset, nLength;
3809 POINTL pt = {0,0};
3811 nCharOfs = wParam;
3812 /* detect which API version we're dealing with */
3813 if (wParam >= 0x40000)
3814 nCharOfs = lParam;
3815 nLength = ME_GetTextLength(editor);
3816 nCharOfs = min(nCharOfs, nLength);
3817 nCharOfs = max(nCharOfs, 0);
3819 ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3820 assert(pRun->type == diRun);
3821 pt.y = pRun->member.run.pt.y;
3822 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3823 pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3824 pt.x += editor->rcFormat.left;
3826 pt.x -= editor->horz_si.nPos;
3827 pt.y -= editor->vert_si.nPos;
3829 if (wParam >= 0x40000) {
3830 *(POINTL *)wParam = pt;
3832 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3834 case WM_CREATE:
3836 INT max;
3838 ME_SetDefaultFormatRect(editor);
3840 max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3841 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3842 ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3844 if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3845 ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3847 if (editor->styleFlags & ES_DISABLENOSCROLL)
3849 if (editor->styleFlags & WS_VSCROLL)
3851 ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3852 ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3854 if (editor->styleFlags & WS_HSCROLL)
3856 ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3857 ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3861 ME_CommitUndo(editor);
3862 ME_WrapMarkedParagraphs(editor);
3863 ME_MoveCaret(editor);
3864 return 0;
3866 case WM_DESTROY:
3867 ME_DestroyEditor(editor);
3868 return 0;
3869 case WM_SETCURSOR:
3871 return ME_SetCursor(editor);
3873 case WM_LBUTTONDBLCLK:
3874 case WM_LBUTTONDOWN:
3876 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3877 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3878 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3879 return 0;
3880 ITextHost_TxSetFocus(editor->texthost);
3881 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3882 ME_CalculateClickCount(editor, msg, wParam, lParam));
3883 ITextHost_TxSetCapture(editor->texthost, TRUE);
3884 editor->bMouseCaptured = TRUE;
3885 ME_LinkNotify(editor,msg,wParam,lParam);
3886 if (!ME_SetCursor(editor)) goto do_default;
3887 break;
3889 case WM_MOUSEMOVE:
3890 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3891 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3892 return 0;
3893 if (editor->bMouseCaptured)
3894 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3895 ME_LinkNotify(editor,msg,wParam,lParam);
3896 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3897 if (editor->bMouseCaptured)
3898 ME_SetCursor(editor);
3899 break;
3900 case WM_LBUTTONUP:
3901 if (editor->bMouseCaptured) {
3902 ITextHost_TxSetCapture(editor->texthost, FALSE);
3903 editor->bMouseCaptured = FALSE;
3905 if (editor->nSelectionType == stDocument)
3906 editor->nSelectionType = stPosition;
3907 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3908 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3909 return 0;
3910 else
3912 ME_SetCursor(editor);
3913 ME_LinkNotify(editor,msg,wParam,lParam);
3915 break;
3916 case WM_RBUTTONUP:
3917 case WM_RBUTTONDOWN:
3918 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3919 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3920 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3921 return 0;
3922 goto do_default;
3923 case WM_CONTEXTMENU:
3924 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3925 goto do_default;
3926 break;
3927 case WM_SETFOCUS:
3928 editor->bHaveFocus = TRUE;
3929 ME_ShowCaret(editor);
3930 ME_SendOldNotify(editor, EN_SETFOCUS);
3931 return 0;
3932 case WM_KILLFOCUS:
3933 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3934 editor->bHaveFocus = FALSE;
3935 ME_HideCaret(editor);
3936 ME_SendOldNotify(editor, EN_KILLFOCUS);
3937 return 0;
3938 case WM_COMMAND:
3939 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3940 return 0;
3941 case WM_KEYUP:
3942 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3943 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3944 return 0;
3945 goto do_default;
3946 case WM_KEYDOWN:
3947 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3948 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3949 return 0;
3950 if (ME_KeyDown(editor, LOWORD(wParam)))
3951 return 0;
3952 goto do_default;
3953 case WM_CHAR:
3954 return ME_Char(editor, wParam, lParam, unicode);
3955 case WM_UNICHAR:
3956 if (unicode)
3958 if(wParam == UNICODE_NOCHAR) return TRUE;
3959 if(wParam <= 0x000fffff)
3961 if(wParam > 0xffff) /* convert to surrogates */
3963 wParam -= 0x10000;
3964 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
3965 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
3966 } else {
3967 ME_Char(editor, wParam, 0, TRUE);
3970 return 0;
3972 break;
3973 case EM_STOPGROUPTYPING:
3974 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3975 return 0;
3976 case WM_HSCROLL:
3978 const int scrollUnit = 7;
3980 switch(LOWORD(wParam))
3982 case SB_LEFT:
3983 ME_ScrollAbs(editor, 0, 0);
3984 break;
3985 case SB_RIGHT:
3986 ME_ScrollAbs(editor,
3987 editor->horz_si.nMax - (int)editor->horz_si.nPage,
3988 editor->vert_si.nMax - (int)editor->vert_si.nPage);
3989 break;
3990 case SB_LINELEFT:
3991 ME_ScrollLeft(editor, scrollUnit);
3992 break;
3993 case SB_LINERIGHT:
3994 ME_ScrollRight(editor, scrollUnit);
3995 break;
3996 case SB_PAGELEFT:
3997 ME_ScrollLeft(editor, editor->sizeWindow.cx);
3998 break;
3999 case SB_PAGERIGHT:
4000 ME_ScrollRight(editor, editor->sizeWindow.cx);
4001 break;
4002 case SB_THUMBTRACK:
4003 case SB_THUMBPOSITION:
4005 int pos = HIWORD(wParam);
4006 if (editor->horz_si.nMax > 0xffff)
4007 pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4008 ME_HScrollAbs(editor, pos);
4009 break;
4012 break;
4014 case EM_SCROLL: /* fall through */
4015 case WM_VSCROLL:
4017 int origNPos;
4018 int lineHeight;
4020 origNPos = editor->vert_si.nPos;
4021 lineHeight = 24;
4023 if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4024 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4025 if (lineHeight <= 0) lineHeight = 24;
4027 switch(LOWORD(wParam))
4029 case SB_TOP:
4030 ME_ScrollAbs(editor, 0, 0);
4031 break;
4032 case SB_BOTTOM:
4033 ME_ScrollAbs(editor,
4034 editor->horz_si.nMax - (int)editor->horz_si.nPage,
4035 editor->vert_si.nMax - (int)editor->vert_si.nPage);
4036 break;
4037 case SB_LINEUP:
4038 ME_ScrollUp(editor,lineHeight);
4039 break;
4040 case SB_LINEDOWN:
4041 ME_ScrollDown(editor,lineHeight);
4042 break;
4043 case SB_PAGEUP:
4044 ME_ScrollUp(editor,editor->sizeWindow.cy);
4045 break;
4046 case SB_PAGEDOWN:
4047 ME_ScrollDown(editor,editor->sizeWindow.cy);
4048 break;
4049 case SB_THUMBTRACK:
4050 case SB_THUMBPOSITION:
4052 int pos = HIWORD(wParam);
4053 if (editor->vert_si.nMax > 0xffff)
4054 pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4055 ME_VScrollAbs(editor, pos);
4056 break;
4059 if (msg == EM_SCROLL)
4060 return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4061 break;
4063 case WM_MOUSEWHEEL:
4065 int gcWheelDelta;
4066 UINT pulScrollLines;
4067 BOOL ctrl_is_down;
4069 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4070 !ME_FilterEvent(editor, msg, &wParam, &lParam))
4071 return 0;
4073 ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4075 gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4077 if (abs(gcWheelDelta) >= WHEEL_DELTA)
4079 if (ctrl_is_down) {
4080 int numerator;
4081 if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4083 numerator = 100;
4084 } else {
4085 numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4087 numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4088 if (numerator >= 10 && numerator <= 500)
4089 ME_SetZoom(editor, numerator, 100);
4090 } else {
4091 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4092 /* FIXME follow the original */
4093 if (pulScrollLines)
4094 ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4097 break;
4099 case EM_GETRECT:
4101 *((RECT *)lParam) = editor->rcFormat;
4102 if (editor->bDefaultFormatRect)
4103 ((RECT *)lParam)->left -= editor->selofs;
4104 return 0;
4106 case EM_SETRECT:
4107 case EM_SETRECTNP:
4109 if (lParam)
4111 int border = 0;
4112 RECT clientRect;
4113 RECT *rc = (RECT *)lParam;
4115 border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4116 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4117 if (wParam == 0)
4119 editor->rcFormat.top = max(0, rc->top - border);
4120 editor->rcFormat.left = max(0, rc->left - border);
4121 editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4122 editor->rcFormat.right = min(clientRect.right, rc->right + border);
4123 } else if (wParam == 1) {
4124 /* MSDN incorrectly says a wParam value of 1 causes the
4125 * lParam rect to be used as a relative offset,
4126 * however, the tests show it just prevents min/max bound
4127 * checking. */
4128 editor->rcFormat.top = rc->top - border;
4129 editor->rcFormat.left = rc->left - border;
4130 editor->rcFormat.bottom = rc->bottom;
4131 editor->rcFormat.right = rc->right + border;
4132 } else {
4133 return 0;
4135 editor->bDefaultFormatRect = FALSE;
4137 else
4139 ME_SetDefaultFormatRect(editor);
4140 editor->bDefaultFormatRect = TRUE;
4142 ME_MarkAllForWrapping(editor);
4143 ME_WrapMarkedParagraphs(editor);
4144 ME_UpdateScrollBar(editor);
4145 if (msg != EM_SETRECTNP)
4146 ME_Repaint(editor);
4147 return 0;
4149 case EM_REQUESTRESIZE:
4150 ME_SendRequestResize(editor, TRUE);
4151 return 0;
4152 case WM_SETREDRAW:
4153 goto do_default;
4154 case WM_SIZE:
4156 RECT clientRect;
4158 ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4159 if (editor->bDefaultFormatRect) {
4160 ME_SetDefaultFormatRect(editor);
4161 } else {
4162 editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4163 editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4165 editor->prevClientRect = clientRect;
4166 ME_RewrapRepaint(editor);
4167 goto do_default;
4169 /* IME messages to make richedit controls IME aware */
4170 case WM_IME_SETCONTEXT:
4171 case WM_IME_CONTROL:
4172 case WM_IME_SELECT:
4173 case WM_IME_COMPOSITIONFULL:
4174 return 0;
4175 case WM_IME_STARTCOMPOSITION:
4177 editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4178 ME_DeleteSelection(editor);
4179 ME_CommitUndo(editor);
4180 ME_UpdateRepaint(editor);
4181 return 0;
4183 case WM_IME_COMPOSITION:
4185 HIMC hIMC;
4187 ME_Style *style = ME_GetInsertStyle(editor, 0);
4188 hIMC = ITextHost_TxImmGetContext(editor->texthost);
4189 ME_DeleteSelection(editor);
4190 ME_CommitUndo(editor);
4191 ME_SaveTempStyle(editor);
4192 if (lParam & GCS_RESULTSTR)
4194 LPWSTR lpCompStr = NULL;
4195 DWORD dwBufLen;
4197 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
4198 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4199 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
4200 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4201 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4203 else if (lParam & GCS_COMPSTR)
4205 LPWSTR lpCompStr = NULL;
4206 DWORD dwBufLen;
4208 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4209 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4210 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
4211 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4213 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4214 ME_SetSelection(editor,editor->imeStartIndex,
4215 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4217 ME_ReleaseStyle(style);
4218 ME_UpdateRepaint(editor);
4219 return 0;
4221 case WM_IME_ENDCOMPOSITION:
4223 ME_DeleteSelection(editor);
4224 editor->imeStartIndex=-1;
4225 return 0;
4227 case EM_GETOLEINTERFACE:
4229 LPVOID *ppvObj = (LPVOID*) lParam;
4230 return CreateIRichEditOle(editor, ppvObj);
4232 case EM_GETPASSWORDCHAR:
4234 return editor->cPasswordMask;
4236 case EM_SETOLECALLBACK:
4237 if(editor->lpOleCallback)
4238 IUnknown_Release(editor->lpOleCallback);
4239 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4240 if(editor->lpOleCallback)
4241 IUnknown_AddRef(editor->lpOleCallback);
4242 return TRUE;
4243 case EM_GETWORDBREAKPROC:
4244 return (LRESULT)editor->pfnWordBreak;
4245 case EM_SETWORDBREAKPROC:
4247 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4249 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4250 return (LRESULT)pfnOld;
4252 case EM_GETTEXTMODE:
4253 return editor->mode;
4254 case EM_SETTEXTMODE:
4256 LRESULT ret;
4257 int mask = 0;
4258 int changes = 0;
4259 GETTEXTLENGTHEX how;
4261 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
4262 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
4263 how.codepage = unicode ? 1200 : CP_ACP;
4264 ret = ME_GetTextLengthEx(editor, &how);
4265 if (!ret)
4267 /*Check for valid wParam*/
4268 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4269 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4270 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4271 return 1;
4272 else
4274 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4276 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4277 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4279 /*FIXME: Currently no support for undo level and code page options*/
4280 editor->mode = (editor->mode & (~mask)) | changes;
4281 return 0;
4284 return ret;
4286 case EM_SETPASSWORDCHAR:
4288 editor->cPasswordMask = wParam;
4289 ME_RewrapRepaint(editor);
4290 return 0;
4292 case EM_SETTARGETDEVICE:
4293 if (wParam == 0)
4295 BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4296 if (editor->nAvailWidth || editor->bWordWrap != new)
4298 editor->bWordWrap = new;
4299 editor->nAvailWidth = 0; /* wrap to client area */
4300 ME_RewrapRepaint(editor);
4302 } else {
4303 int width = max(0, lParam);
4304 if ((editor->styleFlags & ES_MULTILINE) &&
4305 (!editor->bWordWrap || editor->nAvailWidth != width))
4307 editor->nAvailWidth = width;
4308 editor->bWordWrap = TRUE;
4309 ME_RewrapRepaint(editor);
4311 FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4313 return TRUE;
4314 default:
4315 do_default:
4316 *phresult = S_FALSE;
4317 break;
4319 return 0L;
4322 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4323 LPARAM lParam, BOOL unicode)
4325 ME_TextEditor *editor;
4326 HRESULT hresult;
4327 LRESULT lresult = 0;
4329 TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4330 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4332 editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4333 if (!editor)
4335 if (msg == WM_NCCREATE)
4337 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4338 ITextHost *texthost;
4340 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4341 texthost = ME_CreateTextHost(hWnd, FALSE);
4342 return texthost != NULL;
4344 else if (msg != WM_NCDESTROY)
4346 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
4347 return 0;
4351 switch (msg)
4353 case WM_PAINT:
4355 HDC hDC;
4356 RECT rc;
4357 PAINTSTRUCT ps;
4359 hDC = BeginPaint(editor->hWnd, &ps);
4360 /* Erase area outside of the formatting rectangle */
4361 if (ps.rcPaint.top < editor->rcFormat.top)
4363 rc = ps.rcPaint;
4364 rc.bottom = editor->rcFormat.top;
4365 FillRect(hDC, &rc, editor->hbrBackground);
4366 ps.rcPaint.top = editor->rcFormat.top;
4368 if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4369 rc = ps.rcPaint;
4370 rc.top = editor->rcFormat.bottom;
4371 FillRect(hDC, &rc, editor->hbrBackground);
4372 ps.rcPaint.bottom = editor->rcFormat.bottom;
4374 if (ps.rcPaint.left < editor->rcFormat.left) {
4375 rc = ps.rcPaint;
4376 rc.right = editor->rcFormat.left;
4377 FillRect(hDC, &rc, editor->hbrBackground);
4378 ps.rcPaint.left = editor->rcFormat.left;
4380 if (ps.rcPaint.right > editor->rcFormat.right) {
4381 rc = ps.rcPaint;
4382 rc.left = editor->rcFormat.right;
4383 FillRect(hDC, &rc, editor->hbrBackground);
4384 ps.rcPaint.right = editor->rcFormat.right;
4387 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4388 EndPaint(editor->hWnd, &ps);
4389 return 0;
4391 case WM_ERASEBKGND:
4393 HDC hDC = (HDC)wParam;
4394 RECT rc;
4396 if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4397 FillRect(hDC, &rc, editor->hbrBackground);
4398 return 1;
4400 case EM_SETOPTIONS:
4402 DWORD dwStyle;
4403 const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4404 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4405 ECO_SELECTIONBAR;
4406 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4407 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4408 dwStyle = (dwStyle & ~mask) | (lresult & mask);
4409 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4410 return lresult;
4412 case EM_SETREADONLY:
4414 DWORD dwStyle;
4415 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4416 dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4417 dwStyle &= ~ES_READONLY;
4418 if (wParam)
4419 dwStyle |= ES_READONLY;
4420 SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4421 return lresult;
4423 default:
4424 lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4427 if (hresult == S_FALSE)
4428 lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4430 TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4431 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4433 return lresult;
4436 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4438 BOOL unicode = TRUE;
4440 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4441 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4442 unicode = FALSE;
4444 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4447 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4449 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4452 /******************************************************************
4453 * RichEditANSIWndProc (RICHED20.10)
4455 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4457 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4460 /******************************************************************
4461 * RichEdit10ANSIWndProc (RICHED20.9)
4463 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4465 if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4467 ITextHost *texthost;
4468 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4470 TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4471 texthost = ME_CreateTextHost(hWnd, TRUE);
4472 return texthost != NULL;
4474 return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4477 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4479 ITextHost_TxNotify(editor->texthost, nCode, NULL);
4482 /* Fill buffer with srcChars unicode characters from the start cursor.
4484 * buffer: destination buffer
4485 * buflen: length of buffer in characters excluding the NULL terminator.
4486 * start: start of editor text to copy into buffer.
4487 * srcChars: Number of characters to use from the editor text.
4488 * bCRLF: if true, replaces all end of lines with \r\n pairs.
4490 * returns the number of characters written excluding the NULL terminator.
4492 * The written text is always NULL terminated.
4494 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4495 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4497 ME_DisplayItem *pRun, *pNextRun;
4498 const WCHAR *pStart = buffer;
4499 const WCHAR cr_lf[] = {'\r', '\n', 0};
4500 const WCHAR *str;
4501 int nLen;
4503 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4504 if (editor->bEmulateVersion10) bCRLF = 0;
4506 pRun = start->pRun;
4507 assert(pRun);
4508 pNextRun = ME_FindItemFwd(pRun, diRun);
4510 nLen = pRun->member.run.strText->nLen - start->nOffset;
4511 str = pRun->member.run.strText->szData + start->nOffset;
4513 /* No '\r' is appended to the last paragraph. */
4514 while (srcChars && buflen && pNextRun)
4516 int nFlags = pRun->member.run.nFlags;
4518 if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4520 if (buflen == 1) break;
4521 /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4522 * EM_GETTEXTEX, however, this is done for copying text which
4523 * also uses this function. */
4524 srcChars -= min(nLen, srcChars);
4525 nLen = 2;
4526 str = cr_lf;
4527 } else {
4528 nLen = min(nLen, srcChars);
4529 srcChars -= nLen;
4532 nLen = min(nLen, buflen);
4533 buflen -= nLen;
4535 CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4537 buffer += nLen;
4539 pRun = pNextRun;
4540 pNextRun = ME_FindItemFwd(pRun, diRun);
4542 nLen = pRun->member.run.strText->nLen;
4543 str = pRun->member.run.strText->szData;
4545 *buffer = 0;
4546 return buffer - pStart;
4549 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4551 WNDCLASSW wcW;
4552 WNDCLASSA wcA;
4554 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4555 wcW.lpfnWndProc = RichEditWndProcW;
4556 wcW.cbClsExtra = 0;
4557 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4558 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4559 wcW.hIcon = NULL;
4560 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4561 wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4562 wcW.lpszMenuName = NULL;
4564 if (is_version_nt())
4566 wcW.lpszClassName = RICHEDIT_CLASS20W;
4567 if (!RegisterClassW(&wcW)) return FALSE;
4568 wcW.lpszClassName = MSFTEDIT_CLASS;
4569 if (!RegisterClassW(&wcW)) return FALSE;
4571 else
4573 /* WNDCLASSA/W have the same layout */
4574 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4575 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4576 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4577 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4580 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4581 wcA.lpfnWndProc = RichEditWndProcA;
4582 wcA.cbClsExtra = 0;
4583 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4584 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4585 wcA.hIcon = NULL;
4586 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4587 wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4588 wcA.lpszMenuName = NULL;
4589 wcA.lpszClassName = RICHEDIT_CLASS20A;
4590 if (!RegisterClassA(&wcA)) return FALSE;
4591 wcA.lpszClassName = "RichEdit50A";
4592 if (!RegisterClassA(&wcA)) return FALSE;
4594 return TRUE;
4597 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4598 /* FIXME: Not implemented */
4599 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4600 hWnd, msg, get_msg_name(msg), wParam, lParam);
4601 return DefWindowProcW(hWnd, msg, wParam, lParam);
4604 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4605 /* FIXME: Not implemented */
4606 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4607 hWnd, msg, get_msg_name(msg), wParam, lParam);
4608 return DefWindowProcW(hWnd, msg, wParam, lParam);
4611 /******************************************************************
4612 * REExtendedRegisterClass (RICHED20.8)
4614 * FIXME undocumented
4615 * Need to check for errors and implement controls and callbacks
4617 LRESULT WINAPI REExtendedRegisterClass(void)
4619 WNDCLASSW wcW;
4620 UINT result;
4622 FIXME("semi stub\n");
4624 wcW.cbClsExtra = 0;
4625 wcW.cbWndExtra = 4;
4626 wcW.hInstance = NULL;
4627 wcW.hIcon = NULL;
4628 wcW.hCursor = NULL;
4629 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4630 wcW.lpszMenuName = NULL;
4632 if (!ME_ListBoxRegistered)
4634 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4635 wcW.lpfnWndProc = REListWndProc;
4636 wcW.lpszClassName = REListBox20W;
4637 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4640 if (!ME_ComboBoxRegistered)
4642 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4643 wcW.lpfnWndProc = REComboWndProc;
4644 wcW.lpszClassName = REComboBox20W;
4645 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4648 result = 0;
4649 if (ME_ListBoxRegistered)
4650 result += 1;
4651 if (ME_ComboBoxRegistered)
4652 result += 2;
4654 return result;
4657 static BOOL isurlspecial(WCHAR c)
4659 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4660 return strchrW( special_chars, c ) != NULL;
4664 * This proc takes a selection, and scans it forward in order to select the span
4665 * of a possible URL candidate. A possible URL candidate must start with isalnum
4666 * or one of the following special characters: *|/\+%#@ and must consist entirely
4667 * of the characters allowed to start the URL, plus : (colon) which may occur
4668 * at most once, and not at either end.
4670 * sel_max == -1 indicates scan to end of text.
4672 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4673 int * candidate_min, int * candidate_max)
4675 ME_DisplayItem * item;
4676 ME_DisplayItem * para;
4677 int nStart;
4678 BOOL foundColon = FALSE;
4679 WCHAR lastAcceptedChar = '\0';
4681 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4683 *candidate_min = *candidate_max = -1;
4684 ME_RunOfsFromCharOfs(editor, sel_min, &para, &item, &nStart);
4685 TRACE("nStart = %d\n", nStart);
4686 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4687 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4689 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4690 /* Find start of candidate */
4691 if (*candidate_min == -1) {
4692 while (nStart < item->member.run.strText->nLen &&
4693 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4694 isurlspecial(item->member.run.strText->szData[nStart]))) {
4695 nStart++;
4697 if (nStart < item->member.run.strText->nLen &&
4698 (isalnumW(item->member.run.strText->szData[nStart]) ||
4699 isurlspecial(item->member.run.strText->szData[nStart]))) {
4700 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4701 lastAcceptedChar = item->member.run.strText->szData[nStart];
4702 nStart++;
4706 /* Find end of candidate */
4707 if (*candidate_min >= 0) {
4708 while (nStart < item->member.run.strText->nLen &&
4709 (isalnumW(item->member.run.strText->szData[nStart]) ||
4710 isurlspecial(item->member.run.strText->szData[nStart]) ||
4711 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4712 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4713 lastAcceptedChar = item->member.run.strText->szData[nStart];
4714 nStart++;
4716 if (nStart < item->member.run.strText->nLen &&
4717 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4718 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4719 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4720 nStart++;
4721 if (lastAcceptedChar == ':') (*candidate_max)--;
4722 return TRUE;
4725 } else {
4726 /* End of paragraph: skip it if before candidate span, or terminates
4727 current active span */
4728 if (*candidate_min >= 0) {
4729 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4730 if (lastAcceptedChar == ':') (*candidate_max)--;
4731 return TRUE;
4735 /* Reaching this point means no span was found, so get next span */
4736 if (!ME_NextRun(&para, &item)) {
4737 if (*candidate_min >= 0) {
4738 /* There are no further runs, so take end of text as end of candidate */
4739 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4740 if (lastAcceptedChar == ':') (*candidate_max)--;
4741 return TRUE;
4743 return FALSE;
4745 nStart = 0;
4748 if (item) {
4749 if (*candidate_min >= 0) {
4750 /* There are no further runs, so take end of text as end of candidate */
4751 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4752 if (lastAcceptedChar == ':') (*candidate_max)--;
4753 return TRUE;
4756 return FALSE;
4760 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4762 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4764 #define MAX_PREFIX_LEN 9
4765 struct prefix_s {
4766 const WCHAR text[MAX_PREFIX_LEN];
4767 int length;
4768 }prefixes[] = {
4769 {{'p','r','o','s','p','e','r','o',':'}, 9},
4770 {{'t','e','l','n','e','t',':'}, 7},
4771 {{'g','o','p','h','e','r',':'}, 7},
4772 {{'m','a','i','l','t','o',':'}, 7},
4773 {{'h','t','t','p','s',':'}, 6},
4774 {{'f','i','l','e',':'}, 5},
4775 {{'n','e','w','s',':'}, 5},
4776 {{'w','a','i','s',':'}, 5},
4777 {{'n','n','t','p',':'}, 5},
4778 {{'h','t','t','p',':'}, 5},
4779 {{'w','w','w','.'}, 4},
4780 {{'f','t','p',':'}, 4},
4782 WCHAR bufferW[MAX_PREFIX_LEN + 1];
4783 unsigned int i;
4785 ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4786 for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4788 if (nChars < prefixes[i].length) continue;
4789 if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4790 return TRUE;
4792 return FALSE;
4793 #undef MAX_PREFIX_LEN
4797 * This proc walks through the indicated selection and evaluates whether each
4798 * section identified by ME_FindNextURLCandidate and in-between sections have
4799 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4800 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4802 * Returns TRUE if at least one section was modified.
4804 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4806 BOOL modified = FALSE;
4807 int cMin, cMax;
4809 if (!editor->AutoURLDetect_bEnable) return FALSE;
4811 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4814 int beforeURL[2];
4815 int inURL[2];
4816 CHARFORMAT2W link;
4818 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4820 ME_Cursor candidateStart;
4821 /* Section before candidate is not an URL */
4822 beforeURL[0] = sel_min;
4823 beforeURL[1] = cMin;
4825 ME_CursorFromCharOfs(editor, cMin, &candidateStart);
4826 if (ME_IsCandidateAnURL(editor, &candidateStart,
4827 (cMax == -1 ? INT_MAX : cMax) - cMin))
4829 inURL[0] = cMin; inURL[1] = cMax;
4831 else
4833 beforeURL[1] = cMax;
4834 inURL[0] = inURL[1] = -1;
4836 sel_min = cMax;
4838 else
4840 /* No more candidates until end of selection */
4841 beforeURL[0] = sel_min;
4842 beforeURL[1] = sel_max;
4843 inURL[0] = inURL[1] = -1;
4844 sel_min = sel_max;
4847 if (beforeURL[0] < beforeURL[1])
4849 /* CFE_LINK effect should be consistently unset */
4850 link.cbSize = sizeof(link);
4851 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4852 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4854 /* CFE_LINK must be unset from this range */
4855 memset(&link, 0, sizeof(CHARFORMAT2W));
4856 link.cbSize = sizeof(link);
4857 link.dwMask = CFM_LINK;
4858 link.dwEffects = 0;
4859 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4860 modified = TRUE;
4863 if (inURL[0] < inURL[1])
4865 /* CFE_LINK effect should be consistently set */
4866 link.cbSize = sizeof(link);
4867 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4868 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4870 /* CFE_LINK must be set on this range */
4871 memset(&link, 0, sizeof(CHARFORMAT2W));
4872 link.cbSize = sizeof(link);
4873 link.dwMask = CFM_LINK;
4874 link.dwEffects = CFE_LINK;
4875 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4876 modified = TRUE;
4879 } while (sel_min < sel_max);
4880 return modified;