push b0b97fcd59eff07f047585692fa36859b459324f
[wine/hacks.git] / dlls / riched20 / editor.c
blobadc9362907f2e941dff30990eb0a6a60afd637ec
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 (only Y value valid)
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_SETLANGOPTIONS 2.0
103 - EM_SETLIMITTEXT
104 + EM_SETMODIFY (not sure if implementation is correct)
105 - EM_SETOLECALLBACK
106 + EM_SETOPTIONS (partially implemented)
107 - EM_SETPALETTE 2.0
108 + EM_SETPARAFORMAT
109 + EM_SETPASSWORDCHAR 2.0
110 - EM_SETPUNCTUATION 1.0asian
111 + EM_SETREADONLY no beep on modification attempt
112 + EM_SETRECT
113 + EM_SETRECTNP (EM_SETRECT without repainting)
114 + EM_SETSEL
115 + EM_SETSCROLLPOS 3.0
116 - EM_SETTABSTOPS 3.0
117 - EM_SETTARGETDEVICE (partial)
118 + EM_SETTEXTEX 3.0 (proper style?)
119 - EM_SETTEXTMODE 2.0
120 - EM_SETTYPOGRAPHYOPTIONS 3.0
121 + EM_SETUNDOLIMIT 2.0
122 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
123 - EM_SETWORDBREAKPROCEX
124 - EM_SETWORDWRAPMODE 1.0asian
125 + EM_SETZOOM 3.0
126 + EM_SHOWSCROLLBAR 2.0
127 + EM_STOPGROUPTYPING 2.0
128 + EM_STREAMIN
129 + EM_STREAMOUT
130 + EM_UNDO
131 + WM_CHAR
132 + WM_CLEAR
133 + WM_COPY
134 + WM_CUT
135 + WM_GETDLGCODE (the current implementation is incomplete)
136 + WM_GETTEXT (ANSI&Unicode)
137 + WM_GETTEXTLENGTH (ANSI version sucks)
138 + WM_PASTE
139 + WM_SETFONT
140 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
141 - WM_STYLECHANGING
142 - WM_STYLECHANGED (things like read-only flag)
143 + WM_UNICHAR
145 Notifications
147 * EN_CHANGE (sent from the wrong place)
148 - EN_CORRECTTEXT
149 - EN_DROPFILES
150 - EN_ERRSPACE
151 - EN_HSCROLL
152 - EN_IMECHANGE
153 + EN_KILLFOCUS
154 - EN_LINK
155 - EN_MAXTEXT
156 - EN_MSGFILTER
157 - EN_OLEOPFAILED
158 - EN_PROTECTED
159 + EN_REQUESTRESIZE
160 - EN_SAVECLIPBOARD
161 + EN_SELCHANGE
162 + EN_SETFOCUS
163 - EN_STOPNOUNDO
164 * EN_UPDATE (sent from the wrong place)
165 - EN_VSCROLL
167 Styles
169 - ES_AUTOHSCROLL
170 - ES_AUTOVSCROLL
171 - ES_CENTER
172 + ES_DISABLENOSCROLL (scrollbar is always visible)
173 - ES_EX_NOCALLOLEINIT
174 - ES_LEFT
175 - ES_MULTILINE (currently single line controls aren't supported)
176 - ES_NOIME
177 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
178 - ES_RIGHT
179 - ES_SAVESEL
180 - ES_SELFIME
181 - ES_SUNKEN
182 - ES_VERTICAL
183 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
184 - WS_SETFONT
185 - WS_HSCROLL
186 + WS_VSCROLL
190 * RICHED20 TODO (incomplete):
192 * - messages/styles/notifications listed above
193 * - add remaining CHARFORMAT/PARAFORMAT fields
194 * - right/center align should strip spaces from the beginning
195 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196 * - COM interface (looks like a major pain in the TODO list)
197 * - calculate heights of pictures (half-done)
198 * - horizontal scrolling (not even started)
199 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200 * - find/replace
201 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202 * - italic caret with italic fonts
203 * - IME
204 * - most notifications aren't sent at all (the most important ones are)
205 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208 * - full justification
209 * - hyphenation
210 * - tables
211 * - ListBox & ComboBox not implemented
213 * Bugs that are probably fixed, but not so easy to verify:
214 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217 * - caret shouldn't be displayed when selection isn't empty
218 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219 * - undo for setting default format (done, might be buggy)
220 * - styles might be not released properly (looks like they work like charm, but who knows?
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM
228 #include "shlwapi.h"
229 #include "rtf.h"
230 #include "imm.h"
231 #include "res.h"
233 #define STACK_SIZE_DEFAULT 100
234 #define STACK_SIZE_MAX 1000
236 #define TEXT_LIMIT_DEFAULT 32767
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
248 int me_debug = 0;
249 HANDLE me_heap = NULL;
251 static BOOL ME_ListBoxRegistered = FALSE;
252 static BOOL ME_ComboBoxRegistered = FALSE;
254 static inline int is_version_nt(void)
256 return !(GetVersion() & 0x80000000);
259 static ME_TextBuffer *ME_MakeText(void) {
261 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
263 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
264 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
266 p1->prev = NULL;
267 p1->next = p2;
268 p2->prev = p1;
269 p2->next = NULL;
270 p1->member.para.next_para = p2;
271 p2->member.para.prev_para = p1;
272 p2->member.para.nCharOfs = 0;
274 buf->pFirst = p1;
275 buf->pLast = p2;
276 buf->pCharStyle = NULL;
278 return buf;
282 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
284 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
285 WCHAR *pText;
287 TRACE("%08x %p\n", dwFormat, stream);
289 do {
290 long nWideChars = 0;
292 if (!stream->dwSize)
294 ME_StreamInFill(stream);
295 if (stream->editstream->dwError)
296 break;
297 if (!stream->dwSize)
298 break;
301 if (!(dwFormat & SF_UNICODE))
303 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
304 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
305 pText = wszText;
307 else
309 nWideChars = stream->dwSize >> 1;
310 pText = (WCHAR *)stream->buffer;
313 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
314 if (stream->dwSize == 0)
315 break;
316 stream->dwSize = 0;
317 } while(1);
318 ME_CommitUndo(editor);
319 ME_UpdateRepaint(editor);
320 return 0;
323 static void ME_ApplyBorderProperties(RTF_Info *info,
324 ME_BorderRect *borderRect,
325 RTFBorder *borderDef)
327 int i, colorNum;
328 ME_Border *pBorders[] = {&borderRect->top,
329 &borderRect->left,
330 &borderRect->bottom,
331 &borderRect->right};
332 for (i = 0; i < 4; i++)
334 RTFColor *colorDef = info->colorList;
335 pBorders[i]->width = borderDef[i].width;
336 colorNum = borderDef[i].color;
337 while (colorDef && colorDef->rtfCNum != colorNum)
338 colorDef = colorDef->rtfNextColor;
339 if (colorDef)
340 pBorders[i]->colorRef = RGB(
341 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
342 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
343 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
344 else
345 pBorders[i]->colorRef = RGB(0, 0, 0);
349 static void ME_RTFCharAttrHook(RTF_Info *info)
351 CHARFORMAT2W fmt;
352 fmt.cbSize = sizeof(fmt);
353 fmt.dwMask = 0;
354 fmt.dwEffects = 0;
356 switch(info->rtfMinor)
358 case rtfPlain:
359 /* FIXME add more flags once they're implemented */
360 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
361 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
362 fmt.yHeight = 12*20; /* 12pt */
363 fmt.wWeight = FW_NORMAL;
364 fmt.bUnderlineType = CFU_UNDERLINENONE;
365 break;
366 case rtfBold:
367 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
368 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
369 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
370 break;
371 case rtfItalic:
372 fmt.dwMask = CFM_ITALIC;
373 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
374 break;
375 case rtfUnderline:
376 fmt.dwMask = CFM_UNDERLINETYPE;
377 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
378 break;
379 case rtfDotUnderline:
380 fmt.dwMask = CFM_UNDERLINETYPE;
381 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
382 break;
383 case rtfDbUnderline:
384 fmt.dwMask = CFM_UNDERLINETYPE;
385 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
386 break;
387 case rtfWordUnderline:
388 fmt.dwMask = CFM_UNDERLINETYPE;
389 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
390 break;
391 case rtfNoUnderline:
392 fmt.dwMask = CFM_UNDERLINETYPE;
393 fmt.bUnderlineType = CFU_UNDERLINENONE;
394 break;
395 case rtfStrikeThru:
396 fmt.dwMask = CFM_STRIKEOUT;
397 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
398 break;
399 case rtfSubScript:
400 case rtfSuperScript:
401 case rtfSubScrShrink:
402 case rtfSuperScrShrink:
403 case rtfNoSuperSub:
404 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
405 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
406 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
407 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
408 break;
409 case rtfInvisible:
410 fmt.dwMask = CFM_HIDDEN;
411 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
412 break;
413 case rtfBackColor:
414 fmt.dwMask = CFM_BACKCOLOR;
415 fmt.dwEffects = 0;
416 if (info->rtfParam == 0)
417 fmt.dwEffects = CFE_AUTOBACKCOLOR;
418 else if (info->rtfParam != rtfNoParam)
420 RTFColor *c = RTFGetColor(info, info->rtfParam);
421 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
423 break;
424 case rtfForeColor:
425 fmt.dwMask = CFM_COLOR;
426 fmt.dwEffects = 0;
427 if (info->rtfParam == 0)
428 fmt.dwEffects = CFE_AUTOCOLOR;
429 else if (info->rtfParam != rtfNoParam)
431 RTFColor *c = RTFGetColor(info, info->rtfParam);
432 if (c)
433 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
434 else
435 fmt.crTextColor = 0;
437 break;
438 case rtfFontNum:
439 if (info->rtfParam != rtfNoParam)
441 RTFFont *f = RTFGetFont(info, info->rtfParam);
442 if (f)
444 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
445 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
446 fmt.bCharSet = f->rtfFCharSet;
447 fmt.dwMask = CFM_FACE | CFM_CHARSET;
448 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
451 break;
452 case rtfFontSize:
453 fmt.dwMask = CFM_SIZE;
454 if (info->rtfParam != rtfNoParam)
455 fmt.yHeight = info->rtfParam*10;
456 break;
458 if (fmt.dwMask) {
459 ME_Style *style2;
460 RTFFlushOutputBuffer(info);
461 /* FIXME too slow ? how come ? */
462 style2 = ME_ApplyStyle(info->style, &fmt);
463 ME_ReleaseStyle(info->style);
464 info->style = style2;
465 info->styleChanged = TRUE;
469 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
470 the same tags mean different things in different contexts */
471 static void ME_RTFParAttrHook(RTF_Info *info)
473 PARAFORMAT2 fmt;
474 fmt.cbSize = sizeof(fmt);
475 fmt.dwMask = 0;
477 switch(info->rtfMinor)
479 case rtfParDef: /* restores default paragraph attributes */
480 if (!info->editor->bEmulateVersion10) /* v4.1 */
481 info->borderType = RTFBorderParaLeft;
482 else /* v1.0 - 3.0 */
483 info->borderType = RTFBorderParaTop;
484 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
485 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
486 PFM_STARTINDENT;
487 /* TODO: numbering, shading */
488 fmt.wAlignment = PFA_LEFT;
489 fmt.cTabCount = 0;
490 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
491 fmt.wBorderWidth = fmt.wBorders = 0;
492 fmt.wBorderSpace = 0;
493 fmt.bLineSpacingRule = 0;
494 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
495 fmt.dyLineSpacing = 0;
496 if (!info->editor->bEmulateVersion10) /* v4.1 */
498 if (info->tableDef && info->tableDef->tableRowStart &&
499 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
501 ME_Cursor cursor;
502 ME_DisplayItem *para;
503 /* We are just after a table row. */
504 RTFFlushOutputBuffer(info);
505 cursor = info->editor->pCursors[0];
506 para = ME_GetParagraph(cursor.pRun);
507 if (para == info->tableDef->tableRowStart->member.para.next_para
508 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
510 /* Since the table row end, no text has been inserted, and the \intbl
511 * control word has not be used. We can confirm that we are not in a
512 * table anymore.
514 info->tableDef->tableRowStart = NULL;
515 info->canInheritInTbl = FALSE;
518 } else { /* v1.0 - v3.0 */
519 fmt.dwMask |= PFM_TABLE;
520 fmt.wEffects &= ~PFE_TABLE;
522 break;
523 case rtfNestLevel:
524 if (!info->editor->bEmulateVersion10) /* v4.1 */
526 while (info->rtfParam > info->nestingLevel) {
527 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
528 ZeroMemory(tableDef, sizeof(RTFTable));
529 tableDef->parent = info->tableDef;
530 info->tableDef = tableDef;
532 RTFFlushOutputBuffer(info);
533 if (tableDef->tableRowStart &&
534 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
536 ME_DisplayItem *para = tableDef->tableRowStart;
537 para = para->member.para.next_para;
538 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
539 tableDef->tableRowStart = para;
540 } else {
541 ME_Cursor cursor;
542 WCHAR endl = '\r';
543 cursor = info->editor->pCursors[0];
544 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
545 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
546 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
549 info->nestingLevel++;
551 info->canInheritInTbl = FALSE;
553 break;
554 case rtfInTable:
556 if (!info->editor->bEmulateVersion10) /* v4.1 */
558 if (info->nestingLevel < 1)
560 RTFTable *tableDef;
561 if (!info->tableDef)
563 info->tableDef = ALLOC_OBJ(RTFTable);
564 ZeroMemory(info->tableDef, sizeof(RTFTable));
566 tableDef = info->tableDef;
567 RTFFlushOutputBuffer(info);
568 if (tableDef->tableRowStart &&
569 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
571 ME_DisplayItem *para = tableDef->tableRowStart;
572 para = para->member.para.next_para;
573 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
574 tableDef->tableRowStart = para;
575 } else {
576 ME_Cursor cursor;
577 WCHAR endl = '\r';
578 cursor = info->editor->pCursors[0];
579 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
580 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
581 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
583 info->nestingLevel = 1;
584 info->canInheritInTbl = TRUE;
586 return;
587 } else { /* v1.0 - v3.0 */
588 fmt.dwMask |= PFM_TABLE;
589 fmt.wEffects |= PFE_TABLE;
591 break;
593 case rtfFirstIndent:
594 ME_GetSelectionParaFormat(info->editor, &fmt);
595 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
596 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
597 fmt.dxOffset = -info->rtfParam;
598 break;
599 case rtfLeftIndent:
600 ME_GetSelectionParaFormat(info->editor, &fmt);
601 fmt.dwMask = PFM_STARTINDENT;
602 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
603 break;
604 case rtfRightIndent:
605 fmt.dwMask = PFM_RIGHTINDENT;
606 fmt.dxRightIndent = info->rtfParam;
607 break;
608 case rtfQuadLeft:
609 case rtfQuadJust:
610 fmt.dwMask = PFM_ALIGNMENT;
611 fmt.wAlignment = PFA_LEFT;
612 break;
613 case rtfQuadRight:
614 fmt.dwMask = PFM_ALIGNMENT;
615 fmt.wAlignment = PFA_RIGHT;
616 break;
617 case rtfQuadCenter:
618 fmt.dwMask = PFM_ALIGNMENT;
619 fmt.wAlignment = PFA_CENTER;
620 break;
621 case rtfTabPos:
622 ME_GetSelectionParaFormat(info->editor, &fmt);
623 if (!(fmt.dwMask & PFM_TABSTOPS))
625 fmt.cTabCount = 0;
627 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
628 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
629 fmt.dwMask = PFM_TABSTOPS;
630 break;
631 case rtfKeep:
632 fmt.dwMask = PFM_KEEP;
633 fmt.wEffects = PFE_KEEP;
634 break;
635 case rtfNoWidowControl:
636 fmt.dwMask = PFM_NOWIDOWCONTROL;
637 fmt.wEffects = PFE_NOWIDOWCONTROL;
638 break;
639 case rtfKeepNext:
640 fmt.dwMask = PFM_KEEPNEXT;
641 fmt.wEffects = PFE_KEEPNEXT;
642 break;
643 case rtfSpaceAfter:
644 fmt.dwMask = PFM_SPACEAFTER;
645 fmt.dySpaceAfter = info->rtfParam;
646 break;
647 case rtfSpaceBefore:
648 fmt.dwMask = PFM_SPACEBEFORE;
649 fmt.dySpaceBefore = info->rtfParam;
650 break;
651 case rtfSpaceBetween:
652 fmt.dwMask = PFM_LINESPACING;
653 if ((int)info->rtfParam > 0)
655 fmt.dyLineSpacing = info->rtfParam;
656 fmt.bLineSpacingRule = 3;
658 else
660 fmt.dyLineSpacing = info->rtfParam;
661 fmt.bLineSpacingRule = 4;
663 case rtfSpaceMultiply:
664 fmt.dwMask = PFM_LINESPACING;
665 fmt.dyLineSpacing = info->rtfParam * 20;
666 fmt.bLineSpacingRule = 5;
667 break;
668 case rtfParBullet:
669 fmt.dwMask = PFM_NUMBERING;
670 fmt.wNumbering = PFN_BULLET;
671 break;
672 case rtfParSimple:
673 fmt.dwMask = PFM_NUMBERING;
674 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
675 break;
676 case rtfParNumDecimal:
677 fmt.dwMask = PFM_NUMBERING;
678 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
679 break;
680 case rtfParNumIndent:
681 fmt.dwMask = PFM_NUMBERINGTAB;
682 fmt.wNumberingTab = info->rtfParam;
683 break;
684 case rtfParNumStartAt:
685 fmt.dwMask = PFM_NUMBERINGSTART;
686 fmt.wNumberingStart = info->rtfParam;
687 break;
688 case rtfBorderLeft:
689 info->borderType = RTFBorderParaLeft;
690 ME_GetSelectionParaFormat(info->editor, &fmt);
691 if (!(fmt.dwMask & PFM_BORDER))
693 fmt.wBorderSpace = 0;
694 fmt.wBorderWidth = 1;
695 fmt.wBorders = 0;
697 fmt.wBorders |= 1;
698 fmt.dwMask = PFM_BORDER;
699 break;
700 case rtfBorderRight:
701 info->borderType = RTFBorderParaRight;
702 ME_GetSelectionParaFormat(info->editor, &fmt);
703 if (!(fmt.dwMask & PFM_BORDER))
705 fmt.wBorderSpace = 0;
706 fmt.wBorderWidth = 1;
707 fmt.wBorders = 0;
709 fmt.wBorders |= 2;
710 fmt.dwMask = PFM_BORDER;
711 break;
712 case rtfBorderTop:
713 info->borderType = RTFBorderParaTop;
714 ME_GetSelectionParaFormat(info->editor, &fmt);
715 if (!(fmt.dwMask & PFM_BORDER))
717 fmt.wBorderSpace = 0;
718 fmt.wBorderWidth = 1;
719 fmt.wBorders = 0;
721 fmt.wBorders |= 4;
722 fmt.dwMask = PFM_BORDER;
723 break;
724 case rtfBorderBottom:
725 info->borderType = RTFBorderParaBottom;
726 ME_GetSelectionParaFormat(info->editor, &fmt);
727 if (!(fmt.dwMask & PFM_BORDER))
729 fmt.wBorderSpace = 0;
730 fmt.wBorderWidth = 1;
731 fmt.wBorders = 0;
733 fmt.wBorders |= 8;
734 fmt.dwMask = PFM_BORDER;
735 break;
736 case rtfBorderSingle:
737 ME_GetSelectionParaFormat(info->editor, &fmt);
738 /* we assume that borders have been created before (RTF spec) */
739 fmt.wBorders &= ~0x700;
740 fmt.wBorders |= 1 << 8;
741 fmt.dwMask = PFM_BORDER;
742 break;
743 case rtfBorderThick:
744 ME_GetSelectionParaFormat(info->editor, &fmt);
745 /* we assume that borders have been created before (RTF spec) */
746 fmt.wBorders &= ~0x700;
747 fmt.wBorders |= 2 << 8;
748 fmt.dwMask = PFM_BORDER;
749 break;
750 case rtfBorderShadow:
751 ME_GetSelectionParaFormat(info->editor, &fmt);
752 /* we assume that borders have been created before (RTF spec) */
753 fmt.wBorders &= ~0x700;
754 fmt.wBorders |= 10 << 8;
755 fmt.dwMask = PFM_BORDER;
756 break;
757 case rtfBorderDouble:
758 ME_GetSelectionParaFormat(info->editor, &fmt);
759 /* we assume that borders have been created before (RTF spec) */
760 fmt.wBorders &= ~0x700;
761 fmt.wBorders |= 7 << 8;
762 fmt.dwMask = PFM_BORDER;
763 break;
764 case rtfBorderDot:
765 ME_GetSelectionParaFormat(info->editor, &fmt);
766 /* we assume that borders have been created before (RTF spec) */
767 fmt.wBorders &= ~0x700;
768 fmt.wBorders |= 11 << 8;
769 fmt.dwMask = PFM_BORDER;
770 break;
771 case rtfBorderWidth:
773 int borderSide = info->borderType & RTFBorderSideMask;
774 RTFTable *tableDef = info->tableDef;
775 ME_GetSelectionParaFormat(info->editor, &fmt);
776 /* we assume that borders have been created before (RTF spec) */
777 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
778 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
780 RTFBorder *border;
781 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
782 break;
783 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
784 border->width = info->rtfParam;
785 break;
787 fmt.dwMask = PFM_BORDER;
788 break;
790 case rtfBorderSpace:
791 ME_GetSelectionParaFormat(info->editor, &fmt);
792 /* we assume that borders have been created before (RTF spec) */
793 fmt.wBorderSpace = info->rtfParam;
794 fmt.dwMask = PFM_BORDER;
795 break;
796 case rtfBorderColor:
798 RTFTable *tableDef = info->tableDef;
799 int borderSide = info->borderType & RTFBorderSideMask;
800 int borderType = info->borderType & RTFBorderTypeMask;
801 switch(borderType)
803 case RTFBorderTypePara:
804 if (!info->editor->bEmulateVersion10) /* v4.1 */
805 break;
806 /* v1.0 - 3.0 treat paragraph and row borders the same. */
807 case RTFBorderTypeRow:
808 if (tableDef) {
809 tableDef->border[borderSide].color = info->rtfParam;
811 break;
812 case RTFBorderTypeCell:
813 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
814 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
816 break;
818 break;
821 if (fmt.dwMask) {
822 RTFFlushOutputBuffer(info);
823 /* FIXME too slow ? how come ?*/
824 ME_SetSelectionParaFormat(info->editor, &fmt);
828 static void ME_RTFTblAttrHook(RTF_Info *info)
830 switch (info->rtfMinor)
832 case rtfRowDef:
834 if (!info->editor->bEmulateVersion10) /* v4.1 */
835 info->borderType = 0; /* Not sure */
836 else /* v1.0 - 3.0 */
837 info->borderType = RTFBorderRowTop;
838 if (!info->tableDef) {
839 info->tableDef = ME_MakeTableDef(info->editor);
840 } else {
841 ME_InitTableDef(info->editor, info->tableDef);
843 break;
845 case rtfCellPos:
846 if (!info->tableDef)
848 info->tableDef = ME_MakeTableDef(info->editor);
850 if (info->tableDef->numCellsDefined >= MAX_TABLE_CELLS)
851 break;
852 info->tableDef->cells[info->tableDef->numCellsDefined].rightBoundary = info->rtfParam;
854 /* Tab stops were used to store cell positions before v4.1 but v4.1
855 * still seems to set the tabstops without using them. */
856 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
857 PARAFORMAT2 *pFmt = para->member.para.pFmt;
858 int cellNum = info->tableDef->numCellsDefined;
859 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
860 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
862 info->tableDef->numCellsDefined++;
863 break;
864 case rtfRowBordTop:
865 info->borderType = RTFBorderRowTop;
866 break;
867 case rtfRowBordLeft:
868 info->borderType = RTFBorderRowLeft;
869 break;
870 case rtfRowBordBottom:
871 info->borderType = RTFBorderRowBottom;
872 break;
873 case rtfRowBordRight:
874 info->borderType = RTFBorderRowRight;
875 break;
876 case rtfCellBordTop:
877 info->borderType = RTFBorderCellTop;
878 break;
879 case rtfCellBordLeft:
880 info->borderType = RTFBorderCellLeft;
881 break;
882 case rtfCellBordBottom:
883 info->borderType = RTFBorderCellBottom;
884 break;
885 case rtfCellBordRight:
886 info->borderType = RTFBorderCellRight;
887 break;
888 case rtfRowGapH:
889 if (info->tableDef)
890 info->tableDef->gapH = info->rtfParam;
891 break;
892 case rtfRowLeftEdge:
893 if (info->tableDef)
894 info->tableDef->leftEdge = info->rtfParam;
895 break;
899 static void ME_RTFSpecialCharHook(RTF_Info *info)
901 RTFTable *tableDef = info->tableDef;
902 switch (info->rtfMinor)
904 case rtfNestCell:
905 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
906 break;
907 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
908 case rtfCell:
909 if (!tableDef)
910 break;
911 RTFFlushOutputBuffer(info);
912 if (!info->editor->bEmulateVersion10) { /* v4.1 */
913 if (tableDef->tableRowStart)
915 if (!info->nestingLevel &&
916 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
918 ME_DisplayItem *para = tableDef->tableRowStart;
919 para = para->member.para.next_para;
920 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
921 tableDef->tableRowStart = para;
922 info->nestingLevel = 1;
924 ME_InsertTableCellFromCursor(info->editor);
926 } else { /* v1.0 - v3.0 */
927 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
928 PARAFORMAT2 *pFmt = para->member.para.pFmt;
929 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
930 tableDef->numCellsInserted < tableDef->numCellsDefined)
932 WCHAR tab = '\t';
933 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
934 tableDef->numCellsInserted++;
937 break;
938 case rtfNestRow:
939 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
940 break;
941 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
942 case rtfRow:
944 ME_DisplayItem *para, *cell, *run;
945 int i;
947 if (!tableDef)
948 break;
949 RTFFlushOutputBuffer(info);
950 if (!info->editor->bEmulateVersion10) { /* v4.1 */
951 if (!tableDef->tableRowStart)
952 break;
953 if (!info->nestingLevel &&
954 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
956 para = tableDef->tableRowStart;
957 para = para->member.para.next_para;
958 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
959 tableDef->tableRowStart = para;
960 info->nestingLevel++;
962 para = tableDef->tableRowStart;
963 cell = ME_FindItemFwd(para, diCell);
964 assert(cell && !cell->member.cell.prev_cell);
965 if (tableDef->numCellsDefined < 1)
967 /* 2000 twips appears to be the cell size that native richedit uses
968 * when no cell sizes are specified. */
969 const int defaultCellSize = 2000;
970 int nRightBoundary = defaultCellSize;
971 cell->member.cell.nRightBoundary = nRightBoundary;
972 while (cell->member.cell.next_cell) {
973 cell = cell->member.cell.next_cell;
974 nRightBoundary += defaultCellSize;
975 cell->member.cell.nRightBoundary = nRightBoundary;
977 para = ME_InsertTableCellFromCursor(info->editor);
978 cell = para->member.para.pCell;
979 cell->member.cell.nRightBoundary = nRightBoundary;
980 } else {
981 for (i = 0; i < tableDef->numCellsDefined; i++)
983 RTFCell *cellDef = &tableDef->cells[i];
984 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
985 ME_ApplyBorderProperties(info, &cell->member.cell.border,
986 cellDef->border);
987 cell = cell->member.cell.next_cell;
988 if (!cell)
990 para = ME_InsertTableCellFromCursor(info->editor);
991 cell = para->member.para.pCell;
994 /* Cell for table row delimiter is empty */
995 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
998 run = ME_FindItemFwd(cell, diRun);
999 if (info->editor->pCursors[0].pRun != run ||
1000 info->editor->pCursors[0].nOffset)
1002 int nOfs, nChars;
1003 /* Delete inserted cells that aren't defined. */
1004 info->editor->pCursors[1].pRun = run;
1005 info->editor->pCursors[1].nOffset = 0;
1006 nOfs = ME_GetCursorOfs(info->editor, 1);
1007 nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
1008 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
1011 para = ME_InsertTableRowEndFromCursor(info->editor);
1012 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1013 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1014 ME_ApplyBorderProperties(info, &para->member.para.border,
1015 tableDef->border);
1016 info->nestingLevel--;
1017 if (!info->nestingLevel)
1019 if (info->canInheritInTbl) {
1020 tableDef->tableRowStart = para;
1021 } else {
1022 while (info->tableDef) {
1023 tableDef = info->tableDef;
1024 info->tableDef = tableDef->parent;
1025 heap_free(tableDef);
1028 } else {
1029 info->tableDef = tableDef->parent;
1030 heap_free(tableDef);
1032 } else { /* v1.0 - v3.0 */
1033 WCHAR endl = '\r';
1034 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1035 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1036 pFmt->dxOffset = info->tableDef->gapH;
1037 pFmt->dxStartIndent = info->tableDef->leftEdge;
1039 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1040 ME_ApplyBorderProperties(info, &para->member.para.border,
1041 tableDef->border);
1042 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1044 WCHAR tab = '\t';
1045 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1046 tableDef->numCellsInserted++;
1048 pFmt->cTabCount = tableDef->numCellsDefined;
1049 if (!tableDef->numCellsDefined)
1050 pFmt->wEffects &= ~PFE_TABLE;
1051 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1052 tableDef->numCellsInserted = 0;
1054 break;
1056 case rtfTab:
1057 case rtfPar:
1058 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1059 ME_DisplayItem *para;
1060 PARAFORMAT2 *pFmt;
1061 RTFFlushOutputBuffer(info);
1062 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1063 pFmt = para->member.para.pFmt;
1064 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1066 /* rtfPar is treated like a space within a table. */
1067 info->rtfClass = rtfText;
1068 info->rtfMajor = ' ';
1070 else if (info->rtfMinor == rtfPar && tableDef)
1071 tableDef->numCellsInserted = 0;
1073 break;
1077 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1078 const SIZEL* sz)
1080 LPOLEOBJECT lpObject = NULL;
1081 LPSTORAGE lpStorage = NULL;
1082 LPOLECLIENTSITE lpClientSite = NULL;
1083 LPDATAOBJECT lpDataObject = NULL;
1084 LPOLECACHE lpOleCache = NULL;
1085 STGMEDIUM stgm;
1086 FORMATETC fm;
1087 CLSID clsid;
1088 BOOL ret = FALSE;
1089 DWORD conn;
1091 if (hemf)
1093 stgm.tymed = TYMED_ENHMF;
1094 stgm.u.hEnhMetaFile = hemf;
1095 fm.cfFormat = CF_ENHMETAFILE;
1097 else if (hbmp)
1099 stgm.tymed = TYMED_GDI;
1100 stgm.u.hBitmap = hbmp;
1101 fm.cfFormat = CF_BITMAP;
1103 stgm.pUnkForRelease = NULL;
1105 fm.ptd = NULL;
1106 fm.dwAspect = DVASPECT_CONTENT;
1107 fm.lindex = -1;
1108 fm.tymed = stgm.tymed;
1110 if (!info->lpRichEditOle)
1112 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1115 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1116 #if 0
1117 /* FIXME: enable it when rich-edit properly implements this method */
1118 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1119 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1120 #endif
1121 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1122 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1123 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1124 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1125 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1127 REOBJECT reobject;
1129 reobject.cbStruct = sizeof(reobject);
1130 reobject.cp = REO_CP_SELECTION;
1131 reobject.clsid = clsid;
1132 reobject.poleobj = lpObject;
1133 reobject.pstg = lpStorage;
1134 reobject.polesite = lpClientSite;
1135 /* convert from twips to .01 mm */
1136 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1137 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1138 reobject.dvaspect = DVASPECT_CONTENT;
1139 reobject.dwFlags = 0; /* FIXME */
1140 reobject.dwUser = 0;
1142 /* FIXME: could be simpler */
1143 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1146 if (lpObject) IOleObject_Release(lpObject);
1147 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1148 if (lpStorage) IStorage_Release(lpStorage);
1149 if (lpDataObject) IDataObject_Release(lpDataObject);
1150 if (lpOleCache) IOleCache_Release(lpOleCache);
1152 return ret;
1155 static void ME_RTFReadPictGroup(RTF_Info *info)
1157 SIZEL sz;
1158 BYTE* buffer = NULL;
1159 unsigned bufsz, bufidx;
1160 BOOL flip;
1161 BYTE val;
1162 METAFILEPICT mfp;
1163 HENHMETAFILE hemf;
1164 HBITMAP hbmp;
1165 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1167 RTFGetToken (info);
1168 if (info->rtfClass == rtfEOF)
1169 return;
1170 mfp.mm = MM_TEXT;
1171 /* fetch picture type */
1172 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1174 mfp.mm = info->rtfParam;
1175 gfx = gfx_metafile;
1177 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1179 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1180 gfx = gfx_dib;
1182 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1184 gfx = gfx_enhmetafile;
1186 else
1188 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1189 goto skip_group;
1191 sz.cx = sz.cy = 0;
1192 /* fetch picture attributes */
1193 for (;;)
1195 RTFGetToken (info);
1196 if (info->rtfClass == rtfEOF)
1197 return;
1198 if (info->rtfClass == rtfText)
1199 break;
1200 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1202 ERR("Expected picture attribute (%d %d)\n",
1203 info->rtfClass, info->rtfMajor);
1204 goto skip_group;
1206 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1208 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1210 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1212 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1214 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1215 sz.cx = info->rtfParam;
1216 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1217 sz.cy = info->rtfParam;
1218 else
1219 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1221 /* fetch picture data */
1222 bufsz = 1024;
1223 bufidx = 0;
1224 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1225 val = info->rtfMajor;
1226 for (flip = TRUE;; flip = !flip)
1228 RTFGetToken (info);
1229 if (info->rtfClass == rtfEOF)
1231 HeapFree(GetProcessHeap(), 0, buffer);
1232 return; /* Warn ?? */
1234 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1235 break;
1236 if (info->rtfClass != rtfText) goto skip_group;
1237 if (flip)
1239 if (bufidx >= bufsz &&
1240 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1241 goto skip_group;
1242 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1244 else
1245 val = info->rtfMajor;
1247 if (flip) FIXME("wrong hex string\n");
1249 switch (gfx)
1251 case gfx_enhmetafile:
1252 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1253 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1254 break;
1255 case gfx_metafile:
1256 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1257 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1258 break;
1259 case gfx_dib:
1261 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1262 HDC hdc = GetDC(0);
1263 unsigned nc = bi->bmiHeader.biClrUsed;
1265 /* not quite right, especially for bitfields type of compression */
1266 if (!nc && bi->bmiHeader.biBitCount <= 8)
1267 nc = 1 << bi->bmiHeader.biBitCount;
1268 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1269 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1270 bi, DIB_RGB_COLORS)))
1271 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1272 ReleaseDC(0, hdc);
1274 break;
1275 default:
1276 break;
1278 HeapFree(GetProcessHeap(), 0, buffer);
1279 RTFRouteToken (info); /* feed "}" back to router */
1280 return;
1281 skip_group:
1282 HeapFree(GetProcessHeap(), 0, buffer);
1283 RTFSkipGroup(info);
1284 RTFRouteToken(info); /* feed "}" back to router */
1287 /* for now, lookup the \result part and use it, whatever the object */
1288 static void ME_RTFReadObjectGroup(RTF_Info *info)
1290 for (;;)
1292 RTFGetToken (info);
1293 if (info->rtfClass == rtfEOF)
1294 return;
1295 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1296 break;
1297 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1299 RTFGetToken (info);
1300 if (info->rtfClass == rtfEOF)
1301 return;
1302 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1304 int level = 1;
1306 while (RTFGetToken (info) != rtfEOF)
1308 if (info->rtfClass == rtfGroup)
1310 if (info->rtfMajor == rtfBeginGroup) level++;
1311 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1313 RTFRouteToken(info);
1316 else RTFSkipGroup(info);
1317 continue;
1319 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1321 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1322 return;
1325 RTFRouteToken(info); /* feed "}" back to router */
1328 static void ME_RTFReadHook(RTF_Info *info) {
1329 switch(info->rtfClass)
1331 case rtfGroup:
1332 switch(info->rtfMajor)
1334 case rtfBeginGroup:
1335 if (info->stackTop < maxStack) {
1336 info->stack[info->stackTop].fmt = info->style->fmt;
1337 info->stack[info->stackTop].codePage = info->codePage;
1338 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1340 info->stackTop++;
1341 info->styleChanged = FALSE;
1342 break;
1343 case rtfEndGroup:
1345 ME_Style *s;
1346 RTFFlushOutputBuffer(info);
1347 info->stackTop--;
1348 if (info->stackTop<=0) {
1349 info->rtfClass = rtfEOF;
1350 return;
1352 assert(info->stackTop >= 0);
1353 if (info->styleChanged)
1355 /* FIXME too slow ? how come ? */
1356 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1357 ME_ReleaseStyle(info->style);
1358 info->style = s;
1359 info->codePage = info->stack[info->stackTop].codePage;
1360 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1362 break;
1365 break;
1366 case rtfControl:
1367 switch(info->rtfMajor)
1369 case rtfCharAttr:
1370 ME_RTFCharAttrHook(info);
1371 break;
1372 case rtfParAttr:
1373 ME_RTFParAttrHook(info);
1374 break;
1375 case rtfTblAttr:
1376 ME_RTFTblAttrHook(info);
1377 break;
1378 case rtfSpecialChar:
1379 ME_RTFSpecialCharHook(info);
1380 break;
1382 break;
1386 void
1387 ME_StreamInFill(ME_InStream *stream)
1389 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1390 (BYTE *)stream->buffer,
1391 sizeof(stream->buffer),
1392 (LONG *)&stream->dwSize);
1393 stream->dwUsed = 0;
1396 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1398 RTF_Info parser;
1399 ME_Style *style;
1400 int from, to, to2, nUndoMode;
1401 int nEventMask = editor->nEventMask;
1402 ME_InStream inStream;
1403 BOOL invalidRTF = FALSE;
1405 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1406 editor->nEventMask = 0;
1408 ME_GetSelection(editor, &from, &to);
1409 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1410 style = ME_GetSelectionInsertStyle(editor);
1412 ME_InternalDeleteText(editor, from, to-from, FALSE);
1414 /* Don't insert text at the end of the table row */
1415 if (!editor->bEmulateVersion10) { /* v4.1 */
1416 ME_DisplayItem *para = ME_GetParagraph(editor->pCursors->pRun);
1417 if (para->member.para.nFlags & MEPF_ROWEND)
1419 para = para->member.para.next_para;
1420 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1421 editor->pCursors[0].nOffset = 0;
1423 if (para->member.para.nFlags & MEPF_ROWSTART)
1425 para = para->member.para.next_para;
1426 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1427 editor->pCursors[0].nOffset = 0;
1429 editor->pCursors[1] = editor->pCursors[0];
1430 } else { /* v1.0 - 3.0 */
1431 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1432 ME_IsInTable(editor->pCursors[0].pRun))
1433 return 0;
1436 else {
1437 ME_DisplayItem *para_item;
1438 style = editor->pBuffer->pDefaultStyle;
1439 ME_AddRefStyle(style);
1440 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1441 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1442 from = to = 0;
1443 ME_ClearTempStyle(editor);
1445 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1446 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1450 /* Back up undo mode to a local variable */
1451 nUndoMode = editor->nUndoMode;
1453 /* Only create an undo if SFF_SELECTION is set */
1454 if (!(format & SFF_SELECTION))
1455 editor->nUndoMode = umIgnore;
1457 inStream.editstream = stream;
1458 inStream.editstream->dwError = 0;
1459 inStream.dwSize = 0;
1460 inStream.dwUsed = 0;
1462 if (format & SF_RTF)
1464 /* Check if it's really RTF, and if it is not, use plain text */
1465 ME_StreamInFill(&inStream);
1466 if (!inStream.editstream->dwError)
1468 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1469 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1471 invalidRTF = TRUE;
1472 inStream.editstream->dwError = -16;
1477 if (!invalidRTF && !inStream.editstream->dwError)
1479 if (format & SF_RTF) {
1480 ME_DisplayItem *para;
1482 /* setup the RTF parser */
1483 memset(&parser, 0, sizeof parser);
1484 RTFSetEditStream(&parser, &inStream);
1485 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1486 parser.hwndEdit = editor->hWnd;
1487 parser.editor = editor;
1488 parser.style = style;
1489 WriterInit(&parser);
1490 RTFInit(&parser);
1491 RTFSetReadHook(&parser, ME_RTFReadHook);
1492 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1493 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1494 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1495 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1496 BeginFile(&parser);
1498 /* do the parsing */
1499 RTFRead(&parser);
1500 RTFFlushOutputBuffer(&parser);
1501 if (!editor->bEmulateVersion10) { /* v4.1 */
1502 if (parser.tableDef && parser.tableDef->tableRowStart)
1504 /* Delete any incomplete table row at the end of the rich text. */
1505 int nOfs, nChars;
1506 ME_DisplayItem *pCell;
1508 para = parser.tableDef->tableRowStart;
1510 parser.rtfMinor = rtfRow;
1511 /* Complete the table row before deleting it.
1512 * By doing it this way we will have the current paragraph format set
1513 * properly to reflect that is not in the complete table, and undo items
1514 * will be added for this change to the current paragraph format. */
1515 if (parser.nestingLevel > 0)
1517 while (parser.nestingLevel--)
1518 ME_RTFSpecialCharHook(&parser);
1519 } else if (parser.canInheritInTbl) {
1520 ME_RTFSpecialCharHook(&parser);
1522 if (parser.tableDef && parser.tableDef->tableRowStart &&
1523 para->member.para.nFlags & MEPF_ROWEND)
1525 para = para->member.para.next_para;
1527 pCell = para->member.para.pCell;
1529 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1530 editor->pCursors[1].nOffset = 0;
1531 nOfs = ME_GetCursorOfs(editor, 1);
1532 nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1533 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1534 parser.tableDef->tableRowStart = NULL;
1537 ME_CheckTablesForCorruption(editor);
1538 RTFDestroy(&parser);
1539 if (parser.lpRichEditOle)
1540 IRichEditOle_Release(parser.lpRichEditOle);
1542 if (!inStream.editstream->dwError && parser.stackTop > 0)
1543 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1545 /* Remove last line break, as mandated by tests. This is not affected by
1546 CR/LF counters, since RTF streaming presents only \para tokens, which
1547 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1549 if (stripLastCR) {
1550 int newfrom, newto;
1551 ME_GetSelection(editor, &newfrom, &newto);
1552 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1553 WCHAR lastchar[3] = {'\0', '\0'};
1554 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1556 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1557 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1558 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1563 style = parser.style;
1565 else if (format & SF_TEXT)
1566 ME_StreamInText(editor, format, &inStream, style);
1567 else
1568 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1569 ME_GetSelection(editor, &to, &to2);
1570 /* put the cursor at the top */
1571 if (!(format & SFF_SELECTION))
1572 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1575 /* Restore saved undo mode */
1576 editor->nUndoMode = nUndoMode;
1578 /* even if we didn't add an undo, we need to commit anything on the stack */
1579 ME_CommitUndo(editor);
1581 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1582 if (!(format & SFF_SELECTION))
1583 ME_EmptyUndoStack(editor);
1585 ME_ReleaseStyle(style);
1586 editor->nEventMask = nEventMask;
1587 ME_UpdateRepaint(editor);
1588 if (!(format & SFF_SELECTION)) {
1589 ME_ClearTempStyle(editor);
1591 HideCaret(editor->hWnd);
1592 ME_MoveCaret(editor);
1593 ShowCaret(editor->hWnd);
1594 ME_SendSelChange(editor);
1595 ME_SendRequestResize(editor, FALSE);
1597 return 0;
1601 typedef struct tagME_RTFStringStreamStruct
1603 char *string;
1604 int pos;
1605 int length;
1606 } ME_RTFStringStreamStruct;
1608 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1610 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1611 int count;
1613 count = min(cb, pStruct->length - pStruct->pos);
1614 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1615 pStruct->pos += count;
1616 *pcb = count;
1617 return 0;
1620 static void
1621 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1623 EDITSTREAM es;
1624 ME_RTFStringStreamStruct data;
1626 data.string = string;
1627 data.length = strlen(string);
1628 data.pos = 0;
1629 es.dwCookie = (DWORD)&data;
1630 es.pfnCallback = ME_ReadFromRTFString;
1631 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1635 ME_DisplayItem *
1636 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1638 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1639 int runLength;
1641 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1642 item = ME_FindItemFwd(item, diParagraph);
1644 if (!item)
1645 return item;
1647 nOffset -= item->member.para.nCharOfs;
1648 if (nItemType == diParagraph) {
1649 if (nItemOffset)
1650 *nItemOffset = nOffset;
1651 return item;
1654 do {
1655 item = ME_FindItemFwd(item, diRun);
1656 runLength = ME_StrLen(item->member.run.strText);
1657 if (item->member.run.nFlags & MERF_ENDPARA)
1658 runLength = item->member.run.nCR + item->member.run.nLF;
1659 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1660 if (item) {
1661 nOffset -= item->member.run.nCharOfs;
1663 /* Special case: nOffset may not point exactly at the division between the
1664 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1665 into the next run, if one exists
1667 if ( item->member.run.nFlags & MERF_ENDPARA
1668 && nOffset == item->member.run.nCR
1669 && item->member.run.nLF > 0) {
1670 ME_DisplayItem *nextItem;
1671 nextItem = ME_FindItemFwd(item, diRun);
1672 if (nextItem) {
1673 nOffset = 0;
1674 item = nextItem;
1677 if (nItemOffset)
1678 *nItemOffset = nOffset;
1680 return item;
1684 static int
1685 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1687 const int nLen = lstrlenW(text);
1688 const int nTextLen = ME_GetTextLength(editor);
1689 int nStart, nEnd;
1690 int nMin, nMax;
1691 ME_DisplayItem *item;
1692 ME_DisplayItem *para;
1693 WCHAR wLastChar = ' ';
1695 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1696 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1698 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1699 FIXME("Flags 0x%08x not implemented\n",
1700 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1702 nMin = chrg->cpMin;
1703 if (chrg->cpMax == -1)
1704 nMax = nTextLen;
1705 else
1706 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1708 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1709 if (editor->bEmulateVersion10 && nMax == nTextLen)
1711 flags |= FR_DOWN;
1714 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1715 if (editor->bEmulateVersion10 && nMax < nMin)
1717 if (chrgText)
1719 chrgText->cpMin = -1;
1720 chrgText->cpMax = -1;
1722 return -1;
1725 /* when searching up, if cpMin < cpMax, then instead of searching
1726 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1727 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1728 * case, it is always bigger than cpMin.
1730 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1732 int nSwap = nMax;
1734 nMax = nMin > nTextLen ? nTextLen : nMin;
1735 if (nMin < nSwap || chrg->cpMax == -1)
1736 nMin = 0;
1737 else
1738 nMin = nSwap;
1741 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1743 if (chrgText)
1744 chrgText->cpMin = chrgText->cpMax = -1;
1745 return -1;
1748 if (flags & FR_DOWN) /* Forward search */
1750 /* If possible, find the character before where the search starts */
1751 if ((flags & FR_WHOLEWORD) && nMin)
1753 nStart = nMin - 1;
1754 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1755 if (!item)
1757 if (chrgText)
1758 chrgText->cpMin = chrgText->cpMax = -1;
1759 return -1;
1761 wLastChar = item->member.run.strText->szData[nStart];
1764 nStart = nMin;
1765 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1766 if (!item)
1768 if (chrgText)
1769 chrgText->cpMin = chrgText->cpMax = -1;
1770 return -1;
1773 para = ME_GetParagraph(item);
1774 while (item
1775 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1777 ME_DisplayItem *pCurItem = item;
1778 int nCurStart = nStart;
1779 int nMatched = 0;
1781 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1783 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1784 break;
1786 nMatched++;
1787 if (nMatched == nLen)
1789 ME_DisplayItem *pNextItem = pCurItem;
1790 int nNextStart = nCurStart;
1791 WCHAR wNextChar;
1793 /* Check to see if next character is a whitespace */
1794 if (flags & FR_WHOLEWORD)
1796 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1798 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1799 nNextStart = -nMatched;
1802 if (pNextItem)
1803 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1804 else
1805 wNextChar = ' ';
1807 if (isalnumW(wNextChar))
1808 break;
1811 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1812 if (chrgText)
1814 chrgText->cpMin = nStart;
1815 chrgText->cpMax = nStart + nLen;
1817 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1818 return nStart;
1820 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1822 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1823 para = ME_GetParagraph(pCurItem);
1824 nCurStart = -nMatched;
1827 if (pCurItem)
1828 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1829 else
1830 wLastChar = ' ';
1832 nStart++;
1833 if (nStart == ME_StrLen(item->member.run.strText))
1835 item = ME_FindItemFwd(item, diRun);
1836 para = ME_GetParagraph(item);
1837 nStart = 0;
1841 else /* Backward search */
1843 /* If possible, find the character after where the search ends */
1844 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1846 nEnd = nMax + 1;
1847 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1848 if (!item)
1850 if (chrgText)
1851 chrgText->cpMin = chrgText->cpMax = -1;
1852 return -1;
1854 wLastChar = item->member.run.strText->szData[nEnd];
1857 nEnd = nMax;
1858 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1859 if (!item)
1861 if (chrgText)
1862 chrgText->cpMin = chrgText->cpMax = -1;
1863 return -1;
1866 para = ME_GetParagraph(item);
1868 while (item
1869 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1871 ME_DisplayItem *pCurItem = item;
1872 int nCurEnd = nEnd;
1873 int nMatched = 0;
1875 if (nCurEnd - nMatched == 0)
1877 pCurItem = ME_FindItemBack(pCurItem, diRun);
1878 para = ME_GetParagraph(pCurItem);
1879 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1882 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1884 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1885 break;
1887 nMatched++;
1888 if (nMatched == nLen)
1890 ME_DisplayItem *pPrevItem = pCurItem;
1891 int nPrevEnd = nCurEnd;
1892 WCHAR wPrevChar;
1894 /* Check to see if previous character is a whitespace */
1895 if (flags & FR_WHOLEWORD)
1897 if (nPrevEnd - nMatched == 0)
1899 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1900 if (pPrevItem)
1901 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1904 if (pPrevItem)
1905 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1906 else
1907 wPrevChar = ' ';
1909 if (isalnumW(wPrevChar))
1910 break;
1913 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1914 if (chrgText)
1916 chrgText->cpMin = nStart;
1917 chrgText->cpMax = nStart + nLen;
1919 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1920 return nStart;
1922 if (nCurEnd - nMatched == 0)
1924 pCurItem = ME_FindItemBack(pCurItem, diRun);
1925 /* Don't care about pCurItem becoming NULL here; it's already taken
1926 * care of in the exterior loop condition */
1927 para = ME_GetParagraph(pCurItem);
1928 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1931 if (pCurItem)
1932 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1933 else
1934 wLastChar = ' ';
1936 nEnd--;
1937 if (nEnd < 0)
1939 item = ME_FindItemBack(item, diRun);
1940 para = ME_GetParagraph(item);
1941 nEnd = ME_StrLen(item->member.run.strText);
1945 TRACE("not found\n");
1946 if (chrgText)
1947 chrgText->cpMin = chrgText->cpMax = -1;
1948 return -1;
1951 /* helper to send a msg filter notification */
1952 static BOOL
1953 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1955 MSGFILTER msgf;
1957 msgf.nmhdr.hwndFrom = editor->hWnd;
1958 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1959 msgf.nmhdr.code = EN_MSGFILTER;
1960 msgf.msg = msg;
1962 msgf.wParam = *wParam;
1963 msgf.lParam = *lParam;
1964 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1965 return FALSE;
1966 *wParam = msgf.wParam;
1967 *lParam = msgf.lParam;
1968 msgf.wParam = *wParam;
1970 return TRUE;
1973 static BOOL
1974 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1976 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1977 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1979 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1980 editor->nSelectionType = stPosition;
1982 switch (nKey)
1984 case VK_LEFT:
1985 case VK_RIGHT:
1986 case VK_HOME:
1987 case VK_END:
1988 editor->nUDArrowX = -1;
1989 /* fall through */
1990 case VK_UP:
1991 case VK_DOWN:
1992 case VK_PRIOR:
1993 case VK_NEXT:
1994 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1995 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1996 return TRUE;
1997 case VK_BACK:
1998 case VK_DELETE:
1999 editor->nUDArrowX = -1;
2000 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2001 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
2002 return FALSE;
2003 if (ME_IsSelection(editor))
2005 ME_DeleteSelection(editor);
2006 ME_CommitUndo(editor);
2008 else if (nKey == VK_DELETE)
2010 /* Delete stops group typing.
2011 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2012 ME_DeleteTextAtCursor(editor, 1, 1);
2013 ME_CommitUndo(editor);
2015 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2017 BOOL bDeletionSucceeded;
2018 /* Backspace can be grouped for a single undo */
2019 ME_ContinueCoalescingTransaction(editor);
2020 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2021 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2022 /* Deletion was prevented so the cursor is moved back to where it was.
2023 * (e.g. this happens when trying to delete cell boundaries)
2025 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2027 ME_CommitCoalescingUndo(editor);
2029 else
2030 return TRUE;
2031 ME_UpdateSelectionLinkAttribute(editor);
2032 ME_UpdateRepaint(editor);
2033 ME_SendRequestResize(editor, FALSE);
2034 return TRUE;
2036 default:
2037 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2038 editor->nUDArrowX = -1;
2039 if (ctrl_is_down)
2041 if (nKey == 'W')
2043 CHARFORMAT2W chf;
2044 char buf[2048];
2045 chf.cbSize = sizeof(chf);
2047 ME_GetSelectionCharFormat(editor, &chf);
2048 ME_DumpStyleToBuf(&chf, buf);
2049 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2051 if (nKey == 'Q')
2053 ME_CheckCharOffsets(editor);
2057 return FALSE;
2060 /* Process the message and calculate the new click count.
2062 * returns: The click count if it is mouse down event, else returns 0. */
2063 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
2064 LPARAM lParam)
2066 static int clickNum = 0;
2067 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2068 return 0;
2070 if ((msg == WM_LBUTTONDBLCLK) ||
2071 (msg == WM_RBUTTONDBLCLK) ||
2072 (msg == WM_MBUTTONDBLCLK) ||
2073 (msg == WM_XBUTTONDBLCLK))
2075 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2078 if ((msg == WM_LBUTTONDOWN) ||
2079 (msg == WM_RBUTTONDOWN) ||
2080 (msg == WM_MBUTTONDOWN) ||
2081 (msg == WM_XBUTTONDOWN))
2083 static MSG prevClickMsg;
2084 MSG clickMsg;
2085 clickMsg.hwnd = hWnd;
2086 clickMsg.message = msg;
2087 clickMsg.wParam = wParam;
2088 clickMsg.lParam = lParam;
2089 clickMsg.time = GetMessageTime();
2090 clickMsg.pt.x = (short)LOWORD(lParam);
2091 clickMsg.pt.y = (short)HIWORD(lParam);
2092 if ((clickNum != 0) &&
2093 (clickMsg.message == prevClickMsg.message) &&
2094 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2095 (clickMsg.wParam == prevClickMsg.wParam) &&
2096 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2097 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2098 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2100 clickNum++;
2101 } else {
2102 clickNum = 1;
2104 prevClickMsg = clickMsg;
2105 } else {
2106 return 0;
2108 return clickNum;
2111 static BOOL ME_SetCursor(ME_TextEditor *editor)
2113 POINT pt;
2114 BOOL isExact;
2115 int offset;
2116 DWORD messagePos = GetMessagePos();
2117 pt.x = (short)LOWORD(messagePos);
2118 pt.y = (short)HIWORD(messagePos);
2119 ScreenToClient(editor->hWnd, &pt);
2120 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
2121 (pt.x < editor->selofs ||
2122 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
2124 SetCursor(hLeft);
2125 return TRUE;
2127 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2128 if (isExact)
2130 if (editor->AutoURLDetect_bEnable)
2132 ME_Cursor cursor;
2133 ME_Run *run;
2134 ME_CursorFromCharOfs(editor, offset, &cursor);
2135 run = &cursor.pRun->member.run;
2136 if (editor->AutoURLDetect_bEnable &&
2137 run->style->fmt.dwMask & CFM_LINK &&
2138 run->style->fmt.dwEffects & CFE_LINK)
2140 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
2141 return TRUE;
2144 if (ME_IsSelection(editor))
2146 int selStart, selEnd;
2147 ME_GetSelection(editor, &selStart, &selEnd);
2148 if (selStart <= offset && selEnd >= offset) {
2149 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2150 return TRUE;
2154 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
2155 return TRUE;
2158 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2160 CHARRANGE selrange;
2161 HMENU menu;
2162 int seltype = 0;
2163 if(!editor->lpOleCallback)
2164 return FALSE;
2165 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2166 if(selrange.cpMin == selrange.cpMax)
2167 seltype |= SEL_EMPTY;
2168 else
2170 /* FIXME: Handle objects */
2171 seltype |= SEL_TEXT;
2172 if(selrange.cpMax-selrange.cpMin > 1)
2173 seltype |= SEL_MULTICHAR;
2175 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2177 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2178 DestroyMenu(menu);
2180 return TRUE;
2183 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
2184 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2185 int i;
2186 ed->hWnd = hWnd;
2187 ed->bEmulateVersion10 = FALSE;
2188 ed->pBuffer = ME_MakeText();
2189 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2190 ME_MakeFirstParagraph(ed);
2191 /* The four cursors are for:
2192 * 0 - The position where the caret is shown
2193 * 1 - The anchored end of the selection (for normal selection)
2194 * 2 & 3 - The anchored start and end respectively for word, line,
2195 * or paragraph selection.
2197 ed->nCursors = 4;
2198 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2199 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2200 ed->pCursors[0].nOffset = 0;
2201 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2202 ed->pCursors[1].nOffset = 0;
2203 ed->pCursors[2] = ed->pCursors[0];
2204 ed->pCursors[3] = ed->pCursors[1];
2205 ed->nLastTotalLength = ed->nTotalLength = 0;
2206 ed->nHeight = 0;
2207 ed->nUDArrowX = -1;
2208 ed->nSequence = 0;
2209 ed->rgbBackColor = -1;
2210 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2211 ed->bCaretAtEnd = FALSE;
2212 ed->nEventMask = 0;
2213 ed->nModifyStep = 0;
2214 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2215 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2216 ed->nUndoStackSize = 0;
2217 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2218 ed->nUndoMode = umAddToUndo;
2219 ed->nParagraphs = 1;
2220 ed->nLastSelStart = ed->nLastSelEnd = 0;
2221 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2222 ed->bRedraw = TRUE;
2223 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
2224 ed->bHideSelection = FALSE;
2225 ed->nInvalidOfs = -1;
2226 ed->pfnWordBreak = NULL;
2227 ed->lpOleCallback = NULL;
2228 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2229 ed->AutoURLDetect_bEnable = FALSE;
2230 ed->bHaveFocus = FALSE;
2231 for (i=0; i<HFONT_CACHE_SIZE; i++)
2233 ed->pFontCache[i].nRefs = 0;
2234 ed->pFontCache[i].nAge = 0;
2235 ed->pFontCache[i].hFont = NULL;
2238 ME_CheckCharOffsets(ed);
2239 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
2240 ed->selofs = SELECTIONBAR_WIDTH;
2241 else
2242 ed->selofs = 0;
2243 ed->nSelectionType = stPosition;
2245 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
2246 ed->cPasswordMask = '*';
2247 else
2248 ed->cPasswordMask = 0;
2250 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2252 /* Default vertical scrollbar information */
2253 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2254 ed->vert_si.nMin = 0;
2255 ed->vert_si.nMax = 0;
2256 ed->vert_si.nPage = 0;
2257 ed->vert_si.nPos = 0;
2259 OleInitialize(NULL);
2261 return ed;
2264 typedef struct tagME_GlobalDestStruct
2266 HGLOBAL hData;
2267 int nLength;
2268 } ME_GlobalDestStruct;
2270 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2272 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2273 int i;
2274 WORD *pSrc, *pDest;
2276 cb = cb >> 1;
2277 pDest = (WORD *)lpBuff;
2278 pSrc = (WORD *)GlobalLock(pData->hData);
2279 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2280 pDest[i] = pSrc[pData->nLength+i];
2282 pData->nLength += i;
2283 *pcb = 2*i;
2284 GlobalUnlock(pData->hData);
2285 return 0;
2288 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2290 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2291 int i;
2292 BYTE *pSrc, *pDest;
2294 pDest = lpBuff;
2295 pSrc = (BYTE *)GlobalLock(pData->hData);
2296 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2297 pDest[i] = pSrc[pData->nLength+i];
2299 pData->nLength += i;
2300 *pcb = i;
2301 GlobalUnlock(pData->hData);
2302 return 0;
2306 void ME_DestroyEditor(ME_TextEditor *editor)
2308 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2309 ME_DisplayItem *p = pFirst, *pNext = NULL;
2310 int i;
2312 ME_ClearTempStyle(editor);
2313 ME_EmptyUndoStack(editor);
2314 while(p) {
2315 pNext = p->next;
2316 ME_DestroyDisplayItem(p);
2317 p = pNext;
2319 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2320 for (i=0; i<HFONT_CACHE_SIZE; i++)
2322 if (editor->pFontCache[i].hFont)
2323 DeleteObject(editor->pFontCache[i].hFont);
2325 if (editor->rgbBackColor != -1)
2326 DeleteObject(editor->hbrBackground);
2327 if(editor->lpOleCallback)
2328 IUnknown_Release(editor->lpOleCallback);
2329 OleUninitialize();
2331 FREE_OBJ(editor->pBuffer);
2332 FREE_OBJ(editor->pCursors);
2334 FREE_OBJ(editor);
2337 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2339 TRACE("\n");
2340 switch (fdwReason)
2342 case DLL_PROCESS_ATTACH:
2343 DisableThreadLibraryCalls(hinstDLL);
2344 me_heap = HeapCreate (0, 0x10000, 0);
2345 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2346 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2347 LookupInit();
2348 break;
2350 case DLL_PROCESS_DETACH:
2351 UnregisterClassW(RichEdit20W, 0);
2352 UnregisterClassW(RichEdit50W, 0);
2353 UnregisterClassA("RichEdit20A", 0);
2354 UnregisterClassA("RichEdit50A", 0);
2355 if (ME_ListBoxRegistered)
2356 UnregisterClassW(REListBox20W, 0);
2357 if (ME_ComboBoxRegistered)
2358 UnregisterClassW(REComboBox20W, 0);
2359 LookupCleanup();
2360 HeapDestroy (me_heap);
2361 me_heap = NULL;
2362 break;
2364 return TRUE;
2368 #define UNSUPPORTED_MSG(e) \
2369 case e: \
2370 FIXME(#e ": stub\n"); \
2371 return DefWindowProcW(hWnd, msg, wParam, lParam);
2373 static const char * const edit_messages[] = {
2374 "EM_GETSEL",
2375 "EM_SETSEL",
2376 "EM_GETRECT",
2377 "EM_SETRECT",
2378 "EM_SETRECTNP",
2379 "EM_SCROLL",
2380 "EM_LINESCROLL",
2381 "EM_SCROLLCARET",
2382 "EM_GETMODIFY",
2383 "EM_SETMODIFY",
2384 "EM_GETLINECOUNT",
2385 "EM_LINEINDEX",
2386 "EM_SETHANDLE",
2387 "EM_GETHANDLE",
2388 "EM_GETTHUMB",
2389 "EM_UNKNOWN_BF",
2390 "EM_UNKNOWN_C0",
2391 "EM_LINELENGTH",
2392 "EM_REPLACESEL",
2393 "EM_UNKNOWN_C3",
2394 "EM_GETLINE",
2395 "EM_LIMITTEXT",
2396 "EM_CANUNDO",
2397 "EM_UNDO",
2398 "EM_FMTLINES",
2399 "EM_LINEFROMCHAR",
2400 "EM_UNKNOWN_CA",
2401 "EM_SETTABSTOPS",
2402 "EM_SETPASSWORDCHAR",
2403 "EM_EMPTYUNDOBUFFER",
2404 "EM_GETFIRSTVISIBLELINE",
2405 "EM_SETREADONLY",
2406 "EM_SETWORDBREAKPROC",
2407 "EM_GETWORDBREAKPROC",
2408 "EM_GETPASSWORDCHAR",
2409 "EM_SETMARGINS",
2410 "EM_GETMARGINS",
2411 "EM_GETLIMITTEXT",
2412 "EM_POSFROMCHAR",
2413 "EM_CHARFROMPOS"
2416 static const char * const richedit_messages[] = {
2417 "EM_CANPASTE",
2418 "EM_DISPLAYBAND",
2419 "EM_EXGETSEL",
2420 "EM_EXLIMITTEXT",
2421 "EM_EXLINEFROMCHAR",
2422 "EM_EXSETSEL",
2423 "EM_FINDTEXT",
2424 "EM_FORMATRANGE",
2425 "EM_GETCHARFORMAT",
2426 "EM_GETEVENTMASK",
2427 "EM_GETOLEINTERFACE",
2428 "EM_GETPARAFORMAT",
2429 "EM_GETSELTEXT",
2430 "EM_HIDESELECTION",
2431 "EM_PASTESPECIAL",
2432 "EM_REQUESTRESIZE",
2433 "EM_SELECTIONTYPE",
2434 "EM_SETBKGNDCOLOR",
2435 "EM_SETCHARFORMAT",
2436 "EM_SETEVENTMASK",
2437 "EM_SETOLECALLBACK",
2438 "EM_SETPARAFORMAT",
2439 "EM_SETTARGETDEVICE",
2440 "EM_STREAMIN",
2441 "EM_STREAMOUT",
2442 "EM_GETTEXTRANGE",
2443 "EM_FINDWORDBREAK",
2444 "EM_SETOPTIONS",
2445 "EM_GETOPTIONS",
2446 "EM_FINDTEXTEX",
2447 "EM_GETWORDBREAKPROCEX",
2448 "EM_SETWORDBREAKPROCEX",
2449 "EM_SETUNDOLIMIT",
2450 "EM_UNKNOWN_USER_83",
2451 "EM_REDO",
2452 "EM_CANREDO",
2453 "EM_GETUNDONAME",
2454 "EM_GETREDONAME",
2455 "EM_STOPGROUPTYPING",
2456 "EM_SETTEXTMODE",
2457 "EM_GETTEXTMODE",
2458 "EM_AUTOURLDETECT",
2459 "EM_GETAUTOURLDETECT",
2460 "EM_SETPALETTE",
2461 "EM_GETTEXTEX",
2462 "EM_GETTEXTLENGTHEX",
2463 "EM_SHOWSCROLLBAR",
2464 "EM_SETTEXTEX",
2465 "EM_UNKNOWN_USER_98",
2466 "EM_UNKNOWN_USER_99",
2467 "EM_SETPUNCTUATION",
2468 "EM_GETPUNCTUATION",
2469 "EM_SETWORDWRAPMODE",
2470 "EM_GETWORDWRAPMODE",
2471 "EM_SETIMECOLOR",
2472 "EM_GETIMECOLOR",
2473 "EM_SETIMEOPTIONS",
2474 "EM_GETIMEOPTIONS",
2475 "EM_CONVPOSITION",
2476 "EM_UNKNOWN_USER_109",
2477 "EM_UNKNOWN_USER_110",
2478 "EM_UNKNOWN_USER_111",
2479 "EM_UNKNOWN_USER_112",
2480 "EM_UNKNOWN_USER_113",
2481 "EM_UNKNOWN_USER_114",
2482 "EM_UNKNOWN_USER_115",
2483 "EM_UNKNOWN_USER_116",
2484 "EM_UNKNOWN_USER_117",
2485 "EM_UNKNOWN_USER_118",
2486 "EM_UNKNOWN_USER_119",
2487 "EM_SETLANGOPTIONS",
2488 "EM_GETLANGOPTIONS",
2489 "EM_GETIMECOMPMODE",
2490 "EM_FINDTEXTW",
2491 "EM_FINDTEXTEXW",
2492 "EM_RECONVERSION",
2493 "EM_SETIMEMODEBIAS",
2494 "EM_GETIMEMODEBIAS"
2497 static const char *
2498 get_msg_name(UINT msg)
2500 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2501 return edit_messages[msg - EM_GETSEL];
2502 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2503 return richedit_messages[msg - EM_CANPASTE];
2504 return "";
2507 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2508 LPARAM lParam, BOOL unicode)
2510 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2512 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2513 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2515 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2516 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2517 return 0;
2520 switch(msg) {
2522 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2523 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2524 UNSUPPORTED_MSG(EM_FMTLINES)
2525 UNSUPPORTED_MSG(EM_FORMATRANGE)
2526 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2527 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2528 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2529 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2530 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2531 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2532 UNSUPPORTED_MSG(EM_GETREDONAME)
2533 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2534 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2535 UNSUPPORTED_MSG(EM_GETUNDONAME)
2536 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2537 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2538 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2539 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2540 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2541 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2542 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2543 UNSUPPORTED_MSG(EM_SETPALETTE)
2544 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2545 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2546 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2547 UNSUPPORTED_MSG(WM_STYLECHANGING)
2548 UNSUPPORTED_MSG(WM_STYLECHANGED)
2550 /* Messages specific to Richedit controls */
2552 case EM_STREAMIN:
2553 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2554 case EM_STREAMOUT:
2555 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2556 case WM_GETDLGCODE:
2558 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2559 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2561 int vk = (int)((LPMSG)lParam)->wParam;
2562 /* if style says we want return key */
2563 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2565 code |= DLGC_WANTMESSAGE;
2567 /* we always handle ctrl-tab */
2568 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2570 code |= DLGC_WANTMESSAGE;
2573 return code;
2575 case WM_NCCREATE:
2577 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2578 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2579 editor = ME_MakeEditor(hWnd);
2580 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2581 return TRUE;
2583 case EM_EMPTYUNDOBUFFER:
2584 ME_EmptyUndoStack(editor);
2585 return 0;
2586 case EM_GETSEL:
2588 /* Note: wParam/lParam can be NULL */
2589 UINT from, to;
2590 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2591 PUINT pto = lParam ? (PUINT)lParam : &to;
2592 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2593 if ((*pfrom|*pto) & 0xFFFF0000)
2594 return -1;
2595 return MAKELONG(*pfrom,*pto);
2597 case EM_EXGETSEL:
2599 CHARRANGE *pRange = (CHARRANGE *)lParam;
2600 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2601 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2602 return 0;
2604 case EM_SETUNDOLIMIT:
2606 if ((int)wParam < 0)
2607 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2608 else
2609 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2610 /* Setting a max stack size keeps wine from getting killed
2611 for hogging memory. Windows allocates all this memory at once, so
2612 no program would realistically set a value above our maximum. */
2613 return editor->nUndoLimit;
2615 case EM_CANUNDO:
2616 return editor->pUndoStack != NULL;
2617 case EM_CANREDO:
2618 return editor->pRedoStack != NULL;
2619 case WM_UNDO: /* FIXME: actually not the same */
2620 case EM_UNDO:
2621 return ME_Undo(editor);
2622 case EM_REDO:
2623 return ME_Redo(editor);
2624 case EM_GETOPTIONS:
2626 /* these flags are equivalent to the ES_* counterparts */
2627 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2628 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2629 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2631 return settings;
2633 case EM_SETOPTIONS:
2635 /* these flags are equivalent to ES_* counterparts
2636 * ECO_READONLY is already implemented in the code, only requires
2637 * setting the bit to work
2639 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2640 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2641 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2642 DWORD settings = mask & raw;
2644 switch(wParam)
2646 case ECOOP_SET:
2647 settings = lParam;
2648 break;
2649 case ECOOP_OR:
2650 settings |= lParam;
2651 break;
2652 case ECOOP_AND:
2653 settings &= lParam;
2654 break;
2655 case ECOOP_XOR:
2656 settings ^= lParam;
2658 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2660 if (settings & ECO_AUTOWORDSELECTION)
2661 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2662 if (settings & ECO_SELECTIONBAR)
2663 editor->selofs = SELECTIONBAR_WIDTH;
2664 else
2665 editor->selofs = 0;
2666 ME_WrapMarkedParagraphs(editor);
2668 if (settings & ECO_VERTICAL)
2669 FIXME("ECO_VERTICAL not implemented yet!\n");
2670 if (settings & ECO_AUTOHSCROLL)
2671 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2672 if (settings & ECO_AUTOVSCROLL)
2673 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2674 if (settings & ECO_NOHIDESEL)
2675 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2676 if (settings & ECO_WANTRETURN)
2677 FIXME("ECO_WANTRETURN not implemented yet!\n");
2679 return settings;
2681 case EM_SETSEL:
2683 ME_InvalidateSelection(editor);
2684 ME_SetSelection(editor, wParam, lParam);
2685 ME_InvalidateSelection(editor);
2686 HideCaret(editor->hWnd);
2687 ME_ShowCaret(editor);
2688 ME_SendSelChange(editor);
2689 return 0;
2691 case EM_SETSCROLLPOS:
2693 POINT *point = (POINT *)lParam;
2694 ME_ScrollAbs(editor, point->y);
2695 return 0;
2697 case EM_AUTOURLDETECT:
2699 if (wParam==1 || wParam ==0)
2701 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2702 return 0;
2704 return E_INVALIDARG;
2706 case EM_GETAUTOURLDETECT:
2708 return editor->AutoURLDetect_bEnable;
2710 case EM_EXSETSEL:
2712 int end;
2713 CHARRANGE range = *(CHARRANGE *)lParam;
2715 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2717 ME_InvalidateSelection(editor);
2718 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2719 ME_InvalidateSelection(editor);
2720 HideCaret(editor->hWnd);
2721 ME_ShowCaret(editor);
2722 ME_SendSelChange(editor);
2724 return end;
2726 case EM_SHOWSCROLLBAR:
2728 ShowScrollBar(editor->hWnd, wParam, lParam);
2729 return 0;
2731 case EM_SETTEXTEX:
2733 LPWSTR wszText;
2734 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2735 size_t len;
2736 int from, to;
2737 ME_Style *style;
2738 int oldModify = editor->nModifyStep;
2740 if (!pStruct) return 0;
2742 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2743 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2744 pStruct->flags, pStruct->codepage);
2746 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2747 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2748 len = wszText ? lstrlenW(wszText) : 0;
2750 if (pStruct->flags & ST_SELECTION) {
2751 ME_GetSelection(editor, &from, &to);
2752 style = ME_GetSelectionInsertStyle(editor);
2753 ME_InternalDeleteText(editor, from, to - from, FALSE);
2754 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2755 ME_StreamInRTFString(editor, 1, (char *)lParam);
2756 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2757 ME_ReleaseStyle(style);
2759 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2761 else {
2762 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2763 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2764 ME_StreamInRTFString(editor, 0, (char *)lParam);
2765 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2766 len = 1;
2768 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2770 ME_CommitUndo(editor);
2771 if (!(pStruct->flags & ST_KEEPUNDO))
2773 editor->nModifyStep = oldModify;
2774 ME_EmptyUndoStack(editor);
2776 ME_UpdateRepaint(editor);
2777 return len;
2779 case EM_SETBKGNDCOLOR:
2781 LRESULT lColor;
2782 if (editor->rgbBackColor != -1) {
2783 DeleteObject(editor->hbrBackground);
2784 lColor = editor->rgbBackColor;
2786 else lColor = GetSysColor(COLOR_WINDOW);
2788 if (wParam)
2790 editor->rgbBackColor = -1;
2791 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2793 else
2795 editor->rgbBackColor = lParam;
2796 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2798 if (editor->bRedraw)
2800 InvalidateRect(hWnd, NULL, TRUE);
2801 UpdateWindow(hWnd);
2803 return lColor;
2805 case EM_GETMODIFY:
2806 return editor->nModifyStep == 0 ? 0 : -1;
2807 case EM_SETMODIFY:
2809 if (wParam)
2810 editor->nModifyStep = 1;
2811 else
2812 editor->nModifyStep = 0;
2814 return 0;
2816 case EM_SETREADONLY:
2818 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2819 if (wParam)
2820 nStyle |= ES_READONLY;
2821 else
2822 nStyle &= ~ES_READONLY;
2823 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2824 return 0;
2826 case EM_SETEVENTMASK:
2828 DWORD nOldMask = editor->nEventMask;
2830 editor->nEventMask = lParam;
2831 return nOldMask;
2833 case EM_GETEVENTMASK:
2834 return editor->nEventMask;
2835 case EM_SETCHARFORMAT:
2837 CHARFORMAT2W buf, *p;
2838 BOOL bRepaint = TRUE;
2839 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2840 if (p == NULL) return 0;
2841 if (!wParam)
2842 ME_SetDefaultCharFormat(editor, p);
2843 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2844 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2845 return 0;
2846 } else if (wParam == SCF_ALL) {
2847 if (editor->mode & TM_PLAINTEXT)
2848 ME_SetDefaultCharFormat(editor, p);
2849 else {
2850 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2851 editor->nModifyStep = 1;
2853 } else if (editor->mode & TM_PLAINTEXT) {
2854 return 0;
2855 } else {
2856 int from, to;
2857 ME_GetSelection(editor, &from, &to);
2858 bRepaint = (from != to);
2859 ME_SetSelectionCharFormat(editor, p);
2860 if (from != to) editor->nModifyStep = 1;
2862 ME_CommitUndo(editor);
2863 if (bRepaint)
2864 ME_RewrapRepaint(editor);
2865 return 1;
2867 case EM_GETCHARFORMAT:
2869 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2870 if (dst->cbSize != sizeof(CHARFORMATA) &&
2871 dst->cbSize != sizeof(CHARFORMATW) &&
2872 dst->cbSize != sizeof(CHARFORMAT2A) &&
2873 dst->cbSize != sizeof(CHARFORMAT2W))
2874 return 0;
2875 tmp.cbSize = sizeof(tmp);
2876 if (!wParam)
2877 ME_GetDefaultCharFormat(editor, &tmp);
2878 else
2879 ME_GetSelectionCharFormat(editor, &tmp);
2880 ME_CopyToCFAny(dst, &tmp);
2881 return tmp.dwMask;
2883 case EM_SETPARAFORMAT:
2885 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2886 ME_RewrapRepaint(editor);
2887 ME_CommitUndo(editor);
2888 return result;
2890 case EM_GETPARAFORMAT:
2891 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2892 return ((PARAFORMAT2 *)lParam)->dwMask;
2893 case EM_GETFIRSTVISIBLELINE:
2895 ME_DisplayItem *p = editor->pBuffer->pFirst;
2896 int y = ME_GetYScrollPos(editor);
2897 int ypara = 0;
2898 int count = 0;
2899 int ystart, yend;
2900 while(p) {
2901 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2902 if (p->type == diTextEnd)
2903 break;
2904 if (p->type == diParagraph) {
2905 ypara = p->member.para.pt.y;
2906 continue;
2908 ystart = ypara + p->member.row.pt.y;
2909 yend = ystart + p->member.row.nHeight;
2910 if (y < yend) {
2911 break;
2913 count++;
2915 return count;
2917 case EM_HIDESELECTION:
2919 editor->bHideSelection = (wParam != 0);
2920 ME_InvalidateSelection(editor);
2921 return 0;
2923 case EM_LINESCROLL:
2925 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2926 return TRUE; /* Should return false if a single line richedit control */
2928 case WM_CLEAR:
2930 int from, to;
2931 ME_GetSelection(editor, &from, &to);
2932 ME_InternalDeleteText(editor, from, to-from, FALSE);
2933 ME_CommitUndo(editor);
2934 ME_UpdateRepaint(editor);
2935 return 0;
2937 case EM_REPLACESEL:
2939 int from, to;
2940 ME_Style *style;
2941 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2942 size_t len = wszText ? lstrlenW(wszText) : 0;
2943 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2945 ME_GetSelection(editor, &from, &to);
2946 style = ME_GetSelectionInsertStyle(editor);
2947 ME_InternalDeleteText(editor, from, to-from, FALSE);
2948 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2949 ME_ReleaseStyle(style);
2950 /* drop temporary style if line end */
2952 * FIXME question: does abc\n mean: put abc,
2953 * clear temp style, put \n? (would require a change)
2955 if (len>0 && wszText[len-1] == '\n')
2956 ME_ClearTempStyle(editor);
2957 ME_EndToUnicode(unicode, wszText);
2958 ME_CommitUndo(editor);
2959 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2960 if (!wParam)
2961 ME_EmptyUndoStack(editor);
2962 ME_UpdateRepaint(editor);
2963 return len;
2965 case EM_SCROLLCARET:
2967 int top, bottom; /* row's edges relative to document top */
2968 int nPos;
2969 ME_DisplayItem *para, *row;
2971 nPos = ME_GetYScrollPos(editor);
2972 row = ME_RowStart(editor->pCursors[0].pRun);
2973 para = ME_GetParagraph(row);
2974 top = para->member.para.pt.y + row->member.row.pt.y;
2975 bottom = top + row->member.row.nHeight;
2977 if (top < nPos) /* caret above window */
2978 ME_ScrollAbs(editor, top);
2979 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2980 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2981 return 0;
2983 case WM_SETFONT:
2985 LOGFONTW lf;
2986 CHARFORMAT2W fmt;
2987 HDC hDC;
2988 BOOL bRepaint = LOWORD(lParam);
2990 if (!wParam)
2991 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2992 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2993 hDC = GetDC(hWnd);
2994 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2995 ReleaseDC(hWnd, hDC);
2996 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2997 ME_SetDefaultCharFormat(editor, &fmt);
2999 ME_CommitUndo(editor);
3000 if (bRepaint)
3001 ME_RewrapRepaint(editor);
3002 return 0;
3004 case WM_SETTEXT:
3006 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3007 if (lParam)
3009 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3010 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
3012 /* Undocumented: WM_SETTEXT supports RTF text */
3013 ME_StreamInRTFString(editor, 0, (char *)lParam);
3015 else
3017 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3018 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3019 if (lstrlenW(wszText) > 0)
3021 int len = -1;
3023 /* uses default style! */
3024 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3026 WCHAR * p;
3028 p = wszText;
3029 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3030 len = p - wszText;
3032 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3034 ME_EndToUnicode(unicode, wszText);
3037 else
3038 TRACE("WM_SETTEXT - NULL\n");
3039 if (editor->AutoURLDetect_bEnable)
3041 ME_UpdateLinkAttribute(editor, 0, -1);
3043 ME_SetSelection(editor, 0, 0);
3044 editor->nModifyStep = 0;
3045 ME_CommitUndo(editor);
3046 ME_EmptyUndoStack(editor);
3047 ME_UpdateRepaint(editor);
3048 return 1;
3050 case EM_CANPASTE:
3052 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3053 if (IsClipboardFormatAvailable(nRTFFormat))
3054 return TRUE;
3055 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3056 return TRUE;
3057 return FALSE;
3059 case WM_PASTE:
3061 DWORD dwFormat = 0;
3062 EDITSTREAM es;
3063 ME_GlobalDestStruct gds;
3064 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3065 UINT cf = 0;
3067 if (IsClipboardFormatAvailable(nRTFFormat))
3068 cf = nRTFFormat, dwFormat = SF_RTF;
3069 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3070 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
3071 else
3072 return 0;
3074 if (!OpenClipboard(hWnd))
3075 return 0;
3076 gds.hData = GetClipboardData(cf);
3077 gds.nLength = 0;
3078 es.dwCookie = (DWORD)&gds;
3079 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
3080 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
3082 CloseClipboard();
3083 return 0;
3085 case WM_CUT:
3086 case WM_COPY:
3088 LPDATAOBJECT dataObj = NULL;
3089 CHARRANGE range;
3090 HRESULT hr = S_OK;
3092 if (editor->cPasswordMask)
3093 return 0; /* Copying or Cutting masked text isn't allowed */
3095 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
3096 if(editor->lpOleCallback)
3097 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
3098 if(FAILED(hr) || !dataObj)
3099 hr = ME_GetDataObject(editor, &range, &dataObj);
3100 if(SUCCEEDED(hr)) {
3101 hr = OleSetClipboard(dataObj);
3102 IDataObject_Release(dataObj);
3104 if (SUCCEEDED(hr) && msg == WM_CUT)
3106 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3107 ME_CommitUndo(editor);
3108 ME_UpdateRepaint(editor);
3110 return 0;
3112 case WM_GETTEXTLENGTH:
3114 GETTEXTLENGTHEX how;
3116 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3117 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3118 how.codepage = unicode ? 1200 : CP_ACP;
3119 return ME_GetTextLengthEx(editor, &how);
3121 case EM_GETTEXTLENGTHEX:
3122 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3123 case WM_GETTEXT:
3125 GETTEXTEX ex;
3126 LRESULT rc;
3127 LPSTR bufferA = NULL;
3128 LPWSTR bufferW = NULL;
3130 if (unicode)
3131 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
3132 else
3133 bufferA = heap_alloc(wParam + 2);
3135 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3136 ex.flags = GT_USECRLF;
3137 ex.codepage = unicode ? 1200 : CP_ACP;
3138 ex.lpDefaultChar = NULL;
3139 ex.lpUsedDefChar = NULL;
3140 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
3142 if (unicode)
3144 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3145 if (lstrlenW(bufferW) >= wParam) rc = 0;
3147 else
3149 memcpy((LPSTR)lParam, bufferA, wParam);
3150 if (strlen(bufferA) >= wParam) rc = 0;
3152 heap_free(bufferA);
3153 heap_free(bufferW);
3154 return rc;
3156 case EM_GETTEXTEX:
3158 GETTEXTEX *ex = (GETTEXTEX*)wParam;
3159 int nStart, nCount; /* in chars */
3161 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
3162 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
3164 if (ex->flags & GT_SELECTION)
3166 ME_GetSelection(editor, &nStart, &nCount);
3167 nCount -= nStart;
3169 else
3171 nStart = 0;
3172 nCount = 0x7fffffff;
3174 if (ex->codepage == 1200)
3176 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
3177 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
3179 else
3181 /* potentially each char may be a CR, why calculate the exact value with O(N) when
3182 we can just take a bigger buffer? :)
3183 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
3184 occurs only in richedit 2.0 mode, in which line breaks have only one CR
3186 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
3187 LPWSTR buffer;
3188 DWORD buflen = ex->cb;
3189 LRESULT rc;
3190 DWORD flags = 0;
3192 nCount = min(nCount, ex->cb - 1);
3193 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
3195 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
3196 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
3197 if (rc) rc--; /* do not count 0 terminator */
3199 heap_free(buffer);
3200 return rc;
3203 case EM_GETSELTEXT:
3205 int from, to;
3206 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3207 ME_GetSelection(editor, &from, &to);
3208 tr.chrg.cpMin = from;
3209 tr.chrg.cpMax = to;
3210 tr.lpstrText = (WCHAR *)lParam;
3211 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
3213 case EM_GETSCROLLPOS:
3215 POINT *point = (POINT *)lParam;
3216 point->x = 0; /* FIXME side scrolling not implemented */
3217 point->y = ME_GetYScrollPos(editor);
3218 return 1;
3220 case EM_GETTEXTRANGE:
3222 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3223 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3224 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3225 editor->bEmulateVersion10, ME_GetTextLength(editor));
3226 if (unicode)
3227 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
3228 else
3230 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
3231 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
3232 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
3233 /* FIXME this is a potential security hole (buffer overrun)
3234 if you know more about wchar->mbyte conversion please explain
3236 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
3237 FREE_OBJ(p);
3238 return nChars;
3241 case EM_GETLINE:
3243 ME_DisplayItem *run;
3244 const unsigned int nMaxChars = *(WORD *) lParam;
3245 unsigned int nCharsLeft = nMaxChars;
3246 char *dest = (char *) lParam;
3247 BOOL wroteNull = FALSE;
3249 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3250 unicode ? "Unicode" : "Ansi");
3252 run = ME_FindRowWithNumber(editor, wParam);
3253 if (run == NULL)
3254 return 0;
3256 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3257 && !(run->member.run.nFlags & MERF_ENDPARA))
3259 unsigned int nCopy;
3260 ME_String *strText;
3261 if (run->type != diRun)
3262 break;
3263 strText = run->member.run.strText;
3264 nCopy = min(nCharsLeft, strText->nLen);
3266 if (unicode)
3267 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
3268 else
3269 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3270 nCharsLeft, NULL, NULL);
3271 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3272 nCharsLeft -= nCopy;
3275 /* append line termination, space allowing */
3276 if (nCharsLeft > 0)
3278 if (run && (run->member.run.nFlags & MERF_ENDPARA))
3280 unsigned int i;
3281 /* Write as many \r as encoded in end-of-paragraph, space allowing */
3282 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3284 *((WCHAR *)dest) = '\r';
3285 dest += unicode ? sizeof(WCHAR) : 1;
3287 /* Write as many \n as encoded in end-of-paragraph, space allowing */
3288 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3290 *((WCHAR *)dest) = '\n';
3291 dest += unicode ? sizeof(WCHAR) : 1;
3294 if (nCharsLeft > 0)
3296 if (unicode)
3297 *((WCHAR *)dest) = '\0';
3298 else
3299 *dest = '\0';
3300 nCharsLeft--;
3301 wroteNull = TRUE;
3305 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3306 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3308 case EM_GETLINECOUNT:
3310 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3311 int nRows = 0;
3313 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3315 while (item != editor->pBuffer->pLast)
3317 assert(item->type == diParagraph);
3318 prev_para = ME_FindItemBack(item, diRun);
3319 if (prev_para) {
3320 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3322 nRows += item->member.para.nRows;
3323 item = item->member.para.next_para;
3325 last_para = ME_FindItemBack(item, diRun);
3326 assert(last_para);
3327 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3328 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3329 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3331 /* In 1.0 emulation, the last solitary \r at the very end of the text
3332 (if one exists) is NOT a line break.
3333 FIXME: this is an ugly hack. This should have a more regular model. */
3334 nRows--;
3337 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3338 return max(1, nRows);
3340 case EM_LINEFROMCHAR:
3342 if (wParam == -1)
3343 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3344 else
3345 return ME_RowNumberFromCharOfs(editor, wParam);
3347 case EM_EXLINEFROMCHAR:
3349 if (lParam == -1)
3350 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3351 else
3352 return ME_RowNumberFromCharOfs(editor, lParam);
3354 case EM_LINEINDEX:
3356 ME_DisplayItem *item, *para;
3357 int nCharOfs;
3359 if (wParam == -1)
3360 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3361 else
3362 item = ME_FindRowWithNumber(editor, wParam);
3363 if (!item)
3364 return -1;
3365 para = ME_GetParagraph(item);
3366 item = ME_FindItemFwd(item, diRun);
3367 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3368 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3369 return nCharOfs;
3371 case EM_LINELENGTH:
3373 ME_DisplayItem *item, *item_end;
3374 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3376 if (wParam > ME_GetTextLength(editor))
3377 return 0;
3378 if (wParam == -1)
3380 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3381 return 0;
3383 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3384 item = ME_RowStart(item);
3385 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3386 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3387 if (item_end->type == diStartRow)
3388 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3389 else
3391 ME_DisplayItem *endPara;
3393 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3394 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3395 endPara = ME_FindItemBack(endPara, diRun);
3396 assert(endPara);
3397 assert(endPara->type == diRun);
3398 assert(endPara->member.run.nFlags & MERF_ENDPARA);
3399 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3401 nChars = nNextLineOfs - nThisLineOfs;
3402 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3403 return nChars;
3405 case EM_EXLIMITTEXT:
3407 if ((int)lParam < 0)
3408 return 0;
3409 if (lParam == 0)
3410 editor->nTextLimit = 65536;
3411 else
3412 editor->nTextLimit = (int) lParam;
3413 return 0;
3415 case EM_LIMITTEXT:
3417 if (wParam == 0)
3418 editor->nTextLimit = 65536;
3419 else
3420 editor->nTextLimit = (int) wParam;
3421 return 0;
3423 case EM_GETLIMITTEXT:
3425 return editor->nTextLimit;
3427 case EM_FINDTEXT:
3429 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3430 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3431 WCHAR *tmp;
3432 LRESULT r;
3434 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3435 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3436 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3437 FREE_OBJ( tmp );
3438 return r;
3440 case EM_FINDTEXTEX:
3442 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3443 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3444 WCHAR *tmp;
3445 LRESULT r;
3447 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3448 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3449 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3450 FREE_OBJ( tmp );
3451 return r;
3453 case EM_FINDTEXTW:
3455 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3456 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3458 case EM_FINDTEXTEXW:
3460 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3461 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3463 case EM_GETZOOM:
3464 if (!wParam || !lParam)
3465 return FALSE;
3466 *(int *)wParam = editor->nZoomNumerator;
3467 *(int *)lParam = editor->nZoomDenominator;
3468 return TRUE;
3469 case EM_SETZOOM:
3470 return ME_SetZoom(editor, wParam, lParam);
3471 case EM_CHARFROMPOS:
3472 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3473 case EM_POSFROMCHAR:
3475 ME_DisplayItem *pRun;
3476 int nCharOfs, nOffset, nLength;
3477 POINTL pt = {0,0};
3478 SCROLLINFO si;
3480 nCharOfs = wParam;
3481 /* detect which API version we're dealing with */
3482 if (wParam >= 0x40000)
3483 nCharOfs = lParam;
3484 nLength = ME_GetTextLength(editor);
3486 if (nCharOfs < nLength) {
3487 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3488 assert(pRun->type == diRun);
3489 pt.y = pRun->member.run.pt.y;
3490 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3491 pt.y += ME_GetParagraph(pRun)->member.para.pt.y;
3492 } else {
3493 pt.x = 0;
3494 pt.y = editor->pBuffer->pLast->member.para.pt.y;
3496 pt.x += editor->selofs;
3498 si.cbSize = sizeof(si);
3499 si.fMask = SIF_POS;
3500 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3501 si.cbSize = sizeof(si);
3502 si.fMask = SIF_POS;
3503 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3505 if (wParam >= 0x40000) {
3506 *(POINTL *)wParam = pt;
3508 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3510 case WM_CREATE:
3512 SCROLLINFO si;
3514 GetClientRect(hWnd, &editor->rcFormat);
3515 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3516 { /* Squelch the default horizontal scrollbar it would make */
3517 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3520 si.cbSize = sizeof(si);
3521 si.fMask = SIF_PAGE | SIF_RANGE;
3522 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3523 si.fMask |= SIF_DISABLENOSCROLL;
3524 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3525 si.nMin = 0;
3526 si.nPage = 0;
3527 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3529 ME_CommitUndo(editor);
3530 ME_WrapMarkedParagraphs(editor);
3531 ME_MoveCaret(editor);
3532 return 0;
3534 case WM_DESTROY:
3535 ME_DestroyEditor(editor);
3536 SetWindowLongPtrW(hWnd, 0, 0);
3537 return 0;
3538 case WM_SETCURSOR:
3540 return ME_SetCursor(editor);
3542 case WM_LBUTTONDBLCLK:
3543 case WM_LBUTTONDOWN:
3545 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3546 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3547 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3548 return 0;
3549 SetFocus(hWnd);
3550 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3551 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3552 SetCapture(hWnd);
3553 ME_LinkNotify(editor,msg,wParam,lParam);
3554 if (!ME_SetCursor(editor)) goto do_default;
3555 break;
3557 case WM_MOUSEMOVE:
3558 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3559 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3560 return 0;
3561 if (GetCapture() == hWnd)
3562 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3563 ME_LinkNotify(editor,msg,wParam,lParam);
3564 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3565 if (GetCapture() == hWnd)
3566 ME_SetCursor(editor);
3567 break;
3568 case WM_LBUTTONUP:
3569 if (GetCapture() == hWnd)
3570 ReleaseCapture();
3571 if (editor->nSelectionType == stDocument)
3572 editor->nSelectionType = stPosition;
3573 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3574 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3575 return 0;
3576 else
3578 ME_SetCursor(editor);
3579 ME_LinkNotify(editor,msg,wParam,lParam);
3581 break;
3582 case WM_RBUTTONUP:
3583 case WM_RBUTTONDOWN:
3584 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3585 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3586 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3587 return 0;
3588 goto do_default;
3589 case WM_CONTEXTMENU:
3590 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3591 goto do_default;
3592 break;
3593 case WM_PAINT:
3594 if (editor->bRedraw)
3596 HDC hDC;
3597 PAINTSTRUCT ps;
3599 hDC = BeginPaint(hWnd, &ps);
3600 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3601 EndPaint(hWnd, &ps);
3603 break;
3604 case WM_SETFOCUS:
3605 editor->bHaveFocus = TRUE;
3606 ME_ShowCaret(editor);
3607 ME_SendOldNotify(editor, EN_SETFOCUS);
3608 return 0;
3609 case WM_KILLFOCUS:
3610 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3611 editor->bHaveFocus = FALSE;
3612 ME_HideCaret(editor);
3613 ME_SendOldNotify(editor, EN_KILLFOCUS);
3614 return 0;
3615 case WM_ERASEBKGND:
3617 if (editor->bRedraw)
3619 HDC hDC = (HDC)wParam;
3620 RECT rc;
3621 if (GetUpdateRect(hWnd,&rc,TRUE))
3623 FillRect(hDC, &rc, editor->hbrBackground);
3626 return 1;
3628 case WM_COMMAND:
3629 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3630 return 0;
3631 case WM_KEYUP:
3632 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3633 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3634 return 0;
3635 goto do_default;
3636 case WM_KEYDOWN:
3637 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3638 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3639 return 0;
3640 if (ME_KeyDown(editor, LOWORD(wParam)))
3641 return 0;
3642 goto do_default;
3643 case WM_CHAR:
3645 WCHAR wstr;
3647 if (unicode)
3648 wstr = (WCHAR)wParam;
3649 else
3651 CHAR charA = wParam;
3652 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3655 switch (wstr)
3657 case 1: /* Ctrl-A */
3658 ME_SetSelection(editor, 0, -1);
3659 return 0;
3660 case 3: /* Ctrl-C */
3661 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3662 return 0;
3665 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3666 MessageBeep(MB_ICONERROR);
3667 return 0; /* FIXME really 0 ? */
3670 switch (wstr)
3672 case 22: /* Ctrl-V */
3673 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3674 return 0;
3675 case 24: /* Ctrl-X */
3676 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3677 return 0;
3678 case 25: /* Ctrl-Y */
3679 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3680 return 0;
3681 case 26: /* Ctrl-Z */
3682 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3683 return 0;
3685 if (((unsigned)wstr)>=' '
3686 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3687 || wstr=='\t') {
3688 ME_Cursor cursor = editor->pCursors[0];
3689 ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
3690 int from, to;
3691 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
3692 ME_GetSelection(editor, &from, &to);
3693 if (wstr=='\t'
3694 /* v4.1 allows tabs to be inserted with ctrl key down */
3695 && !(ctrl_is_down && !editor->bEmulateVersion10)
3698 ME_DisplayItem *para;
3699 BOOL bSelectedRow = FALSE;
3701 para = ME_GetParagraph(cursor.pRun);
3702 if (ME_IsSelection(editor) &&
3703 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3704 to == ME_GetCursorOfs(editor, 0) &&
3705 para->member.para.prev_para->type == diParagraph)
3707 para = para->member.para.prev_para;
3708 bSelectedRow = TRUE;
3710 if (ME_IsInTable(para))
3712 ME_TabPressedInTable(editor, bSelectedRow);
3713 ME_CommitUndo(editor);
3714 return 0;
3716 } else if (!editor->bEmulateVersion10) { /* v4.1 */
3717 if (para->member.para.nFlags & MEPF_ROWEND) {
3718 if (wstr=='\r') {
3719 /* FIXME: Add a new table row after this row. */
3720 return 0;
3721 } else if (from == to) {
3722 para = para->member.para.next_para;
3723 if (para->member.para.nFlags & MEPF_ROWSTART)
3724 para = para->member.para.next_para;
3725 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3726 editor->pCursors[0].nOffset = 0;
3727 editor->pCursors[1] = editor->pCursors[0];
3730 else if (para == ME_GetParagraph(editor->pCursors[1].pRun) &&
3731 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
3732 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
3733 !para->member.para.prev_para->member.para.nCharOfs)
3735 /* FIXME: Insert a newline before the table. */
3737 } else { /* v1.0 - 3.0 */
3738 ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
3739 if (ME_IsInTable(cursor.pRun))
3741 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
3743 if (from == to) {
3744 if (wstr=='\r') {
3745 ME_ContinueCoalescingTransaction(editor);
3746 para = ME_AppendTableRow(editor, para);
3747 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3748 editor->pCursors[0].nOffset = 0;
3749 editor->pCursors[1] = editor->pCursors[0];
3750 ME_CommitCoalescingUndo(editor);
3751 ME_UpdateRepaint(editor);
3752 } else {
3753 /* Text should not be inserted at the end of the table. */
3754 MessageBeep(-1);
3756 return 0;
3758 } else if (wstr == '\r') {
3759 ME_ContinueCoalescingTransaction(editor);
3760 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3761 !ME_IsInTable(para->member.para.prev_para))
3763 /* Insert newline before table */
3764 WCHAR endl = '\r';
3765 cursor.pRun = ME_FindItemBack(para, diRun);
3766 if (cursor.pRun)
3767 editor->pCursors[0].pRun = cursor.pRun;
3768 editor->pCursors[0].nOffset = 0;
3769 editor->pCursors[1] = editor->pCursors[0];
3770 ME_InsertTextFromCursor(editor, 0, &endl, 1,
3771 editor->pCursors[0].pRun->member.run.style);
3772 } else {
3773 editor->pCursors[1] = editor->pCursors[0];
3774 para = ME_AppendTableRow(editor, para);
3775 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3776 editor->pCursors[0].nOffset = 0;
3777 editor->pCursors[1] = editor->pCursors[0];
3779 ME_CommitCoalescingUndo(editor);
3780 ME_UpdateRepaint(editor);
3781 return 0;
3785 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3786 /* WM_CHAR is restricted to nTextLimit */
3787 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3789 ME_Style *style = ME_GetInsertStyle(editor, 0);
3790 ME_SaveTempStyle(editor);
3791 ME_ContinueCoalescingTransaction(editor);
3792 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3793 ME_InsertEndRowFromCursor(editor, 0);
3794 else
3795 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3796 ME_ReleaseStyle(style);
3797 ME_CommitCoalescingUndo(editor);
3798 SetCursor(NULL);
3801 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3803 ME_UpdateRepaint(editor);
3805 return 0;
3807 case WM_UNICHAR:
3808 if (unicode)
3810 if(wParam == UNICODE_NOCHAR) return TRUE;
3811 if(wParam <= 0x000fffff)
3813 if(wParam > 0xffff) /* convert to surrogates */
3815 wParam -= 0x10000;
3816 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3817 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3819 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3821 return 0;
3823 break;
3824 case EM_STOPGROUPTYPING:
3825 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3826 return 0;
3827 case EM_SCROLL: /* fall through */
3828 case WM_VSCROLL:
3830 int origNPos;
3831 int lineHeight;
3833 origNPos = ME_GetYScrollPos(editor);
3834 lineHeight = 24;
3836 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3837 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3838 if (lineHeight <= 0) lineHeight = 24;
3840 switch(LOWORD(wParam))
3842 case SB_LINEUP:
3843 ME_ScrollUp(editor,lineHeight);
3844 break;
3845 case SB_LINEDOWN:
3846 ME_ScrollDown(editor,lineHeight);
3847 break;
3848 case SB_PAGEUP:
3849 ME_ScrollUp(editor,editor->sizeWindow.cy);
3850 break;
3851 case SB_PAGEDOWN:
3852 ME_ScrollDown(editor,editor->sizeWindow.cy);
3853 break;
3854 case SB_THUMBTRACK:
3855 case SB_THUMBPOSITION:
3856 ME_ScrollAbs(editor,HIWORD(wParam));
3857 break;
3859 if (msg == EM_SCROLL)
3860 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3861 break;
3863 case WM_MOUSEWHEEL:
3865 int gcWheelDelta;
3866 UINT pulScrollLines;
3868 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3869 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3870 return 0;
3872 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3873 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3875 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3877 /* FIXME follow the original */
3878 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3880 break;
3882 case EM_GETRECT:
3884 *((RECT *)lParam) = editor->rcFormat;
3885 return 0;
3887 case EM_SETRECT:
3888 case EM_SETRECTNP:
3890 if (lParam)
3892 RECT *rc = (RECT *)lParam;
3894 if (wParam)
3896 editor->rcFormat.left += rc->left;
3897 editor->rcFormat.top += rc->top;
3898 editor->rcFormat.right += rc->right;
3899 editor->rcFormat.bottom += rc->bottom;
3901 else
3903 editor->rcFormat = *rc;
3906 else
3908 GetClientRect(hWnd, &editor->rcFormat);
3910 if (msg != EM_SETRECTNP)
3911 ME_RewrapRepaint(editor);
3912 return 0;
3914 case EM_REQUESTRESIZE:
3915 ME_SendRequestResize(editor, TRUE);
3916 return 0;
3917 case WM_SETREDRAW:
3918 if ((editor->bRedraw = wParam))
3919 ME_RewrapRepaint(editor);
3920 return 0;
3921 case WM_SIZE:
3923 GetClientRect(hWnd, &editor->rcFormat);
3924 ME_RewrapRepaint(editor);
3925 return DefWindowProcW(hWnd, msg, wParam, lParam);
3927 /* IME messages to make richedit controls IME aware */
3928 case WM_IME_SETCONTEXT:
3929 case WM_IME_CONTROL:
3930 case WM_IME_SELECT:
3931 case WM_IME_COMPOSITIONFULL:
3932 return 0;
3933 case WM_IME_STARTCOMPOSITION:
3935 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3936 ME_DeleteSelection(editor);
3937 ME_CommitUndo(editor);
3938 ME_UpdateRepaint(editor);
3939 return 0;
3941 case WM_IME_COMPOSITION:
3943 HIMC hIMC;
3945 ME_Style *style = ME_GetInsertStyle(editor, 0);
3946 hIMC = ImmGetContext(hWnd);
3947 ME_DeleteSelection(editor);
3948 ME_CommitUndo(editor);
3949 ME_SaveTempStyle(editor);
3950 if (lParam & GCS_RESULTSTR)
3952 LPWSTR lpCompStr = NULL;
3953 DWORD dwBufLen;
3955 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3956 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3957 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3958 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3959 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3961 else if (lParam & GCS_COMPSTR)
3963 LPWSTR lpCompStr = NULL;
3964 DWORD dwBufLen;
3966 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3967 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3968 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3969 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3971 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3972 ME_SetSelection(editor,editor->imeStartIndex,
3973 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3975 ME_ReleaseStyle(style);
3976 ME_UpdateRepaint(editor);
3977 return 0;
3979 case WM_IME_ENDCOMPOSITION:
3981 ME_DeleteSelection(editor);
3982 editor->imeStartIndex=-1;
3983 return 0;
3985 case EM_GETOLEINTERFACE:
3987 LPVOID *ppvObj = (LPVOID*) lParam;
3988 return CreateIRichEditOle(editor, ppvObj);
3990 case EM_GETPASSWORDCHAR:
3992 return editor->cPasswordMask;
3994 case EM_SETOLECALLBACK:
3995 if(editor->lpOleCallback)
3996 IUnknown_Release(editor->lpOleCallback);
3997 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3998 if(editor->lpOleCallback)
3999 IUnknown_AddRef(editor->lpOleCallback);
4000 return TRUE;
4001 case EM_GETWORDBREAKPROC:
4002 return (LRESULT)editor->pfnWordBreak;
4003 case EM_SETWORDBREAKPROC:
4005 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4007 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4008 return (LRESULT)pfnOld;
4010 case EM_SETTEXTMODE:
4012 LRESULT ret;
4013 int mask = 0;
4014 int changes = 0;
4015 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
4016 if (!ret)
4018 /*Check for valid wParam*/
4019 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4020 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4021 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4022 return 1;
4023 else
4025 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4027 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4028 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4030 /*FIXME: Currently no support for undo level and code page options*/
4031 editor->mode = (editor->mode & (~mask)) | changes;
4032 return 0;
4035 return ret;
4037 case EM_SETPASSWORDCHAR:
4039 editor->cPasswordMask = wParam;
4040 ME_RewrapRepaint(editor);
4041 return 0;
4043 case EM_SETTARGETDEVICE:
4044 if (wParam == 0)
4046 BOOL new = (lParam == 0);
4047 if (editor->bWordWrap != new)
4049 editor->bWordWrap = new;
4050 ME_RewrapRepaint(editor);
4053 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
4054 break;
4055 default:
4056 do_default:
4057 return DefWindowProcW(hWnd, msg, wParam, lParam);
4059 return 0L;
4062 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4064 BOOL unicode = TRUE;
4066 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4067 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4068 unicode = FALSE;
4070 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4073 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4075 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4078 /******************************************************************
4079 * RichEditANSIWndProc (RICHED20.10)
4081 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4083 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4086 /******************************************************************
4087 * RichEdit10ANSIWndProc (RICHED20.9)
4089 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4091 LRESULT result;
4093 /* FIXME: this is NOT the same as 2.0 version */
4094 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4095 if (msg == WM_NCCREATE)
4097 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4099 editor->bEmulateVersion10 = TRUE;
4100 editor->pBuffer->pLast->member.para.nCharOfs = 2;
4101 assert(editor->pBuffer->pLast->prev->type == diRun);
4102 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
4103 editor->pBuffer->pLast->prev->member.run.nLF = 1;
4105 return result;
4108 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4110 HWND hWnd = editor->hWnd;
4111 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
4114 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
4116 int x,y;
4117 ME_Cursor tmpCursor;
4118 BOOL isExact;
4119 int nCharOfs; /* The start of the clicked text. Absolute character offset */
4121 ME_Run *tmpRun;
4123 ENLINK info;
4124 x = (short)LOWORD(lParam);
4125 y = (short)HIWORD(lParam);
4126 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
4127 if (!isExact) return;
4129 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
4130 tmpRun = &tmpCursor.pRun->member.run;
4132 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
4133 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
4134 { /* The clicked run has CFE_LINK set */
4135 info.nmhdr.hwndFrom = editor->hWnd;
4136 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
4137 info.nmhdr.code = EN_LINK;
4138 info.msg = msg;
4139 info.wParam = wParam;
4140 info.lParam = lParam;
4141 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
4142 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
4143 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
4147 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
4149 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
4150 int i = 0;
4152 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
4153 item = item->member.para.next_para;
4154 if (!item)
4155 return 0;
4156 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
4157 item = item->member.para.next_para;
4158 i++;
4160 return i;
4164 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
4166 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
4167 int nWritten = 0;
4168 WCHAR *pStart = buffer;
4170 if (!item) {
4171 *buffer = 0;
4172 return 0;
4175 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4176 if (editor->bEmulateVersion10) bCRLF = 0;
4178 if (nStart)
4180 int nLen = ME_StrLen(item->member.run.strText) - nStart;
4181 if (nLen > nChars)
4182 nLen = nChars;
4183 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
4184 nChars -= nLen;
4185 nWritten += nLen;
4186 buffer += nLen;
4187 if (!nChars) {
4188 *buffer = 0;
4189 return nWritten;
4191 nStart = 0;
4192 item = ME_FindItemFwd(item, diRun);
4195 while(nChars && item)
4197 int nLen = ME_StrLen(item->member.run.strText);
4198 if (item->member.run.nFlags & MERF_ENDPARA)
4199 nLen = item->member.run.nCR + item->member.run.nLF;
4200 if (nLen > nChars)
4201 nLen = nChars;
4203 if (item->member.run.nFlags & MERF_ENDCELL &&
4204 item->member.run.nFlags & MERF_ENDPARA)
4206 *buffer = '\t';
4208 else if (item->member.run.nFlags & MERF_ENDPARA)
4210 if (!ME_FindItemFwd(item, diRun))
4211 /* No '\r' is appended to the last paragraph. */
4212 nLen = 0;
4213 else if (bCRLF && nChars == 1) {
4214 nLen = 0;
4215 nChars = 0;
4216 } else {
4217 if (bCRLF)
4219 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
4220 if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4221 assert(nLen == 2);
4222 else
4223 assert(nLen == 1);
4224 *buffer++ = '\r';
4225 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4226 if (nLen == 1)
4227 nWritten++;
4228 else
4229 buffer--;
4231 else
4233 int i, j;
4235 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4236 i = 0;
4237 while (nChars - i > 0 && i < item->member.run.nCR)
4239 buffer[i] = '\r'; i++;
4241 j = 0;
4242 while (nChars - i - j > 0 && j < item->member.run.nLF)
4244 buffer[i+j] = '\n'; j++;
4249 else
4250 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4251 nChars -= nLen;
4252 nWritten += nLen;
4253 buffer += nLen;
4255 if (!nChars)
4257 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4258 *buffer = 0;
4259 return nWritten;
4261 item = ME_FindItemFwd(item, diRun);
4263 *buffer = 0;
4264 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4265 return nWritten;
4268 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4270 WNDCLASSW wcW;
4271 WNDCLASSA wcA;
4273 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4274 wcW.lpfnWndProc = RichEditWndProcW;
4275 wcW.cbClsExtra = 0;
4276 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4277 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4278 wcW.hIcon = NULL;
4279 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4280 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4281 wcW.lpszMenuName = NULL;
4283 if (is_version_nt())
4285 wcW.lpszClassName = RichEdit20W;
4286 if (!RegisterClassW(&wcW)) return FALSE;
4287 wcW.lpszClassName = RichEdit50W;
4288 if (!RegisterClassW(&wcW)) return FALSE;
4290 else
4292 /* WNDCLASSA/W have the same layout */
4293 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4294 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4295 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4296 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4299 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4300 wcA.lpfnWndProc = RichEditWndProcA;
4301 wcA.cbClsExtra = 0;
4302 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4303 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4304 wcA.hIcon = NULL;
4305 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4306 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4307 wcA.lpszMenuName = NULL;
4308 wcA.lpszClassName = "RichEdit20A";
4309 if (!RegisterClassA(&wcA)) return FALSE;
4310 wcA.lpszClassName = "RichEdit50A";
4311 if (!RegisterClassA(&wcA)) return FALSE;
4313 return TRUE;
4316 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4317 /* FIXME: Not implemented */
4318 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4319 hWnd, msg, get_msg_name(msg), wParam, lParam);
4320 return DefWindowProcW(hWnd, msg, wParam, lParam);
4323 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4324 /* FIXME: Not implemented */
4325 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4326 hWnd, msg, get_msg_name(msg), wParam, lParam);
4327 return DefWindowProcW(hWnd, msg, wParam, lParam);
4330 /******************************************************************
4331 * REExtendedRegisterClass (RICHED20.8)
4333 * FIXME undocumented
4334 * Need to check for errors and implement controls and callbacks
4336 LRESULT WINAPI REExtendedRegisterClass(void)
4338 WNDCLASSW wcW;
4339 UINT result;
4341 FIXME("semi stub\n");
4343 wcW.cbClsExtra = 0;
4344 wcW.cbWndExtra = 4;
4345 wcW.hInstance = NULL;
4346 wcW.hIcon = NULL;
4347 wcW.hCursor = NULL;
4348 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4349 wcW.lpszMenuName = NULL;
4351 if (!ME_ListBoxRegistered)
4353 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4354 wcW.lpfnWndProc = REListWndProc;
4355 wcW.lpszClassName = REListBox20W;
4356 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4359 if (!ME_ComboBoxRegistered)
4361 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4362 wcW.lpfnWndProc = REComboWndProc;
4363 wcW.lpszClassName = REComboBox20W;
4364 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4367 result = 0;
4368 if (ME_ListBoxRegistered)
4369 result += 1;
4370 if (ME_ComboBoxRegistered)
4371 result += 2;
4373 return result;
4376 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
4378 struct prefix_s {
4379 const char *text;
4380 int length;
4381 } prefixes[12] = {
4382 {"http:", 5},
4383 {"file:", 6},
4384 {"mailto:", 8},
4385 {"ftp:", 5},
4386 {"https:", 7},
4387 {"gopher:", 8},
4388 {"nntp:", 6},
4389 {"prospero:", 10},
4390 {"telnet:", 8},
4391 {"news:", 6},
4392 {"wais:", 6},
4393 {"www.", 5}
4395 CHARRANGE ins_pt;
4396 int curf_ef, link_ef, def_ef;
4397 int cur_prefx, prefx_cnt;
4398 int sel_min, sel_max;
4399 int car_pos = 0;
4400 int text_pos=-1;
4401 int URLmin, URLmax = 0;
4402 FINDTEXTA ft;
4403 CHARFORMAT2W cur_format;
4404 CHARFORMAT2W default_format;
4405 CHARFORMAT2W link;
4406 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
4407 sel_min = ins_pt.cpMin;
4408 sel_max = ins_pt.cpMax;
4409 if (sel_min==sel_max)
4410 car_pos = sel_min;
4411 if (sel_min!=sel_max)
4412 car_pos = ME_GetTextLength(editor)+1;
4413 cur_format.cbSize = sizeof(cur_format);
4414 default_format.cbSize = sizeof(default_format);
4415 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
4416 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
4417 link.cbSize = sizeof(link);
4418 link.dwMask = CFM_LINK;
4419 link.dwEffects = CFE_LINK;
4420 curf_ef = cur_format.dwEffects & link.dwEffects;
4421 def_ef = default_format.dwEffects & link.dwEffects;
4422 link_ef = link.dwEffects & link.dwEffects;
4423 if (curf_ef == link_ef)
4425 if( curChar == '\n' || curChar=='\r' || curChar==' ')
4427 ME_SetSelection(editor, car_pos, car_pos);
4428 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
4429 text_pos=-1;
4430 return 0;
4433 if (curf_ef == def_ef)
4435 cur_prefx = 0;
4436 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
4437 while (cur_prefx<=prefx_cnt)
4439 if (text_pos == -1)
4441 ft.lpstrText = prefixes[cur_prefx].text;
4442 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
4443 URLmax=max(0, car_pos);
4444 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
4446 URLmax = ME_GetTextLength(editor)+1;
4448 ft.chrg.cpMin = URLmin;
4449 ft.chrg.cpMax = URLmax;
4450 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
4451 cur_prefx++;
4453 if (text_pos != -1)
4455 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
4456 ME_RewrapRepaint(editor);
4457 break;
4461 return 0;
4465 static BOOL isurlspecial(WCHAR c)
4467 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4468 return strchrW( special_chars, c ) != NULL;
4472 * This proc takes a selection, and scans it forward in order to select the span
4473 * of a possible URL candidate. A possible URL candidate must start with isalnum
4474 * or one of the following special characters: *|/\+%#@ and must consist entirely
4475 * of the characters allowed to start the URL, plus : (colon) which may occur
4476 * at most once, and not at either end.
4478 * sel_max == -1 indicates scan to end of text.
4480 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4481 int * candidate_min, int * candidate_max)
4483 ME_DisplayItem * item;
4484 ME_DisplayItem * para;
4485 int nStart;
4486 BOOL foundColon = FALSE;
4487 WCHAR lastAcceptedChar = '\0';
4489 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4491 *candidate_min = *candidate_max = -1;
4492 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4493 if (!item) return FALSE;
4494 TRACE("nStart = %d\n", nStart);
4495 para = ME_GetParagraph(item);
4496 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4497 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4499 ME_DisplayItem * next_item;
4501 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4502 /* Find start of candidate */
4503 if (*candidate_min == -1) {
4504 while (nStart < ME_StrLen(item->member.run.strText) &&
4505 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4506 isurlspecial(item->member.run.strText->szData[nStart]))) {
4507 nStart++;
4509 if (nStart < ME_StrLen(item->member.run.strText) &&
4510 (isalnumW(item->member.run.strText->szData[nStart]) ||
4511 isurlspecial(item->member.run.strText->szData[nStart]))) {
4512 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4513 lastAcceptedChar = item->member.run.strText->szData[nStart];
4514 nStart++;
4518 /* Find end of candidate */
4519 if (*candidate_min >= 0) {
4520 while (nStart < ME_StrLen(item->member.run.strText) &&
4521 (isalnumW(item->member.run.strText->szData[nStart]) ||
4522 isurlspecial(item->member.run.strText->szData[nStart]) ||
4523 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4524 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4525 lastAcceptedChar = item->member.run.strText->szData[nStart];
4526 nStart++;
4528 if (nStart < ME_StrLen(item->member.run.strText) &&
4529 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4530 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4531 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4532 nStart++;
4533 if (lastAcceptedChar == ':') (*candidate_max)--;
4534 return TRUE;
4537 } else {
4538 /* End of paragraph: skip it if before candidate span, or terminates
4539 current active span */
4540 if (*candidate_min >= 0) {
4541 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4542 if (lastAcceptedChar == ':') (*candidate_max)--;
4543 return TRUE;
4547 /* Reaching this point means no span was found, so get next span */
4548 next_item = ME_FindItemFwd(item, diRun);
4549 if (!next_item) {
4550 if (*candidate_min >= 0) {
4551 /* There are no further runs, so take end of text as end of candidate */
4552 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4553 if (lastAcceptedChar == ':') (*candidate_max)--;
4554 return TRUE;
4557 item = next_item;
4558 para = ME_GetParagraph(item);
4559 nStart = 0;
4562 if (item) {
4563 if (*candidate_min >= 0) {
4564 /* There are no further runs, so take end of text as end of candidate */
4565 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4566 if (lastAcceptedChar == ':') (*candidate_max)--;
4567 return TRUE;
4570 return FALSE;
4574 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4576 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4578 struct prefix_s {
4579 const char *text;
4580 int length;
4581 } prefixes[12] = {
4582 /* Code below depends on these being in decreasing length order! */
4583 {"prospero:", 10},
4584 {"telnet:", 8},
4585 {"gopher:", 8},
4586 {"mailto:", 8},
4587 {"https:", 7},
4588 {"file:", 6},
4589 {"news:", 6},
4590 {"wais:", 6},
4591 {"nntp:", 6},
4592 {"http:", 5},
4593 {"www.", 5},
4594 {"ftp:", 5},
4596 LPWSTR bufferW = NULL;
4597 WCHAR bufW[32];
4598 int i;
4600 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4601 assert(sel_min <= sel_max);
4602 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4604 if (sel_max - sel_min < prefixes[i].length) continue;
4605 if (bufferW == NULL) {
4606 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4608 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4609 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4610 if (!lstrcmpW(bufW, bufferW))
4612 heap_free(bufferW);
4613 return TRUE;
4616 heap_free(bufferW);
4617 return FALSE;
4621 * This proc walks through the indicated selection and evaluates whether each
4622 * section identified by ME_FindNextURLCandidate and in-between sections have
4623 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4624 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4626 * Returns TRUE if at least one section was modified.
4628 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4630 BOOL modified = FALSE;
4631 int cMin, cMax;
4633 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4636 int beforeURL[2];
4637 int inURL[2];
4638 CHARFORMAT2W link;
4640 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4642 /* Section before candidate is not an URL */
4643 beforeURL[0] = sel_min;
4644 beforeURL[1] = cMin;
4646 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4648 inURL[0] = cMin; inURL[1] = cMax;
4650 else
4652 beforeURL[1] = cMax;
4653 inURL[0] = inURL[1] = -1;
4655 sel_min = cMax;
4657 else
4659 /* No more candidates until end of selection */
4660 beforeURL[0] = sel_min;
4661 beforeURL[1] = sel_max;
4662 inURL[0] = inURL[1] = -1;
4663 sel_min = sel_max;
4666 if (beforeURL[0] < beforeURL[1])
4668 /* CFE_LINK effect should be consistently unset */
4669 link.cbSize = sizeof(link);
4670 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4671 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4673 /* CFE_LINK must be unset from this range */
4674 memset(&link, 0, sizeof(CHARFORMAT2W));
4675 link.cbSize = sizeof(link);
4676 link.dwMask = CFM_LINK;
4677 link.dwEffects = 0;
4678 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4679 modified = TRUE;
4682 if (inURL[0] < inURL[1])
4684 /* CFE_LINK effect should be consistently set */
4685 link.cbSize = sizeof(link);
4686 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4687 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4689 /* CFE_LINK must be set on this range */
4690 memset(&link, 0, sizeof(CHARFORMAT2W));
4691 link.cbSize = sizeof(link);
4692 link.dwMask = CFM_LINK;
4693 link.dwEffects = CFE_LINK;
4694 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4695 modified = TRUE;
4698 } while (sel_min < sel_max);
4699 return modified;
4702 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4704 ME_DisplayItem * startPara, * endPara;
4705 ME_DisplayItem * item;
4706 int dummy;
4707 int from, to;
4709 ME_GetSelection(editor, &from, &to);
4710 if (from > to) from ^= to, to ^=from, from ^= to;
4711 startPara = NULL; endPara = NULL;
4713 /* Find paragraph previous to the one that contains start cursor */
4714 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4715 if (item) {
4716 startPara = ME_FindItemBack(item, diParagraph);
4717 item = ME_FindItemBack(startPara, diParagraph);
4718 if (item) startPara = item;
4721 /* Find paragraph that contains end cursor */
4722 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4723 if (item) {
4724 endPara = ME_FindItemFwd(item, diParagraph);
4727 if (startPara && endPara) {
4728 ME_UpdateLinkAttribute(editor,
4729 startPara->member.para.nCharOfs,
4730 endPara->member.para.nCharOfs);
4731 } else if (startPara) {
4732 ME_UpdateLinkAttribute(editor,
4733 startPara->member.para.nCharOfs,
4734 -1);