richedit: Substitute space for \tab and \par control words for simple tables.
[wine/wine64.git] / dlls / riched20 / editor.c
blob15ad39f24b28254b22705a5f2500604511489a5c
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_RTFCharAttrHook(RTF_Info *info)
325 CHARFORMAT2W fmt;
326 fmt.cbSize = sizeof(fmt);
327 fmt.dwMask = 0;
328 fmt.dwEffects = 0;
330 switch(info->rtfMinor)
332 case rtfPlain:
333 /* FIXME add more flags once they're implemented */
334 fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
335 fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
336 fmt.yHeight = 12*20; /* 12pt */
337 fmt.wWeight = FW_NORMAL;
338 fmt.bUnderlineType = CFU_UNDERLINENONE;
339 break;
340 case rtfBold:
341 fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
342 fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
343 fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
344 break;
345 case rtfItalic:
346 fmt.dwMask = CFM_ITALIC;
347 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
348 break;
349 case rtfUnderline:
350 fmt.dwMask = CFM_UNDERLINETYPE;
351 fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
352 break;
353 case rtfDotUnderline:
354 fmt.dwMask = CFM_UNDERLINETYPE;
355 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
356 break;
357 case rtfDbUnderline:
358 fmt.dwMask = CFM_UNDERLINETYPE;
359 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
360 break;
361 case rtfWordUnderline:
362 fmt.dwMask = CFM_UNDERLINETYPE;
363 fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
364 break;
365 case rtfNoUnderline:
366 fmt.dwMask = CFM_UNDERLINETYPE;
367 fmt.bUnderlineType = CFU_UNDERLINENONE;
368 break;
369 case rtfStrikeThru:
370 fmt.dwMask = CFM_STRIKEOUT;
371 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
372 break;
373 case rtfSubScript:
374 case rtfSuperScript:
375 case rtfSubScrShrink:
376 case rtfSuperScrShrink:
377 case rtfNoSuperSub:
378 fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
379 if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
380 if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
381 if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
382 break;
383 case rtfInvisible:
384 fmt.dwMask = CFM_HIDDEN;
385 fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
386 break;
387 case rtfBackColor:
388 fmt.dwMask = CFM_BACKCOLOR;
389 fmt.dwEffects = 0;
390 if (info->rtfParam == 0)
391 fmt.dwEffects = CFE_AUTOBACKCOLOR;
392 else if (info->rtfParam != rtfNoParam)
394 RTFColor *c = RTFGetColor(info, info->rtfParam);
395 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
397 break;
398 case rtfForeColor:
399 fmt.dwMask = CFM_COLOR;
400 fmt.dwEffects = 0;
401 if (info->rtfParam == 0)
402 fmt.dwEffects = CFE_AUTOCOLOR;
403 else if (info->rtfParam != rtfNoParam)
405 RTFColor *c = RTFGetColor(info, info->rtfParam);
406 if (c)
407 fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
408 else
409 fmt.crTextColor = 0;
411 break;
412 case rtfFontNum:
413 if (info->rtfParam != rtfNoParam)
415 RTFFont *f = RTFGetFont(info, info->rtfParam);
416 if (f)
418 MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
419 fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
420 fmt.bCharSet = f->rtfFCharSet;
421 fmt.dwMask = CFM_FACE | CFM_CHARSET;
422 fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
425 break;
426 case rtfFontSize:
427 fmt.dwMask = CFM_SIZE;
428 if (info->rtfParam != rtfNoParam)
429 fmt.yHeight = info->rtfParam*10;
430 break;
432 if (fmt.dwMask) {
433 ME_Style *style2;
434 RTFFlushOutputBuffer(info);
435 /* FIXME too slow ? how come ? */
436 style2 = ME_ApplyStyle(info->style, &fmt);
437 ME_ReleaseStyle(info->style);
438 info->style = style2;
439 info->styleChanged = TRUE;
443 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
444 the same tags mean different things in different contexts */
445 static void ME_RTFParAttrHook(RTF_Info *info)
447 PARAFORMAT2 fmt;
448 fmt.cbSize = sizeof(fmt);
449 fmt.dwMask = 0;
451 switch(info->rtfMinor)
453 case rtfParDef: /* restores default paragraph attributes */
454 fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
455 PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
456 PFM_STARTINDENT;
457 /* TODO: numbering, shading */
458 fmt.wAlignment = PFA_LEFT;
459 fmt.cTabCount = 0;
460 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
461 fmt.wBorderWidth = fmt.wBorders = 0;
462 fmt.wBorderSpace = 0;
463 fmt.bLineSpacingRule = 0;
464 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
465 fmt.dyLineSpacing = 0;
466 if (!info->editor->bEmulateVersion10) /* v4.1 */
468 if (info->tableDef && info->tableDef->tableRowStart &&
469 info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
471 ME_Cursor cursor;
472 ME_DisplayItem *para;
473 /* We are just after a table row. */
474 RTFFlushOutputBuffer(info);
475 cursor = info->editor->pCursors[0];
476 para = ME_GetParagraph(cursor.pRun);
477 if (para == info->tableDef->tableRowStart->member.para.next_para
478 && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
480 /* Since the table row end, no text has been inserted, and the \intbl
481 * control word has not be used. We can confirm that we are not in a
482 * table anymore.
484 info->tableDef->tableRowStart = NULL;
485 info->canInheritInTbl = FALSE;
488 } else { /* v1.0 - v3.0 */
489 fmt.dwMask |= PFM_TABLE;
490 fmt.wEffects &= ~PFE_TABLE;
492 break;
493 case rtfNestLevel:
494 if (!info->editor->bEmulateVersion10) /* v4.1 */
496 while (info->rtfParam > info->nestingLevel) {
497 RTFTable *tableDef = ALLOC_OBJ(RTFTable);
498 ZeroMemory(tableDef, sizeof(RTFTable));
499 tableDef->parent = info->tableDef;
500 info->tableDef = tableDef;
502 RTFFlushOutputBuffer(info);
503 if (tableDef->tableRowStart &&
504 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
506 ME_DisplayItem *para = tableDef->tableRowStart;
507 para = para->member.para.next_para;
508 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
509 tableDef->tableRowStart = para;
510 } else {
511 ME_Cursor cursor;
512 WCHAR endl = '\r';
513 cursor = info->editor->pCursors[0];
514 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
515 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
516 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
519 info->nestingLevel++;
521 info->canInheritInTbl = FALSE;
523 break;
524 case rtfInTable:
526 if (!info->editor->bEmulateVersion10) /* v4.1 */
528 if (info->nestingLevel < 1)
530 RTFTable *tableDef;
531 if (!info->tableDef)
533 info->tableDef = ALLOC_OBJ(RTFTable);
534 ZeroMemory(info->tableDef, sizeof(RTFTable));
536 tableDef = info->tableDef;
537 RTFFlushOutputBuffer(info);
538 if (tableDef->tableRowStart &&
539 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
541 ME_DisplayItem *para = tableDef->tableRowStart;
542 para = para->member.para.next_para;
543 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
544 tableDef->tableRowStart = para;
545 } else {
546 ME_Cursor cursor;
547 WCHAR endl = '\r';
548 cursor = info->editor->pCursors[0];
549 if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
550 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
551 tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
553 info->nestingLevel = 1;
554 info->canInheritInTbl = TRUE;
556 return;
557 } else { /* v1.0 - v3.0 */
558 fmt.dwMask |= PFM_TABLE;
559 fmt.wEffects |= PFE_TABLE;
561 break;
563 case rtfFirstIndent:
564 ME_GetSelectionParaFormat(info->editor, &fmt);
565 fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
566 fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
567 fmt.dxOffset = -info->rtfParam;
568 break;
569 case rtfLeftIndent:
570 ME_GetSelectionParaFormat(info->editor, &fmt);
571 fmt.dwMask = PFM_STARTINDENT;
572 fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
573 break;
574 case rtfRightIndent:
575 fmt.dwMask = PFM_RIGHTINDENT;
576 fmt.dxRightIndent = info->rtfParam;
577 break;
578 case rtfQuadLeft:
579 case rtfQuadJust:
580 fmt.dwMask = PFM_ALIGNMENT;
581 fmt.wAlignment = PFA_LEFT;
582 break;
583 case rtfQuadRight:
584 fmt.dwMask = PFM_ALIGNMENT;
585 fmt.wAlignment = PFA_RIGHT;
586 break;
587 case rtfQuadCenter:
588 fmt.dwMask = PFM_ALIGNMENT;
589 fmt.wAlignment = PFA_CENTER;
590 break;
591 case rtfTabPos:
592 ME_GetSelectionParaFormat(info->editor, &fmt);
593 if (!(fmt.dwMask & PFM_TABSTOPS))
595 fmt.cTabCount = 0;
597 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
598 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
599 fmt.dwMask = PFM_TABSTOPS;
600 break;
601 case rtfKeep:
602 fmt.dwMask = PFM_KEEP;
603 fmt.wEffects = PFE_KEEP;
604 break;
605 case rtfNoWidowControl:
606 fmt.dwMask = PFM_NOWIDOWCONTROL;
607 fmt.wEffects = PFE_NOWIDOWCONTROL;
608 break;
609 case rtfKeepNext:
610 fmt.dwMask = PFM_KEEPNEXT;
611 fmt.wEffects = PFE_KEEPNEXT;
612 break;
613 case rtfSpaceAfter:
614 fmt.dwMask = PFM_SPACEAFTER;
615 fmt.dySpaceAfter = info->rtfParam;
616 break;
617 case rtfSpaceBefore:
618 fmt.dwMask = PFM_SPACEBEFORE;
619 fmt.dySpaceBefore = info->rtfParam;
620 break;
621 case rtfSpaceBetween:
622 fmt.dwMask = PFM_LINESPACING;
623 if ((int)info->rtfParam > 0)
625 fmt.dyLineSpacing = info->rtfParam;
626 fmt.bLineSpacingRule = 3;
628 else
630 fmt.dyLineSpacing = info->rtfParam;
631 fmt.bLineSpacingRule = 4;
633 case rtfSpaceMultiply:
634 fmt.dwMask = PFM_LINESPACING;
635 fmt.dyLineSpacing = info->rtfParam * 20;
636 fmt.bLineSpacingRule = 5;
637 break;
638 case rtfParBullet:
639 fmt.dwMask = PFM_NUMBERING;
640 fmt.wNumbering = PFN_BULLET;
641 break;
642 case rtfParSimple:
643 fmt.dwMask = PFM_NUMBERING;
644 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
645 break;
646 case rtfParNumDecimal:
647 fmt.dwMask = PFM_NUMBERING;
648 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
649 break;
650 case rtfParNumIndent:
651 fmt.dwMask = PFM_NUMBERINGTAB;
652 fmt.wNumberingTab = info->rtfParam;
653 break;
654 case rtfParNumStartAt:
655 fmt.dwMask = PFM_NUMBERINGSTART;
656 fmt.wNumberingStart = info->rtfParam;
657 break;
658 case rtfBorderLeft:
659 ME_GetSelectionParaFormat(info->editor, &fmt);
660 if (!(fmt.dwMask & PFM_BORDER))
662 fmt.wBorderSpace = 0;
663 fmt.wBorderWidth = 1;
664 fmt.wBorders = 0;
666 fmt.wBorders |= 1;
667 fmt.dwMask = PFM_BORDER;
668 break;
669 case rtfBorderRight:
670 ME_GetSelectionParaFormat(info->editor, &fmt);
671 if (!(fmt.dwMask & PFM_BORDER))
673 fmt.wBorderSpace = 0;
674 fmt.wBorderWidth = 1;
675 fmt.wBorders = 0;
677 fmt.wBorders |= 2;
678 fmt.dwMask = PFM_BORDER;
679 break;
680 case rtfBorderTop:
681 ME_GetSelectionParaFormat(info->editor, &fmt);
682 if (!(fmt.dwMask & PFM_BORDER))
684 fmt.wBorderSpace = 0;
685 fmt.wBorderWidth = 1;
686 fmt.wBorders = 0;
688 fmt.wBorders |= 4;
689 fmt.dwMask = PFM_BORDER;
690 break;
691 case rtfBorderBottom:
692 ME_GetSelectionParaFormat(info->editor, &fmt);
693 if (!(fmt.dwMask & PFM_BORDER))
695 fmt.wBorderSpace = 0;
696 fmt.wBorderWidth = 1;
697 fmt.wBorders = 0;
699 fmt.wBorders |= 8;
700 fmt.dwMask = PFM_BORDER;
701 break;
702 case rtfBorderSingle:
703 ME_GetSelectionParaFormat(info->editor, &fmt);
704 /* we assume that borders have been created before (RTF spec) */
705 fmt.wBorders &= ~0x700;
706 fmt.wBorders |= 1 << 8;
707 fmt.dwMask = PFM_BORDER;
708 break;
709 case rtfBorderThick:
710 ME_GetSelectionParaFormat(info->editor, &fmt);
711 /* we assume that borders have been created before (RTF spec) */
712 fmt.wBorders &= ~0x700;
713 fmt.wBorders |= 2 << 8;
714 fmt.dwMask = PFM_BORDER;
715 break;
716 case rtfBorderShadow:
717 ME_GetSelectionParaFormat(info->editor, &fmt);
718 /* we assume that borders have been created before (RTF spec) */
719 fmt.wBorders &= ~0x700;
720 fmt.wBorders |= 10 << 8;
721 fmt.dwMask = PFM_BORDER;
722 break;
723 case rtfBorderDouble:
724 ME_GetSelectionParaFormat(info->editor, &fmt);
725 /* we assume that borders have been created before (RTF spec) */
726 fmt.wBorders &= ~0x700;
727 fmt.wBorders |= 7 << 8;
728 fmt.dwMask = PFM_BORDER;
729 break;
730 case rtfBorderDot:
731 ME_GetSelectionParaFormat(info->editor, &fmt);
732 /* we assume that borders have been created before (RTF spec) */
733 fmt.wBorders &= ~0x700;
734 fmt.wBorders |= 11 << 8;
735 fmt.dwMask = PFM_BORDER;
736 break;
737 case rtfBorderWidth:
738 ME_GetSelectionParaFormat(info->editor, &fmt);
739 /* we assume that borders have been created before (RTF spec) */
740 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
741 fmt.dwMask = PFM_BORDER;
742 break;
743 case rtfBorderSpace:
744 ME_GetSelectionParaFormat(info->editor, &fmt);
745 /* we assume that borders have been created before (RTF spec) */
746 fmt.wBorderSpace = info->rtfParam;
747 fmt.dwMask = PFM_BORDER;
748 break;
750 if (fmt.dwMask) {
751 RTFFlushOutputBuffer(info);
752 /* FIXME too slow ? how come ?*/
753 ME_SetSelectionParaFormat(info->editor, &fmt);
757 static void ME_RTFTblAttrHook(RTF_Info *info)
759 switch (info->rtfMinor)
761 case rtfRowDef:
763 if (!info->tableDef) {
764 info->tableDef = ALLOC_OBJ(RTFTable);
765 ZeroMemory(info->tableDef, sizeof(RTFTable));
766 } else {
767 ZeroMemory(info->tableDef->cells, sizeof(info->tableDef->cells));
768 info->tableDef->numCellsDefined = 0;
770 break;
772 case rtfCellPos:
773 if (!info->tableDef)
775 info->tableDef = ALLOC_OBJ(RTFTable);
776 ZeroMemory(info->tableDef, sizeof(RTFTable));
778 if (info->tableDef->numCellsDefined >= MAX_TABLE_CELLS)
779 break;
780 info->tableDef->cells[info->tableDef->numCellsDefined].rightBoundary = info->rtfParam;
782 /* Tab stops were used to store cell positions before v4.1 but v4.1
783 * still seems to set the tabstops without using them. */
784 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
785 PARAFORMAT2 *pFmt = para->member.para.pFmt;
786 int cellNum = info->tableDef->numCellsDefined;
787 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
788 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
790 info->tableDef->numCellsDefined++;
791 break;
795 static void ME_RTFSpecialCharHook(RTF_Info *info)
797 RTFTable *tableDef = info->tableDef;
798 switch (info->rtfMinor)
800 case rtfNestCell:
801 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
802 break;
803 /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
804 case rtfCell:
805 if (!tableDef)
806 break;
807 RTFFlushOutputBuffer(info);
808 if (!info->editor->bEmulateVersion10) { /* v4.1 */
809 if (tableDef->tableRowStart)
811 if (!info->nestingLevel &&
812 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
814 ME_DisplayItem *para = tableDef->tableRowStart;
815 para = para->member.para.next_para;
816 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
817 tableDef->tableRowStart = para;
818 info->nestingLevel = 1;
820 ME_InsertTableCellFromCursor(info->editor);
822 } else { /* v1.0 - v3.0 */
823 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
824 PARAFORMAT2 *pFmt = para->member.para.pFmt;
825 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
826 tableDef->numCellsInserted < tableDef->numCellsDefined)
828 WCHAR tab = '\t';
829 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
830 tableDef->numCellsInserted++;
833 break;
834 case rtfNestRow:
835 if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
836 break;
837 /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
838 case rtfRow:
840 ME_DisplayItem *para, *cell, *run;
841 int i;
843 if (!tableDef)
844 break;
845 RTFFlushOutputBuffer(info);
846 if (!info->editor->bEmulateVersion10) { /* v4.1 */
847 if (!tableDef->tableRowStart)
848 break;
849 if (!info->nestingLevel &&
850 tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
852 para = tableDef->tableRowStart;
853 para = para->member.para.next_para;
854 para = ME_InsertTableRowStartAtParagraph(info->editor, para);
855 tableDef->tableRowStart = para;
856 info->nestingLevel++;
858 para = tableDef->tableRowStart;
859 cell = ME_FindItemFwd(para, diCell);
860 assert(cell && !cell->member.cell.prev_cell);
861 if (tableDef->numCellsDefined < 1)
863 /* 2000 twips appears to be the cell size that native richedit uses
864 * when no cell sizes are specified. */
865 const int defaultCellSize = 2000;
866 int nRightBoundary = defaultCellSize;
867 cell->member.cell.nRightBoundary = nRightBoundary;
868 while (cell->member.cell.next_cell) {
869 cell = cell->member.cell.next_cell;
870 nRightBoundary += defaultCellSize;
871 cell->member.cell.nRightBoundary = nRightBoundary;
873 para = ME_InsertTableCellFromCursor(info->editor);
874 cell = para->member.para.pCell;
875 cell->member.cell.nRightBoundary = nRightBoundary;
876 } else {
877 for (i = 0; i < tableDef->numCellsDefined; i++)
879 cell->member.cell.nRightBoundary = tableDef->cells[i].rightBoundary;
880 cell = cell->member.cell.next_cell;
881 if (!cell)
883 para = ME_InsertTableCellFromCursor(info->editor);
884 cell = para->member.para.pCell;
887 /* Cell for table row delimiter is empty */
888 cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
891 run = ME_FindItemFwd(cell, diRun);
892 if (info->editor->pCursors[0].pRun != run ||
893 info->editor->pCursors[0].nOffset)
895 int nOfs, nChars;
896 /* Delete inserted cells that aren't defined. */
897 info->editor->pCursors[1].pRun = run;
898 info->editor->pCursors[1].nOffset = 0;
899 nOfs = ME_GetCursorOfs(info->editor, 1);
900 nChars = ME_GetCursorOfs(info->editor, 0) - nOfs;
901 ME_InternalDeleteText(info->editor, nOfs, nChars, TRUE);
904 para = ME_InsertTableRowEndFromCursor(info->editor);
905 info->nestingLevel--;
906 if (!info->nestingLevel)
908 if (info->canInheritInTbl) {
909 tableDef->tableRowStart = para;
910 } else {
911 while (info->tableDef) {
912 tableDef = info->tableDef;
913 info->tableDef = tableDef->parent;
914 heap_free(tableDef);
917 } else {
918 info->tableDef = tableDef->parent;
919 heap_free(tableDef);
921 } else { /* v1.0 - v3.0 */
922 WCHAR endl = '\r';
923 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
924 PARAFORMAT2 *pFmt = para->member.para.pFmt;
925 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
927 WCHAR tab = '\t';
928 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
929 tableDef->numCellsInserted++;
931 pFmt->cTabCount = tableDef->numCellsDefined;
932 if (!tableDef->numCellsDefined)
933 pFmt->wEffects &= ~PFE_TABLE;
934 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
935 tableDef->numCellsInserted = 0;
937 break;
939 case rtfTab:
940 case rtfPar:
941 if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
942 ME_DisplayItem *para;
943 PARAFORMAT2 *pFmt;
944 RTFFlushOutputBuffer(info);
945 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
946 pFmt = para->member.para.pFmt;
947 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
949 /* rtfPar is treated like a space within a table. */
950 info->rtfClass = rtfText;
951 info->rtfMajor = ' ';
953 else if (info->rtfMinor == rtfPar && tableDef)
954 tableDef->numCellsInserted = 0;
956 break;
960 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
961 const SIZEL* sz)
963 LPOLEOBJECT lpObject = NULL;
964 LPSTORAGE lpStorage = NULL;
965 LPOLECLIENTSITE lpClientSite = NULL;
966 LPDATAOBJECT lpDataObject = NULL;
967 LPOLECACHE lpOleCache = NULL;
968 STGMEDIUM stgm;
969 FORMATETC fm;
970 CLSID clsid;
971 BOOL ret = FALSE;
972 DWORD conn;
974 if (hemf)
976 stgm.tymed = TYMED_ENHMF;
977 stgm.u.hEnhMetaFile = hemf;
978 fm.cfFormat = CF_ENHMETAFILE;
980 else if (hbmp)
982 stgm.tymed = TYMED_GDI;
983 stgm.u.hBitmap = hbmp;
984 fm.cfFormat = CF_BITMAP;
986 stgm.pUnkForRelease = NULL;
988 fm.ptd = NULL;
989 fm.dwAspect = DVASPECT_CONTENT;
990 fm.lindex = -1;
991 fm.tymed = stgm.tymed;
993 if (!info->lpRichEditOle)
995 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
998 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
999 #if 0
1000 /* FIXME: enable it when rich-edit properly implements this method */
1001 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1002 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1003 #endif
1004 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1005 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1006 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1007 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1008 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1010 REOBJECT reobject;
1012 reobject.cbStruct = sizeof(reobject);
1013 reobject.cp = REO_CP_SELECTION;
1014 reobject.clsid = clsid;
1015 reobject.poleobj = lpObject;
1016 reobject.pstg = lpStorage;
1017 reobject.polesite = lpClientSite;
1018 /* convert from twips to .01 mm */
1019 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1020 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1021 reobject.dvaspect = DVASPECT_CONTENT;
1022 reobject.dwFlags = 0; /* FIXME */
1023 reobject.dwUser = 0;
1025 /* FIXME: could be simpler */
1026 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1029 if (lpObject) IOleObject_Release(lpObject);
1030 if (lpClientSite) IOleClientSite_Release(lpClientSite);
1031 if (lpStorage) IStorage_Release(lpStorage);
1032 if (lpDataObject) IDataObject_Release(lpDataObject);
1033 if (lpOleCache) IOleCache_Release(lpOleCache);
1035 return ret;
1038 static void ME_RTFReadPictGroup(RTF_Info *info)
1040 SIZEL sz;
1041 BYTE* buffer = NULL;
1042 unsigned bufsz, bufidx;
1043 BOOL flip;
1044 BYTE val;
1045 METAFILEPICT mfp;
1046 HENHMETAFILE hemf;
1047 HBITMAP hbmp;
1048 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1050 RTFGetToken (info);
1051 if (info->rtfClass == rtfEOF)
1052 return;
1053 mfp.mm = MM_TEXT;
1054 /* fetch picture type */
1055 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1057 mfp.mm = info->rtfParam;
1058 gfx = gfx_metafile;
1060 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1062 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1063 gfx = gfx_dib;
1065 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1067 gfx = gfx_enhmetafile;
1069 else
1071 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1072 goto skip_group;
1074 sz.cx = sz.cy = 0;
1075 /* fetch picture attributes */
1076 for (;;)
1078 RTFGetToken (info);
1079 if (info->rtfClass == rtfEOF)
1080 return;
1081 if (info->rtfClass == rtfText)
1082 break;
1083 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1085 ERR("Expected picture attribute (%d %d)\n",
1086 info->rtfClass, info->rtfMajor);
1087 goto skip_group;
1089 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1091 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1093 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1095 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1097 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1098 sz.cx = info->rtfParam;
1099 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1100 sz.cy = info->rtfParam;
1101 else
1102 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1104 /* fetch picture data */
1105 bufsz = 1024;
1106 bufidx = 0;
1107 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1108 val = info->rtfMajor;
1109 for (flip = TRUE;; flip = !flip)
1111 RTFGetToken (info);
1112 if (info->rtfClass == rtfEOF)
1114 HeapFree(GetProcessHeap(), 0, buffer);
1115 return; /* Warn ?? */
1117 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1118 break;
1119 if (info->rtfClass != rtfText) goto skip_group;
1120 if (flip)
1122 if (bufidx >= bufsz &&
1123 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1124 goto skip_group;
1125 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1127 else
1128 val = info->rtfMajor;
1130 if (flip) FIXME("wrong hex string\n");
1132 switch (gfx)
1134 case gfx_enhmetafile:
1135 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1136 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1137 break;
1138 case gfx_metafile:
1139 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1140 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1141 break;
1142 case gfx_dib:
1144 BITMAPINFO* bi = (BITMAPINFO*)buffer;
1145 HDC hdc = GetDC(0);
1146 unsigned nc = bi->bmiHeader.biClrUsed;
1148 /* not quite right, especially for bitfields type of compression */
1149 if (!nc && bi->bmiHeader.biBitCount <= 8)
1150 nc = 1 << bi->bmiHeader.biBitCount;
1151 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1152 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1153 bi, DIB_RGB_COLORS)))
1154 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1155 ReleaseDC(0, hdc);
1157 break;
1158 default:
1159 break;
1161 HeapFree(GetProcessHeap(), 0, buffer);
1162 RTFRouteToken (info); /* feed "}" back to router */
1163 return;
1164 skip_group:
1165 HeapFree(GetProcessHeap(), 0, buffer);
1166 RTFSkipGroup(info);
1167 RTFRouteToken(info); /* feed "}" back to router */
1170 /* for now, lookup the \result part and use it, whatever the object */
1171 static void ME_RTFReadObjectGroup(RTF_Info *info)
1173 for (;;)
1175 RTFGetToken (info);
1176 if (info->rtfClass == rtfEOF)
1177 return;
1178 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1179 break;
1180 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1182 RTFGetToken (info);
1183 if (info->rtfClass == rtfEOF)
1184 return;
1185 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1187 int level = 1;
1189 while (RTFGetToken (info) != rtfEOF)
1191 if (info->rtfClass == rtfGroup)
1193 if (info->rtfMajor == rtfBeginGroup) level++;
1194 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1196 RTFRouteToken(info);
1199 else RTFSkipGroup(info);
1200 continue;
1202 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1204 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1205 return;
1208 RTFRouteToken(info); /* feed "}" back to router */
1211 static void ME_RTFReadHook(RTF_Info *info) {
1212 switch(info->rtfClass)
1214 case rtfGroup:
1215 switch(info->rtfMajor)
1217 case rtfBeginGroup:
1218 if (info->stackTop < maxStack) {
1219 info->stack[info->stackTop].fmt = info->style->fmt;
1220 info->stack[info->stackTop].codePage = info->codePage;
1221 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1223 info->stackTop++;
1224 info->styleChanged = FALSE;
1225 break;
1226 case rtfEndGroup:
1228 ME_Style *s;
1229 RTFFlushOutputBuffer(info);
1230 info->stackTop--;
1231 if (info->stackTop<=0) {
1232 info->rtfClass = rtfEOF;
1233 return;
1235 assert(info->stackTop >= 0);
1236 if (info->styleChanged)
1238 /* FIXME too slow ? how come ? */
1239 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1240 ME_ReleaseStyle(info->style);
1241 info->style = s;
1242 info->codePage = info->stack[info->stackTop].codePage;
1243 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1245 break;
1248 break;
1249 case rtfControl:
1250 switch(info->rtfMajor)
1252 case rtfCharAttr:
1253 ME_RTFCharAttrHook(info);
1254 break;
1255 case rtfParAttr:
1256 ME_RTFParAttrHook(info);
1257 break;
1258 case rtfTblAttr:
1259 ME_RTFTblAttrHook(info);
1260 break;
1261 case rtfSpecialChar:
1262 ME_RTFSpecialCharHook(info);
1263 break;
1265 break;
1269 void
1270 ME_StreamInFill(ME_InStream *stream)
1272 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1273 (BYTE *)stream->buffer,
1274 sizeof(stream->buffer),
1275 (LONG *)&stream->dwSize);
1276 stream->dwUsed = 0;
1279 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1281 RTF_Info parser;
1282 ME_Style *style;
1283 int from, to, to2, nUndoMode;
1284 int nEventMask = editor->nEventMask;
1285 ME_InStream inStream;
1286 BOOL invalidRTF = FALSE;
1288 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1289 editor->nEventMask = 0;
1291 ME_GetSelection(editor, &from, &to);
1292 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1293 style = ME_GetSelectionInsertStyle(editor);
1295 ME_InternalDeleteText(editor, from, to-from, FALSE);
1297 else {
1298 ME_DisplayItem *para_item;
1299 style = editor->pBuffer->pDefaultStyle;
1300 ME_AddRefStyle(style);
1301 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1302 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
1303 from = to = 0;
1304 ME_ClearTempStyle(editor);
1306 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1307 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1311 /* Back up undo mode to a local variable */
1312 nUndoMode = editor->nUndoMode;
1314 /* Only create an undo if SFF_SELECTION is set */
1315 if (!(format & SFF_SELECTION))
1316 editor->nUndoMode = umIgnore;
1318 inStream.editstream = stream;
1319 inStream.editstream->dwError = 0;
1320 inStream.dwSize = 0;
1321 inStream.dwUsed = 0;
1323 if (format & SF_RTF)
1325 /* Check if it's really RTF, and if it is not, use plain text */
1326 ME_StreamInFill(&inStream);
1327 if (!inStream.editstream->dwError)
1329 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1330 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1332 invalidRTF = TRUE;
1333 inStream.editstream->dwError = -16;
1338 if (!invalidRTF && !inStream.editstream->dwError)
1340 if (format & SF_RTF) {
1341 ME_DisplayItem *para;
1343 /* setup the RTF parser */
1344 memset(&parser, 0, sizeof parser);
1345 RTFSetEditStream(&parser, &inStream);
1346 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1347 parser.hwndEdit = editor->hWnd;
1348 parser.editor = editor;
1349 parser.style = style;
1350 WriterInit(&parser);
1351 RTFInit(&parser);
1352 RTFSetReadHook(&parser, ME_RTFReadHook);
1353 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1354 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1355 if (!parser.editor->bEmulateVersion10) /* v4.1 */
1356 RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1357 BeginFile(&parser);
1359 /* do the parsing */
1360 RTFRead(&parser);
1361 RTFFlushOutputBuffer(&parser);
1362 if (!editor->bEmulateVersion10) { /* v4.1 */
1363 if (parser.tableDef && parser.tableDef->tableRowStart)
1365 /* Delete any incomplete table row at the end of the rich text. */
1366 int nOfs, nChars;
1367 ME_DisplayItem *pCell;
1369 para = parser.tableDef->tableRowStart;
1371 parser.rtfMinor = rtfRow;
1372 /* Complete the table row before deleting it.
1373 * By doing it this way we will have the current paragraph format set
1374 * properly to reflect that is not in the complete table, and undo items
1375 * will be added for this change to the current paragraph format. */
1376 if (parser.nestingLevel > 0)
1378 while (parser.nestingLevel--)
1379 ME_RTFSpecialCharHook(&parser);
1380 } else if (parser.canInheritInTbl) {
1381 ME_RTFSpecialCharHook(&parser);
1383 if (parser.tableDef && parser.tableDef->tableRowStart &&
1384 para->member.para.nFlags & MEPF_ROWEND)
1386 para = para->member.para.next_para;
1388 pCell = para->member.para.pCell;
1390 editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1391 editor->pCursors[1].nOffset = 0;
1392 nOfs = ME_GetCursorOfs(editor, 1);
1393 nChars = ME_GetCursorOfs(editor, 0) - nOfs;
1394 ME_InternalDeleteText(editor, nOfs, nChars, TRUE);
1395 parser.tableDef->tableRowStart = NULL;
1398 ME_CheckTablesForCorruption(editor);
1399 RTFDestroy(&parser);
1400 if (parser.lpRichEditOle)
1401 IRichEditOle_Release(parser.lpRichEditOle);
1403 if (!inStream.editstream->dwError && parser.stackTop > 0)
1404 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1406 /* Remove last line break, as mandated by tests. This is not affected by
1407 CR/LF counters, since RTF streaming presents only \para tokens, which
1408 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1410 if (stripLastCR) {
1411 int newfrom, newto;
1412 ME_GetSelection(editor, &newfrom, &newto);
1413 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1414 WCHAR lastchar[3] = {'\0', '\0'};
1415 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1417 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1418 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1419 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize, FALSE);
1424 style = parser.style;
1426 else if (format & SF_TEXT)
1427 ME_StreamInText(editor, format, &inStream, style);
1428 else
1429 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1430 ME_GetSelection(editor, &to, &to2);
1431 /* put the cursor at the top */
1432 if (!(format & SFF_SELECTION))
1433 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1436 /* Restore saved undo mode */
1437 editor->nUndoMode = nUndoMode;
1439 /* even if we didn't add an undo, we need to commit anything on the stack */
1440 ME_CommitUndo(editor);
1442 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1443 if (!(format & SFF_SELECTION))
1444 ME_EmptyUndoStack(editor);
1446 ME_ReleaseStyle(style);
1447 editor->nEventMask = nEventMask;
1448 ME_UpdateRepaint(editor);
1449 if (!(format & SFF_SELECTION)) {
1450 ME_ClearTempStyle(editor);
1452 HideCaret(editor->hWnd);
1453 ME_MoveCaret(editor);
1454 ShowCaret(editor->hWnd);
1455 ME_SendSelChange(editor);
1456 ME_SendRequestResize(editor, FALSE);
1458 return 0;
1462 typedef struct tagME_RTFStringStreamStruct
1464 char *string;
1465 int pos;
1466 int length;
1467 } ME_RTFStringStreamStruct;
1469 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1471 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1472 int count;
1474 count = min(cb, pStruct->length - pStruct->pos);
1475 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1476 pStruct->pos += count;
1477 *pcb = count;
1478 return 0;
1481 static void
1482 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1484 EDITSTREAM es;
1485 ME_RTFStringStreamStruct data;
1487 data.string = string;
1488 data.length = strlen(string);
1489 data.pos = 0;
1490 es.dwCookie = (DWORD)&data;
1491 es.pfnCallback = ME_ReadFromRTFString;
1492 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1496 ME_DisplayItem *
1497 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1499 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1500 int runLength;
1502 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1503 item = ME_FindItemFwd(item, diParagraph);
1505 if (!item)
1506 return item;
1508 nOffset -= item->member.para.nCharOfs;
1509 if (nItemType == diParagraph) {
1510 if (nItemOffset)
1511 *nItemOffset = nOffset;
1512 return item;
1515 do {
1516 item = ME_FindItemFwd(item, diRun);
1517 runLength = ME_StrLen(item->member.run.strText);
1518 if (item->member.run.nFlags & MERF_ENDPARA)
1519 runLength = item->member.run.nCR + item->member.run.nLF;
1520 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1521 if (item) {
1522 nOffset -= item->member.run.nCharOfs;
1524 /* Special case: nOffset may not point exactly at the division between the
1525 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1526 into the next run, if one exists
1528 if ( item->member.run.nFlags & MERF_ENDPARA
1529 && nOffset == item->member.run.nCR
1530 && item->member.run.nLF > 0) {
1531 ME_DisplayItem *nextItem;
1532 nextItem = ME_FindItemFwd(item, diRun);
1533 if (nextItem) {
1534 nOffset = 0;
1535 item = nextItem;
1538 if (nItemOffset)
1539 *nItemOffset = nOffset;
1541 return item;
1545 static int
1546 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1548 const int nLen = lstrlenW(text);
1549 const int nTextLen = ME_GetTextLength(editor);
1550 int nStart, nEnd;
1551 int nMin, nMax;
1552 ME_DisplayItem *item;
1553 ME_DisplayItem *para;
1554 WCHAR wLastChar = ' ';
1556 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1557 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1559 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1560 FIXME("Flags 0x%08x not implemented\n",
1561 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1563 nMin = chrg->cpMin;
1564 if (chrg->cpMax == -1)
1565 nMax = nTextLen;
1566 else
1567 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1569 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1570 if (editor->bEmulateVersion10 && nMax == nTextLen)
1572 flags |= FR_DOWN;
1575 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1576 if (editor->bEmulateVersion10 && nMax < nMin)
1578 if (chrgText)
1580 chrgText->cpMin = -1;
1581 chrgText->cpMax = -1;
1583 return -1;
1586 /* when searching up, if cpMin < cpMax, then instead of searching
1587 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1588 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1589 * case, it is always bigger than cpMin.
1591 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1593 int nSwap = nMax;
1595 nMax = nMin > nTextLen ? nTextLen : nMin;
1596 if (nMin < nSwap || chrg->cpMax == -1)
1597 nMin = 0;
1598 else
1599 nMin = nSwap;
1602 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1604 if (chrgText)
1605 chrgText->cpMin = chrgText->cpMax = -1;
1606 return -1;
1609 if (flags & FR_DOWN) /* Forward search */
1611 /* If possible, find the character before where the search starts */
1612 if ((flags & FR_WHOLEWORD) && nMin)
1614 nStart = nMin - 1;
1615 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1616 if (!item)
1618 if (chrgText)
1619 chrgText->cpMin = chrgText->cpMax = -1;
1620 return -1;
1622 wLastChar = item->member.run.strText->szData[nStart];
1625 nStart = nMin;
1626 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1627 if (!item)
1629 if (chrgText)
1630 chrgText->cpMin = chrgText->cpMax = -1;
1631 return -1;
1634 para = ME_GetParagraph(item);
1635 while (item
1636 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1638 ME_DisplayItem *pCurItem = item;
1639 int nCurStart = nStart;
1640 int nMatched = 0;
1642 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1644 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1645 break;
1647 nMatched++;
1648 if (nMatched == nLen)
1650 ME_DisplayItem *pNextItem = pCurItem;
1651 int nNextStart = nCurStart;
1652 WCHAR wNextChar;
1654 /* Check to see if next character is a whitespace */
1655 if (flags & FR_WHOLEWORD)
1657 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1659 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1660 nNextStart = -nMatched;
1663 if (pNextItem)
1664 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1665 else
1666 wNextChar = ' ';
1668 if (isalnumW(wNextChar))
1669 break;
1672 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1673 if (chrgText)
1675 chrgText->cpMin = nStart;
1676 chrgText->cpMax = nStart + nLen;
1678 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1679 return nStart;
1681 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1683 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1684 para = ME_GetParagraph(pCurItem);
1685 nCurStart = -nMatched;
1688 if (pCurItem)
1689 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1690 else
1691 wLastChar = ' ';
1693 nStart++;
1694 if (nStart == ME_StrLen(item->member.run.strText))
1696 item = ME_FindItemFwd(item, diRun);
1697 para = ME_GetParagraph(item);
1698 nStart = 0;
1702 else /* Backward search */
1704 /* If possible, find the character after where the search ends */
1705 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1707 nEnd = nMax + 1;
1708 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1709 if (!item)
1711 if (chrgText)
1712 chrgText->cpMin = chrgText->cpMax = -1;
1713 return -1;
1715 wLastChar = item->member.run.strText->szData[nEnd];
1718 nEnd = nMax;
1719 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1720 if (!item)
1722 if (chrgText)
1723 chrgText->cpMin = chrgText->cpMax = -1;
1724 return -1;
1727 para = ME_GetParagraph(item);
1729 while (item
1730 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1732 ME_DisplayItem *pCurItem = item;
1733 int nCurEnd = nEnd;
1734 int nMatched = 0;
1736 if (nCurEnd - nMatched == 0)
1738 pCurItem = ME_FindItemBack(pCurItem, diRun);
1739 para = ME_GetParagraph(pCurItem);
1740 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1743 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1745 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1746 break;
1748 nMatched++;
1749 if (nMatched == nLen)
1751 ME_DisplayItem *pPrevItem = pCurItem;
1752 int nPrevEnd = nCurEnd;
1753 WCHAR wPrevChar;
1755 /* Check to see if previous character is a whitespace */
1756 if (flags & FR_WHOLEWORD)
1758 if (nPrevEnd - nMatched == 0)
1760 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1761 if (pPrevItem)
1762 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1765 if (pPrevItem)
1766 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1767 else
1768 wPrevChar = ' ';
1770 if (isalnumW(wPrevChar))
1771 break;
1774 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1775 if (chrgText)
1777 chrgText->cpMin = nStart;
1778 chrgText->cpMax = nStart + nLen;
1780 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1781 return nStart;
1783 if (nCurEnd - nMatched == 0)
1785 pCurItem = ME_FindItemBack(pCurItem, diRun);
1786 /* Don't care about pCurItem becoming NULL here; it's already taken
1787 * care of in the exterior loop condition */
1788 para = ME_GetParagraph(pCurItem);
1789 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1792 if (pCurItem)
1793 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1794 else
1795 wLastChar = ' ';
1797 nEnd--;
1798 if (nEnd < 0)
1800 item = ME_FindItemBack(item, diRun);
1801 para = ME_GetParagraph(item);
1802 nEnd = ME_StrLen(item->member.run.strText);
1806 TRACE("not found\n");
1807 if (chrgText)
1808 chrgText->cpMin = chrgText->cpMax = -1;
1809 return -1;
1812 /* helper to send a msg filter notification */
1813 static BOOL
1814 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1816 MSGFILTER msgf;
1818 msgf.nmhdr.hwndFrom = editor->hWnd;
1819 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1820 msgf.nmhdr.code = EN_MSGFILTER;
1821 msgf.msg = msg;
1823 msgf.wParam = *wParam;
1824 msgf.lParam = *lParam;
1825 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1826 return FALSE;
1827 *wParam = msgf.wParam;
1828 *lParam = msgf.lParam;
1829 msgf.wParam = *wParam;
1831 return TRUE;
1834 static BOOL
1835 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1837 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1838 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1840 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1841 editor->nSelectionType = stPosition;
1843 switch (nKey)
1845 case VK_LEFT:
1846 case VK_RIGHT:
1847 case VK_HOME:
1848 case VK_END:
1849 editor->nUDArrowX = -1;
1850 /* fall through */
1851 case VK_UP:
1852 case VK_DOWN:
1853 case VK_PRIOR:
1854 case VK_NEXT:
1855 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1856 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1857 return TRUE;
1858 case VK_BACK:
1859 case VK_DELETE:
1860 editor->nUDArrowX = -1;
1861 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1862 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1863 return FALSE;
1864 if (ME_IsSelection(editor))
1866 ME_DeleteSelection(editor);
1867 ME_CommitUndo(editor);
1869 else if (nKey == VK_DELETE)
1871 /* Delete stops group typing.
1872 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1873 ME_DeleteTextAtCursor(editor, 1, 1);
1874 ME_CommitUndo(editor);
1876 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1878 BOOL bDeletionSucceeded;
1879 /* Backspace can be grouped for a single undo */
1880 ME_ContinueCoalescingTransaction(editor);
1881 bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
1882 if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
1883 /* Deletion was prevented so the cursor is moved back to where it was.
1884 * (e.g. this happens when trying to delete cell boundaries)
1886 ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
1888 ME_CommitCoalescingUndo(editor);
1890 else
1891 return TRUE;
1892 ME_UpdateSelectionLinkAttribute(editor);
1893 ME_UpdateRepaint(editor);
1894 ME_SendRequestResize(editor, FALSE);
1895 return TRUE;
1897 default:
1898 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1899 editor->nUDArrowX = -1;
1900 if (ctrl_is_down)
1902 if (nKey == 'W')
1904 CHARFORMAT2W chf;
1905 char buf[2048];
1906 chf.cbSize = sizeof(chf);
1908 ME_GetSelectionCharFormat(editor, &chf);
1909 ME_DumpStyleToBuf(&chf, buf);
1910 MessageBoxA(NULL, buf, "Style dump", MB_OK);
1912 if (nKey == 'Q')
1914 ME_CheckCharOffsets(editor);
1918 return FALSE;
1921 /* Process the message and calculate the new click count.
1923 * returns: The click count if it is mouse down event, else returns 0. */
1924 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
1925 LPARAM lParam)
1927 static int clickNum = 0;
1928 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
1929 return 0;
1931 if ((msg == WM_LBUTTONDBLCLK) ||
1932 (msg == WM_RBUTTONDBLCLK) ||
1933 (msg == WM_MBUTTONDBLCLK) ||
1934 (msg == WM_XBUTTONDBLCLK))
1936 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1939 if ((msg == WM_LBUTTONDOWN) ||
1940 (msg == WM_RBUTTONDOWN) ||
1941 (msg == WM_MBUTTONDOWN) ||
1942 (msg == WM_XBUTTONDOWN))
1944 static MSG prevClickMsg;
1945 MSG clickMsg;
1946 clickMsg.hwnd = hWnd;
1947 clickMsg.message = msg;
1948 clickMsg.wParam = wParam;
1949 clickMsg.lParam = lParam;
1950 clickMsg.time = GetMessageTime();
1951 clickMsg.pt.x = (short)LOWORD(lParam);
1952 clickMsg.pt.y = (short)HIWORD(lParam);
1953 if ((clickNum != 0) &&
1954 (clickMsg.message == prevClickMsg.message) &&
1955 (clickMsg.hwnd == prevClickMsg.hwnd) &&
1956 (clickMsg.wParam == prevClickMsg.wParam) &&
1957 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
1958 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1959 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1961 clickNum++;
1962 } else {
1963 clickNum = 1;
1965 prevClickMsg = clickMsg;
1966 } else {
1967 return 0;
1969 return clickNum;
1972 static BOOL ME_SetCursor(ME_TextEditor *editor)
1974 POINT pt;
1975 BOOL isExact;
1976 int offset;
1977 DWORD messagePos = GetMessagePos();
1978 pt.x = (short)LOWORD(messagePos);
1979 pt.y = (short)HIWORD(messagePos);
1980 ScreenToClient(editor->hWnd, &pt);
1981 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1982 (pt.x < editor->selofs ||
1983 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
1985 SetCursor(hLeft);
1986 return TRUE;
1988 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
1989 if (isExact)
1991 if (editor->AutoURLDetect_bEnable)
1993 ME_Cursor cursor;
1994 ME_Run *run;
1995 ME_CursorFromCharOfs(editor, offset, &cursor);
1996 run = &cursor.pRun->member.run;
1997 if (editor->AutoURLDetect_bEnable &&
1998 run->style->fmt.dwMask & CFM_LINK &&
1999 run->style->fmt.dwEffects & CFE_LINK)
2001 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
2002 return TRUE;
2005 if (ME_IsSelection(editor))
2007 int selStart, selEnd;
2008 ME_GetSelection(editor, &selStart, &selEnd);
2009 if (selStart <= offset && selEnd >= offset) {
2010 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
2011 return TRUE;
2015 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
2016 return TRUE;
2019 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2021 CHARRANGE selrange;
2022 HMENU menu;
2023 int seltype = 0;
2024 if(!editor->lpOleCallback)
2025 return FALSE;
2026 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
2027 if(selrange.cpMin == selrange.cpMax)
2028 seltype |= SEL_EMPTY;
2029 else
2031 /* FIXME: Handle objects */
2032 seltype |= SEL_TEXT;
2033 if(selrange.cpMax-selrange.cpMin > 1)
2034 seltype |= SEL_MULTICHAR;
2036 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2038 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2039 DestroyMenu(menu);
2041 return TRUE;
2044 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
2045 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2046 int i;
2047 ed->hWnd = hWnd;
2048 ed->bEmulateVersion10 = FALSE;
2049 ed->pBuffer = ME_MakeText();
2050 ed->nZoomNumerator = ed->nZoomDenominator = 0;
2051 ME_MakeFirstParagraph(ed);
2052 /* The four cursors are for:
2053 * 0 - The position where the caret is shown
2054 * 1 - The anchored end of the selection (for normal selection)
2055 * 2 & 3 - The anchored start and end respectively for word, line,
2056 * or paragraph selection.
2058 ed->nCursors = 4;
2059 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2060 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2061 ed->pCursors[0].nOffset = 0;
2062 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
2063 ed->pCursors[1].nOffset = 0;
2064 ed->pCursors[2] = ed->pCursors[0];
2065 ed->pCursors[3] = ed->pCursors[1];
2066 ed->nLastTotalLength = ed->nTotalLength = 0;
2067 ed->nHeight = 0;
2068 ed->nUDArrowX = -1;
2069 ed->nSequence = 0;
2070 ed->rgbBackColor = -1;
2071 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2072 ed->bCaretAtEnd = FALSE;
2073 ed->nEventMask = 0;
2074 ed->nModifyStep = 0;
2075 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2076 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2077 ed->nUndoStackSize = 0;
2078 ed->nUndoLimit = STACK_SIZE_DEFAULT;
2079 ed->nUndoMode = umAddToUndo;
2080 ed->nParagraphs = 1;
2081 ed->nLastSelStart = ed->nLastSelEnd = 0;
2082 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
2083 ed->bRedraw = TRUE;
2084 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
2085 ed->bHideSelection = FALSE;
2086 ed->nInvalidOfs = -1;
2087 ed->pfnWordBreak = NULL;
2088 ed->lpOleCallback = NULL;
2089 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2090 ed->AutoURLDetect_bEnable = FALSE;
2091 ed->bHaveFocus = FALSE;
2092 for (i=0; i<HFONT_CACHE_SIZE; i++)
2094 ed->pFontCache[i].nRefs = 0;
2095 ed->pFontCache[i].nAge = 0;
2096 ed->pFontCache[i].hFont = NULL;
2099 ME_CheckCharOffsets(ed);
2100 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
2101 ed->selofs = SELECTIONBAR_WIDTH;
2102 else
2103 ed->selofs = 0;
2104 ed->nSelectionType = stPosition;
2106 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
2107 ed->cPasswordMask = '*';
2108 else
2109 ed->cPasswordMask = 0;
2111 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2113 /* Default vertical scrollbar information */
2114 ed->vert_si.cbSize = sizeof(SCROLLINFO);
2115 ed->vert_si.nMin = 0;
2116 ed->vert_si.nMax = 0;
2117 ed->vert_si.nPage = 0;
2118 ed->vert_si.nPos = 0;
2120 OleInitialize(NULL);
2122 return ed;
2125 typedef struct tagME_GlobalDestStruct
2127 HGLOBAL hData;
2128 int nLength;
2129 } ME_GlobalDestStruct;
2131 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2133 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2134 int i;
2135 WORD *pSrc, *pDest;
2137 cb = cb >> 1;
2138 pDest = (WORD *)lpBuff;
2139 pSrc = (WORD *)GlobalLock(pData->hData);
2140 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2141 pDest[i] = pSrc[pData->nLength+i];
2143 pData->nLength += i;
2144 *pcb = 2*i;
2145 GlobalUnlock(pData->hData);
2146 return 0;
2149 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
2151 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
2152 int i;
2153 BYTE *pSrc, *pDest;
2155 pDest = lpBuff;
2156 pSrc = (BYTE *)GlobalLock(pData->hData);
2157 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
2158 pDest[i] = pSrc[pData->nLength+i];
2160 pData->nLength += i;
2161 *pcb = i;
2162 GlobalUnlock(pData->hData);
2163 return 0;
2167 void ME_DestroyEditor(ME_TextEditor *editor)
2169 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2170 ME_DisplayItem *p = pFirst, *pNext = NULL;
2171 int i;
2173 ME_ClearTempStyle(editor);
2174 ME_EmptyUndoStack(editor);
2175 while(p) {
2176 pNext = p->next;
2177 ME_DestroyDisplayItem(p);
2178 p = pNext;
2180 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2181 for (i=0; i<HFONT_CACHE_SIZE; i++)
2183 if (editor->pFontCache[i].hFont)
2184 DeleteObject(editor->pFontCache[i].hFont);
2186 if (editor->rgbBackColor != -1)
2187 DeleteObject(editor->hbrBackground);
2188 if(editor->lpOleCallback)
2189 IUnknown_Release(editor->lpOleCallback);
2190 OleUninitialize();
2192 FREE_OBJ(editor->pBuffer);
2193 FREE_OBJ(editor->pCursors);
2195 FREE_OBJ(editor);
2198 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2200 TRACE("\n");
2201 switch (fdwReason)
2203 case DLL_PROCESS_ATTACH:
2204 DisableThreadLibraryCalls(hinstDLL);
2205 me_heap = HeapCreate (0, 0x10000, 0);
2206 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2207 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2208 LookupInit();
2209 break;
2211 case DLL_PROCESS_DETACH:
2212 UnregisterClassW(RichEdit20W, 0);
2213 UnregisterClassW(RichEdit50W, 0);
2214 UnregisterClassA("RichEdit20A", 0);
2215 UnregisterClassA("RichEdit50A", 0);
2216 if (ME_ListBoxRegistered)
2217 UnregisterClassW(REListBox20W, 0);
2218 if (ME_ComboBoxRegistered)
2219 UnregisterClassW(REComboBox20W, 0);
2220 LookupCleanup();
2221 HeapDestroy (me_heap);
2222 me_heap = NULL;
2223 break;
2225 return TRUE;
2229 #define UNSUPPORTED_MSG(e) \
2230 case e: \
2231 FIXME(#e ": stub\n"); \
2232 return DefWindowProcW(hWnd, msg, wParam, lParam);
2234 static const char * const edit_messages[] = {
2235 "EM_GETSEL",
2236 "EM_SETSEL",
2237 "EM_GETRECT",
2238 "EM_SETRECT",
2239 "EM_SETRECTNP",
2240 "EM_SCROLL",
2241 "EM_LINESCROLL",
2242 "EM_SCROLLCARET",
2243 "EM_GETMODIFY",
2244 "EM_SETMODIFY",
2245 "EM_GETLINECOUNT",
2246 "EM_LINEINDEX",
2247 "EM_SETHANDLE",
2248 "EM_GETHANDLE",
2249 "EM_GETTHUMB",
2250 "EM_UNKNOWN_BF",
2251 "EM_UNKNOWN_C0",
2252 "EM_LINELENGTH",
2253 "EM_REPLACESEL",
2254 "EM_UNKNOWN_C3",
2255 "EM_GETLINE",
2256 "EM_LIMITTEXT",
2257 "EM_CANUNDO",
2258 "EM_UNDO",
2259 "EM_FMTLINES",
2260 "EM_LINEFROMCHAR",
2261 "EM_UNKNOWN_CA",
2262 "EM_SETTABSTOPS",
2263 "EM_SETPASSWORDCHAR",
2264 "EM_EMPTYUNDOBUFFER",
2265 "EM_GETFIRSTVISIBLELINE",
2266 "EM_SETREADONLY",
2267 "EM_SETWORDBREAKPROC",
2268 "EM_GETWORDBREAKPROC",
2269 "EM_GETPASSWORDCHAR",
2270 "EM_SETMARGINS",
2271 "EM_GETMARGINS",
2272 "EM_GETLIMITTEXT",
2273 "EM_POSFROMCHAR",
2274 "EM_CHARFROMPOS"
2277 static const char * const richedit_messages[] = {
2278 "EM_CANPASTE",
2279 "EM_DISPLAYBAND",
2280 "EM_EXGETSEL",
2281 "EM_EXLIMITTEXT",
2282 "EM_EXLINEFROMCHAR",
2283 "EM_EXSETSEL",
2284 "EM_FINDTEXT",
2285 "EM_FORMATRANGE",
2286 "EM_GETCHARFORMAT",
2287 "EM_GETEVENTMASK",
2288 "EM_GETOLEINTERFACE",
2289 "EM_GETPARAFORMAT",
2290 "EM_GETSELTEXT",
2291 "EM_HIDESELECTION",
2292 "EM_PASTESPECIAL",
2293 "EM_REQUESTRESIZE",
2294 "EM_SELECTIONTYPE",
2295 "EM_SETBKGNDCOLOR",
2296 "EM_SETCHARFORMAT",
2297 "EM_SETEVENTMASK",
2298 "EM_SETOLECALLBACK",
2299 "EM_SETPARAFORMAT",
2300 "EM_SETTARGETDEVICE",
2301 "EM_STREAMIN",
2302 "EM_STREAMOUT",
2303 "EM_GETTEXTRANGE",
2304 "EM_FINDWORDBREAK",
2305 "EM_SETOPTIONS",
2306 "EM_GETOPTIONS",
2307 "EM_FINDTEXTEX",
2308 "EM_GETWORDBREAKPROCEX",
2309 "EM_SETWORDBREAKPROCEX",
2310 "EM_SETUNDOLIMIT",
2311 "EM_UNKNOWN_USER_83",
2312 "EM_REDO",
2313 "EM_CANREDO",
2314 "EM_GETUNDONAME",
2315 "EM_GETREDONAME",
2316 "EM_STOPGROUPTYPING",
2317 "EM_SETTEXTMODE",
2318 "EM_GETTEXTMODE",
2319 "EM_AUTOURLDETECT",
2320 "EM_GETAUTOURLDETECT",
2321 "EM_SETPALETTE",
2322 "EM_GETTEXTEX",
2323 "EM_GETTEXTLENGTHEX",
2324 "EM_SHOWSCROLLBAR",
2325 "EM_SETTEXTEX",
2326 "EM_UNKNOWN_USER_98",
2327 "EM_UNKNOWN_USER_99",
2328 "EM_SETPUNCTUATION",
2329 "EM_GETPUNCTUATION",
2330 "EM_SETWORDWRAPMODE",
2331 "EM_GETWORDWRAPMODE",
2332 "EM_SETIMECOLOR",
2333 "EM_GETIMECOLOR",
2334 "EM_SETIMEOPTIONS",
2335 "EM_GETIMEOPTIONS",
2336 "EM_CONVPOSITION",
2337 "EM_UNKNOWN_USER_109",
2338 "EM_UNKNOWN_USER_110",
2339 "EM_UNKNOWN_USER_111",
2340 "EM_UNKNOWN_USER_112",
2341 "EM_UNKNOWN_USER_113",
2342 "EM_UNKNOWN_USER_114",
2343 "EM_UNKNOWN_USER_115",
2344 "EM_UNKNOWN_USER_116",
2345 "EM_UNKNOWN_USER_117",
2346 "EM_UNKNOWN_USER_118",
2347 "EM_UNKNOWN_USER_119",
2348 "EM_SETLANGOPTIONS",
2349 "EM_GETLANGOPTIONS",
2350 "EM_GETIMECOMPMODE",
2351 "EM_FINDTEXTW",
2352 "EM_FINDTEXTEXW",
2353 "EM_RECONVERSION",
2354 "EM_SETIMEMODEBIAS",
2355 "EM_GETIMEMODEBIAS"
2358 static const char *
2359 get_msg_name(UINT msg)
2361 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2362 return edit_messages[msg - EM_GETSEL];
2363 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2364 return richedit_messages[msg - EM_CANPASTE];
2365 return "";
2368 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2369 LPARAM lParam, BOOL unicode)
2371 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2373 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2374 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2376 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2377 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2378 return 0;
2381 switch(msg) {
2383 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2384 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2385 UNSUPPORTED_MSG(EM_FMTLINES)
2386 UNSUPPORTED_MSG(EM_FORMATRANGE)
2387 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2388 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2389 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2390 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2391 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2392 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2393 UNSUPPORTED_MSG(EM_GETREDONAME)
2394 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2395 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2396 UNSUPPORTED_MSG(EM_GETUNDONAME)
2397 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2398 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2399 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2400 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2401 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2402 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2403 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2404 UNSUPPORTED_MSG(EM_SETPALETTE)
2405 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2406 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2407 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2408 UNSUPPORTED_MSG(WM_STYLECHANGING)
2409 UNSUPPORTED_MSG(WM_STYLECHANGED)
2411 /* Messages specific to Richedit controls */
2413 case EM_STREAMIN:
2414 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2415 case EM_STREAMOUT:
2416 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2417 case WM_GETDLGCODE:
2419 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2420 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2422 int vk = (int)((LPMSG)lParam)->wParam;
2423 /* if style says we want return key */
2424 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2426 code |= DLGC_WANTMESSAGE;
2428 /* we always handle ctrl-tab */
2429 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2431 code |= DLGC_WANTMESSAGE;
2434 return code;
2436 case WM_NCCREATE:
2438 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2439 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2440 editor = ME_MakeEditor(hWnd);
2441 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2442 return TRUE;
2444 case EM_EMPTYUNDOBUFFER:
2445 ME_EmptyUndoStack(editor);
2446 return 0;
2447 case EM_GETSEL:
2449 /* Note: wParam/lParam can be NULL */
2450 UINT from, to;
2451 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2452 PUINT pto = lParam ? (PUINT)lParam : &to;
2453 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2454 if ((*pfrom|*pto) & 0xFFFF0000)
2455 return -1;
2456 return MAKELONG(*pfrom,*pto);
2458 case EM_EXGETSEL:
2460 CHARRANGE *pRange = (CHARRANGE *)lParam;
2461 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2462 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2463 return 0;
2465 case EM_SETUNDOLIMIT:
2467 if ((int)wParam < 0)
2468 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2469 else
2470 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2471 /* Setting a max stack size keeps wine from getting killed
2472 for hogging memory. Windows allocates all this memory at once, so
2473 no program would realistically set a value above our maximum. */
2474 return editor->nUndoLimit;
2476 case EM_CANUNDO:
2477 return editor->pUndoStack != NULL;
2478 case EM_CANREDO:
2479 return editor->pRedoStack != NULL;
2480 case WM_UNDO: /* FIXME: actually not the same */
2481 case EM_UNDO:
2482 return ME_Undo(editor);
2483 case EM_REDO:
2484 return ME_Redo(editor);
2485 case EM_GETOPTIONS:
2487 /* these flags are equivalent to the ES_* counterparts */
2488 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2489 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2490 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2492 return settings;
2494 case EM_SETOPTIONS:
2496 /* these flags are equivalent to ES_* counterparts
2497 * ECO_READONLY is already implemented in the code, only requires
2498 * setting the bit to work
2500 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2501 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2502 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2503 DWORD settings = mask & raw;
2505 switch(wParam)
2507 case ECOOP_SET:
2508 settings = lParam;
2509 break;
2510 case ECOOP_OR:
2511 settings |= lParam;
2512 break;
2513 case ECOOP_AND:
2514 settings &= lParam;
2515 break;
2516 case ECOOP_XOR:
2517 settings ^= lParam;
2519 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2521 if (settings & ECO_AUTOWORDSELECTION)
2522 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2523 if (settings & ECO_SELECTIONBAR)
2524 editor->selofs = SELECTIONBAR_WIDTH;
2525 else
2526 editor->selofs = 0;
2527 ME_WrapMarkedParagraphs(editor);
2529 if (settings & ECO_VERTICAL)
2530 FIXME("ECO_VERTICAL not implemented yet!\n");
2531 if (settings & ECO_AUTOHSCROLL)
2532 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2533 if (settings & ECO_AUTOVSCROLL)
2534 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2535 if (settings & ECO_NOHIDESEL)
2536 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2537 if (settings & ECO_WANTRETURN)
2538 FIXME("ECO_WANTRETURN not implemented yet!\n");
2540 return settings;
2542 case EM_SETSEL:
2544 ME_InvalidateSelection(editor);
2545 ME_SetSelection(editor, wParam, lParam);
2546 ME_InvalidateSelection(editor);
2547 HideCaret(editor->hWnd);
2548 ME_ShowCaret(editor);
2549 ME_SendSelChange(editor);
2550 return 0;
2552 case EM_SETSCROLLPOS:
2554 POINT *point = (POINT *)lParam;
2555 ME_ScrollAbs(editor, point->y);
2556 return 0;
2558 case EM_AUTOURLDETECT:
2560 if (wParam==1 || wParam ==0)
2562 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2563 return 0;
2565 return E_INVALIDARG;
2567 case EM_GETAUTOURLDETECT:
2569 return editor->AutoURLDetect_bEnable;
2571 case EM_EXSETSEL:
2573 int end;
2574 CHARRANGE range = *(CHARRANGE *)lParam;
2576 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2578 ME_InvalidateSelection(editor);
2579 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2580 ME_InvalidateSelection(editor);
2581 HideCaret(editor->hWnd);
2582 ME_ShowCaret(editor);
2583 ME_SendSelChange(editor);
2585 return end;
2587 case EM_SHOWSCROLLBAR:
2589 ShowScrollBar(editor->hWnd, wParam, lParam);
2590 return 0;
2592 case EM_SETTEXTEX:
2594 LPWSTR wszText;
2595 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2596 size_t len;
2597 int from, to;
2598 ME_Style *style;
2599 int oldModify = editor->nModifyStep;
2601 if (!pStruct) return 0;
2603 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2604 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2605 pStruct->flags, pStruct->codepage);
2607 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2608 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2609 len = wszText ? lstrlenW(wszText) : 0;
2611 if (pStruct->flags & ST_SELECTION) {
2612 ME_GetSelection(editor, &from, &to);
2613 style = ME_GetSelectionInsertStyle(editor);
2614 ME_InternalDeleteText(editor, from, to - from, FALSE);
2615 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2616 ME_StreamInRTFString(editor, 1, (char *)lParam);
2617 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2618 ME_ReleaseStyle(style);
2620 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2622 else {
2623 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2624 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2625 ME_StreamInRTFString(editor, 0, (char *)lParam);
2626 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2627 len = 1;
2629 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2631 ME_CommitUndo(editor);
2632 if (!(pStruct->flags & ST_KEEPUNDO))
2634 editor->nModifyStep = oldModify;
2635 ME_EmptyUndoStack(editor);
2637 ME_UpdateRepaint(editor);
2638 return len;
2640 case EM_SETBKGNDCOLOR:
2642 LRESULT lColor;
2643 if (editor->rgbBackColor != -1) {
2644 DeleteObject(editor->hbrBackground);
2645 lColor = editor->rgbBackColor;
2647 else lColor = GetSysColor(COLOR_WINDOW);
2649 if (wParam)
2651 editor->rgbBackColor = -1;
2652 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2654 else
2656 editor->rgbBackColor = lParam;
2657 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2659 if (editor->bRedraw)
2661 InvalidateRect(hWnd, NULL, TRUE);
2662 UpdateWindow(hWnd);
2664 return lColor;
2666 case EM_GETMODIFY:
2667 return editor->nModifyStep == 0 ? 0 : -1;
2668 case EM_SETMODIFY:
2670 if (wParam)
2671 editor->nModifyStep = 1;
2672 else
2673 editor->nModifyStep = 0;
2675 return 0;
2677 case EM_SETREADONLY:
2679 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2680 if (wParam)
2681 nStyle |= ES_READONLY;
2682 else
2683 nStyle &= ~ES_READONLY;
2684 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2685 return 0;
2687 case EM_SETEVENTMASK:
2689 DWORD nOldMask = editor->nEventMask;
2691 editor->nEventMask = lParam;
2692 return nOldMask;
2694 case EM_GETEVENTMASK:
2695 return editor->nEventMask;
2696 case EM_SETCHARFORMAT:
2698 CHARFORMAT2W buf, *p;
2699 BOOL bRepaint = TRUE;
2700 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2701 if (p == NULL) return 0;
2702 if (!wParam)
2703 ME_SetDefaultCharFormat(editor, p);
2704 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2705 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2706 return 0;
2707 } else if (wParam == SCF_ALL) {
2708 if (editor->mode & TM_PLAINTEXT)
2709 ME_SetDefaultCharFormat(editor, p);
2710 else {
2711 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2712 editor->nModifyStep = 1;
2714 } else if (editor->mode & TM_PLAINTEXT) {
2715 return 0;
2716 } else {
2717 int from, to;
2718 ME_GetSelection(editor, &from, &to);
2719 bRepaint = (from != to);
2720 ME_SetSelectionCharFormat(editor, p);
2721 if (from != to) editor->nModifyStep = 1;
2723 ME_CommitUndo(editor);
2724 if (bRepaint)
2725 ME_RewrapRepaint(editor);
2726 return 1;
2728 case EM_GETCHARFORMAT:
2730 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2731 if (dst->cbSize != sizeof(CHARFORMATA) &&
2732 dst->cbSize != sizeof(CHARFORMATW) &&
2733 dst->cbSize != sizeof(CHARFORMAT2A) &&
2734 dst->cbSize != sizeof(CHARFORMAT2W))
2735 return 0;
2736 tmp.cbSize = sizeof(tmp);
2737 if (!wParam)
2738 ME_GetDefaultCharFormat(editor, &tmp);
2739 else
2740 ME_GetSelectionCharFormat(editor, &tmp);
2741 ME_CopyToCFAny(dst, &tmp);
2742 return tmp.dwMask;
2744 case EM_SETPARAFORMAT:
2746 BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2747 ME_RewrapRepaint(editor);
2748 ME_CommitUndo(editor);
2749 return result;
2751 case EM_GETPARAFORMAT:
2752 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2753 return ((PARAFORMAT2 *)lParam)->dwMask;
2754 case EM_GETFIRSTVISIBLELINE:
2756 ME_DisplayItem *p = editor->pBuffer->pFirst;
2757 int y = ME_GetYScrollPos(editor);
2758 int ypara = 0;
2759 int count = 0;
2760 int ystart, yend;
2761 while(p) {
2762 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2763 if (p->type == diTextEnd)
2764 break;
2765 if (p->type == diParagraph) {
2766 ypara = p->member.para.pt.y;
2767 continue;
2769 ystart = ypara + p->member.row.pt.y;
2770 yend = ystart + p->member.row.nHeight;
2771 if (y < yend) {
2772 break;
2774 count++;
2776 return count;
2778 case EM_HIDESELECTION:
2780 editor->bHideSelection = (wParam != 0);
2781 ME_InvalidateSelection(editor);
2782 return 0;
2784 case EM_LINESCROLL:
2786 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2787 return TRUE; /* Should return false if a single line richedit control */
2789 case WM_CLEAR:
2791 int from, to;
2792 ME_GetSelection(editor, &from, &to);
2793 ME_InternalDeleteText(editor, from, to-from, FALSE);
2794 ME_CommitUndo(editor);
2795 ME_UpdateRepaint(editor);
2796 return 0;
2798 case EM_REPLACESEL:
2800 int from, to;
2801 ME_Style *style;
2802 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2803 size_t len = wszText ? lstrlenW(wszText) : 0;
2804 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2806 ME_GetSelection(editor, &from, &to);
2807 style = ME_GetSelectionInsertStyle(editor);
2808 ME_InternalDeleteText(editor, from, to-from, FALSE);
2809 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2810 ME_ReleaseStyle(style);
2811 /* drop temporary style if line end */
2813 * FIXME question: does abc\n mean: put abc,
2814 * clear temp style, put \n? (would require a change)
2816 if (len>0 && wszText[len-1] == '\n')
2817 ME_ClearTempStyle(editor);
2818 ME_EndToUnicode(unicode, wszText);
2819 ME_CommitUndo(editor);
2820 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2821 if (!wParam)
2822 ME_EmptyUndoStack(editor);
2823 ME_UpdateRepaint(editor);
2824 return len;
2826 case EM_SCROLLCARET:
2828 int top, bottom; /* row's edges relative to document top */
2829 int nPos;
2830 ME_DisplayItem *para, *row;
2832 nPos = ME_GetYScrollPos(editor);
2833 row = ME_RowStart(editor->pCursors[0].pRun);
2834 para = ME_GetParagraph(row);
2835 top = para->member.para.pt.y + row->member.row.pt.y;
2836 bottom = top + row->member.row.nHeight;
2838 if (top < nPos) /* caret above window */
2839 ME_ScrollAbs(editor, top);
2840 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2841 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2842 return 0;
2844 case WM_SETFONT:
2846 LOGFONTW lf;
2847 CHARFORMAT2W fmt;
2848 HDC hDC;
2849 BOOL bRepaint = LOWORD(lParam);
2851 if (!wParam)
2852 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2853 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2854 hDC = GetDC(hWnd);
2855 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2856 ReleaseDC(hWnd, hDC);
2857 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2858 ME_SetDefaultCharFormat(editor, &fmt);
2860 ME_CommitUndo(editor);
2861 if (bRepaint)
2862 ME_RewrapRepaint(editor);
2863 return 0;
2865 case WM_SETTEXT:
2867 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor), FALSE);
2868 if (lParam)
2870 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2871 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2873 /* Undocumented: WM_SETTEXT supports RTF text */
2874 ME_StreamInRTFString(editor, 0, (char *)lParam);
2876 else
2878 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2879 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2880 if (lstrlenW(wszText) > 0)
2882 int len = -1;
2884 /* uses default style! */
2885 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2887 WCHAR * p;
2889 p = wszText;
2890 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2891 len = p - wszText;
2893 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2895 ME_EndToUnicode(unicode, wszText);
2898 else
2899 TRACE("WM_SETTEXT - NULL\n");
2900 if (editor->AutoURLDetect_bEnable)
2902 ME_UpdateLinkAttribute(editor, 0, -1);
2904 ME_SetSelection(editor, 0, 0);
2905 editor->nModifyStep = 0;
2906 ME_CommitUndo(editor);
2907 ME_EmptyUndoStack(editor);
2908 ME_UpdateRepaint(editor);
2909 return 1;
2911 case EM_CANPASTE:
2913 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2914 if (IsClipboardFormatAvailable(nRTFFormat))
2915 return TRUE;
2916 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2917 return TRUE;
2918 return FALSE;
2920 case WM_PASTE:
2922 DWORD dwFormat = 0;
2923 EDITSTREAM es;
2924 ME_GlobalDestStruct gds;
2925 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2926 UINT cf = 0;
2928 if (IsClipboardFormatAvailable(nRTFFormat))
2929 cf = nRTFFormat, dwFormat = SF_RTF;
2930 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2931 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2932 else
2933 return 0;
2935 if (!OpenClipboard(hWnd))
2936 return 0;
2937 gds.hData = GetClipboardData(cf);
2938 gds.nLength = 0;
2939 es.dwCookie = (DWORD)&gds;
2940 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2941 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2943 CloseClipboard();
2944 return 0;
2946 case WM_CUT:
2947 case WM_COPY:
2949 LPDATAOBJECT dataObj = NULL;
2950 CHARRANGE range;
2951 HRESULT hr = S_OK;
2953 if (editor->cPasswordMask)
2954 return 0; /* Copying or Cutting masked text isn't allowed */
2956 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2957 if(editor->lpOleCallback)
2958 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2959 if(FAILED(hr) || !dataObj)
2960 hr = ME_GetDataObject(editor, &range, &dataObj);
2961 if(SUCCEEDED(hr)) {
2962 hr = OleSetClipboard(dataObj);
2963 IDataObject_Release(dataObj);
2965 if (SUCCEEDED(hr) && msg == WM_CUT)
2967 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin, FALSE);
2968 ME_CommitUndo(editor);
2969 ME_UpdateRepaint(editor);
2971 return 0;
2973 case WM_GETTEXTLENGTH:
2975 GETTEXTLENGTHEX how;
2977 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2978 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2979 how.codepage = unicode ? 1200 : CP_ACP;
2980 return ME_GetTextLengthEx(editor, &how);
2982 case EM_GETTEXTLENGTHEX:
2983 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2984 case WM_GETTEXT:
2986 GETTEXTEX ex;
2987 LRESULT rc;
2988 LPSTR bufferA = NULL;
2989 LPWSTR bufferW = NULL;
2991 if (unicode)
2992 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2993 else
2994 bufferA = heap_alloc(wParam + 2);
2996 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2997 ex.flags = GT_USECRLF;
2998 ex.codepage = unicode ? 1200 : CP_ACP;
2999 ex.lpDefaultChar = NULL;
3000 ex.lpUsedDefChar = NULL;
3001 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
3003 if (unicode)
3005 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
3006 if (lstrlenW(bufferW) >= wParam) rc = 0;
3008 else
3010 memcpy((LPSTR)lParam, bufferA, wParam);
3011 if (strlen(bufferA) >= wParam) rc = 0;
3013 heap_free(bufferA);
3014 heap_free(bufferW);
3015 return rc;
3017 case EM_GETTEXTEX:
3019 GETTEXTEX *ex = (GETTEXTEX*)wParam;
3020 int nStart, nCount; /* in chars */
3022 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
3023 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
3025 if (ex->flags & GT_SELECTION)
3027 ME_GetSelection(editor, &nStart, &nCount);
3028 nCount -= nStart;
3030 else
3032 nStart = 0;
3033 nCount = 0x7fffffff;
3035 if (ex->codepage == 1200)
3037 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
3038 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
3040 else
3042 /* potentially each char may be a CR, why calculate the exact value with O(N) when
3043 we can just take a bigger buffer? :)
3044 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
3045 occurs only in richedit 2.0 mode, in which line breaks have only one CR
3047 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
3048 LPWSTR buffer;
3049 DWORD buflen = ex->cb;
3050 LRESULT rc;
3051 DWORD flags = 0;
3053 nCount = min(nCount, ex->cb - 1);
3054 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
3056 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
3057 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
3058 if (rc) rc--; /* do not count 0 terminator */
3060 heap_free(buffer);
3061 return rc;
3064 case EM_GETSELTEXT:
3066 int from, to;
3067 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
3068 ME_GetSelection(editor, &from, &to);
3069 tr.chrg.cpMin = from;
3070 tr.chrg.cpMax = to;
3071 tr.lpstrText = (WCHAR *)lParam;
3072 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
3074 case EM_GETSCROLLPOS:
3076 POINT *point = (POINT *)lParam;
3077 point->x = 0; /* FIXME side scrolling not implemented */
3078 point->y = ME_GetYScrollPos(editor);
3079 return 1;
3081 case EM_GETTEXTRANGE:
3083 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3084 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
3085 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
3086 editor->bEmulateVersion10, ME_GetTextLength(editor));
3087 if (unicode)
3088 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
3089 else
3091 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
3092 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
3093 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
3094 /* FIXME this is a potential security hole (buffer overrun)
3095 if you know more about wchar->mbyte conversion please explain
3097 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
3098 FREE_OBJ(p);
3099 return nChars;
3102 case EM_GETLINE:
3104 ME_DisplayItem *run;
3105 const unsigned int nMaxChars = *(WORD *) lParam;
3106 unsigned int nCharsLeft = nMaxChars;
3107 char *dest = (char *) lParam;
3108 BOOL wroteNull = FALSE;
3110 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3111 unicode ? "Unicode" : "Ansi");
3113 run = ME_FindRowWithNumber(editor, wParam);
3114 if (run == NULL)
3115 return 0;
3117 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3118 && !(run->member.run.nFlags & MERF_ENDPARA))
3120 unsigned int nCopy;
3121 ME_String *strText;
3122 if (run->type != diRun)
3123 break;
3124 strText = run->member.run.strText;
3125 nCopy = min(nCharsLeft, strText->nLen);
3127 if (unicode)
3128 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
3129 else
3130 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3131 nCharsLeft, NULL, NULL);
3132 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3133 nCharsLeft -= nCopy;
3136 /* append line termination, space allowing */
3137 if (nCharsLeft > 0)
3139 if (run && (run->member.run.nFlags & MERF_ENDPARA))
3141 unsigned int i;
3142 /* Write as many \r as encoded in end-of-paragraph, space allowing */
3143 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
3145 *((WCHAR *)dest) = '\r';
3146 dest += unicode ? sizeof(WCHAR) : 1;
3148 /* Write as many \n as encoded in end-of-paragraph, space allowing */
3149 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
3151 *((WCHAR *)dest) = '\n';
3152 dest += unicode ? sizeof(WCHAR) : 1;
3155 if (nCharsLeft > 0)
3157 if (unicode)
3158 *((WCHAR *)dest) = '\0';
3159 else
3160 *dest = '\0';
3161 nCharsLeft--;
3162 wroteNull = TRUE;
3166 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3167 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3169 case EM_GETLINECOUNT:
3171 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3172 int nRows = 0;
3174 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3176 while (item != editor->pBuffer->pLast)
3178 assert(item->type == diParagraph);
3179 prev_para = ME_FindItemBack(item, diRun);
3180 if (prev_para) {
3181 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3183 nRows += item->member.para.nRows;
3184 item = item->member.para.next_para;
3186 last_para = ME_FindItemBack(item, diRun);
3187 assert(last_para);
3188 assert(last_para->member.run.nFlags & MERF_ENDPARA);
3189 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
3190 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
3192 /* In 1.0 emulation, the last solitary \r at the very end of the text
3193 (if one exists) is NOT a line break.
3194 FIXME: this is an ugly hack. This should have a more regular model. */
3195 nRows--;
3198 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3199 return max(1, nRows);
3201 case EM_LINEFROMCHAR:
3203 if (wParam == -1)
3204 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
3205 else
3206 return ME_RowNumberFromCharOfs(editor, wParam);
3208 case EM_EXLINEFROMCHAR:
3210 if (lParam == -1)
3211 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
3212 else
3213 return ME_RowNumberFromCharOfs(editor, lParam);
3215 case EM_LINEINDEX:
3217 ME_DisplayItem *item, *para;
3218 int nCharOfs;
3220 if (wParam == -1)
3221 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3222 else
3223 item = ME_FindRowWithNumber(editor, wParam);
3224 if (!item)
3225 return -1;
3226 para = ME_GetParagraph(item);
3227 item = ME_FindItemFwd(item, diRun);
3228 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3229 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3230 return nCharOfs;
3232 case EM_LINELENGTH:
3234 ME_DisplayItem *item, *item_end;
3235 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3237 if (wParam > ME_GetTextLength(editor))
3238 return 0;
3239 if (wParam == -1)
3241 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3242 return 0;
3244 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
3245 item = ME_RowStart(item);
3246 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
3247 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3248 if (item_end->type == diStartRow)
3249 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
3250 else
3252 ME_DisplayItem *endPara;
3254 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
3255 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
3256 endPara = ME_FindItemBack(endPara, diRun);
3257 assert(endPara);
3258 assert(endPara->type == diRun);
3259 assert(endPara->member.run.nFlags & MERF_ENDPARA);
3260 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
3262 nChars = nNextLineOfs - nThisLineOfs;
3263 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3264 return nChars;
3266 case EM_EXLIMITTEXT:
3268 if ((int)lParam < 0)
3269 return 0;
3270 if (lParam == 0)
3271 editor->nTextLimit = 65536;
3272 else
3273 editor->nTextLimit = (int) lParam;
3274 return 0;
3276 case EM_LIMITTEXT:
3278 if (wParam == 0)
3279 editor->nTextLimit = 65536;
3280 else
3281 editor->nTextLimit = (int) wParam;
3282 return 0;
3284 case EM_GETLIMITTEXT:
3286 return editor->nTextLimit;
3288 case EM_FINDTEXT:
3290 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3291 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3292 WCHAR *tmp;
3293 LRESULT r;
3295 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3296 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3297 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3298 FREE_OBJ( tmp );
3299 return r;
3301 case EM_FINDTEXTEX:
3303 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3304 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3305 WCHAR *tmp;
3306 LRESULT r;
3308 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3309 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3310 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3311 FREE_OBJ( tmp );
3312 return r;
3314 case EM_FINDTEXTW:
3316 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3317 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3319 case EM_FINDTEXTEXW:
3321 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3322 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3324 case EM_GETZOOM:
3325 if (!wParam || !lParam)
3326 return FALSE;
3327 *(int *)wParam = editor->nZoomNumerator;
3328 *(int *)lParam = editor->nZoomDenominator;
3329 return TRUE;
3330 case EM_SETZOOM:
3331 return ME_SetZoom(editor, wParam, lParam);
3332 case EM_CHARFROMPOS:
3333 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3334 case EM_POSFROMCHAR:
3336 ME_DisplayItem *pRun;
3337 int nCharOfs, nOffset, nLength;
3338 POINTL pt = {0,0};
3339 SCROLLINFO si;
3341 nCharOfs = wParam;
3342 /* detect which API version we're dealing with */
3343 if (wParam >= 0x40000)
3344 nCharOfs = lParam;
3345 nLength = ME_GetTextLength(editor);
3347 if (nCharOfs < nLength) {
3348 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3349 assert(pRun->type == diRun);
3350 pt.y = pRun->member.run.pt.y;
3351 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3352 pt.y += ME_GetParagraph(pRun)->member.para.pt.y;
3353 } else {
3354 pt.x = 0;
3355 pt.y = editor->pBuffer->pLast->member.para.pt.y;
3357 pt.x += editor->selofs;
3359 si.cbSize = sizeof(si);
3360 si.fMask = SIF_POS;
3361 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3362 si.cbSize = sizeof(si);
3363 si.fMask = SIF_POS;
3364 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3366 if (wParam >= 0x40000) {
3367 *(POINTL *)wParam = pt;
3369 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3371 case WM_CREATE:
3373 SCROLLINFO si;
3375 GetClientRect(hWnd, &editor->rcFormat);
3376 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3377 { /* Squelch the default horizontal scrollbar it would make */
3378 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3381 si.cbSize = sizeof(si);
3382 si.fMask = SIF_PAGE | SIF_RANGE;
3383 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3384 si.fMask |= SIF_DISABLENOSCROLL;
3385 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3386 si.nMin = 0;
3387 si.nPage = 0;
3388 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3390 ME_CommitUndo(editor);
3391 ME_WrapMarkedParagraphs(editor);
3392 ME_MoveCaret(editor);
3393 return 0;
3395 case WM_DESTROY:
3396 ME_DestroyEditor(editor);
3397 SetWindowLongPtrW(hWnd, 0, 0);
3398 return 0;
3399 case WM_SETCURSOR:
3401 return ME_SetCursor(editor);
3403 case WM_LBUTTONDBLCLK:
3404 case WM_LBUTTONDOWN:
3406 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3407 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3408 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3409 return 0;
3410 SetFocus(hWnd);
3411 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3412 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3413 SetCapture(hWnd);
3414 ME_LinkNotify(editor,msg,wParam,lParam);
3415 if (!ME_SetCursor(editor)) goto do_default;
3416 break;
3418 case WM_MOUSEMOVE:
3419 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3420 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3421 return 0;
3422 if (GetCapture() == hWnd)
3423 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3424 ME_LinkNotify(editor,msg,wParam,lParam);
3425 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3426 if (GetCapture() == hWnd)
3427 ME_SetCursor(editor);
3428 break;
3429 case WM_LBUTTONUP:
3430 if (GetCapture() == hWnd)
3431 ReleaseCapture();
3432 if (editor->nSelectionType == stDocument)
3433 editor->nSelectionType = stPosition;
3434 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3435 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3436 return 0;
3437 else
3439 ME_SetCursor(editor);
3440 ME_LinkNotify(editor,msg,wParam,lParam);
3442 break;
3443 case WM_RBUTTONUP:
3444 case WM_RBUTTONDOWN:
3445 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3446 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3447 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3448 return 0;
3449 goto do_default;
3450 case WM_CONTEXTMENU:
3451 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3452 goto do_default;
3453 break;
3454 case WM_PAINT:
3455 if (editor->bRedraw)
3457 HDC hDC;
3458 PAINTSTRUCT ps;
3460 hDC = BeginPaint(hWnd, &ps);
3461 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3462 EndPaint(hWnd, &ps);
3464 break;
3465 case WM_SETFOCUS:
3466 editor->bHaveFocus = TRUE;
3467 ME_ShowCaret(editor);
3468 ME_SendOldNotify(editor, EN_SETFOCUS);
3469 return 0;
3470 case WM_KILLFOCUS:
3471 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3472 editor->bHaveFocus = FALSE;
3473 ME_HideCaret(editor);
3474 ME_SendOldNotify(editor, EN_KILLFOCUS);
3475 return 0;
3476 case WM_ERASEBKGND:
3478 if (editor->bRedraw)
3480 HDC hDC = (HDC)wParam;
3481 RECT rc;
3482 if (GetUpdateRect(hWnd,&rc,TRUE))
3484 FillRect(hDC, &rc, editor->hbrBackground);
3487 return 1;
3489 case WM_COMMAND:
3490 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3491 return 0;
3492 case WM_KEYUP:
3493 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3494 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3495 return 0;
3496 goto do_default;
3497 case WM_KEYDOWN:
3498 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3499 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3500 return 0;
3501 if (ME_KeyDown(editor, LOWORD(wParam)))
3502 return 0;
3503 goto do_default;
3504 case WM_CHAR:
3506 WCHAR wstr;
3508 if (unicode)
3509 wstr = (WCHAR)wParam;
3510 else
3512 CHAR charA = wParam;
3513 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3516 switch (wstr)
3518 case 1: /* Ctrl-A */
3519 ME_SetSelection(editor, 0, -1);
3520 return 0;
3521 case 3: /* Ctrl-C */
3522 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3523 return 0;
3526 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3527 MessageBeep(MB_ICONERROR);
3528 return 0; /* FIXME really 0 ? */
3531 switch (wstr)
3533 case 22: /* Ctrl-V */
3534 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3535 return 0;
3536 case 24: /* Ctrl-X */
3537 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3538 return 0;
3539 case 25: /* Ctrl-Y */
3540 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3541 return 0;
3542 case 26: /* Ctrl-Z */
3543 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3544 return 0;
3546 if (((unsigned)wstr)>=' '
3547 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3548 || wstr=='\t') {
3549 int from, to;
3550 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
3551 ME_GetSelection(editor, &from, &to);
3552 if (wstr=='\t'
3553 /* v4.1 allows tabs to be inserted with ctrl key down */
3554 && !(ctrl_is_down && !editor->bEmulateVersion10)
3557 ME_Cursor cursor = editor->pCursors[0];
3558 ME_DisplayItem *para;
3559 BOOL bSelectedRow = FALSE;
3561 para = ME_GetParagraph(cursor.pRun);
3562 if (ME_IsSelection(editor) &&
3563 cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
3564 para->member.para.prev_para->type == diParagraph)
3566 para = para->member.para.prev_para;
3567 bSelectedRow = TRUE;
3569 if (ME_IsInTable(para))
3571 ME_TabPressedInTable(editor, bSelectedRow);
3572 ME_CommitUndo(editor);
3573 return 0;
3576 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3577 /* WM_CHAR is restricted to nTextLimit */
3578 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3580 ME_Style *style = ME_GetInsertStyle(editor, 0);
3581 ME_SaveTempStyle(editor);
3582 ME_ContinueCoalescingTransaction(editor);
3583 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3584 ME_InsertEndRowFromCursor(editor, 0);
3585 else
3586 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3587 ME_ReleaseStyle(style);
3588 ME_CommitCoalescingUndo(editor);
3589 SetCursor(NULL);
3592 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3594 ME_UpdateRepaint(editor);
3596 return 0;
3598 case WM_UNICHAR:
3599 if (unicode)
3601 if(wParam == UNICODE_NOCHAR) return TRUE;
3602 if(wParam <= 0x000fffff)
3604 if(wParam > 0xffff) /* convert to surrogates */
3606 wParam -= 0x10000;
3607 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3608 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3610 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3612 return 0;
3614 break;
3615 case EM_STOPGROUPTYPING:
3616 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3617 return 0;
3618 case EM_SCROLL: /* fall through */
3619 case WM_VSCROLL:
3621 int origNPos;
3622 int lineHeight;
3624 origNPos = ME_GetYScrollPos(editor);
3625 lineHeight = 24;
3627 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3628 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3629 if (lineHeight <= 0) lineHeight = 24;
3631 switch(LOWORD(wParam))
3633 case SB_LINEUP:
3634 ME_ScrollUp(editor,lineHeight);
3635 break;
3636 case SB_LINEDOWN:
3637 ME_ScrollDown(editor,lineHeight);
3638 break;
3639 case SB_PAGEUP:
3640 ME_ScrollUp(editor,editor->sizeWindow.cy);
3641 break;
3642 case SB_PAGEDOWN:
3643 ME_ScrollDown(editor,editor->sizeWindow.cy);
3644 break;
3645 case SB_THUMBTRACK:
3646 case SB_THUMBPOSITION:
3647 ME_ScrollAbs(editor,HIWORD(wParam));
3648 break;
3650 if (msg == EM_SCROLL)
3651 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3652 break;
3654 case WM_MOUSEWHEEL:
3656 int gcWheelDelta;
3657 UINT pulScrollLines;
3659 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3660 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3661 return 0;
3663 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3664 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3666 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3668 /* FIXME follow the original */
3669 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3671 break;
3673 case EM_GETRECT:
3675 *((RECT *)lParam) = editor->rcFormat;
3676 return 0;
3678 case EM_SETRECT:
3679 case EM_SETRECTNP:
3681 if (lParam)
3683 RECT *rc = (RECT *)lParam;
3685 if (wParam)
3687 editor->rcFormat.left += rc->left;
3688 editor->rcFormat.top += rc->top;
3689 editor->rcFormat.right += rc->right;
3690 editor->rcFormat.bottom += rc->bottom;
3692 else
3694 editor->rcFormat = *rc;
3697 else
3699 GetClientRect(hWnd, &editor->rcFormat);
3701 if (msg != EM_SETRECTNP)
3702 ME_RewrapRepaint(editor);
3703 return 0;
3705 case EM_REQUESTRESIZE:
3706 ME_SendRequestResize(editor, TRUE);
3707 return 0;
3708 case WM_SETREDRAW:
3709 if ((editor->bRedraw = wParam))
3710 ME_RewrapRepaint(editor);
3711 return 0;
3712 case WM_SIZE:
3714 GetClientRect(hWnd, &editor->rcFormat);
3715 ME_RewrapRepaint(editor);
3716 return DefWindowProcW(hWnd, msg, wParam, lParam);
3718 /* IME messages to make richedit controls IME aware */
3719 case WM_IME_SETCONTEXT:
3720 case WM_IME_CONTROL:
3721 case WM_IME_SELECT:
3722 case WM_IME_COMPOSITIONFULL:
3723 return 0;
3724 case WM_IME_STARTCOMPOSITION:
3726 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3727 ME_DeleteSelection(editor);
3728 ME_CommitUndo(editor);
3729 ME_UpdateRepaint(editor);
3730 return 0;
3732 case WM_IME_COMPOSITION:
3734 HIMC hIMC;
3736 ME_Style *style = ME_GetInsertStyle(editor, 0);
3737 hIMC = ImmGetContext(hWnd);
3738 ME_DeleteSelection(editor);
3739 ME_CommitUndo(editor);
3740 ME_SaveTempStyle(editor);
3741 if (lParam & GCS_RESULTSTR)
3743 LPWSTR lpCompStr = NULL;
3744 DWORD dwBufLen;
3746 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3747 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3748 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3749 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3750 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3752 else if (lParam & GCS_COMPSTR)
3754 LPWSTR lpCompStr = NULL;
3755 DWORD dwBufLen;
3757 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3758 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3759 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3760 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3762 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3763 ME_SetSelection(editor,editor->imeStartIndex,
3764 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3766 ME_ReleaseStyle(style);
3767 ME_UpdateRepaint(editor);
3768 return 0;
3770 case WM_IME_ENDCOMPOSITION:
3772 ME_DeleteSelection(editor);
3773 editor->imeStartIndex=-1;
3774 return 0;
3776 case EM_GETOLEINTERFACE:
3778 LPVOID *ppvObj = (LPVOID*) lParam;
3779 return CreateIRichEditOle(editor, ppvObj);
3781 case EM_GETPASSWORDCHAR:
3783 return editor->cPasswordMask;
3785 case EM_SETOLECALLBACK:
3786 if(editor->lpOleCallback)
3787 IUnknown_Release(editor->lpOleCallback);
3788 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3789 if(editor->lpOleCallback)
3790 IUnknown_AddRef(editor->lpOleCallback);
3791 return TRUE;
3792 case EM_GETWORDBREAKPROC:
3793 return (LRESULT)editor->pfnWordBreak;
3794 case EM_SETWORDBREAKPROC:
3796 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3798 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3799 return (LRESULT)pfnOld;
3801 case EM_SETTEXTMODE:
3803 LRESULT ret;
3804 int mask = 0;
3805 int changes = 0;
3806 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3807 if (!ret)
3809 /*Check for valid wParam*/
3810 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3811 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3812 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3813 return 1;
3814 else
3816 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3818 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3819 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3821 /*FIXME: Currently no support for undo level and code page options*/
3822 editor->mode = (editor->mode & (~mask)) | changes;
3823 return 0;
3826 return ret;
3828 case EM_SETPASSWORDCHAR:
3830 editor->cPasswordMask = wParam;
3831 ME_RewrapRepaint(editor);
3832 return 0;
3834 case EM_SETTARGETDEVICE:
3835 if (wParam == 0)
3837 BOOL new = (lParam == 0);
3838 if (editor->bWordWrap != new)
3840 editor->bWordWrap = new;
3841 ME_RewrapRepaint(editor);
3844 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3845 break;
3846 default:
3847 do_default:
3848 return DefWindowProcW(hWnd, msg, wParam, lParam);
3850 return 0L;
3853 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3855 BOOL unicode = TRUE;
3857 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3858 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3859 unicode = FALSE;
3861 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3864 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3866 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3869 /******************************************************************
3870 * RichEditANSIWndProc (RICHED20.10)
3872 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3874 return RichEditWndProcA(hWnd, msg, wParam, lParam);
3877 /******************************************************************
3878 * RichEdit10ANSIWndProc (RICHED20.9)
3880 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3882 LRESULT result;
3884 /* FIXME: this is NOT the same as 2.0 version */
3885 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3886 if (msg == WM_NCCREATE)
3888 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3890 editor->bEmulateVersion10 = TRUE;
3891 editor->pBuffer->pLast->member.para.nCharOfs = 2;
3892 assert(editor->pBuffer->pLast->prev->type == diRun);
3893 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3894 editor->pBuffer->pLast->prev->member.run.nLF = 1;
3896 return result;
3899 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3901 HWND hWnd = editor->hWnd;
3902 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3905 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3907 int x,y;
3908 ME_Cursor tmpCursor;
3909 BOOL isExact;
3910 int nCharOfs; /* The start of the clicked text. Absolute character offset */
3912 ME_Run *tmpRun;
3914 ENLINK info;
3915 x = (short)LOWORD(lParam);
3916 y = (short)HIWORD(lParam);
3917 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
3918 if (!isExact) return;
3920 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3921 tmpRun = &tmpCursor.pRun->member.run;
3923 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3924 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3925 { /* The clicked run has CFE_LINK set */
3926 info.nmhdr.hwndFrom = editor->hWnd;
3927 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3928 info.nmhdr.code = EN_LINK;
3929 info.msg = msg;
3930 info.wParam = wParam;
3931 info.lParam = lParam;
3932 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3933 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3934 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3938 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3940 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3941 int i = 0;
3943 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3944 item = item->member.para.next_para;
3945 if (!item)
3946 return 0;
3947 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3948 item = item->member.para.next_para;
3949 i++;
3951 return i;
3955 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3957 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3958 int nWritten = 0;
3959 WCHAR *pStart = buffer;
3961 if (!item) {
3962 *buffer = 0;
3963 return 0;
3966 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3967 if (editor->bEmulateVersion10) bCRLF = 0;
3969 if (nStart)
3971 int nLen = ME_StrLen(item->member.run.strText) - nStart;
3972 if (nLen > nChars)
3973 nLen = nChars;
3974 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3975 nChars -= nLen;
3976 nWritten += nLen;
3977 buffer += nLen;
3978 if (!nChars) {
3979 *buffer = 0;
3980 return nWritten;
3982 nStart = 0;
3983 item = ME_FindItemFwd(item, diRun);
3986 while(nChars && item)
3988 int nLen = ME_StrLen(item->member.run.strText);
3989 if (item->member.run.nFlags & MERF_ENDPARA)
3990 nLen = item->member.run.nCR + item->member.run.nLF;
3991 if (nLen > nChars)
3992 nLen = nChars;
3994 if (item->member.run.nFlags & MERF_ENDCELL &&
3995 item->member.run.nFlags & MERF_ENDPARA)
3997 *buffer = '\t';
3999 else if (item->member.run.nFlags & MERF_ENDPARA)
4001 if (!ME_FindItemFwd(item, diRun))
4002 /* No '\r' is appended to the last paragraph. */
4003 nLen = 0;
4004 else if (bCRLF && nChars == 1) {
4005 nLen = 0;
4006 nChars = 0;
4007 } else {
4008 if (bCRLF)
4010 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
4011 if (ME_GetParagraph(item)->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
4012 assert(nLen == 2);
4013 else
4014 assert(nLen == 1);
4015 *buffer++ = '\r';
4016 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
4017 if (nLen == 1)
4018 nWritten++;
4019 else
4020 buffer--;
4022 else
4024 int i, j;
4026 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
4027 i = 0;
4028 while (nChars - i > 0 && i < item->member.run.nCR)
4030 buffer[i] = '\r'; i++;
4032 j = 0;
4033 while (nChars - i - j > 0 && j < item->member.run.nLF)
4035 buffer[i+j] = '\n'; j++;
4040 else
4041 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
4042 nChars -= nLen;
4043 nWritten += nLen;
4044 buffer += nLen;
4046 if (!nChars)
4048 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4049 *buffer = 0;
4050 return nWritten;
4052 item = ME_FindItemFwd(item, diRun);
4054 *buffer = 0;
4055 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
4056 return nWritten;
4059 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4061 WNDCLASSW wcW;
4062 WNDCLASSA wcA;
4064 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4065 wcW.lpfnWndProc = RichEditWndProcW;
4066 wcW.cbClsExtra = 0;
4067 wcW.cbWndExtra = sizeof(ME_TextEditor *);
4068 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4069 wcW.hIcon = NULL;
4070 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4071 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4072 wcW.lpszMenuName = NULL;
4074 if (is_version_nt())
4076 wcW.lpszClassName = RichEdit20W;
4077 if (!RegisterClassW(&wcW)) return FALSE;
4078 wcW.lpszClassName = RichEdit50W;
4079 if (!RegisterClassW(&wcW)) return FALSE;
4081 else
4083 /* WNDCLASSA/W have the same layout */
4084 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4085 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4086 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4087 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4090 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4091 wcA.lpfnWndProc = RichEditWndProcA;
4092 wcA.cbClsExtra = 0;
4093 wcA.cbWndExtra = sizeof(ME_TextEditor *);
4094 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4095 wcA.hIcon = NULL;
4096 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4097 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
4098 wcA.lpszMenuName = NULL;
4099 wcA.lpszClassName = "RichEdit20A";
4100 if (!RegisterClassA(&wcA)) return FALSE;
4101 wcA.lpszClassName = "RichEdit50A";
4102 if (!RegisterClassA(&wcA)) return FALSE;
4104 return TRUE;
4107 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4108 /* FIXME: Not implemented */
4109 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4110 hWnd, msg, get_msg_name(msg), wParam, lParam);
4111 return DefWindowProcW(hWnd, msg, wParam, lParam);
4114 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4115 /* FIXME: Not implemented */
4116 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4117 hWnd, msg, get_msg_name(msg), wParam, lParam);
4118 return DefWindowProcW(hWnd, msg, wParam, lParam);
4121 /******************************************************************
4122 * REExtendedRegisterClass (RICHED20.8)
4124 * FIXME undocumented
4125 * Need to check for errors and implement controls and callbacks
4127 LRESULT WINAPI REExtendedRegisterClass(void)
4129 WNDCLASSW wcW;
4130 UINT result;
4132 FIXME("semi stub\n");
4134 wcW.cbClsExtra = 0;
4135 wcW.cbWndExtra = 4;
4136 wcW.hInstance = NULL;
4137 wcW.hIcon = NULL;
4138 wcW.hCursor = NULL;
4139 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4140 wcW.lpszMenuName = NULL;
4142 if (!ME_ListBoxRegistered)
4144 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4145 wcW.lpfnWndProc = REListWndProc;
4146 wcW.lpszClassName = REListBox20W;
4147 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4150 if (!ME_ComboBoxRegistered)
4152 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4153 wcW.lpfnWndProc = REComboWndProc;
4154 wcW.lpszClassName = REComboBox20W;
4155 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
4158 result = 0;
4159 if (ME_ListBoxRegistered)
4160 result += 1;
4161 if (ME_ComboBoxRegistered)
4162 result += 2;
4164 return result;
4167 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
4169 struct prefix_s {
4170 const char *text;
4171 int length;
4172 } prefixes[12] = {
4173 {"http:", 5},
4174 {"file:", 6},
4175 {"mailto:", 8},
4176 {"ftp:", 5},
4177 {"https:", 7},
4178 {"gopher:", 8},
4179 {"nntp:", 6},
4180 {"prospero:", 10},
4181 {"telnet:", 8},
4182 {"news:", 6},
4183 {"wais:", 6},
4184 {"www.", 5}
4186 CHARRANGE ins_pt;
4187 int curf_ef, link_ef, def_ef;
4188 int cur_prefx, prefx_cnt;
4189 int sel_min, sel_max;
4190 int car_pos = 0;
4191 int text_pos=-1;
4192 int URLmin, URLmax = 0;
4193 FINDTEXTA ft;
4194 CHARFORMAT2W cur_format;
4195 CHARFORMAT2W default_format;
4196 CHARFORMAT2W link;
4197 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
4198 sel_min = ins_pt.cpMin;
4199 sel_max = ins_pt.cpMax;
4200 if (sel_min==sel_max)
4201 car_pos = sel_min;
4202 if (sel_min!=sel_max)
4203 car_pos = ME_GetTextLength(editor)+1;
4204 cur_format.cbSize = sizeof(cur_format);
4205 default_format.cbSize = sizeof(default_format);
4206 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
4207 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
4208 link.cbSize = sizeof(link);
4209 link.dwMask = CFM_LINK;
4210 link.dwEffects = CFE_LINK;
4211 curf_ef = cur_format.dwEffects & link.dwEffects;
4212 def_ef = default_format.dwEffects & link.dwEffects;
4213 link_ef = link.dwEffects & link.dwEffects;
4214 if (curf_ef == link_ef)
4216 if( curChar == '\n' || curChar=='\r' || curChar==' ')
4218 ME_SetSelection(editor, car_pos, car_pos);
4219 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
4220 text_pos=-1;
4221 return 0;
4224 if (curf_ef == def_ef)
4226 cur_prefx = 0;
4227 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
4228 while (cur_prefx<=prefx_cnt)
4230 if (text_pos == -1)
4232 ft.lpstrText = prefixes[cur_prefx].text;
4233 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
4234 URLmax=max(0, car_pos);
4235 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
4237 URLmax = ME_GetTextLength(editor)+1;
4239 ft.chrg.cpMin = URLmin;
4240 ft.chrg.cpMax = URLmax;
4241 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
4242 cur_prefx++;
4244 if (text_pos != -1)
4246 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
4247 ME_RewrapRepaint(editor);
4248 break;
4252 return 0;
4256 static BOOL isurlspecial(WCHAR c)
4258 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4259 return strchrW( special_chars, c ) != NULL;
4263 * This proc takes a selection, and scans it forward in order to select the span
4264 * of a possible URL candidate. A possible URL candidate must start with isalnum
4265 * or one of the following special characters: *|/\+%#@ and must consist entirely
4266 * of the characters allowed to start the URL, plus : (colon) which may occur
4267 * at most once, and not at either end.
4269 * sel_max == -1 indicates scan to end of text.
4271 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
4272 int * candidate_min, int * candidate_max)
4274 ME_DisplayItem * item;
4275 ME_DisplayItem * para;
4276 int nStart;
4277 BOOL foundColon = FALSE;
4278 WCHAR lastAcceptedChar = '\0';
4280 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
4282 *candidate_min = *candidate_max = -1;
4283 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
4284 if (!item) return FALSE;
4285 TRACE("nStart = %d\n", nStart);
4286 para = ME_GetParagraph(item);
4287 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4288 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
4290 ME_DisplayItem * next_item;
4292 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
4293 /* Find start of candidate */
4294 if (*candidate_min == -1) {
4295 while (nStart < ME_StrLen(item->member.run.strText) &&
4296 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4297 isurlspecial(item->member.run.strText->szData[nStart]))) {
4298 nStart++;
4300 if (nStart < ME_StrLen(item->member.run.strText) &&
4301 (isalnumW(item->member.run.strText->szData[nStart]) ||
4302 isurlspecial(item->member.run.strText->szData[nStart]))) {
4303 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4304 lastAcceptedChar = item->member.run.strText->szData[nStart];
4305 nStart++;
4309 /* Find end of candidate */
4310 if (*candidate_min >= 0) {
4311 while (nStart < ME_StrLen(item->member.run.strText) &&
4312 (isalnumW(item->member.run.strText->szData[nStart]) ||
4313 isurlspecial(item->member.run.strText->szData[nStart]) ||
4314 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4315 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4316 lastAcceptedChar = item->member.run.strText->szData[nStart];
4317 nStart++;
4319 if (nStart < ME_StrLen(item->member.run.strText) &&
4320 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4321 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4322 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4323 nStart++;
4324 if (lastAcceptedChar == ':') (*candidate_max)--;
4325 return TRUE;
4328 } else {
4329 /* End of paragraph: skip it if before candidate span, or terminates
4330 current active span */
4331 if (*candidate_min >= 0) {
4332 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4333 if (lastAcceptedChar == ':') (*candidate_max)--;
4334 return TRUE;
4338 /* Reaching this point means no span was found, so get next span */
4339 next_item = ME_FindItemFwd(item, diRun);
4340 if (!next_item) {
4341 if (*candidate_min >= 0) {
4342 /* There are no further runs, so take end of text as end of candidate */
4343 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4344 if (lastAcceptedChar == ':') (*candidate_max)--;
4345 return TRUE;
4348 item = next_item;
4349 para = ME_GetParagraph(item);
4350 nStart = 0;
4353 if (item) {
4354 if (*candidate_min >= 0) {
4355 /* There are no further runs, so take end of text as end of candidate */
4356 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4357 if (lastAcceptedChar == ':') (*candidate_max)--;
4358 return TRUE;
4361 return FALSE;
4365 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4367 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4369 struct prefix_s {
4370 const char *text;
4371 int length;
4372 } prefixes[12] = {
4373 /* Code below depends on these being in decreasing length order! */
4374 {"prospero:", 10},
4375 {"telnet:", 8},
4376 {"gopher:", 8},
4377 {"mailto:", 8},
4378 {"https:", 7},
4379 {"file:", 6},
4380 {"news:", 6},
4381 {"wais:", 6},
4382 {"nntp:", 6},
4383 {"http:", 5},
4384 {"www.", 5},
4385 {"ftp:", 5},
4387 LPWSTR bufferW = NULL;
4388 WCHAR bufW[32];
4389 int i;
4391 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4392 assert(sel_min <= sel_max);
4393 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4395 if (sel_max - sel_min < prefixes[i].length) continue;
4396 if (bufferW == NULL) {
4397 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4399 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4400 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4401 if (!lstrcmpW(bufW, bufferW))
4403 heap_free(bufferW);
4404 return TRUE;
4407 heap_free(bufferW);
4408 return FALSE;
4412 * This proc walks through the indicated selection and evaluates whether each
4413 * section identified by ME_FindNextURLCandidate and in-between sections have
4414 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4415 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4417 * Returns TRUE if at least one section was modified.
4419 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4421 BOOL modified = FALSE;
4422 int cMin, cMax;
4424 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4427 int beforeURL[2];
4428 int inURL[2];
4429 CHARFORMAT2W link;
4431 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4433 /* Section before candidate is not an URL */
4434 beforeURL[0] = sel_min;
4435 beforeURL[1] = cMin;
4437 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4439 inURL[0] = cMin; inURL[1] = cMax;
4441 else
4443 beforeURL[1] = cMax;
4444 inURL[0] = inURL[1] = -1;
4446 sel_min = cMax;
4448 else
4450 /* No more candidates until end of selection */
4451 beforeURL[0] = sel_min;
4452 beforeURL[1] = sel_max;
4453 inURL[0] = inURL[1] = -1;
4454 sel_min = sel_max;
4457 if (beforeURL[0] < beforeURL[1])
4459 /* CFE_LINK effect should be consistently unset */
4460 link.cbSize = sizeof(link);
4461 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4462 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4464 /* CFE_LINK must be unset from this range */
4465 memset(&link, 0, sizeof(CHARFORMAT2W));
4466 link.cbSize = sizeof(link);
4467 link.dwMask = CFM_LINK;
4468 link.dwEffects = 0;
4469 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4470 modified = TRUE;
4473 if (inURL[0] < inURL[1])
4475 /* CFE_LINK effect should be consistently set */
4476 link.cbSize = sizeof(link);
4477 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4478 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4480 /* CFE_LINK must be set on this range */
4481 memset(&link, 0, sizeof(CHARFORMAT2W));
4482 link.cbSize = sizeof(link);
4483 link.dwMask = CFM_LINK;
4484 link.dwEffects = CFE_LINK;
4485 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4486 modified = TRUE;
4489 } while (sel_min < sel_max);
4490 return modified;
4493 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4495 ME_DisplayItem * startPara, * endPara;
4496 ME_DisplayItem * item;
4497 int dummy;
4498 int from, to;
4500 ME_GetSelection(editor, &from, &to);
4501 if (from > to) from ^= to, to ^=from, from ^= to;
4502 startPara = NULL; endPara = NULL;
4504 /* Find paragraph previous to the one that contains start cursor */
4505 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4506 if (item) {
4507 startPara = ME_FindItemBack(item, diParagraph);
4508 item = ME_FindItemBack(startPara, diParagraph);
4509 if (item) startPara = item;
4512 /* Find paragraph that contains end cursor */
4513 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4514 if (item) {
4515 endPara = ME_FindItemFwd(item, diParagraph);
4518 if (startPara && endPara) {
4519 ME_UpdateLinkAttribute(editor,
4520 startPara->member.para.nCharOfs,
4521 endPara->member.para.nCharOfs);
4522 } else if (startPara) {
4523 ME_UpdateLinkAttribute(editor,
4524 startPara->member.para.nCharOfs,
4525 -1);