wininet: Fix trace typo.
[wine/multimedia.git] / dlls / riched20 / editor.c
blobf78e5155bd980c2d3e3698fb82d4c81ca6000439
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 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 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 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:
847 int cellNum;
848 if (!info->tableDef)
850 info->tableDef = ME_MakeTableDef(info->editor);
852 cellNum = info->tableDef->numCellsDefined;
853 if (cellNum >= MAX_TABLE_CELLS)
854 break;
855 info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
856 if (cellNum < MAX_TAB_STOPS) {
857 /* Tab stops were used to store cell positions before v4.1 but v4.1
858 * still seems to set the tabstops without using them. */
859 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
860 PARAFORMAT2 *pFmt = para->member.para.pFmt;
861 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
862 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
864 info->tableDef->numCellsDefined++;
865 break;
867 case rtfRowBordTop:
868 info->borderType = RTFBorderRowTop;
869 break;
870 case rtfRowBordLeft:
871 info->borderType = RTFBorderRowLeft;
872 break;
873 case rtfRowBordBottom:
874 info->borderType = RTFBorderRowBottom;
875 break;
876 case rtfRowBordRight:
877 info->borderType = RTFBorderRowRight;
878 break;
879 case rtfCellBordTop:
880 info->borderType = RTFBorderCellTop;
881 break;
882 case rtfCellBordLeft:
883 info->borderType = RTFBorderCellLeft;
884 break;
885 case rtfCellBordBottom:
886 info->borderType = RTFBorderCellBottom;
887 break;
888 case rtfCellBordRight:
889 info->borderType = RTFBorderCellRight;
890 break;
891 case rtfRowGapH:
892 if (info->tableDef)
893 info->tableDef->gapH = info->rtfParam;
894 break;
895 case rtfRowLeftEdge:
896 if (info->tableDef)
897 info->tableDef->leftEdge = info->rtfParam;
898 break;
902 void ME_RTFSpecialCharHook(RTF_Info *info)
904 RTFTable *tableDef = info->tableDef;
905 switch (info->rtfMinor)
907 case rtfNestCell:
908 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
909 break;
910 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
911 case rtfCell:
912 if (!tableDef)
913 break;
914 RTFFlushOutputBuffer(info);
915 if (!info->editor->bEmulateVersion10) { /* v4.1 */
916 if (tableDef->tableRowStart)
918 if (!info->nestingLevel &&
919 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
921 ME_DisplayItem *para = tableDef->tableRowStart;
922 para = para->member.para.next_para;
923 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
924 tableDef->tableRowStart = para;
925 info->nestingLevel = 1;
927 ME_InsertTableCellFromCursor(info->editor);
929 } else { /* v1.0 - v3.0 */
930 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
931 PARAFORMAT2 *pFmt = para->member.para.pFmt;
932 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
933 tableDef->numCellsInserted < tableDef->numCellsDefined)
935 WCHAR tab = '\t';
936 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
937 tableDef->numCellsInserted++;
940 break;
941 case rtfNestRow:
942 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
943 break;
944 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
945 case rtfRow:
947 ME_DisplayItem *para, *cell, *run;
948 int i;
950 if (!tableDef)
951 break;
952 RTFFlushOutputBuffer(info);
953 if (!info->editor->bEmulateVersion10) { /* v4.1 */
954 if (!tableDef->tableRowStart)
955 break;
956 if (!info->nestingLevel &&
957 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
959 para = tableDef->tableRowStart;
960 para = para->member.para.next_para;
961 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
962 tableDef->tableRowStart = para;
963 info->nestingLevel++;
965 para = tableDef->tableRowStart;
966 cell = ME_FindItemFwd(para, diCell);
967 assert(cell && !cell->member.cell.prev_cell);
968 if (tableDef->numCellsDefined < 1)
970 /* 2000 twips appears to be the cell size that native richedit uses
971 * when no cell sizes are specified. */
972 const int defaultCellSize = 2000;
973 int nRightBoundary = defaultCellSize;
974 cell->member.cell.nRightBoundary = nRightBoundary;
975 while (cell->member.cell.next_cell) {
976 cell = cell->member.cell.next_cell;
977 nRightBoundary += defaultCellSize;
978 cell->member.cell.nRightBoundary = nRightBoundary;
980 para = ME_InsertTableCellFromCursor(info->editor);
981 cell = para->member.para.pCell;
982 cell->member.cell.nRightBoundary = nRightBoundary;
983 } else {
984 for (i = 0; i < tableDef->numCellsDefined; i++)
986 RTFCell *cellDef = &tableDef->cells[i];
987 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
988 ME_ApplyBorderProperties(info, &cell->member.cell.border,
989 cellDef->border);
990 cell = cell->member.cell.next_cell;
991 if (!cell)
993 para = ME_InsertTableCellFromCursor(info->editor);
994 cell = para->member.para.pCell;
997 /* Cell for table row delimiter is empty */
998 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1001 run = ME_FindItemFwd(cell, diRun);
1002 if (info->editor->pCursors[0].pRun != run ||
1003 info->editor->pCursors[0].nOffset)
1005 int nOfs, nChars;
1006 /* Delete inserted cells that aren't defined. */
1007 info->editor->pCursors[1].pRun = run;
1008 info->editor->pCursors[1].nOffset = 0;
1009 nOfs = ME_GetCursorOfs(info->editor, 1);
1010 nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
1011 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
1014 para = ME_InsertTableRowEndFromCursor(info->editor);
1015 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1016 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1017 ME_ApplyBorderProperties(info, &para->member.para.border,
1018 tableDef->border);
1019 info->nestingLevel--;
1020 if (!info->nestingLevel)
1022 if (info->canInheritInTbl) {
1023 tableDef->tableRowStart = para;
1024 } else {
1025 while (info->tableDef) {
1026 tableDef = info->tableDef;
1027 info->tableDef = tableDef->parent;
1028 heap_free(tableDef);
1031 } else {
1032 info->tableDef = tableDef->parent;
1033 heap_free(tableDef);
1035 } else { /* v1.0 - v3.0 */
1036 WCHAR endl = '\r';
1037 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1038 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1039 pFmt->dxOffset = info->tableDef->gapH;
1040 pFmt->dxStartIndent = info->tableDef->leftEdge;
1042 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1043 ME_ApplyBorderProperties(info, &para->member.para.border,
1044 tableDef->border);
1045 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1047 WCHAR tab = '\t';
1048 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1049 tableDef->numCellsInserted++;
1051 pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1052 if (!tableDef->numCellsDefined)
1053 pFmt->wEffects &= ~PFE_TABLE;
1054 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1055 tableDef->numCellsInserted = 0;
1057 break;
1059 case rtfTab:
1060 case rtfPar:
1061 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1062 ME_DisplayItem *para;
1063 PARAFORMAT2 *pFmt;
1064 RTFFlushOutputBuffer(info);
1065 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1066 pFmt = para->member.para.pFmt;
1067 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1069 /* rtfPar is treated like a space within a table. */
1070 info->rtfClass = rtfText;
1071 info->rtfMajor = ' ';
1073 else if (info->rtfMinor == rtfPar && tableDef)
1074 tableDef->numCellsInserted = 0;
1076 break;
1080 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1081 const SIZEL* sz)
1083 LPOLEOBJECT lpObject = NULL;
1084 LPSTORAGE lpStorage = NULL;
1085 LPOLECLIENTSITE lpClientSite = NULL;
1086 LPDATAOBJECT lpDataObject = NULL;
1087 LPOLECACHE lpOleCache = NULL;
1088 STGMEDIUM stgm;
1089 FORMATETC fm;
1090 CLSID clsid;
1091 BOOL ret = FALSE;
1092 DWORD conn;
1094 if (hemf)
1096 stgm.tymed = TYMED_ENHMF;
1097 stgm.u.hEnhMetaFile = hemf;
1098 fm.cfFormat = CF_ENHMETAFILE;
1100 else if (hbmp)
1102 stgm.tymed = TYMED_GDI;
1103 stgm.u.hBitmap = hbmp;
1104 fm.cfFormat = CF_BITMAP;
1106 stgm.pUnkForRelease = NULL;
1108 fm.ptd = NULL;
1109 fm.dwAspect = DVASPECT_CONTENT;
1110 fm.lindex = -1;
1111 fm.tymed = stgm.tymed;
1113 if (!info->lpRichEditOle)
1115 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1118 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1119 #if 0
1120 /* FIXME: enable it when rich-edit properly implements this method */
1121 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1122 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1123 #endif
1124 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1125 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1126 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1127 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1128 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1130 REOBJECT reobject;
1132 reobject.cbStruct = sizeof(reobject);
1133 reobject.cp = REO_CP_SELECTION;
1134 reobject.clsid = clsid;
1135 reobject.poleobj = lpObject;
1136 reobject.pstg = lpStorage;
1137 reobject.polesite = lpClientSite;
1138 /* convert from twips to .01 mm */
1139 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1140 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1141 reobject.dvaspect = DVASPECT_CONTENT;
1142 reobject.dwFlags = 0; /* FIXME */
1143 reobject.dwUser = 0;
1145 /* FIXME: could be simpler */
1146 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1149 if (lpObject) IOleObject_Release(lpObject);
1150 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1151 if (lpStorage) IStorage_Release(lpStorage);
1152 if (lpDataObject) IDataObject_Release(lpDataObject);
1153 if (lpOleCache) IOleCache_Release(lpOleCache);
1155 return ret;
1158 static void ME_RTFReadPictGroup(RTF_Info *info)
1160 SIZEL sz;
1161 BYTE* buffer = NULL;
1162 unsigned bufsz, bufidx;
1163 BOOL flip;
1164 BYTE val;
1165 METAFILEPICT mfp;
1166 HENHMETAFILE hemf;
1167 HBITMAP hbmp;
1168 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1170 RTFGetToken (info);
1171 if (info->rtfClass == rtfEOF)
1172 return;
1173 mfp.mm = MM_TEXT;
1174 /* fetch picture type */
1175 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1177 mfp.mm = info->rtfParam;
1178 gfx = gfx_metafile;
1180 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1182 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1183 gfx = gfx_dib;
1185 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1187 gfx = gfx_enhmetafile;
1189 else
1191 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1192 goto skip_group;
1194 sz.cx = sz.cy = 0;
1195 /* fetch picture attributes */
1196 for (;;)
1198 RTFGetToken (info);
1199 if (info->rtfClass == rtfEOF)
1200 return;
1201 if (info->rtfClass == rtfText)
1202 break;
1203 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1205 ERR("Expected picture attribute (%d %d)\n",
1206 info->rtfClass, info->rtfMajor);
1207 goto skip_group;
1209 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1211 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1213 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1215 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1217 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1218 sz.cx = info->rtfParam;
1219 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1220 sz.cy = info->rtfParam;
1221 else
1222 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1224 /* fetch picture data */
1225 bufsz = 1024;
1226 bufidx = 0;
1227 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1228 val = info->rtfMajor;
1229 for (flip = TRUE;; flip = !flip)
1231 RTFGetToken (info);
1232 if (info->rtfClass == rtfEOF)
1234 HeapFree(GetProcessHeap(), 0, buffer);
1235 return; /* Warn ?? */
1237 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1238 break;
1239 if (info->rtfClass != rtfText) goto skip_group;
1240 if (flip)
1242 if (bufidx >= bufsz &&
1243 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1244 goto skip_group;
1245 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1247 else
1248 val = info->rtfMajor;
1250 if (flip) FIXME("wrong hex string\n");
1252 switch (gfx)
1254 case gfx_enhmetafile:
1255 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1256 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1257 break;
1258 case gfx_metafile:
1259 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1260 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1261 break;
1262 case gfx_dib:
1264 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1265 HDC hdc = GetDC(0);
1266 unsigned nc = bi->bmiHeader.biClrUsed;
1268 /* not quite right, especially for bitfields type of compression */
1269 if (!nc && bi->bmiHeader.biBitCount <= 8)
1270 nc = 1 << bi->bmiHeader.biBitCount;
1271 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1272 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1273 bi, DIB_RGB_COLORS)))
1274 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1275 ReleaseDC(0, hdc);
1277 break;
1278 default:
1279 break;
1281 HeapFree(GetProcessHeap(), 0, buffer);
1282 RTFRouteToken (info); /* feed "}" back to router */
1283 return;
1284 skip_group:
1285 HeapFree(GetProcessHeap(), 0, buffer);
1286 RTFSkipGroup(info);
1287 RTFRouteToken(info); /* feed "}" back to router */
1290 /* for now, lookup the \result part and use it, whatever the object */
1291 static void ME_RTFReadObjectGroup(RTF_Info *info)
1293 for (;;)
1295 RTFGetToken (info);
1296 if (info->rtfClass == rtfEOF)
1297 return;
1298 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1299 break;
1300 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1302 RTFGetToken (info);
1303 if (info->rtfClass == rtfEOF)
1304 return;
1305 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1307 int level = 1;
1309 while (RTFGetToken (info) != rtfEOF)
1311 if (info->rtfClass == rtfGroup)
1313 if (info->rtfMajor == rtfBeginGroup) level++;
1314 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1316 RTFRouteToken(info);
1319 else RTFSkipGroup(info);
1320 continue;
1322 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1324 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1325 return;
1328 RTFRouteToken(info); /* feed "}" back to router */
1331 static void ME_RTFReadHook(RTF_Info *info)
1333 switch(info->rtfClass)
1335 case rtfGroup:
1336 switch(info->rtfMajor)
1338 case rtfBeginGroup:
1339 if (info->stackTop < maxStack) {
1340 info->stack[info->stackTop].fmt = info->style->fmt;
1341 info->stack[info->stackTop].codePage = info->codePage;
1342 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1344 info->stackTop++;
1345 info->styleChanged = FALSE;
1346 break;
1347 case rtfEndGroup:
1349 ME_Style *s;
1350 RTFFlushOutputBuffer(info);
1351 info->stackTop--;
1352 if (info->stackTop<=0) {
1353 info->rtfClass = rtfEOF;
1354 return;
1356 assert(info->stackTop >= 0);
1357 if (info->styleChanged)
1359 /* FIXME too slow ? how come ? */
1360 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1361 ME_ReleaseStyle(info->style);
1362 info->style = s;
1363 info->codePage = info->stack[info->stackTop].codePage;
1364 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1366 break;
1369 break;
1373 void
1374 ME_StreamInFill(ME_InStream *stream)
1376 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1377 (BYTE *)stream->buffer,
1378 sizeof(stream->buffer),
1379 (LONG *)&stream->dwSize);
1380 stream->dwUsed = 0;
1383 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1385 RTF_Info parser;
1386 ME_Style *style;
1387 int from, to, to2, nUndoMode;
1388 int nEventMask = editor->nEventMask;
1389 ME_InStream inStream;
1390 BOOL invalidRTF = FALSE;
1392 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1393 editor->nEventMask = 0;
1395 ME_GetSelection(editor, &from, &to);
1396 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1397 style = ME_GetSelectionInsertStyle(editor);
1399 ME_InternalDeleteText(editor, from, to-from, FALSE);
1401 /* Don't insert text at the end of the table row */
1402 if (!editor->bEmulateVersion10) { /* v4.1 */
1403 ME_DisplayItem *para = ME_GetParagraph(editor->pCursors->pRun);
1404 if (para->member.para.nFlags & MEPF_ROWEND)
1406 para = para->member.para.next_para;
1407 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1408 editor->pCursors[0].nOffset = 0;
1410 if (para->member.para.nFlags & MEPF_ROWSTART)
1412 para = para->member.para.next_para;
1413 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1414 editor->pCursors[0].nOffset = 0;
1416 editor->pCursors[1] = editor->pCursors[0];
1417 } else { /* v1.0 - 3.0 */
1418 if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1419 ME_IsInTable(editor->pCursors[0].pRun))
1420 return 0;
1423 else {
1424 ME_DisplayItem *para_item;
1425 style = editor->pBuffer->pDefaultStyle;
1426 ME_AddRefStyle(style);
1427 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1428 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1429 from = to = 0;
1430 ME_ClearTempStyle(editor);
1432 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1433 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1437 /* Back up undo mode to a local variable */
1438 nUndoMode = editor->nUndoMode;
1440 /* Only create an undo if SFF_SELECTION is set */
1441 if (!(format & SFF_SELECTION))
1442 editor->nUndoMode = umIgnore;
1444 inStream.editstream = stream;
1445 inStream.editstream->dwError = 0;
1446 inStream.dwSize = 0;
1447 inStream.dwUsed = 0;
1449 if (format & SF_RTF)
1451 /* Check if it's really RTF, and if it is not, use plain text */
1452 ME_StreamInFill(&inStream);
1453 if (!inStream.editstream->dwError)
1455 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1456 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1458 invalidRTF = TRUE;
1459 inStream.editstream->dwError = -16;
1464 if (!invalidRTF && !inStream.editstream->dwError)
1466 if (format & SF_RTF) {
1467 /* setup the RTF parser */
1468 memset(&parser, 0, sizeof parser);
1469 RTFSetEditStream(&parser, &inStream);
1470 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1471 parser.hwndEdit = editor->hWnd;
1472 parser.editor = editor;
1473 parser.style = style;
1474 WriterInit(&parser);
1475 RTFInit(&parser);
1476 RTFSetReadHook(&parser, ME_RTFReadHook);
1477 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1478 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1479 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1481 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1482 RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1484 BeginFile(&parser);
1486 /* do the parsing */
1487 RTFRead(&parser);
1488 RTFFlushOutputBuffer(&parser);
1489 if (!editor->bEmulateVersion10) { /* v4.1 */
1490 if (parser.tableDef && parser.tableDef->tableRowStart &&
1491 (parser.nestingLevel > 0 || parser.canInheritInTbl))
1493 /* Delete any incomplete table row at the end of the rich text. */
1494 int nOfs, nChars;
1495 ME_DisplayItem *pCell;
1496 ME_DisplayItem *para;
1498 parser.rtfMinor = rtfRow;
1499 /* Complete the table row before deleting it.
1500 * By doing it this way we will have the current paragraph format set
1501 * properly to reflect that is not in the complete table, and undo items
1502 * will be added for this change to the current paragraph format. */
1503 if (parser.nestingLevel > 0)
1505 while (parser.nestingLevel > 1)
1506 ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1507 para = parser.tableDef->tableRowStart;
1508 ME_RTFSpecialCharHook(&parser);
1509 } else {
1510 para = parser.tableDef->tableRowStart;
1511 ME_RTFSpecialCharHook(&parser);
1512 assert(para->member.para.nFlags & MEPF_ROWEND);
1513 para = para->member.para.next_para;
1515 pCell = para->member.para.pCell;
1517 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1518 editor->pCursors[1].nOffset = 0;
1519 nOfs = ME_GetCursorOfs(editor, 1);
1520 nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1521 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1522 if (parser.tableDef)
1523 parser.tableDef->tableRowStart = NULL;
1526 ME_CheckTablesForCorruption(editor);
1527 RTFDestroy(&parser);
1528 if (parser.lpRichEditOle)
1529 IRichEditOle_Release(parser.lpRichEditOle);
1531 if (!inStream.editstream->dwError && parser.stackTop > 0)
1532 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1534 /* Remove last line break, as mandated by tests. This is not affected by
1535 CR/LF counters, since RTF streaming presents only \para tokens, which
1536 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1538 if (stripLastCR) {
1539 int newfrom, newto;
1540 ME_GetSelection(editor, &newfrom, &newto);
1541 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1542 WCHAR lastchar[3] = {'\0', '\0'};
1543 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1545 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1546 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1547 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1552 style = parser.style;
1554 else if (format & SF_TEXT)
1555 ME_StreamInText(editor, format, &inStream, style);
1556 else
1557 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1558 ME_GetSelection(editor, &to, &to2);
1559 /* put the cursor at the top */
1560 if (!(format & SFF_SELECTION))
1561 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1564 /* Restore saved undo mode */
1565 editor->nUndoMode = nUndoMode;
1567 /* even if we didn't add an undo, we need to commit anything on the stack */
1568 ME_CommitUndo(editor);
1570 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1571 if (!(format & SFF_SELECTION))
1572 ME_EmptyUndoStack(editor);
1574 ME_ReleaseStyle(style);
1575 editor->nEventMask = nEventMask;
1576 ME_UpdateRepaint(editor);
1577 if (!(format & SFF_SELECTION)) {
1578 ME_ClearTempStyle(editor);
1580 HideCaret(editor->hWnd);
1581 ME_MoveCaret(editor);
1582 ShowCaret(editor->hWnd);
1583 ME_SendSelChange(editor);
1584 ME_SendRequestResize(editor, FALSE);
1586 return 0;
1590 typedef struct tagME_RTFStringStreamStruct
1592 char *string;
1593 int pos;
1594 int length;
1595 } ME_RTFStringStreamStruct;
1597 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1599 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1600 int count;
1602 count = min(cb, pStruct->length - pStruct->pos);
1603 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1604 pStruct->pos += count;
1605 *pcb = count;
1606 return 0;
1609 static void
1610 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1612 EDITSTREAM es;
1613 ME_RTFStringStreamStruct data;
1615 data.string = string;
1616 data.length = strlen(string);
1617 data.pos = 0;
1618 es.dwCookie = (DWORD)&data;
1619 es.pfnCallback = ME_ReadFromRTFString;
1620 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1624 ME_DisplayItem *
1625 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1627 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1628 int runLength;
1630 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1631 item = ME_FindItemFwd(item, diParagraph);
1633 if (!item)
1634 return item;
1636 nOffset -= item->member.para.nCharOfs;
1637 if (nItemType == diParagraph) {
1638 if (nItemOffset)
1639 *nItemOffset = nOffset;
1640 return item;
1643 do {
1644 item = ME_FindItemFwd(item, diRun);
1645 runLength = ME_StrLen(item->member.run.strText);
1646 if (item->member.run.nFlags & MERF_ENDPARA)
1647 runLength = item->member.run.nCR + item->member.run.nLF;
1648 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1649 if (item) {
1650 nOffset -= item->member.run.nCharOfs;
1652 /* Special case: nOffset may not point exactly at the division between the
1653 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1654 into the next run, if one exists
1656 if ( item->member.run.nFlags & MERF_ENDPARA
1657 && nOffset == item->member.run.nCR
1658 && item->member.run.nLF > 0) {
1659 ME_DisplayItem *nextItem;
1660 nextItem = ME_FindItemFwd(item, diRun);
1661 if (nextItem) {
1662 nOffset = 0;
1663 item = nextItem;
1666 if (nItemOffset)
1667 *nItemOffset = nOffset;
1669 return item;
1673 static int
1674 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1676 const int nLen = lstrlenW(text);
1677 const int nTextLen = ME_GetTextLength(editor);
1678 int nStart, nEnd;
1679 int nMin, nMax;
1680 ME_DisplayItem *item;
1681 ME_DisplayItem *para;
1682 WCHAR wLastChar = ' ';
1684 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1685 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1687 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1688 FIXME("Flags 0x%08x not implemented\n",
1689 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1691 nMin = chrg->cpMin;
1692 if (chrg->cpMax == -1)
1693 nMax = nTextLen;
1694 else
1695 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1697 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1698 if (editor->bEmulateVersion10 && nMax == nTextLen)
1700 flags |= FR_DOWN;
1703 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1704 if (editor->bEmulateVersion10 && nMax < nMin)
1706 if (chrgText)
1708 chrgText->cpMin = -1;
1709 chrgText->cpMax = -1;
1711 return -1;
1714 /* when searching up, if cpMin < cpMax, then instead of searching
1715 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1716 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1717 * case, it is always bigger than cpMin.
1719 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1721 int nSwap = nMax;
1723 nMax = nMin > nTextLen ? nTextLen : nMin;
1724 if (nMin < nSwap || chrg->cpMax == -1)
1725 nMin = 0;
1726 else
1727 nMin = nSwap;
1730 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1732 if (chrgText)
1733 chrgText->cpMin = chrgText->cpMax = -1;
1734 return -1;
1737 if (flags & FR_DOWN) /* Forward search */
1739 /* If possible, find the character before where the search starts */
1740 if ((flags & FR_WHOLEWORD) && nMin)
1742 nStart = nMin - 1;
1743 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1744 if (!item)
1746 if (chrgText)
1747 chrgText->cpMin = chrgText->cpMax = -1;
1748 return -1;
1750 wLastChar = item->member.run.strText->szData[nStart];
1753 nStart = nMin;
1754 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1755 if (!item)
1757 if (chrgText)
1758 chrgText->cpMin = chrgText->cpMax = -1;
1759 return -1;
1762 para = ME_GetParagraph(item);
1763 while (item
1764 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1766 ME_DisplayItem *pCurItem = item;
1767 int nCurStart = nStart;
1768 int nMatched = 0;
1770 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1772 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1773 break;
1775 nMatched++;
1776 if (nMatched == nLen)
1778 ME_DisplayItem *pNextItem = pCurItem;
1779 int nNextStart = nCurStart;
1780 WCHAR wNextChar;
1782 /* Check to see if next character is a whitespace */
1783 if (flags & FR_WHOLEWORD)
1785 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1787 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1788 nNextStart = -nMatched;
1791 if (pNextItem)
1792 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1793 else
1794 wNextChar = ' ';
1796 if (isalnumW(wNextChar))
1797 break;
1800 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1801 if (chrgText)
1803 chrgText->cpMin = nStart;
1804 chrgText->cpMax = nStart + nLen;
1806 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1807 return nStart;
1809 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1811 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1812 para = ME_GetParagraph(pCurItem);
1813 nCurStart = -nMatched;
1816 if (pCurItem)
1817 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1818 else
1819 wLastChar = ' ';
1821 nStart++;
1822 if (nStart == ME_StrLen(item->member.run.strText))
1824 item = ME_FindItemFwd(item, diRun);
1825 para = ME_GetParagraph(item);
1826 nStart = 0;
1830 else /* Backward search */
1832 /* If possible, find the character after where the search ends */
1833 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1835 nEnd = nMax + 1;
1836 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1837 if (!item)
1839 if (chrgText)
1840 chrgText->cpMin = chrgText->cpMax = -1;
1841 return -1;
1843 wLastChar = item->member.run.strText->szData[nEnd];
1846 nEnd = nMax;
1847 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1848 if (!item)
1850 if (chrgText)
1851 chrgText->cpMin = chrgText->cpMax = -1;
1852 return -1;
1855 para = ME_GetParagraph(item);
1857 while (item
1858 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1860 ME_DisplayItem *pCurItem = item;
1861 int nCurEnd = nEnd;
1862 int nMatched = 0;
1864 if (nCurEnd - nMatched == 0)
1866 pCurItem = ME_FindItemBack(pCurItem, diRun);
1867 para = ME_GetParagraph(pCurItem);
1868 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1871 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1873 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1874 break;
1876 nMatched++;
1877 if (nMatched == nLen)
1879 ME_DisplayItem *pPrevItem = pCurItem;
1880 int nPrevEnd = nCurEnd;
1881 WCHAR wPrevChar;
1883 /* Check to see if previous character is a whitespace */
1884 if (flags & FR_WHOLEWORD)
1886 if (nPrevEnd - nMatched == 0)
1888 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1889 if (pPrevItem)
1890 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1893 if (pPrevItem)
1894 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1895 else
1896 wPrevChar = ' ';
1898 if (isalnumW(wPrevChar))
1899 break;
1902 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1903 if (chrgText)
1905 chrgText->cpMin = nStart;
1906 chrgText->cpMax = nStart + nLen;
1908 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1909 return nStart;
1911 if (nCurEnd - nMatched == 0)
1913 pCurItem = ME_FindItemBack(pCurItem, diRun);
1914 /* Don't care about pCurItem becoming NULL here; it's already taken
1915 * care of in the exterior loop condition */
1916 para = ME_GetParagraph(pCurItem);
1917 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1920 if (pCurItem)
1921 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1922 else
1923 wLastChar = ' ';
1925 nEnd--;
1926 if (nEnd < 0)
1928 item = ME_FindItemBack(item, diRun);
1929 para = ME_GetParagraph(item);
1930 nEnd = ME_StrLen(item->member.run.strText);
1934 TRACE("not found\n");
1935 if (chrgText)
1936 chrgText->cpMin = chrgText->cpMax = -1;
1937 return -1;
1940 /* helper to send a msg filter notification */
1941 static BOOL
1942 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1944 MSGFILTER msgf;
1946 msgf.nmhdr.hwndFrom = editor->hWnd;
1947 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1948 msgf.nmhdr.code = EN_MSGFILTER;
1949 msgf.msg = msg;
1951 msgf.wParam = *wParam;
1952 msgf.lParam = *lParam;
1953 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1954 return FALSE;
1955 *wParam = msgf.wParam;
1956 *lParam = msgf.lParam;
1957 msgf.wParam = *wParam;
1959 return TRUE;
1962 static BOOL
1963 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1965 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1966 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1968 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1969 editor->nSelectionType = stPosition;
1971 switch (nKey)
1973 case VK_LEFT:
1974 case VK_RIGHT:
1975 case VK_HOME:
1976 case VK_END:
1977 editor->nUDArrowX = -1;
1978 /* fall through */
1979 case VK_UP:
1980 case VK_DOWN:
1981 case VK_PRIOR:
1982 case VK_NEXT:
1983 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1984 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1985 return TRUE;
1986 case VK_BACK:
1987 case VK_DELETE:
1988 editor->nUDArrowX = -1;
1989 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1990 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1991 return FALSE;
1992 if (ME_IsSelection(editor))
1994 ME_DeleteSelection(editor);
1995 ME_CommitUndo(editor);
1997 else if (nKey == VK_DELETE)
1999 /* Delete stops group typing.
2000 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2001 ME_DeleteTextAtCursor(editor, 1, 1);
2002 ME_CommitUndo(editor);
2004 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2006 BOOL bDeletionSucceeded;
2007 /* Backspace can be grouped for a single undo */
2008 ME_ContinueCoalescingTransaction(editor);
2009 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2010 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2011 /* Deletion was prevented so the cursor is moved back to where it was.
2012 * (e.g. this happens when trying to delete cell boundaries)
2014 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2016 ME_CommitCoalescingUndo(editor);
2018 else
2019 return TRUE;
2020 ME_MoveCursorFromTableRowStartParagraph(editor);
2021 ME_UpdateSelectionLinkAttribute(editor);
2022 ME_UpdateRepaint(editor);
2023 ME_SendRequestResize(editor, FALSE);
2024 return TRUE;
2026 default:
2027 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2028 editor->nUDArrowX = -1;
2029 if (ctrl_is_down)
2031 if (nKey == 'W')
2033 CHARFORMAT2W chf;
2034 char buf[2048];
2035 chf.cbSize = sizeof(chf);
2037 ME_GetSelectionCharFormat(editor, &chf);
2038 ME_DumpStyleToBuf(&chf, buf);
2039 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2041 if (nKey == 'Q')
2043 ME_CheckCharOffsets(editor);
2047 return FALSE;
2050 /* Process the message and calculate the new click count.
2052 * returns: The click count if it is mouse down event, else returns 0. */
2053 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
2054 LPARAM lParam)
2056 static int clickNum = 0;
2057 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2058 return 0;
2060 if ((msg == WM_LBUTTONDBLCLK) ||
2061 (msg == WM_RBUTTONDBLCLK) ||
2062 (msg == WM_MBUTTONDBLCLK) ||
2063 (msg == WM_XBUTTONDBLCLK))
2065 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2068 if ((msg == WM_LBUTTONDOWN) ||
2069 (msg == WM_RBUTTONDOWN) ||
2070 (msg == WM_MBUTTONDOWN) ||
2071 (msg == WM_XBUTTONDOWN))
2073 static MSG prevClickMsg;
2074 MSG clickMsg;
2075 clickMsg.hwnd = hWnd;
2076 clickMsg.message = msg;
2077 clickMsg.wParam = wParam;
2078 clickMsg.lParam = lParam;
2079 clickMsg.time = GetMessageTime();
2080 clickMsg.pt.x = (short)LOWORD(lParam);
2081 clickMsg.pt.y = (short)HIWORD(lParam);
2082 if ((clickNum != 0) &&
2083 (clickMsg.message == prevClickMsg.message) &&
2084 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2085 (clickMsg.wParam == prevClickMsg.wParam) &&
2086 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2087 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2088 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2090 clickNum++;
2091 } else {
2092 clickNum = 1;
2094 prevClickMsg = clickMsg;
2095 } else {
2096 return 0;
2098 return clickNum;
2101 static BOOL ME_SetCursor(ME_TextEditor *editor)
2103 POINT pt;
2104 BOOL isExact;
2105 int offset;
2106 SCROLLBARINFO sbi;
2107 DWORD messagePos = GetMessagePos();
2108 pt.x = (short)LOWORD(messagePos);
2109 pt.y = (short)HIWORD(messagePos);
2111 sbi.cbSize = sizeof(sbi);
2112 GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2113 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2114 PtInRect(&sbi.rcScrollBar, pt))
2116 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2117 return TRUE;
2119 sbi.cbSize = sizeof(sbi);
2120 GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2121 if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2122 PtInRect(&sbi.rcScrollBar, pt))
2124 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2125 return TRUE;
2127 ScreenToClient(editor->hWnd, &pt);
2129 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
2130 (pt.x < editor->selofs ||
2131 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
2133 SetCursor(hLeft);
2134 return TRUE;
2136 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2137 if (isExact)
2139 if (editor->AutoURLDetect_bEnable)
2141 ME_Cursor cursor;
2142 ME_Run *run;
2143 ME_CursorFromCharOfs(editor, offset, &cursor);
2144 run = &cursor.pRun->member.run;
2145 if (editor->AutoURLDetect_bEnable &&
2146 run->style->fmt.dwMask & CFM_LINK &&
2147 run->style->fmt.dwEffects & CFE_LINK)
2149 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
2150 return TRUE;
2153 if (ME_IsSelection(editor))
2155 int selStart, selEnd;
2156 ME_GetSelection(editor, &selStart, &selEnd);
2157 if (selStart <= offset && selEnd >= offset) {
2158 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2159 return TRUE;
2163 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
2164 return TRUE;
2167 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2169 CHARRANGE selrange;
2170 HMENU menu;
2171 int seltype = 0;
2172 if(!editor->lpOleCallback)
2173 return FALSE;
2174 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2175 if(selrange.cpMin == selrange.cpMax)
2176 seltype |= SEL_EMPTY;
2177 else
2179 /* FIXME: Handle objects */
2180 seltype |= SEL_TEXT;
2181 if(selrange.cpMax-selrange.cpMin > 1)
2182 seltype |= SEL_MULTICHAR;
2184 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2186 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2187 DestroyMenu(menu);
2189 return TRUE;
2192 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
2193 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2194 int i;
2195 ed->hWnd = hWnd;
2196 ed->bEmulateVersion10 = FALSE;
2197 ed->pBuffer = ME_MakeText();
2198 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2199 ME_MakeFirstParagraph(ed);
2200 /* The four cursors are for:
2201 * 0 - The position where the caret is shown
2202 * 1 - The anchored end of the selection (for normal selection)
2203 * 2 & 3 - The anchored start and end respectively for word, line,
2204 * or paragraph selection.
2206 ed->nCursors = 4;
2207 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2208 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2209 ed->pCursors[0].nOffset = 0;
2210 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2211 ed->pCursors[1].nOffset = 0;
2212 ed->pCursors[2] = ed->pCursors[0];
2213 ed->pCursors[3] = ed->pCursors[1];
2214 ed->nLastTotalLength = ed->nTotalLength = 0;
2215 ed->nHeight = 0;
2216 ed->nUDArrowX = -1;
2217 ed->nSequence = 0;
2218 ed->rgbBackColor = -1;
2219 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2220 ed->bCaretAtEnd = FALSE;
2221 ed->nEventMask = 0;
2222 ed->nModifyStep = 0;
2223 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2224 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2225 ed->nUndoStackSize = 0;
2226 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2227 ed->nUndoMode = umAddToUndo;
2228 ed->nParagraphs = 1;
2229 ed->nLastSelStart = ed->nLastSelEnd = 0;
2230 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2231 ed->bRedraw = TRUE;
2232 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & (WS_HSCROLL|ES_AUTOHSCROLL)) ? FALSE : TRUE;
2233 ed->bHideSelection = FALSE;
2234 ed->nInvalidOfs = -1;
2235 ed->pfnWordBreak = NULL;
2236 ed->lpOleCallback = NULL;
2237 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2238 ed->AutoURLDetect_bEnable = FALSE;
2239 ed->bHaveFocus = FALSE;
2240 for (i=0; i<HFONT_CACHE_SIZE; i++)
2242 ed->pFontCache[i].nRefs = 0;
2243 ed->pFontCache[i].nAge = 0;
2244 ed->pFontCache[i].hFont = NULL;
2247 ME_CheckCharOffsets(ed);
2248 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
2249 ed->selofs = SELECTIONBAR_WIDTH;
2250 else
2251 ed->selofs = 0;
2252 ed->nSelectionType = stPosition;
2254 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
2255 ed->cPasswordMask = '*';
2256 else
2257 ed->cPasswordMask = 0;
2259 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2261 /* Default vertical scrollbar information */
2262 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2263 ed->vert_si.nMin = 0;
2264 ed->vert_si.nMax = 0;
2265 ed->vert_si.nPage = 0;
2266 ed->vert_si.nPos = 0;
2268 OleInitialize(NULL);
2270 return ed;
2273 typedef struct tagME_GlobalDestStruct
2275 HGLOBAL hData;
2276 int nLength;
2277 } ME_GlobalDestStruct;
2279 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2281 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2282 int i;
2283 WORD *pSrc, *pDest;
2285 cb = cb >> 1;
2286 pDest = (WORD *)lpBuff;
2287 pSrc = (WORD *)GlobalLock(pData->hData);
2288 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2289 pDest[i] = pSrc[pData->nLength+i];
2291 pData->nLength += i;
2292 *pcb = 2*i;
2293 GlobalUnlock(pData->hData);
2294 return 0;
2297 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2299 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2300 int i;
2301 BYTE *pSrc, *pDest;
2303 pDest = lpBuff;
2304 pSrc = (BYTE *)GlobalLock(pData->hData);
2305 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2306 pDest[i] = pSrc[pData->nLength+i];
2308 pData->nLength += i;
2309 *pcb = i;
2310 GlobalUnlock(pData->hData);
2311 return 0;
2315 void ME_DestroyEditor(ME_TextEditor *editor)
2317 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2318 ME_DisplayItem *p = pFirst, *pNext = NULL;
2319 int i;
2321 ME_ClearTempStyle(editor);
2322 ME_EmptyUndoStack(editor);
2323 while(p) {
2324 pNext = p->next;
2325 ME_DestroyDisplayItem(p);
2326 p = pNext;
2328 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2329 for (i=0; i<HFONT_CACHE_SIZE; i++)
2331 if (editor->pFontCache[i].hFont)
2332 DeleteObject(editor->pFontCache[i].hFont);
2334 if (editor->rgbBackColor != -1)
2335 DeleteObject(editor->hbrBackground);
2336 if(editor->lpOleCallback)
2337 IUnknown_Release(editor->lpOleCallback);
2338 OleUninitialize();
2340 FREE_OBJ(editor->pBuffer);
2341 FREE_OBJ(editor->pCursors);
2343 FREE_OBJ(editor);
2346 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2348 TRACE("\n");
2349 switch (fdwReason)
2351 case DLL_PROCESS_ATTACH:
2352 DisableThreadLibraryCalls(hinstDLL);
2353 me_heap = HeapCreate (0, 0x10000, 0);
2354 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2355 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2356 LookupInit();
2357 break;
2359 case DLL_PROCESS_DETACH:
2360 UnregisterClassW(RichEdit20W, 0);
2361 UnregisterClassW(RichEdit50W, 0);
2362 UnregisterClassA("RichEdit20A", 0);
2363 UnregisterClassA("RichEdit50A", 0);
2364 if (ME_ListBoxRegistered)
2365 UnregisterClassW(REListBox20W, 0);
2366 if (ME_ComboBoxRegistered)
2367 UnregisterClassW(REComboBox20W, 0);
2368 LookupCleanup();
2369 HeapDestroy (me_heap);
2370 me_heap = NULL;
2371 break;
2373 return TRUE;
2377 #define UNSUPPORTED_MSG(e) \
2378 case e: \
2379 FIXME(#e ": stub\n"); \
2380 return DefWindowProcW(hWnd, msg, wParam, lParam);
2382 static const char * const edit_messages[] = {
2383 "EM_GETSEL",
2384 "EM_SETSEL",
2385 "EM_GETRECT",
2386 "EM_SETRECT",
2387 "EM_SETRECTNP",
2388 "EM_SCROLL",
2389 "EM_LINESCROLL",
2390 "EM_SCROLLCARET",
2391 "EM_GETMODIFY",
2392 "EM_SETMODIFY",
2393 "EM_GETLINECOUNT",
2394 "EM_LINEINDEX",
2395 "EM_SETHANDLE",
2396 "EM_GETHANDLE",
2397 "EM_GETTHUMB",
2398 "EM_UNKNOWN_BF",
2399 "EM_UNKNOWN_C0",
2400 "EM_LINELENGTH",
2401 "EM_REPLACESEL",
2402 "EM_UNKNOWN_C3",
2403 "EM_GETLINE",
2404 "EM_LIMITTEXT",
2405 "EM_CANUNDO",
2406 "EM_UNDO",
2407 "EM_FMTLINES",
2408 "EM_LINEFROMCHAR",
2409 "EM_UNKNOWN_CA",
2410 "EM_SETTABSTOPS",
2411 "EM_SETPASSWORDCHAR",
2412 "EM_EMPTYUNDOBUFFER",
2413 "EM_GETFIRSTVISIBLELINE",
2414 "EM_SETREADONLY",
2415 "EM_SETWORDBREAKPROC",
2416 "EM_GETWORDBREAKPROC",
2417 "EM_GETPASSWORDCHAR",
2418 "EM_SETMARGINS",
2419 "EM_GETMARGINS",
2420 "EM_GETLIMITTEXT",
2421 "EM_POSFROMCHAR",
2422 "EM_CHARFROMPOS"
2425 static const char * const richedit_messages[] = {
2426 "EM_CANPASTE",
2427 "EM_DISPLAYBAND",
2428 "EM_EXGETSEL",
2429 "EM_EXLIMITTEXT",
2430 "EM_EXLINEFROMCHAR",
2431 "EM_EXSETSEL",
2432 "EM_FINDTEXT",
2433 "EM_FORMATRANGE",
2434 "EM_GETCHARFORMAT",
2435 "EM_GETEVENTMASK",
2436 "EM_GETOLEINTERFACE",
2437 "EM_GETPARAFORMAT",
2438 "EM_GETSELTEXT",
2439 "EM_HIDESELECTION",
2440 "EM_PASTESPECIAL",
2441 "EM_REQUESTRESIZE",
2442 "EM_SELECTIONTYPE",
2443 "EM_SETBKGNDCOLOR",
2444 "EM_SETCHARFORMAT",
2445 "EM_SETEVENTMASK",
2446 "EM_SETOLECALLBACK",
2447 "EM_SETPARAFORMAT",
2448 "EM_SETTARGETDEVICE",
2449 "EM_STREAMIN",
2450 "EM_STREAMOUT",
2451 "EM_GETTEXTRANGE",
2452 "EM_FINDWORDBREAK",
2453 "EM_SETOPTIONS",
2454 "EM_GETOPTIONS",
2455 "EM_FINDTEXTEX",
2456 "EM_GETWORDBREAKPROCEX",
2457 "EM_SETWORDBREAKPROCEX",
2458 "EM_SETUNDOLIMIT",
2459 "EM_UNKNOWN_USER_83",
2460 "EM_REDO",
2461 "EM_CANREDO",
2462 "EM_GETUNDONAME",
2463 "EM_GETREDONAME",
2464 "EM_STOPGROUPTYPING",
2465 "EM_SETTEXTMODE",
2466 "EM_GETTEXTMODE",
2467 "EM_AUTOURLDETECT",
2468 "EM_GETAUTOURLDETECT",
2469 "EM_SETPALETTE",
2470 "EM_GETTEXTEX",
2471 "EM_GETTEXTLENGTHEX",
2472 "EM_SHOWSCROLLBAR",
2473 "EM_SETTEXTEX",
2474 "EM_UNKNOWN_USER_98",
2475 "EM_UNKNOWN_USER_99",
2476 "EM_SETPUNCTUATION",
2477 "EM_GETPUNCTUATION",
2478 "EM_SETWORDWRAPMODE",
2479 "EM_GETWORDWRAPMODE",
2480 "EM_SETIMECOLOR",
2481 "EM_GETIMECOLOR",
2482 "EM_SETIMEOPTIONS",
2483 "EM_GETIMEOPTIONS",
2484 "EM_CONVPOSITION",
2485 "EM_UNKNOWN_USER_109",
2486 "EM_UNKNOWN_USER_110",
2487 "EM_UNKNOWN_USER_111",
2488 "EM_UNKNOWN_USER_112",
2489 "EM_UNKNOWN_USER_113",
2490 "EM_UNKNOWN_USER_114",
2491 "EM_UNKNOWN_USER_115",
2492 "EM_UNKNOWN_USER_116",
2493 "EM_UNKNOWN_USER_117",
2494 "EM_UNKNOWN_USER_118",
2495 "EM_UNKNOWN_USER_119",
2496 "EM_SETLANGOPTIONS",
2497 "EM_GETLANGOPTIONS",
2498 "EM_GETIMECOMPMODE",
2499 "EM_FINDTEXTW",
2500 "EM_FINDTEXTEXW",
2501 "EM_RECONVERSION",
2502 "EM_SETIMEMODEBIAS",
2503 "EM_GETIMEMODEBIAS"
2506 static const char *
2507 get_msg_name(UINT msg)
2509 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2510 return edit_messages[msg - EM_GETSEL];
2511 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2512 return richedit_messages[msg - EM_CANPASTE];
2513 return "";
2516 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2517 LPARAM lParam, BOOL unicode)
2519 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2521 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2522 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2524 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2525 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2526 return 0;
2529 switch(msg) {
2531 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2532 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2533 UNSUPPORTED_MSG(EM_FMTLINES)
2534 UNSUPPORTED_MSG(EM_FORMATRANGE)
2535 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2536 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2537 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2538 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2539 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2540 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2541 UNSUPPORTED_MSG(EM_GETREDONAME)
2542 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2543 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2544 UNSUPPORTED_MSG(EM_GETUNDONAME)
2545 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2546 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2547 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2548 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2549 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2550 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2551 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2552 UNSUPPORTED_MSG(EM_SETPALETTE)
2553 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2554 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2555 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2556 UNSUPPORTED_MSG(WM_STYLECHANGING)
2557 UNSUPPORTED_MSG(WM_STYLECHANGED)
2559 /* Messages specific to Richedit controls */
2561 case EM_STREAMIN:
2562 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2563 case EM_STREAMOUT:
2564 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2565 case WM_GETDLGCODE:
2567 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2568 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2570 int vk = (int)((LPMSG)lParam)->wParam;
2571 /* if style says we want return key */
2572 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2574 code |= DLGC_WANTMESSAGE;
2576 /* we always handle ctrl-tab */
2577 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2579 code |= DLGC_WANTMESSAGE;
2582 return code;
2584 case WM_NCCREATE:
2586 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2587 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2588 editor = ME_MakeEditor(hWnd);
2589 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2590 return TRUE;
2592 case EM_EMPTYUNDOBUFFER:
2593 ME_EmptyUndoStack(editor);
2594 return 0;
2595 case EM_GETSEL:
2597 /* Note: wParam/lParam can be NULL */
2598 UINT from, to;
2599 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2600 PUINT pto = lParam ? (PUINT)lParam : &to;
2601 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2602 if ((*pfrom|*pto) & 0xFFFF0000)
2603 return -1;
2604 return MAKELONG(*pfrom,*pto);
2606 case EM_EXGETSEL:
2608 CHARRANGE *pRange = (CHARRANGE *)lParam;
2609 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2610 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2611 return 0;
2613 case EM_SETUNDOLIMIT:
2615 if ((int)wParam < 0)
2616 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2617 else
2618 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2619 /* Setting a max stack size keeps wine from getting killed
2620 for hogging memory. Windows allocates all this memory at once, so
2621 no program would realistically set a value above our maximum. */
2622 return editor->nUndoLimit;
2624 case EM_CANUNDO:
2625 return editor->pUndoStack != NULL;
2626 case EM_CANREDO:
2627 return editor->pRedoStack != NULL;
2628 case WM_UNDO: /* FIXME: actually not the same */
2629 case EM_UNDO:
2630 return ME_Undo(editor);
2631 case EM_REDO:
2632 return ME_Redo(editor);
2633 case EM_GETOPTIONS:
2635 /* these flags are equivalent to the ES_* counterparts */
2636 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2637 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2638 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2640 return settings;
2642 case EM_SETOPTIONS:
2644 /* these flags are equivalent to ES_* counterparts
2645 * ECO_READONLY is already implemented in the code, only requires
2646 * setting the bit to work
2648 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2649 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2650 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2651 DWORD settings = mask & raw;
2653 switch(wParam)
2655 case ECOOP_SET:
2656 settings = lParam;
2657 break;
2658 case ECOOP_OR:
2659 settings |= lParam;
2660 break;
2661 case ECOOP_AND:
2662 settings &= lParam;
2663 break;
2664 case ECOOP_XOR:
2665 settings ^= lParam;
2667 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2669 if (settings & ECO_AUTOWORDSELECTION)
2670 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2671 if (settings & ECO_SELECTIONBAR)
2672 editor->selofs = SELECTIONBAR_WIDTH;
2673 else
2674 editor->selofs = 0;
2675 ME_WrapMarkedParagraphs(editor);
2677 if (settings & ECO_VERTICAL)
2678 FIXME("ECO_VERTICAL not implemented yet!\n");
2679 if (settings & ECO_AUTOHSCROLL)
2680 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2681 if (settings & ECO_AUTOVSCROLL)
2682 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2683 if (settings & ECO_NOHIDESEL)
2684 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2685 if (settings & ECO_WANTRETURN)
2686 FIXME("ECO_WANTRETURN not implemented yet!\n");
2688 return settings;
2690 case EM_SETSEL:
2692 ME_InvalidateSelection(editor);
2693 ME_SetSelection(editor, wParam, lParam);
2694 ME_InvalidateSelection(editor);
2695 HideCaret(editor->hWnd);
2696 ME_ShowCaret(editor);
2697 ME_SendSelChange(editor);
2698 return 0;
2700 case EM_SETSCROLLPOS:
2702 POINT *point = (POINT *)lParam;
2703 ME_ScrollAbs(editor, point->y);
2704 return 0;
2706 case EM_AUTOURLDETECT:
2708 if (wParam==1 || wParam ==0)
2710 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2711 return 0;
2713 return E_INVALIDARG;
2715 case EM_GETAUTOURLDETECT:
2717 return editor->AutoURLDetect_bEnable;
2719 case EM_EXSETSEL:
2721 int end;
2722 CHARRANGE range = *(CHARRANGE *)lParam;
2724 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2726 ME_InvalidateSelection(editor);
2727 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2728 ME_InvalidateSelection(editor);
2729 HideCaret(editor->hWnd);
2730 ME_ShowCaret(editor);
2731 ME_SendSelChange(editor);
2733 return end;
2735 case EM_SHOWSCROLLBAR:
2737 ShowScrollBar(editor->hWnd, wParam, lParam);
2738 return 0;
2740 case EM_SETTEXTEX:
2742 LPWSTR wszText;
2743 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2744 size_t len;
2745 int from, to;
2746 ME_Style *style;
2747 int oldModify = editor->nModifyStep;
2749 if (!pStruct) return 0;
2751 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2752 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2753 pStruct->flags, pStruct->codepage);
2755 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2756 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2757 len = wszText ? lstrlenW(wszText) : 0;
2759 if (pStruct->flags & ST_SELECTION) {
2760 ME_GetSelection(editor, &from, &to);
2761 style = ME_GetSelectionInsertStyle(editor);
2762 ME_InternalDeleteText(editor, from, to - from, FALSE);
2763 if (pStruct->codepage != 1200 && lParam &&
2764 (!strncmp((char *)lParam, "{\\rtf", 5) || !strncmp((char *)lParam, "{\\urtf}", 6)))
2765 ME_StreamInRTFString(editor, 1, (char *)lParam);
2766 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2767 ME_ReleaseStyle(style);
2769 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2771 else {
2772 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2773 if (pStruct->codepage != 1200 && lParam &&
2774 (!strncmp((char *)lParam, "{\\rtf", 5) || !strncmp((char *)lParam, "{\\urtf}", 6)))
2775 ME_StreamInRTFString(editor, 0, (char *)lParam);
2776 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2777 len = 1;
2779 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2781 ME_CommitUndo(editor);
2782 if (!(pStruct->flags & ST_KEEPUNDO))
2784 editor->nModifyStep = oldModify;
2785 ME_EmptyUndoStack(editor);
2787 ME_UpdateRepaint(editor);
2788 return len;
2790 case EM_SETBKGNDCOLOR:
2792 LRESULT lColor;
2793 if (editor->rgbBackColor != -1) {
2794 DeleteObject(editor->hbrBackground);
2795 lColor = editor->rgbBackColor;
2797 else lColor = GetSysColor(COLOR_WINDOW);
2799 if (wParam)
2801 editor->rgbBackColor = -1;
2802 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2804 else
2806 editor->rgbBackColor = lParam;
2807 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2809 if (editor->bRedraw)
2811 InvalidateRect(hWnd, NULL, TRUE);
2812 UpdateWindow(hWnd);
2814 return lColor;
2816 case EM_GETMODIFY:
2817 return editor->nModifyStep == 0 ? 0 : -1;
2818 case EM_SETMODIFY:
2820 if (wParam)
2821 editor->nModifyStep = 1;
2822 else
2823 editor->nModifyStep = 0;
2825 return 0;
2827 case EM_SETREADONLY:
2829 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2830 if (wParam)
2831 nStyle |= ES_READONLY;
2832 else
2833 nStyle &= ~ES_READONLY;
2834 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2835 return 0;
2837 case EM_SETEVENTMASK:
2839 DWORD nOldMask = editor->nEventMask;
2841 editor->nEventMask = lParam;
2842 return nOldMask;
2844 case EM_GETEVENTMASK:
2845 return editor->nEventMask;
2846 case EM_SETCHARFORMAT:
2848 CHARFORMAT2W buf, *p;
2849 BOOL bRepaint = TRUE;
2850 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2851 if (p == NULL) return 0;
2852 if (!wParam)
2853 ME_SetDefaultCharFormat(editor, p);
2854 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2855 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2856 return 0;
2857 } else if (wParam == SCF_ALL) {
2858 if (editor->mode & TM_PLAINTEXT)
2859 ME_SetDefaultCharFormat(editor, p);
2860 else {
2861 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2862 editor->nModifyStep = 1;
2864 } else if (editor->mode & TM_PLAINTEXT) {
2865 return 0;
2866 } else {
2867 int from, to;
2868 ME_GetSelection(editor, &from, &to);
2869 bRepaint = (from != to);
2870 ME_SetSelectionCharFormat(editor, p);
2871 if (from != to) editor->nModifyStep = 1;
2873 ME_CommitUndo(editor);
2874 if (bRepaint)
2875 ME_RewrapRepaint(editor);
2876 return 1;
2878 case EM_GETCHARFORMAT:
2880 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2881 if (dst->cbSize != sizeof(CHARFORMATA) &&
2882 dst->cbSize != sizeof(CHARFORMATW) &&
2883 dst->cbSize != sizeof(CHARFORMAT2A) &&
2884 dst->cbSize != sizeof(CHARFORMAT2W))
2885 return 0;
2886 tmp.cbSize = sizeof(tmp);
2887 if (!wParam)
2888 ME_GetDefaultCharFormat(editor, &tmp);
2889 else
2890 ME_GetSelectionCharFormat(editor, &tmp);
2891 ME_CopyToCFAny(dst, &tmp);
2892 return tmp.dwMask;
2894 case EM_SETPARAFORMAT:
2896 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2897 ME_RewrapRepaint(editor);
2898 ME_CommitUndo(editor);
2899 return result;
2901 case EM_GETPARAFORMAT:
2902 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2903 return ((PARAFORMAT2 *)lParam)->dwMask;
2904 case EM_GETFIRSTVISIBLELINE:
2906 ME_DisplayItem *p = editor->pBuffer->pFirst;
2907 int y = ME_GetYScrollPos(editor);
2908 int ypara = 0;
2909 int count = 0;
2910 int ystart, yend;
2911 while(p) {
2912 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2913 if (p->type == diTextEnd)
2914 break;
2915 if (p->type == diParagraph) {
2916 ypara = p->member.para.pt.y;
2917 continue;
2919 ystart = ypara + p->member.row.pt.y;
2920 yend = ystart + p->member.row.nHeight;
2921 if (y < yend) {
2922 break;
2924 count++;
2926 return count;
2928 case EM_HIDESELECTION:
2930 editor->bHideSelection = (wParam != 0);
2931 ME_InvalidateSelection(editor);
2932 return 0;
2934 case EM_LINESCROLL:
2936 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2937 return TRUE; /* Should return false if a single line richedit control */
2939 case WM_CLEAR:
2941 int from, to;
2942 ME_GetSelection(editor, &from, &to);
2943 ME_InternalDeleteText(editor, from, to-from, FALSE);
2944 ME_CommitUndo(editor);
2945 ME_UpdateRepaint(editor);
2946 return 0;
2948 case EM_REPLACESEL:
2950 int from, to;
2951 ME_Style *style;
2952 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2953 size_t len = wszText ? lstrlenW(wszText) : 0;
2954 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2956 ME_GetSelection(editor, &from, &to);
2957 style = ME_GetSelectionInsertStyle(editor);
2958 ME_InternalDeleteText(editor, from, to-from, FALSE);
2959 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2960 ME_ReleaseStyle(style);
2961 /* drop temporary style if line end */
2963 * FIXME question: does abc\n mean: put abc,
2964 * clear temp style, put \n? (would require a change)
2966 if (len>0 && wszText[len-1] == '\n')
2967 ME_ClearTempStyle(editor);
2968 ME_EndToUnicode(unicode, wszText);
2969 ME_CommitUndo(editor);
2970 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2971 if (!wParam)
2972 ME_EmptyUndoStack(editor);
2973 ME_UpdateRepaint(editor);
2974 return len;
2976 case EM_SCROLLCARET:
2978 int top, bottom; /* row's edges relative to document top */
2979 int nPos;
2980 ME_DisplayItem *para, *row;
2982 nPos = ME_GetYScrollPos(editor);
2983 row = ME_RowStart(editor->pCursors[0].pRun);
2984 para = ME_GetParagraph(row);
2985 top = para->member.para.pt.y + row->member.row.pt.y;
2986 bottom = top + row->member.row.nHeight;
2988 if (top < nPos) /* caret above window */
2989 ME_ScrollAbs(editor, top);
2990 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2991 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2992 return 0;
2994 case WM_SETFONT:
2996 LOGFONTW lf;
2997 CHARFORMAT2W fmt;
2998 HDC hDC;
2999 BOOL bRepaint = LOWORD(lParam);
3001 if (!wParam)
3002 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
3003 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3004 hDC = GetDC(hWnd);
3005 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
3006 ReleaseDC(hWnd, hDC);
3007 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
3008 ME_SetDefaultCharFormat(editor, &fmt);
3010 ME_CommitUndo(editor);
3011 if (bRepaint)
3012 ME_RewrapRepaint(editor);
3013 return 0;
3015 case WM_SETTEXT:
3017 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
3018 if (lParam)
3020 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3021 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
3023 /* Undocumented: WM_SETTEXT supports RTF text */
3024 ME_StreamInRTFString(editor, 0, (char *)lParam);
3026 else
3028 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3029 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3030 if (lstrlenW(wszText) > 0)
3032 int len = -1;
3034 /* uses default style! */
3035 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3037 WCHAR * p;
3039 p = wszText;
3040 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3041 len = p - wszText;
3043 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3045 ME_EndToUnicode(unicode, wszText);
3048 else
3049 TRACE("WM_SETTEXT - NULL\n");
3050 if (editor->AutoURLDetect_bEnable)
3052 ME_UpdateLinkAttribute(editor, 0, -1);
3054 ME_SetSelection(editor, 0, 0);
3055 editor->nModifyStep = 0;
3056 ME_CommitUndo(editor);
3057 ME_EmptyUndoStack(editor);
3058 ME_UpdateRepaint(editor);
3059 return 1;
3061 case EM_CANPASTE:
3063 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3064 if (IsClipboardFormatAvailable(nRTFFormat))
3065 return TRUE;
3066 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3067 return TRUE;
3068 return FALSE;
3070 case WM_PASTE:
3072 DWORD dwFormat = 0;
3073 EDITSTREAM es;
3074 ME_GlobalDestStruct gds;
3075 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3076 UINT cf = 0;
3078 if (IsClipboardFormatAvailable(nRTFFormat))
3079 cf = nRTFFormat, dwFormat = SF_RTF;
3080 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3081 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
3082 else
3083 return 0;
3085 if (!OpenClipboard(hWnd))
3086 return 0;
3087 gds.hData = GetClipboardData(cf);
3088 gds.nLength = 0;
3089 es.dwCookie = (DWORD)&gds;
3090 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
3091 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
3093 CloseClipboard();
3094 return 0;
3096 case WM_CUT:
3097 case WM_COPY:
3099 LPDATAOBJECT dataObj = NULL;
3100 CHARRANGE range;
3101 HRESULT hr = S_OK;
3103 if (editor->cPasswordMask)
3104 return 0; /* Copying or Cutting masked text isn't allowed */
3106 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
3107 if(editor->lpOleCallback)
3108 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
3109 if(FAILED(hr) || !dataObj)
3110 hr = ME_GetDataObject(editor, &range, &dataObj);
3111 if(SUCCEEDED(hr)) {
3112 hr = OleSetClipboard(dataObj);
3113 IDataObject_Release(dataObj);
3115 if (SUCCEEDED(hr) && msg == WM_CUT)
3117 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3118 ME_CommitUndo(editor);
3119 ME_UpdateRepaint(editor);
3121 return 0;
3123 case WM_GETTEXTLENGTH:
3125 GETTEXTLENGTHEX how;
3127 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3128 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3129 how.codepage = unicode ? 1200 : CP_ACP;
3130 return ME_GetTextLengthEx(editor, &how);
3132 case EM_GETTEXTLENGTHEX:
3133 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3134 case WM_GETTEXT:
3136 GETTEXTEX ex;
3137 LRESULT rc;
3138 LPSTR bufferA = NULL;
3139 LPWSTR bufferW = NULL;
3141 if (unicode)
3142 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
3143 else
3144 bufferA = heap_alloc(wParam + 2);
3146 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3147 ex.flags = GT_USECRLF;
3148 ex.codepage = unicode ? 1200 : CP_ACP;
3149 ex.lpDefaultChar = NULL;
3150 ex.lpUsedDefChar = NULL;
3151 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
3153 if (unicode)
3155 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3156 if (lstrlenW(bufferW) >= wParam) rc = 0;
3158 else
3160 memcpy((LPSTR)lParam, bufferA, wParam);
3161 if (strlen(bufferA) >= wParam) rc = 0;
3163 heap_free(bufferA);
3164 heap_free(bufferW);
3165 return rc;
3167 case EM_GETTEXTEX:
3169 GETTEXTEX *ex = (GETTEXTEX*)wParam;
3170 int nStart, nCount; /* in chars */
3172 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
3173 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
3175 if (ex->flags & GT_SELECTION)
3177 ME_GetSelection(editor, &nStart, &nCount);
3178 nCount -= nStart;
3180 else
3182 nStart = 0;
3183 nCount = 0x7fffffff;
3185 if (ex->codepage == 1200)
3187 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
3188 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
3190 else
3192 /* potentially each char may be a CR, why calculate the exact value with O(N) when
3193 we can just take a bigger buffer? :)
3194 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
3195 occurs only in richedit 2.0 mode, in which line breaks have only one CR
3197 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
3198 LPWSTR buffer;
3199 DWORD buflen = ex->cb;
3200 LRESULT rc;
3201 DWORD flags = 0;
3203 nCount = min(nCount, ex->cb - 1);
3204 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
3206 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
3207 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
3208 if (rc) rc--; /* do not count 0 terminator */
3210 heap_free(buffer);
3211 return rc;
3214 case EM_GETSELTEXT:
3216 int from, to;
3217 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3218 ME_GetSelection(editor, &from, &to);
3219 tr.chrg.cpMin = from;
3220 tr.chrg.cpMax = to;
3221 tr.lpstrText = (WCHAR *)lParam;
3222 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
3224 case EM_GETSCROLLPOS:
3226 POINT *point = (POINT *)lParam;
3227 point->x = 0; /* FIXME side scrolling not implemented */
3228 point->y = ME_GetYScrollPos(editor);
3229 return 1;
3231 case EM_GETTEXTRANGE:
3233 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3234 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3235 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3236 editor->bEmulateVersion10, ME_GetTextLength(editor));
3237 if (unicode)
3238 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
3239 else
3241 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
3242 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
3243 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
3244 /* FIXME this is a potential security hole (buffer overrun)
3245 if you know more about wchar->mbyte conversion please explain
3247 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
3248 FREE_OBJ(p);
3249 return nChars;
3252 case EM_GETLINE:
3254 ME_DisplayItem *run;
3255 const unsigned int nMaxChars = *(WORD *) lParam;
3256 unsigned int nCharsLeft = nMaxChars;
3257 char *dest = (char *) lParam;
3258 BOOL wroteNull = FALSE;
3260 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3261 unicode ? "Unicode" : "Ansi");
3263 run = ME_FindRowWithNumber(editor, wParam);
3264 if (run == NULL)
3265 return 0;
3267 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3268 && !(run->member.run.nFlags & MERF_ENDPARA))
3270 unsigned int nCopy;
3271 ME_String *strText;
3272 if (run->type != diRun)
3273 break;
3274 strText = run->member.run.strText;
3275 nCopy = min(nCharsLeft, strText->nLen);
3277 if (unicode)
3278 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
3279 else
3280 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3281 nCharsLeft, NULL, NULL);
3282 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3283 nCharsLeft -= nCopy;
3286 /* append line termination, space allowing */
3287 if (nCharsLeft > 0)
3289 if (run && (run->member.run.nFlags & MERF_ENDPARA))
3291 unsigned int i;
3292 /* Write as many \r as encoded in end-of-paragraph, space allowing */
3293 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3295 *((WCHAR *)dest) = '\r';
3296 dest += unicode ? sizeof(WCHAR) : 1;
3298 /* Write as many \n as encoded in end-of-paragraph, space allowing */
3299 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3301 *((WCHAR *)dest) = '\n';
3302 dest += unicode ? sizeof(WCHAR) : 1;
3305 if (nCharsLeft > 0)
3307 if (unicode)
3308 *((WCHAR *)dest) = '\0';
3309 else
3310 *dest = '\0';
3311 nCharsLeft--;
3312 wroteNull = TRUE;
3316 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3317 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3319 case EM_GETLINECOUNT:
3321 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3322 int nRows = 0;
3324 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3326 while (item != editor->pBuffer->pLast)
3328 assert(item->type == diParagraph);
3329 prev_para = ME_FindItemBack(item, diRun);
3330 if (prev_para) {
3331 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3333 nRows += item->member.para.nRows;
3334 item = item->member.para.next_para;
3336 last_para = ME_FindItemBack(item, diRun);
3337 assert(last_para);
3338 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3339 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3340 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3342 /* In 1.0 emulation, the last solitary \r at the very end of the text
3343 (if one exists) is NOT a line break.
3344 FIXME: this is an ugly hack. This should have a more regular model. */
3345 nRows--;
3348 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3349 return max(1, nRows);
3351 case EM_LINEFROMCHAR:
3353 if (wParam == -1)
3354 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3355 else
3356 return ME_RowNumberFromCharOfs(editor, wParam);
3358 case EM_EXLINEFROMCHAR:
3360 if (lParam == -1)
3361 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3362 else
3363 return ME_RowNumberFromCharOfs(editor, lParam);
3365 case EM_LINEINDEX:
3367 ME_DisplayItem *item, *para;
3368 int nCharOfs;
3370 if (wParam == -1)
3371 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3372 else
3373 item = ME_FindRowWithNumber(editor, wParam);
3374 if (!item)
3375 return -1;
3376 para = ME_GetParagraph(item);
3377 item = ME_FindItemFwd(item, diRun);
3378 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3379 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3380 return nCharOfs;
3382 case EM_LINELENGTH:
3384 ME_DisplayItem *item, *item_end;
3385 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3387 if (wParam > ME_GetTextLength(editor))
3388 return 0;
3389 if (wParam == -1)
3391 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3392 return 0;
3394 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3395 item = ME_RowStart(item);
3396 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3397 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3398 if (item_end->type == diStartRow)
3399 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3400 else
3402 ME_DisplayItem *endPara;
3404 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3405 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3406 endPara = ME_FindItemBack(endPara, diRun);
3407 assert(endPara);
3408 assert(endPara->type == diRun);
3409 assert(endPara->member.run.nFlags & MERF_ENDPARA);
3410 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3412 nChars = nNextLineOfs - nThisLineOfs;
3413 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3414 return nChars;
3416 case EM_EXLIMITTEXT:
3418 if ((int)lParam < 0)
3419 return 0;
3420 if (lParam == 0)
3421 editor->nTextLimit = 65536;
3422 else
3423 editor->nTextLimit = (int) lParam;
3424 return 0;
3426 case EM_LIMITTEXT:
3428 if (wParam == 0)
3429 editor->nTextLimit = 65536;
3430 else
3431 editor->nTextLimit = (int) wParam;
3432 return 0;
3434 case EM_GETLIMITTEXT:
3436 return editor->nTextLimit;
3438 case EM_FINDTEXT:
3440 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3441 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3442 WCHAR *tmp;
3443 LRESULT r;
3445 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3446 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3447 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3448 FREE_OBJ( tmp );
3449 return r;
3451 case EM_FINDTEXTEX:
3453 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3454 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3455 WCHAR *tmp;
3456 LRESULT r;
3458 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3459 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3460 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3461 FREE_OBJ( tmp );
3462 return r;
3464 case EM_FINDTEXTW:
3466 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3467 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3469 case EM_FINDTEXTEXW:
3471 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3472 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3474 case EM_GETZOOM:
3475 if (!wParam || !lParam)
3476 return FALSE;
3477 *(int *)wParam = editor->nZoomNumerator;
3478 *(int *)lParam = editor->nZoomDenominator;
3479 return TRUE;
3480 case EM_SETZOOM:
3481 return ME_SetZoom(editor, wParam, lParam);
3482 case EM_CHARFROMPOS:
3483 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3484 case EM_POSFROMCHAR:
3486 ME_DisplayItem *pRun;
3487 int nCharOfs, nOffset, nLength;
3488 POINTL pt = {0,0};
3489 SCROLLINFO si;
3491 nCharOfs = wParam;
3492 /* detect which API version we're dealing with */
3493 if (wParam >= 0x40000)
3494 nCharOfs = lParam;
3495 nLength = ME_GetTextLength(editor);
3497 if (nCharOfs < nLength) {
3498 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3499 assert(pRun->type == diRun);
3500 pt.y = pRun->member.run.pt.y;
3501 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3502 pt.y += ME_GetParagraph(pRun)->member.para.pt.y;
3503 } else {
3504 pt.x = 0;
3505 pt.y = editor->pBuffer->pLast->member.para.pt.y;
3507 pt.x += editor->selofs;
3509 si.cbSize = sizeof(si);
3510 si.fMask = SIF_POS;
3511 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3512 si.cbSize = sizeof(si);
3513 si.fMask = SIF_POS;
3514 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3516 if (wParam >= 0x40000) {
3517 *(POINTL *)wParam = pt;
3519 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3521 case WM_CREATE:
3523 SCROLLINFO si;
3525 GetClientRect(hWnd, &editor->rcFormat);
3526 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3527 { /* Squelch the default horizontal scrollbar it would make */
3528 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3531 si.cbSize = sizeof(si);
3532 si.fMask = SIF_PAGE | SIF_RANGE;
3533 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3534 si.fMask |= SIF_DISABLENOSCROLL;
3535 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3536 si.nMin = 0;
3537 si.nPage = 0;
3538 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3540 ME_CommitUndo(editor);
3541 ME_WrapMarkedParagraphs(editor);
3542 ME_MoveCaret(editor);
3543 return 0;
3545 case WM_DESTROY:
3546 ME_DestroyEditor(editor);
3547 SetWindowLongPtrW(hWnd, 0, 0);
3548 return 0;
3549 case WM_SETCURSOR:
3551 return ME_SetCursor(editor);
3553 case WM_LBUTTONDBLCLK:
3554 case WM_LBUTTONDOWN:
3556 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3557 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3558 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3559 return 0;
3560 SetFocus(hWnd);
3561 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3562 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3563 SetCapture(hWnd);
3564 ME_LinkNotify(editor,msg,wParam,lParam);
3565 if (!ME_SetCursor(editor)) goto do_default;
3566 break;
3568 case WM_MOUSEMOVE:
3569 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3570 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3571 return 0;
3572 if (GetCapture() == hWnd)
3573 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3574 ME_LinkNotify(editor,msg,wParam,lParam);
3575 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3576 if (GetCapture() == hWnd)
3577 ME_SetCursor(editor);
3578 break;
3579 case WM_LBUTTONUP:
3580 if (GetCapture() == hWnd)
3581 ReleaseCapture();
3582 if (editor->nSelectionType == stDocument)
3583 editor->nSelectionType = stPosition;
3584 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3585 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3586 return 0;
3587 else
3589 ME_SetCursor(editor);
3590 ME_LinkNotify(editor,msg,wParam,lParam);
3592 break;
3593 case WM_RBUTTONUP:
3594 case WM_RBUTTONDOWN:
3595 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3596 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3597 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3598 return 0;
3599 goto do_default;
3600 case WM_CONTEXTMENU:
3601 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3602 goto do_default;
3603 break;
3604 case WM_PAINT:
3605 if (editor->bRedraw)
3607 HDC hDC;
3608 PAINTSTRUCT ps;
3610 hDC = BeginPaint(hWnd, &ps);
3611 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3612 EndPaint(hWnd, &ps);
3614 break;
3615 case WM_SETFOCUS:
3616 editor->bHaveFocus = TRUE;
3617 ME_ShowCaret(editor);
3618 ME_SendOldNotify(editor, EN_SETFOCUS);
3619 return 0;
3620 case WM_KILLFOCUS:
3621 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3622 editor->bHaveFocus = FALSE;
3623 ME_HideCaret(editor);
3624 ME_SendOldNotify(editor, EN_KILLFOCUS);
3625 return 0;
3626 case WM_ERASEBKGND:
3628 if (editor->bRedraw)
3630 HDC hDC = (HDC)wParam;
3631 RECT rc;
3632 if (GetUpdateRect(hWnd,&rc,TRUE))
3634 FillRect(hDC, &rc, editor->hbrBackground);
3637 return 1;
3639 case WM_COMMAND:
3640 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3641 return 0;
3642 case WM_KEYUP:
3643 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3644 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3645 return 0;
3646 goto do_default;
3647 case WM_KEYDOWN:
3648 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3649 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3650 return 0;
3651 if (ME_KeyDown(editor, LOWORD(wParam)))
3652 return 0;
3653 goto do_default;
3654 case WM_CHAR:
3656 WCHAR wstr;
3658 if (unicode)
3659 wstr = (WCHAR)wParam;
3660 else
3662 CHAR charA = wParam;
3663 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3666 switch (wstr)
3668 case 1: /* Ctrl-A */
3669 ME_SetSelection(editor, 0, -1);
3670 return 0;
3671 case 3: /* Ctrl-C */
3672 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3673 return 0;
3676 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3677 MessageBeep(MB_ICONERROR);
3678 return 0; /* FIXME really 0 ? */
3681 switch (wstr)
3683 case 22: /* Ctrl-V */
3684 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3685 return 0;
3686 case 24: /* Ctrl-X */
3687 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3688 return 0;
3689 case 25: /* Ctrl-Y */
3690 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3691 return 0;
3692 case 26: /* Ctrl-Z */
3693 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3694 return 0;
3696 if (((unsigned)wstr)>=' '
3697 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3698 || wstr=='\t') {
3699 ME_Cursor cursor = editor->pCursors[0];
3700 ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
3701 int from, to;
3702 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
3703 ME_GetSelection(editor, &from, &to);
3704 if (wstr=='\t'
3705 /* v4.1 allows tabs to be inserted with ctrl key down */
3706 && !(ctrl_is_down && !editor->bEmulateVersion10)
3709 ME_DisplayItem *para;
3710 BOOL bSelectedRow = FALSE;
3712 para = ME_GetParagraph(cursor.pRun);
3713 if (ME_IsSelection(editor) &&
3714 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3715 to == ME_GetCursorOfs(editor, 0) &&
3716 para->member.para.prev_para->type == diParagraph)
3718 para = para->member.para.prev_para;
3719 bSelectedRow = TRUE;
3721 if (ME_IsInTable(para))
3723 ME_TabPressedInTable(editor, bSelectedRow);
3724 ME_CommitUndo(editor);
3725 return 0;
3727 } else if (!editor->bEmulateVersion10) { /* v4.1 */
3728 if (para->member.para.nFlags & MEPF_ROWEND) {
3729 if (wstr=='\r') {
3730 /* Add a new table row after this row. */
3731 para = ME_AppendTableRow(editor, para);
3732 para = para->member.para.next_para;
3733 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3734 editor->pCursors[0].nOffset = 0;
3735 editor->pCursors[1] = editor->pCursors[0];
3736 ME_CommitUndo(editor);
3737 ME_CheckTablesForCorruption(editor);
3738 ME_UpdateRepaint(editor);
3739 return 0;
3740 } else if (from == to) {
3741 para = para->member.para.next_para;
3742 if (para->member.para.nFlags & MEPF_ROWSTART)
3743 para = para->member.para.next_para;
3744 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3745 editor->pCursors[0].nOffset = 0;
3746 editor->pCursors[1] = editor->pCursors[0];
3749 else if (para == ME_GetParagraph(editor->pCursors[1].pRun) &&
3750 cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
3751 para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
3752 !para->member.para.prev_para->member.para.nCharOfs)
3754 /* Insert a newline before the table. */
3755 WCHAR endl = '\r';
3756 para = para->member.para.prev_para;
3757 para->member.para.nFlags &= ~MEPF_ROWSTART;
3758 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3759 editor->pCursors[1] = editor->pCursors[0];
3760 ME_InsertTextFromCursor(editor, 0, &endl, 1,
3761 editor->pCursors[0].pRun->member.run.style);
3762 para = editor->pBuffer->pFirst->member.para.next_para;
3763 ME_SetDefaultParaFormat(para->member.para.pFmt);
3764 para->member.para.nFlags = MEPF_REWRAP;
3765 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3766 editor->pCursors[1] = editor->pCursors[0];
3767 para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
3768 ME_CommitCoalescingUndo(editor);
3769 ME_CheckTablesForCorruption(editor);
3770 ME_UpdateRepaint(editor);
3771 return 0;
3773 } else { /* v1.0 - 3.0 */
3774 ME_DisplayItem *para = ME_GetParagraph(cursor.pRun);
3775 if (ME_IsInTable(cursor.pRun))
3777 if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
3779 if (from == to) {
3780 if (wstr=='\r') {
3781 ME_ContinueCoalescingTransaction(editor);
3782 para = ME_AppendTableRow(editor, para);
3783 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3784 editor->pCursors[0].nOffset = 0;
3785 editor->pCursors[1] = editor->pCursors[0];
3786 ME_CommitCoalescingUndo(editor);
3787 ME_UpdateRepaint(editor);
3788 } else {
3789 /* Text should not be inserted at the end of the table. */
3790 MessageBeep(-1);
3792 return 0;
3794 } else if (wstr == '\r') {
3795 ME_ContinueCoalescingTransaction(editor);
3796 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3797 !ME_IsInTable(para->member.para.prev_para))
3799 /* Insert newline before table */
3800 WCHAR endl = '\r';
3801 cursor.pRun = ME_FindItemBack(para, diRun);
3802 if (cursor.pRun)
3803 editor->pCursors[0].pRun = cursor.pRun;
3804 editor->pCursors[0].nOffset = 0;
3805 editor->pCursors[1] = editor->pCursors[0];
3806 ME_InsertTextFromCursor(editor, 0, &endl, 1,
3807 editor->pCursors[0].pRun->member.run.style);
3808 } else {
3809 editor->pCursors[1] = editor->pCursors[0];
3810 para = ME_AppendTableRow(editor, para);
3811 editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
3812 editor->pCursors[0].nOffset = 0;
3813 editor->pCursors[1] = editor->pCursors[0];
3815 ME_CommitCoalescingUndo(editor);
3816 ME_UpdateRepaint(editor);
3817 return 0;
3821 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3822 /* WM_CHAR is restricted to nTextLimit */
3823 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3825 ME_Style *style = ME_GetInsertStyle(editor, 0);
3826 ME_SaveTempStyle(editor);
3827 ME_ContinueCoalescingTransaction(editor);
3828 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3829 ME_InsertEndRowFromCursor(editor, 0);
3830 else
3831 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3832 ME_ReleaseStyle(style);
3833 ME_CommitCoalescingUndo(editor);
3834 SetCursor(NULL);
3837 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3839 ME_UpdateRepaint(editor);
3841 return 0;
3843 case WM_UNICHAR:
3844 if (unicode)
3846 if(wParam == UNICODE_NOCHAR) return TRUE;
3847 if(wParam <= 0x000fffff)
3849 if(wParam > 0xffff) /* convert to surrogates */
3851 wParam -= 0x10000;
3852 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3853 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3855 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3857 return 0;
3859 break;
3860 case EM_STOPGROUPTYPING:
3861 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3862 return 0;
3863 case EM_SCROLL: /* fall through */
3864 case WM_VSCROLL:
3866 int origNPos;
3867 int lineHeight;
3869 origNPos = ME_GetYScrollPos(editor);
3870 lineHeight = 24;
3872 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3873 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3874 if (lineHeight <= 0) lineHeight = 24;
3876 switch(LOWORD(wParam))
3878 case SB_LINEUP:
3879 ME_ScrollUp(editor,lineHeight);
3880 break;
3881 case SB_LINEDOWN:
3882 ME_ScrollDown(editor,lineHeight);
3883 break;
3884 case SB_PAGEUP:
3885 ME_ScrollUp(editor,editor->sizeWindow.cy);
3886 break;
3887 case SB_PAGEDOWN:
3888 ME_ScrollDown(editor,editor->sizeWindow.cy);
3889 break;
3890 case SB_THUMBTRACK:
3891 case SB_THUMBPOSITION:
3892 ME_ScrollAbs(editor,HIWORD(wParam));
3893 break;
3895 if (msg == EM_SCROLL)
3896 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3897 break;
3899 case WM_MOUSEWHEEL:
3901 int gcWheelDelta;
3902 UINT pulScrollLines;
3904 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3905 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3906 return 0;
3908 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3909 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3911 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3913 /* FIXME follow the original */
3914 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3916 break;
3918 case EM_GETRECT:
3920 *((RECT *)lParam) = editor->rcFormat;
3921 return 0;
3923 case EM_SETRECT:
3924 case EM_SETRECTNP:
3926 if (lParam)
3928 RECT *rc = (RECT *)lParam;
3930 if (wParam)
3932 editor->rcFormat.left += rc->left;
3933 editor->rcFormat.top += rc->top;
3934 editor->rcFormat.right += rc->right;
3935 editor->rcFormat.bottom += rc->bottom;
3937 else
3939 editor->rcFormat = *rc;
3942 else
3944 GetClientRect(hWnd, &editor->rcFormat);
3946 if (msg != EM_SETRECTNP)
3947 ME_RewrapRepaint(editor);
3948 return 0;
3950 case EM_REQUESTRESIZE:
3951 ME_SendRequestResize(editor, TRUE);
3952 return 0;
3953 case WM_SETREDRAW:
3954 if ((editor->bRedraw = wParam))
3955 ME_RewrapRepaint(editor);
3956 return 0;
3957 case WM_SIZE:
3959 GetClientRect(hWnd, &editor->rcFormat);
3960 ME_RewrapRepaint(editor);
3961 return DefWindowProcW(hWnd, msg, wParam, lParam);
3963 /* IME messages to make richedit controls IME aware */
3964 case WM_IME_SETCONTEXT:
3965 case WM_IME_CONTROL:
3966 case WM_IME_SELECT:
3967 case WM_IME_COMPOSITIONFULL:
3968 return 0;
3969 case WM_IME_STARTCOMPOSITION:
3971 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3972 ME_DeleteSelection(editor);
3973 ME_CommitUndo(editor);
3974 ME_UpdateRepaint(editor);
3975 return 0;
3977 case WM_IME_COMPOSITION:
3979 HIMC hIMC;
3981 ME_Style *style = ME_GetInsertStyle(editor, 0);
3982 hIMC = ImmGetContext(hWnd);
3983 ME_DeleteSelection(editor);
3984 ME_CommitUndo(editor);
3985 ME_SaveTempStyle(editor);
3986 if (lParam & GCS_RESULTSTR)
3988 LPWSTR lpCompStr = NULL;
3989 DWORD dwBufLen;
3991 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3992 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3993 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3994 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3995 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3997 else if (lParam & GCS_COMPSTR)
3999 LPWSTR lpCompStr = NULL;
4000 DWORD dwBufLen;
4002 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4003 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4004 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
4005 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4007 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4008 ME_SetSelection(editor,editor->imeStartIndex,
4009 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4011 ME_ReleaseStyle(style);
4012 ME_UpdateRepaint(editor);
4013 return 0;
4015 case WM_IME_ENDCOMPOSITION:
4017 ME_DeleteSelection(editor);
4018 editor->imeStartIndex=-1;
4019 return 0;
4021 case EM_GETOLEINTERFACE:
4023 LPVOID *ppvObj = (LPVOID*) lParam;
4024 return CreateIRichEditOle(editor, ppvObj);
4026 case EM_GETPASSWORDCHAR:
4028 return editor->cPasswordMask;
4030 case EM_SETOLECALLBACK:
4031 if(editor->lpOleCallback)
4032 IUnknown_Release(editor->lpOleCallback);
4033 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4034 if(editor->lpOleCallback)
4035 IUnknown_AddRef(editor->lpOleCallback);
4036 return TRUE;
4037 case EM_GETWORDBREAKPROC:
4038 return (LRESULT)editor->pfnWordBreak;
4039 case EM_SETWORDBREAKPROC:
4041 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4043 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4044 return (LRESULT)pfnOld;
4046 case EM_SETTEXTMODE:
4048 LRESULT ret;
4049 int mask = 0;
4050 int changes = 0;
4051 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
4052 if (!ret)
4054 /*Check for valid wParam*/
4055 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4056 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4057 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4058 return 1;
4059 else
4061 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4063 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4064 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4066 /*FIXME: Currently no support for undo level and code page options*/
4067 editor->mode = (editor->mode & (~mask)) | changes;
4068 return 0;
4071 return ret;
4073 case EM_SETPASSWORDCHAR:
4075 editor->cPasswordMask = wParam;
4076 ME_RewrapRepaint(editor);
4077 return 0;
4079 case EM_SETTARGETDEVICE:
4080 if (wParam == 0)
4082 BOOL new = (lParam == 0);
4083 if (editor->bWordWrap != new)
4085 editor->bWordWrap = new;
4086 ME_RewrapRepaint(editor);
4089 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
4090 break;
4091 default:
4092 do_default:
4093 return DefWindowProcW(hWnd, msg, wParam, lParam);
4095 return 0L;
4098 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4100 BOOL unicode = TRUE;
4102 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4103 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4104 unicode = FALSE;
4106 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4109 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4111 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4114 /******************************************************************
4115 * RichEditANSIWndProc (RICHED20.10)
4117 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4119 return RichEditWndProcA(hWnd, msg, wParam, lParam);
4122 /******************************************************************
4123 * RichEdit10ANSIWndProc (RICHED20.9)
4125 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4127 LRESULT result;
4129 /* FIXME: this is NOT the same as 2.0 version */
4130 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4131 if (msg == WM_NCCREATE)
4133 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4135 editor->bEmulateVersion10 = TRUE;
4136 editor->pBuffer->pLast->member.para.nCharOfs = 2;
4137 assert(editor->pBuffer->pLast->prev->type == diRun);
4138 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
4139 editor->pBuffer->pLast->prev->member.run.nLF = 1;
4141 return result;
4144 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4146 HWND hWnd = editor->hWnd;
4147 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
4150 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
4152 int x,y;
4153 ME_Cursor tmpCursor;
4154 BOOL isExact;
4155 int nCharOfs; /* The start of the clicked text. Absolute character offset */
4157 ME_Run *tmpRun;
4159 ENLINK info;
4160 x = (short)LOWORD(lParam);
4161 y = (short)HIWORD(lParam);
4162 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
4163 if (!isExact) return;
4165 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
4166 tmpRun = &tmpCursor.pRun->member.run;
4168 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
4169 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
4170 { /* The clicked run has CFE_LINK set */
4171 info.nmhdr.hwndFrom = editor->hWnd;
4172 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
4173 info.nmhdr.code = EN_LINK;
4174 info.msg = msg;
4175 info.wParam = wParam;
4176 info.lParam = lParam;
4177 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
4178 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
4179 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
4183 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
4185 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
4186 int i = 0;
4188 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
4189 item = item->member.para.next_para;
4190 if (!item)
4191 return 0;
4192 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
4193 item = item->member.para.next_para;
4194 i++;
4196 return i;
4200 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
4202 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
4203 int nWritten = 0;
4204 WCHAR *pStart = buffer;
4206 if (!item) {
4207 *buffer = 0;
4208 return 0;
4211 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4212 if (editor->bEmulateVersion10) bCRLF = 0;
4214 if (nStart)
4216 int nLen = ME_StrLen(item->member.run.strText) - nStart;
4217 if (nLen > nChars)
4218 nLen = nChars;
4219 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
4220 nChars -= nLen;
4221 nWritten += nLen;
4222 buffer += nLen;
4223 if (!nChars) {
4224 *buffer = 0;
4225 return nWritten;
4227 nStart = 0;
4228 item = ME_FindItemFwd(item, diRun);
4231 while(nChars && item)
4233 int nLen = ME_StrLen(item->member.run.strText);
4234 if (item->member.run.nFlags & MERF_ENDPARA)
4235 nLen = item->member.run.nCR + item->member.run.nLF;
4236 if (nLen > nChars)
4237 nLen = nChars;
4239 if (item->member.run.nFlags & MERF_ENDCELL &&
4240 item->member.run.nFlags & MERF_ENDPARA)
4242 *buffer = '\t';
4244 else if (item->member.run.nFlags & MERF_ENDPARA)
4246 if (!ME_FindItemFwd(item, diRun))
4247 /* No '\r' is appended to the last paragraph. */
4248 nLen = 0;
4249 else if (bCRLF && nChars == 1) {
4250 nLen = 0;
4251 nChars = 0;
4252 } else {
4253 if (bCRLF)
4255 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
4256 if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4257 assert(nLen == 2);
4258 else
4259 assert(nLen == 1);
4260 *buffer++ = '\r';
4261 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4262 if (nLen == 1)
4263 nWritten++;
4264 else
4265 buffer--;
4267 else
4269 int i, j;
4271 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4272 i = 0;
4273 while (nChars - i > 0 && i < item->member.run.nCR)
4275 buffer[i] = '\r'; i++;
4277 j = 0;
4278 while (nChars - i - j > 0 && j < item->member.run.nLF)
4280 buffer[i+j] = '\n'; j++;
4285 else
4286 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4287 nChars -= nLen;
4288 nWritten += nLen;
4289 buffer += nLen;
4291 if (!nChars)
4293 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4294 *buffer = 0;
4295 return nWritten;
4297 item = ME_FindItemFwd(item, diRun);
4299 *buffer = 0;
4300 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4301 return nWritten;
4304 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4306 WNDCLASSW wcW;
4307 WNDCLASSA wcA;
4309 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4310 wcW.lpfnWndProc = RichEditWndProcW;
4311 wcW.cbClsExtra = 0;
4312 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4313 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4314 wcW.hIcon = NULL;
4315 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4316 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4317 wcW.lpszMenuName = NULL;
4319 if (is_version_nt())
4321 wcW.lpszClassName = RichEdit20W;
4322 if (!RegisterClassW(&wcW)) return FALSE;
4323 wcW.lpszClassName = RichEdit50W;
4324 if (!RegisterClassW(&wcW)) return FALSE;
4326 else
4328 /* WNDCLASSA/W have the same layout */
4329 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4330 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4331 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4332 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4335 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4336 wcA.lpfnWndProc = RichEditWndProcA;
4337 wcA.cbClsExtra = 0;
4338 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4339 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4340 wcA.hIcon = NULL;
4341 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4342 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4343 wcA.lpszMenuName = NULL;
4344 wcA.lpszClassName = "RichEdit20A";
4345 if (!RegisterClassA(&wcA)) return FALSE;
4346 wcA.lpszClassName = "RichEdit50A";
4347 if (!RegisterClassA(&wcA)) return FALSE;
4349 return TRUE;
4352 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4353 /* FIXME: Not implemented */
4354 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4355 hWnd, msg, get_msg_name(msg), wParam, lParam);
4356 return DefWindowProcW(hWnd, msg, wParam, lParam);
4359 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4360 /* FIXME: Not implemented */
4361 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4362 hWnd, msg, get_msg_name(msg), wParam, lParam);
4363 return DefWindowProcW(hWnd, msg, wParam, lParam);
4366 /******************************************************************
4367 * REExtendedRegisterClass (RICHED20.8)
4369 * FIXME undocumented
4370 * Need to check for errors and implement controls and callbacks
4372 LRESULT WINAPI REExtendedRegisterClass(void)
4374 WNDCLASSW wcW;
4375 UINT result;
4377 FIXME("semi stub\n");
4379 wcW.cbClsExtra = 0;
4380 wcW.cbWndExtra = 4;
4381 wcW.hInstance = NULL;
4382 wcW.hIcon = NULL;
4383 wcW.hCursor = NULL;
4384 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4385 wcW.lpszMenuName = NULL;
4387 if (!ME_ListBoxRegistered)
4389 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4390 wcW.lpfnWndProc = REListWndProc;
4391 wcW.lpszClassName = REListBox20W;
4392 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4395 if (!ME_ComboBoxRegistered)
4397 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4398 wcW.lpfnWndProc = REComboWndProc;
4399 wcW.lpszClassName = REComboBox20W;
4400 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4403 result = 0;
4404 if (ME_ListBoxRegistered)
4405 result += 1;
4406 if (ME_ComboBoxRegistered)
4407 result += 2;
4409 return result;
4412 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
4414 struct prefix_s {
4415 const char *text;
4416 int length;
4417 } prefixes[12] = {
4418 {"http:", 5},
4419 {"file:", 6},
4420 {"mailto:", 8},
4421 {"ftp:", 5},
4422 {"https:", 7},
4423 {"gopher:", 8},
4424 {"nntp:", 6},
4425 {"prospero:", 10},
4426 {"telnet:", 8},
4427 {"news:", 6},
4428 {"wais:", 6},
4429 {"www.", 5}
4431 CHARRANGE ins_pt;
4432 int curf_ef, link_ef, def_ef;
4433 int cur_prefx, prefx_cnt;
4434 int sel_min, sel_max;
4435 int car_pos = 0;
4436 int text_pos=-1;
4437 int URLmin, URLmax = 0;
4438 FINDTEXTA ft;
4439 CHARFORMAT2W cur_format;
4440 CHARFORMAT2W default_format;
4441 CHARFORMAT2W link;
4442 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
4443 sel_min = ins_pt.cpMin;
4444 sel_max = ins_pt.cpMax;
4445 if (sel_min==sel_max)
4446 car_pos = sel_min;
4447 if (sel_min!=sel_max)
4448 car_pos = ME_GetTextLength(editor)+1;
4449 cur_format.cbSize = sizeof(cur_format);
4450 default_format.cbSize = sizeof(default_format);
4451 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
4452 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
4453 link.cbSize = sizeof(link);
4454 link.dwMask = CFM_LINK;
4455 link.dwEffects = CFE_LINK;
4456 curf_ef = cur_format.dwEffects & link.dwEffects;
4457 def_ef = default_format.dwEffects & link.dwEffects;
4458 link_ef = link.dwEffects & link.dwEffects;
4459 if (curf_ef == link_ef)
4461 if( curChar == '\n' || curChar=='\r' || curChar==' ')
4463 ME_SetSelection(editor, car_pos, car_pos);
4464 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
4465 text_pos=-1;
4466 return 0;
4469 if (curf_ef == def_ef)
4471 cur_prefx = 0;
4472 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
4473 while (cur_prefx<=prefx_cnt)
4475 if (text_pos == -1)
4477 ft.lpstrText = prefixes[cur_prefx].text;
4478 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
4479 URLmax=max(0, car_pos);
4480 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
4482 URLmax = ME_GetTextLength(editor)+1;
4484 ft.chrg.cpMin = URLmin;
4485 ft.chrg.cpMax = URLmax;
4486 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
4487 cur_prefx++;
4489 if (text_pos != -1)
4491 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
4492 ME_RewrapRepaint(editor);
4493 break;
4497 return 0;
4501 static BOOL isurlspecial(WCHAR c)
4503 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4504 return strchrW( special_chars, c ) != NULL;
4508 * This proc takes a selection, and scans it forward in order to select the span
4509 * of a possible URL candidate. A possible URL candidate must start with isalnum
4510 * or one of the following special characters: *|/\+%#@ and must consist entirely
4511 * of the characters allowed to start the URL, plus : (colon) which may occur
4512 * at most once, and not at either end.
4514 * sel_max == -1 indicates scan to end of text.
4516 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4517 int * candidate_min, int * candidate_max)
4519 ME_DisplayItem * item;
4520 ME_DisplayItem * para;
4521 int nStart;
4522 BOOL foundColon = FALSE;
4523 WCHAR lastAcceptedChar = '\0';
4525 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4527 *candidate_min = *candidate_max = -1;
4528 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4529 if (!item) return FALSE;
4530 TRACE("nStart = %d\n", nStart);
4531 para = ME_GetParagraph(item);
4532 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4533 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4535 ME_DisplayItem * next_item;
4537 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4538 /* Find start of candidate */
4539 if (*candidate_min == -1) {
4540 while (nStart < ME_StrLen(item->member.run.strText) &&
4541 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4542 isurlspecial(item->member.run.strText->szData[nStart]))) {
4543 nStart++;
4545 if (nStart < ME_StrLen(item->member.run.strText) &&
4546 (isalnumW(item->member.run.strText->szData[nStart]) ||
4547 isurlspecial(item->member.run.strText->szData[nStart]))) {
4548 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4549 lastAcceptedChar = item->member.run.strText->szData[nStart];
4550 nStart++;
4554 /* Find end of candidate */
4555 if (*candidate_min >= 0) {
4556 while (nStart < ME_StrLen(item->member.run.strText) &&
4557 (isalnumW(item->member.run.strText->szData[nStart]) ||
4558 isurlspecial(item->member.run.strText->szData[nStart]) ||
4559 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4560 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4561 lastAcceptedChar = item->member.run.strText->szData[nStart];
4562 nStart++;
4564 if (nStart < ME_StrLen(item->member.run.strText) &&
4565 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4566 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4567 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4568 nStart++;
4569 if (lastAcceptedChar == ':') (*candidate_max)--;
4570 return TRUE;
4573 } else {
4574 /* End of paragraph: skip it if before candidate span, or terminates
4575 current active span */
4576 if (*candidate_min >= 0) {
4577 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4578 if (lastAcceptedChar == ':') (*candidate_max)--;
4579 return TRUE;
4583 /* Reaching this point means no span was found, so get next span */
4584 next_item = ME_FindItemFwd(item, diRun);
4585 if (!next_item) {
4586 if (*candidate_min >= 0) {
4587 /* There are no further runs, so take end of text as end of candidate */
4588 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4589 if (lastAcceptedChar == ':') (*candidate_max)--;
4590 return TRUE;
4593 item = next_item;
4594 para = ME_GetParagraph(item);
4595 nStart = 0;
4598 if (item) {
4599 if (*candidate_min >= 0) {
4600 /* There are no further runs, so take end of text as end of candidate */
4601 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4602 if (lastAcceptedChar == ':') (*candidate_max)--;
4603 return TRUE;
4606 return FALSE;
4610 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4612 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4614 struct prefix_s {
4615 const char *text;
4616 int length;
4617 } prefixes[12] = {
4618 /* Code below depends on these being in decreasing length order! */
4619 {"prospero:", 10},
4620 {"telnet:", 8},
4621 {"gopher:", 8},
4622 {"mailto:", 8},
4623 {"https:", 7},
4624 {"file:", 6},
4625 {"news:", 6},
4626 {"wais:", 6},
4627 {"nntp:", 6},
4628 {"http:", 5},
4629 {"www.", 5},
4630 {"ftp:", 5},
4632 LPWSTR bufferW = NULL;
4633 WCHAR bufW[32];
4634 int i;
4636 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4637 assert(sel_min <= sel_max);
4638 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4640 if (sel_max - sel_min < prefixes[i].length) continue;
4641 if (bufferW == NULL) {
4642 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4644 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4645 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4646 if (!lstrcmpW(bufW, bufferW))
4648 heap_free(bufferW);
4649 return TRUE;
4652 heap_free(bufferW);
4653 return FALSE;
4657 * This proc walks through the indicated selection and evaluates whether each
4658 * section identified by ME_FindNextURLCandidate and in-between sections have
4659 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4660 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4662 * Returns TRUE if at least one section was modified.
4664 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4666 BOOL modified = FALSE;
4667 int cMin, cMax;
4669 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4672 int beforeURL[2];
4673 int inURL[2];
4674 CHARFORMAT2W link;
4676 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4678 /* Section before candidate is not an URL */
4679 beforeURL[0] = sel_min;
4680 beforeURL[1] = cMin;
4682 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4684 inURL[0] = cMin; inURL[1] = cMax;
4686 else
4688 beforeURL[1] = cMax;
4689 inURL[0] = inURL[1] = -1;
4691 sel_min = cMax;
4693 else
4695 /* No more candidates until end of selection */
4696 beforeURL[0] = sel_min;
4697 beforeURL[1] = sel_max;
4698 inURL[0] = inURL[1] = -1;
4699 sel_min = sel_max;
4702 if (beforeURL[0] < beforeURL[1])
4704 /* CFE_LINK effect should be consistently unset */
4705 link.cbSize = sizeof(link);
4706 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4707 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4709 /* CFE_LINK must be unset from this range */
4710 memset(&link, 0, sizeof(CHARFORMAT2W));
4711 link.cbSize = sizeof(link);
4712 link.dwMask = CFM_LINK;
4713 link.dwEffects = 0;
4714 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4715 modified = TRUE;
4718 if (inURL[0] < inURL[1])
4720 /* CFE_LINK effect should be consistently set */
4721 link.cbSize = sizeof(link);
4722 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4723 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4725 /* CFE_LINK must be set on this range */
4726 memset(&link, 0, sizeof(CHARFORMAT2W));
4727 link.cbSize = sizeof(link);
4728 link.dwMask = CFM_LINK;
4729 link.dwEffects = CFE_LINK;
4730 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4731 modified = TRUE;
4734 } while (sel_min < sel_max);
4735 return modified;
4738 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4740 ME_DisplayItem * startPara, * endPara;
4741 ME_DisplayItem * item;
4742 int dummy;
4743 int from, to;
4745 ME_GetSelection(editor, &from, &to);
4746 if (from > to) from ^= to, to ^=from, from ^= to;
4747 startPara = NULL; endPara = NULL;
4749 /* Find paragraph previous to the one that contains start cursor */
4750 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4751 if (item) {
4752 startPara = ME_FindItemBack(item, diParagraph);
4753 item = ME_FindItemBack(startPara, diParagraph);
4754 if (item) startPara = item;
4757 /* Find paragraph that contains end cursor */
4758 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4759 if (item) {
4760 endPara = ME_FindItemFwd(item, diParagraph);
4763 if (startPara && endPara) {
4764 ME_UpdateLinkAttribute(editor,
4765 startPara->member.para.nCharOfs,
4766 endPara->member.para.nCharOfs);
4767 } else if (startPara) {
4768 ME_UpdateLinkAttribute(editor,
4769 startPara->member.para.nCharOfs,
4770 -1);