push 6495605bb529da27066f1c178d57d902552737a0
[wine/hacks.git] / dlls / riched20 / editor.c
blobaa5938326a3a980ad0f88f32ecc0af62458f47e3
1 /*
2 * RichEdit - functions dealing with editor object
4 * Copyright 2004 by Krzysztof Foltman
5 * Copyright 2005 by Cihan Altinay
6 * Copyright 2005 by Phil Krylov
7 * Copyright 2008 Eric Pouech
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 /*
25 API implementation status:
27 Messages (ANSI versions not done yet)
28 + EM_AUTOURLDETECT 2.0
29 + EM_CANPASTE
30 + EM_CANREDO 2.0
31 + EM_CANUNDO
32 + EM_CHARFROMPOS
33 - EM_DISPLAYBAND
34 + EM_EMPTYUNDOBUFFER
35 + EM_EXGETSEL
36 + EM_EXLIMITTEXT
37 + EM_EXLINEFROMCHAR
38 + EM_EXSETSEL
39 + EM_FINDTEXT (only FR_DOWN flag implemented)
40 + EM_FINDTEXTEX (only FR_DOWN flag implemented)
41 - EM_FINDWORDBREAK
42 - EM_FMTLINES
43 - EM_FORMATRANGE
44 + EM_GETAUTOURLDETECT 2.0
45 - EM_GETBIDIOPTIONS 3.0
46 - EM_GETCHARFORMAT (partly done)
47 - EM_GETEDITSTYLE
48 + EM_GETEVENTMASK
49 + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
50 - EM_GETIMECOLOR 1.0asian
51 - EM_GETIMECOMPMODE 2.0
52 - EM_GETIMEOPTIONS 1.0asian
53 - EM_GETIMESTATUS
54 - EM_GETLANGOPTIONS 2.0
55 + EM_GETLIMITTEXT
56 + EM_GETLINE
57 + EM_GETLINECOUNT returns number of rows, not of paragraphs
58 + EM_GETMODIFY
59 - EM_GETOLEINTERFACE
60 + EM_GETOPTIONS
61 + EM_GETPARAFORMAT
62 + EM_GETPASSWORDCHAR 2.0
63 - EM_GETPUNCTUATION 1.0asian
64 + EM_GETRECT
65 - EM_GETREDONAME 2.0
66 + EM_GETSEL
67 + EM_GETSELTEXT (ANSI&Unicode)
68 + EM_GETSCROLLPOS 3.0 (only Y value valid)
69 ! - EM_GETTHUMB
70 + EM_GETTEXTEX 2.0
71 + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
72 - EM_GETTEXTMODE 2.0
73 ? + EM_GETTEXTRANGE (ANSI&Unicode)
74 - EM_GETTYPOGRAPHYOPTIONS 3.0
75 - EM_GETUNDONAME
76 + EM_GETWORDBREAKPROC
77 - EM_GETWORDBREAKPROCEX
78 - EM_GETWORDWRAPMODE 1.0asian
79 + EM_GETZOOM 3.0
80 + EM_HIDESELECTION
81 + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
82 + EM_LINEFROMCHAR
83 + EM_LINEINDEX
84 + EM_LINELENGTH
85 + EM_LINESCROLL
86 - EM_PASTESPECIAL
87 + EM_POSFROMCHAR
88 + EM_REDO 2.0
89 + EM_REQUESTRESIZE
90 + EM_REPLACESEL (proper style?) ANSI&Unicode
91 + EM_SCROLL
92 + EM_SCROLLCARET
93 - EM_SELECTIONTYPE
94 - EM_SETBIDIOPTIONS 3.0
95 + EM_SETBKGNDCOLOR
96 + EM_SETCHARFORMAT (partly done, no ANSI)
97 - EM_SETEDITSTYLE
98 + EM_SETEVENTMASK (few notifications supported)
99 - EM_SETFONTSIZE
100 - EM_SETIMECOLOR 1.0asian
101 - EM_SETIMEOPTIONS 1.0asian
102 - EM_SETLANGOPTIONS 2.0
103 - EM_SETLIMITTEXT
104 + EM_SETMODIFY (not sure if implementation is correct)
105 - EM_SETOLECALLBACK
106 + EM_SETOPTIONS (partially implemented)
107 - EM_SETPALETTE 2.0
108 + EM_SETPARAFORMAT
109 + EM_SETPASSWORDCHAR 2.0
110 - EM_SETPUNCTUATION 1.0asian
111 + EM_SETREADONLY no beep on modification attempt
112 + EM_SETRECT
113 + EM_SETRECTNP (EM_SETRECT without repainting)
114 + EM_SETSEL
115 + EM_SETSCROLLPOS 3.0
116 - EM_SETTABSTOPS 3.0
117 - EM_SETTARGETDEVICE (partial)
118 + EM_SETTEXTEX 3.0 (proper style?)
119 - EM_SETTEXTMODE 2.0
120 - EM_SETTYPOGRAPHYOPTIONS 3.0
121 + EM_SETUNDOLIMIT 2.0
122 + EM_SETWORDBREAKPROC (used only for word movement at the moment)
123 - EM_SETWORDBREAKPROCEX
124 - EM_SETWORDWRAPMODE 1.0asian
125 + EM_SETZOOM 3.0
126 + EM_SHOWSCROLLBAR 2.0
127 + EM_STOPGROUPTYPING 2.0
128 + EM_STREAMIN
129 + EM_STREAMOUT
130 + EM_UNDO
131 + WM_CHAR
132 + WM_CLEAR
133 + WM_COPY
134 + WM_CUT
135 + WM_GETDLGCODE (the current implementation is incomplete)
136 + WM_GETTEXT (ANSI&Unicode)
137 + WM_GETTEXTLENGTH (ANSI version sucks)
138 + WM_PASTE
139 + WM_SETFONT
140 + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
141 - WM_STYLECHANGING
142 - WM_STYLECHANGED (things like read-only flag)
143 + WM_UNICHAR
145 Notifications
147 * EN_CHANGE (sent from the wrong place)
148 - EN_CORRECTTEXT
149 - EN_DROPFILES
150 - EN_ERRSPACE
151 - EN_HSCROLL
152 - EN_IMECHANGE
153 + EN_KILLFOCUS
154 - EN_LINK
155 - EN_MAXTEXT
156 - EN_MSGFILTER
157 - EN_OLEOPFAILED
158 - EN_PROTECTED
159 + EN_REQUESTRESIZE
160 - EN_SAVECLIPBOARD
161 + EN_SELCHANGE
162 + EN_SETFOCUS
163 - EN_STOPNOUNDO
164 * EN_UPDATE (sent from the wrong place)
165 - EN_VSCROLL
167 Styles
169 - ES_AUTOHSCROLL
170 - ES_AUTOVSCROLL
171 - ES_CENTER
172 + ES_DISABLENOSCROLL (scrollbar is always visible)
173 - ES_EX_NOCALLOLEINIT
174 - ES_LEFT
175 - ES_MULTILINE (currently single line controls aren't supported)
176 - ES_NOIME
177 - ES_READONLY (I'm not sure if beeping is the proper behaviour)
178 - ES_RIGHT
179 - ES_SAVESEL
180 - ES_SELFIME
181 - ES_SUNKEN
182 - ES_VERTICAL
183 - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
184 - WS_SETFONT
185 - WS_HSCROLL
186 + WS_VSCROLL
190 * RICHED20 TODO (incomplete):
192 * - messages/styles/notifications listed above
193 * - add remaining CHARFORMAT/PARAFORMAT fields
194 * - right/center align should strip spaces from the beginning
195 * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196 * - COM interface (looks like a major pain in the TODO list)
197 * - calculate heights of pictures (half-done)
198 * - horizontal scrolling (not even started)
199 * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200 * - find/replace
201 * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202 * - italic caret with italic fonts
203 * - IME
204 * - most notifications aren't sent at all (the most important ones are)
205 * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206 * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207 * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208 * - full justification
209 * - hyphenation
210 * - tables
211 * - ListBox & ComboBox not implemented
213 * Bugs that are probably fixed, but not so easy to verify:
214 * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215 * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216 * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217 * - caret shouldn't be displayed when selection isn't empty
218 * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219 * - undo for setting default format (done, might be buggy)
220 * - styles might be not released properly (looks like they work like charm, but who knows?
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM
228 #include "shlwapi.h"
229 #include "rtf.h"
230 #include "imm.h"
231 #include "res.h"
233 #define STACK_SIZE_DEFAULT 100
234 #define STACK_SIZE_MAX 1000
236 #define TEXT_LIMIT_DEFAULT 32767
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
240 static BOOL ME_RegisterEditorClass(HINSTANCE);
242 static const WCHAR RichEdit20W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
243 static const WCHAR RichEdit50W[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
244 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
245 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
246 static HCURSOR hLeft;
248 int me_debug = 0;
249 HANDLE me_heap = NULL;
251 static BOOL ME_ListBoxRegistered = FALSE;
252 static BOOL ME_ComboBoxRegistered = FALSE;
254 static inline int is_version_nt(void)
256 return !(GetVersion() & 0x80000000);
259 static ME_TextBuffer *ME_MakeText(void) {
261 ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
263 ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
264 ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
266 p1->prev = NULL;
267 p1->next = p2;
268 p2->prev = p1;
269 p2->next = NULL;
270 p1->member.para.next_para = p2;
271 p2->member.para.prev_para = p1;
272 p2->member.para.nCharOfs = 0;
274 buf->pFirst = p1;
275 buf->pLast = p2;
276 buf->pCharStyle = NULL;
278 return buf;
282 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
284 WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
285 WCHAR *pText;
287 TRACE("%08x %p\n", dwFormat, stream);
289 do {
290 long nWideChars = 0;
292 if (!stream->dwSize)
294 ME_StreamInFill(stream);
295 if (stream->editstream->dwError)
296 break;
297 if (!stream->dwSize)
298 break;
301 if (!(dwFormat & SF_UNICODE))
303 /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
304 nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
305 pText = wszText;
307 else
309 nWideChars = stream->dwSize >> 1;
310 pText = (WCHAR *)stream->buffer;
313 ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
314 if (stream->dwSize == 0)
315 break;
316 stream->dwSize = 0;
317 } while(1);
318 ME_CommitUndo(editor);
319 ME_UpdateRepaint(editor);
320 return 0;
323 static void ME_ApplyBorderProperties(RTF_Info *info,
324 ME_BorderRect *borderRect,
325 RTFBorder *borderDef)
327 int i, colorNum;
328 ME_Border *pBorders[] = {&borderRect->top,
329 &borderRect->left,
330 &borderRect->bottom,
331 &borderRect->right};
332 for (i = 0; i < 4; i++)
334 RTFColor *colorDef = info->colorList;
335 pBorders[i]->width = borderDef[i].width;
336 colorNum = borderDef[i].color;
337 while (colorDef && colorDef->rtfCNum != colorNum)
338 colorDef = colorDef->rtfNextColor;
339 if (colorDef)
340 pBorders[i]->colorRef = RGB(
341 colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
342 colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
343 colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
344 else
345 pBorders[i]->colorRef = RGB(0, 0, 0);
349 static void ME_RTFCharAttrHook(RTF_Info *info)
351 CHARFORMAT2W fmt;
352 fmt.cbSize = sizeof(fmt);
353 fmt.dwMask = 0;
354 fmt.dwEffects = 0;
356 switch(info->rtfMinor)
358 case rtfPlain:
359 /* FIXME add more flags once they're implemented */
360 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
361 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
362 fmt.yHeight = 12*20; /* 12pt */
363 fmt.wWeight = FW_NORMAL;
364 fmt.bUnderlineType = CFU_UNDERLINENONE;
365 break;
366 case rtfBold:
367 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
368 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
369 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
370 break;
371 case rtfItalic:
372 fmt.dwMask = CFM_ITALIC;
373 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
374 break;
375 case rtfUnderline:
376 fmt.dwMask = CFM_UNDERLINETYPE;
377 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
378 break;
379 case rtfDotUnderline:
380 fmt.dwMask = CFM_UNDERLINETYPE;
381 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
382 break;
383 case rtfDbUnderline:
384 fmt.dwMask = CFM_UNDERLINETYPE;
385 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
386 break;
387 case rtfWordUnderline:
388 fmt.dwMask = CFM_UNDERLINETYPE;
389 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
390 break;
391 case rtfNoUnderline:
392 fmt.dwMask = CFM_UNDERLINETYPE;
393 fmt.bUnderlineType = CFU_UNDERLINENONE;
394 break;
395 case rtfStrikeThru:
396 fmt.dwMask = CFM_STRIKEOUT;
397 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
398 break;
399 case rtfSubScript:
400 case rtfSuperScript:
401 case rtfSubScrShrink:
402 case rtfSuperScrShrink:
403 case rtfNoSuperSub:
404 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
405 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
406 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
407 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
408 break;
409 case rtfInvisible:
410 fmt.dwMask = CFM_HIDDEN;
411 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
412 break;
413 case rtfBackColor:
414 fmt.dwMask = CFM_BACKCOLOR;
415 fmt.dwEffects = 0;
416 if (info->rtfParam == 0)
417 fmt.dwEffects = CFE_AUTOBACKCOLOR;
418 else if (info->rtfParam != rtfNoParam)
420 RTFColor *c = RTFGetColor(info, info->rtfParam);
421 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
423 break;
424 case rtfForeColor:
425 fmt.dwMask = CFM_COLOR;
426 fmt.dwEffects = 0;
427 if (info->rtfParam == 0)
428 fmt.dwEffects = CFE_AUTOCOLOR;
429 else if (info->rtfParam != rtfNoParam)
431 RTFColor *c = RTFGetColor(info, info->rtfParam);
432 if (c)
433 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
434 else
435 fmt.crTextColor = 0;
437 break;
438 case rtfFontNum:
439 if (info->rtfParam != rtfNoParam)
441 RTFFont *f = RTFGetFont(info, info->rtfParam);
442 if (f)
444 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
445 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
446 fmt.bCharSet = f->rtfFCharSet;
447 fmt.dwMask = CFM_FACE | CFM_CHARSET;
448 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
451 break;
452 case rtfFontSize:
453 fmt.dwMask = CFM_SIZE;
454 if (info->rtfParam != rtfNoParam)
455 fmt.yHeight = info->rtfParam*10;
456 break;
458 if (fmt.dwMask) {
459 ME_Style *style2;
460 RTFFlushOutputBuffer(info);
461 /* FIXME too slow ? how come ? */
462 style2 = ME_ApplyStyle(info->style, &fmt);
463 ME_ReleaseStyle(info->style);
464 info->style = style2;
465 info->styleChanged = TRUE;
469 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
470 the same tags mean different things in different contexts */
471 static void ME_RTFParAttrHook(RTF_Info *info)
473 PARAFORMAT2 fmt;
474 fmt.cbSize = sizeof(fmt);
475 fmt.dwMask = 0;
477 switch(info->rtfMinor)
479 case rtfParDef: /* restores default paragraph attributes */
480 if (!info->editor->bEmulateVersion10) /* v4.1 */
481 info->borderType = RTFBorderParaLeft;
482 else /* v1.0 - 3.0 */
483 info->borderType = RTFBorderParaTop;
484 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
485 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
486 PFM_STARTINDENT;
487 /* TODO: numbering, shading */
488 fmt.wAlignment = PFA_LEFT;
489 fmt.cTabCount = 0;
490 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
491 fmt.wBorderWidth = fmt.wBorders = 0;
492 fmt.wBorderSpace = 0;
493 fmt.bLineSpacingRule = 0;
494 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
495 fmt.dyLineSpacing = 0;
496 if (!info->editor->bEmulateVersion10) /* v4.1 */
498 if (info->tableDef && info->tableDef->tableRowStart &&
499 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
501 ME_Cursor cursor;
502 ME_DisplayItem *para;
503 /* We are just after a table row. */
504 RTFFlushOutputBuffer(info);
505 cursor = info->editor->pCursors[0];
506 para = ME_GetParagraph(cursor.pRun);
507 if (para == info->tableDef->tableRowStart->member.para.next_para
508 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
510 /* Since the table row end, no text has been inserted, and the \intbl
511 * control word has not be used. We can confirm that we are not in a
512 * table anymore.
514 info->tableDef->tableRowStart = NULL;
515 info->canInheritInTbl = FALSE;
518 } else { /* v1.0 - v3.0 */
519 fmt.dwMask |= PFM_TABLE;
520 fmt.wEffects &= ~PFE_TABLE;
522 break;
523 case rtfNestLevel:
524 if (!info->editor->bEmulateVersion10) /* v4.1 */
526 while (info->rtfParam > info->nestingLevel) {
527 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
528 ZeroMemory(tableDef, sizeof(RTFTable));
529 tableDef->parent = info->tableDef;
530 info->tableDef = tableDef;
532 RTFFlushOutputBuffer(info);
533 if (tableDef->tableRowStart &&
534 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
536 ME_DisplayItem *para = tableDef->tableRowStart;
537 para = para->member.para.next_para;
538 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
539 tableDef->tableRowStart = para;
540 } else {
541 ME_Cursor cursor;
542 WCHAR endl = '\r';
543 cursor = info->editor->pCursors[0];
544 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
545 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
546 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
549 info->nestingLevel++;
551 info->canInheritInTbl = FALSE;
553 break;
554 case rtfInTable:
556 if (!info->editor->bEmulateVersion10) /* v4.1 */
558 if (info->nestingLevel < 1)
560 RTFTable *tableDef;
561 if (!info->tableDef)
563 info->tableDef = ALLOC_OBJ(RTFTable);
564 ZeroMemory(info->tableDef, sizeof(RTFTable));
566 tableDef = info->tableDef;
567 RTFFlushOutputBuffer(info);
568 if (tableDef->tableRowStart &&
569 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
571 ME_DisplayItem *para = tableDef->tableRowStart;
572 para = para->member.para.next_para;
573 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
574 tableDef->tableRowStart = para;
575 } else {
576 ME_Cursor cursor;
577 WCHAR endl = '\r';
578 cursor = info->editor->pCursors[0];
579 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
580 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
581 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
583 info->nestingLevel = 1;
584 info->canInheritInTbl = TRUE;
586 return;
587 } else { /* v1.0 - v3.0 */
588 fmt.dwMask |= PFM_TABLE;
589 fmt.wEffects |= PFE_TABLE;
591 break;
593 case rtfFirstIndent:
594 ME_GetSelectionParaFormat(info->editor, &fmt);
595 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
596 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
597 fmt.dxOffset = -info->rtfParam;
598 break;
599 case rtfLeftIndent:
600 ME_GetSelectionParaFormat(info->editor, &fmt);
601 fmt.dwMask = PFM_STARTINDENT;
602 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
603 break;
604 case rtfRightIndent:
605 fmt.dwMask = PFM_RIGHTINDENT;
606 fmt.dxRightIndent = info->rtfParam;
607 break;
608 case rtfQuadLeft:
609 case rtfQuadJust:
610 fmt.dwMask = PFM_ALIGNMENT;
611 fmt.wAlignment = PFA_LEFT;
612 break;
613 case rtfQuadRight:
614 fmt.dwMask = PFM_ALIGNMENT;
615 fmt.wAlignment = PFA_RIGHT;
616 break;
617 case rtfQuadCenter:
618 fmt.dwMask = PFM_ALIGNMENT;
619 fmt.wAlignment = PFA_CENTER;
620 break;
621 case rtfTabPos:
622 ME_GetSelectionParaFormat(info->editor, &fmt);
623 if (!(fmt.dwMask & PFM_TABSTOPS))
625 fmt.cTabCount = 0;
627 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
628 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
629 fmt.dwMask = PFM_TABSTOPS;
630 break;
631 case rtfKeep:
632 fmt.dwMask = PFM_KEEP;
633 fmt.wEffects = PFE_KEEP;
634 break;
635 case rtfNoWidowControl:
636 fmt.dwMask = PFM_NOWIDOWCONTROL;
637 fmt.wEffects = PFE_NOWIDOWCONTROL;
638 break;
639 case rtfKeepNext:
640 fmt.dwMask = PFM_KEEPNEXT;
641 fmt.wEffects = PFE_KEEPNEXT;
642 break;
643 case rtfSpaceAfter:
644 fmt.dwMask = PFM_SPACEAFTER;
645 fmt.dySpaceAfter = info->rtfParam;
646 break;
647 case rtfSpaceBefore:
648 fmt.dwMask = PFM_SPACEBEFORE;
649 fmt.dySpaceBefore = info->rtfParam;
650 break;
651 case rtfSpaceBetween:
652 fmt.dwMask = PFM_LINESPACING;
653 if ((int)info->rtfParam > 0)
655 fmt.dyLineSpacing = info->rtfParam;
656 fmt.bLineSpacingRule = 3;
658 else
660 fmt.dyLineSpacing = info->rtfParam;
661 fmt.bLineSpacingRule = 4;
663 case rtfSpaceMultiply:
664 fmt.dwMask = PFM_LINESPACING;
665 fmt.dyLineSpacing = info->rtfParam * 20;
666 fmt.bLineSpacingRule = 5;
667 break;
668 case rtfParBullet:
669 fmt.dwMask = PFM_NUMBERING;
670 fmt.wNumbering = PFN_BULLET;
671 break;
672 case rtfParSimple:
673 fmt.dwMask = PFM_NUMBERING;
674 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
675 break;
676 case rtfParNumDecimal:
677 fmt.dwMask = PFM_NUMBERING;
678 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
679 break;
680 case rtfParNumIndent:
681 fmt.dwMask = PFM_NUMBERINGTAB;
682 fmt.wNumberingTab = info->rtfParam;
683 break;
684 case rtfParNumStartAt:
685 fmt.dwMask = PFM_NUMBERINGSTART;
686 fmt.wNumberingStart = info->rtfParam;
687 break;
688 case rtfBorderLeft:
689 info->borderType = RTFBorderParaLeft;
690 ME_GetSelectionParaFormat(info->editor, &fmt);
691 if (!(fmt.dwMask & PFM_BORDER))
693 fmt.wBorderSpace = 0;
694 fmt.wBorderWidth = 1;
695 fmt.wBorders = 0;
697 fmt.wBorders |= 1;
698 fmt.dwMask = PFM_BORDER;
699 break;
700 case rtfBorderRight:
701 info->borderType = RTFBorderParaRight;
702 ME_GetSelectionParaFormat(info->editor, &fmt);
703 if (!(fmt.dwMask & PFM_BORDER))
705 fmt.wBorderSpace = 0;
706 fmt.wBorderWidth = 1;
707 fmt.wBorders = 0;
709 fmt.wBorders |= 2;
710 fmt.dwMask = PFM_BORDER;
711 break;
712 case rtfBorderTop:
713 info->borderType = RTFBorderParaTop;
714 ME_GetSelectionParaFormat(info->editor, &fmt);
715 if (!(fmt.dwMask & PFM_BORDER))
717 fmt.wBorderSpace = 0;
718 fmt.wBorderWidth = 1;
719 fmt.wBorders = 0;
721 fmt.wBorders |= 4;
722 fmt.dwMask = PFM_BORDER;
723 break;
724 case rtfBorderBottom:
725 info->borderType = RTFBorderParaBottom;
726 ME_GetSelectionParaFormat(info->editor, &fmt);
727 if (!(fmt.dwMask & PFM_BORDER))
729 fmt.wBorderSpace = 0;
730 fmt.wBorderWidth = 1;
731 fmt.wBorders = 0;
733 fmt.wBorders |= 8;
734 fmt.dwMask = PFM_BORDER;
735 break;
736 case rtfBorderSingle:
737 ME_GetSelectionParaFormat(info->editor, &fmt);
738 /* we assume that borders have been created before (RTF spec) */
739 fmt.wBorders &= ~0x700;
740 fmt.wBorders |= 1 << 8;
741 fmt.dwMask = PFM_BORDER;
742 break;
743 case rtfBorderThick:
744 ME_GetSelectionParaFormat(info->editor, &fmt);
745 /* we assume that borders have been created before (RTF spec) */
746 fmt.wBorders &= ~0x700;
747 fmt.wBorders |= 2 << 8;
748 fmt.dwMask = PFM_BORDER;
749 break;
750 case rtfBorderShadow:
751 ME_GetSelectionParaFormat(info->editor, &fmt);
752 /* we assume that borders have been created before (RTF spec) */
753 fmt.wBorders &= ~0x700;
754 fmt.wBorders |= 10 << 8;
755 fmt.dwMask = PFM_BORDER;
756 break;
757 case rtfBorderDouble:
758 ME_GetSelectionParaFormat(info->editor, &fmt);
759 /* we assume that borders have been created before (RTF spec) */
760 fmt.wBorders &= ~0x700;
761 fmt.wBorders |= 7 << 8;
762 fmt.dwMask = PFM_BORDER;
763 break;
764 case rtfBorderDot:
765 ME_GetSelectionParaFormat(info->editor, &fmt);
766 /* we assume that borders have been created before (RTF spec) */
767 fmt.wBorders &= ~0x700;
768 fmt.wBorders |= 11 << 8;
769 fmt.dwMask = PFM_BORDER;
770 break;
771 case rtfBorderWidth:
773 int borderSide = info->borderType & RTFBorderSideMask;
774 RTFTable *tableDef = info->tableDef;
775 ME_GetSelectionParaFormat(info->editor, &fmt);
776 /* we assume that borders have been created before (RTF spec) */
777 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
778 if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
780 RTFBorder *border;
781 if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
782 break;
783 border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
784 border->width = info->rtfParam;
785 break;
787 fmt.dwMask = PFM_BORDER;
788 break;
790 case rtfBorderSpace:
791 ME_GetSelectionParaFormat(info->editor, &fmt);
792 /* we assume that borders have been created before (RTF spec) */
793 fmt.wBorderSpace = info->rtfParam;
794 fmt.dwMask = PFM_BORDER;
795 break;
796 case rtfBorderColor:
798 RTFTable *tableDef = info->tableDef;
799 int borderSide = info->borderType & RTFBorderSideMask;
800 int borderType = info->borderType & RTFBorderTypeMask;
801 switch(borderType)
803 case RTFBorderTypePara:
804 if (!info->editor->bEmulateVersion10) /* v4.1 */
805 break;
806 /* v1.0 - 3.0 treat paragraph and row borders the same. */
807 case RTFBorderTypeRow:
808 if (tableDef) {
809 tableDef->border[borderSide].color = info->rtfParam;
811 break;
812 case RTFBorderTypeCell:
813 if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
814 tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
816 break;
818 break;
821 if (fmt.dwMask) {
822 RTFFlushOutputBuffer(info);
823 /* FIXME too slow ? how come ?*/
824 ME_SetSelectionParaFormat(info->editor, &fmt);
828 static void ME_RTFTblAttrHook(RTF_Info *info)
830 switch (info->rtfMinor)
832 case rtfRowDef:
834 if (!info->editor->bEmulateVersion10) /* v4.1 */
835 info->borderType = 0; /* Not sure */
836 else /* v1.0 - 3.0 */
837 info->borderType = RTFBorderRowTop;
838 if (!info->tableDef) {
839 info->tableDef = ME_MakeTableDef(info->editor);
840 } else {
841 ME_InitTableDef(info->editor, info->tableDef);
843 break;
845 case rtfCellPos:
846 if (!info->tableDef)
848 info->tableDef = ME_MakeTableDef(info->editor);
850 if (info->tableDef->numCellsDefined >= MAX_TABLE_CELLS)
851 break;
852 info->tableDef->cells[info->tableDef->numCellsDefined].rightBoundary = info->rtfParam;
854 /* Tab stops were used to store cell positions before v4.1 but v4.1
855 * still seems to set the tabstops without using them. */
856 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
857 PARAFORMAT2 *pFmt = para->member.para.pFmt;
858 int cellNum = info->tableDef->numCellsDefined;
859 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
860 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
862 info->tableDef->numCellsDefined++;
863 break;
864 case rtfRowBordTop:
865 info->borderType = RTFBorderRowTop;
866 break;
867 case rtfRowBordLeft:
868 info->borderType = RTFBorderRowLeft;
869 break;
870 case rtfRowBordBottom:
871 info->borderType = RTFBorderRowBottom;
872 break;
873 case rtfRowBordRight:
874 info->borderType = RTFBorderRowRight;
875 break;
876 case rtfCellBordTop:
877 info->borderType = RTFBorderCellTop;
878 break;
879 case rtfCellBordLeft:
880 info->borderType = RTFBorderCellLeft;
881 break;
882 case rtfCellBordBottom:
883 info->borderType = RTFBorderCellBottom;
884 break;
885 case rtfCellBordRight:
886 info->borderType = RTFBorderCellRight;
887 break;
888 case rtfRowGapH:
889 if (info->tableDef)
890 info->tableDef->gapH = info->rtfParam;
891 break;
892 case rtfRowLeftEdge:
893 if (info->tableDef)
894 info->tableDef->leftEdge = info->rtfParam;
895 break;
899 static void ME_RTFSpecialCharHook(RTF_Info *info)
901 RTFTable *tableDef = info->tableDef;
902 switch (info->rtfMinor)
904 case rtfNestCell:
905 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
906 break;
907 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
908 case rtfCell:
909 if (!tableDef)
910 break;
911 RTFFlushOutputBuffer(info);
912 if (!info->editor->bEmulateVersion10) { /* v4.1 */
913 if (tableDef->tableRowStart)
915 if (!info->nestingLevel &&
916 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
918 ME_DisplayItem *para = tableDef->tableRowStart;
919 para = para->member.para.next_para;
920 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
921 tableDef->tableRowStart = para;
922 info->nestingLevel = 1;
924 ME_InsertTableCellFromCursor(info->editor);
926 } else { /* v1.0 - v3.0 */
927 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
928 PARAFORMAT2 *pFmt = para->member.para.pFmt;
929 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
930 tableDef->numCellsInserted < tableDef->numCellsDefined)
932 WCHAR tab = '\t';
933 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
934 tableDef->numCellsInserted++;
937 break;
938 case rtfNestRow:
939 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
940 break;
941 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
942 case rtfRow:
944 ME_DisplayItem *para, *cell, *run;
945 int i;
947 if (!tableDef)
948 break;
949 RTFFlushOutputBuffer(info);
950 if (!info->editor->bEmulateVersion10) { /* v4.1 */
951 if (!tableDef->tableRowStart)
952 break;
953 if (!info->nestingLevel &&
954 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
956 para = tableDef->tableRowStart;
957 para = para->member.para.next_para;
958 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
959 tableDef->tableRowStart = para;
960 info->nestingLevel++;
962 para = tableDef->tableRowStart;
963 cell = ME_FindItemFwd(para, diCell);
964 assert(cell && !cell->member.cell.prev_cell);
965 if (tableDef->numCellsDefined < 1)
967 /* 2000 twips appears to be the cell size that native richedit uses
968 * when no cell sizes are specified. */
969 const int defaultCellSize = 2000;
970 int nRightBoundary = defaultCellSize;
971 cell->member.cell.nRightBoundary = nRightBoundary;
972 while (cell->member.cell.next_cell) {
973 cell = cell->member.cell.next_cell;
974 nRightBoundary += defaultCellSize;
975 cell->member.cell.nRightBoundary = nRightBoundary;
977 para = ME_InsertTableCellFromCursor(info->editor);
978 cell = para->member.para.pCell;
979 cell->member.cell.nRightBoundary = nRightBoundary;
980 } else {
981 for (i = 0; i < tableDef->numCellsDefined; i++)
983 RTFCell *cellDef = &tableDef->cells[i];
984 cell->member.cell.nRightBoundary = cellDef->rightBoundary;
985 ME_ApplyBorderProperties(info, &cell->member.cell.border,
986 cellDef->border);
987 cell = cell->member.cell.next_cell;
988 if (!cell)
990 para = ME_InsertTableCellFromCursor(info->editor);
991 cell = para->member.para.pCell;
994 /* Cell for table row delimiter is empty */
995 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
998 run = ME_FindItemFwd(cell, diRun);
999 if (info->editor->pCursors[0].pRun != run ||
1000 info->editor->pCursors[0].nOffset)
1002 int nOfs, nChars;
1003 /* Delete inserted cells that aren't defined. */
1004 info->editor->pCursors[1].pRun = run;
1005 info->editor->pCursors[1].nOffset = 0;
1006 nOfs = ME_GetCursorOfs(info->editor, 1);
1007 nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
1008 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
1011 para = ME_InsertTableRowEndFromCursor(info->editor);
1012 para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1013 para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1014 ME_ApplyBorderProperties(info, &para->member.para.border,
1015 tableDef->border);
1016 info->nestingLevel--;
1017 if (!info->nestingLevel)
1019 if (info->canInheritInTbl) {
1020 tableDef->tableRowStart = para;
1021 } else {
1022 while (info->tableDef) {
1023 tableDef = info->tableDef;
1024 info->tableDef = tableDef->parent;
1025 heap_free(tableDef);
1028 } else {
1029 info->tableDef = tableDef->parent;
1030 heap_free(tableDef);
1032 } else { /* v1.0 - v3.0 */
1033 WCHAR endl = '\r';
1034 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1035 PARAFORMAT2 *pFmt = para->member.para.pFmt;
1036 pFmt->dxOffset = info->tableDef->gapH;
1037 pFmt->dxStartIndent = info->tableDef->leftEdge;
1039 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1040 ME_ApplyBorderProperties(info, &para->member.para.border,
1041 tableDef->border);
1042 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1044 WCHAR tab = '\t';
1045 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1046 tableDef->numCellsInserted++;
1048 pFmt->cTabCount = tableDef->numCellsDefined;
1049 if (!tableDef->numCellsDefined)
1050 pFmt->wEffects &= ~PFE_TABLE;
1051 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1052 tableDef->numCellsInserted = 0;
1054 break;
1056 case rtfTab:
1057 case rtfPar:
1058 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1059 ME_DisplayItem *para;
1060 PARAFORMAT2 *pFmt;
1061 RTFFlushOutputBuffer(info);
1062 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
1063 pFmt = para->member.para.pFmt;
1064 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1066 /* rtfPar is treated like a space within a table. */
1067 info->rtfClass = rtfText;
1068 info->rtfMajor = ' ';
1070 else if (info->rtfMinor == rtfPar && tableDef)
1071 tableDef->numCellsInserted = 0;
1073 break;
1077 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1078 const SIZEL* sz)
1080 LPOLEOBJECT lpObject = NULL;
1081 LPSTORAGE lpStorage = NULL;
1082 LPOLECLIENTSITE lpClientSite = NULL;
1083 LPDATAOBJECT lpDataObject = NULL;
1084 LPOLECACHE lpOleCache = NULL;
1085 STGMEDIUM stgm;
1086 FORMATETC fm;
1087 CLSID clsid;
1088 BOOL ret = FALSE;
1089 DWORD conn;
1091 if (hemf)
1093 stgm.tymed = TYMED_ENHMF;
1094 stgm.u.hEnhMetaFile = hemf;
1095 fm.cfFormat = CF_ENHMETAFILE;
1097 else if (hbmp)
1099 stgm.tymed = TYMED_GDI;
1100 stgm.u.hBitmap = hbmp;
1101 fm.cfFormat = CF_BITMAP;
1103 stgm.pUnkForRelease = NULL;
1105 fm.ptd = NULL;
1106 fm.dwAspect = DVASPECT_CONTENT;
1107 fm.lindex = -1;
1108 fm.tymed = stgm.tymed;
1110 if (!info->lpRichEditOle)
1112 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1115 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1116 #if 0
1117 /* FIXME: enable it when rich-edit properly implements this method */
1118 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1119 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1120 #endif
1121 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1122 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1123 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1124 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1125 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1127 REOBJECT reobject;
1129 reobject.cbStruct = sizeof(reobject);
1130 reobject.cp = REO_CP_SELECTION;
1131 reobject.clsid = clsid;
1132 reobject.poleobj = lpObject;
1133 reobject.pstg = lpStorage;
1134 reobject.polesite = lpClientSite;
1135 /* convert from twips to .01 mm */
1136 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1137 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1138 reobject.dvaspect = DVASPECT_CONTENT;
1139 reobject.dwFlags = 0; /* FIXME */
1140 reobject.dwUser = 0;
1142 /* FIXME: could be simpler */
1143 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1146 if (lpObject) IOleObject_Release(lpObject);
1147 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1148 if (lpStorage) IStorage_Release(lpStorage);
1149 if (lpDataObject) IDataObject_Release(lpDataObject);
1150 if (lpOleCache) IOleCache_Release(lpOleCache);
1152 return ret;
1155 static void ME_RTFReadPictGroup(RTF_Info *info)
1157 SIZEL sz;
1158 BYTE* buffer = NULL;
1159 unsigned bufsz, bufidx;
1160 BOOL flip;
1161 BYTE val;
1162 METAFILEPICT mfp;
1163 HENHMETAFILE hemf;
1164 HBITMAP hbmp;
1165 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1167 RTFGetToken (info);
1168 if (info->rtfClass == rtfEOF)
1169 return;
1170 mfp.mm = MM_TEXT;
1171 /* fetch picture type */
1172 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1174 mfp.mm = info->rtfParam;
1175 gfx = gfx_metafile;
1177 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1179 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1180 gfx = gfx_dib;
1182 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1184 gfx = gfx_enhmetafile;
1186 else
1188 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1189 goto skip_group;
1191 sz.cx = sz.cy = 0;
1192 /* fetch picture attributes */
1193 for (;;)
1195 RTFGetToken (info);
1196 if (info->rtfClass == rtfEOF)
1197 return;
1198 if (info->rtfClass == rtfText)
1199 break;
1200 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1202 ERR("Expected picture attribute (%d %d)\n",
1203 info->rtfClass, info->rtfMajor);
1204 goto skip_group;
1206 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1208 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1210 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1212 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1214 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1215 sz.cx = info->rtfParam;
1216 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1217 sz.cy = info->rtfParam;
1218 else
1219 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1221 /* fetch picture data */
1222 bufsz = 1024;
1223 bufidx = 0;
1224 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1225 val = info->rtfMajor;
1226 for (flip = TRUE;; flip = !flip)
1228 RTFGetToken (info);
1229 if (info->rtfClass == rtfEOF)
1231 HeapFree(GetProcessHeap(), 0, buffer);
1232 return; /* Warn ?? */
1234 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1235 break;
1236 if (info->rtfClass != rtfText) goto skip_group;
1237 if (flip)
1239 if (bufidx >= bufsz &&
1240 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1241 goto skip_group;
1242 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1244 else
1245 val = info->rtfMajor;
1247 if (flip) FIXME("wrong hex string\n");
1249 switch (gfx)
1251 case gfx_enhmetafile:
1252 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1253 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1254 break;
1255 case gfx_metafile:
1256 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1257 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1258 break;
1259 case gfx_dib:
1261 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1262 HDC hdc = GetDC(0);
1263 unsigned nc = bi->bmiHeader.biClrUsed;
1265 /* not quite right, especially for bitfields type of compression */
1266 if (!nc && bi->bmiHeader.biBitCount <= 8)
1267 nc = 1 << bi->bmiHeader.biBitCount;
1268 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1269 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1270 bi, DIB_RGB_COLORS)))
1271 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1272 ReleaseDC(0, hdc);
1274 break;
1275 default:
1276 break;
1278 HeapFree(GetProcessHeap(), 0, buffer);
1279 RTFRouteToken (info); /* feed "}" back to router */
1280 return;
1281 skip_group:
1282 HeapFree(GetProcessHeap(), 0, buffer);
1283 RTFSkipGroup(info);
1284 RTFRouteToken(info); /* feed "}" back to router */
1287 /* for now, lookup the \result part and use it, whatever the object */
1288 static void ME_RTFReadObjectGroup(RTF_Info *info)
1290 for (;;)
1292 RTFGetToken (info);
1293 if (info->rtfClass == rtfEOF)
1294 return;
1295 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1296 break;
1297 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1299 RTFGetToken (info);
1300 if (info->rtfClass == rtfEOF)
1301 return;
1302 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1304 int level = 1;
1306 while (RTFGetToken (info) != rtfEOF)
1308 if (info->rtfClass == rtfGroup)
1310 if (info->rtfMajor == rtfBeginGroup) level++;
1311 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1313 RTFRouteToken(info);
1316 else RTFSkipGroup(info);
1317 continue;
1319 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1321 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1322 return;
1325 RTFRouteToken(info); /* feed "}" back to router */
1328 static void ME_RTFReadHook(RTF_Info *info) {
1329 switch(info->rtfClass)
1331 case rtfGroup:
1332 switch(info->rtfMajor)
1334 case rtfBeginGroup:
1335 if (info->stackTop < maxStack) {
1336 info->stack[info->stackTop].fmt = info->style->fmt;
1337 info->stack[info->stackTop].codePage = info->codePage;
1338 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1340 info->stackTop++;
1341 info->styleChanged = FALSE;
1342 break;
1343 case rtfEndGroup:
1345 ME_Style *s;
1346 RTFFlushOutputBuffer(info);
1347 info->stackTop--;
1348 if (info->stackTop<=0) {
1349 info->rtfClass = rtfEOF;
1350 return;
1352 assert(info->stackTop >= 0);
1353 if (info->styleChanged)
1355 /* FIXME too slow ? how come ? */
1356 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1357 ME_ReleaseStyle(info->style);
1358 info->style = s;
1359 info->codePage = info->stack[info->stackTop].codePage;
1360 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1362 break;
1365 break;
1366 case rtfControl:
1367 switch(info->rtfMajor)
1369 case rtfCharAttr:
1370 ME_RTFCharAttrHook(info);
1371 break;
1372 case rtfParAttr:
1373 ME_RTFParAttrHook(info);
1374 break;
1375 case rtfTblAttr:
1376 ME_RTFTblAttrHook(info);
1377 break;
1378 case rtfSpecialChar:
1379 ME_RTFSpecialCharHook(info);
1380 break;
1382 break;
1386 void
1387 ME_StreamInFill(ME_InStream *stream)
1389 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1390 (BYTE *)stream->buffer,
1391 sizeof(stream->buffer),
1392 (LONG *)&stream->dwSize);
1393 stream->dwUsed = 0;
1396 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1398 RTF_Info parser;
1399 ME_Style *style;
1400 int from, to, to2, nUndoMode;
1401 int nEventMask = editor->nEventMask;
1402 ME_InStream inStream;
1403 BOOL invalidRTF = FALSE;
1405 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1406 editor->nEventMask = 0;
1408 ME_GetSelection(editor, &from, &to);
1409 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1410 style = ME_GetSelectionInsertStyle(editor);
1412 ME_InternalDeleteText(editor, from, to-from, FALSE);
1414 else {
1415 ME_DisplayItem *para_item;
1416 style = editor->pBuffer->pDefaultStyle;
1417 ME_AddRefStyle(style);
1418 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1419 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1420 from = to = 0;
1421 ME_ClearTempStyle(editor);
1423 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1424 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1428 /* Back up undo mode to a local variable */
1429 nUndoMode = editor->nUndoMode;
1431 /* Only create an undo if SFF_SELECTION is set */
1432 if (!(format & SFF_SELECTION))
1433 editor->nUndoMode = umIgnore;
1435 inStream.editstream = stream;
1436 inStream.editstream->dwError = 0;
1437 inStream.dwSize = 0;
1438 inStream.dwUsed = 0;
1440 if (format & SF_RTF)
1442 /* Check if it's really RTF, and if it is not, use plain text */
1443 ME_StreamInFill(&inStream);
1444 if (!inStream.editstream->dwError)
1446 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1447 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1449 invalidRTF = TRUE;
1450 inStream.editstream->dwError = -16;
1455 if (!invalidRTF && !inStream.editstream->dwError)
1457 if (format & SF_RTF) {
1458 ME_DisplayItem *para;
1460 /* setup the RTF parser */
1461 memset(&parser, 0, sizeof parser);
1462 RTFSetEditStream(&parser, &inStream);
1463 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1464 parser.hwndEdit = editor->hWnd;
1465 parser.editor = editor;
1466 parser.style = style;
1467 WriterInit(&parser);
1468 RTFInit(&parser);
1469 RTFSetReadHook(&parser, ME_RTFReadHook);
1470 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1471 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1472 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1473 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1474 BeginFile(&parser);
1476 /* do the parsing */
1477 RTFRead(&parser);
1478 RTFFlushOutputBuffer(&parser);
1479 if (!editor->bEmulateVersion10) { /* v4.1 */
1480 if (parser.tableDef && parser.tableDef->tableRowStart)
1482 /* Delete any incomplete table row at the end of the rich text. */
1483 int nOfs, nChars;
1484 ME_DisplayItem *pCell;
1486 para = parser.tableDef->tableRowStart;
1488 parser.rtfMinor = rtfRow;
1489 /* Complete the table row before deleting it.
1490 * By doing it this way we will have the current paragraph format set
1491 * properly to reflect that is not in the complete table, and undo items
1492 * will be added for this change to the current paragraph format. */
1493 if (parser.nestingLevel > 0)
1495 while (parser.nestingLevel--)
1496 ME_RTFSpecialCharHook(&parser);
1497 } else if (parser.canInheritInTbl) {
1498 ME_RTFSpecialCharHook(&parser);
1500 if (parser.tableDef && parser.tableDef->tableRowStart &&
1501 para->member.para.nFlags & MEPF_ROWEND)
1503 para = para->member.para.next_para;
1505 pCell = para->member.para.pCell;
1507 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1508 editor->pCursors[1].nOffset = 0;
1509 nOfs = ME_GetCursorOfs(editor, 1);
1510 nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1511 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1512 parser.tableDef->tableRowStart = NULL;
1515 ME_CheckTablesForCorruption(editor);
1516 RTFDestroy(&parser);
1517 if (parser.lpRichEditOle)
1518 IRichEditOle_Release(parser.lpRichEditOle);
1520 if (!inStream.editstream->dwError && parser.stackTop > 0)
1521 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1523 /* Remove last line break, as mandated by tests. This is not affected by
1524 CR/LF counters, since RTF streaming presents only \para tokens, which
1525 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1527 if (stripLastCR) {
1528 int newfrom, newto;
1529 ME_GetSelection(editor, &newfrom, &newto);
1530 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1531 WCHAR lastchar[3] = {'\0', '\0'};
1532 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1534 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1535 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1536 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1541 style = parser.style;
1543 else if (format & SF_TEXT)
1544 ME_StreamInText(editor, format, &inStream, style);
1545 else
1546 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1547 ME_GetSelection(editor, &to, &to2);
1548 /* put the cursor at the top */
1549 if (!(format & SFF_SELECTION))
1550 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1553 /* Restore saved undo mode */
1554 editor->nUndoMode = nUndoMode;
1556 /* even if we didn't add an undo, we need to commit anything on the stack */
1557 ME_CommitUndo(editor);
1559 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1560 if (!(format & SFF_SELECTION))
1561 ME_EmptyUndoStack(editor);
1563 ME_ReleaseStyle(style);
1564 editor->nEventMask = nEventMask;
1565 ME_UpdateRepaint(editor);
1566 if (!(format & SFF_SELECTION)) {
1567 ME_ClearTempStyle(editor);
1569 HideCaret(editor->hWnd);
1570 ME_MoveCaret(editor);
1571 ShowCaret(editor->hWnd);
1572 ME_SendSelChange(editor);
1573 ME_SendRequestResize(editor, FALSE);
1575 return 0;
1579 typedef struct tagME_RTFStringStreamStruct
1581 char *string;
1582 int pos;
1583 int length;
1584 } ME_RTFStringStreamStruct;
1586 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1588 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1589 int count;
1591 count = min(cb, pStruct->length - pStruct->pos);
1592 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1593 pStruct->pos += count;
1594 *pcb = count;
1595 return 0;
1598 static void
1599 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1601 EDITSTREAM es;
1602 ME_RTFStringStreamStruct data;
1604 data.string = string;
1605 data.length = strlen(string);
1606 data.pos = 0;
1607 es.dwCookie = (DWORD)&data;
1608 es.pfnCallback = ME_ReadFromRTFString;
1609 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1613 ME_DisplayItem *
1614 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1616 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1617 int runLength;
1619 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1620 item = ME_FindItemFwd(item, diParagraph);
1622 if (!item)
1623 return item;
1625 nOffset -= item->member.para.nCharOfs;
1626 if (nItemType == diParagraph) {
1627 if (nItemOffset)
1628 *nItemOffset = nOffset;
1629 return item;
1632 do {
1633 item = ME_FindItemFwd(item, diRun);
1634 runLength = ME_StrLen(item->member.run.strText);
1635 if (item->member.run.nFlags & MERF_ENDPARA)
1636 runLength = item->member.run.nCR + item->member.run.nLF;
1637 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1638 if (item) {
1639 nOffset -= item->member.run.nCharOfs;
1641 /* Special case: nOffset may not point exactly at the division between the
1642 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1643 into the next run, if one exists
1645 if ( item->member.run.nFlags & MERF_ENDPARA
1646 && nOffset == item->member.run.nCR
1647 && item->member.run.nLF > 0) {
1648 ME_DisplayItem *nextItem;
1649 nextItem = ME_FindItemFwd(item, diRun);
1650 if (nextItem) {
1651 nOffset = 0;
1652 item = nextItem;
1655 if (nItemOffset)
1656 *nItemOffset = nOffset;
1658 return item;
1662 static int
1663 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1665 const int nLen = lstrlenW(text);
1666 const int nTextLen = ME_GetTextLength(editor);
1667 int nStart, nEnd;
1668 int nMin, nMax;
1669 ME_DisplayItem *item;
1670 ME_DisplayItem *para;
1671 WCHAR wLastChar = ' ';
1673 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1674 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1676 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1677 FIXME("Flags 0x%08x not implemented\n",
1678 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1680 nMin = chrg->cpMin;
1681 if (chrg->cpMax == -1)
1682 nMax = nTextLen;
1683 else
1684 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1686 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1687 if (editor->bEmulateVersion10 && nMax == nTextLen)
1689 flags |= FR_DOWN;
1692 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1693 if (editor->bEmulateVersion10 && nMax < nMin)
1695 if (chrgText)
1697 chrgText->cpMin = -1;
1698 chrgText->cpMax = -1;
1700 return -1;
1703 /* when searching up, if cpMin < cpMax, then instead of searching
1704 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1705 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1706 * case, it is always bigger than cpMin.
1708 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1710 int nSwap = nMax;
1712 nMax = nMin > nTextLen ? nTextLen : nMin;
1713 if (nMin < nSwap || chrg->cpMax == -1)
1714 nMin = 0;
1715 else
1716 nMin = nSwap;
1719 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1721 if (chrgText)
1722 chrgText->cpMin = chrgText->cpMax = -1;
1723 return -1;
1726 if (flags & FR_DOWN) /* Forward search */
1728 /* If possible, find the character before where the search starts */
1729 if ((flags & FR_WHOLEWORD) && nMin)
1731 nStart = nMin - 1;
1732 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1733 if (!item)
1735 if (chrgText)
1736 chrgText->cpMin = chrgText->cpMax = -1;
1737 return -1;
1739 wLastChar = item->member.run.strText->szData[nStart];
1742 nStart = nMin;
1743 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1744 if (!item)
1746 if (chrgText)
1747 chrgText->cpMin = chrgText->cpMax = -1;
1748 return -1;
1751 para = ME_GetParagraph(item);
1752 while (item
1753 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1755 ME_DisplayItem *pCurItem = item;
1756 int nCurStart = nStart;
1757 int nMatched = 0;
1759 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1761 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1762 break;
1764 nMatched++;
1765 if (nMatched == nLen)
1767 ME_DisplayItem *pNextItem = pCurItem;
1768 int nNextStart = nCurStart;
1769 WCHAR wNextChar;
1771 /* Check to see if next character is a whitespace */
1772 if (flags & FR_WHOLEWORD)
1774 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1776 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1777 nNextStart = -nMatched;
1780 if (pNextItem)
1781 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1782 else
1783 wNextChar = ' ';
1785 if (isalnumW(wNextChar))
1786 break;
1789 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1790 if (chrgText)
1792 chrgText->cpMin = nStart;
1793 chrgText->cpMax = nStart + nLen;
1795 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1796 return nStart;
1798 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1800 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1801 para = ME_GetParagraph(pCurItem);
1802 nCurStart = -nMatched;
1805 if (pCurItem)
1806 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1807 else
1808 wLastChar = ' ';
1810 nStart++;
1811 if (nStart == ME_StrLen(item->member.run.strText))
1813 item = ME_FindItemFwd(item, diRun);
1814 para = ME_GetParagraph(item);
1815 nStart = 0;
1819 else /* Backward search */
1821 /* If possible, find the character after where the search ends */
1822 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1824 nEnd = nMax + 1;
1825 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1826 if (!item)
1828 if (chrgText)
1829 chrgText->cpMin = chrgText->cpMax = -1;
1830 return -1;
1832 wLastChar = item->member.run.strText->szData[nEnd];
1835 nEnd = nMax;
1836 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1837 if (!item)
1839 if (chrgText)
1840 chrgText->cpMin = chrgText->cpMax = -1;
1841 return -1;
1844 para = ME_GetParagraph(item);
1846 while (item
1847 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1849 ME_DisplayItem *pCurItem = item;
1850 int nCurEnd = nEnd;
1851 int nMatched = 0;
1853 if (nCurEnd - nMatched == 0)
1855 pCurItem = ME_FindItemBack(pCurItem, diRun);
1856 para = ME_GetParagraph(pCurItem);
1857 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1860 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1862 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1863 break;
1865 nMatched++;
1866 if (nMatched == nLen)
1868 ME_DisplayItem *pPrevItem = pCurItem;
1869 int nPrevEnd = nCurEnd;
1870 WCHAR wPrevChar;
1872 /* Check to see if previous character is a whitespace */
1873 if (flags & FR_WHOLEWORD)
1875 if (nPrevEnd - nMatched == 0)
1877 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1878 if (pPrevItem)
1879 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1882 if (pPrevItem)
1883 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1884 else
1885 wPrevChar = ' ';
1887 if (isalnumW(wPrevChar))
1888 break;
1891 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1892 if (chrgText)
1894 chrgText->cpMin = nStart;
1895 chrgText->cpMax = nStart + nLen;
1897 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1898 return nStart;
1900 if (nCurEnd - nMatched == 0)
1902 pCurItem = ME_FindItemBack(pCurItem, diRun);
1903 /* Don't care about pCurItem becoming NULL here; it's already taken
1904 * care of in the exterior loop condition */
1905 para = ME_GetParagraph(pCurItem);
1906 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1909 if (pCurItem)
1910 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1911 else
1912 wLastChar = ' ';
1914 nEnd--;
1915 if (nEnd < 0)
1917 item = ME_FindItemBack(item, diRun);
1918 para = ME_GetParagraph(item);
1919 nEnd = ME_StrLen(item->member.run.strText);
1923 TRACE("not found\n");
1924 if (chrgText)
1925 chrgText->cpMin = chrgText->cpMax = -1;
1926 return -1;
1929 /* helper to send a msg filter notification */
1930 static BOOL
1931 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1933 MSGFILTER msgf;
1935 msgf.nmhdr.hwndFrom = editor->hWnd;
1936 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1937 msgf.nmhdr.code = EN_MSGFILTER;
1938 msgf.msg = msg;
1940 msgf.wParam = *wParam;
1941 msgf.lParam = *lParam;
1942 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1943 return FALSE;
1944 *wParam = msgf.wParam;
1945 *lParam = msgf.lParam;
1946 msgf.wParam = *wParam;
1948 return TRUE;
1951 static BOOL
1952 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1954 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1955 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1957 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1958 editor->nSelectionType = stPosition;
1960 switch (nKey)
1962 case VK_LEFT:
1963 case VK_RIGHT:
1964 case VK_HOME:
1965 case VK_END:
1966 editor->nUDArrowX = -1;
1967 /* fall through */
1968 case VK_UP:
1969 case VK_DOWN:
1970 case VK_PRIOR:
1971 case VK_NEXT:
1972 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1973 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1974 return TRUE;
1975 case VK_BACK:
1976 case VK_DELETE:
1977 editor->nUDArrowX = -1;
1978 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1979 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1980 return FALSE;
1981 if (ME_IsSelection(editor))
1983 ME_DeleteSelection(editor);
1984 ME_CommitUndo(editor);
1986 else if (nKey == VK_DELETE)
1988 /* Delete stops group typing.
1989 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1990 ME_DeleteTextAtCursor(editor, 1, 1);
1991 ME_CommitUndo(editor);
1993 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1995 BOOL bDeletionSucceeded;
1996 /* Backspace can be grouped for a single undo */
1997 ME_ContinueCoalescingTransaction(editor);
1998 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
1999 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2000 /* Deletion was prevented so the cursor is moved back to where it was.
2001 * (e.g. this happens when trying to delete cell boundaries)
2003 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2005 ME_CommitCoalescingUndo(editor);
2007 else
2008 return TRUE;
2009 ME_UpdateSelectionLinkAttribute(editor);
2010 ME_UpdateRepaint(editor);
2011 ME_SendRequestResize(editor, FALSE);
2012 return TRUE;
2014 default:
2015 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2016 editor->nUDArrowX = -1;
2017 if (ctrl_is_down)
2019 if (nKey == 'W')
2021 CHARFORMAT2W chf;
2022 char buf[2048];
2023 chf.cbSize = sizeof(chf);
2025 ME_GetSelectionCharFormat(editor, &chf);
2026 ME_DumpStyleToBuf(&chf, buf);
2027 MessageBoxA(NULL, buf, "Style dump", MB_OK);
2029 if (nKey == 'Q')
2031 ME_CheckCharOffsets(editor);
2035 return FALSE;
2038 /* Process the message and calculate the new click count.
2040 * returns: The click count if it is mouse down event, else returns 0. */
2041 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
2042 LPARAM lParam)
2044 static int clickNum = 0;
2045 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2046 return 0;
2048 if ((msg == WM_LBUTTONDBLCLK) ||
2049 (msg == WM_RBUTTONDBLCLK) ||
2050 (msg == WM_MBUTTONDBLCLK) ||
2051 (msg == WM_XBUTTONDBLCLK))
2053 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2056 if ((msg == WM_LBUTTONDOWN) ||
2057 (msg == WM_RBUTTONDOWN) ||
2058 (msg == WM_MBUTTONDOWN) ||
2059 (msg == WM_XBUTTONDOWN))
2061 static MSG prevClickMsg;
2062 MSG clickMsg;
2063 clickMsg.hwnd = hWnd;
2064 clickMsg.message = msg;
2065 clickMsg.wParam = wParam;
2066 clickMsg.lParam = lParam;
2067 clickMsg.time = GetMessageTime();
2068 clickMsg.pt.x = (short)LOWORD(lParam);
2069 clickMsg.pt.y = (short)HIWORD(lParam);
2070 if ((clickNum != 0) &&
2071 (clickMsg.message == prevClickMsg.message) &&
2072 (clickMsg.hwnd == prevClickMsg.hwnd) &&
2073 (clickMsg.wParam == prevClickMsg.wParam) &&
2074 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2075 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2076 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2078 clickNum++;
2079 } else {
2080 clickNum = 1;
2082 prevClickMsg = clickMsg;
2083 } else {
2084 return 0;
2086 return clickNum;
2089 static BOOL ME_SetCursor(ME_TextEditor *editor)
2091 POINT pt;
2092 BOOL isExact;
2093 int offset;
2094 DWORD messagePos = GetMessagePos();
2095 pt.x = (short)LOWORD(messagePos);
2096 pt.y = (short)HIWORD(messagePos);
2097 ScreenToClient(editor->hWnd, &pt);
2098 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
2099 (pt.x < editor->selofs ||
2100 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
2102 SetCursor(hLeft);
2103 return TRUE;
2105 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
2106 if (isExact)
2108 if (editor->AutoURLDetect_bEnable)
2110 ME_Cursor cursor;
2111 ME_Run *run;
2112 ME_CursorFromCharOfs(editor, offset, &cursor);
2113 run = &cursor.pRun->member.run;
2114 if (editor->AutoURLDetect_bEnable &&
2115 run->style->fmt.dwMask & CFM_LINK &&
2116 run->style->fmt.dwEffects & CFE_LINK)
2118 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
2119 return TRUE;
2122 if (ME_IsSelection(editor))
2124 int selStart, selEnd;
2125 ME_GetSelection(editor, &selStart, &selEnd);
2126 if (selStart <= offset && selEnd >= offset) {
2127 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2128 return TRUE;
2132 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
2133 return TRUE;
2136 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2138 CHARRANGE selrange;
2139 HMENU menu;
2140 int seltype = 0;
2141 if(!editor->lpOleCallback)
2142 return FALSE;
2143 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2144 if(selrange.cpMin == selrange.cpMax)
2145 seltype |= SEL_EMPTY;
2146 else
2148 /* FIXME: Handle objects */
2149 seltype |= SEL_TEXT;
2150 if(selrange.cpMax-selrange.cpMin > 1)
2151 seltype |= SEL_MULTICHAR;
2153 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2155 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2156 DestroyMenu(menu);
2158 return TRUE;
2161 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
2162 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2163 int i;
2164 ed->hWnd = hWnd;
2165 ed->bEmulateVersion10 = FALSE;
2166 ed->pBuffer = ME_MakeText();
2167 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2168 ME_MakeFirstParagraph(ed);
2169 /* The four cursors are for:
2170 * 0 - The position where the caret is shown
2171 * 1 - The anchored end of the selection (for normal selection)
2172 * 2 & 3 - The anchored start and end respectively for word, line,
2173 * or paragraph selection.
2175 ed->nCursors = 4;
2176 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2177 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2178 ed->pCursors[0].nOffset = 0;
2179 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2180 ed->pCursors[1].nOffset = 0;
2181 ed->pCursors[2] = ed->pCursors[0];
2182 ed->pCursors[3] = ed->pCursors[1];
2183 ed->nLastTotalLength = ed->nTotalLength = 0;
2184 ed->nHeight = 0;
2185 ed->nUDArrowX = -1;
2186 ed->nSequence = 0;
2187 ed->rgbBackColor = -1;
2188 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2189 ed->bCaretAtEnd = FALSE;
2190 ed->nEventMask = 0;
2191 ed->nModifyStep = 0;
2192 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2193 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2194 ed->nUndoStackSize = 0;
2195 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2196 ed->nUndoMode = umAddToUndo;
2197 ed->nParagraphs = 1;
2198 ed->nLastSelStart = ed->nLastSelEnd = 0;
2199 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2200 ed->bRedraw = TRUE;
2201 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
2202 ed->bHideSelection = FALSE;
2203 ed->nInvalidOfs = -1;
2204 ed->pfnWordBreak = NULL;
2205 ed->lpOleCallback = NULL;
2206 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2207 ed->AutoURLDetect_bEnable = FALSE;
2208 ed->bHaveFocus = FALSE;
2209 for (i=0; i<HFONT_CACHE_SIZE; i++)
2211 ed->pFontCache[i].nRefs = 0;
2212 ed->pFontCache[i].nAge = 0;
2213 ed->pFontCache[i].hFont = NULL;
2216 ME_CheckCharOffsets(ed);
2217 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
2218 ed->selofs = SELECTIONBAR_WIDTH;
2219 else
2220 ed->selofs = 0;
2221 ed->nSelectionType = stPosition;
2223 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
2224 ed->cPasswordMask = '*';
2225 else
2226 ed->cPasswordMask = 0;
2228 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2230 /* Default vertical scrollbar information */
2231 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2232 ed->vert_si.nMin = 0;
2233 ed->vert_si.nMax = 0;
2234 ed->vert_si.nPage = 0;
2235 ed->vert_si.nPos = 0;
2237 OleInitialize(NULL);
2239 return ed;
2242 typedef struct tagME_GlobalDestStruct
2244 HGLOBAL hData;
2245 int nLength;
2246 } ME_GlobalDestStruct;
2248 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2250 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2251 int i;
2252 WORD *pSrc, *pDest;
2254 cb = cb >> 1;
2255 pDest = (WORD *)lpBuff;
2256 pSrc = (WORD *)GlobalLock(pData->hData);
2257 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2258 pDest[i] = pSrc[pData->nLength+i];
2260 pData->nLength += i;
2261 *pcb = 2*i;
2262 GlobalUnlock(pData->hData);
2263 return 0;
2266 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2268 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2269 int i;
2270 BYTE *pSrc, *pDest;
2272 pDest = lpBuff;
2273 pSrc = (BYTE *)GlobalLock(pData->hData);
2274 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2275 pDest[i] = pSrc[pData->nLength+i];
2277 pData->nLength += i;
2278 *pcb = i;
2279 GlobalUnlock(pData->hData);
2280 return 0;
2284 void ME_DestroyEditor(ME_TextEditor *editor)
2286 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2287 ME_DisplayItem *p = pFirst, *pNext = NULL;
2288 int i;
2290 ME_ClearTempStyle(editor);
2291 ME_EmptyUndoStack(editor);
2292 while(p) {
2293 pNext = p->next;
2294 ME_DestroyDisplayItem(p);
2295 p = pNext;
2297 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2298 for (i=0; i<HFONT_CACHE_SIZE; i++)
2300 if (editor->pFontCache[i].hFont)
2301 DeleteObject(editor->pFontCache[i].hFont);
2303 if (editor->rgbBackColor != -1)
2304 DeleteObject(editor->hbrBackground);
2305 if(editor->lpOleCallback)
2306 IUnknown_Release(editor->lpOleCallback);
2307 OleUninitialize();
2309 FREE_OBJ(editor->pBuffer);
2310 FREE_OBJ(editor->pCursors);
2312 FREE_OBJ(editor);
2315 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2317 TRACE("\n");
2318 switch (fdwReason)
2320 case DLL_PROCESS_ATTACH:
2321 DisableThreadLibraryCalls(hinstDLL);
2322 me_heap = HeapCreate (0, 0x10000, 0);
2323 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2324 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2325 LookupInit();
2326 break;
2328 case DLL_PROCESS_DETACH:
2329 UnregisterClassW(RichEdit20W, 0);
2330 UnregisterClassW(RichEdit50W, 0);
2331 UnregisterClassA("RichEdit20A", 0);
2332 UnregisterClassA("RichEdit50A", 0);
2333 if (ME_ListBoxRegistered)
2334 UnregisterClassW(REListBox20W, 0);
2335 if (ME_ComboBoxRegistered)
2336 UnregisterClassW(REComboBox20W, 0);
2337 LookupCleanup();
2338 HeapDestroy (me_heap);
2339 me_heap = NULL;
2340 break;
2342 return TRUE;
2346 #define UNSUPPORTED_MSG(e) \
2347 case e: \
2348 FIXME(#e ": stub\n"); \
2349 return DefWindowProcW(hWnd, msg, wParam, lParam);
2351 static const char * const edit_messages[] = {
2352 "EM_GETSEL",
2353 "EM_SETSEL",
2354 "EM_GETRECT",
2355 "EM_SETRECT",
2356 "EM_SETRECTNP",
2357 "EM_SCROLL",
2358 "EM_LINESCROLL",
2359 "EM_SCROLLCARET",
2360 "EM_GETMODIFY",
2361 "EM_SETMODIFY",
2362 "EM_GETLINECOUNT",
2363 "EM_LINEINDEX",
2364 "EM_SETHANDLE",
2365 "EM_GETHANDLE",
2366 "EM_GETTHUMB",
2367 "EM_UNKNOWN_BF",
2368 "EM_UNKNOWN_C0",
2369 "EM_LINELENGTH",
2370 "EM_REPLACESEL",
2371 "EM_UNKNOWN_C3",
2372 "EM_GETLINE",
2373 "EM_LIMITTEXT",
2374 "EM_CANUNDO",
2375 "EM_UNDO",
2376 "EM_FMTLINES",
2377 "EM_LINEFROMCHAR",
2378 "EM_UNKNOWN_CA",
2379 "EM_SETTABSTOPS",
2380 "EM_SETPASSWORDCHAR",
2381 "EM_EMPTYUNDOBUFFER",
2382 "EM_GETFIRSTVISIBLELINE",
2383 "EM_SETREADONLY",
2384 "EM_SETWORDBREAKPROC",
2385 "EM_GETWORDBREAKPROC",
2386 "EM_GETPASSWORDCHAR",
2387 "EM_SETMARGINS",
2388 "EM_GETMARGINS",
2389 "EM_GETLIMITTEXT",
2390 "EM_POSFROMCHAR",
2391 "EM_CHARFROMPOS"
2394 static const char * const richedit_messages[] = {
2395 "EM_CANPASTE",
2396 "EM_DISPLAYBAND",
2397 "EM_EXGETSEL",
2398 "EM_EXLIMITTEXT",
2399 "EM_EXLINEFROMCHAR",
2400 "EM_EXSETSEL",
2401 "EM_FINDTEXT",
2402 "EM_FORMATRANGE",
2403 "EM_GETCHARFORMAT",
2404 "EM_GETEVENTMASK",
2405 "EM_GETOLEINTERFACE",
2406 "EM_GETPARAFORMAT",
2407 "EM_GETSELTEXT",
2408 "EM_HIDESELECTION",
2409 "EM_PASTESPECIAL",
2410 "EM_REQUESTRESIZE",
2411 "EM_SELECTIONTYPE",
2412 "EM_SETBKGNDCOLOR",
2413 "EM_SETCHARFORMAT",
2414 "EM_SETEVENTMASK",
2415 "EM_SETOLECALLBACK",
2416 "EM_SETPARAFORMAT",
2417 "EM_SETTARGETDEVICE",
2418 "EM_STREAMIN",
2419 "EM_STREAMOUT",
2420 "EM_GETTEXTRANGE",
2421 "EM_FINDWORDBREAK",
2422 "EM_SETOPTIONS",
2423 "EM_GETOPTIONS",
2424 "EM_FINDTEXTEX",
2425 "EM_GETWORDBREAKPROCEX",
2426 "EM_SETWORDBREAKPROCEX",
2427 "EM_SETUNDOLIMIT",
2428 "EM_UNKNOWN_USER_83",
2429 "EM_REDO",
2430 "EM_CANREDO",
2431 "EM_GETUNDONAME",
2432 "EM_GETREDONAME",
2433 "EM_STOPGROUPTYPING",
2434 "EM_SETTEXTMODE",
2435 "EM_GETTEXTMODE",
2436 "EM_AUTOURLDETECT",
2437 "EM_GETAUTOURLDETECT",
2438 "EM_SETPALETTE",
2439 "EM_GETTEXTEX",
2440 "EM_GETTEXTLENGTHEX",
2441 "EM_SHOWSCROLLBAR",
2442 "EM_SETTEXTEX",
2443 "EM_UNKNOWN_USER_98",
2444 "EM_UNKNOWN_USER_99",
2445 "EM_SETPUNCTUATION",
2446 "EM_GETPUNCTUATION",
2447 "EM_SETWORDWRAPMODE",
2448 "EM_GETWORDWRAPMODE",
2449 "EM_SETIMECOLOR",
2450 "EM_GETIMECOLOR",
2451 "EM_SETIMEOPTIONS",
2452 "EM_GETIMEOPTIONS",
2453 "EM_CONVPOSITION",
2454 "EM_UNKNOWN_USER_109",
2455 "EM_UNKNOWN_USER_110",
2456 "EM_UNKNOWN_USER_111",
2457 "EM_UNKNOWN_USER_112",
2458 "EM_UNKNOWN_USER_113",
2459 "EM_UNKNOWN_USER_114",
2460 "EM_UNKNOWN_USER_115",
2461 "EM_UNKNOWN_USER_116",
2462 "EM_UNKNOWN_USER_117",
2463 "EM_UNKNOWN_USER_118",
2464 "EM_UNKNOWN_USER_119",
2465 "EM_SETLANGOPTIONS",
2466 "EM_GETLANGOPTIONS",
2467 "EM_GETIMECOMPMODE",
2468 "EM_FINDTEXTW",
2469 "EM_FINDTEXTEXW",
2470 "EM_RECONVERSION",
2471 "EM_SETIMEMODEBIAS",
2472 "EM_GETIMEMODEBIAS"
2475 static const char *
2476 get_msg_name(UINT msg)
2478 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2479 return edit_messages[msg - EM_GETSEL];
2480 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2481 return richedit_messages[msg - EM_CANPASTE];
2482 return "";
2485 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2486 LPARAM lParam, BOOL unicode)
2488 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2490 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2491 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2493 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2494 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2495 return 0;
2498 switch(msg) {
2500 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2501 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2502 UNSUPPORTED_MSG(EM_FMTLINES)
2503 UNSUPPORTED_MSG(EM_FORMATRANGE)
2504 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2505 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2506 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2507 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2508 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2509 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2510 UNSUPPORTED_MSG(EM_GETREDONAME)
2511 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2512 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2513 UNSUPPORTED_MSG(EM_GETUNDONAME)
2514 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2515 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2516 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2517 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2518 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2519 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2520 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2521 UNSUPPORTED_MSG(EM_SETPALETTE)
2522 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2523 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2524 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2525 UNSUPPORTED_MSG(WM_STYLECHANGING)
2526 UNSUPPORTED_MSG(WM_STYLECHANGED)
2528 /* Messages specific to Richedit controls */
2530 case EM_STREAMIN:
2531 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2532 case EM_STREAMOUT:
2533 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2534 case WM_GETDLGCODE:
2536 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2537 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2539 int vk = (int)((LPMSG)lParam)->wParam;
2540 /* if style says we want return key */
2541 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2543 code |= DLGC_WANTMESSAGE;
2545 /* we always handle ctrl-tab */
2546 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2548 code |= DLGC_WANTMESSAGE;
2551 return code;
2553 case WM_NCCREATE:
2555 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2556 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2557 editor = ME_MakeEditor(hWnd);
2558 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2559 return TRUE;
2561 case EM_EMPTYUNDOBUFFER:
2562 ME_EmptyUndoStack(editor);
2563 return 0;
2564 case EM_GETSEL:
2566 /* Note: wParam/lParam can be NULL */
2567 UINT from, to;
2568 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2569 PUINT pto = lParam ? (PUINT)lParam : &to;
2570 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2571 if ((*pfrom|*pto) & 0xFFFF0000)
2572 return -1;
2573 return MAKELONG(*pfrom,*pto);
2575 case EM_EXGETSEL:
2577 CHARRANGE *pRange = (CHARRANGE *)lParam;
2578 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2579 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2580 return 0;
2582 case EM_SETUNDOLIMIT:
2584 if ((int)wParam < 0)
2585 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2586 else
2587 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2588 /* Setting a max stack size keeps wine from getting killed
2589 for hogging memory. Windows allocates all this memory at once, so
2590 no program would realistically set a value above our maximum. */
2591 return editor->nUndoLimit;
2593 case EM_CANUNDO:
2594 return editor->pUndoStack != NULL;
2595 case EM_CANREDO:
2596 return editor->pRedoStack != NULL;
2597 case WM_UNDO: /* FIXME: actually not the same */
2598 case EM_UNDO:
2599 return ME_Undo(editor);
2600 case EM_REDO:
2601 return ME_Redo(editor);
2602 case EM_GETOPTIONS:
2604 /* these flags are equivalent to the ES_* counterparts */
2605 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2606 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2607 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2609 return settings;
2611 case EM_SETOPTIONS:
2613 /* these flags are equivalent to ES_* counterparts
2614 * ECO_READONLY is already implemented in the code, only requires
2615 * setting the bit to work
2617 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2618 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2619 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2620 DWORD settings = mask & raw;
2622 switch(wParam)
2624 case ECOOP_SET:
2625 settings = lParam;
2626 break;
2627 case ECOOP_OR:
2628 settings |= lParam;
2629 break;
2630 case ECOOP_AND:
2631 settings &= lParam;
2632 break;
2633 case ECOOP_XOR:
2634 settings ^= lParam;
2636 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2638 if (settings & ECO_AUTOWORDSELECTION)
2639 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2640 if (settings & ECO_SELECTIONBAR)
2641 editor->selofs = SELECTIONBAR_WIDTH;
2642 else
2643 editor->selofs = 0;
2644 ME_WrapMarkedParagraphs(editor);
2646 if (settings & ECO_VERTICAL)
2647 FIXME("ECO_VERTICAL not implemented yet!\n");
2648 if (settings & ECO_AUTOHSCROLL)
2649 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2650 if (settings & ECO_AUTOVSCROLL)
2651 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2652 if (settings & ECO_NOHIDESEL)
2653 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2654 if (settings & ECO_WANTRETURN)
2655 FIXME("ECO_WANTRETURN not implemented yet!\n");
2657 return settings;
2659 case EM_SETSEL:
2661 ME_InvalidateSelection(editor);
2662 ME_SetSelection(editor, wParam, lParam);
2663 ME_InvalidateSelection(editor);
2664 HideCaret(editor->hWnd);
2665 ME_ShowCaret(editor);
2666 ME_SendSelChange(editor);
2667 return 0;
2669 case EM_SETSCROLLPOS:
2671 POINT *point = (POINT *)lParam;
2672 ME_ScrollAbs(editor, point->y);
2673 return 0;
2675 case EM_AUTOURLDETECT:
2677 if (wParam==1 || wParam ==0)
2679 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2680 return 0;
2682 return E_INVALIDARG;
2684 case EM_GETAUTOURLDETECT:
2686 return editor->AutoURLDetect_bEnable;
2688 case EM_EXSETSEL:
2690 int end;
2691 CHARRANGE range = *(CHARRANGE *)lParam;
2693 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2695 ME_InvalidateSelection(editor);
2696 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2697 ME_InvalidateSelection(editor);
2698 HideCaret(editor->hWnd);
2699 ME_ShowCaret(editor);
2700 ME_SendSelChange(editor);
2702 return end;
2704 case EM_SHOWSCROLLBAR:
2706 ShowScrollBar(editor->hWnd, wParam, lParam);
2707 return 0;
2709 case EM_SETTEXTEX:
2711 LPWSTR wszText;
2712 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2713 size_t len;
2714 int from, to;
2715 ME_Style *style;
2716 int oldModify = editor->nModifyStep;
2718 if (!pStruct) return 0;
2720 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2721 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2722 pStruct->flags, pStruct->codepage);
2724 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2725 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2726 len = wszText ? lstrlenW(wszText) : 0;
2728 if (pStruct->flags & ST_SELECTION) {
2729 ME_GetSelection(editor, &from, &to);
2730 style = ME_GetSelectionInsertStyle(editor);
2731 ME_InternalDeleteText(editor, from, to - from, FALSE);
2732 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2733 ME_StreamInRTFString(editor, 1, (char *)lParam);
2734 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2735 ME_ReleaseStyle(style);
2737 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2739 else {
2740 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2741 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2742 ME_StreamInRTFString(editor, 0, (char *)lParam);
2743 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2744 len = 1;
2746 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2748 ME_CommitUndo(editor);
2749 if (!(pStruct->flags & ST_KEEPUNDO))
2751 editor->nModifyStep = oldModify;
2752 ME_EmptyUndoStack(editor);
2754 ME_UpdateRepaint(editor);
2755 return len;
2757 case EM_SETBKGNDCOLOR:
2759 LRESULT lColor;
2760 if (editor->rgbBackColor != -1) {
2761 DeleteObject(editor->hbrBackground);
2762 lColor = editor->rgbBackColor;
2764 else lColor = GetSysColor(COLOR_WINDOW);
2766 if (wParam)
2768 editor->rgbBackColor = -1;
2769 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2771 else
2773 editor->rgbBackColor = lParam;
2774 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2776 if (editor->bRedraw)
2778 InvalidateRect(hWnd, NULL, TRUE);
2779 UpdateWindow(hWnd);
2781 return lColor;
2783 case EM_GETMODIFY:
2784 return editor->nModifyStep == 0 ? 0 : -1;
2785 case EM_SETMODIFY:
2787 if (wParam)
2788 editor->nModifyStep = 1;
2789 else
2790 editor->nModifyStep = 0;
2792 return 0;
2794 case EM_SETREADONLY:
2796 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2797 if (wParam)
2798 nStyle |= ES_READONLY;
2799 else
2800 nStyle &= ~ES_READONLY;
2801 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2802 return 0;
2804 case EM_SETEVENTMASK:
2806 DWORD nOldMask = editor->nEventMask;
2808 editor->nEventMask = lParam;
2809 return nOldMask;
2811 case EM_GETEVENTMASK:
2812 return editor->nEventMask;
2813 case EM_SETCHARFORMAT:
2815 CHARFORMAT2W buf, *p;
2816 BOOL bRepaint = TRUE;
2817 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2818 if (p == NULL) return 0;
2819 if (!wParam)
2820 ME_SetDefaultCharFormat(editor, p);
2821 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2822 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2823 return 0;
2824 } else if (wParam == SCF_ALL) {
2825 if (editor->mode & TM_PLAINTEXT)
2826 ME_SetDefaultCharFormat(editor, p);
2827 else {
2828 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2829 editor->nModifyStep = 1;
2831 } else if (editor->mode & TM_PLAINTEXT) {
2832 return 0;
2833 } else {
2834 int from, to;
2835 ME_GetSelection(editor, &from, &to);
2836 bRepaint = (from != to);
2837 ME_SetSelectionCharFormat(editor, p);
2838 if (from != to) editor->nModifyStep = 1;
2840 ME_CommitUndo(editor);
2841 if (bRepaint)
2842 ME_RewrapRepaint(editor);
2843 return 1;
2845 case EM_GETCHARFORMAT:
2847 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2848 if (dst->cbSize != sizeof(CHARFORMATA) &&
2849 dst->cbSize != sizeof(CHARFORMATW) &&
2850 dst->cbSize != sizeof(CHARFORMAT2A) &&
2851 dst->cbSize != sizeof(CHARFORMAT2W))
2852 return 0;
2853 tmp.cbSize = sizeof(tmp);
2854 if (!wParam)
2855 ME_GetDefaultCharFormat(editor, &tmp);
2856 else
2857 ME_GetSelectionCharFormat(editor, &tmp);
2858 ME_CopyToCFAny(dst, &tmp);
2859 return tmp.dwMask;
2861 case EM_SETPARAFORMAT:
2863 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2864 ME_RewrapRepaint(editor);
2865 ME_CommitUndo(editor);
2866 return result;
2868 case EM_GETPARAFORMAT:
2869 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2870 return ((PARAFORMAT2 *)lParam)->dwMask;
2871 case EM_GETFIRSTVISIBLELINE:
2873 ME_DisplayItem *p = editor->pBuffer->pFirst;
2874 int y = ME_GetYScrollPos(editor);
2875 int ypara = 0;
2876 int count = 0;
2877 int ystart, yend;
2878 while(p) {
2879 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2880 if (p->type == diTextEnd)
2881 break;
2882 if (p->type == diParagraph) {
2883 ypara = p->member.para.pt.y;
2884 continue;
2886 ystart = ypara + p->member.row.pt.y;
2887 yend = ystart + p->member.row.nHeight;
2888 if (y < yend) {
2889 break;
2891 count++;
2893 return count;
2895 case EM_HIDESELECTION:
2897 editor->bHideSelection = (wParam != 0);
2898 ME_InvalidateSelection(editor);
2899 return 0;
2901 case EM_LINESCROLL:
2903 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2904 return TRUE; /* Should return false if a single line richedit control */
2906 case WM_CLEAR:
2908 int from, to;
2909 ME_GetSelection(editor, &from, &to);
2910 ME_InternalDeleteText(editor, from, to-from, FALSE);
2911 ME_CommitUndo(editor);
2912 ME_UpdateRepaint(editor);
2913 return 0;
2915 case EM_REPLACESEL:
2917 int from, to;
2918 ME_Style *style;
2919 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2920 size_t len = wszText ? lstrlenW(wszText) : 0;
2921 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2923 ME_GetSelection(editor, &from, &to);
2924 style = ME_GetSelectionInsertStyle(editor);
2925 ME_InternalDeleteText(editor, from, to-from, FALSE);
2926 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2927 ME_ReleaseStyle(style);
2928 /* drop temporary style if line end */
2930 * FIXME question: does abc\n mean: put abc,
2931 * clear temp style, put \n? (would require a change)
2933 if (len>0 && wszText[len-1] == '\n')
2934 ME_ClearTempStyle(editor);
2935 ME_EndToUnicode(unicode, wszText);
2936 ME_CommitUndo(editor);
2937 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2938 if (!wParam)
2939 ME_EmptyUndoStack(editor);
2940 ME_UpdateRepaint(editor);
2941 return len;
2943 case EM_SCROLLCARET:
2945 int top, bottom; /* row's edges relative to document top */
2946 int nPos;
2947 ME_DisplayItem *para, *row;
2949 nPos = ME_GetYScrollPos(editor);
2950 row = ME_RowStart(editor->pCursors[0].pRun);
2951 para = ME_GetParagraph(row);
2952 top = para->member.para.pt.y + row->member.row.pt.y;
2953 bottom = top + row->member.row.nHeight;
2955 if (top < nPos) /* caret above window */
2956 ME_ScrollAbs(editor, top);
2957 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2958 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2959 return 0;
2961 case WM_SETFONT:
2963 LOGFONTW lf;
2964 CHARFORMAT2W fmt;
2965 HDC hDC;
2966 BOOL bRepaint = LOWORD(lParam);
2968 if (!wParam)
2969 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2970 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2971 hDC = GetDC(hWnd);
2972 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2973 ReleaseDC(hWnd, hDC);
2974 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2975 ME_SetDefaultCharFormat(editor, &fmt);
2977 ME_CommitUndo(editor);
2978 if (bRepaint)
2979 ME_RewrapRepaint(editor);
2980 return 0;
2982 case WM_SETTEXT:
2984 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2985 if (lParam)
2987 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2988 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2990 /* Undocumented: WM_SETTEXT supports RTF text */
2991 ME_StreamInRTFString(editor, 0, (char *)lParam);
2993 else
2995 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2996 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2997 if (lstrlenW(wszText) > 0)
2999 int len = -1;
3001 /* uses default style! */
3002 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3004 WCHAR * p;
3006 p = wszText;
3007 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3008 len = p - wszText;
3010 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3012 ME_EndToUnicode(unicode, wszText);
3015 else
3016 TRACE("WM_SETTEXT - NULL\n");
3017 if (editor->AutoURLDetect_bEnable)
3019 ME_UpdateLinkAttribute(editor, 0, -1);
3021 ME_SetSelection(editor, 0, 0);
3022 editor->nModifyStep = 0;
3023 ME_CommitUndo(editor);
3024 ME_EmptyUndoStack(editor);
3025 ME_UpdateRepaint(editor);
3026 return 1;
3028 case EM_CANPASTE:
3030 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3031 if (IsClipboardFormatAvailable(nRTFFormat))
3032 return TRUE;
3033 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3034 return TRUE;
3035 return FALSE;
3037 case WM_PASTE:
3039 DWORD dwFormat = 0;
3040 EDITSTREAM es;
3041 ME_GlobalDestStruct gds;
3042 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3043 UINT cf = 0;
3045 if (IsClipboardFormatAvailable(nRTFFormat))
3046 cf = nRTFFormat, dwFormat = SF_RTF;
3047 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3048 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
3049 else
3050 return 0;
3052 if (!OpenClipboard(hWnd))
3053 return 0;
3054 gds.hData = GetClipboardData(cf);
3055 gds.nLength = 0;
3056 es.dwCookie = (DWORD)&gds;
3057 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
3058 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
3060 CloseClipboard();
3061 return 0;
3063 case WM_CUT:
3064 case WM_COPY:
3066 LPDATAOBJECT dataObj = NULL;
3067 CHARRANGE range;
3068 HRESULT hr = S_OK;
3070 if (editor->cPasswordMask)
3071 return 0; /* Copying or Cutting masked text isn't allowed */
3073 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
3074 if(editor->lpOleCallback)
3075 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
3076 if(FAILED(hr) || !dataObj)
3077 hr = ME_GetDataObject(editor, &range, &dataObj);
3078 if(SUCCEEDED(hr)) {
3079 hr = OleSetClipboard(dataObj);
3080 IDataObject_Release(dataObj);
3082 if (SUCCEEDED(hr) && msg == WM_CUT)
3084 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
3085 ME_CommitUndo(editor);
3086 ME_UpdateRepaint(editor);
3088 return 0;
3090 case WM_GETTEXTLENGTH:
3092 GETTEXTLENGTHEX how;
3094 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3095 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3096 how.codepage = unicode ? 1200 : CP_ACP;
3097 return ME_GetTextLengthEx(editor, &how);
3099 case EM_GETTEXTLENGTHEX:
3100 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3101 case WM_GETTEXT:
3103 GETTEXTEX ex;
3104 LRESULT rc;
3105 LPSTR bufferA = NULL;
3106 LPWSTR bufferW = NULL;
3108 if (unicode)
3109 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
3110 else
3111 bufferA = heap_alloc(wParam + 2);
3113 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3114 ex.flags = GT_USECRLF;
3115 ex.codepage = unicode ? 1200 : CP_ACP;
3116 ex.lpDefaultChar = NULL;
3117 ex.lpUsedDefChar = NULL;
3118 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
3120 if (unicode)
3122 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3123 if (lstrlenW(bufferW) >= wParam) rc = 0;
3125 else
3127 memcpy((LPSTR)lParam, bufferA, wParam);
3128 if (strlen(bufferA) >= wParam) rc = 0;
3130 heap_free(bufferA);
3131 heap_free(bufferW);
3132 return rc;
3134 case EM_GETTEXTEX:
3136 GETTEXTEX *ex = (GETTEXTEX*)wParam;
3137 int nStart, nCount; /* in chars */
3139 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
3140 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
3142 if (ex->flags & GT_SELECTION)
3144 ME_GetSelection(editor, &nStart, &nCount);
3145 nCount -= nStart;
3147 else
3149 nStart = 0;
3150 nCount = 0x7fffffff;
3152 if (ex->codepage == 1200)
3154 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
3155 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
3157 else
3159 /* potentially each char may be a CR, why calculate the exact value with O(N) when
3160 we can just take a bigger buffer? :)
3161 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
3162 occurs only in richedit 2.0 mode, in which line breaks have only one CR
3164 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
3165 LPWSTR buffer;
3166 DWORD buflen = ex->cb;
3167 LRESULT rc;
3168 DWORD flags = 0;
3170 nCount = min(nCount, ex->cb - 1);
3171 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
3173 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
3174 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
3175 if (rc) rc--; /* do not count 0 terminator */
3177 heap_free(buffer);
3178 return rc;
3181 case EM_GETSELTEXT:
3183 int from, to;
3184 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3185 ME_GetSelection(editor, &from, &to);
3186 tr.chrg.cpMin = from;
3187 tr.chrg.cpMax = to;
3188 tr.lpstrText = (WCHAR *)lParam;
3189 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
3191 case EM_GETSCROLLPOS:
3193 POINT *point = (POINT *)lParam;
3194 point->x = 0; /* FIXME side scrolling not implemented */
3195 point->y = ME_GetYScrollPos(editor);
3196 return 1;
3198 case EM_GETTEXTRANGE:
3200 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3201 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3202 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3203 editor->bEmulateVersion10, ME_GetTextLength(editor));
3204 if (unicode)
3205 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
3206 else
3208 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
3209 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
3210 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
3211 /* FIXME this is a potential security hole (buffer overrun)
3212 if you know more about wchar->mbyte conversion please explain
3214 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
3215 FREE_OBJ(p);
3216 return nChars;
3219 case EM_GETLINE:
3221 ME_DisplayItem *run;
3222 const unsigned int nMaxChars = *(WORD *) lParam;
3223 unsigned int nCharsLeft = nMaxChars;
3224 char *dest = (char *) lParam;
3225 BOOL wroteNull = FALSE;
3227 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3228 unicode ? "Unicode" : "Ansi");
3230 run = ME_FindRowWithNumber(editor, wParam);
3231 if (run == NULL)
3232 return 0;
3234 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3235 && !(run->member.run.nFlags & MERF_ENDPARA))
3237 unsigned int nCopy;
3238 ME_String *strText;
3239 if (run->type != diRun)
3240 break;
3241 strText = run->member.run.strText;
3242 nCopy = min(nCharsLeft, strText->nLen);
3244 if (unicode)
3245 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
3246 else
3247 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3248 nCharsLeft, NULL, NULL);
3249 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3250 nCharsLeft -= nCopy;
3253 /* append line termination, space allowing */
3254 if (nCharsLeft > 0)
3256 if (run && (run->member.run.nFlags & MERF_ENDPARA))
3258 unsigned int i;
3259 /* Write as many \r as encoded in end-of-paragraph, space allowing */
3260 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3262 *((WCHAR *)dest) = '\r';
3263 dest += unicode ? sizeof(WCHAR) : 1;
3265 /* Write as many \n as encoded in end-of-paragraph, space allowing */
3266 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3268 *((WCHAR *)dest) = '\n';
3269 dest += unicode ? sizeof(WCHAR) : 1;
3272 if (nCharsLeft > 0)
3274 if (unicode)
3275 *((WCHAR *)dest) = '\0';
3276 else
3277 *dest = '\0';
3278 nCharsLeft--;
3279 wroteNull = TRUE;
3283 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3284 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3286 case EM_GETLINECOUNT:
3288 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3289 int nRows = 0;
3291 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3293 while (item != editor->pBuffer->pLast)
3295 assert(item->type == diParagraph);
3296 prev_para = ME_FindItemBack(item, diRun);
3297 if (prev_para) {
3298 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3300 nRows += item->member.para.nRows;
3301 item = item->member.para.next_para;
3303 last_para = ME_FindItemBack(item, diRun);
3304 assert(last_para);
3305 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3306 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3307 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3309 /* In 1.0 emulation, the last solitary \r at the very end of the text
3310 (if one exists) is NOT a line break.
3311 FIXME: this is an ugly hack. This should have a more regular model. */
3312 nRows--;
3315 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3316 return max(1, nRows);
3318 case EM_LINEFROMCHAR:
3320 if (wParam == -1)
3321 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3322 else
3323 return ME_RowNumberFromCharOfs(editor, wParam);
3325 case EM_EXLINEFROMCHAR:
3327 if (lParam == -1)
3328 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3329 else
3330 return ME_RowNumberFromCharOfs(editor, lParam);
3332 case EM_LINEINDEX:
3334 ME_DisplayItem *item, *para;
3335 int nCharOfs;
3337 if (wParam == -1)
3338 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3339 else
3340 item = ME_FindRowWithNumber(editor, wParam);
3341 if (!item)
3342 return -1;
3343 para = ME_GetParagraph(item);
3344 item = ME_FindItemFwd(item, diRun);
3345 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3346 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3347 return nCharOfs;
3349 case EM_LINELENGTH:
3351 ME_DisplayItem *item, *item_end;
3352 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3354 if (wParam > ME_GetTextLength(editor))
3355 return 0;
3356 if (wParam == -1)
3358 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3359 return 0;
3361 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3362 item = ME_RowStart(item);
3363 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3364 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3365 if (item_end->type == diStartRow)
3366 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3367 else
3369 ME_DisplayItem *endPara;
3371 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3372 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3373 endPara = ME_FindItemBack(endPara, diRun);
3374 assert(endPara);
3375 assert(endPara->type == diRun);
3376 assert(endPara->member.run.nFlags & MERF_ENDPARA);
3377 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3379 nChars = nNextLineOfs - nThisLineOfs;
3380 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3381 return nChars;
3383 case EM_EXLIMITTEXT:
3385 if ((int)lParam < 0)
3386 return 0;
3387 if (lParam == 0)
3388 editor->nTextLimit = 65536;
3389 else
3390 editor->nTextLimit = (int) lParam;
3391 return 0;
3393 case EM_LIMITTEXT:
3395 if (wParam == 0)
3396 editor->nTextLimit = 65536;
3397 else
3398 editor->nTextLimit = (int) wParam;
3399 return 0;
3401 case EM_GETLIMITTEXT:
3403 return editor->nTextLimit;
3405 case EM_FINDTEXT:
3407 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3408 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3409 WCHAR *tmp;
3410 LRESULT r;
3412 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3413 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3414 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3415 FREE_OBJ( tmp );
3416 return r;
3418 case EM_FINDTEXTEX:
3420 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3421 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3422 WCHAR *tmp;
3423 LRESULT r;
3425 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3426 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3427 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3428 FREE_OBJ( tmp );
3429 return r;
3431 case EM_FINDTEXTW:
3433 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3434 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3436 case EM_FINDTEXTEXW:
3438 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3439 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3441 case EM_GETZOOM:
3442 if (!wParam || !lParam)
3443 return FALSE;
3444 *(int *)wParam = editor->nZoomNumerator;
3445 *(int *)lParam = editor->nZoomDenominator;
3446 return TRUE;
3447 case EM_SETZOOM:
3448 return ME_SetZoom(editor, wParam, lParam);
3449 case EM_CHARFROMPOS:
3450 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3451 case EM_POSFROMCHAR:
3453 ME_DisplayItem *pRun;
3454 int nCharOfs, nOffset, nLength;
3455 POINTL pt = {0,0};
3456 SCROLLINFO si;
3458 nCharOfs = wParam;
3459 /* detect which API version we're dealing with */
3460 if (wParam >= 0x40000)
3461 nCharOfs = lParam;
3462 nLength = ME_GetTextLength(editor);
3464 if (nCharOfs < nLength) {
3465 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3466 assert(pRun->type == diRun);
3467 pt.y = pRun->member.run.pt.y;
3468 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3469 pt.y += ME_GetParagraph(pRun)->member.para.pt.y;
3470 } else {
3471 pt.x = 0;
3472 pt.y = editor->pBuffer->pLast->member.para.pt.y;
3474 pt.x += editor->selofs;
3476 si.cbSize = sizeof(si);
3477 si.fMask = SIF_POS;
3478 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3479 si.cbSize = sizeof(si);
3480 si.fMask = SIF_POS;
3481 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3483 if (wParam >= 0x40000) {
3484 *(POINTL *)wParam = pt;
3486 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3488 case WM_CREATE:
3490 SCROLLINFO si;
3492 GetClientRect(hWnd, &editor->rcFormat);
3493 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3494 { /* Squelch the default horizontal scrollbar it would make */
3495 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3498 si.cbSize = sizeof(si);
3499 si.fMask = SIF_PAGE | SIF_RANGE;
3500 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3501 si.fMask |= SIF_DISABLENOSCROLL;
3502 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3503 si.nMin = 0;
3504 si.nPage = 0;
3505 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3507 ME_CommitUndo(editor);
3508 ME_WrapMarkedParagraphs(editor);
3509 ME_MoveCaret(editor);
3510 return 0;
3512 case WM_DESTROY:
3513 ME_DestroyEditor(editor);
3514 SetWindowLongPtrW(hWnd, 0, 0);
3515 return 0;
3516 case WM_SETCURSOR:
3518 return ME_SetCursor(editor);
3520 case WM_LBUTTONDBLCLK:
3521 case WM_LBUTTONDOWN:
3523 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3524 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3525 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3526 return 0;
3527 SetFocus(hWnd);
3528 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3529 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3530 SetCapture(hWnd);
3531 ME_LinkNotify(editor,msg,wParam,lParam);
3532 if (!ME_SetCursor(editor)) goto do_default;
3533 break;
3535 case WM_MOUSEMOVE:
3536 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3537 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3538 return 0;
3539 if (GetCapture() == hWnd)
3540 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3541 ME_LinkNotify(editor,msg,wParam,lParam);
3542 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3543 if (GetCapture() == hWnd)
3544 ME_SetCursor(editor);
3545 break;
3546 case WM_LBUTTONUP:
3547 if (GetCapture() == hWnd)
3548 ReleaseCapture();
3549 if (editor->nSelectionType == stDocument)
3550 editor->nSelectionType = stPosition;
3551 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3552 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3553 return 0;
3554 else
3556 ME_SetCursor(editor);
3557 ME_LinkNotify(editor,msg,wParam,lParam);
3559 break;
3560 case WM_RBUTTONUP:
3561 case WM_RBUTTONDOWN:
3562 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3563 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3564 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3565 return 0;
3566 goto do_default;
3567 case WM_CONTEXTMENU:
3568 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3569 goto do_default;
3570 break;
3571 case WM_PAINT:
3572 if (editor->bRedraw)
3574 HDC hDC;
3575 PAINTSTRUCT ps;
3577 hDC = BeginPaint(hWnd, &ps);
3578 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3579 EndPaint(hWnd, &ps);
3581 break;
3582 case WM_SETFOCUS:
3583 editor->bHaveFocus = TRUE;
3584 ME_ShowCaret(editor);
3585 ME_SendOldNotify(editor, EN_SETFOCUS);
3586 return 0;
3587 case WM_KILLFOCUS:
3588 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3589 editor->bHaveFocus = FALSE;
3590 ME_HideCaret(editor);
3591 ME_SendOldNotify(editor, EN_KILLFOCUS);
3592 return 0;
3593 case WM_ERASEBKGND:
3595 if (editor->bRedraw)
3597 HDC hDC = (HDC)wParam;
3598 RECT rc;
3599 if (GetUpdateRect(hWnd,&rc,TRUE))
3601 FillRect(hDC, &rc, editor->hbrBackground);
3604 return 1;
3606 case WM_COMMAND:
3607 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3608 return 0;
3609 case WM_KEYUP:
3610 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3611 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3612 return 0;
3613 goto do_default;
3614 case WM_KEYDOWN:
3615 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3616 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3617 return 0;
3618 if (ME_KeyDown(editor, LOWORD(wParam)))
3619 return 0;
3620 goto do_default;
3621 case WM_CHAR:
3623 WCHAR wstr;
3625 if (unicode)
3626 wstr = (WCHAR)wParam;
3627 else
3629 CHAR charA = wParam;
3630 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3633 switch (wstr)
3635 case 1: /* Ctrl-A */
3636 ME_SetSelection(editor, 0, -1);
3637 return 0;
3638 case 3: /* Ctrl-C */
3639 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3640 return 0;
3643 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3644 MessageBeep(MB_ICONERROR);
3645 return 0; /* FIXME really 0 ? */
3648 switch (wstr)
3650 case 22: /* Ctrl-V */
3651 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3652 return 0;
3653 case 24: /* Ctrl-X */
3654 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3655 return 0;
3656 case 25: /* Ctrl-Y */
3657 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3658 return 0;
3659 case 26: /* Ctrl-Z */
3660 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3661 return 0;
3663 if (((unsigned)wstr)>=' '
3664 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3665 || wstr=='\t') {
3666 int from, to;
3667 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
3668 ME_GetSelection(editor, &from, &to);
3669 if (wstr=='\t'
3670 /* v4.1 allows tabs to be inserted with ctrl key down */
3671 && !(ctrl_is_down && !editor->bEmulateVersion10)
3674 ME_Cursor cursor = editor->pCursors[0];
3675 ME_DisplayItem *para;
3676 BOOL bSelectedRow = FALSE;
3678 para = ME_GetParagraph(cursor.pRun);
3679 if (ME_IsSelection(editor) &&
3680 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3681 para->member.para.prev_para->type == diParagraph)
3683 para = para->member.para.prev_para;
3684 bSelectedRow = TRUE;
3686 if (ME_IsInTable(para))
3688 ME_TabPressedInTable(editor, bSelectedRow);
3689 ME_CommitUndo(editor);
3690 return 0;
3693 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3694 /* WM_CHAR is restricted to nTextLimit */
3695 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3697 ME_Style *style = ME_GetInsertStyle(editor, 0);
3698 ME_SaveTempStyle(editor);
3699 ME_ContinueCoalescingTransaction(editor);
3700 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3701 ME_InsertEndRowFromCursor(editor, 0);
3702 else
3703 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3704 ME_ReleaseStyle(style);
3705 ME_CommitCoalescingUndo(editor);
3706 SetCursor(NULL);
3709 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3711 ME_UpdateRepaint(editor);
3713 return 0;
3715 case WM_UNICHAR:
3716 if (unicode)
3718 if(wParam == UNICODE_NOCHAR) return TRUE;
3719 if(wParam <= 0x000fffff)
3721 if(wParam > 0xffff) /* convert to surrogates */
3723 wParam -= 0x10000;
3724 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3725 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3727 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3729 return 0;
3731 break;
3732 case EM_STOPGROUPTYPING:
3733 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3734 return 0;
3735 case EM_SCROLL: /* fall through */
3736 case WM_VSCROLL:
3738 int origNPos;
3739 int lineHeight;
3741 origNPos = ME_GetYScrollPos(editor);
3742 lineHeight = 24;
3744 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3745 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3746 if (lineHeight <= 0) lineHeight = 24;
3748 switch(LOWORD(wParam))
3750 case SB_LINEUP:
3751 ME_ScrollUp(editor,lineHeight);
3752 break;
3753 case SB_LINEDOWN:
3754 ME_ScrollDown(editor,lineHeight);
3755 break;
3756 case SB_PAGEUP:
3757 ME_ScrollUp(editor,editor->sizeWindow.cy);
3758 break;
3759 case SB_PAGEDOWN:
3760 ME_ScrollDown(editor,editor->sizeWindow.cy);
3761 break;
3762 case SB_THUMBTRACK:
3763 case SB_THUMBPOSITION:
3764 ME_ScrollAbs(editor,HIWORD(wParam));
3765 break;
3767 if (msg == EM_SCROLL)
3768 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3769 break;
3771 case WM_MOUSEWHEEL:
3773 int gcWheelDelta;
3774 UINT pulScrollLines;
3776 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3777 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3778 return 0;
3780 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3781 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3783 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3785 /* FIXME follow the original */
3786 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3788 break;
3790 case EM_GETRECT:
3792 *((RECT *)lParam) = editor->rcFormat;
3793 return 0;
3795 case EM_SETRECT:
3796 case EM_SETRECTNP:
3798 if (lParam)
3800 RECT *rc = (RECT *)lParam;
3802 if (wParam)
3804 editor->rcFormat.left += rc->left;
3805 editor->rcFormat.top += rc->top;
3806 editor->rcFormat.right += rc->right;
3807 editor->rcFormat.bottom += rc->bottom;
3809 else
3811 editor->rcFormat = *rc;
3814 else
3816 GetClientRect(hWnd, &editor->rcFormat);
3818 if (msg != EM_SETRECTNP)
3819 ME_RewrapRepaint(editor);
3820 return 0;
3822 case EM_REQUESTRESIZE:
3823 ME_SendRequestResize(editor, TRUE);
3824 return 0;
3825 case WM_SETREDRAW:
3826 if ((editor->bRedraw = wParam))
3827 ME_RewrapRepaint(editor);
3828 return 0;
3829 case WM_SIZE:
3831 GetClientRect(hWnd, &editor->rcFormat);
3832 ME_RewrapRepaint(editor);
3833 return DefWindowProcW(hWnd, msg, wParam, lParam);
3835 /* IME messages to make richedit controls IME aware */
3836 case WM_IME_SETCONTEXT:
3837 case WM_IME_CONTROL:
3838 case WM_IME_SELECT:
3839 case WM_IME_COMPOSITIONFULL:
3840 return 0;
3841 case WM_IME_STARTCOMPOSITION:
3843 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3844 ME_DeleteSelection(editor);
3845 ME_CommitUndo(editor);
3846 ME_UpdateRepaint(editor);
3847 return 0;
3849 case WM_IME_COMPOSITION:
3851 HIMC hIMC;
3853 ME_Style *style = ME_GetInsertStyle(editor, 0);
3854 hIMC = ImmGetContext(hWnd);
3855 ME_DeleteSelection(editor);
3856 ME_CommitUndo(editor);
3857 ME_SaveTempStyle(editor);
3858 if (lParam & GCS_RESULTSTR)
3860 LPWSTR lpCompStr = NULL;
3861 DWORD dwBufLen;
3863 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3864 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3865 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3866 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3867 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3869 else if (lParam & GCS_COMPSTR)
3871 LPWSTR lpCompStr = NULL;
3872 DWORD dwBufLen;
3874 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3875 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3876 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3877 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3879 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3880 ME_SetSelection(editor,editor->imeStartIndex,
3881 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3883 ME_ReleaseStyle(style);
3884 ME_UpdateRepaint(editor);
3885 return 0;
3887 case WM_IME_ENDCOMPOSITION:
3889 ME_DeleteSelection(editor);
3890 editor->imeStartIndex=-1;
3891 return 0;
3893 case EM_GETOLEINTERFACE:
3895 LPVOID *ppvObj = (LPVOID*) lParam;
3896 return CreateIRichEditOle(editor, ppvObj);
3898 case EM_GETPASSWORDCHAR:
3900 return editor->cPasswordMask;
3902 case EM_SETOLECALLBACK:
3903 if(editor->lpOleCallback)
3904 IUnknown_Release(editor->lpOleCallback);
3905 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3906 if(editor->lpOleCallback)
3907 IUnknown_AddRef(editor->lpOleCallback);
3908 return TRUE;
3909 case EM_GETWORDBREAKPROC:
3910 return (LRESULT)editor->pfnWordBreak;
3911 case EM_SETWORDBREAKPROC:
3913 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3915 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3916 return (LRESULT)pfnOld;
3918 case EM_SETTEXTMODE:
3920 LRESULT ret;
3921 int mask = 0;
3922 int changes = 0;
3923 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3924 if (!ret)
3926 /*Check for valid wParam*/
3927 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3928 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3929 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3930 return 1;
3931 else
3933 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3935 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3936 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3938 /*FIXME: Currently no support for undo level and code page options*/
3939 editor->mode = (editor->mode & (~mask)) | changes;
3940 return 0;
3943 return ret;
3945 case EM_SETPASSWORDCHAR:
3947 editor->cPasswordMask = wParam;
3948 ME_RewrapRepaint(editor);
3949 return 0;
3951 case EM_SETTARGETDEVICE:
3952 if (wParam == 0)
3954 BOOL new = (lParam == 0);
3955 if (editor->bWordWrap != new)
3957 editor->bWordWrap = new;
3958 ME_RewrapRepaint(editor);
3961 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3962 break;
3963 default:
3964 do_default:
3965 return DefWindowProcW(hWnd, msg, wParam, lParam);
3967 return 0L;
3970 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3972 BOOL unicode = TRUE;
3974 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3975 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3976 unicode = FALSE;
3978 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3981 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3983 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3986 /******************************************************************
3987 * RichEditANSIWndProc (RICHED20.10)
3989 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3991 return RichEditWndProcA(hWnd, msg, wParam, lParam);
3994 /******************************************************************
3995 * RichEdit10ANSIWndProc (RICHED20.9)
3997 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3999 LRESULT result;
4001 /* FIXME: this is NOT the same as 2.0 version */
4002 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4003 if (msg == WM_NCCREATE)
4005 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4007 editor->bEmulateVersion10 = TRUE;
4008 editor->pBuffer->pLast->member.para.nCharOfs = 2;
4009 assert(editor->pBuffer->pLast->prev->type == diRun);
4010 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
4011 editor->pBuffer->pLast->prev->member.run.nLF = 1;
4013 return result;
4016 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4018 HWND hWnd = editor->hWnd;
4019 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
4022 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
4024 int x,y;
4025 ME_Cursor tmpCursor;
4026 BOOL isExact;
4027 int nCharOfs; /* The start of the clicked text. Absolute character offset */
4029 ME_Run *tmpRun;
4031 ENLINK info;
4032 x = (short)LOWORD(lParam);
4033 y = (short)HIWORD(lParam);
4034 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
4035 if (!isExact) return;
4037 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
4038 tmpRun = &tmpCursor.pRun->member.run;
4040 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
4041 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
4042 { /* The clicked run has CFE_LINK set */
4043 info.nmhdr.hwndFrom = editor->hWnd;
4044 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
4045 info.nmhdr.code = EN_LINK;
4046 info.msg = msg;
4047 info.wParam = wParam;
4048 info.lParam = lParam;
4049 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
4050 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
4051 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
4055 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
4057 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
4058 int i = 0;
4060 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
4061 item = item->member.para.next_para;
4062 if (!item)
4063 return 0;
4064 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
4065 item = item->member.para.next_para;
4066 i++;
4068 return i;
4072 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
4074 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
4075 int nWritten = 0;
4076 WCHAR *pStart = buffer;
4078 if (!item) {
4079 *buffer = 0;
4080 return 0;
4083 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4084 if (editor->bEmulateVersion10) bCRLF = 0;
4086 if (nStart)
4088 int nLen = ME_StrLen(item->member.run.strText) - nStart;
4089 if (nLen > nChars)
4090 nLen = nChars;
4091 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
4092 nChars -= nLen;
4093 nWritten += nLen;
4094 buffer += nLen;
4095 if (!nChars) {
4096 *buffer = 0;
4097 return nWritten;
4099 nStart = 0;
4100 item = ME_FindItemFwd(item, diRun);
4103 while(nChars && item)
4105 int nLen = ME_StrLen(item->member.run.strText);
4106 if (item->member.run.nFlags & MERF_ENDPARA)
4107 nLen = item->member.run.nCR + item->member.run.nLF;
4108 if (nLen > nChars)
4109 nLen = nChars;
4111 if (item->member.run.nFlags & MERF_ENDCELL &&
4112 item->member.run.nFlags & MERF_ENDPARA)
4114 *buffer = '\t';
4116 else if (item->member.run.nFlags & MERF_ENDPARA)
4118 if (!ME_FindItemFwd(item, diRun))
4119 /* No '\r' is appended to the last paragraph. */
4120 nLen = 0;
4121 else if (bCRLF && nChars == 1) {
4122 nLen = 0;
4123 nChars = 0;
4124 } else {
4125 if (bCRLF)
4127 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
4128 if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4129 assert(nLen == 2);
4130 else
4131 assert(nLen == 1);
4132 *buffer++ = '\r';
4133 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4134 if (nLen == 1)
4135 nWritten++;
4136 else
4137 buffer--;
4139 else
4141 int i, j;
4143 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4144 i = 0;
4145 while (nChars - i > 0 && i < item->member.run.nCR)
4147 buffer[i] = '\r'; i++;
4149 j = 0;
4150 while (nChars - i - j > 0 && j < item->member.run.nLF)
4152 buffer[i+j] = '\n'; j++;
4157 else
4158 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4159 nChars -= nLen;
4160 nWritten += nLen;
4161 buffer += nLen;
4163 if (!nChars)
4165 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4166 *buffer = 0;
4167 return nWritten;
4169 item = ME_FindItemFwd(item, diRun);
4171 *buffer = 0;
4172 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4173 return nWritten;
4176 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4178 WNDCLASSW wcW;
4179 WNDCLASSA wcA;
4181 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4182 wcW.lpfnWndProc = RichEditWndProcW;
4183 wcW.cbClsExtra = 0;
4184 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4185 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4186 wcW.hIcon = NULL;
4187 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4188 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4189 wcW.lpszMenuName = NULL;
4191 if (is_version_nt())
4193 wcW.lpszClassName = RichEdit20W;
4194 if (!RegisterClassW(&wcW)) return FALSE;
4195 wcW.lpszClassName = RichEdit50W;
4196 if (!RegisterClassW(&wcW)) return FALSE;
4198 else
4200 /* WNDCLASSA/W have the same layout */
4201 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4202 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4203 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4204 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4207 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4208 wcA.lpfnWndProc = RichEditWndProcA;
4209 wcA.cbClsExtra = 0;
4210 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4211 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4212 wcA.hIcon = NULL;
4213 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4214 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4215 wcA.lpszMenuName = NULL;
4216 wcA.lpszClassName = "RichEdit20A";
4217 if (!RegisterClassA(&wcA)) return FALSE;
4218 wcA.lpszClassName = "RichEdit50A";
4219 if (!RegisterClassA(&wcA)) return FALSE;
4221 return TRUE;
4224 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4225 /* FIXME: Not implemented */
4226 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4227 hWnd, msg, get_msg_name(msg), wParam, lParam);
4228 return DefWindowProcW(hWnd, msg, wParam, lParam);
4231 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4232 /* FIXME: Not implemented */
4233 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4234 hWnd, msg, get_msg_name(msg), wParam, lParam);
4235 return DefWindowProcW(hWnd, msg, wParam, lParam);
4238 /******************************************************************
4239 * REExtendedRegisterClass (RICHED20.8)
4241 * FIXME undocumented
4242 * Need to check for errors and implement controls and callbacks
4244 LRESULT WINAPI REExtendedRegisterClass(void)
4246 WNDCLASSW wcW;
4247 UINT result;
4249 FIXME("semi stub\n");
4251 wcW.cbClsExtra = 0;
4252 wcW.cbWndExtra = 4;
4253 wcW.hInstance = NULL;
4254 wcW.hIcon = NULL;
4255 wcW.hCursor = NULL;
4256 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4257 wcW.lpszMenuName = NULL;
4259 if (!ME_ListBoxRegistered)
4261 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4262 wcW.lpfnWndProc = REListWndProc;
4263 wcW.lpszClassName = REListBox20W;
4264 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4267 if (!ME_ComboBoxRegistered)
4269 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4270 wcW.lpfnWndProc = REComboWndProc;
4271 wcW.lpszClassName = REComboBox20W;
4272 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4275 result = 0;
4276 if (ME_ListBoxRegistered)
4277 result += 1;
4278 if (ME_ComboBoxRegistered)
4279 result += 2;
4281 return result;
4284 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
4286 struct prefix_s {
4287 const char *text;
4288 int length;
4289 } prefixes[12] = {
4290 {"http:", 5},
4291 {"file:", 6},
4292 {"mailto:", 8},
4293 {"ftp:", 5},
4294 {"https:", 7},
4295 {"gopher:", 8},
4296 {"nntp:", 6},
4297 {"prospero:", 10},
4298 {"telnet:", 8},
4299 {"news:", 6},
4300 {"wais:", 6},
4301 {"www.", 5}
4303 CHARRANGE ins_pt;
4304 int curf_ef, link_ef, def_ef;
4305 int cur_prefx, prefx_cnt;
4306 int sel_min, sel_max;
4307 int car_pos = 0;
4308 int text_pos=-1;
4309 int URLmin, URLmax = 0;
4310 FINDTEXTA ft;
4311 CHARFORMAT2W cur_format;
4312 CHARFORMAT2W default_format;
4313 CHARFORMAT2W link;
4314 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
4315 sel_min = ins_pt.cpMin;
4316 sel_max = ins_pt.cpMax;
4317 if (sel_min==sel_max)
4318 car_pos = sel_min;
4319 if (sel_min!=sel_max)
4320 car_pos = ME_GetTextLength(editor)+1;
4321 cur_format.cbSize = sizeof(cur_format);
4322 default_format.cbSize = sizeof(default_format);
4323 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
4324 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
4325 link.cbSize = sizeof(link);
4326 link.dwMask = CFM_LINK;
4327 link.dwEffects = CFE_LINK;
4328 curf_ef = cur_format.dwEffects & link.dwEffects;
4329 def_ef = default_format.dwEffects & link.dwEffects;
4330 link_ef = link.dwEffects & link.dwEffects;
4331 if (curf_ef == link_ef)
4333 if( curChar == '\n' || curChar=='\r' || curChar==' ')
4335 ME_SetSelection(editor, car_pos, car_pos);
4336 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
4337 text_pos=-1;
4338 return 0;
4341 if (curf_ef == def_ef)
4343 cur_prefx = 0;
4344 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
4345 while (cur_prefx<=prefx_cnt)
4347 if (text_pos == -1)
4349 ft.lpstrText = prefixes[cur_prefx].text;
4350 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
4351 URLmax=max(0, car_pos);
4352 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
4354 URLmax = ME_GetTextLength(editor)+1;
4356 ft.chrg.cpMin = URLmin;
4357 ft.chrg.cpMax = URLmax;
4358 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
4359 cur_prefx++;
4361 if (text_pos != -1)
4363 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
4364 ME_RewrapRepaint(editor);
4365 break;
4369 return 0;
4373 static BOOL isurlspecial(WCHAR c)
4375 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4376 return strchrW( special_chars, c ) != NULL;
4380 * This proc takes a selection, and scans it forward in order to select the span
4381 * of a possible URL candidate. A possible URL candidate must start with isalnum
4382 * or one of the following special characters: *|/\+%#@ and must consist entirely
4383 * of the characters allowed to start the URL, plus : (colon) which may occur
4384 * at most once, and not at either end.
4386 * sel_max == -1 indicates scan to end of text.
4388 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4389 int * candidate_min, int * candidate_max)
4391 ME_DisplayItem * item;
4392 ME_DisplayItem * para;
4393 int nStart;
4394 BOOL foundColon = FALSE;
4395 WCHAR lastAcceptedChar = '\0';
4397 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4399 *candidate_min = *candidate_max = -1;
4400 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4401 if (!item) return FALSE;
4402 TRACE("nStart = %d\n", nStart);
4403 para = ME_GetParagraph(item);
4404 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4405 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4407 ME_DisplayItem * next_item;
4409 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4410 /* Find start of candidate */
4411 if (*candidate_min == -1) {
4412 while (nStart < ME_StrLen(item->member.run.strText) &&
4413 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4414 isurlspecial(item->member.run.strText->szData[nStart]))) {
4415 nStart++;
4417 if (nStart < ME_StrLen(item->member.run.strText) &&
4418 (isalnumW(item->member.run.strText->szData[nStart]) ||
4419 isurlspecial(item->member.run.strText->szData[nStart]))) {
4420 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4421 lastAcceptedChar = item->member.run.strText->szData[nStart];
4422 nStart++;
4426 /* Find end of candidate */
4427 if (*candidate_min >= 0) {
4428 while (nStart < ME_StrLen(item->member.run.strText) &&
4429 (isalnumW(item->member.run.strText->szData[nStart]) ||
4430 isurlspecial(item->member.run.strText->szData[nStart]) ||
4431 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4432 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4433 lastAcceptedChar = item->member.run.strText->szData[nStart];
4434 nStart++;
4436 if (nStart < ME_StrLen(item->member.run.strText) &&
4437 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4438 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4439 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4440 nStart++;
4441 if (lastAcceptedChar == ':') (*candidate_max)--;
4442 return TRUE;
4445 } else {
4446 /* End of paragraph: skip it if before candidate span, or terminates
4447 current active span */
4448 if (*candidate_min >= 0) {
4449 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4450 if (lastAcceptedChar == ':') (*candidate_max)--;
4451 return TRUE;
4455 /* Reaching this point means no span was found, so get next span */
4456 next_item = ME_FindItemFwd(item, diRun);
4457 if (!next_item) {
4458 if (*candidate_min >= 0) {
4459 /* There are no further runs, so take end of text as end of candidate */
4460 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4461 if (lastAcceptedChar == ':') (*candidate_max)--;
4462 return TRUE;
4465 item = next_item;
4466 para = ME_GetParagraph(item);
4467 nStart = 0;
4470 if (item) {
4471 if (*candidate_min >= 0) {
4472 /* There are no further runs, so take end of text as end of candidate */
4473 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4474 if (lastAcceptedChar == ':') (*candidate_max)--;
4475 return TRUE;
4478 return FALSE;
4482 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4484 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4486 struct prefix_s {
4487 const char *text;
4488 int length;
4489 } prefixes[12] = {
4490 /* Code below depends on these being in decreasing length order! */
4491 {"prospero:", 10},
4492 {"telnet:", 8},
4493 {"gopher:", 8},
4494 {"mailto:", 8},
4495 {"https:", 7},
4496 {"file:", 6},
4497 {"news:", 6},
4498 {"wais:", 6},
4499 {"nntp:", 6},
4500 {"http:", 5},
4501 {"www.", 5},
4502 {"ftp:", 5},
4504 LPWSTR bufferW = NULL;
4505 WCHAR bufW[32];
4506 int i;
4508 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4509 assert(sel_min <= sel_max);
4510 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4512 if (sel_max - sel_min < prefixes[i].length) continue;
4513 if (bufferW == NULL) {
4514 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4516 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4517 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4518 if (!lstrcmpW(bufW, bufferW))
4520 heap_free(bufferW);
4521 return TRUE;
4524 heap_free(bufferW);
4525 return FALSE;
4529 * This proc walks through the indicated selection and evaluates whether each
4530 * section identified by ME_FindNextURLCandidate and in-between sections have
4531 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4532 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4534 * Returns TRUE if at least one section was modified.
4536 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4538 BOOL modified = FALSE;
4539 int cMin, cMax;
4541 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4544 int beforeURL[2];
4545 int inURL[2];
4546 CHARFORMAT2W link;
4548 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4550 /* Section before candidate is not an URL */
4551 beforeURL[0] = sel_min;
4552 beforeURL[1] = cMin;
4554 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4556 inURL[0] = cMin; inURL[1] = cMax;
4558 else
4560 beforeURL[1] = cMax;
4561 inURL[0] = inURL[1] = -1;
4563 sel_min = cMax;
4565 else
4567 /* No more candidates until end of selection */
4568 beforeURL[0] = sel_min;
4569 beforeURL[1] = sel_max;
4570 inURL[0] = inURL[1] = -1;
4571 sel_min = sel_max;
4574 if (beforeURL[0] < beforeURL[1])
4576 /* CFE_LINK effect should be consistently unset */
4577 link.cbSize = sizeof(link);
4578 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4579 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4581 /* CFE_LINK must be unset from this range */
4582 memset(&link, 0, sizeof(CHARFORMAT2W));
4583 link.cbSize = sizeof(link);
4584 link.dwMask = CFM_LINK;
4585 link.dwEffects = 0;
4586 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4587 modified = TRUE;
4590 if (inURL[0] < inURL[1])
4592 /* CFE_LINK effect should be consistently set */
4593 link.cbSize = sizeof(link);
4594 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4595 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4597 /* CFE_LINK must be set on this range */
4598 memset(&link, 0, sizeof(CHARFORMAT2W));
4599 link.cbSize = sizeof(link);
4600 link.dwMask = CFM_LINK;
4601 link.dwEffects = CFE_LINK;
4602 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4603 modified = TRUE;
4606 } while (sel_min < sel_max);
4607 return modified;
4610 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4612 ME_DisplayItem * startPara, * endPara;
4613 ME_DisplayItem * item;
4614 int dummy;
4615 int from, to;
4617 ME_GetSelection(editor, &from, &to);
4618 if (from > to) from ^= to, to ^=from, from ^= to;
4619 startPara = NULL; endPara = NULL;
4621 /* Find paragraph previous to the one that contains start cursor */
4622 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4623 if (item) {
4624 startPara = ME_FindItemBack(item, diParagraph);
4625 item = ME_FindItemBack(startPara, diParagraph);
4626 if (item) startPara = item;
4629 /* Find paragraph that contains end cursor */
4630 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4631 if (item) {
4632 endPara = ME_FindItemFwd(item, diParagraph);
4635 if (startPara && endPara) {
4636 ME_UpdateLinkAttribute(editor,
4637 startPara->member.para.nCharOfs,
4638 endPara->member.para.nCharOfs);
4639 } else if (startPara) {
4640 ME_UpdateLinkAttribute(editor,
4641 startPara->member.para.nCharOfs,
4642 -1);