push 63c1876572cbb61a874995ad42ef27c14590d232
[wine/hacks.git] / dlls / riched20 / editor.c
blobb5d1df5f279aea1cdf1e6b26b49e1b9001604807
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 | PFM_TABLE;
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 fmt.wEffects &= ~PFE_TABLE;
466 break;
467 case rtfInTable:
469 fmt.dwMask |= PFM_TABLE;
470 fmt.wEffects |= PFE_TABLE;
471 break;
473 case rtfFirstIndent:
474 ME_GetSelectionParaFormat(info->editor, &fmt);
475 fmt.dwMask |= PFM_STARTINDENT | PFM_OFFSET;
476 fmt.dxStartIndent += info->rtfParam;
477 fmt.dxOffset = -info->rtfParam;
478 break;
479 case rtfLeftIndent:
480 /* we assume rtfLeftIndent is always specified before rtfFirstIndent */
481 ME_GetSelectionParaFormat(info->editor, &fmt);
482 fmt.dwMask |= PFM_STARTINDENT;
483 fmt.dxStartIndent = info->rtfParam;
484 fmt.dxOffset = 0;
485 break;
486 case rtfRightIndent:
487 fmt.dwMask = PFM_RIGHTINDENT;
488 fmt.dxRightIndent = info->rtfParam;
489 break;
490 case rtfQuadLeft:
491 case rtfQuadJust:
492 fmt.dwMask = PFM_ALIGNMENT;
493 fmt.wAlignment = PFA_LEFT;
494 break;
495 case rtfQuadRight:
496 fmt.dwMask = PFM_ALIGNMENT;
497 fmt.wAlignment = PFA_RIGHT;
498 break;
499 case rtfQuadCenter:
500 fmt.dwMask = PFM_ALIGNMENT;
501 fmt.wAlignment = PFA_CENTER;
502 break;
503 case rtfTabPos:
504 ME_GetSelectionParaFormat(info->editor, &fmt);
505 if (!(fmt.dwMask & PFM_TABSTOPS))
507 fmt.dwMask |= PFM_TABSTOPS;
508 fmt.cTabCount = 0;
510 if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
511 fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
512 break;
513 case rtfKeep:
514 fmt.dwMask = PFM_KEEP;
515 fmt.wEffects = PFE_KEEP;
516 break;
517 case rtfNoWidowControl:
518 fmt.dwMask = PFM_NOWIDOWCONTROL;
519 fmt.wEffects = PFE_NOWIDOWCONTROL;
520 break;
521 case rtfKeepNext:
522 fmt.dwMask = PFM_KEEPNEXT;
523 fmt.wEffects = PFE_KEEPNEXT;
524 break;
525 case rtfSpaceAfter:
526 fmt.dwMask = PFM_SPACEAFTER;
527 fmt.dySpaceAfter = info->rtfParam;
528 break;
529 case rtfSpaceBefore:
530 fmt.dwMask = PFM_SPACEBEFORE;
531 fmt.dySpaceBefore = info->rtfParam;
532 break;
533 case rtfSpaceBetween:
534 fmt.dwMask = PFM_LINESPACING;
535 if ((int)info->rtfParam > 0)
537 fmt.dyLineSpacing = info->rtfParam;
538 fmt.bLineSpacingRule = 3;
540 else
542 fmt.dyLineSpacing = info->rtfParam;
543 fmt.bLineSpacingRule = 4;
545 case rtfSpaceMultiply:
546 fmt.dwMask = PFM_LINESPACING;
547 fmt.dyLineSpacing = info->rtfParam * 20;
548 fmt.bLineSpacingRule = 5;
549 break;
550 case rtfParBullet:
551 fmt.dwMask = PFM_NUMBERING;
552 fmt.wNumbering = PFN_BULLET;
553 break;
554 case rtfParSimple:
555 fmt.dwMask = PFM_NUMBERING;
556 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
557 break;
558 case rtfParNumDecimal:
559 fmt.dwMask = PFM_NUMBERING;
560 fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
561 break;
562 case rtfParNumIndent:
563 fmt.dwMask = PFM_NUMBERINGTAB;
564 fmt.wNumberingTab = info->rtfParam;
565 break;
566 case rtfParNumStartAt:
567 fmt.dwMask = PFM_NUMBERINGSTART;
568 fmt.wNumberingStart = info->rtfParam;
569 break;
570 case rtfBorderLeft:
571 ME_GetSelectionParaFormat(info->editor, &fmt);
572 if (!(fmt.dwMask & PFM_BORDER))
574 fmt.dwMask |= PFM_BORDER;
575 fmt.wBorderSpace = 0;
576 fmt.wBorderWidth = 1;
577 fmt.wBorders = 0;
579 fmt.wBorders |= 1;
580 break;
581 case rtfBorderRight:
582 ME_GetSelectionParaFormat(info->editor, &fmt);
583 if (!(fmt.dwMask & PFM_BORDER))
585 fmt.dwMask |= PFM_BORDER;
586 fmt.wBorderSpace = 0;
587 fmt.wBorderWidth = 1;
588 fmt.wBorders = 0;
590 fmt.wBorders |= 2;
591 break;
592 case rtfBorderTop:
593 ME_GetSelectionParaFormat(info->editor, &fmt);
594 if (!(fmt.dwMask & PFM_BORDER))
596 fmt.dwMask |= PFM_BORDER;
597 fmt.wBorderSpace = 0;
598 fmt.wBorderWidth = 1;
599 fmt.wBorders = 0;
601 fmt.wBorders |= 4;
602 break;
603 case rtfBorderBottom:
604 ME_GetSelectionParaFormat(info->editor, &fmt);
605 if (!(fmt.dwMask & PFM_BORDER))
607 fmt.dwMask |= PFM_BORDER;
608 fmt.wBorderSpace = 0;
609 fmt.wBorderWidth = 1;
610 fmt.wBorders = 0;
612 fmt.wBorders |= 8;
613 break;
614 case rtfBorderSingle:
615 ME_GetSelectionParaFormat(info->editor, &fmt);
616 /* we assume that borders have been created before (RTF spec) */
617 fmt.wBorders &= ~0x700;
618 fmt.wBorders |= 1 << 8;
619 break;
620 case rtfBorderThick:
621 ME_GetSelectionParaFormat(info->editor, &fmt);
622 /* we assume that borders have been created before (RTF spec) */
623 fmt.wBorders &= ~0x700;
624 fmt.wBorders |= 2 << 8;
625 break;
626 case rtfBorderShadow:
627 ME_GetSelectionParaFormat(info->editor, &fmt);
628 /* we assume that borders have been created before (RTF spec) */
629 fmt.wBorders &= ~0x700;
630 fmt.wBorders |= 10 << 8;
631 break;
632 case rtfBorderDouble:
633 ME_GetSelectionParaFormat(info->editor, &fmt);
634 /* we assume that borders have been created before (RTF spec) */
635 fmt.wBorders &= ~0x700;
636 fmt.wBorders |= 7 << 8;
637 break;
638 case rtfBorderDot:
639 ME_GetSelectionParaFormat(info->editor, &fmt);
640 /* we assume that borders have been created before (RTF spec) */
641 fmt.wBorders &= ~0x700;
642 fmt.wBorders |= 11 << 8;
643 break;
644 case rtfBorderWidth:
645 ME_GetSelectionParaFormat(info->editor, &fmt);
646 /* we assume that borders have been created before (RTF spec) */
647 fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
648 break;
649 case rtfBorderSpace:
650 ME_GetSelectionParaFormat(info->editor, &fmt);
651 /* we assume that borders have been created before (RTF spec) */
652 fmt.wBorderSpace = info->rtfParam;
653 break;
655 if (fmt.dwMask) {
656 RTFFlushOutputBuffer(info);
657 /* FIXME too slow ? how come ?*/
658 ME_SetSelectionParaFormat(info->editor, &fmt);
662 static void ME_RTFTblAttrHook(RTF_Info *info)
664 switch (info->rtfMinor)
666 case rtfRowDef:
667 if (!info->tableDef)
668 info->tableDef = ALLOC_OBJ(RTFTable);
669 ZeroMemory(info->tableDef, sizeof(RTFTable));
670 break;
671 case rtfCellPos:
672 if (!info->tableDef)
674 info->tableDef = ALLOC_OBJ(RTFTable);
675 ZeroMemory(info->tableDef, sizeof(RTFTable));
677 if (info->tableDef->numCellsDefined >= MAX_TABLE_CELLS)
678 break;
679 info->tableDef->cells[info->tableDef->numCellsDefined].rightBoundary = info->rtfParam;
681 /* Tab stops store the cell positions. */
682 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
683 PARAFORMAT2 *pFmt = para->member.para.pFmt;
684 int cellNum = info->tableDef->numCellsDefined;
685 pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
686 pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
688 info->tableDef->numCellsDefined++;
689 break;
693 static void ME_RTFSpecialCharHook(RTF_Info *info)
695 RTFTable *tableDef = info->tableDef;
696 switch (info->rtfMinor)
698 case rtfCell:
699 if (!tableDef)
700 break;
701 RTFFlushOutputBuffer(info);
703 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
704 PARAFORMAT2 *pFmt = para->member.para.pFmt;
705 if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
706 tableDef->numCellsInserted < tableDef->numCellsDefined)
708 WCHAR tab = '\t';
709 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
710 tableDef->numCellsInserted++;
713 break;
714 case rtfRow:
716 if (!tableDef)
717 break;
718 RTFFlushOutputBuffer(info);
721 WCHAR endl = '\r';
722 ME_DisplayItem *para = ME_GetParagraph(info->editor->pCursors[0].pRun);
723 PARAFORMAT2 *pFmt = para->member.para.pFmt;
724 while (tableDef->numCellsInserted < tableDef->numCellsDefined)
726 WCHAR tab = '\t';
727 ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
728 tableDef->numCellsInserted++;
730 pFmt->cTabCount = tableDef->numCellsDefined;
731 if (!tableDef->numCellsDefined)
732 pFmt->wEffects &= ~PFE_TABLE;
733 ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
734 tableDef->numCellsInserted = 0;
736 break;
738 case rtfPar:
739 if (tableDef)
740 tableDef->numCellsInserted = 0;
741 break;
745 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
746 const SIZEL* sz)
748 LPOLEOBJECT lpObject = NULL;
749 LPSTORAGE lpStorage = NULL;
750 LPOLECLIENTSITE lpClientSite = NULL;
751 LPDATAOBJECT lpDataObject = NULL;
752 LPOLECACHE lpOleCache = NULL;
753 STGMEDIUM stgm;
754 FORMATETC fm;
755 CLSID clsid;
756 BOOL ret = FALSE;
757 DWORD conn;
759 if (hemf)
761 stgm.tymed = TYMED_ENHMF;
762 stgm.u.hEnhMetaFile = hemf;
763 fm.cfFormat = CF_ENHMETAFILE;
765 else if (hbmp)
767 stgm.tymed = TYMED_GDI;
768 stgm.u.hBitmap = hbmp;
769 fm.cfFormat = CF_BITMAP;
771 stgm.pUnkForRelease = NULL;
773 fm.ptd = NULL;
774 fm.dwAspect = DVASPECT_CONTENT;
775 fm.lindex = -1;
776 fm.tymed = stgm.tymed;
778 if (!info->lpRichEditOle)
780 CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
783 if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
784 #if 0
785 /* FIXME: enable it when rich-edit properly implements this method */
786 IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
787 IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
788 #endif
789 IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
790 IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
791 IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
792 IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
793 IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
795 REOBJECT reobject;
797 reobject.cbStruct = sizeof(reobject);
798 reobject.cp = REO_CP_SELECTION;
799 reobject.clsid = clsid;
800 reobject.poleobj = lpObject;
801 reobject.pstg = lpStorage;
802 reobject.polesite = lpClientSite;
803 /* convert from twips to .01 mm */
804 reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
805 reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
806 reobject.dvaspect = DVASPECT_CONTENT;
807 reobject.dwFlags = 0; /* FIXME */
808 reobject.dwUser = 0;
810 /* FIXME: could be simpler */
811 ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
814 if (lpObject) IOleObject_Release(lpObject);
815 if (lpClientSite) IOleClientSite_Release(lpClientSite);
816 if (lpStorage) IStorage_Release(lpStorage);
817 if (lpDataObject) IDataObject_Release(lpDataObject);
818 if (lpOleCache) IOleCache_Release(lpOleCache);
820 return ret;
823 static void ME_RTFReadPictGroup(RTF_Info *info)
825 SIZEL sz;
826 BYTE* buffer = NULL;
827 unsigned bufsz, bufidx;
828 BOOL flip;
829 BYTE val;
830 METAFILEPICT mfp;
831 HENHMETAFILE hemf;
832 HBITMAP hbmp;
833 enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
835 RTFGetToken (info);
836 if (info->rtfClass == rtfEOF)
837 return;
838 mfp.mm = MM_TEXT;
839 /* fetch picture type */
840 if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
842 mfp.mm = info->rtfParam;
843 gfx = gfx_metafile;
845 else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
847 if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
848 gfx = gfx_dib;
850 else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
852 gfx = gfx_enhmetafile;
854 else
856 FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
857 goto skip_group;
859 sz.cx = sz.cy = 0;
860 /* fetch picture attributes */
861 for (;;)
863 RTFGetToken (info);
864 if (info->rtfClass == rtfEOF)
865 return;
866 if (info->rtfClass == rtfText)
867 break;
868 if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
870 ERR("Expected picture attribute (%d %d)\n",
871 info->rtfClass, info->rtfMajor);
872 goto skip_group;
874 else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
876 if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
878 else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
880 if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
882 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
883 sz.cx = info->rtfParam;
884 else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
885 sz.cy = info->rtfParam;
886 else
887 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
889 /* fetch picture data */
890 bufsz = 1024;
891 bufidx = 0;
892 buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
893 val = info->rtfMajor;
894 for (flip = TRUE;; flip = !flip)
896 RTFGetToken (info);
897 if (info->rtfClass == rtfEOF)
899 HeapFree(GetProcessHeap(), 0, buffer);
900 return; /* Warn ?? */
902 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
903 break;
904 if (info->rtfClass != rtfText) goto skip_group;
905 if (flip)
907 if (bufidx >= bufsz &&
908 !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
909 goto skip_group;
910 buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
912 else
913 val = info->rtfMajor;
915 if (flip) FIXME("wrong hex string\n");
917 switch (gfx)
919 case gfx_enhmetafile:
920 if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
921 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
922 break;
923 case gfx_metafile:
924 if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
925 ME_RTFInsertOleObject(info, hemf, NULL, &sz);
926 break;
927 case gfx_dib:
929 BITMAPINFO* bi = (BITMAPINFO*)buffer;
930 HDC hdc = GetDC(0);
931 unsigned nc = bi->bmiHeader.biClrUsed;
933 /* not quite right, especially for bitfields type of compression */
934 if (!nc && bi->bmiHeader.biBitCount <= 8)
935 nc = 1 << bi->bmiHeader.biBitCount;
936 if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
937 CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
938 bi, DIB_RGB_COLORS)))
939 ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
940 ReleaseDC(0, hdc);
942 break;
943 default:
944 break;
946 HeapFree(GetProcessHeap(), 0, buffer);
947 RTFRouteToken (info); /* feed "}" back to router */
948 return;
949 skip_group:
950 HeapFree(GetProcessHeap(), 0, buffer);
951 RTFSkipGroup(info);
952 RTFRouteToken(info); /* feed "}" back to router */
955 /* for now, lookup the \result part and use it, whatever the object */
956 static void ME_RTFReadObjectGroup(RTF_Info *info)
958 for (;;)
960 RTFGetToken (info);
961 if (info->rtfClass == rtfEOF)
962 return;
963 if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
964 break;
965 if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
967 RTFGetToken (info);
968 if (info->rtfClass == rtfEOF)
969 return;
970 if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
972 int level = 1;
974 while (RTFGetToken (info) != rtfEOF)
976 if (info->rtfClass == rtfGroup)
978 if (info->rtfMajor == rtfBeginGroup) level++;
979 else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
981 RTFRouteToken(info);
984 else RTFSkipGroup(info);
985 continue;
987 if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
989 FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
990 return;
993 RTFRouteToken(info); /* feed "}" back to router */
996 static void ME_RTFReadHook(RTF_Info *info) {
997 switch(info->rtfClass)
999 case rtfGroup:
1000 switch(info->rtfMajor)
1002 case rtfBeginGroup:
1003 if (info->stackTop < maxStack) {
1004 info->stack[info->stackTop].fmt = info->style->fmt;
1005 info->stack[info->stackTop].codePage = info->codePage;
1006 info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1008 info->stackTop++;
1009 info->styleChanged = FALSE;
1010 break;
1011 case rtfEndGroup:
1013 ME_Style *s;
1014 RTFFlushOutputBuffer(info);
1015 info->stackTop--;
1016 if (info->stackTop<=0) {
1017 info->rtfClass = rtfEOF;
1018 return;
1020 assert(info->stackTop >= 0);
1021 if (info->styleChanged)
1023 /* FIXME too slow ? how come ? */
1024 s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
1025 ME_ReleaseStyle(info->style);
1026 info->style = s;
1027 info->codePage = info->stack[info->stackTop].codePage;
1028 info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1030 break;
1033 break;
1034 case rtfControl:
1035 switch(info->rtfMajor)
1037 case rtfCharAttr:
1038 ME_RTFCharAttrHook(info);
1039 break;
1040 case rtfParAttr:
1041 ME_RTFParAttrHook(info);
1042 break;
1043 case rtfTblAttr:
1044 ME_RTFTblAttrHook(info);
1045 break;
1046 case rtfSpecialChar:
1047 ME_RTFSpecialCharHook(info);
1048 break;
1050 break;
1054 void
1055 ME_StreamInFill(ME_InStream *stream)
1057 stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1058 (BYTE *)stream->buffer,
1059 sizeof(stream->buffer),
1060 (LONG *)&stream->dwSize);
1061 stream->dwUsed = 0;
1064 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1066 RTF_Info parser;
1067 ME_Style *style;
1068 int from, to, to2, nUndoMode;
1069 int nEventMask = editor->nEventMask;
1070 ME_InStream inStream;
1071 BOOL invalidRTF = FALSE;
1073 TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, format);
1074 editor->nEventMask = 0;
1076 ME_GetSelection(editor, &from, &to);
1077 if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
1078 style = ME_GetSelectionInsertStyle(editor);
1080 ME_InternalDeleteText(editor, from, to-from);
1082 else {
1083 ME_DisplayItem *para_item;
1084 style = editor->pBuffer->pDefaultStyle;
1085 ME_AddRefStyle(style);
1086 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1087 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1088 from = to = 0;
1089 ME_ClearTempStyle(editor);
1091 para_item = ME_GetParagraph(editor->pCursors[0].pRun);
1092 ME_SetDefaultParaFormat(para_item->member.para.pFmt);
1096 /* Back up undo mode to a local variable */
1097 nUndoMode = editor->nUndoMode;
1099 /* Only create an undo if SFF_SELECTION is set */
1100 if (!(format & SFF_SELECTION))
1101 editor->nUndoMode = umIgnore;
1103 inStream.editstream = stream;
1104 inStream.editstream->dwError = 0;
1105 inStream.dwSize = 0;
1106 inStream.dwUsed = 0;
1108 if (format & SF_RTF)
1110 /* Check if it's really RTF, and if it is not, use plain text */
1111 ME_StreamInFill(&inStream);
1112 if (!inStream.editstream->dwError)
1114 if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1115 || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1117 invalidRTF = TRUE;
1118 inStream.editstream->dwError = -16;
1123 if (!invalidRTF && !inStream.editstream->dwError)
1125 if (format & SF_RTF) {
1126 /* setup the RTF parser */
1127 memset(&parser, 0, sizeof parser);
1128 RTFSetEditStream(&parser, &inStream);
1129 parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1130 parser.hwndEdit = editor->hWnd;
1131 parser.editor = editor;
1132 parser.style = style;
1133 WriterInit(&parser);
1134 RTFInit(&parser);
1135 RTFSetReadHook(&parser, ME_RTFReadHook);
1136 RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1137 RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1138 BeginFile(&parser);
1140 /* do the parsing */
1141 RTFRead(&parser);
1142 RTFFlushOutputBuffer(&parser);
1143 RTFDestroy(&parser);
1144 if (parser.lpRichEditOle)
1145 IRichEditOle_Release(parser.lpRichEditOle);
1147 if (!inStream.editstream->dwError && parser.stackTop > 0)
1148 inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1150 /* Remove last line break, as mandated by tests. This is not affected by
1151 CR/LF counters, since RTF streaming presents only \para tokens, which
1152 are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1154 if (stripLastCR) {
1155 int newfrom, newto;
1156 ME_GetSelection(editor, &newfrom, &newto);
1157 if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1158 WCHAR lastchar[3] = {'\0', '\0'};
1159 int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1161 ME_GetTextW(editor, lastchar, newto - linebreakSize, linebreakSize, 0);
1162 if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1163 ME_InternalDeleteText(editor, newto - linebreakSize, linebreakSize);
1168 style = parser.style;
1170 else if (format & SF_TEXT)
1171 ME_StreamInText(editor, format, &inStream, style);
1172 else
1173 ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1174 ME_GetSelection(editor, &to, &to2);
1175 /* put the cursor at the top */
1176 if (!(format & SFF_SELECTION))
1177 SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
1180 /* Restore saved undo mode */
1181 editor->nUndoMode = nUndoMode;
1183 /* even if we didn't add an undo, we need to commit anything on the stack */
1184 ME_CommitUndo(editor);
1186 /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1187 if (!(format & SFF_SELECTION))
1188 ME_EmptyUndoStack(editor);
1190 ME_ReleaseStyle(style);
1191 editor->nEventMask = nEventMask;
1192 ME_UpdateRepaint(editor);
1193 if (!(format & SFF_SELECTION)) {
1194 ME_ClearTempStyle(editor);
1196 HideCaret(editor->hWnd);
1197 ME_MoveCaret(editor);
1198 ShowCaret(editor->hWnd);
1199 ME_SendSelChange(editor);
1200 ME_SendRequestResize(editor, FALSE);
1202 return 0;
1206 typedef struct tagME_RTFStringStreamStruct
1208 char *string;
1209 int pos;
1210 int length;
1211 } ME_RTFStringStreamStruct;
1213 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1215 ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1216 int count;
1218 count = min(cb, pStruct->length - pStruct->pos);
1219 memmove(lpBuff, pStruct->string + pStruct->pos, count);
1220 pStruct->pos += count;
1221 *pcb = count;
1222 return 0;
1225 static void
1226 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1228 EDITSTREAM es;
1229 ME_RTFStringStreamStruct data;
1231 data.string = string;
1232 data.length = strlen(string);
1233 data.pos = 0;
1234 es.dwCookie = (DWORD)&data;
1235 es.pfnCallback = ME_ReadFromRTFString;
1236 ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1240 ME_DisplayItem *
1241 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
1243 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1244 int runLength;
1246 while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
1247 item = ME_FindItemFwd(item, diParagraph);
1249 if (!item)
1250 return item;
1252 nOffset -= item->member.para.nCharOfs;
1253 if (nItemType == diParagraph) {
1254 if (nItemOffset)
1255 *nItemOffset = nOffset;
1256 return item;
1259 do {
1260 item = ME_FindItemFwd(item, diRun);
1261 runLength = ME_StrLen(item->member.run.strText);
1262 if (item->member.run.nFlags & MERF_ENDPARA)
1263 runLength = item->member.run.nCR + item->member.run.nLF;
1264 } while (item && (item->member.run.nCharOfs + runLength <= nOffset));
1265 if (item) {
1266 nOffset -= item->member.run.nCharOfs;
1268 /* Special case: nOffset may not point exactly at the division between the
1269 \r and the \n in 1.0 emulation. If such a case happens, it is sent
1270 into the next run, if one exists
1272 if ( item->member.run.nFlags & MERF_ENDPARA
1273 && nOffset == item->member.run.nCR
1274 && item->member.run.nLF > 0) {
1275 ME_DisplayItem *nextItem;
1276 nextItem = ME_FindItemFwd(item, diRun);
1277 if (nextItem) {
1278 nOffset = 0;
1279 item = nextItem;
1282 if (nItemOffset)
1283 *nItemOffset = nOffset;
1285 return item;
1289 static int
1290 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1292 const int nLen = lstrlenW(text);
1293 const int nTextLen = ME_GetTextLength(editor);
1294 int nStart, nEnd;
1295 int nMin, nMax;
1296 ME_DisplayItem *item;
1297 ME_DisplayItem *para;
1298 WCHAR wLastChar = ' ';
1300 TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1301 flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1303 if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1304 FIXME("Flags 0x%08x not implemented\n",
1305 flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1307 nMin = chrg->cpMin;
1308 if (chrg->cpMax == -1)
1309 nMax = nTextLen;
1310 else
1311 nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1313 /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1314 if (editor->bEmulateVersion10 && nMax == nTextLen)
1316 flags |= FR_DOWN;
1319 /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1320 if (editor->bEmulateVersion10 && nMax < nMin)
1322 if (chrgText)
1324 chrgText->cpMin = -1;
1325 chrgText->cpMax = -1;
1327 return -1;
1330 /* when searching up, if cpMin < cpMax, then instead of searching
1331 * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1332 * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1333 * case, it is always bigger than cpMin.
1335 if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1337 int nSwap = nMax;
1339 nMax = nMin > nTextLen ? nTextLen : nMin;
1340 if (nMin < nSwap || chrg->cpMax == -1)
1341 nMin = 0;
1342 else
1343 nMin = nSwap;
1346 if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1348 if (chrgText)
1349 chrgText->cpMin = chrgText->cpMax = -1;
1350 return -1;
1353 if (flags & FR_DOWN) /* Forward search */
1355 /* If possible, find the character before where the search starts */
1356 if ((flags & FR_WHOLEWORD) && nMin)
1358 nStart = nMin - 1;
1359 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1360 if (!item)
1362 if (chrgText)
1363 chrgText->cpMin = chrgText->cpMax = -1;
1364 return -1;
1366 wLastChar = item->member.run.strText->szData[nStart];
1369 nStart = nMin;
1370 item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1371 if (!item)
1373 if (chrgText)
1374 chrgText->cpMin = chrgText->cpMax = -1;
1375 return -1;
1378 para = ME_GetParagraph(item);
1379 while (item
1380 && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
1382 ME_DisplayItem *pCurItem = item;
1383 int nCurStart = nStart;
1384 int nMatched = 0;
1386 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1388 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1389 break;
1391 nMatched++;
1392 if (nMatched == nLen)
1394 ME_DisplayItem *pNextItem = pCurItem;
1395 int nNextStart = nCurStart;
1396 WCHAR wNextChar;
1398 /* Check to see if next character is a whitespace */
1399 if (flags & FR_WHOLEWORD)
1401 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1403 pNextItem = ME_FindItemFwd(pCurItem, diRun);
1404 nNextStart = -nMatched;
1407 if (pNextItem)
1408 wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1409 else
1410 wNextChar = ' ';
1412 if (isalnumW(wNextChar))
1413 break;
1416 nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
1417 if (chrgText)
1419 chrgText->cpMin = nStart;
1420 chrgText->cpMax = nStart + nLen;
1422 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1423 return nStart;
1425 if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
1427 pCurItem = ME_FindItemFwd(pCurItem, diRun);
1428 para = ME_GetParagraph(pCurItem);
1429 nCurStart = -nMatched;
1432 if (pCurItem)
1433 wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1434 else
1435 wLastChar = ' ';
1437 nStart++;
1438 if (nStart == ME_StrLen(item->member.run.strText))
1440 item = ME_FindItemFwd(item, diRun);
1441 para = ME_GetParagraph(item);
1442 nStart = 0;
1446 else /* Backward search */
1448 /* If possible, find the character after where the search ends */
1449 if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1451 nEnd = nMax + 1;
1452 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1453 if (!item)
1455 if (chrgText)
1456 chrgText->cpMin = chrgText->cpMax = -1;
1457 return -1;
1459 wLastChar = item->member.run.strText->szData[nEnd];
1462 nEnd = nMax;
1463 item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
1464 if (!item)
1466 if (chrgText)
1467 chrgText->cpMin = chrgText->cpMax = -1;
1468 return -1;
1471 para = ME_GetParagraph(item);
1473 while (item
1474 && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
1476 ME_DisplayItem *pCurItem = item;
1477 int nCurEnd = nEnd;
1478 int nMatched = 0;
1480 if (nCurEnd - nMatched == 0)
1482 pCurItem = ME_FindItemBack(pCurItem, diRun);
1483 para = ME_GetParagraph(pCurItem);
1484 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1487 while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1489 if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1490 break;
1492 nMatched++;
1493 if (nMatched == nLen)
1495 ME_DisplayItem *pPrevItem = pCurItem;
1496 int nPrevEnd = nCurEnd;
1497 WCHAR wPrevChar;
1499 /* Check to see if previous character is a whitespace */
1500 if (flags & FR_WHOLEWORD)
1502 if (nPrevEnd - nMatched == 0)
1504 pPrevItem = ME_FindItemBack(pCurItem, diRun);
1505 if (pPrevItem)
1506 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
1509 if (pPrevItem)
1510 wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1511 else
1512 wPrevChar = ' ';
1514 if (isalnumW(wPrevChar))
1515 break;
1518 nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1519 if (chrgText)
1521 chrgText->cpMin = nStart;
1522 chrgText->cpMax = nStart + nLen;
1524 TRACE("found at %d-%d\n", nStart, nStart + nLen);
1525 return nStart;
1527 if (nCurEnd - nMatched == 0)
1529 pCurItem = ME_FindItemBack(pCurItem, diRun);
1530 /* Don't care about pCurItem becoming NULL here; it's already taken
1531 * care of in the exterior loop condition */
1532 para = ME_GetParagraph(pCurItem);
1533 nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1536 if (pCurItem)
1537 wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1538 else
1539 wLastChar = ' ';
1541 nEnd--;
1542 if (nEnd < 0)
1544 item = ME_FindItemBack(item, diRun);
1545 para = ME_GetParagraph(item);
1546 nEnd = ME_StrLen(item->member.run.strText);
1550 TRACE("not found\n");
1551 if (chrgText)
1552 chrgText->cpMin = chrgText->cpMax = -1;
1553 return -1;
1556 /* helper to send a msg filter notification */
1557 static BOOL
1558 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
1560 MSGFILTER msgf;
1562 msgf.nmhdr.hwndFrom = editor->hWnd;
1563 msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
1564 msgf.nmhdr.code = EN_MSGFILTER;
1565 msgf.msg = msg;
1567 msgf.wParam = *wParam;
1568 msgf.lParam = *lParam;
1569 if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
1570 return FALSE;
1571 *wParam = msgf.wParam;
1572 *lParam = msgf.lParam;
1573 msgf.wParam = *wParam;
1575 return TRUE;
1578 static BOOL
1579 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1581 BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1582 BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1584 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
1585 editor->nSelectionType = stPosition;
1587 switch (nKey)
1589 case VK_LEFT:
1590 case VK_RIGHT:
1591 case VK_HOME:
1592 case VK_END:
1593 editor->nUDArrowX = -1;
1594 /* fall through */
1595 case VK_UP:
1596 case VK_DOWN:
1597 case VK_PRIOR:
1598 case VK_NEXT:
1599 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
1600 ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1601 return TRUE;
1602 case VK_BACK:
1603 case VK_DELETE:
1604 editor->nUDArrowX = -1;
1605 /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1606 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1607 return FALSE;
1608 if (ME_IsSelection(editor))
1610 ME_DeleteSelection(editor);
1611 ME_CommitUndo(editor);
1613 else if (nKey == VK_DELETE)
1615 /* Delete stops group typing.
1616 * (See MSDN remarks on EM_STOPGROUPTYPING message) */
1617 ME_DeleteTextAtCursor(editor, 1, 1);
1618 ME_CommitUndo(editor);
1620 else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1622 /* Backspace can be grouped for a single undo */
1623 ME_ContinueCoalescingTransaction(editor);
1624 ME_DeleteTextAtCursor(editor, 1, 1);
1625 ME_CommitCoalescingUndo(editor);
1627 else
1628 return TRUE;
1629 ME_UpdateSelectionLinkAttribute(editor);
1630 ME_UpdateRepaint(editor);
1631 ME_SendRequestResize(editor, FALSE);
1632 return TRUE;
1634 default:
1635 if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
1636 editor->nUDArrowX = -1;
1637 if (ctrl_is_down)
1639 if (nKey == 'W')
1641 CHARFORMAT2W chf;
1642 char buf[2048];
1643 chf.cbSize = sizeof(chf);
1645 ME_GetSelectionCharFormat(editor, &chf);
1646 ME_DumpStyleToBuf(&chf, buf);
1647 MessageBoxA(NULL, buf, "Style dump", MB_OK);
1649 if (nKey == 'Q')
1651 ME_CheckCharOffsets(editor);
1655 return FALSE;
1658 /* Process the message and calculate the new click count.
1660 * returns: The click count if it is mouse down event, else returns 0. */
1661 static int ME_CalculateClickCount(HWND hWnd, UINT msg, WPARAM wParam,
1662 LPARAM lParam)
1664 static int clickNum = 0;
1665 if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
1666 return 0;
1668 if ((msg == WM_LBUTTONDBLCLK) ||
1669 (msg == WM_RBUTTONDBLCLK) ||
1670 (msg == WM_MBUTTONDBLCLK) ||
1671 (msg == WM_XBUTTONDBLCLK))
1673 msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
1676 if ((msg == WM_LBUTTONDOWN) ||
1677 (msg == WM_RBUTTONDOWN) ||
1678 (msg == WM_MBUTTONDOWN) ||
1679 (msg == WM_XBUTTONDOWN))
1681 static MSG prevClickMsg;
1682 MSG clickMsg;
1683 clickMsg.hwnd = hWnd;
1684 clickMsg.message = msg;
1685 clickMsg.wParam = wParam;
1686 clickMsg.lParam = lParam;
1687 clickMsg.time = GetMessageTime();
1688 clickMsg.pt.x = (short)LOWORD(lParam);
1689 clickMsg.pt.y = (short)HIWORD(lParam);
1690 if ((clickNum != 0) &&
1691 (clickMsg.message == prevClickMsg.message) &&
1692 (clickMsg.hwnd == prevClickMsg.hwnd) &&
1693 (clickMsg.wParam == prevClickMsg.wParam) &&
1694 (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
1695 (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
1696 (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
1698 clickNum++;
1699 } else {
1700 clickNum = 1;
1702 prevClickMsg = clickMsg;
1703 } else {
1704 return 0;
1706 return clickNum;
1709 static BOOL ME_SetCursor(ME_TextEditor *editor)
1711 POINT pt;
1712 BOOL isExact;
1713 int offset;
1714 DWORD messagePos = GetMessagePos();
1715 pt.x = (short)LOWORD(messagePos);
1716 pt.y = (short)HIWORD(messagePos);
1717 ScreenToClient(editor->hWnd, &pt);
1718 if ((GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_SELECTIONBAR) &&
1719 (pt.x < editor->selofs ||
1720 (editor->nSelectionType == stLine && GetCapture() == editor->hWnd)))
1722 SetCursor(hLeft);
1723 return TRUE;
1725 offset = ME_CharFromPos(editor, pt.x, pt.y, &isExact);
1726 if (isExact)
1728 if (editor->AutoURLDetect_bEnable)
1730 ME_Cursor cursor;
1731 ME_Run *run;
1732 ME_CursorFromCharOfs(editor, offset, &cursor);
1733 run = &cursor.pRun->member.run;
1734 if (editor->AutoURLDetect_bEnable &&
1735 run->style->fmt.dwMask & CFM_LINK &&
1736 run->style->fmt.dwEffects & CFE_LINK)
1738 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_HAND));
1739 return TRUE;
1742 if (ME_IsSelection(editor))
1744 int selStart, selEnd;
1745 ME_GetSelection(editor, &selStart, &selEnd);
1746 if (selStart <= offset && selEnd >= offset) {
1747 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_ARROW));
1748 return TRUE;
1752 SetCursor(LoadCursorW(NULL, (WCHAR*)IDC_IBEAM));
1753 return TRUE;
1756 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1758 CHARRANGE selrange;
1759 HMENU menu;
1760 int seltype = 0;
1761 if(!editor->lpOleCallback)
1762 return FALSE;
1763 ME_GetSelection(editor, &selrange.cpMin, &selrange.cpMax);
1764 if(selrange.cpMin == selrange.cpMax)
1765 seltype |= SEL_EMPTY;
1766 else
1768 /* FIXME: Handle objects */
1769 seltype |= SEL_TEXT;
1770 if(selrange.cpMax-selrange.cpMin > 1)
1771 seltype |= SEL_MULTICHAR;
1773 if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1775 TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1776 DestroyMenu(menu);
1778 return TRUE;
1781 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1782 ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1783 int i;
1784 ed->hWnd = hWnd;
1785 ed->bEmulateVersion10 = FALSE;
1786 ed->pBuffer = ME_MakeText();
1787 ed->nZoomNumerator = ed->nZoomDenominator = 0;
1788 ME_MakeFirstParagraph(ed);
1789 /* The four cursors are for:
1790 * 0 - The position where the caret is shown
1791 * 1 - The anchored end of the selection (for normal selection)
1792 * 2 & 3 - The anchored start and end respectively for word, line,
1793 * or paragraph selection.
1795 ed->nCursors = 4;
1796 ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1797 ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1798 ed->pCursors[0].nOffset = 0;
1799 ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1800 ed->pCursors[1].nOffset = 0;
1801 ed->pCursors[2] = ed->pCursors[0];
1802 ed->pCursors[3] = ed->pCursors[1];
1803 ed->nLastTotalLength = ed->nTotalLength = 0;
1804 ed->nHeight = 0;
1805 ed->nUDArrowX = -1;
1806 ed->nSequence = 0;
1807 ed->rgbBackColor = -1;
1808 ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1809 ed->bCaretAtEnd = FALSE;
1810 ed->nEventMask = 0;
1811 ed->nModifyStep = 0;
1812 ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1813 ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1814 ed->nUndoStackSize = 0;
1815 ed->nUndoLimit = STACK_SIZE_DEFAULT;
1816 ed->nUndoMode = umAddToUndo;
1817 ed->nParagraphs = 1;
1818 ed->nLastSelStart = ed->nLastSelEnd = 0;
1819 ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1820 ed->bRedraw = TRUE;
1821 ed->bWordWrap = (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL) ? FALSE : TRUE;
1822 ed->bHideSelection = FALSE;
1823 ed->nInvalidOfs = -1;
1824 ed->pfnWordBreak = NULL;
1825 ed->lpOleCallback = NULL;
1826 ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1827 ed->AutoURLDetect_bEnable = FALSE;
1828 ed->bHaveFocus = FALSE;
1829 for (i=0; i<HFONT_CACHE_SIZE; i++)
1831 ed->pFontCache[i].nRefs = 0;
1832 ed->pFontCache[i].nAge = 0;
1833 ed->pFontCache[i].hFont = NULL;
1836 ME_CheckCharOffsets(ed);
1837 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_SELECTIONBAR)
1838 ed->selofs = SELECTIONBAR_WIDTH;
1839 else
1840 ed->selofs = 0;
1841 ed->nSelectionType = stPosition;
1843 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1844 ed->cPasswordMask = '*';
1845 else
1846 ed->cPasswordMask = 0;
1848 ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
1850 /* Default vertical scrollbar information */
1851 ed->vert_si.cbSize = sizeof(SCROLLINFO);
1852 ed->vert_si.nMin = 0;
1853 ed->vert_si.nMax = 0;
1854 ed->vert_si.nPage = 0;
1855 ed->vert_si.nPos = 0;
1857 OleInitialize(NULL);
1859 return ed;
1862 typedef struct tagME_GlobalDestStruct
1864 HGLOBAL hData;
1865 int nLength;
1866 } ME_GlobalDestStruct;
1868 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1870 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1871 int i;
1872 WORD *pSrc, *pDest;
1874 cb = cb >> 1;
1875 pDest = (WORD *)lpBuff;
1876 pSrc = (WORD *)GlobalLock(pData->hData);
1877 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1878 pDest[i] = pSrc[pData->nLength+i];
1880 pData->nLength += i;
1881 *pcb = 2*i;
1882 GlobalUnlock(pData->hData);
1883 return 0;
1886 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1888 ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1889 int i;
1890 BYTE *pSrc, *pDest;
1892 pDest = lpBuff;
1893 pSrc = (BYTE *)GlobalLock(pData->hData);
1894 for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1895 pDest[i] = pSrc[pData->nLength+i];
1897 pData->nLength += i;
1898 *pcb = i;
1899 GlobalUnlock(pData->hData);
1900 return 0;
1904 void ME_DestroyEditor(ME_TextEditor *editor)
1906 ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1907 ME_DisplayItem *p = pFirst, *pNext = NULL;
1908 int i;
1910 ME_ClearTempStyle(editor);
1911 ME_EmptyUndoStack(editor);
1912 while(p) {
1913 pNext = p->next;
1914 ME_DestroyDisplayItem(p);
1915 p = pNext;
1917 ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1918 for (i=0; i<HFONT_CACHE_SIZE; i++)
1920 if (editor->pFontCache[i].hFont)
1921 DeleteObject(editor->pFontCache[i].hFont);
1923 if (editor->rgbBackColor != -1)
1924 DeleteObject(editor->hbrBackground);
1925 if(editor->lpOleCallback)
1926 IUnknown_Release(editor->lpOleCallback);
1927 OleUninitialize();
1929 FREE_OBJ(editor->pBuffer);
1930 FREE_OBJ(editor->pCursors);
1932 FREE_OBJ(editor);
1935 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1937 TRACE("\n");
1938 switch (fdwReason)
1940 case DLL_PROCESS_ATTACH:
1941 DisableThreadLibraryCalls(hinstDLL);
1942 me_heap = HeapCreate (0, 0x10000, 0);
1943 if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
1944 hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
1945 LookupInit();
1946 break;
1948 case DLL_PROCESS_DETACH:
1949 UnregisterClassW(RichEdit20W, 0);
1950 UnregisterClassW(RichEdit50W, 0);
1951 UnregisterClassA("RichEdit20A", 0);
1952 UnregisterClassA("RichEdit50A", 0);
1953 if (ME_ListBoxRegistered)
1954 UnregisterClassW(REListBox20W, 0);
1955 if (ME_ComboBoxRegistered)
1956 UnregisterClassW(REComboBox20W, 0);
1957 LookupCleanup();
1958 HeapDestroy (me_heap);
1959 me_heap = NULL;
1960 break;
1962 return TRUE;
1966 #define UNSUPPORTED_MSG(e) \
1967 case e: \
1968 FIXME(#e ": stub\n"); \
1969 return DefWindowProcW(hWnd, msg, wParam, lParam);
1971 static const char * const edit_messages[] = {
1972 "EM_GETSEL",
1973 "EM_SETSEL",
1974 "EM_GETRECT",
1975 "EM_SETRECT",
1976 "EM_SETRECTNP",
1977 "EM_SCROLL",
1978 "EM_LINESCROLL",
1979 "EM_SCROLLCARET",
1980 "EM_GETMODIFY",
1981 "EM_SETMODIFY",
1982 "EM_GETLINECOUNT",
1983 "EM_LINEINDEX",
1984 "EM_SETHANDLE",
1985 "EM_GETHANDLE",
1986 "EM_GETTHUMB",
1987 "EM_UNKNOWN_BF",
1988 "EM_UNKNOWN_C0",
1989 "EM_LINELENGTH",
1990 "EM_REPLACESEL",
1991 "EM_UNKNOWN_C3",
1992 "EM_GETLINE",
1993 "EM_LIMITTEXT",
1994 "EM_CANUNDO",
1995 "EM_UNDO",
1996 "EM_FMTLINES",
1997 "EM_LINEFROMCHAR",
1998 "EM_UNKNOWN_CA",
1999 "EM_SETTABSTOPS",
2000 "EM_SETPASSWORDCHAR",
2001 "EM_EMPTYUNDOBUFFER",
2002 "EM_GETFIRSTVISIBLELINE",
2003 "EM_SETREADONLY",
2004 "EM_SETWORDBREAKPROC",
2005 "EM_GETWORDBREAKPROC",
2006 "EM_GETPASSWORDCHAR",
2007 "EM_SETMARGINS",
2008 "EM_GETMARGINS",
2009 "EM_GETLIMITTEXT",
2010 "EM_POSFROMCHAR",
2011 "EM_CHARFROMPOS"
2014 static const char * const richedit_messages[] = {
2015 "EM_CANPASTE",
2016 "EM_DISPLAYBAND",
2017 "EM_EXGETSEL",
2018 "EM_EXLIMITTEXT",
2019 "EM_EXLINEFROMCHAR",
2020 "EM_EXSETSEL",
2021 "EM_FINDTEXT",
2022 "EM_FORMATRANGE",
2023 "EM_GETCHARFORMAT",
2024 "EM_GETEVENTMASK",
2025 "EM_GETOLEINTERFACE",
2026 "EM_GETPARAFORMAT",
2027 "EM_GETSELTEXT",
2028 "EM_HIDESELECTION",
2029 "EM_PASTESPECIAL",
2030 "EM_REQUESTRESIZE",
2031 "EM_SELECTIONTYPE",
2032 "EM_SETBKGNDCOLOR",
2033 "EM_SETCHARFORMAT",
2034 "EM_SETEVENTMASK",
2035 "EM_SETOLECALLBACK",
2036 "EM_SETPARAFORMAT",
2037 "EM_SETTARGETDEVICE",
2038 "EM_STREAMIN",
2039 "EM_STREAMOUT",
2040 "EM_GETTEXTRANGE",
2041 "EM_FINDWORDBREAK",
2042 "EM_SETOPTIONS",
2043 "EM_GETOPTIONS",
2044 "EM_FINDTEXTEX",
2045 "EM_GETWORDBREAKPROCEX",
2046 "EM_SETWORDBREAKPROCEX",
2047 "EM_SETUNDOLIMIT",
2048 "EM_UNKNOWN_USER_83",
2049 "EM_REDO",
2050 "EM_CANREDO",
2051 "EM_GETUNDONAME",
2052 "EM_GETREDONAME",
2053 "EM_STOPGROUPTYPING",
2054 "EM_SETTEXTMODE",
2055 "EM_GETTEXTMODE",
2056 "EM_AUTOURLDETECT",
2057 "EM_GETAUTOURLDETECT",
2058 "EM_SETPALETTE",
2059 "EM_GETTEXTEX",
2060 "EM_GETTEXTLENGTHEX",
2061 "EM_SHOWSCROLLBAR",
2062 "EM_SETTEXTEX",
2063 "EM_UNKNOWN_USER_98",
2064 "EM_UNKNOWN_USER_99",
2065 "EM_SETPUNCTUATION",
2066 "EM_GETPUNCTUATION",
2067 "EM_SETWORDWRAPMODE",
2068 "EM_GETWORDWRAPMODE",
2069 "EM_SETIMECOLOR",
2070 "EM_GETIMECOLOR",
2071 "EM_SETIMEOPTIONS",
2072 "EM_GETIMEOPTIONS",
2073 "EM_CONVPOSITION",
2074 "EM_UNKNOWN_USER_109",
2075 "EM_UNKNOWN_USER_110",
2076 "EM_UNKNOWN_USER_111",
2077 "EM_UNKNOWN_USER_112",
2078 "EM_UNKNOWN_USER_113",
2079 "EM_UNKNOWN_USER_114",
2080 "EM_UNKNOWN_USER_115",
2081 "EM_UNKNOWN_USER_116",
2082 "EM_UNKNOWN_USER_117",
2083 "EM_UNKNOWN_USER_118",
2084 "EM_UNKNOWN_USER_119",
2085 "EM_SETLANGOPTIONS",
2086 "EM_GETLANGOPTIONS",
2087 "EM_GETIMECOMPMODE",
2088 "EM_FINDTEXTW",
2089 "EM_FINDTEXTEXW",
2090 "EM_RECONVERSION",
2091 "EM_SETIMEMODEBIAS",
2092 "EM_GETIMEMODEBIAS"
2095 static const char *
2096 get_msg_name(UINT msg)
2098 if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2099 return edit_messages[msg - EM_GETSEL];
2100 if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2101 return richedit_messages[msg - EM_CANPASTE];
2102 return "";
2105 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
2106 LPARAM lParam, BOOL unicode)
2108 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2110 TRACE("hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
2111 hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
2113 if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
2114 ERR("called with invalid hWnd %p - application bug?\n", hWnd);
2115 return 0;
2118 switch(msg) {
2120 UNSUPPORTED_MSG(EM_DISPLAYBAND)
2121 UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2122 UNSUPPORTED_MSG(EM_FMTLINES)
2123 UNSUPPORTED_MSG(EM_FORMATRANGE)
2124 UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2125 UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2126 UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2127 /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
2128 UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2129 /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
2130 UNSUPPORTED_MSG(EM_GETREDONAME)
2131 UNSUPPORTED_MSG(EM_GETTEXTMODE)
2132 UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2133 UNSUPPORTED_MSG(EM_GETUNDONAME)
2134 UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2135 UNSUPPORTED_MSG(EM_PASTESPECIAL)
2136 UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2137 UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2138 UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2139 UNSUPPORTED_MSG(EM_SETFONTSIZE)
2140 UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2141 UNSUPPORTED_MSG(EM_SETPALETTE)
2142 UNSUPPORTED_MSG(EM_SETTABSTOPS)
2143 UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2144 UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
2145 UNSUPPORTED_MSG(WM_STYLECHANGING)
2146 UNSUPPORTED_MSG(WM_STYLECHANGED)
2148 /* Messages specific to Richedit controls */
2150 case EM_STREAMIN:
2151 return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
2152 case EM_STREAMOUT:
2153 return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
2154 case WM_GETDLGCODE:
2156 UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
2157 if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
2159 int vk = (int)((LPMSG)lParam)->wParam;
2160 /* if style says we want return key */
2161 if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
2163 code |= DLGC_WANTMESSAGE;
2165 /* we always handle ctrl-tab */
2166 if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
2168 code |= DLGC_WANTMESSAGE;
2171 return code;
2173 case WM_NCCREATE:
2175 CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
2176 TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
2177 editor = ME_MakeEditor(hWnd);
2178 SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
2179 return TRUE;
2181 case EM_EMPTYUNDOBUFFER:
2182 ME_EmptyUndoStack(editor);
2183 return 0;
2184 case EM_GETSEL:
2186 /* Note: wParam/lParam can be NULL */
2187 UINT from, to;
2188 PUINT pfrom = wParam ? (PUINT)wParam : &from;
2189 PUINT pto = lParam ? (PUINT)lParam : &to;
2190 ME_GetSelection(editor, (int *)pfrom, (int *)pto);
2191 if ((*pfrom|*pto) & 0xFFFF0000)
2192 return -1;
2193 return MAKELONG(*pfrom,*pto);
2195 case EM_EXGETSEL:
2197 CHARRANGE *pRange = (CHARRANGE *)lParam;
2198 ME_GetSelection(editor, &pRange->cpMin, &pRange->cpMax);
2199 TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
2200 return 0;
2202 case EM_SETUNDOLIMIT:
2204 if ((int)wParam < 0)
2205 editor->nUndoLimit = STACK_SIZE_DEFAULT;
2206 else
2207 editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
2208 /* Setting a max stack size keeps wine from getting killed
2209 for hogging memory. Windows allocates all this memory at once, so
2210 no program would realistically set a value above our maximum. */
2211 return editor->nUndoLimit;
2213 case EM_CANUNDO:
2214 return editor->pUndoStack != NULL;
2215 case EM_CANREDO:
2216 return editor->pRedoStack != NULL;
2217 case WM_UNDO: /* FIXME: actually not the same */
2218 case EM_UNDO:
2219 return ME_Undo(editor);
2220 case EM_REDO:
2221 return ME_Redo(editor);
2222 case EM_GETOPTIONS:
2224 /* these flags are equivalent to the ES_* counterparts */
2225 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2226 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
2227 DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
2229 return settings;
2231 case EM_SETOPTIONS:
2233 /* these flags are equivalent to ES_* counterparts
2234 * ECO_READONLY is already implemented in the code, only requires
2235 * setting the bit to work
2237 DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
2238 ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
2239 DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
2240 DWORD settings = mask & raw;
2242 switch(wParam)
2244 case ECOOP_SET:
2245 settings = lParam;
2246 break;
2247 case ECOOP_OR:
2248 settings |= lParam;
2249 break;
2250 case ECOOP_AND:
2251 settings &= lParam;
2252 break;
2253 case ECOOP_XOR:
2254 settings ^= lParam;
2256 SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
2258 if (settings & ECO_AUTOWORDSELECTION)
2259 FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
2260 if (settings & ECO_SELECTIONBAR)
2261 editor->selofs = SELECTIONBAR_WIDTH;
2262 else
2263 editor->selofs = 0;
2264 ME_WrapMarkedParagraphs(editor);
2266 if (settings & ECO_VERTICAL)
2267 FIXME("ECO_VERTICAL not implemented yet!\n");
2268 if (settings & ECO_AUTOHSCROLL)
2269 FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
2270 if (settings & ECO_AUTOVSCROLL)
2271 FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
2272 if (settings & ECO_NOHIDESEL)
2273 FIXME("ECO_NOHIDESEL not implemented yet!\n");
2274 if (settings & ECO_WANTRETURN)
2275 FIXME("ECO_WANTRETURN not implemented yet!\n");
2277 return settings;
2279 case EM_SETSEL:
2281 ME_InvalidateSelection(editor);
2282 ME_SetSelection(editor, wParam, lParam);
2283 ME_InvalidateSelection(editor);
2284 HideCaret(editor->hWnd);
2285 ME_ShowCaret(editor);
2286 ME_SendSelChange(editor);
2287 return 0;
2289 case EM_SETSCROLLPOS:
2291 POINT *point = (POINT *)lParam;
2292 ME_ScrollAbs(editor, point->y);
2293 return 0;
2295 case EM_AUTOURLDETECT:
2297 if (wParam==1 || wParam ==0)
2299 editor->AutoURLDetect_bEnable = (BOOL)wParam;
2300 return 0;
2302 return E_INVALIDARG;
2304 case EM_GETAUTOURLDETECT:
2306 return editor->AutoURLDetect_bEnable;
2308 case EM_EXSETSEL:
2310 int end;
2311 CHARRANGE range = *(CHARRANGE *)lParam;
2313 TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
2315 ME_InvalidateSelection(editor);
2316 end = ME_SetSelection(editor, range.cpMin, range.cpMax);
2317 ME_InvalidateSelection(editor);
2318 HideCaret(editor->hWnd);
2319 ME_ShowCaret(editor);
2320 ME_SendSelChange(editor);
2322 return end;
2324 case EM_SHOWSCROLLBAR:
2326 ShowScrollBar(editor->hWnd, wParam, lParam);
2327 return 0;
2329 case EM_SETTEXTEX:
2331 LPWSTR wszText;
2332 SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
2333 size_t len;
2334 int from, to;
2335 ME_Style *style;
2336 int oldModify = editor->nModifyStep;
2338 if (!pStruct) return 0;
2340 TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
2341 pStruct->codepage == 1200 ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
2342 pStruct->flags, pStruct->codepage);
2344 /* FIXME: make use of pStruct->codepage in the to unicode translation */
2345 wszText = lParam ? ME_ToUnicode(pStruct->codepage == 1200, (void *)lParam) : NULL;
2346 len = wszText ? lstrlenW(wszText) : 0;
2348 if (pStruct->flags & ST_SELECTION) {
2349 ME_GetSelection(editor, &from, &to);
2350 style = ME_GetSelectionInsertStyle(editor);
2351 ME_InternalDeleteText(editor, from, to - from);
2352 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2353 ME_StreamInRTFString(editor, 1, (char *)lParam);
2354 else ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2355 ME_ReleaseStyle(style);
2357 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2359 else {
2360 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2361 if (pStruct->codepage != 1200 && lParam && !strncmp((char *)lParam, "{\\rtf", 5))
2362 ME_StreamInRTFString(editor, 0, (char *)lParam);
2363 else ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2364 len = 1;
2366 if (editor->AutoURLDetect_bEnable) ME_UpdateLinkAttribute(editor, 0, -1);
2368 ME_CommitUndo(editor);
2369 if (!(pStruct->flags & ST_KEEPUNDO))
2371 editor->nModifyStep = oldModify;
2372 ME_EmptyUndoStack(editor);
2374 ME_UpdateRepaint(editor);
2375 return len;
2377 case EM_SETBKGNDCOLOR:
2379 LRESULT lColor;
2380 if (editor->rgbBackColor != -1) {
2381 DeleteObject(editor->hbrBackground);
2382 lColor = editor->rgbBackColor;
2384 else lColor = GetSysColor(COLOR_WINDOW);
2386 if (wParam)
2388 editor->rgbBackColor = -1;
2389 editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2391 else
2393 editor->rgbBackColor = lParam;
2394 editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
2396 if (editor->bRedraw)
2398 InvalidateRect(hWnd, NULL, TRUE);
2399 UpdateWindow(hWnd);
2401 return lColor;
2403 case EM_GETMODIFY:
2404 return editor->nModifyStep == 0 ? 0 : -1;
2405 case EM_SETMODIFY:
2407 if (wParam)
2408 editor->nModifyStep = 1;
2409 else
2410 editor->nModifyStep = 0;
2412 return 0;
2414 case EM_SETREADONLY:
2416 long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
2417 if (wParam)
2418 nStyle |= ES_READONLY;
2419 else
2420 nStyle &= ~ES_READONLY;
2421 SetWindowLongW(hWnd, GWL_STYLE, nStyle);
2422 return 0;
2424 case EM_SETEVENTMASK:
2426 DWORD nOldMask = editor->nEventMask;
2428 editor->nEventMask = lParam;
2429 return nOldMask;
2431 case EM_GETEVENTMASK:
2432 return editor->nEventMask;
2433 case EM_SETCHARFORMAT:
2435 CHARFORMAT2W buf, *p;
2436 BOOL bRepaint = TRUE;
2437 p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
2438 if (p == NULL) return 0;
2439 if (!wParam)
2440 ME_SetDefaultCharFormat(editor, p);
2441 else if (wParam == (SCF_WORD | SCF_SELECTION)) {
2442 FIXME("EM_SETCHARFORMAT: word selection not supported\n");
2443 return 0;
2444 } else if (wParam == SCF_ALL) {
2445 if (editor->mode & TM_PLAINTEXT)
2446 ME_SetDefaultCharFormat(editor, p);
2447 else {
2448 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
2449 editor->nModifyStep = 1;
2451 } else if (editor->mode & TM_PLAINTEXT) {
2452 return 0;
2453 } else {
2454 int from, to;
2455 ME_GetSelection(editor, &from, &to);
2456 bRepaint = (from != to);
2457 ME_SetSelectionCharFormat(editor, p);
2458 if (from != to) editor->nModifyStep = 1;
2460 ME_CommitUndo(editor);
2461 if (bRepaint)
2462 ME_RewrapRepaint(editor);
2463 return 1;
2465 case EM_GETCHARFORMAT:
2467 CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
2468 if (dst->cbSize != sizeof(CHARFORMATA) &&
2469 dst->cbSize != sizeof(CHARFORMATW) &&
2470 dst->cbSize != sizeof(CHARFORMAT2A) &&
2471 dst->cbSize != sizeof(CHARFORMAT2W))
2472 return 0;
2473 tmp.cbSize = sizeof(tmp);
2474 if (!wParam)
2475 ME_GetDefaultCharFormat(editor, &tmp);
2476 else
2477 ME_GetSelectionCharFormat(editor, &tmp);
2478 ME_CopyToCFAny(dst, &tmp);
2479 return tmp.dwMask;
2481 case EM_SETPARAFORMAT:
2482 ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2483 ME_RewrapRepaint(editor);
2484 ME_CommitUndo(editor);
2485 return 0;
2486 case EM_GETPARAFORMAT:
2487 ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
2488 return 0;
2489 case EM_GETFIRSTVISIBLELINE:
2491 ME_DisplayItem *p = editor->pBuffer->pFirst;
2492 int y = ME_GetYScrollPos(editor);
2493 int ypara = 0;
2494 int count = 0;
2495 int ystart, yend;
2496 while(p) {
2497 p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
2498 if (p->type == diTextEnd)
2499 break;
2500 if (p->type == diParagraph) {
2501 ypara = p->member.para.nYPos;
2502 continue;
2504 ystart = ypara + p->member.row.nYPos;
2505 yend = ystart + p->member.row.nHeight;
2506 if (y < yend) {
2507 break;
2509 count++;
2511 return count;
2513 case EM_HIDESELECTION:
2515 editor->bHideSelection = (wParam != 0);
2516 ME_InvalidateSelection(editor);
2517 return 0;
2519 case EM_LINESCROLL:
2521 ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
2522 return TRUE; /* Should return false if a single line richedit control */
2524 case WM_CLEAR:
2526 int from, to;
2527 ME_GetSelection(editor, &from, &to);
2528 ME_InternalDeleteText(editor, from, to-from);
2529 ME_CommitUndo(editor);
2530 ME_UpdateRepaint(editor);
2531 return 0;
2533 case EM_REPLACESEL:
2535 int from, to;
2536 ME_Style *style;
2537 LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
2538 size_t len = wszText ? lstrlenW(wszText) : 0;
2539 TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
2541 ME_GetSelection(editor, &from, &to);
2542 style = ME_GetSelectionInsertStyle(editor);
2543 ME_InternalDeleteText(editor, from, to-from);
2544 ME_InsertTextFromCursor(editor, 0, wszText, len, style);
2545 ME_ReleaseStyle(style);
2546 /* drop temporary style if line end */
2548 * FIXME question: does abc\n mean: put abc,
2549 * clear temp style, put \n? (would require a change)
2551 if (len>0 && wszText[len-1] == '\n')
2552 ME_ClearTempStyle(editor);
2553 ME_EndToUnicode(unicode, wszText);
2554 ME_CommitUndo(editor);
2555 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
2556 if (!wParam)
2557 ME_EmptyUndoStack(editor);
2558 ME_UpdateRepaint(editor);
2559 return len;
2561 case EM_SCROLLCARET:
2563 int top, bottom; /* row's edges relative to document top */
2564 int nPos;
2565 ME_DisplayItem *para, *row;
2567 nPos = ME_GetYScrollPos(editor);
2568 row = ME_RowStart(editor->pCursors[0].pRun);
2569 para = ME_GetParagraph(row);
2570 top = para->member.para.nYPos + row->member.row.nYPos;
2571 bottom = top + row->member.row.nHeight;
2573 if (top < nPos) /* caret above window */
2574 ME_ScrollAbs(editor, top);
2575 else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
2576 ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
2577 return 0;
2579 case WM_SETFONT:
2581 LOGFONTW lf;
2582 CHARFORMAT2W fmt;
2583 HDC hDC;
2584 BOOL bRepaint = LOWORD(lParam);
2586 if (!wParam)
2587 wParam = (WPARAM)GetStockObject(SYSTEM_FONT);
2588 GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
2589 hDC = GetDC(hWnd);
2590 ME_CharFormatFromLogFont(hDC, &lf, &fmt);
2591 ReleaseDC(hWnd, hDC);
2592 ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
2593 ME_SetDefaultCharFormat(editor, &fmt);
2595 ME_CommitUndo(editor);
2596 if (bRepaint)
2597 ME_RewrapRepaint(editor);
2598 return 0;
2600 case WM_SETTEXT:
2602 ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
2603 if (lParam)
2605 TRACE("WM_SETTEXT lParam==%lx\n",lParam);
2606 if (!unicode && !strncmp((char *)lParam, "{\\rtf", 5))
2608 /* Undocumented: WM_SETTEXT supports RTF text */
2609 ME_StreamInRTFString(editor, 0, (char *)lParam);
2611 else
2613 LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
2614 TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
2615 if (lstrlenW(wszText) > 0)
2617 int len = -1;
2619 /* uses default style! */
2620 if (!(GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
2622 WCHAR * p;
2624 p = wszText;
2625 while (*p != '\0' && *p != '\r' && *p != '\n') p++;
2626 len = p - wszText;
2628 ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
2630 ME_EndToUnicode(unicode, wszText);
2633 else
2634 TRACE("WM_SETTEXT - NULL\n");
2635 if (editor->AutoURLDetect_bEnable)
2637 ME_UpdateLinkAttribute(editor, 0, -1);
2639 ME_SetSelection(editor, 0, 0);
2640 editor->nModifyStep = 0;
2641 ME_CommitUndo(editor);
2642 ME_EmptyUndoStack(editor);
2643 ME_UpdateRepaint(editor);
2644 return 1;
2646 case EM_CANPASTE:
2648 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2649 if (IsClipboardFormatAvailable(nRTFFormat))
2650 return TRUE;
2651 if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2652 return TRUE;
2653 return FALSE;
2655 case WM_PASTE:
2657 DWORD dwFormat = 0;
2658 EDITSTREAM es;
2659 ME_GlobalDestStruct gds;
2660 UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
2661 UINT cf = 0;
2663 if (IsClipboardFormatAvailable(nRTFFormat))
2664 cf = nRTFFormat, dwFormat = SF_RTF;
2665 else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
2666 cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
2667 else
2668 return 0;
2670 if (!OpenClipboard(hWnd))
2671 return 0;
2672 gds.hData = GetClipboardData(cf);
2673 gds.nLength = 0;
2674 es.dwCookie = (DWORD)&gds;
2675 es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2676 ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2678 CloseClipboard();
2679 return 0;
2681 case WM_CUT:
2682 case WM_COPY:
2684 LPDATAOBJECT dataObj = NULL;
2685 CHARRANGE range;
2686 HRESULT hr = S_OK;
2688 if (editor->cPasswordMask)
2689 return 0; /* Copying or Cutting masked text isn't allowed */
2691 ME_GetSelection(editor, &range.cpMin, &range.cpMax);
2692 if(editor->lpOleCallback)
2693 hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2694 if(FAILED(hr) || !dataObj)
2695 hr = ME_GetDataObject(editor, &range, &dataObj);
2696 if(SUCCEEDED(hr)) {
2697 hr = OleSetClipboard(dataObj);
2698 IDataObject_Release(dataObj);
2700 if (SUCCEEDED(hr) && msg == WM_CUT)
2702 ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
2703 ME_CommitUndo(editor);
2704 ME_UpdateRepaint(editor);
2706 return 0;
2708 case WM_GETTEXTLENGTH:
2710 GETTEXTLENGTHEX how;
2712 /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
2713 how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
2714 how.codepage = unicode ? 1200 : CP_ACP;
2715 return ME_GetTextLengthEx(editor, &how);
2717 case EM_GETTEXTLENGTHEX:
2718 return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
2719 case WM_GETTEXT:
2721 GETTEXTEX ex;
2722 LRESULT rc;
2723 LPSTR bufferA = NULL;
2724 LPWSTR bufferW = NULL;
2726 if (unicode)
2727 bufferW = heap_alloc((wParam + 2) * sizeof(WCHAR));
2728 else
2729 bufferA = heap_alloc(wParam + 2);
2731 ex.cb = (wParam + 2) * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
2732 ex.flags = GT_USECRLF;
2733 ex.codepage = unicode ? 1200 : CP_ACP;
2734 ex.lpDefaultChar = NULL;
2735 ex.lpUsedDefChar = NULL;
2736 rc = RichEditWndProc_common(hWnd, EM_GETTEXTEX, (WPARAM)&ex, unicode ? (LPARAM)bufferW : (LPARAM)bufferA, unicode);
2738 if (unicode)
2740 memcpy((LPWSTR)lParam, bufferW, wParam * sizeof(WCHAR));
2741 if (lstrlenW(bufferW) >= wParam) rc = 0;
2743 else
2745 memcpy((LPSTR)lParam, bufferA, wParam);
2746 if (strlen(bufferA) >= wParam) rc = 0;
2748 heap_free(bufferA);
2749 heap_free(bufferW);
2750 return rc;
2752 case EM_GETTEXTEX:
2754 GETTEXTEX *ex = (GETTEXTEX*)wParam;
2755 int nStart, nCount; /* in chars */
2757 if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
2758 FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
2760 if (ex->flags & GT_SELECTION)
2762 ME_GetSelection(editor, &nStart, &nCount);
2763 nCount -= nStart;
2765 else
2767 nStart = 0;
2768 nCount = 0x7fffffff;
2770 if (ex->codepage == 1200)
2772 nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2773 return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2775 else
2777 /* potentially each char may be a CR, why calculate the exact value with O(N) when
2778 we can just take a bigger buffer? :)
2779 The above assumption still holds with CR/LF counters, since CR->CRLF expansion
2780 occurs only in richedit 2.0 mode, in which line breaks have only one CR
2782 int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2783 LPWSTR buffer;
2784 DWORD buflen = ex->cb;
2785 LRESULT rc;
2786 DWORD flags = 0;
2788 nCount = min(nCount, ex->cb - 1);
2789 buffer = heap_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2791 buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2792 rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen+1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
2793 if (rc) rc--; /* do not count 0 terminator */
2795 heap_free(buffer);
2796 return rc;
2799 case EM_GETSELTEXT:
2801 int from, to;
2802 TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2803 ME_GetSelection(editor, &from, &to);
2804 tr.chrg.cpMin = from;
2805 tr.chrg.cpMax = to;
2806 tr.lpstrText = (WCHAR *)lParam;
2807 return RichEditWndProc_common(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr, unicode);
2809 case EM_GETSCROLLPOS:
2811 POINT *point = (POINT *)lParam;
2812 point->x = 0; /* FIXME side scrolling not implemented */
2813 point->y = ME_GetYScrollPos(editor);
2814 return 1;
2816 case EM_GETTEXTRANGE:
2818 TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2819 TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2820 rng->chrg.cpMin, rng->chrg.cpMax, unicode,
2821 editor->bEmulateVersion10, ME_GetTextLength(editor));
2822 if (unicode)
2823 return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, 0);
2824 else
2826 int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2827 WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2828 int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, 0);
2829 /* FIXME this is a potential security hole (buffer overrun)
2830 if you know more about wchar->mbyte conversion please explain
2832 WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2833 FREE_OBJ(p);
2834 return nChars;
2837 case EM_GETLINE:
2839 ME_DisplayItem *run;
2840 const unsigned int nMaxChars = *(WORD *) lParam;
2841 unsigned int nCharsLeft = nMaxChars;
2842 char *dest = (char *) lParam;
2843 BOOL wroteNull = FALSE;
2845 TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2846 unicode ? "Unicode" : "Ansi");
2848 run = ME_FindRowWithNumber(editor, wParam);
2849 if (run == NULL)
2850 return 0;
2852 while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2853 && !(run->member.run.nFlags & MERF_ENDPARA))
2855 unsigned int nCopy;
2856 ME_String *strText;
2857 if (run->type != diRun)
2858 break;
2859 strText = run->member.run.strText;
2860 nCopy = min(nCharsLeft, strText->nLen);
2862 if (unicode)
2863 lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2864 else
2865 nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2866 nCharsLeft, NULL, NULL);
2867 dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
2868 nCharsLeft -= nCopy;
2871 /* append line termination, space allowing */
2872 if (nCharsLeft > 0)
2874 if (run && (run->member.run.nFlags & MERF_ENDPARA))
2876 unsigned int i;
2877 /* Write as many \r as encoded in end-of-paragraph, space allowing */
2878 for (i = 0; i < run->member.run.nCR && nCharsLeft > 0; i++, nCharsLeft--)
2880 *((WCHAR *)dest) = '\r';
2881 dest += unicode ? sizeof(WCHAR) : 1;
2883 /* Write as many \n as encoded in end-of-paragraph, space allowing */
2884 for (i = 0; i < run->member.run.nLF && nCharsLeft > 0; i++, nCharsLeft--)
2886 *((WCHAR *)dest) = '\n';
2887 dest += unicode ? sizeof(WCHAR) : 1;
2890 if (nCharsLeft > 0)
2892 if (unicode)
2893 *((WCHAR *)dest) = '\0';
2894 else
2895 *dest = '\0';
2896 nCharsLeft--;
2897 wroteNull = TRUE;
2901 TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
2902 return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
2904 case EM_GETLINECOUNT:
2906 ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2907 int nRows = 0;
2909 ME_DisplayItem *prev_para = NULL, *last_para = NULL;
2911 while (item != editor->pBuffer->pLast)
2913 assert(item->type == diParagraph);
2914 prev_para = ME_FindItemBack(item, diRun);
2915 if (prev_para) {
2916 assert(prev_para->member.run.nFlags & MERF_ENDPARA);
2918 nRows += item->member.para.nRows;
2919 item = item->member.para.next_para;
2921 last_para = ME_FindItemBack(item, diRun);
2922 assert(last_para);
2923 assert(last_para->member.run.nFlags & MERF_ENDPARA);
2924 if (editor->bEmulateVersion10 && prev_para && last_para->member.run.nCharOfs == 0
2925 && prev_para->member.run.nCR == 1 && prev_para->member.run.nLF == 0)
2927 /* In 1.0 emulation, the last solitary \r at the very end of the text
2928 (if one exists) is NOT a line break.
2929 FIXME: this is an ugly hack. This should have a more regular model. */
2930 nRows--;
2933 TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2934 return max(1, nRows);
2936 case EM_LINEFROMCHAR:
2938 if (wParam == -1)
2939 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2940 else
2941 return ME_RowNumberFromCharOfs(editor, wParam);
2943 case EM_EXLINEFROMCHAR:
2945 if (lParam == -1)
2946 return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2947 else
2948 return ME_RowNumberFromCharOfs(editor, lParam);
2950 case EM_LINEINDEX:
2952 ME_DisplayItem *item, *para;
2953 int nCharOfs;
2955 if (wParam == -1)
2956 item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2957 else
2958 item = ME_FindRowWithNumber(editor, wParam);
2959 if (!item)
2960 return -1;
2961 para = ME_GetParagraph(item);
2962 item = ME_FindItemFwd(item, diRun);
2963 nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2964 TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2965 return nCharOfs;
2967 case EM_LINELENGTH:
2969 ME_DisplayItem *item, *item_end;
2970 int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2972 if (wParam > ME_GetTextLength(editor))
2973 return 0;
2974 if (wParam == -1)
2976 FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2977 return 0;
2979 item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2980 item = ME_RowStart(item);
2981 nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2982 item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2983 if (item_end->type == diStartRow)
2984 nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2985 else
2987 ME_DisplayItem *endPara;
2989 nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs;
2990 endPara = ME_FindItemFwd(item, diParagraphOrEnd);
2991 endPara = ME_FindItemBack(endPara, diRun);
2992 assert(endPara);
2993 assert(endPara->type == diRun);
2994 assert(endPara->member.run.nFlags & MERF_ENDPARA);
2995 nNextLineOfs -= endPara->member.run.nCR + endPara->member.run.nLF;
2997 nChars = nNextLineOfs - nThisLineOfs;
2998 TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
2999 return nChars;
3001 case EM_EXLIMITTEXT:
3003 if ((int)lParam < 0)
3004 return 0;
3005 if (lParam == 0)
3006 editor->nTextLimit = 65536;
3007 else
3008 editor->nTextLimit = (int) lParam;
3009 return 0;
3011 case EM_LIMITTEXT:
3013 if (wParam == 0)
3014 editor->nTextLimit = 65536;
3015 else
3016 editor->nTextLimit = (int) wParam;
3017 return 0;
3019 case EM_GETLIMITTEXT:
3021 return editor->nTextLimit;
3023 case EM_FINDTEXT:
3025 FINDTEXTA *ft = (FINDTEXTA *)lParam;
3026 int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3027 WCHAR *tmp;
3028 LRESULT r;
3030 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3031 MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3032 r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3033 FREE_OBJ( tmp );
3034 return r;
3036 case EM_FINDTEXTEX:
3038 FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3039 int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3040 WCHAR *tmp;
3041 LRESULT r;
3043 if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3044 MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3045 r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3046 FREE_OBJ( tmp );
3047 return r;
3049 case EM_FINDTEXTW:
3051 FINDTEXTW *ft = (FINDTEXTW *)lParam;
3052 return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3054 case EM_FINDTEXTEXW:
3056 FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3057 return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3059 case EM_GETZOOM:
3060 if (!wParam || !lParam)
3061 return FALSE;
3062 *(int *)wParam = editor->nZoomNumerator;
3063 *(int *)lParam = editor->nZoomDenominator;
3064 return TRUE;
3065 case EM_SETZOOM:
3066 return ME_SetZoom(editor, wParam, lParam);
3067 case EM_CHARFROMPOS:
3068 return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y, NULL);
3069 case EM_POSFROMCHAR:
3071 ME_DisplayItem *pRun;
3072 int nCharOfs, nOffset, nLength;
3073 POINTL pt = {0,0};
3074 SCROLLINFO si;
3076 nCharOfs = wParam;
3077 /* detect which API version we're dealing with */
3078 if (wParam >= 0x40000)
3079 nCharOfs = lParam;
3080 nLength = ME_GetTextLength(editor);
3082 if (nCharOfs < nLength) {
3083 ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
3084 assert(pRun->type == diRun);
3085 pt.y = pRun->member.run.pt.y;
3086 pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3087 pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
3088 } else {
3089 pt.x = 0;
3090 pt.y = editor->pBuffer->pLast->member.para.nYPos;
3092 pt.x += editor->selofs;
3094 si.cbSize = sizeof(si);
3095 si.fMask = SIF_POS;
3096 if (GetScrollInfo(editor->hWnd, SB_VERT, &si)) pt.y -= si.nPos;
3097 si.cbSize = sizeof(si);
3098 si.fMask = SIF_POS;
3099 if (GetScrollInfo(editor->hWnd, SB_HORZ, &si)) pt.x -= si.nPos;
3101 if (wParam >= 0x40000) {
3102 *(POINTL *)wParam = pt;
3104 return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3106 case WM_CREATE:
3108 SCROLLINFO si;
3110 GetClientRect(hWnd, &editor->rcFormat);
3111 if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
3112 { /* Squelch the default horizontal scrollbar it would make */
3113 ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
3116 si.cbSize = sizeof(si);
3117 si.fMask = SIF_PAGE | SIF_RANGE;
3118 if (GetWindowLongW(hWnd, GWL_STYLE) & ES_DISABLENOSCROLL)
3119 si.fMask |= SIF_DISABLENOSCROLL;
3120 si.nMax = (si.fMask & SIF_DISABLENOSCROLL) ? 1 : 0;
3121 si.nMin = 0;
3122 si.nPage = 0;
3123 SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
3125 ME_CommitUndo(editor);
3126 ME_WrapMarkedParagraphs(editor);
3127 ME_MoveCaret(editor);
3128 return 0;
3130 case WM_DESTROY:
3131 ME_DestroyEditor(editor);
3132 SetWindowLongPtrW(hWnd, 0, 0);
3133 return 0;
3134 case WM_SETCURSOR:
3136 return ME_SetCursor(editor);
3138 case WM_LBUTTONDBLCLK:
3139 case WM_LBUTTONDOWN:
3141 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3142 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3143 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3144 return 0;
3145 SetFocus(hWnd);
3146 ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3147 ME_CalculateClickCount(hWnd, msg, wParam, lParam));
3148 SetCapture(hWnd);
3149 ME_LinkNotify(editor,msg,wParam,lParam);
3150 if (!ME_SetCursor(editor)) goto do_default;
3151 break;
3153 case WM_MOUSEMOVE:
3154 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3155 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3156 return 0;
3157 if (GetCapture() == hWnd)
3158 ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3159 ME_LinkNotify(editor,msg,wParam,lParam);
3160 /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3161 if (GetCapture() == hWnd)
3162 ME_SetCursor(editor);
3163 break;
3164 case WM_LBUTTONUP:
3165 if (GetCapture() == hWnd)
3166 ReleaseCapture();
3167 if (editor->nSelectionType == stDocument)
3168 editor->nSelectionType = stPosition;
3169 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3170 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3171 return 0;
3172 else
3174 ME_SetCursor(editor);
3175 ME_LinkNotify(editor,msg,wParam,lParam);
3177 break;
3178 case WM_RBUTTONUP:
3179 case WM_RBUTTONDOWN:
3180 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3181 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3182 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3183 return 0;
3184 goto do_default;
3185 case WM_CONTEXTMENU:
3186 if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3187 goto do_default;
3188 break;
3189 case WM_PAINT:
3190 if (editor->bRedraw)
3192 HDC hDC;
3193 PAINTSTRUCT ps;
3195 hDC = BeginPaint(hWnd, &ps);
3196 ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
3197 EndPaint(hWnd, &ps);
3199 break;
3200 case WM_SETFOCUS:
3201 editor->bHaveFocus = TRUE;
3202 ME_ShowCaret(editor);
3203 ME_SendOldNotify(editor, EN_SETFOCUS);
3204 return 0;
3205 case WM_KILLFOCUS:
3206 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3207 editor->bHaveFocus = FALSE;
3208 ME_HideCaret(editor);
3209 ME_SendOldNotify(editor, EN_KILLFOCUS);
3210 return 0;
3211 case WM_ERASEBKGND:
3213 if (editor->bRedraw)
3215 HDC hDC = (HDC)wParam;
3216 RECT rc;
3217 if (GetUpdateRect(hWnd,&rc,TRUE))
3219 FillRect(hDC, &rc, editor->hbrBackground);
3222 return 1;
3224 case WM_COMMAND:
3225 TRACE("editor wnd command = %d\n", LOWORD(wParam));
3226 return 0;
3227 case WM_KEYUP:
3228 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3229 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3230 return 0;
3231 goto do_default;
3232 case WM_KEYDOWN:
3233 if ((editor->nEventMask & ENM_KEYEVENTS) &&
3234 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3235 return 0;
3236 if (ME_KeyDown(editor, LOWORD(wParam)))
3237 return 0;
3238 goto do_default;
3239 case WM_CHAR:
3241 WCHAR wstr;
3243 if (unicode)
3244 wstr = (WCHAR)wParam;
3245 else
3247 CHAR charA = wParam;
3248 MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
3251 switch (wstr)
3253 case 1: /* Ctrl-A */
3254 ME_SetSelection(editor, 0, -1);
3255 return 0;
3256 case 3: /* Ctrl-C */
3257 SendMessageW(editor->hWnd, WM_COPY, 0, 0);
3258 return 0;
3261 if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
3262 MessageBeep(MB_ICONERROR);
3263 return 0; /* FIXME really 0 ? */
3266 switch (wstr)
3268 case 22: /* Ctrl-V */
3269 SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
3270 return 0;
3271 case 24: /* Ctrl-X */
3272 SendMessageW(editor->hWnd, WM_CUT, 0, 0);
3273 return 0;
3274 case 25: /* Ctrl-Y */
3275 SendMessageW(editor->hWnd, EM_REDO, 0, 0);
3276 return 0;
3277 case 26: /* Ctrl-Z */
3278 SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
3279 return 0;
3281 if (((unsigned)wstr)>=' '
3282 || (wstr=='\r' && (GetWindowLongW(hWnd, GWL_STYLE) & ES_MULTILINE))
3283 || wstr=='\t') {
3284 /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
3285 /* WM_CHAR is restricted to nTextLimit */
3286 int from, to;
3287 ME_GetSelection(editor, &from, &to);
3288 if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
3290 ME_Style *style = ME_GetInsertStyle(editor, 0);
3291 ME_SaveTempStyle(editor);
3292 ME_ContinueCoalescingTransaction(editor);
3293 if (wstr == '\r' && (GetKeyState(VK_SHIFT) & 0x8000))
3294 ME_InsertEndRowFromCursor(editor, 0);
3295 else
3296 ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
3297 ME_ReleaseStyle(style);
3298 ME_CommitCoalescingUndo(editor);
3299 SetCursor(NULL);
3302 if (editor->AutoURLDetect_bEnable) ME_UpdateSelectionLinkAttribute(editor);
3304 ME_UpdateRepaint(editor);
3306 return 0;
3308 case WM_UNICHAR:
3309 if (unicode)
3311 if(wParam == UNICODE_NOCHAR) return TRUE;
3312 if(wParam <= 0x000fffff)
3314 if(wParam > 0xffff) /* convert to surrogates */
3316 wParam -= 0x10000;
3317 SendMessageW(editor->hWnd, WM_CHAR, (wParam >> 10) + 0xd800, 0);
3318 SendMessageW(editor->hWnd, WM_CHAR, (wParam & 0x03ff) + 0xdc00, 0);
3320 else SendMessageW(editor->hWnd, WM_CHAR, wParam, 0);
3322 return 0;
3324 break;
3325 case EM_STOPGROUPTYPING:
3326 ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3327 return 0;
3328 case EM_SCROLL: /* fall through */
3329 case WM_VSCROLL:
3331 int origNPos;
3332 int lineHeight;
3334 origNPos = ME_GetYScrollPos(editor);
3335 lineHeight = 24;
3337 if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
3338 lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
3339 if (lineHeight <= 0) lineHeight = 24;
3341 switch(LOWORD(wParam))
3343 case SB_LINEUP:
3344 ME_ScrollUp(editor,lineHeight);
3345 break;
3346 case SB_LINEDOWN:
3347 ME_ScrollDown(editor,lineHeight);
3348 break;
3349 case SB_PAGEUP:
3350 ME_ScrollUp(editor,editor->sizeWindow.cy);
3351 break;
3352 case SB_PAGEDOWN:
3353 ME_ScrollDown(editor,editor->sizeWindow.cy);
3354 break;
3355 case SB_THUMBTRACK:
3356 case SB_THUMBPOSITION:
3357 ME_ScrollAbs(editor,HIWORD(wParam));
3358 break;
3360 if (msg == EM_SCROLL)
3361 return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
3362 break;
3364 case WM_MOUSEWHEEL:
3366 int gcWheelDelta;
3367 UINT pulScrollLines;
3369 if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3370 !ME_FilterEvent(editor, msg, &wParam, &lParam))
3371 return 0;
3373 SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
3374 gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
3376 if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
3378 /* FIXME follow the original */
3379 ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8);
3381 break;
3383 case EM_GETRECT:
3385 *((RECT *)lParam) = editor->rcFormat;
3386 return 0;
3388 case EM_SETRECT:
3389 case EM_SETRECTNP:
3391 if (lParam)
3393 RECT *rc = (RECT *)lParam;
3395 if (wParam)
3397 editor->rcFormat.left += rc->left;
3398 editor->rcFormat.top += rc->top;
3399 editor->rcFormat.right += rc->right;
3400 editor->rcFormat.bottom += rc->bottom;
3402 else
3404 editor->rcFormat = *rc;
3407 else
3409 GetClientRect(hWnd, &editor->rcFormat);
3411 if (msg != EM_SETRECTNP)
3412 ME_RewrapRepaint(editor);
3413 return 0;
3415 case EM_REQUESTRESIZE:
3416 ME_SendRequestResize(editor, TRUE);
3417 return 0;
3418 case WM_SETREDRAW:
3419 if ((editor->bRedraw = wParam))
3420 ME_RewrapRepaint(editor);
3421 return 0;
3422 case WM_SIZE:
3424 GetClientRect(hWnd, &editor->rcFormat);
3425 ME_RewrapRepaint(editor);
3426 return DefWindowProcW(hWnd, msg, wParam, lParam);
3428 /* IME messages to make richedit controls IME aware */
3429 case WM_IME_SETCONTEXT:
3430 case WM_IME_CONTROL:
3431 case WM_IME_SELECT:
3432 case WM_IME_COMPOSITIONFULL:
3433 return 0;
3434 case WM_IME_STARTCOMPOSITION:
3436 editor->imeStartIndex=ME_GetCursorOfs(editor,0);
3437 ME_DeleteSelection(editor);
3438 ME_CommitUndo(editor);
3439 ME_UpdateRepaint(editor);
3440 return 0;
3442 case WM_IME_COMPOSITION:
3444 HIMC hIMC;
3446 ME_Style *style = ME_GetInsertStyle(editor, 0);
3447 hIMC = ImmGetContext(hWnd);
3448 ME_DeleteSelection(editor);
3449 ME_CommitUndo(editor);
3450 ME_SaveTempStyle(editor);
3451 if (lParam & GCS_RESULTSTR)
3453 LPWSTR lpCompStr = NULL;
3454 DWORD dwBufLen;
3456 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3457 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3458 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
3459 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3460 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3462 else if (lParam & GCS_COMPSTR)
3464 LPWSTR lpCompStr = NULL;
3465 DWORD dwBufLen;
3467 dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
3468 lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
3469 ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
3470 lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
3472 ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
3473 ME_SetSelection(editor,editor->imeStartIndex,
3474 editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
3476 ME_ReleaseStyle(style);
3477 ME_UpdateRepaint(editor);
3478 return 0;
3480 case WM_IME_ENDCOMPOSITION:
3482 ME_DeleteSelection(editor);
3483 editor->imeStartIndex=-1;
3484 return 0;
3486 case EM_GETOLEINTERFACE:
3488 LPVOID *ppvObj = (LPVOID*) lParam;
3489 return CreateIRichEditOle(editor, ppvObj);
3491 case EM_GETPASSWORDCHAR:
3493 return editor->cPasswordMask;
3495 case EM_SETOLECALLBACK:
3496 if(editor->lpOleCallback)
3497 IUnknown_Release(editor->lpOleCallback);
3498 editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
3499 if(editor->lpOleCallback)
3500 IUnknown_AddRef(editor->lpOleCallback);
3501 return TRUE;
3502 case EM_GETWORDBREAKPROC:
3503 return (LRESULT)editor->pfnWordBreak;
3504 case EM_SETWORDBREAKPROC:
3506 EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
3508 editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
3509 return (LRESULT)pfnOld;
3511 case EM_SETTEXTMODE:
3513 LRESULT ret;
3514 int mask = 0;
3515 int changes = 0;
3516 ret = RichEditWndProc_common(hWnd, WM_GETTEXTLENGTH, 0, 0, unicode);
3517 if (!ret)
3519 /*Check for valid wParam*/
3520 if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
3521 (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
3522 (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
3523 return 1;
3524 else
3526 if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
3528 mask |= (TM_RICHTEXT | TM_PLAINTEXT);
3529 changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
3531 /*FIXME: Currently no support for undo level and code page options*/
3532 editor->mode = (editor->mode & (~mask)) | changes;
3533 return 0;
3536 return ret;
3538 case EM_SETPASSWORDCHAR:
3540 editor->cPasswordMask = wParam;
3541 ME_RewrapRepaint(editor);
3542 return 0;
3544 case EM_SETTARGETDEVICE:
3545 if (wParam == 0)
3547 BOOL new = (lParam == 0);
3548 if (editor->bWordWrap != new)
3550 editor->bWordWrap = new;
3551 ME_RewrapRepaint(editor);
3554 else FIXME("Unsupported yet non NULL device in EM_SETTARGETDEVICE\n");
3555 break;
3556 default:
3557 do_default:
3558 return DefWindowProcW(hWnd, msg, wParam, lParam);
3560 return 0L;
3563 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3565 BOOL unicode = TRUE;
3567 /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
3568 if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
3569 unicode = FALSE;
3571 return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
3574 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3576 return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
3579 /******************************************************************
3580 * RichEditANSIWndProc (RICHED20.10)
3582 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3584 return RichEditWndProcA(hWnd, msg, wParam, lParam);
3587 /******************************************************************
3588 * RichEdit10ANSIWndProc (RICHED20.9)
3590 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
3592 LRESULT result;
3594 /* FIXME: this is NOT the same as 2.0 version */
3595 result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
3596 if (msg == WM_NCCREATE)
3598 ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
3600 editor->bEmulateVersion10 = TRUE;
3601 editor->pBuffer->pLast->member.para.nCharOfs = 2;
3602 assert(editor->pBuffer->pLast->prev->type == diRun);
3603 assert(editor->pBuffer->pLast->prev->member.run.nFlags & MERF_ENDPARA);
3604 editor->pBuffer->pLast->prev->member.run.nLF = 1;
3606 return result;
3609 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
3611 HWND hWnd = editor->hWnd;
3612 SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
3615 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
3617 int x,y;
3618 ME_Cursor tmpCursor;
3619 BOOL isExact;
3620 int nCharOfs; /* The start of the clicked text. Absolute character offset */
3622 ME_Run *tmpRun;
3624 ENLINK info;
3625 x = (short)LOWORD(lParam);
3626 y = (short)HIWORD(lParam);
3627 nCharOfs = ME_CharFromPos(editor, x, y, &isExact);
3628 if (!isExact) return;
3630 ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
3631 tmpRun = &tmpCursor.pRun->member.run;
3633 if ((tmpRun->style->fmt.dwMask & CFM_LINK)
3634 && (tmpRun->style->fmt.dwEffects & CFE_LINK))
3635 { /* The clicked run has CFE_LINK set */
3636 info.nmhdr.hwndFrom = editor->hWnd;
3637 info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
3638 info.nmhdr.code = EN_LINK;
3639 info.msg = msg;
3640 info.wParam = wParam;
3641 info.lParam = lParam;
3642 info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
3643 info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
3644 SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
3648 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
3650 ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
3651 int i = 0;
3653 while(item && item->member.para.next_para->member.para.nCharOfs <= from)
3654 item = item->member.para.next_para;
3655 if (!item)
3656 return 0;
3657 while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
3658 item = item->member.para.next_para;
3659 i++;
3661 return i;
3665 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
3667 ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
3668 int nWritten = 0;
3669 WCHAR *pStart = buffer;
3671 if (!item) {
3672 *buffer = 0;
3673 return 0;
3676 /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
3677 if (editor->bEmulateVersion10) bCRLF = 0;
3679 if (nStart)
3681 int nLen = ME_StrLen(item->member.run.strText) - nStart;
3682 if (nLen > nChars)
3683 nLen = nChars;
3684 CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
3685 nChars -= nLen;
3686 nWritten += nLen;
3687 buffer += nLen;
3688 if (!nChars) {
3689 *buffer = 0;
3690 return nWritten;
3692 nStart = 0;
3693 item = ME_FindItemFwd(item, diRun);
3696 while(nChars && item)
3698 int nLen = ME_StrLen(item->member.run.strText);
3699 if (item->member.run.nFlags & MERF_ENDPARA)
3700 nLen = item->member.run.nCR + item->member.run.nLF;
3701 if (nLen > nChars)
3702 nLen = nChars;
3704 if (item->member.run.nFlags & MERF_ENDPARA)
3706 if (!ME_FindItemFwd(item, diRun))
3707 /* No '\r' is appended to the last paragraph. */
3708 nLen = 0;
3709 else if (bCRLF && nChars == 1) {
3710 nLen = 0;
3711 nChars = 0;
3712 } else {
3713 if (bCRLF)
3715 /* richedit 2.0 case - actual line-break is \r but should report \r\n */
3716 assert(nLen == 1);
3717 *buffer++ = '\r';
3718 *buffer = '\n'; /* Later updated by nLen==1 at the end of the loop */
3719 nWritten++;
3721 else
3723 int i, j;
3725 /* richedit 2.0 verbatim has only \r. richedit 1.0 should honor encodings */
3726 i = 0;
3727 while (nChars - i > 0 && i < item->member.run.nCR)
3729 buffer[i] = '\r'; i++;
3731 j = 0;
3732 while (nChars - i - j > 0 && j < item->member.run.nLF)
3734 buffer[i+j] = '\n'; j++;
3739 else
3740 CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
3741 nChars -= nLen;
3742 nWritten += nLen;
3743 buffer += nLen;
3745 if (!nChars)
3747 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3748 *buffer = 0;
3749 return nWritten;
3751 item = ME_FindItemFwd(item, diRun);
3753 *buffer = 0;
3754 TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
3755 return nWritten;
3758 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
3760 WNDCLASSW wcW;
3761 WNDCLASSA wcA;
3763 wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3764 wcW.lpfnWndProc = RichEditWndProcW;
3765 wcW.cbClsExtra = 0;
3766 wcW.cbWndExtra = sizeof(ME_TextEditor *);
3767 wcW.hInstance = NULL; /* hInstance would register DLL-local class */
3768 wcW.hIcon = NULL;
3769 wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3770 wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3771 wcW.lpszMenuName = NULL;
3773 if (is_version_nt())
3775 wcW.lpszClassName = RichEdit20W;
3776 if (!RegisterClassW(&wcW)) return FALSE;
3777 wcW.lpszClassName = RichEdit50W;
3778 if (!RegisterClassW(&wcW)) return FALSE;
3780 else
3782 /* WNDCLASSA/W have the same layout */
3783 wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
3784 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3785 wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
3786 if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
3789 wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
3790 wcA.lpfnWndProc = RichEditWndProcA;
3791 wcA.cbClsExtra = 0;
3792 wcA.cbWndExtra = sizeof(ME_TextEditor *);
3793 wcA.hInstance = NULL; /* hInstance would register DLL-local class */
3794 wcA.hIcon = NULL;
3795 wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
3796 wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
3797 wcA.lpszMenuName = NULL;
3798 wcA.lpszClassName = "RichEdit20A";
3799 if (!RegisterClassA(&wcA)) return FALSE;
3800 wcA.lpszClassName = "RichEdit50A";
3801 if (!RegisterClassA(&wcA)) return FALSE;
3803 return TRUE;
3806 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3807 /* FIXME: Not implemented */
3808 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3809 hWnd, msg, get_msg_name(msg), wParam, lParam);
3810 return DefWindowProcW(hWnd, msg, wParam, lParam);
3813 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
3814 /* FIXME: Not implemented */
3815 TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
3816 hWnd, msg, get_msg_name(msg), wParam, lParam);
3817 return DefWindowProcW(hWnd, msg, wParam, lParam);
3820 /******************************************************************
3821 * REExtendedRegisterClass (RICHED20.8)
3823 * FIXME undocumented
3824 * Need to check for errors and implement controls and callbacks
3826 LRESULT WINAPI REExtendedRegisterClass(void)
3828 WNDCLASSW wcW;
3829 UINT result;
3831 FIXME("semi stub\n");
3833 wcW.cbClsExtra = 0;
3834 wcW.cbWndExtra = 4;
3835 wcW.hInstance = NULL;
3836 wcW.hIcon = NULL;
3837 wcW.hCursor = NULL;
3838 wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
3839 wcW.lpszMenuName = NULL;
3841 if (!ME_ListBoxRegistered)
3843 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
3844 wcW.lpfnWndProc = REListWndProc;
3845 wcW.lpszClassName = REListBox20W;
3846 if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
3849 if (!ME_ComboBoxRegistered)
3851 wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
3852 wcW.lpfnWndProc = REComboWndProc;
3853 wcW.lpszClassName = REComboBox20W;
3854 if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;
3857 result = 0;
3858 if (ME_ListBoxRegistered)
3859 result += 1;
3860 if (ME_ComboBoxRegistered)
3861 result += 2;
3863 return result;
3866 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar)
3868 struct prefix_s {
3869 const char *text;
3870 int length;
3871 } prefixes[12] = {
3872 {"http:", 5},
3873 {"file:", 6},
3874 {"mailto:", 8},
3875 {"ftp:", 5},
3876 {"https:", 7},
3877 {"gopher:", 8},
3878 {"nntp:", 6},
3879 {"prospero:", 10},
3880 {"telnet:", 8},
3881 {"news:", 6},
3882 {"wais:", 6},
3883 {"www.", 5}
3885 CHARRANGE ins_pt;
3886 int curf_ef, link_ef, def_ef;
3887 int cur_prefx, prefx_cnt;
3888 int sel_min, sel_max;
3889 int car_pos = 0;
3890 int text_pos=-1;
3891 int URLmin, URLmax = 0;
3892 FINDTEXTA ft;
3893 CHARFORMAT2W cur_format;
3894 CHARFORMAT2W default_format;
3895 CHARFORMAT2W link;
3896 RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
3897 sel_min = ins_pt.cpMin;
3898 sel_max = ins_pt.cpMax;
3899 if (sel_min==sel_max)
3900 car_pos = sel_min;
3901 if (sel_min!=sel_max)
3902 car_pos = ME_GetTextLength(editor)+1;
3903 cur_format.cbSize = sizeof(cur_format);
3904 default_format.cbSize = sizeof(default_format);
3905 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
3906 RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
3907 link.cbSize = sizeof(link);
3908 link.dwMask = CFM_LINK;
3909 link.dwEffects = CFE_LINK;
3910 curf_ef = cur_format.dwEffects & link.dwEffects;
3911 def_ef = default_format.dwEffects & link.dwEffects;
3912 link_ef = link.dwEffects & link.dwEffects;
3913 if (curf_ef == link_ef)
3915 if( curChar == '\n' || curChar=='\r' || curChar==' ')
3917 ME_SetSelection(editor, car_pos, car_pos);
3918 RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
3919 text_pos=-1;
3920 return 0;
3923 if (curf_ef == def_ef)
3925 cur_prefx = 0;
3926 prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
3927 while (cur_prefx<=prefx_cnt)
3929 if (text_pos == -1)
3931 ft.lpstrText = prefixes[cur_prefx].text;
3932 URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
3933 URLmax=max(0, car_pos);
3934 if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
3936 URLmax = ME_GetTextLength(editor)+1;
3938 ft.chrg.cpMin = URLmin;
3939 ft.chrg.cpMax = URLmax;
3940 text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);
3941 cur_prefx++;
3943 if (text_pos != -1)
3945 ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
3946 ME_RewrapRepaint(editor);
3947 break;
3951 return 0;
3955 static BOOL isurlspecial(WCHAR c)
3957 static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
3958 return strchrW( special_chars, c ) != NULL;
3962 * This proc takes a selection, and scans it forward in order to select the span
3963 * of a possible URL candidate. A possible URL candidate must start with isalnum
3964 * or one of the following special characters: *|/\+%#@ and must consist entirely
3965 * of the characters allowed to start the URL, plus : (colon) which may occur
3966 * at most once, and not at either end.
3968 * sel_max == -1 indicates scan to end of text.
3970 BOOL ME_FindNextURLCandidate(ME_TextEditor *editor, int sel_min, int sel_max,
3971 int * candidate_min, int * candidate_max)
3973 ME_DisplayItem * item;
3974 ME_DisplayItem * para;
3975 int nStart;
3976 BOOL foundColon = FALSE;
3977 WCHAR lastAcceptedChar = '\0';
3979 TRACE("sel_min = %d sel_max = %d\n", sel_min, sel_max);
3981 *candidate_min = *candidate_max = -1;
3982 item = ME_FindItemAtOffset(editor, diRun, sel_min, &nStart);
3983 if (!item) return FALSE;
3984 TRACE("nStart = %d\n", nStart);
3985 para = ME_GetParagraph(item);
3986 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
3987 while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart < sel_max)
3989 ME_DisplayItem * next_item;
3991 if (!(item->member.run.nFlags & MERF_ENDPARA)) {
3992 /* Find start of candidate */
3993 if (*candidate_min == -1) {
3994 while (nStart < ME_StrLen(item->member.run.strText) &&
3995 !(isalnumW(item->member.run.strText->szData[nStart]) ||
3996 isurlspecial(item->member.run.strText->szData[nStart]))) {
3997 nStart++;
3999 if (nStart < ME_StrLen(item->member.run.strText) &&
4000 (isalnumW(item->member.run.strText->szData[nStart]) ||
4001 isurlspecial(item->member.run.strText->szData[nStart]))) {
4002 *candidate_min = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4003 lastAcceptedChar = item->member.run.strText->szData[nStart];
4004 nStart++;
4008 /* Find end of candidate */
4009 if (*candidate_min >= 0) {
4010 while (nStart < ME_StrLen(item->member.run.strText) &&
4011 (isalnumW(item->member.run.strText->szData[nStart]) ||
4012 isurlspecial(item->member.run.strText->szData[nStart]) ||
4013 (!foundColon && item->member.run.strText->szData[nStart] == ':') )) {
4014 if (item->member.run.strText->szData[nStart] == ':') foundColon = TRUE;
4015 lastAcceptedChar = item->member.run.strText->szData[nStart];
4016 nStart++;
4018 if (nStart < ME_StrLen(item->member.run.strText) &&
4019 !(isalnumW(item->member.run.strText->szData[nStart]) ||
4020 isurlspecial(item->member.run.strText->szData[nStart]) )) {
4021 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4022 nStart++;
4023 if (lastAcceptedChar == ':') (*candidate_max)--;
4024 return TRUE;
4027 } else {
4028 /* End of paragraph: skip it if before candidate span, or terminates
4029 current active span */
4030 if (*candidate_min >= 0) {
4031 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs;
4032 if (lastAcceptedChar == ':') (*candidate_max)--;
4033 return TRUE;
4037 /* Reaching this point means no span was found, so get next span */
4038 next_item = ME_FindItemFwd(item, diRun);
4039 if (!next_item) {
4040 if (*candidate_min >= 0) {
4041 /* There are no further runs, so take end of text as end of candidate */
4042 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4043 if (lastAcceptedChar == ':') (*candidate_max)--;
4044 return TRUE;
4047 item = next_item;
4048 para = ME_GetParagraph(item);
4049 nStart = 0;
4052 if (item) {
4053 if (*candidate_min >= 0) {
4054 /* There are no further runs, so take end of text as end of candidate */
4055 *candidate_max = para->member.para.nCharOfs + item->member.run.nCharOfs + nStart;
4056 if (lastAcceptedChar == ':') (*candidate_max)--;
4057 return TRUE;
4060 return FALSE;
4064 * This proc evaluates the selection and returns TRUE if it can be considered an URL
4066 BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, int sel_min, int sel_max)
4068 struct prefix_s {
4069 const char *text;
4070 int length;
4071 } prefixes[12] = {
4072 /* Code below depends on these being in decreasing length order! */
4073 {"prospero:", 10},
4074 {"telnet:", 8},
4075 {"gopher:", 8},
4076 {"mailto:", 8},
4077 {"https:", 7},
4078 {"file:", 6},
4079 {"news:", 6},
4080 {"wais:", 6},
4081 {"nntp:", 6},
4082 {"http:", 5},
4083 {"www.", 5},
4084 {"ftp:", 5},
4086 LPWSTR bufferW = NULL;
4087 WCHAR bufW[32];
4088 int i;
4090 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4091 assert(sel_min <= sel_max);
4092 for (i = 0; i < sizeof(prefixes) / sizeof(struct prefix_s); i++)
4094 if (sel_max - sel_min < prefixes[i].length) continue;
4095 if (bufferW == NULL) {
4096 bufferW = (LPWSTR)heap_alloc((sel_max - sel_min + 1) * sizeof(WCHAR));
4098 ME_GetTextW(editor, bufferW, sel_min, min(sel_max - sel_min, strlen(prefixes[i].text)), 0);
4099 MultiByteToWideChar(CP_ACP, 0, prefixes[i].text, -1, bufW, 32);
4100 if (!lstrcmpW(bufW, bufferW))
4102 heap_free(bufferW);
4103 return TRUE;
4106 heap_free(bufferW);
4107 return FALSE;
4111 * This proc walks through the indicated selection and evaluates whether each
4112 * section identified by ME_FindNextURLCandidate and in-between sections have
4113 * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4114 * not what it is supposed to be, this proc sets or unsets it as appropriate.
4116 * Returns TRUE if at least one section was modified.
4118 BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, int sel_min, int sel_max)
4120 BOOL modified = FALSE;
4121 int cMin, cMax;
4123 if (sel_max == -1) sel_max = ME_GetTextLength(editor);
4126 int beforeURL[2];
4127 int inURL[2];
4128 CHARFORMAT2W link;
4130 if (ME_FindNextURLCandidate(editor, sel_min, sel_max, &cMin, &cMax))
4132 /* Section before candidate is not an URL */
4133 beforeURL[0] = sel_min;
4134 beforeURL[1] = cMin;
4136 if (ME_IsCandidateAnURL(editor, cMin, cMax))
4138 inURL[0] = cMin; inURL[1] = cMax;
4140 else
4142 beforeURL[1] = cMax;
4143 inURL[0] = inURL[1] = -1;
4145 sel_min = cMax;
4147 else
4149 /* No more candidates until end of selection */
4150 beforeURL[0] = sel_min;
4151 beforeURL[1] = sel_max;
4152 inURL[0] = inURL[1] = -1;
4153 sel_min = sel_max;
4156 if (beforeURL[0] < beforeURL[1])
4158 /* CFE_LINK effect should be consistently unset */
4159 link.cbSize = sizeof(link);
4160 ME_GetCharFormat(editor, beforeURL[0], beforeURL[1], &link);
4161 if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4163 /* CFE_LINK must be unset from this range */
4164 memset(&link, 0, sizeof(CHARFORMAT2W));
4165 link.cbSize = sizeof(link);
4166 link.dwMask = CFM_LINK;
4167 link.dwEffects = 0;
4168 ME_SetCharFormat(editor, beforeURL[0], beforeURL[1] - beforeURL[0], &link);
4169 modified = TRUE;
4172 if (inURL[0] < inURL[1])
4174 /* CFE_LINK effect should be consistently set */
4175 link.cbSize = sizeof(link);
4176 ME_GetCharFormat(editor, inURL[0], inURL[1], &link);
4177 if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4179 /* CFE_LINK must be set on this range */
4180 memset(&link, 0, sizeof(CHARFORMAT2W));
4181 link.cbSize = sizeof(link);
4182 link.dwMask = CFM_LINK;
4183 link.dwEffects = CFE_LINK;
4184 ME_SetCharFormat(editor, inURL[0], inURL[1] - inURL[0], &link);
4185 modified = TRUE;
4188 } while (sel_min < sel_max);
4189 return modified;
4192 void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
4194 ME_DisplayItem * startPara, * endPara;
4195 ME_DisplayItem * item;
4196 int dummy;
4197 int from, to;
4199 ME_GetSelection(editor, &from, &to);
4200 if (from > to) from ^= to, to ^=from, from ^= to;
4201 startPara = NULL; endPara = NULL;
4203 /* Find paragraph previous to the one that contains start cursor */
4204 item = ME_FindItemAtOffset(editor, diRun, from, &dummy);
4205 if (item) {
4206 startPara = ME_FindItemBack(item, diParagraph);
4207 item = ME_FindItemBack(startPara, diParagraph);
4208 if (item) startPara = item;
4211 /* Find paragraph that contains end cursor */
4212 item = ME_FindItemAtOffset(editor, diRun, to, &dummy);
4213 if (item) {
4214 endPara = ME_FindItemFwd(item, diParagraph);
4217 if (startPara && endPara) {
4218 ME_UpdateLinkAttribute(editor,
4219 startPara->member.para.nCharOfs,
4220 endPara->member.para.nCharOfs);
4221 } else if (startPara) {
4222 ME_UpdateLinkAttribute(editor,
4223 startPara->member.para.nCharOfs,
4224 -1);