richedit: Fixed the selection bar width.
[wine/multimedia.git] / dlls / riched20 / editor.c
blob6ff1385f26c58a9a992a1b62886baac46d8e7831
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 | PFM_OFFSET |
455 PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE | PFM_STARTINDENT;
456 /* TODO: numbering, shading */
457 fmt.wAlignment = PFA_LEFT;
458 fmt.cTabCount = 0;
459 fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
460 fmt.wBorderWidth = fmt.wBorders = 0;
461 fmt.wBorderSpace = 0;
462 fmt.bLineSpacingRule = 0;
463 fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
464 fmt.dyLineSpacing = 0;
465 RTFFlushOutputBuffer(info);
466 ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
467 break;
468 case rtfInTable:
470 ME_DisplayItem *para;
472 RTFFlushOutputBuffer(info);
473 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
474 assert(para->member.para.pCells);
475 para->member.para.bTable = TRUE;
476 return;
478 case rtfFirstIndent:
479 ME_GetSelectionParaFormat(info->editor, &fmt);
480 fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
481 fmt.dxStartIndent += info->rtfParam;
482 fmt.dxOffset = -info->rtfParam;
483 break;
484 case rtfLeftIndent:
485 /* we assume rtfLeftIndent is always specified before rtfFirstIndent */
486 ME_GetSelectionParaFormat(info->editor, &fmt);
487 fmt.dwMask |= PFM_STARTINDENT;
488 fmt.dxStartIndent = info->rtfParam;
489 fmt.dxOffset = 0;
490 break;
491 case rtfRightIndent:
492 fmt.dwMask = PFM_RIGHTINDENT;
493 fmt.dxRightIndent = info->rtfParam;
494 break;
495 case rtfQuadLeft:
496 case rtfQuadJust:
497 fmt.dwMask = PFM_ALIGNMENT;
498 fmt.wAlignment = PFA_LEFT;
499 break;
500 case rtfQuadRight:
501 fmt.dwMask = PFM_ALIGNMENT;
502 fmt.wAlignment = PFA_RIGHT;
503 break;
504 case rtfQuadCenter:
505 fmt.dwMask = PFM_ALIGNMENT;
506 fmt.wAlignment = PFA_CENTER;
507 break;
508 case rtfTabPos:
509 ME_GetSelectionParaFormat(info->editor, &fmt);
510 if (!(fmt.dwMask & PFM_TABSTOPS))
512 fmt.dwMask |= PFM_TABSTOPS;
513 fmt.cTabCount = 0;
515 if (fmt.cTabCount < MAX_TAB_STOPS)
516 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
517 break;
518 case rtfKeep:
519 fmt.dwMask = PFM_KEEP;
520 fmt.wEffects = PFE_KEEP;
521 break;
522 case rtfNoWidowControl:
523 fmt.dwMask = PFM_NOWIDOWCONTROL;
524 fmt.wEffects = PFE_NOWIDOWCONTROL;
525 break;
526 case rtfKeepNext:
527 fmt.dwMask = PFM_KEEPNEXT;
528 fmt.wEffects = PFE_KEEPNEXT;
529 break;
530 case rtfSpaceAfter:
531 fmt.dwMask = PFM_SPACEAFTER;
532 fmt.dySpaceAfter = info->rtfParam;
533 break;
534 case rtfSpaceBefore:
535 fmt.dwMask = PFM_SPACEBEFORE;
536 fmt.dySpaceBefore = info->rtfParam;
537 break;
538 case rtfSpaceBetween:
539 fmt.dwMask = PFM_LINESPACING;
540 if ((int)info->rtfParam > 0)
542 fmt.dyLineSpacing = info->rtfParam;
543 fmt.bLineSpacingRule = 3;
545 else
547 fmt.dyLineSpacing = info->rtfParam;
548 fmt.bLineSpacingRule = 4;
550 case rtfSpaceMultiply:
551 fmt.dwMask = PFM_LINESPACING;
552 fmt.dyLineSpacing = info->rtfParam * 20;
553 fmt.bLineSpacingRule = 5;
554 break;
555 case rtfParBullet:
556 fmt.dwMask = PFM_NUMBERING;
557 fmt.wNumbering = PFN_BULLET;
558 break;
559 case rtfParSimple:
560 fmt.dwMask = PFM_NUMBERING;
561 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
562 break;
563 case rtfParNumDecimal:
564 fmt.dwMask = PFM_NUMBERING;
565 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
566 break;
567 case rtfParNumIndent:
568 fmt.dwMask = PFM_NUMBERINGTAB;
569 fmt.wNumberingTab = info->rtfParam;
570 break;
571 case rtfParNumStartAt:
572 fmt.dwMask = PFM_NUMBERINGSTART;
573 fmt.wNumberingStart = info->rtfParam;
574 break;
575 case rtfBorderLeft:
576 ME_GetSelectionParaFormat(info->editor, &fmt);
577 if (!(fmt.dwMask & PFM_BORDER))
579 fmt.dwMask |= PFM_BORDER;
580 fmt.wBorderSpace = 0;
581 fmt.wBorderWidth = 1;
582 fmt.wBorders = 0;
584 fmt.wBorders |= 1;
585 break;
586 case rtfBorderRight:
587 ME_GetSelectionParaFormat(info->editor, &fmt);
588 if (!(fmt.dwMask & PFM_BORDER))
590 fmt.dwMask |= PFM_BORDER;
591 fmt.wBorderSpace = 0;
592 fmt.wBorderWidth = 1;
593 fmt.wBorders = 0;
595 fmt.wBorders |= 2;
596 break;
597 case rtfBorderTop:
598 ME_GetSelectionParaFormat(info->editor, &fmt);
599 if (!(fmt.dwMask & PFM_BORDER))
601 fmt.dwMask |= PFM_BORDER;
602 fmt.wBorderSpace = 0;
603 fmt.wBorderWidth = 1;
604 fmt.wBorders = 0;
606 fmt.wBorders |= 4;
607 break;
608 case rtfBorderBottom:
609 ME_GetSelectionParaFormat(info->editor, &fmt);
610 if (!(fmt.dwMask & PFM_BORDER))
612 fmt.dwMask |= PFM_BORDER;
613 fmt.wBorderSpace = 0;
614 fmt.wBorderWidth = 1;
615 fmt.wBorders = 0;
617 fmt.wBorders |= 8;
618 break;
619 case rtfBorderSingle:
620 ME_GetSelectionParaFormat(info->editor, &fmt);
621 /* we assume that borders have been created before (RTF spec) */
622 fmt.wBorders &= ~0x700;
623 fmt.wBorders |= 1 << 8;
624 break;
625 case rtfBorderThick:
626 ME_GetSelectionParaFormat(info->editor, &fmt);
627 /* we assume that borders have been created before (RTF spec) */
628 fmt.wBorders &= ~0x700;
629 fmt.wBorders |= 2 << 8;
630 break;
631 case rtfBorderShadow:
632 ME_GetSelectionParaFormat(info->editor, &fmt);
633 /* we assume that borders have been created before (RTF spec) */
634 fmt.wBorders &= ~0x700;
635 fmt.wBorders |= 10 << 8;
636 break;
637 case rtfBorderDouble:
638 ME_GetSelectionParaFormat(info->editor, &fmt);
639 /* we assume that borders have been created before (RTF spec) */
640 fmt.wBorders &= ~0x700;
641 fmt.wBorders |= 7 << 8;
642 break;
643 case rtfBorderDot:
644 ME_GetSelectionParaFormat(info->editor, &fmt);
645 /* we assume that borders have been created before (RTF spec) */
646 fmt.wBorders &= ~0x700;
647 fmt.wBorders |= 11 << 8;
648 break;
649 case rtfBorderWidth:
650 ME_GetSelectionParaFormat(info->editor, &fmt);
651 /* we assume that borders have been created before (RTF spec) */
652 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
653 break;
654 case rtfBorderSpace:
655 ME_GetSelectionParaFormat(info->editor, &fmt);
656 /* we assume that borders have been created before (RTF spec) */
657 fmt.wBorderSpace = info->rtfParam;
658 break;
660 if (fmt.dwMask) {
661 RTFFlushOutputBuffer(info);
662 /* FIXME too slow ? how come ?*/
663 ME_SetSelectionParaFormat(info->editor, &fmt);
667 static void ME_RTFTblAttrHook(RTF_Info *info)
669 ME_DisplayItem *para;
671 switch (info->rtfMinor)
673 case rtfRowDef:
674 RTFFlushOutputBuffer(info);
675 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
677 /* Release possibly inherited cell definitions */
678 ME_DestroyTableCellList(para);
680 para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
681 para->member.para.pCells->nRightBoundary = 0;
682 para->member.para.pCells->next = NULL;
683 para->member.para.pLastCell = para->member.para.pCells;
684 break;
685 case rtfCellPos:
686 RTFFlushOutputBuffer(info);
687 para = ME_GetParagraph(info->editor->pCursors[0].pRun);
689 if (para->member.para.pLastCell->nRightBoundary)
691 ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
693 pCell->next = NULL;
694 para->member.para.pLastCell->next = pCell;
695 para->member.para.pLastCell = pCell;
697 para->member.para.pLastCell->nRightBoundary = info->rtfParam;
698 break;
702 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
703 const SIZEL* sz)
705 LPOLEOBJECT lpObject = NULL;
706 LPSTORAGE lpStorage = NULL;
707 LPOLECLIENTSITE lpClientSite = NULL;
708 LPDATAOBJECT lpDataObject = NULL;
709 LPOLECACHE lpOleCache = NULL;
710 STGMEDIUM stgm;
711 FORMATETC fm;
712 CLSID clsid;
713 BOOL ret = FALSE;
714 DWORD conn;
716 if (hemf)
718 stgm.tymed = TYMED_ENHMF;
719 stgm.u.hEnhMetaFile = hemf;
720 fm.cfFormat = CF_ENHMETAFILE;
722 else if (hbmp)
724 stgm.tymed = TYMED_GDI;
725 stgm.u.hBitmap = hbmp;
726 fm.cfFormat = CF_BITMAP;
728 stgm.pUnkForRelease = NULL;
730 fm.ptd = NULL;
731 fm.dwAspect = DVASPECT_CONTENT;
732 fm.lindex = -1;
733 fm.tymed = stgm.tymed;
735 if (!info->lpRichEditOle)
737 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
740 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
741 #if 0
742 /* FIXME: enable it when rich-edit properly implements this method */
743 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
744 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
745 #endif
746 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
747 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
748 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
749 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
750 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
752 REOBJECT reobject;
754 reobject.cbStruct = sizeof(reobject);
755 reobject.cp = REO_CP_SELECTION;
756 reobject.clsid = clsid;
757 reobject.poleobj = lpObject;
758 reobject.pstg = lpStorage;
759 reobject.polesite = lpClientSite;
760 /* convert from twips to .01 mm */
761 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
762 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
763 reobject.dvaspect = DVASPECT_CONTENT;
764 reobject.dwFlags = 0; /* FIXME */
765 reobject.dwUser = 0;
767 /* FIXME: could be simpler */
768 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
771 if (lpObject) IOleObject_Release(lpObject);
772 if (lpClientSite) IOleClientSite_Release(lpClientSite);
773 if (lpStorage) IStorage_Release(lpStorage);
774 if (lpDataObject) IDataObject_Release(lpDataObject);
775 if (lpOleCache) IOleCache_Release(lpOleCache);
777 return ret;
780 static void ME_RTFReadPictGroup(RTF_Info *info)
782 SIZEL sz;
783 BYTE* buffer = NULL;
784 unsigned bufsz, bufidx;
785 BOOL flip;
786 BYTE val;
787 METAFILEPICT mfp;
788 HENHMETAFILE hemf;
789 HBITMAP hbmp;
790 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
792 RTFGetToken (info);
793 if (info->rtfClass == rtfEOF)
794 return;
795 mfp.mm = MM_TEXT;
796 /* fetch picture type */
797 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
799 mfp.mm = info->rtfParam;
800 gfx = gfx_metafile;
802 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
804 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
805 gfx = gfx_dib;
807 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
809 gfx = gfx_enhmetafile;
811 else
813 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
814 goto skip_group;
816 sz.cx = sz.cy = 0;
817 /* fetch picture attributes */
818 for (;;)
820 RTFGetToken (info);
821 if (info->rtfClass == rtfEOF)
822 return;
823 if (info->rtfClass == rtfText)
824 break;
825 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
827 ERR("Expected picture attribute (%d %d)\n",
828 info->rtfClass, info->rtfMajor);
829 goto skip_group;
831 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
833 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
835 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
837 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
839 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
840 sz.cx = info->rtfParam;
841 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
842 sz.cy = info->rtfParam;
843 else
844 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
846 /* fetch picture data */
847 bufsz = 1024;
848 bufidx = 0;
849 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
850 val = info->rtfMajor;
851 for (flip = TRUE;; flip = !flip)
853 RTFGetToken (info);
854 if (info->rtfClass == rtfEOF)
856 HeapFree(GetProcessHeap(), 0, buffer);
857 return; /* Warn ?? */
859 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
860 break;
861 if (info->rtfClass != rtfText) goto skip_group;
862 if (flip)
864 if (bufidx >= bufsz &&
865 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
866 goto skip_group;
867 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
869 else
870 val = info->rtfMajor;
872 if (flip) FIXME("wrong hex string\n");
874 switch (gfx)
876 case gfx_enhmetafile:
877 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
878 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
879 break;
880 case gfx_metafile:
881 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
882 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
883 break;
884 case gfx_dib:
886 BITMAPINFO* bi = (BITMAPINFO*)buffer;
887 HDC hdc = GetDC(0);
888 unsigned nc = bi->bmiHeader.biClrUsed;
890 /* not quite right, especially for bitfields type of compression */
891 if (!nc && bi->bmiHeader.biBitCount <= 8)
892 nc = 1 << bi->bmiHeader.biBitCount;
893 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
894 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
895 bi, DIB_RGB_COLORS)))
896 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
897 ReleaseDC(0, hdc);
899 break;
900 default:
901 break;
903 HeapFree(GetProcessHeap(), 0, buffer);
904 RTFRouteToken (info); /* feed "}" back to router */
905 return;
906 skip_group:
907 HeapFree(GetProcessHeap(), 0, buffer);
908 RTFSkipGroup(info);
909 RTFRouteToken(info); /* feed "}" back to router */
912 /* for now, lookup the \result part and use it, whatever the object */
913 static void ME_RTFReadObjectGroup(RTF_Info *info)
915 for (;;)
917 RTFGetToken (info);
918 if (info->rtfClass == rtfEOF)
919 return;
920 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
921 break;
922 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
924 RTFGetToken (info);
925 if (info->rtfClass == rtfEOF)
926 return;
927 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
929 int level = 1;
931 while (RTFGetToken (info) != rtfEOF)
933 if (info->rtfClass == rtfGroup)
935 if (info->rtfMajor == rtfBeginGroup) level++;
936 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
938 RTFRouteToken(info);
941 else RTFSkipGroup(info);
942 continue;
944 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
946 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
947 return;
950 RTFRouteToken(info); /* feed "}" back to router */
953 static void ME_RTFReadHook(RTF_Info *info) {
954 switch(info->rtfClass)
956 case rtfGroup:
957 switch(info->rtfMajor)
959 case rtfBeginGroup:
960 if (info->stackTop < maxStack) {
961 info->stack[info->stackTop].fmt = info->style->fmt;
962 info->stack[info->stackTop].codePage = info->codePage;
963 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
965 info->stackTop++;
966 info->styleChanged = FALSE;
967 break;
968 case rtfEndGroup:
970 ME_Style *s;
971 RTFFlushOutputBuffer(info);
972 info->stackTop--;
973 if (info->stackTop<=0) {
974 info->rtfClass = rtfEOF;
975 return;
977 assert(info->stackTop >= 0);
978 if (info->styleChanged)
980 /* FIXME too slow ? how come ? */
981 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
982 ME_ReleaseStyle(info->style);
983 info->style = s;
984 info->codePage = info->stack[info->stackTop].codePage;
985 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
987 break;
990 break;
991 case rtfControl:
992 switch(info->rtfMajor)
994 case rtfCharAttr:
995 ME_RTFCharAttrHook(info);
996 break;
997 case rtfParAttr:
998 ME_RTFParAttrHook(info);
999 break;
1000 case rtfTblAttr:
1001 ME_RTFTblAttrHook(info);
1002 break;
1003 case rtfSpecialChar:
1004 if (info->rtfMinor == rtfCell)
1006 RTFFlushOutputBuffer(info);
1007 ME_InsertTableCellFromCursor(info->editor, 0);
1010 break;
1014 void
1015 ME_StreamInFill(ME_InStream *stream)
1017 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1018 (BYTE *)stream->buffer,
1019 sizeof(stream->buffer),
1020 (LONG *)&stream->dwSize);
1021 stream->dwUsed = 0;
1024 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1026 RTF_Info parser;
1027 ME_Style *style;
1028 int from, to, to2, nUndoMode;
1029 int nEventMask = editor->nEventMask;
1030 ME_InStream inStream;
1031 BOOL invalidRTF = FALSE;
1033 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1034 editor->nEventMask = 0;
1036 ME_GetSelection(editor, &from, &to);
1037 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1038 style = ME_GetSelectionInsertStyle(editor);
1040 ME_InternalDeleteText(editor, from, to-from);
1042 else {
1043 style = editor->pBuffer->pDefaultStyle;
1044 ME_AddRefStyle(style);
1045 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1046 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1047 from = to = 0;
1048 ME_ClearTempStyle(editor);
1049 /* FIXME restore default paragraph formatting ! */
1053 /* Back up undo mode to a local variable */
1054 nUndoMode = editor->nUndoMode;
1056 /* Only create an undo if SFF_SELECTION is set */
1057 if (!(format & SFF_SELECTION))
1058 editor->nUndoMode = umIgnore;
1060 inStream.editstream = stream;
1061 inStream.editstream->dwError = 0;
1062 inStream.dwSize = 0;
1063 inStream.dwUsed = 0;
1065 if (format & SF_RTF)
1067 /* Check if it's really RTF, and if it is not, use plain text */
1068 ME_StreamInFill(&inStream);
1069 if (!inStream.editstream->dwError)
1071 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1072 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1074 invalidRTF = TRUE;
1075 inStream.editstream->dwError = -16;
1080 if (!invalidRTF && !inStream.editstream->dwError)
1082 if (format & SF_RTF) {
1083 /* setup the RTF parser */
1084 memset(&parser, 0, sizeof parser);
1085 RTFSetEditStream(&parser, &inStream);
1086 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1087 parser.hwndEdit = editor->hWnd;
1088 parser.editor = editor;
1089 parser.style = style;
1090 WriterInit(&parser);
1091 RTFInit(&parser);
1092 RTFSetReadHook(&parser, ME_RTFReadHook);
1093 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1094 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1095 BeginFile(&parser);
1097 /* do the parsing */
1098 RTFRead(&parser);
1099 RTFFlushOutputBuffer(&parser);
1100 RTFDestroy(&parser);
1101 if (parser.lpRichEditOle)
1102 IRichEditOle_Release(parser.lpRichEditOle);
1104 if (!inStream.editstream->dwError && parser.stackTop > 0)
1105 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1107 /* Remove last line break, as mandated by tests. This is not affected by
1108 CR/LF counters, since RTF streaming presents only \para tokens, which
1109 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1111 if (stripLastCR) {
1112 int newfrom, newto;
1113 ME_GetSelection(editor, &newfrom, &newto);
1114 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1115 WCHAR lastchar[3] = {'\0', '\0'};
1116 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1118 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1119 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1120 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize);
1125 style = parser.style;
1127 else if (format & SF_TEXT)
1128 ME_StreamInText(editor, format, &inStream, style);
1129 else
1130 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1131 ME_GetSelection(editor, &to, &to2);
1132 /* put the cursor at the top */
1133 if (!(format & SFF_SELECTION))
1134 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1137 /* Restore saved undo mode */
1138 editor->nUndoMode = nUndoMode;
1140 /* even if we didn't add an undo, we need to commit anything on the stack */
1141 ME_CommitUndo(editor);
1143 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1144 if (!(format & SFF_SELECTION))
1145 ME_EmptyUndoStack(editor);
1147 ME_ReleaseStyle(style);
1148 editor->nEventMask = nEventMask;
1149 ME_UpdateRepaint(editor);
1150 if (!(format & SFF_SELECTION)) {
1151 ME_ClearTempStyle(editor);
1153 HideCaret(editor->hWnd);
1154 ME_MoveCaret(editor);
1155 ShowCaret(editor->hWnd);
1156 ME_SendSelChange(editor);
1157 ME_SendRequestResize(editor, FALSE);
1159 return 0;
1163 typedef struct tagME_RTFStringStreamStruct
1165 char *string;
1166 int pos;
1167 int length;
1168 } ME_RTFStringStreamStruct;
1170 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1172 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1173 int count;
1175 count = min(cb, pStruct->length - pStruct->pos);
1176 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1177 pStruct->pos += count;
1178 *pcb = count;
1179 return 0;
1182 static void
1183 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1185 EDITSTREAM es;
1186 ME_RTFStringStreamStruct data;
1188 data.string = string;
1189 data.length = strlen(string);
1190 data.pos = 0;
1191 es.dwCookie = (DWORD)&data;
1192 es.pfnCallback = ME_ReadFromRTFString;
1193 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1197 ME_DisplayItem *
1198 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1200 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1201 int runLength;
1203 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1204 item = ME_FindItemFwd(item, diParagraph);
1206 if (!item)
1207 return item;
1209 nOffset -= item->member.para.nCharOfs;
1210 if (nItemType == diParagraph) {
1211 if (nItemOffset)
1212 *nItemOffset = nOffset;
1213 return item;
1216 do {
1217 item = ME_FindItemFwd(item, diRun);
1218 runLength = ME_StrLen(item->member.run.strText);
1219 if (item->member.run.nFlags & MERF_ENDPARA)
1220 runLength = item->member.run.nCR + item->member.run.nLF;
1221 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1222 if (item) {
1223 nOffset -= item->member.run.nCharOfs;
1225 /* Special case: nOffset may not point exactly at the division between the
1226 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1227 into the next run, if one exists
1229 if ( item->member.run.nFlags & MERF_ENDPARA
1230 && nOffset == item->member.run.nCR
1231 && item->member.run.nLF > 0) {
1232 ME_DisplayItem *nextItem;
1233 nextItem = ME_FindItemFwd(item, diRun);
1234 if (nextItem) {
1235 nOffset = 0;
1236 item = nextItem;
1239 if (nItemOffset)
1240 *nItemOffset = nOffset;
1242 return item;
1246 static int
1247 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1249 const int nLen = lstrlenW(text);
1250 const int nTextLen = ME_GetTextLength(editor);
1251 int nStart, nEnd;
1252 int nMin, nMax;
1253 ME_DisplayItem *item;
1254 ME_DisplayItem *para;
1255 WCHAR wLastChar = ' ';
1257 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1258 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1260 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1261 FIXME("Flags 0x%08x not implemented\n",
1262 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1264 nMin = chrg->cpMin;
1265 if (chrg->cpMax == -1)
1266 nMax = nTextLen;
1267 else
1268 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1270 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1271 if (editor->bEmulateVersion10 && nMax == nTextLen)
1273 flags |= FR_DOWN;
1276 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1277 if (editor->bEmulateVersion10 && nMax < nMin)
1279 if (chrgText)
1281 chrgText->cpMin = -1;
1282 chrgText->cpMax = -1;
1284 return -1;
1287 /* when searching up, if cpMin < cpMax, then instead of searching
1288 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1289 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1290 * case, it is always bigger than cpMin.
1292 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1294 int nSwap = nMax;
1296 nMax = nMin > nTextLen ? nTextLen : nMin;
1297 if (nMin < nSwap || chrg->cpMax == -1)
1298 nMin = 0;
1299 else
1300 nMin = nSwap;
1303 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1305 if (chrgText)
1306 chrgText->cpMin = chrgText->cpMax = -1;
1307 return -1;
1310 if (flags & FR_DOWN) /* Forward search */
1312 /* If possible, find the character before where the search starts */
1313 if ((flags & FR_WHOLEWORD) && nMin)
1315 nStart = nMin - 1;
1316 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1317 if (!item)
1319 if (chrgText)
1320 chrgText->cpMin = chrgText->cpMax = -1;
1321 return -1;
1323 wLastChar = item->member.run.strText->szData[nStart];
1326 nStart = nMin;
1327 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1328 if (!item)
1330 if (chrgText)
1331 chrgText->cpMin = chrgText->cpMax = -1;
1332 return -1;
1335 para = ME_GetParagraph(item);
1336 while (item
1337 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1339 ME_DisplayItem *pCurItem = item;
1340 int nCurStart = nStart;
1341 int nMatched = 0;
1343 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1345 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1346 break;
1348 nMatched++;
1349 if (nMatched == nLen)
1351 ME_DisplayItem *pNextItem = pCurItem;
1352 int nNextStart = nCurStart;
1353 WCHAR wNextChar;
1355 /* Check to see if next character is a whitespace */
1356 if (flags & FR_WHOLEWORD)
1358 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1360 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1361 nNextStart = -nMatched;
1364 if (pNextItem)
1365 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1366 else
1367 wNextChar = ' ';
1369 if (isalnumW(wNextChar))
1370 break;
1373 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1374 if (chrgText)
1376 chrgText->cpMin = nStart;
1377 chrgText->cpMax = nStart + nLen;
1379 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1380 return nStart;
1382 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1384 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1385 para = ME_GetParagraph(pCurItem);
1386 nCurStart = -nMatched;
1389 if (pCurItem)
1390 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1391 else
1392 wLastChar = ' ';
1394 nStart++;
1395 if (nStart == ME_StrLen(item->member.run.strText))
1397 item = ME_FindItemFwd(item, diRun);
1398 para = ME_GetParagraph(item);
1399 nStart = 0;
1403 else /* Backward search */
1405 /* If possible, find the character after where the search ends */
1406 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1408 nEnd = nMax + 1;
1409 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1410 if (!item)
1412 if (chrgText)
1413 chrgText->cpMin = chrgText->cpMax = -1;
1414 return -1;
1416 wLastChar = item->member.run.strText->szData[nEnd];
1419 nEnd = nMax;
1420 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1421 if (!item)
1423 if (chrgText)
1424 chrgText->cpMin = chrgText->cpMax = -1;
1425 return -1;
1428 para = ME_GetParagraph(item);
1430 while (item
1431 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1433 ME_DisplayItem *pCurItem = item;
1434 int nCurEnd = nEnd;
1435 int nMatched = 0;
1437 if (nCurEnd - nMatched == 0)
1439 pCurItem = ME_FindItemBack(pCurItem, diRun);
1440 para = ME_GetParagraph(pCurItem);
1441 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1444 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1446 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1447 break;
1449 nMatched++;
1450 if (nMatched == nLen)
1452 ME_DisplayItem *pPrevItem = pCurItem;
1453 int nPrevEnd = nCurEnd;
1454 WCHAR wPrevChar;
1456 /* Check to see if previous character is a whitespace */
1457 if (flags & FR_WHOLEWORD)
1459 if (nPrevEnd - nMatched == 0)
1461 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1462 if (pPrevItem)
1463 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1466 if (pPrevItem)
1467 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1468 else
1469 wPrevChar = ' ';
1471 if (isalnumW(wPrevChar))
1472 break;
1475 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1476 if (chrgText)
1478 chrgText->cpMin = nStart;
1479 chrgText->cpMax = nStart + nLen;
1481 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1482 return nStart;
1484 if (nCurEnd - nMatched == 0)
1486 pCurItem = ME_FindItemBack(pCurItem, diRun);
1487 /* Don't care about pCurItem becoming NULL here; it's already taken
1488 * care of in the exterior loop condition */
1489 para = ME_GetParagraph(pCurItem);
1490 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1493 if (pCurItem)
1494 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1495 else
1496 wLastChar = ' ';
1498 nEnd--;
1499 if (nEnd < 0)
1501 item = ME_FindItemBack(item, diRun);
1502 para = ME_GetParagraph(item);
1503 nEnd = ME_StrLen(item->member.run.strText);
1507 TRACE("not found\n");
1508 if (chrgText)
1509 chrgText->cpMin = chrgText->cpMax = -1;
1510 return -1;
1513 /* helper to send a msg filter notification */
1514 static BOOL
1515 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1517 MSGFILTER msgf;
1519 msgf.nmhdr.hwndFrom = editor->hWnd;
1520 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1521 msgf.nmhdr.code = EN_MSGFILTER;
1522 msgf.msg = msg;
1524 msgf.wParam = *wParam;
1525 msgf.lParam = *lParam;
1526 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1527 return FALSE;
1528 *wParam = msgf.wParam;
1529 *lParam = msgf.lParam;
1530 msgf.wParam = *wParam;
1532 return TRUE;
1535 static BOOL
1536 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1538 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1539 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1541 switch (nKey)
1543 case VK_LEFT:
1544 case VK_RIGHT:
1545 case VK_HOME:
1546 case VK_END:
1547 editor->nUDArrowX = -1;
1548 /* fall through */
1549 case VK_UP:
1550 case VK_DOWN:
1551 case VK_PRIOR:
1552 case VK_NEXT:
1553 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1554 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1555 return TRUE;
1556 case VK_BACK:
1557 case VK_DELETE:
1558 editor->nUDArrowX = -1;
1559 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1560 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1561 return FALSE;
1562 if (ME_IsSelection(editor))
1564 ME_DeleteSelection(editor);
1565 ME_CommitUndo(editor);
1567 else if (nKey == VK_DELETE)
1569 /* Delete stops group typing.
1570 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1571 ME_DeleteTextAtCursor(editor, 1, 1);
1572 ME_CommitUndo(editor);
1574 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1576 /* Backspace can be grouped for a single undo */
1577 ME_ContinueCoalescingTransaction(editor);
1578 ME_DeleteTextAtCursor(editor, 1, 1);
1579 ME_CommitCoalescingUndo(editor);
1581 else
1582 return TRUE;
1583 ME_UpdateSelectionLinkAttribute(editor);
1584 ME_UpdateRepaint(editor);
1585 ME_SendRequestResize(editor, FALSE);
1586 return TRUE;
1588 default:
1589 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1590 editor->nUDArrowX = -1;
1591 if (ctrl_is_down)
1593 if (nKey == 'W')
1595 CHARFORMAT2W chf;
1596 char buf[2048];
1597 chf.cbSize = sizeof(chf);
1599 ME_GetSelectionCharFormat(editor, &chf);
1600 ME_DumpStyleToBuf(&chf, buf);
1601 MessageBoxA(NULL, buf, "Style dump", MB_OK);
1603 if (nKey == 'Q')
1605 ME_CheckCharOffsets(editor);
1609 return FALSE;
1612 static BOOL ME_SetCursor(ME_TextEditor *editor, int x)
1614 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1615 (x < editor->selofs || editor->linesel))
1617 SetCursor(hLeft);
1618 return TRUE;
1620 return FALSE;
1623 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1625 CHARRANGE selrange;
1626 HMENU menu;
1627 int seltype = 0;
1628 if(!editor->lpOleCallback)
1629 return FALSE;
1630 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
1631 if(selrange.cpMin == selrange.cpMax)
1632 seltype |= SEL_EMPTY;
1633 else
1635 /* FIXME: Handle objects */
1636 seltype |= SEL_TEXT;
1637 if(selrange.cpMax-selrange.cpMin > 1)
1638 seltype |= SEL_MULTICHAR;
1640 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1642 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1643 DestroyMenu(menu);
1645 return TRUE;
1648 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1649 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1650 int i;
1651 ed->hWnd = hWnd;
1652 ed->bEmulateVersion10 = FALSE;
1653 ed->pBuffer = ME_MakeText();
1654 ed->nZoomNumerator = ed->nZoomDenominator = 0;
1655 ME_MakeFirstParagraph(ed);
1656 ed->bCaretShown = FALSE;
1657 ed->nCursors = 4;
1658 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1659 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1660 ed->pCursors[0].nOffset = 0;
1661 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1662 ed->pCursors[1].nOffset = 0;
1663 ed->pCursors[2] = ed->pCursors[0];
1664 ed->pCursors[3] = ed->pCursors[1];
1665 ed->nLastTotalLength = ed->nTotalLength = 0;
1666 ed->nHeight = 0;
1667 ed->nUDArrowX = -1;
1668 ed->nSequence = 0;
1669 ed->rgbBackColor = -1;
1670 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1671 ed->bCaretAtEnd = FALSE;
1672 ed->nEventMask = 0;
1673 ed->nModifyStep = 0;
1674 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1675 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1676 ed->nUndoStackSize = 0;
1677 ed->nUndoLimit = STACK_SIZE_DEFAULT;
1678 ed->nUndoMode = umAddToUndo;
1679 ed->nParagraphs = 1;
1680 ed->nLastSelStart = ed->nLastSelEnd = 0;
1681 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1682 ed->bRedraw = TRUE;
1683 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
1684 ed->bHideSelection = FALSE;
1685 ed->nInvalidOfs = -1;
1686 ed->pfnWordBreak = NULL;
1687 ed->lpOleCallback = NULL;
1688 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1689 ed->AutoURLDetect_bEnable = FALSE;
1690 ed->bHaveFocus = FALSE;
1691 for (i=0; i<HFONT_CACHE_SIZE; i++)
1693 ed->pFontCache[i].nRefs = 0;
1694 ed->pFontCache[i].nAge = 0;
1695 ed->pFontCache[i].hFont = NULL;
1698 ME_CheckCharOffsets(ed);
1699 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1700 ed->selofs = SELECTIONBAR_WIDTH;
1701 else
1702 ed->selofs = 0;
1703 ed->linesel = 0;
1705 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1706 ed->cPasswordMask = '*';
1707 else
1708 ed->cPasswordMask = 0;
1710 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
1712 return ed;
1715 typedef struct tagME_GlobalDestStruct
1717 HGLOBAL hData;
1718 int nLength;
1719 } ME_GlobalDestStruct;
1721 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1723 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1724 int i;
1725 WORD *pSrc, *pDest;
1727 cb = cb >> 1;
1728 pDest = (WORD *)lpBuff;
1729 pSrc = (WORD *)GlobalLock(pData->hData);
1730 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1731 pDest[i] = pSrc[pData->nLength+i];
1733 pData->nLength += i;
1734 *pcb = 2*i;
1735 GlobalUnlock(pData->hData);
1736 return 0;
1739 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1741 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1742 int i;
1743 BYTE *pSrc, *pDest;
1745 pDest = lpBuff;
1746 pSrc = (BYTE *)GlobalLock(pData->hData);
1747 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1748 pDest[i] = pSrc[pData->nLength+i];
1750 pData->nLength += i;
1751 *pcb = i;
1752 GlobalUnlock(pData->hData);
1753 return 0;
1757 void ME_DestroyEditor(ME_TextEditor *editor)
1759 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1760 ME_DisplayItem *p = pFirst, *pNext = NULL;
1761 int i;
1763 ME_ClearTempStyle(editor);
1764 ME_EmptyUndoStack(editor);
1765 while(p) {
1766 pNext = p->next;
1767 ME_DestroyDisplayItem(p);
1768 p = pNext;
1770 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1771 for (i=0; i<HFONT_CACHE_SIZE; i++)
1773 if (editor->pFontCache[i].hFont)
1774 DeleteObject(editor->pFontCache[i].hFont);
1776 if (editor->rgbBackColor != -1)
1777 DeleteObject(editor->hbrBackground);
1778 if(editor->lpOleCallback)
1779 IUnknown_Release(editor->lpOleCallback);
1781 FREE_OBJ(editor->pBuffer);
1782 FREE_OBJ(editor->pCursors);
1784 FREE_OBJ(editor);
1787 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1789 TRACE("\n");
1790 switch (fdwReason)
1792 case DLL_PROCESS_ATTACH:
1793 DisableThreadLibraryCalls(hinstDLL);
1794 me_heap = HeapCreate (0, 0x10000, 0);
1795 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1796 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1797 LookupInit();
1798 break;
1800 case DLL_PROCESS_DETACH:
1801 UnregisterClassW(RichEdit20W, 0);
1802 UnregisterClassW(RichEdit50W, 0);
1803 UnregisterClassA("RichEdit20A", 0);
1804 UnregisterClassA("RichEdit50A", 0);
1805 if (ME_ListBoxRegistered)
1806 UnregisterClassW(REListBox20W, 0);
1807 if (ME_ComboBoxRegistered)
1808 UnregisterClassW(REComboBox20W, 0);
1809 LookupCleanup();
1810 HeapDestroy (me_heap);
1811 me_heap = NULL;
1812 break;
1814 return TRUE;
1818 #define UNSUPPORTED_MSG(e) \
1819 case e: \
1820 FIXME(#e ": stub\n"); \
1821 return DefWindowProcW(hWnd, msg, wParam, lParam);
1823 static const char * const edit_messages[] = {
1824 "EM_GETSEL",
1825 "EM_SETSEL",
1826 "EM_GETRECT",
1827 "EM_SETRECT",
1828 "EM_SETRECTNP",
1829 "EM_SCROLL",
1830 "EM_LINESCROLL",
1831 "EM_SCROLLCARET",
1832 "EM_GETMODIFY",
1833 "EM_SETMODIFY",
1834 "EM_GETLINECOUNT",
1835 "EM_LINEINDEX",
1836 "EM_SETHANDLE",
1837 "EM_GETHANDLE",
1838 "EM_GETTHUMB",
1839 "EM_UNKNOWN_BF",
1840 "EM_UNKNOWN_C0",
1841 "EM_LINELENGTH",
1842 "EM_REPLACESEL",
1843 "EM_UNKNOWN_C3",
1844 "EM_GETLINE",
1845 "EM_LIMITTEXT",
1846 "EM_CANUNDO",
1847 "EM_UNDO",
1848 "EM_FMTLINES",
1849 "EM_LINEFROMCHAR",
1850 "EM_UNKNOWN_CA",
1851 "EM_SETTABSTOPS",
1852 "EM_SETPASSWORDCHAR",
1853 "EM_EMPTYUNDOBUFFER",
1854 "EM_GETFIRSTVISIBLELINE",
1855 "EM_SETREADONLY",
1856 "EM_SETWORDBREAKPROC",
1857 "EM_GETWORDBREAKPROC",
1858 "EM_GETPASSWORDCHAR",
1859 "EM_SETMARGINS",
1860 "EM_GETMARGINS",
1861 "EM_GETLIMITTEXT",
1862 "EM_POSFROMCHAR",
1863 "EM_CHARFROMPOS"
1866 static const char * const richedit_messages[] = {
1867 "EM_CANPASTE",
1868 "EM_DISPLAYBAND",
1869 "EM_EXGETSEL",
1870 "EM_EXLIMITTEXT",
1871 "EM_EXLINEFROMCHAR",
1872 "EM_EXSETSEL",
1873 "EM_FINDTEXT",
1874 "EM_FORMATRANGE",
1875 "EM_GETCHARFORMAT",
1876 "EM_GETEVENTMASK",
1877 "EM_GETOLEINTERFACE",
1878 "EM_GETPARAFORMAT",
1879 "EM_GETSELTEXT",
1880 "EM_HIDESELECTION",
1881 "EM_PASTESPECIAL",
1882 "EM_REQUESTRESIZE",
1883 "EM_SELECTIONTYPE",
1884 "EM_SETBKGNDCOLOR",
1885 "EM_SETCHARFORMAT",
1886 "EM_SETEVENTMASK",
1887 "EM_SETOLECALLBACK",
1888 "EM_SETPARAFORMAT",
1889 "EM_SETTARGETDEVICE",
1890 "EM_STREAMIN",
1891 "EM_STREAMOUT",
1892 "EM_GETTEXTRANGE",
1893 "EM_FINDWORDBREAK",
1894 "EM_SETOPTIONS",
1895 "EM_GETOPTIONS",
1896 "EM_FINDTEXTEX",
1897 "EM_GETWORDBREAKPROCEX",
1898 "EM_SETWORDBREAKPROCEX",
1899 "EM_SETUNDOLIMIT",
1900 "EM_UNKNOWN_USER_83",
1901 "EM_REDO",
1902 "EM_CANREDO",
1903 "EM_GETUNDONAME",
1904 "EM_GETREDONAME",
1905 "EM_STOPGROUPTYPING",
1906 "EM_SETTEXTMODE",
1907 "EM_GETTEXTMODE",
1908 "EM_AUTOURLDETECT",
1909 "EM_GETAUTOURLDETECT",
1910 "EM_SETPALETTE",
1911 "EM_GETTEXTEX",
1912 "EM_GETTEXTLENGTHEX",
1913 "EM_SHOWSCROLLBAR",
1914 "EM_SETTEXTEX",
1915 "EM_UNKNOWN_USER_98",
1916 "EM_UNKNOWN_USER_99",
1917 "EM_SETPUNCTUATION",
1918 "EM_GETPUNCTUATION",
1919 "EM_SETWORDWRAPMODE",
1920 "EM_GETWORDWRAPMODE",
1921 "EM_SETIMECOLOR",
1922 "EM_GETIMECOLOR",
1923 "EM_SETIMEOPTIONS",
1924 "EM_GETIMEOPTIONS",
1925 "EM_CONVPOSITION",
1926 "EM_UNKNOWN_USER_109",
1927 "EM_UNKNOWN_USER_110",
1928 "EM_UNKNOWN_USER_111",
1929 "EM_UNKNOWN_USER_112",
1930 "EM_UNKNOWN_USER_113",
1931 "EM_UNKNOWN_USER_114",
1932 "EM_UNKNOWN_USER_115",
1933 "EM_UNKNOWN_USER_116",
1934 "EM_UNKNOWN_USER_117",
1935 "EM_UNKNOWN_USER_118",
1936 "EM_UNKNOWN_USER_119",
1937 "EM_SETLANGOPTIONS",
1938 "EM_GETLANGOPTIONS",
1939 "EM_GETIMECOMPMODE",
1940 "EM_FINDTEXTW",
1941 "EM_FINDTEXTEXW",
1942 "EM_RECONVERSION",
1943 "EM_SETIMEMODEBIAS",
1944 "EM_GETIMEMODEBIAS"
1947 static const char *
1948 get_msg_name(UINT msg)
1950 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1951 return edit_messages[msg - EM_GETSEL];
1952 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1953 return richedit_messages[msg - EM_CANPASTE];
1954 return "";
1957 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
1958 LPARAM lParam, BOOL unicode)
1960 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1962 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
1963 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
1965 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1966 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
1967 return 0;
1970 switch(msg) {
1972 UNSUPPORTED_MSG(EM_DISPLAYBAND)
1973 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1974 UNSUPPORTED_MSG(EM_FMTLINES)
1975 UNSUPPORTED_MSG(EM_FORMATRANGE)
1976 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1977 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1978 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1979 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1980 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1981 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1982 UNSUPPORTED_MSG(EM_GETREDONAME)
1983 UNSUPPORTED_MSG(EM_GETTEXTMODE)
1984 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1985 UNSUPPORTED_MSG(EM_GETUNDONAME)
1986 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1987 UNSUPPORTED_MSG(EM_PASTESPECIAL)
1988 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1989 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1990 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1991 UNSUPPORTED_MSG(EM_SETFONTSIZE)
1992 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1993 UNSUPPORTED_MSG(EM_SETPALETTE)
1994 UNSUPPORTED_MSG(EM_SETTABSTOPS)
1995 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1996 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1997 UNSUPPORTED_MSG(WM_STYLECHANGING)
1998 UNSUPPORTED_MSG(WM_STYLECHANGED)
1999 /* UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
2001 /* Messages specific to Richedit controls */
2003 case EM_STREAMIN:
2004 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2005 case EM_STREAMOUT:
2006 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2007 case WM_GETDLGCODE:
2009 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2010 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2012 int vk = (int)((LPMSG)lParam)->wParam;
2013 /* if style says we want return key */
2014 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2016 code |= DLGC_WANTMESSAGE;
2018 /* we always handle ctrl-tab */
2019 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2021 code |= DLGC_WANTMESSAGE;
2024 return code;
2026 case WM_NCCREATE:
2028 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2029 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2030 editor = ME_MakeEditor(hWnd);
2031 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2032 return TRUE;
2034 case EM_EMPTYUNDOBUFFER:
2035 ME_EmptyUndoStack(editor);
2036 return 0;
2037 case EM_GETSEL:
2039 /* Note: wParam/lParam can be NULL */
2040 UINT from, to;
2041 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2042 PUINT pto = lParam ? (PUINT)lParam : &to;
2043 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2044 if ((*pfrom|*pto) & 0xFFFF0000)
2045 return -1;
2046 return MAKELONG(*pfrom,*pto);
2048 case EM_EXGETSEL:
2050 CHARRANGE *pRange = (CHARRANGE *)lParam;
2051 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2052 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2053 return 0;
2055 case EM_SETUNDOLIMIT:
2057 if ((int)wParam < 0)
2058 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2059 else
2060 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2061 /* Setting a max stack size keeps wine from getting killed
2062 for hogging memory. Windows allocates all this memory at once, so
2063 no program would realistically set a value above our maximum. */
2064 return editor->nUndoLimit;
2066 case EM_CANUNDO:
2067 return editor->pUndoStack != NULL;
2068 case EM_CANREDO:
2069 return editor->pRedoStack != NULL;
2070 case WM_UNDO: /* FIXME: actually not the same */
2071 case EM_UNDO:
2072 return ME_Undo(editor);
2073 case EM_REDO:
2074 return ME_Redo(editor);
2075 case EM_GETOPTIONS:
2077 /* these flags are equivalent to the ES_* counterparts */
2078 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2079 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2080 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2082 return settings;
2084 case EM_SETOPTIONS:
2086 /* these flags are equivalent to ES_* counterparts
2087 * ECO_READONLY is already implemented in the code, only requires
2088 * setting the bit to work
2090 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2091 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2092 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2093 DWORD settings = mask & raw;
2095 switch(wParam)
2097 case ECOOP_SET:
2098 settings = lParam;
2099 break;
2100 case ECOOP_OR:
2101 settings |= lParam;
2102 break;
2103 case ECOOP_AND:
2104 settings &= lParam;
2105 break;
2106 case ECOOP_XOR:
2107 settings ^= lParam;
2109 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2111 if (settings & ECO_AUTOWORDSELECTION)
2112 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2113 if (settings & ECO_SELECTIONBAR)
2114 editor->selofs = SELECTIONBAR_WIDTH;
2115 else
2116 editor->selofs = 0;
2117 ME_WrapMarkedParagraphs(editor);
2119 if (settings & ECO_VERTICAL)
2120 FIXME("ECO_VERTICAL not implemented yet!\n");
2121 if (settings & ECO_AUTOHSCROLL)
2122 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2123 if (settings & ECO_AUTOVSCROLL)
2124 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2125 if (settings & ECO_NOHIDESEL)
2126 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2127 if (settings & ECO_WANTRETURN)
2128 FIXME("ECO_WANTRETURN not implemented yet!\n");
2130 return settings;
2132 case EM_SETSEL:
2134 ME_InvalidateSelection(editor);
2135 ME_SetSelection(editor, wParam, lParam);
2136 ME_InvalidateSelection(editor);
2137 ME_SendSelChange(editor);
2138 return 0;
2140 case EM_SETSCROLLPOS:
2142 POINT *point = (POINT *)lParam;
2143 ME_ScrollAbs(editor, point->y);
2144 return 0;
2146 case EM_AUTOURLDETECT:
2148 if (wParam==1 || wParam ==0)
2150 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2151 return 0;
2153 return E_INVALIDARG;
2155 case EM_GETAUTOURLDETECT:
2157 return editor->AutoURLDetect_bEnable;
2159 case EM_EXSETSEL:
2161 int end;
2162 CHARRANGE range = *(CHARRANGE *)lParam;
2164 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2166 ME_InvalidateSelection(editor);
2167 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2168 ME_InvalidateSelection(editor);
2169 ME_SendSelChange(editor);
2171 return end;
2173 case EM_SHOWSCROLLBAR:
2175 ShowScrollBar(editor->hWnd, wParam, lParam);
2176 return 0;
2178 case EM_SETTEXTEX:
2180 LPWSTR wszText;
2181 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2182 size_t len;
2183 int from, to;
2184 ME_Style *style;
2185 int oldModify = editor->nModifyStep;
2187 if (!pStruct) return 0;
2189 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2190 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2191 pStruct->flags, pStruct->codepage);
2193 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2194 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2195 len = wszText ? lstrlenW(wszText) : 0;
2197 if (pStruct->flags & ST_SELECTION) {
2198 ME_GetSelection(editor, &from, &to);
2199 style = ME_GetSelectionInsertStyle(editor);
2200 ME_InternalDeleteText(editor, from, to - from);
2201 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2202 ME_StreamInRTFString(editor, 0, (char *)lParam);
2203 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2204 ME_ReleaseStyle(style);
2206 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2208 else {
2209 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2210 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2211 ME_StreamInRTFString(editor, 0, (char *)lParam);
2212 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2213 len = 1;
2215 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2217 ME_CommitUndo(editor);
2218 if (!(pStruct->flags & ST_KEEPUNDO))
2220 editor->nModifyStep = oldModify;
2221 ME_EmptyUndoStack(editor);
2223 ME_UpdateRepaint(editor);
2224 return len;
2226 case EM_SETBKGNDCOLOR:
2228 LRESULT lColor;
2229 if (editor->rgbBackColor != -1) {
2230 DeleteObject(editor->hbrBackground);
2231 lColor = editor->rgbBackColor;
2233 else lColor = GetSysColor(COLOR_WINDOW);
2235 if (wParam)
2237 editor->rgbBackColor = -1;
2238 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2240 else
2242 editor->rgbBackColor = lParam;
2243 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2245 if (editor->bRedraw)
2247 InvalidateRect(hWnd, NULL, TRUE);
2248 UpdateWindow(hWnd);
2250 return lColor;
2252 case EM_GETMODIFY:
2253 return editor->nModifyStep == 0 ? 0 : -1;
2254 case EM_SETMODIFY:
2256 if (wParam)
2257 editor->nModifyStep = 1;
2258 else
2259 editor->nModifyStep = 0;
2261 return 0;
2263 case EM_SETREADONLY:
2265 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2266 if (wParam)
2267 nStyle |= ES_READONLY;
2268 else
2269 nStyle &= ~ES_READONLY;
2270 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2271 return 0;
2273 case EM_SETEVENTMASK:
2275 DWORD nOldMask = editor->nEventMask;
2277 editor->nEventMask = lParam;
2278 return nOldMask;
2280 case EM_GETEVENTMASK:
2281 return editor->nEventMask;
2282 case EM_SETCHARFORMAT:
2284 CHARFORMAT2W buf, *p;
2285 BOOL bRepaint = TRUE;
2286 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2287 if (p == NULL) return 0;
2288 if (!wParam)
2289 ME_SetDefaultCharFormat(editor, p);
2290 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2291 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2292 return 0;
2293 } else if (wParam == SCF_ALL) {
2294 if (editor->mode & TM_PLAINTEXT)
2295 ME_SetDefaultCharFormat(editor, p);
2296 else {
2297 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2298 editor->nModifyStep = 1;
2300 } else if (editor->mode & TM_PLAINTEXT) {
2301 return 0;
2302 } else {
2303 int from, to;
2304 ME_GetSelection(editor, &from, &to);
2305 bRepaint = (from != to);
2306 ME_SetSelectionCharFormat(editor, p);
2307 if (from != to) editor->nModifyStep = 1;
2309 ME_CommitUndo(editor);
2310 if (bRepaint)
2311 ME_RewrapRepaint(editor);
2312 return 1;
2314 case EM_GETCHARFORMAT:
2316 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2317 if (dst->cbSize != sizeof(CHARFORMATA) &&
2318 dst->cbSize != sizeof(CHARFORMATW) &&
2319 dst->cbSize != sizeof(CHARFORMAT2A) &&
2320 dst->cbSize != sizeof(CHARFORMAT2W))
2321 return 0;
2322 tmp.cbSize = sizeof(tmp);
2323 if (!wParam)
2324 ME_GetDefaultCharFormat(editor, &tmp);
2325 else
2326 ME_GetSelectionCharFormat(editor, &tmp);
2327 ME_CopyToCFAny(dst, &tmp);
2328 return tmp.dwMask;
2330 case EM_SETPARAFORMAT:
2331 ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2332 ME_RewrapRepaint(editor);
2333 ME_CommitUndo(editor);
2334 return 0;
2335 case EM_GETPARAFORMAT:
2336 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2337 return 0;
2338 case EM_GETFIRSTVISIBLELINE:
2340 ME_DisplayItem *p = editor->pBuffer->pFirst;
2341 int y = ME_GetYScrollPos(editor);
2342 int ypara = 0;
2343 int count = 0;
2344 int ystart, yend;
2345 while(p) {
2346 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2347 if (p->type == diTextEnd)
2348 break;
2349 if (p->type == diParagraph) {
2350 ypara = p->member.para.nYPos;
2351 continue;
2353 ystart = ypara + p->member.row.nYPos;
2354 yend = ystart + p->member.row.nHeight;
2355 if (y < yend) {
2356 break;
2358 count++;
2360 return count;
2362 case EM_HIDESELECTION:
2364 editor->bHideSelection = (wParam != 0);
2365 ME_InvalidateSelection(editor);
2366 return 0;
2368 case EM_LINESCROLL:
2370 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2371 return TRUE; /* Should return false if a single line richedit control */
2373 case WM_CLEAR:
2375 int from, to;
2376 ME_GetSelection(editor, &from, &to);
2377 ME_InternalDeleteText(editor, from, to-from);
2378 ME_CommitUndo(editor);
2379 ME_UpdateRepaint(editor);
2380 return 0;
2382 case EM_REPLACESEL:
2384 int from, to;
2385 ME_Style *style;
2386 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2387 size_t len = wszText ? lstrlenW(wszText) : 0;
2388 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2390 ME_GetSelection(editor, &from, &to);
2391 style = ME_GetSelectionInsertStyle(editor);
2392 ME_InternalDeleteText(editor, from, to-from);
2393 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2394 ME_ReleaseStyle(style);
2395 /* drop temporary style if line end */
2397 * FIXME question: does abc\n mean: put abc,
2398 * clear temp style, put \n? (would require a change)
2400 if (len>0 && wszText[len-1] == '\n')
2401 ME_ClearTempStyle(editor);
2402 ME_EndToUnicode(unicode, wszText);
2403 ME_CommitUndo(editor);
2404 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2405 if (!wParam)
2406 ME_EmptyUndoStack(editor);
2407 ME_UpdateRepaint(editor);
2408 return len;
2410 case EM_SCROLLCARET:
2412 int top, bottom; /* row's edges relative to document top */
2413 int nPos;
2414 ME_DisplayItem *para, *row;
2416 nPos = ME_GetYScrollPos(editor);
2417 row = ME_RowStart(editor->pCursors[0].pRun);
2418 para = ME_GetParagraph(row);
2419 top = para->member.para.nYPos + row->member.row.nYPos;
2420 bottom = top + row->member.row.nHeight;
2422 if (top < nPos) /* caret above window */
2423 ME_ScrollAbs(editor, top);
2424 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2425 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2426 return 0;
2428 case WM_SETFONT:
2430 LOGFONTW lf;
2431 CHARFORMAT2W fmt;
2432 HDC hDC;
2433 BOOL bRepaint = LOWORD(lParam);
2435 if (!wParam)
2436 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2437 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2438 hDC = GetDC(hWnd);
2439 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2440 ReleaseDC(hWnd, hDC);
2441 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2442 ME_SetDefaultCharFormat(editor, &fmt);
2444 ME_CommitUndo(editor);
2445 if (bRepaint)
2446 ME_RewrapRepaint(editor);
2447 return 0;
2449 case WM_SETTEXT:
2451 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2452 if (lParam)
2454 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2455 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2457 /* Undocumented: WM_SETTEXT supports RTF text */
2458 ME_StreamInRTFString(editor, 0, (char *)lParam);
2460 else
2462 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2463 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2464 if (lstrlenW(wszText) > 0)
2466 int len = -1;
2468 /* uses default style! */
2469 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2471 WCHAR * p;
2473 p = wszText;
2474 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2475 len = p - wszText;
2477 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2479 ME_EndToUnicode(unicode, wszText);
2482 else
2483 TRACE("WM_SETTEXT - NULL\n");
2484 if (editor->AutoURLDetect_bEnable)
2486 ME_UpdateLinkAttribute(editor, 0, -1);
2488 ME_SetSelection(editor, 0, 0);
2489 editor->nModifyStep = 0;
2490 ME_CommitUndo(editor);
2491 ME_EmptyUndoStack(editor);
2492 ME_UpdateRepaint(editor);
2493 return 1;
2495 case EM_CANPASTE:
2497 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2498 if (IsClipboardFormatAvailable(nRTFFormat))
2499 return TRUE;
2500 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2501 return TRUE;
2502 return FALSE;
2504 case WM_PASTE:
2506 DWORD dwFormat = 0;
2507 EDITSTREAM es;
2508 ME_GlobalDestStruct gds;
2509 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2510 UINT cf = 0;
2512 if (IsClipboardFormatAvailable(nRTFFormat))
2513 cf = nRTFFormat, dwFormat = SF_RTF;
2514 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2515 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2516 else
2517 return 0;
2519 if (!OpenClipboard(hWnd))
2520 return 0;
2521 gds.hData = GetClipboardData(cf);
2522 gds.nLength = 0;
2523 es.dwCookie = (DWORD)&gds;
2524 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2525 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2527 CloseClipboard();
2528 return 0;
2530 case WM_CUT:
2531 case WM_COPY:
2533 LPDATAOBJECT dataObj = NULL;
2534 CHARRANGE range;
2535 HRESULT hr = S_OK;
2537 if (editor->cPasswordMask)
2538 return 0; /* Copying or Cutting masked text isn't allowed */
2540 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2541 if(editor->lpOleCallback)
2542 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2543 if(FAILED(hr) || !dataObj)
2544 hr = ME_GetDataObject(editor, &range, &dataObj);
2545 if(SUCCEEDED(hr)) {
2546 hr = OleSetClipboard(dataObj);
2547 IDataObject_Release(dataObj);
2549 if (SUCCEEDED(hr) && msg == WM_CUT)
2551 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2552 ME_CommitUndo(editor);
2553 ME_UpdateRepaint(editor);
2555 return 0;
2557 case WM_GETTEXTLENGTH:
2559 GETTEXTLENGTHEX how;
2561 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2562 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2563 how.codepage = unicode ? 1200 : CP_ACP;
2564 return ME_GetTextLengthEx(editor, &how);
2566 case EM_GETTEXTLENGTHEX:
2567 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2568 case WM_GETTEXT:
2570 GETTEXTEX ex;
2571 LRESULT rc;
2572 LPSTR bufferA = NULL;
2573 LPWSTR bufferW = NULL;
2575 if (unicode)
2576 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2577 else
2578 bufferA = heap_alloc(wParam + 2);
2580 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2581 ex.flags = GT_USECRLF;
2582 ex.codepage = unicode ? 1200 : CP_ACP;
2583 ex.lpDefaultChar = NULL;
2584 ex.lpUsedDefChar = NULL;
2585 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2587 if (unicode)
2589 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2590 if (lstrlenW(bufferW) >= wParam) rc = 0;
2592 else
2594 memcpy((LPSTR)lParam, bufferA, wParam);
2595 if (strlen(bufferA) >= wParam) rc = 0;
2597 heap_free(bufferA);
2598 heap_free(bufferW);
2599 return rc;
2601 case EM_GETTEXTEX:
2603 GETTEXTEX *ex = (GETTEXTEX*)wParam;
2604 int nStart, nCount; /* in chars */
2606 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2607 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2609 if (ex->flags & GT_SELECTION)
2611 ME_GetSelection(editor, &nStart, &nCount);
2612 nCount -= nStart;
2614 else
2616 nStart = 0;
2617 nCount = 0x7fffffff;
2619 if (ex->codepage == 1200)
2621 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2622 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2624 else
2626 /* potentially each char may be a CR, why calculate the exact value with O(N) when
2627 we can just take a bigger buffer? :)
2628 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2629 occurs only in richedit 2.0 mode, in which line breaks have only one CR
2631 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2632 LPWSTR buffer;
2633 DWORD buflen = ex->cb;
2634 LRESULT rc;
2635 DWORD flags = 0;
2637 nCount = min(nCount, ex->cb - 1);
2638 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2640 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2641 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2642 if (rc) rc--; /* do not count 0 terminator */
2644 heap_free(buffer);
2645 return rc;
2648 case EM_GETSELTEXT:
2650 int from, to;
2651 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2652 ME_GetSelection(editor, &from, &to);
2653 tr.chrg.cpMin = from;
2654 tr.chrg.cpMax = to;
2655 tr.lpstrText = (WCHAR *)lParam;
2656 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2658 case EM_GETSCROLLPOS:
2660 POINT *point = (POINT *)lParam;
2661 point->x = 0; /* FIXME side scrolling not implemented */
2662 point->y = ME_GetYScrollPos(editor);
2663 return 1;
2665 case EM_GETTEXTRANGE:
2667 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2668 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2669 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2670 editor->bEmulateVersion10, ME_GetTextLength(editor));
2671 if (unicode)
2672 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
2673 else
2675 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2676 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2677 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
2678 /* FIXME this is a potential security hole (buffer overrun)
2679 if you know more about wchar->mbyte conversion please explain
2681 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2682 FREE_OBJ(p);
2683 return nChars;
2686 case EM_GETLINE:
2688 ME_DisplayItem *run;
2689 const unsigned int nMaxChars = *(WORD *) lParam;
2690 unsigned int nCharsLeft = nMaxChars;
2691 char *dest = (char *) lParam;
2692 BOOL wroteNull = FALSE;
2694 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2695 unicode ? "Unicode" : "Ansi");
2697 run = ME_FindRowWithNumber(editor, wParam);
2698 if (run == NULL)
2699 return 0;
2701 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2702 && !(run->member.run.nFlags & MERF_ENDPARA))
2704 unsigned int nCopy;
2705 ME_String *strText;
2706 if (run->type != diRun)
2707 break;
2708 strText = run->member.run.strText;
2709 nCopy = min(nCharsLeft, strText->nLen);
2711 if (unicode)
2712 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2713 else
2714 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2715 nCharsLeft, NULL, NULL);
2716 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2717 nCharsLeft -= nCopy;
2720 /* append line termination, space allowing */
2721 if (nCharsLeft > 0)
2723 if (run && (run->member.run.nFlags & MERF_ENDPARA))
2725 unsigned int i;
2726 /* Write as many \r as encoded in end-of-paragraph, space allowing */
2727 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
2729 *((WCHAR *)dest) = '\r';
2730 dest += unicode ? sizeof(WCHAR) : 1;
2732 /* Write as many \n as encoded in end-of-paragraph, space allowing */
2733 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
2735 *((WCHAR *)dest) = '\n';
2736 dest += unicode ? sizeof(WCHAR) : 1;
2739 if (nCharsLeft > 0)
2741 if (unicode)
2742 *((WCHAR *)dest) = '\0';
2743 else
2744 *dest = '\0';
2745 nCharsLeft--;
2746 wroteNull = TRUE;
2750 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
2751 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
2753 case EM_GETLINECOUNT:
2755 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2756 int nRows = 0;
2758 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
2760 while (item != editor->pBuffer->pLast)
2762 assert(item->type == diParagraph);
2763 prev_para = ME_FindItemBack(item, diRun);
2764 if (prev_para) {
2765 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
2767 nRows += item->member.para.nRows;
2768 item = item->member.para.next_para;
2770 last_para = ME_FindItemBack(item, diRun);
2771 assert(last_para);
2772 assert(last_para->member.run.nFlags & MERF_ENDPARA);
2773 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
2774 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
2776 /* In 1.0 emulation, the last solitary \r at the very end of the text
2777 (if one exists) is NOT a line break.
2778 FIXME: this is an ugly hack. This should have a more regular model. */
2779 nRows--;
2782 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2783 return max(1, nRows);
2785 case EM_LINEFROMCHAR:
2787 if (wParam == -1)
2788 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2789 else
2790 return ME_RowNumberFromCharOfs(editor, wParam);
2792 case EM_EXLINEFROMCHAR:
2794 if (lParam == -1)
2795 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2796 else
2797 return ME_RowNumberFromCharOfs(editor, lParam);
2799 case EM_LINEINDEX:
2801 ME_DisplayItem *item, *para;
2802 int nCharOfs;
2804 if (wParam == -1)
2805 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2806 else
2807 item = ME_FindRowWithNumber(editor, wParam);
2808 if (!item)
2809 return -1;
2810 para = ME_GetParagraph(item);
2811 item = ME_FindItemFwd(item, diRun);
2812 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2813 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2814 return nCharOfs;
2816 case EM_LINELENGTH:
2818 ME_DisplayItem *item, *item_end;
2819 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2821 if (wParam > ME_GetTextLength(editor))
2822 return 0;
2823 if (wParam == -1)
2825 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2826 return 0;
2828 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2829 item = ME_RowStart(item);
2830 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2831 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2832 if (item_end->type == diStartRow)
2833 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2834 else
2836 ME_DisplayItem *endPara;
2838 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
2839 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
2840 endPara = ME_FindItemBack(endPara, diRun);
2841 assert(endPara);
2842 assert(endPara->type == diRun);
2843 assert(endPara->member.run.nFlags & MERF_ENDPARA);
2844 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
2846 nChars = nNextLineOfs - nThisLineOfs;
2847 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2848 return nChars;
2850 case EM_EXLIMITTEXT:
2852 if ((int)lParam < 0)
2853 return 0;
2854 if (lParam == 0)
2855 editor->nTextLimit = 65536;
2856 else
2857 editor->nTextLimit = (int) lParam;
2858 return 0;
2860 case EM_LIMITTEXT:
2862 if (wParam == 0)
2863 editor->nTextLimit = 65536;
2864 else
2865 editor->nTextLimit = (int) wParam;
2866 return 0;
2868 case EM_GETLIMITTEXT:
2870 return editor->nTextLimit;
2872 case EM_FINDTEXT:
2874 FINDTEXTA *ft = (FINDTEXTA *)lParam;
2875 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2876 WCHAR *tmp;
2877 LRESULT r;
2879 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2880 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2881 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2882 FREE_OBJ( tmp );
2883 return r;
2885 case EM_FINDTEXTEX:
2887 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2888 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2889 WCHAR *tmp;
2890 LRESULT r;
2892 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2893 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2894 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2895 FREE_OBJ( tmp );
2896 return r;
2898 case EM_FINDTEXTW:
2900 FINDTEXTW *ft = (FINDTEXTW *)lParam;
2901 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2903 case EM_FINDTEXTEXW:
2905 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2906 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2908 case EM_GETZOOM:
2909 if (!wParam || !lParam)
2910 return FALSE;
2911 *(int *)wParam = editor->nZoomNumerator;
2912 *(int *)lParam = editor->nZoomDenominator;
2913 return TRUE;
2914 case EM_SETZOOM:
2915 return ME_SetZoom(editor, wParam, lParam);
2916 case EM_CHARFROMPOS:
2917 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2918 case EM_POSFROMCHAR:
2920 ME_DisplayItem *pRun;
2921 int nCharOfs, nOffset, nLength;
2922 POINTL pt = {0,0};
2923 SCROLLINFO si;
2925 nCharOfs = wParam;
2926 /* detect which API version we're dealing with */
2927 if (wParam >= 0x40000)
2928 nCharOfs = lParam;
2929 nLength = ME_GetTextLength(editor);
2931 if (nCharOfs < nLength) {
2932 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2933 assert(pRun->type == diRun);
2934 pt.y = pRun->member.run.pt.y;
2935 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2936 pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2937 } else {
2938 pt.x = 0;
2939 pt.y = editor->pBuffer->pLast->member.para.nYPos;
2941 pt.x += editor->selofs;
2943 si.cbSize = sizeof(si);
2944 si.fMask = SIF_POS;
2945 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
2946 si.cbSize = sizeof(si);
2947 si.fMask = SIF_POS;
2948 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
2950 if (wParam >= 0x40000) {
2951 *(POINTL *)wParam = pt;
2953 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
2955 case WM_CREATE:
2956 GetClientRect(hWnd, &editor->rcFormat);
2957 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2958 { /* Squelch the default horizontal scrollbar it would make */
2959 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2961 ME_CommitUndo(editor);
2962 ME_WrapMarkedParagraphs(editor);
2963 ME_MoveCaret(editor);
2964 return 0;
2965 case WM_DESTROY:
2966 ME_DestroyEditor(editor);
2967 SetWindowLongPtrW(hWnd, 0, 0);
2968 return 0;
2969 case WM_LBUTTONDOWN:
2970 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2971 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2972 !ME_FilterEvent(editor, msg, &wParam, &lParam))
2973 return 0;
2974 SetFocus(hWnd);
2975 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2976 SetCapture(hWnd);
2977 ME_LinkNotify(editor,msg,wParam,lParam);
2978 if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
2979 break;
2980 case WM_MOUSEMOVE:
2981 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2982 !ME_FilterEvent(editor, msg, &wParam, &lParam))
2983 return 0;
2984 if (GetCapture() == hWnd)
2985 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2986 ME_LinkNotify(editor,msg,wParam,lParam);
2987 if (!ME_SetCursor(editor, LOWORD(lParam))) goto do_default;
2988 break;
2989 case WM_LBUTTONUP:
2990 if (GetCapture() == hWnd)
2991 ReleaseCapture();
2992 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
2993 !ME_FilterEvent(editor, msg, &wParam, &lParam))
2994 return 0;
2995 else
2997 BOOL ret;
2998 editor->linesel = 0;
2999 ret = ME_SetCursor(editor, LOWORD(lParam));
3000 ME_LinkNotify(editor,msg,wParam,lParam);
3001 if (!ret) goto do_default;
3003 break;
3004 case WM_LBUTTONDBLCLK:
3005 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3006 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3007 return 0;
3008 ME_LinkNotify(editor,msg,wParam,lParam);
3009 ME_SelectWord(editor);
3010 break;
3011 case WM_RBUTTONUP:
3012 case WM_RBUTTONDOWN:
3013 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3014 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3015 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3016 return 0;
3017 goto do_default;
3018 case WM_CONTEXTMENU:
3019 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3020 goto do_default;
3021 break;
3022 case WM_PAINT:
3023 if (editor->bRedraw)
3025 HDC hDC;
3026 PAINTSTRUCT ps;
3028 hDC = BeginPaint(hWnd, &ps);
3029 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3030 EndPaint(hWnd, &ps);
3032 break;
3033 case WM_SETFOCUS:
3034 editor->bHaveFocus = TRUE;
3035 ME_ShowCaret(editor);
3036 ME_SendOldNotify(editor, EN_SETFOCUS);
3037 return 0;
3038 case WM_KILLFOCUS:
3039 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3040 ME_HideCaret(editor);
3041 editor->bHaveFocus = FALSE;
3042 ME_SendOldNotify(editor, EN_KILLFOCUS);
3043 return 0;
3044 case WM_ERASEBKGND:
3046 if (editor->bRedraw)
3048 HDC hDC = (HDC)wParam;
3049 RECT rc;
3050 if (GetUpdateRect(hWnd,&rc,TRUE))
3052 FillRect(hDC, &rc, editor->hbrBackground);
3055 return 1;
3057 case WM_COMMAND:
3058 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3059 return 0;
3060 case WM_KEYUP:
3061 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3062 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3063 return 0;
3064 goto do_default;
3065 case WM_KEYDOWN:
3066 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3067 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3068 return 0;
3069 if (ME_KeyDown(editor, LOWORD(wParam)))
3070 return 0;
3071 goto do_default;
3072 case WM_CHAR:
3074 WCHAR wstr;
3076 if (unicode)
3077 wstr = (WCHAR)wParam;
3078 else
3080 CHAR charA = wParam;
3081 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3084 switch (wstr)
3086 case 1: /* Ctrl-A */
3087 ME_SetSelection(editor, 0, -1);
3088 return 0;
3089 case 3: /* Ctrl-C */
3090 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3091 return 0;
3094 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3095 MessageBeep(MB_ICONERROR);
3096 return 0; /* FIXME really 0 ? */
3099 switch (wstr)
3101 case 22: /* Ctrl-V */
3102 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3103 return 0;
3104 case 24: /* Ctrl-X */
3105 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3106 return 0;
3107 case 25: /* Ctrl-Y */
3108 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3109 return 0;
3110 case 26: /* Ctrl-Z */
3111 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3112 return 0;
3114 if (((unsigned)wstr)>=' '
3115 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3116 || wstr=='\t') {
3117 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3118 /* WM_CHAR is restricted to nTextLimit */
3119 int from, to;
3120 ME_GetSelection(editor, &from, &to);
3121 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3123 ME_Style *style = ME_GetInsertStyle(editor, 0);
3124 ME_SaveTempStyle(editor);
3125 ME_ContinueCoalescingTransaction(editor);
3126 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3127 ME_InsertEndRowFromCursor(editor, 0);
3128 else
3129 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3130 ME_ReleaseStyle(style);
3131 ME_CommitCoalescingUndo(editor);
3134 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3136 ME_UpdateRepaint(editor);
3138 return 0;
3140 case EM_STOPGROUPTYPING:
3141 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3142 return 0;
3143 case EM_SCROLL: /* fall through */
3144 case WM_VSCROLL:
3146 int origNPos;
3147 int lineHeight;
3149 origNPos = ME_GetYScrollPos(editor);
3150 lineHeight = 24;
3152 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3153 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3154 if (lineHeight <= 0) lineHeight = 24;
3156 switch(LOWORD(wParam))
3158 case SB_LINEUP:
3159 ME_ScrollUp(editor,lineHeight);
3160 break;
3161 case SB_LINEDOWN:
3162 ME_ScrollDown(editor,lineHeight);
3163 break;
3164 case SB_PAGEUP:
3165 ME_ScrollUp(editor,editor->sizeWindow.cy);
3166 break;
3167 case SB_PAGEDOWN:
3168 ME_ScrollDown(editor,editor->sizeWindow.cy);
3169 break;
3170 case SB_THUMBTRACK:
3171 case SB_THUMBPOSITION:
3172 ME_ScrollAbs(editor,HIWORD(wParam));
3173 break;
3175 if (msg == EM_SCROLL)
3176 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3177 break;
3179 case WM_MOUSEWHEEL:
3181 int gcWheelDelta;
3182 UINT pulScrollLines;
3184 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3185 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3186 return 0;
3188 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3189 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3191 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3193 /* FIXME follow the original */
3194 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3196 break;
3198 case EM_GETRECT:
3200 *((RECT *)lParam) = editor->rcFormat;
3201 return 0;
3203 case EM_SETRECT:
3204 case EM_SETRECTNP:
3206 if (lParam)
3208 RECT *rc = (RECT *)lParam;
3210 if (wParam)
3212 editor->rcFormat.left += rc->left;
3213 editor->rcFormat.top += rc->top;
3214 editor->rcFormat.right += rc->right;
3215 editor->rcFormat.bottom += rc->bottom;
3217 else
3219 editor->rcFormat = *rc;
3222 else
3224 GetClientRect(hWnd, &editor->rcFormat);
3226 if (msg != EM_SETRECTNP)
3227 ME_RewrapRepaint(editor);
3228 return 0;
3230 case EM_REQUESTRESIZE:
3231 ME_SendRequestResize(editor, TRUE);
3232 return 0;
3233 case WM_SETREDRAW:
3234 if ((editor->bRedraw = wParam))
3235 ME_RewrapRepaint(editor);
3236 return 0;
3237 case WM_SIZE:
3239 GetClientRect(hWnd, &editor->rcFormat);
3240 ME_RewrapRepaint(editor);
3241 return DefWindowProcW(hWnd, msg, wParam, lParam);
3243 /* IME messages to make richedit controls IME aware */
3244 case WM_IME_SETCONTEXT:
3245 case WM_IME_CONTROL:
3246 case WM_IME_SELECT:
3247 case WM_IME_COMPOSITIONFULL:
3248 return 0;
3249 case WM_IME_STARTCOMPOSITION:
3251 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3252 ME_DeleteSelection(editor);
3253 ME_CommitUndo(editor);
3254 ME_UpdateRepaint(editor);
3255 return 0;
3257 case WM_IME_COMPOSITION:
3259 HIMC hIMC;
3261 ME_Style *style = ME_GetInsertStyle(editor, 0);
3262 hIMC = ImmGetContext(hWnd);
3263 ME_DeleteSelection(editor);
3264 ME_CommitUndo(editor);
3265 ME_SaveTempStyle(editor);
3266 if (lParam & GCS_RESULTSTR)
3268 LPWSTR lpCompStr = NULL;
3269 DWORD dwBufLen;
3271 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3272 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3273 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3274 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3275 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3277 else if (lParam & GCS_COMPSTR)
3279 LPWSTR lpCompStr = NULL;
3280 DWORD dwBufLen;
3282 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3283 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3284 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3285 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3287 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3288 ME_SetSelection(editor,editor->imeStartIndex,
3289 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3291 ME_ReleaseStyle(style);
3292 ME_UpdateRepaint(editor);
3293 return 0;
3295 case WM_IME_ENDCOMPOSITION:
3297 ME_DeleteSelection(editor);
3298 editor->imeStartIndex=-1;
3299 return 0;
3301 case EM_GETOLEINTERFACE:
3303 LPVOID *ppvObj = (LPVOID*) lParam;
3304 return CreateIRichEditOle(editor, ppvObj);
3306 case EM_GETPASSWORDCHAR:
3308 return editor->cPasswordMask;
3310 case EM_SETOLECALLBACK:
3311 if(editor->lpOleCallback)
3312 IUnknown_Release(editor->lpOleCallback);
3313 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3314 if(editor->lpOleCallback)
3315 IUnknown_AddRef(editor->lpOleCallback);
3316 return TRUE;
3317 case EM_GETWORDBREAKPROC:
3318 return (LRESULT)editor->pfnWordBreak;
3319 case EM_SETWORDBREAKPROC:
3321 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3323 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3324 return (LRESULT)pfnOld;
3326 case EM_SETTEXTMODE:
3328 LRESULT ret;
3329 int mask = 0;
3330 int changes = 0;
3331 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3332 if (!ret)
3334 /*Check for valid wParam*/
3335 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3336 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3337 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3338 return 1;
3339 else
3341 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3343 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3344 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3346 /*FIXME: Currently no support for undo level and code page options*/
3347 editor->mode = (editor->mode & (~mask)) | changes;
3348 return 0;
3351 return ret;
3353 case EM_SETPASSWORDCHAR:
3355 editor->cPasswordMask = wParam;
3356 ME_RewrapRepaint(editor);
3357 return 0;
3359 case EM_SETTARGETDEVICE:
3360 if (wParam == 0)
3362 BOOL new = (lParam == 0);
3363 if (editor->bWordWrap != new)
3365 editor->bWordWrap = new;
3366 ME_RewrapRepaint(editor);
3369 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3370 break;
3371 default:
3372 do_default:
3373 return DefWindowProcW(hWnd, msg, wParam, lParam);
3375 return 0L;
3378 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3380 BOOL unicode = TRUE;
3382 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3383 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3384 unicode = FALSE;
3386 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3389 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3391 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3394 /******************************************************************
3395 * RichEditANSIWndProc (RICHED20.10)
3397 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3399 return RichEditWndProcA(hWnd, msg, wParam, lParam);
3402 /******************************************************************
3403 * RichEdit10ANSIWndProc (RICHED20.9)
3405 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3407 LRESULT result;
3409 /* FIXME: this is NOT the same as 2.0 version */
3410 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3411 if (msg == WM_NCCREATE)
3413 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3415 editor->bEmulateVersion10 = TRUE;
3416 editor->pBuffer->pLast->member.para.nCharOfs = 2;
3417 assert(editor->pBuffer->pLast->prev->type == diRun);
3418 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3419 editor->pBuffer->pLast->prev->member.run.nLF = 1;
3421 return result;
3424 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3426 HWND hWnd = editor->hWnd;
3427 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3430 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3432 int x,y;
3433 ME_Cursor tmpCursor;
3434 int nCharOfs; /* The start of the clicked text. Absolute character offset */
3436 ME_Run *tmpRun;
3438 ENLINK info;
3439 x = (short)LOWORD(lParam);
3440 y = (short)HIWORD(lParam);
3441 nCharOfs = ME_CharFromPos(editor, x, y);
3442 if (nCharOfs < 0) return;
3444 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3445 tmpRun = &tmpCursor.pRun->member.run;
3447 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3448 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3449 { /* The clicked run has CFE_LINK set */
3450 info.nmhdr.hwndFrom = editor->hWnd;
3451 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3452 info.nmhdr.code = EN_LINK;
3453 info.msg = msg;
3454 info.wParam = wParam;
3455 info.lParam = lParam;
3456 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3457 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3458 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3462 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3464 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3465 int i = 0;
3467 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3468 item = item->member.para.next_para;
3469 if (!item)
3470 return 0;
3471 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3472 item = item->member.para.next_para;
3473 i++;
3475 return i;
3479 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3481 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3482 int nWritten = 0;
3483 WCHAR *pStart = buffer;
3485 if (!item) {
3486 *buffer = 0;
3487 return 0;
3490 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3491 if (editor->bEmulateVersion10) bCRLF = 0;
3493 if (nStart)
3495 int nLen = ME_StrLen(item->member.run.strText) - nStart;
3496 if (nLen > nChars)
3497 nLen = nChars;
3498 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3499 nChars -= nLen;
3500 nWritten += nLen;
3501 buffer += nLen;
3502 if (!nChars) {
3503 *buffer = 0;
3504 return nWritten;
3506 nStart = 0;
3507 item = ME_FindItemFwd(item, diRun);
3510 while(nChars && item)
3512 int nLen = ME_StrLen(item->member.run.strText);
3513 if (item->member.run.nFlags & MERF_ENDPARA)
3514 nLen = item->member.run.nCR + item->member.run.nLF;
3515 if (nLen > nChars)
3516 nLen = nChars;
3518 if (item->member.run.nFlags & MERF_ENDPARA)
3520 if (!ME_FindItemFwd(item, diRun))
3521 /* No '\r' is appended to the last paragraph. */
3522 nLen = 0;
3523 else if (bCRLF && nChars == 1) {
3524 nLen = 0;
3525 nChars = 0;
3526 } else {
3527 if (bCRLF)
3529 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
3530 assert(nLen == 1);
3531 *buffer++ = '\r';
3532 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
3533 nWritten++;
3535 else
3537 int i, j;
3539 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
3540 i = 0;
3541 while (nChars - i > 0 && i < item->member.run.nCR)
3543 buffer[i] = '\r'; i++;
3545 j = 0;
3546 while (nChars - i - j > 0 && j < item->member.run.nLF)
3548 buffer[i+j] = '\n'; j++;
3553 else
3554 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
3555 nChars -= nLen;
3556 nWritten += nLen;
3557 buffer += nLen;
3559 if (!nChars)
3561 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3562 *buffer = 0;
3563 return nWritten;
3565 item = ME_FindItemFwd(item, diRun);
3567 *buffer = 0;
3568 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3569 return nWritten;
3572 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
3574 WNDCLASSW wcW;
3575 WNDCLASSA wcA;
3577 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3578 wcW.lpfnWndProc = RichEditWndProcW;
3579 wcW.cbClsExtra = 0;
3580 wcW.cbWndExtra = sizeof(ME_TextEditor *);
3581 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
3582 wcW.hIcon = NULL;
3583 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3584 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3585 wcW.lpszMenuName = NULL;
3587 if (is_version_nt())
3589 wcW.lpszClassName = RichEdit20W;
3590 if (!RegisterClassW(&wcW)) return FALSE;
3591 wcW.lpszClassName = RichEdit50W;
3592 if (!RegisterClassW(&wcW)) return FALSE;
3594 else
3596 /* WNDCLASSA/W have the same layout */
3597 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
3598 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3599 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
3600 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3603 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3604 wcA.lpfnWndProc = RichEditWndProcA;
3605 wcA.cbClsExtra = 0;
3606 wcA.cbWndExtra = sizeof(ME_TextEditor *);
3607 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
3608 wcA.hIcon = NULL;
3609 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3610 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3611 wcA.lpszMenuName = NULL;
3612 wcA.lpszClassName = "RichEdit20A";
3613 if (!RegisterClassA(&wcA)) return FALSE;
3614 wcA.lpszClassName = "RichEdit50A";
3615 if (!RegisterClassA(&wcA)) return FALSE;
3617 return TRUE;
3620 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3621 /* FIXME: Not implemented */
3622 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3623 hWnd, msg, get_msg_name(msg), wParam, lParam);
3624 return DefWindowProcW(hWnd, msg, wParam, lParam);
3627 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3628 /* FIXME: Not implemented */
3629 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3630 hWnd, msg, get_msg_name(msg), wParam, lParam);
3631 return DefWindowProcW(hWnd, msg, wParam, lParam);
3634 /******************************************************************
3635 * REExtendedRegisterClass (RICHED20.8)
3637 * FIXME undocumented
3638 * Need to check for errors and implement controls and callbacks
3640 LRESULT WINAPI REExtendedRegisterClass(void)
3642 WNDCLASSW wcW;
3643 UINT result;
3645 FIXME("semi stub\n");
3647 wcW.cbClsExtra = 0;
3648 wcW.cbWndExtra = 4;
3649 wcW.hInstance = NULL;
3650 wcW.hIcon = NULL;
3651 wcW.hCursor = NULL;
3652 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3653 wcW.lpszMenuName = NULL;
3655 if (!ME_ListBoxRegistered)
3657 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3658 wcW.lpfnWndProc = REListWndProc;
3659 wcW.lpszClassName = REListBox20W;
3660 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3663 if (!ME_ComboBoxRegistered)
3665 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3666 wcW.lpfnWndProc = REComboWndProc;
3667 wcW.lpszClassName = REComboBox20W;
3668 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
3671 result = 0;
3672 if (ME_ListBoxRegistered)
3673 result += 1;
3674 if (ME_ComboBoxRegistered)
3675 result += 2;
3677 return result;
3680 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
3682 struct prefix_s {
3683 const char *text;
3684 int length;
3685 } prefixes[12] = {
3686 {"http:", 5},
3687 {"file:", 6},
3688 {"mailto:", 8},
3689 {"ftp:", 5},
3690 {"https:", 7},
3691 {"gopher:", 8},
3692 {"nntp:", 6},
3693 {"prospero:", 10},
3694 {"telnet:", 8},
3695 {"news:", 6},
3696 {"wais:", 6},
3697 {"www.", 5}
3699 CHARRANGE ins_pt;
3700 int curf_ef, link_ef, def_ef;
3701 int cur_prefx, prefx_cnt;
3702 int sel_min, sel_max;
3703 int car_pos = 0;
3704 int text_pos=-1;
3705 int URLmin, URLmax = 0;
3706 FINDTEXTA ft;
3707 CHARFORMAT2W cur_format;
3708 CHARFORMAT2W default_format;
3709 CHARFORMAT2W link;
3710 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3711 sel_min = ins_pt.cpMin;
3712 sel_max = ins_pt.cpMax;
3713 if (sel_min==sel_max)
3714 car_pos = sel_min;
3715 if (sel_min!=sel_max)
3716 car_pos = ME_GetTextLength(editor)+1;
3717 cur_format.cbSize = sizeof(cur_format);
3718 default_format.cbSize = sizeof(default_format);
3719 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3720 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3721 link.cbSize = sizeof(link);
3722 link.dwMask = CFM_LINK;
3723 link.dwEffects = CFE_LINK;
3724 curf_ef = cur_format.dwEffects & link.dwEffects;
3725 def_ef = default_format.dwEffects & link.dwEffects;
3726 link_ef = link.dwEffects & link.dwEffects;
3727 if (curf_ef == link_ef)
3729 if( curChar == '\n' || curChar=='\r' || curChar==' ')
3731 ME_SetSelection(editor, car_pos, car_pos);
3732 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3733 text_pos=-1;
3734 return 0;
3737 if (curf_ef == def_ef)
3739 cur_prefx = 0;
3740 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3741 while (cur_prefx<=prefx_cnt)
3743 if (text_pos == -1)
3745 ft.lpstrText = prefixes[cur_prefx].text;
3746 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3747 URLmax=max(0, car_pos);
3748 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3750 URLmax = ME_GetTextLength(editor)+1;
3752 ft.chrg.cpMin = URLmin;
3753 ft.chrg.cpMax = URLmax;
3754 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
3755 cur_prefx++;
3757 if (text_pos != -1)
3759 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3760 ME_RewrapRepaint(editor);
3761 break;
3765 return 0;
3769 static BOOL isurlspecial(WCHAR c)
3771 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
3772 return strchrW( special_chars, c ) != NULL;
3776 * This proc takes a selection, and scans it forward in order to select the span
3777 * of a possible URL candidate. A possible URL candidate must start with isalnum
3778 * or one of the following special characters: *|/\+%#@ and must consist entirely
3779 * of the characters allowed to start the URL, plus : (colon) which may occur
3780 * at most once, and not at either end.
3782 * sel_max == -1 indicates scan to end of text.
3784 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
3785 int * candidate_min, int * candidate_max)
3787 ME_DisplayItem * item;
3788 ME_DisplayItem * para;
3789 int nStart;
3790 BOOL foundColon = FALSE;
3791 WCHAR lastAcceptedChar = '\0';
3793 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
3795 *candidate_min = *candidate_max = -1;
3796 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
3797 if (!item) return FALSE;
3798 TRACE("nStart = %d\n", nStart);
3799 para = ME_GetParagraph(item);
3800 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3801 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
3803 ME_DisplayItem * next_item;
3805 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
3806 /* Find start of candidate */
3807 if (*candidate_min == -1) {
3808 while (nStart < ME_StrLen(item->member.run.strText) &&
3809 !(isalnumW(item->member.run.strText->szData[nStart]) ||
3810 isurlspecial(item->member.run.strText->szData[nStart]))) {
3811 nStart++;
3813 if (nStart < ME_StrLen(item->member.run.strText) &&
3814 (isalnumW(item->member.run.strText->szData[nStart]) ||
3815 isurlspecial(item->member.run.strText->szData[nStart]))) {
3816 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3817 lastAcceptedChar = item->member.run.strText->szData[nStart];
3818 nStart++;
3822 /* Find end of candidate */
3823 if (*candidate_min >= 0) {
3824 while (nStart < ME_StrLen(item->member.run.strText) &&
3825 (isalnumW(item->member.run.strText->szData[nStart]) ||
3826 isurlspecial(item->member.run.strText->szData[nStart]) ||
3827 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
3828 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
3829 lastAcceptedChar = item->member.run.strText->szData[nStart];
3830 nStart++;
3832 if (nStart < ME_StrLen(item->member.run.strText) &&
3833 !(isalnumW(item->member.run.strText->szData[nStart]) ||
3834 isurlspecial(item->member.run.strText->szData[nStart]) )) {
3835 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3836 nStart++;
3837 if (lastAcceptedChar == ':') (*candidate_max)--;
3838 return TRUE;
3841 } else {
3842 /* End of paragraph: skip it if before candidate span, or terminates
3843 current active span */
3844 if (*candidate_min >= 0) {
3845 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
3846 if (lastAcceptedChar == ':') (*candidate_max)--;
3847 return TRUE;
3851 /* Reaching this point means no span was found, so get next span */
3852 next_item = ME_FindItemFwd(item, diRun);
3853 if (!next_item) {
3854 if (*candidate_min >= 0) {
3855 /* There are no further runs, so take end of text as end of candidate */
3856 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3857 if (lastAcceptedChar == ':') (*candidate_max)--;
3858 return TRUE;
3861 item = next_item;
3862 para = ME_GetParagraph(item);
3863 nStart = 0;
3866 if (item) {
3867 if (*candidate_min >= 0) {
3868 /* There are no further runs, so take end of text as end of candidate */
3869 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
3870 if (lastAcceptedChar == ':') (*candidate_max)--;
3871 return TRUE;
3874 return FALSE;
3878 * This proc evaluates the selection and returns TRUE if it can be considered an URL
3880 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
3882 struct prefix_s {
3883 const char *text;
3884 int length;
3885 } prefixes[12] = {
3886 /* Code below depends on these being in decreasing length order! */
3887 {"prospero:", 10},
3888 {"telnet:", 8},
3889 {"gopher:", 8},
3890 {"mailto:", 8},
3891 {"https:", 7},
3892 {"file:", 6},
3893 {"news:", 6},
3894 {"wais:", 6},
3895 {"nntp:", 6},
3896 {"http:", 5},
3897 {"www.", 5},
3898 {"ftp:", 5},
3900 LPWSTR bufferW = NULL;
3901 WCHAR bufW[32];
3902 int i;
3904 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3905 assert(sel_min <= sel_max);
3906 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
3908 if (sel_max - sel_min < prefixes[i].length) continue;
3909 if (bufferW == NULL) {
3910 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
3912 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
3913 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
3914 if (!lstrcmpW(bufW, bufferW))
3916 heap_free(bufferW);
3917 return TRUE;
3920 heap_free(bufferW);
3921 return FALSE;
3925 * This proc walks through the indicated selection and evaluates whether each
3926 * section identified by ME_FindNextURLCandidate and in-between sections have
3927 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
3928 * not what it is supposed to be, this proc sets or unsets it as appropriate.
3930 * Returns TRUE if at least one section was modified.
3932 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
3934 BOOL modified = FALSE;
3935 int cMin, cMax;
3937 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3940 int beforeURL[2];
3941 int inURL[2];
3942 CHARFORMAT2W link;
3944 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
3946 /* Section before candidate is not an URL */
3947 beforeURL[0] = sel_min;
3948 beforeURL[1] = cMin;
3950 if (ME_IsCandidateAnURL(editor, cMin, cMax))
3952 inURL[0] = cMin; inURL[1] = cMax;
3954 else
3956 beforeURL[1] = cMax;
3957 inURL[0] = inURL[1] = -1;
3959 sel_min = cMax;
3961 else
3963 /* No more candidates until end of selection */
3964 beforeURL[0] = sel_min;
3965 beforeURL[1] = sel_max;
3966 inURL[0] = inURL[1] = -1;
3967 sel_min = sel_max;
3970 if (beforeURL[0] < beforeURL[1])
3972 /* CFE_LINK effect should be consistently unset */
3973 link.cbSize = sizeof(link);
3974 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
3975 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
3977 /* CFE_LINK must be unset from this range */
3978 memset(&link, 0, sizeof(CHARFORMAT2W));
3979 link.cbSize = sizeof(link);
3980 link.dwMask = CFM_LINK;
3981 link.dwEffects = 0;
3982 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
3983 modified = TRUE;
3986 if (inURL[0] < inURL[1])
3988 /* CFE_LINK effect should be consistently set */
3989 link.cbSize = sizeof(link);
3990 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
3991 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
3993 /* CFE_LINK must be set on this range */
3994 memset(&link, 0, sizeof(CHARFORMAT2W));
3995 link.cbSize = sizeof(link);
3996 link.dwMask = CFM_LINK;
3997 link.dwEffects = CFE_LINK;
3998 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
3999 modified = TRUE;
4002 } while (sel_min < sel_max);
4003 return modified;
4006 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4008 ME_DisplayItem * startPara, * endPara;
4009 ME_DisplayItem * item;
4010 int dummy;
4011 int from, to;
4013 ME_GetSelection(editor, &from, &to);
4014 if (from > to) from ^= to, to ^=from, from ^= to;
4015 startPara = NULL; endPara = NULL;
4017 /* Find paragraph previous to the one that contains start cursor */
4018 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4019 if (item) {
4020 startPara = ME_FindItemBack(item, diParagraph);
4021 item = ME_FindItemBack(startPara, diParagraph);
4022 if (item) startPara = item;
4025 /* Find paragraph that contains end cursor */
4026 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4027 if (item) {
4028 endPara = ME_FindItemFwd(item, diParagraph);
4031 if (startPara && endPara) {
4032 ME_UpdateLinkAttribute(editor,
4033 startPara->member.para.nCharOfs,
4034 endPara->member.para.nCharOfs);
4035 } else if (startPara) {
4036 ME_UpdateLinkAttribute(editor,
4037 startPara->member.para.nCharOfs,
4038 -1);