fltlib: Add a stub dll.
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  * Copyright 2005 by Cihan Altinay
6  * Copyright 2005 by Phil Krylov
7  * Copyright 2008 Eric Pouech
8  *
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.
13  *
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.
18  *
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
22  */
23
24 /* 
25   API implementation status:
26   
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
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_SETIMESTATUS
103   - EM_SETLANGOPTIONS 2.0
104   - EM_SETLIMITTEXT
105   - EM_SETMARGINS
106   + EM_SETMODIFY (not sure if implementation is correct)
107   - EM_SETOLECALLBACK
108   + EM_SETOPTIONS (partially implemented)
109   - EM_SETPALETTE 2.0
110   + EM_SETPARAFORMAT
111   + EM_SETPASSWORDCHAR 2.0
112   - EM_SETPUNCTUATION 1.0asian
113   + EM_SETREADONLY no beep on modification attempt
114   + EM_SETRECT
115   + EM_SETRECTNP (EM_SETRECT without repainting)
116   + EM_SETSEL
117   + EM_SETSCROLLPOS 3.0
118   - EM_SETTABSTOPS 3.0
119   - EM_SETTARGETDEVICE (partial)
120   + EM_SETTEXTEX 3.0 (proper style?)
121   - EM_SETTEXTMODE 2.0
122   - EM_SETTYPOGRAPHYOPTIONS 3.0
123   + EM_SETUNDOLIMIT 2.0
124   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
125   - EM_SETWORDBREAKPROCEX
126   - EM_SETWORDWRAPMODE 1.0asian
127   + EM_SETZOOM 3.0
128   + EM_SHOWSCROLLBAR 2.0
129   + EM_STOPGROUPTYPING 2.0
130   + EM_STREAMIN
131   + EM_STREAMOUT
132   + EM_UNDO
133   + WM_CHAR
134   + WM_CLEAR
135   + WM_COPY
136   + WM_CUT
137   + WM_GETDLGCODE (the current implementation is incomplete)
138   + WM_GETTEXT (ANSI&Unicode)
139   + WM_GETTEXTLENGTH (ANSI version sucks)
140   + WM_HSCROLL
141   + WM_PASTE
142   + WM_SETFONT
143   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
144   + WM_STYLECHANGING (seems to do nothing)
145   + WM_STYLECHANGED (seems to do nothing)
146   + WM_UNICHAR
147   + WM_VSCROLL
148
149   Notifications
150
151   * EN_CHANGE (sent from the wrong place)
152   - EN_CORRECTTEXT
153   - EN_DROPFILES
154   - EN_ERRSPACE
155   - EN_HSCROLL
156   - EN_IMECHANGE
157   + EN_KILLFOCUS
158   - EN_LINK
159   - EN_MAXTEXT
160   - EN_MSGFILTER
161   - EN_OLEOPFAILED
162   - EN_PROTECTED
163   + EN_REQUESTRESIZE
164   - EN_SAVECLIPBOARD
165   + EN_SELCHANGE 
166   + EN_SETFOCUS
167   - EN_STOPNOUNDO
168   * EN_UPDATE (sent from the wrong place)
169   - EN_VSCROLL
170   
171   Styles
172   
173   - ES_AUTOHSCROLL
174   - ES_AUTOVSCROLL
175   - ES_CENTER
176   + ES_DISABLENOSCROLL (scrollbar is always visible)
177   - ES_EX_NOCALLOLEINIT
178   - ES_LEFT
179   - ES_MULTILINE (currently single line controls aren't supported)
180   - ES_NOIME
181   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
182   - ES_RIGHT
183   - ES_SAVESEL
184   - ES_SELFIME
185   - ES_SUNKEN
186   - ES_VERTICAL
187   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
188   - WS_SETFONT
189   + WS_HSCROLL
190   + WS_VSCROLL
191 */
192
193 /*
194  * RICHED20 TODO (incomplete):
195  *
196  * - messages/styles/notifications listed above 
197  * - add remaining CHARFORMAT/PARAFORMAT fields
198  * - right/center align should strip spaces from the beginning
199  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
200  * - COM interface (looks like a major pain in the TODO list)
201  * - calculate heights of pictures (half-done)
202  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
203  * - find/replace
204  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
205  * - italic caret with italic fonts
206  * - IME
207  * - most notifications aren't sent at all (the most important ones are)
208  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
209  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
210  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
211  * - full justification
212  * - hyphenation
213  * - tables
214  * - ListBox & ComboBox not implemented
215  *
216  * Bugs that are probably fixed, but not so easy to verify:
217  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
218  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
219  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
220  * - caret shouldn't be displayed when selection isn't empty
221  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
222  * - undo for setting default format (done, might be buggy)
223  * - styles might be not released properly (looks like they work like charm, but who knows?
224  *
225  */
226
227 #include "editor.h"
228 #include "commdlg.h"
229 #include "winreg.h"
230 #define NO_SHLWAPI_STREAM 
231 #include "shlwapi.h"
232 #include "rtf.h"
233 #include "imm.h"
234 #include "res.h"
235
236 #define STACK_SIZE_DEFAULT  100
237 #define STACK_SIZE_MAX     1000
238
239 #define TEXT_LIMIT_DEFAULT 32767
240  
241 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
242
243 static BOOL ME_RegisterEditorClass(HINSTANCE);
244 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars);
245
246 static const WCHAR REListBox20W[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
247 static const WCHAR REComboBox20W[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
248 static HCURSOR hLeft;
249
250 int me_debug = 0;
251 HANDLE me_heap = NULL;
252
253 static BOOL ME_ListBoxRegistered = FALSE;
254 static BOOL ME_ComboBoxRegistered = FALSE;
255
256 static inline int is_version_nt(void)
257 {
258     return !(GetVersion() & 0x80000000);
259 }
260
261 static ME_TextBuffer *ME_MakeText(void) {
262   
263   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
264
265   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
266   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
267   
268   p1->prev = NULL;
269   p1->next = p2;
270   p2->prev = p1;
271   p2->next = NULL;
272   p1->member.para.next_para = p2;
273   p2->member.para.prev_para = p1;
274   p2->member.para.nCharOfs = 0;  
275   
276   buf->pFirst = p1;
277   buf->pLast = p2;
278   buf->pCharStyle = NULL;
279   
280   return buf;
281 }
282
283
284 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
285 {
286   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
287   WCHAR *pText;
288   
289   TRACE("%08x %p\n", dwFormat, stream);
290   
291   do {
292     long nWideChars = 0;
293
294     if (!stream->dwSize)
295     {
296       ME_StreamInFill(stream);
297       if (stream->editstream->dwError)
298         break;
299       if (!stream->dwSize)
300         break;
301     }
302       
303     if (!(dwFormat & SF_UNICODE))
304     {
305       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
306       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
307       pText = wszText;
308     }
309     else
310     {
311       nWideChars = stream->dwSize >> 1;
312       pText = (WCHAR *)stream->buffer;
313     }
314     
315     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
316     if (stream->dwSize == 0)
317       break;
318     stream->dwSize = 0;
319   } while(1);
320   ME_CommitUndo(editor);
321   ME_UpdateRepaint(editor);
322   return 0;
323 }
324
325 static void ME_ApplyBorderProperties(RTF_Info *info,
326                                      ME_BorderRect *borderRect,
327                                      RTFBorder *borderDef)
328 {
329   int i, colorNum;
330   ME_Border *pBorders[] = {&borderRect->top,
331                            &borderRect->left,
332                            &borderRect->bottom,
333                            &borderRect->right};
334   for (i = 0; i < 4; i++)
335   {
336     RTFColor *colorDef = info->colorList;
337     pBorders[i]->width = borderDef[i].width;
338     colorNum = borderDef[i].color;
339     while (colorDef && colorDef->rtfCNum != colorNum)
340       colorDef = colorDef->rtfNextColor;
341     if (colorDef)
342       pBorders[i]->colorRef = RGB(
343                            colorDef->rtfCRed >= 0 ? colorDef->rtfCRed : 0,
344                            colorDef->rtfCGreen >= 0 ? colorDef->rtfCGreen : 0,
345                            colorDef->rtfCBlue >= 0 ? colorDef->rtfCBlue : 0);
346     else
347       pBorders[i]->colorRef = RGB(0, 0, 0);
348   }
349 }
350
351 void ME_RTFCharAttrHook(RTF_Info *info)
352 {
353   CHARFORMAT2W fmt;
354   fmt.cbSize = sizeof(fmt);
355   fmt.dwMask = 0;
356   fmt.dwEffects = 0;
357
358   switch(info->rtfMinor)
359   {
360     case rtfPlain:
361       /* FIXME add more flags once they're implemented */
362       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINETYPE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
363       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
364       fmt.yHeight = 12*20; /* 12pt */
365       fmt.wWeight = FW_NORMAL;
366       fmt.bUnderlineType = CFU_UNDERLINENONE;
367       break;
368     case rtfBold:
369       fmt.dwMask = CFM_BOLD | CFM_WEIGHT;
370       fmt.dwEffects = info->rtfParam ? CFE_BOLD : 0;
371       fmt.wWeight = info->rtfParam ? FW_BOLD : FW_NORMAL;
372       break;
373     case rtfItalic:
374       fmt.dwMask = CFM_ITALIC;
375       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
376       break;
377     case rtfUnderline:
378       fmt.dwMask = CFM_UNDERLINETYPE;
379       fmt.bUnderlineType = info->rtfParam ? CFU_CF1UNDERLINE : CFU_UNDERLINENONE;
380       break;
381     case rtfDotUnderline:
382       fmt.dwMask = CFM_UNDERLINETYPE;
383       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOTTED : CFU_UNDERLINENONE;
384       break;
385     case rtfDbUnderline:
386       fmt.dwMask = CFM_UNDERLINETYPE;
387       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEDOUBLE : CFU_UNDERLINENONE;
388       break;
389     case rtfWordUnderline:
390       fmt.dwMask = CFM_UNDERLINETYPE;
391       fmt.bUnderlineType = info->rtfParam ? CFU_UNDERLINEWORD : CFU_UNDERLINENONE;
392       break;
393     case rtfNoUnderline:
394       fmt.dwMask = CFM_UNDERLINETYPE;
395       fmt.bUnderlineType = CFU_UNDERLINENONE;
396       break;
397     case rtfStrikeThru:
398       fmt.dwMask = CFM_STRIKEOUT;
399       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
400       break;
401     case rtfSubScript:
402     case rtfSuperScript:
403     case rtfSubScrShrink:
404     case rtfSuperScrShrink:
405     case rtfNoSuperSub:
406       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
407       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
408       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
409       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
410       break;
411     case rtfInvisible:
412       fmt.dwMask = CFM_HIDDEN;
413       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
414       break;
415     case rtfBackColor:
416       fmt.dwMask = CFM_BACKCOLOR;
417       fmt.dwEffects = 0;
418       if (info->rtfParam == 0)
419         fmt.dwEffects = CFE_AUTOBACKCOLOR;
420       else if (info->rtfParam != rtfNoParam)
421       {
422         RTFColor *c = RTFGetColor(info, info->rtfParam);
423         if (c && c->rtfCBlue >= 0)
424           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
425         else
426           fmt.dwEffects = CFE_AUTOBACKCOLOR;
427       }
428       break;
429     case rtfForeColor:
430       fmt.dwMask = CFM_COLOR;
431       fmt.dwEffects = 0;
432       if (info->rtfParam == 0)
433         fmt.dwEffects = CFE_AUTOCOLOR;
434       else if (info->rtfParam != rtfNoParam)
435       {
436         RTFColor *c = RTFGetColor(info, info->rtfParam);
437         if (c && c->rtfCBlue >= 0)
438           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
439         else {
440           fmt.dwEffects = CFE_AUTOCOLOR;
441         }
442       }
443       break;
444     case rtfFontNum:
445       if (info->rtfParam != rtfNoParam)
446       {
447         RTFFont *f = RTFGetFont(info, info->rtfParam);
448         if (f)
449         {
450           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
451           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
452           fmt.bCharSet = f->rtfFCharSet;
453           fmt.dwMask = CFM_FACE | CFM_CHARSET;
454           fmt.bPitchAndFamily = f->rtfFPitch | (f->rtfFFamily << 4);
455         }
456       }
457       break;
458     case rtfFontSize:
459       fmt.dwMask = CFM_SIZE;
460       if (info->rtfParam != rtfNoParam)
461         fmt.yHeight = info->rtfParam*10;
462       break;
463   }
464   if (fmt.dwMask) {
465     ME_Style *style2;
466     RTFFlushOutputBuffer(info);
467     /* FIXME too slow ? how come ? */
468     style2 = ME_ApplyStyle(info->style, &fmt);
469     ME_ReleaseStyle(info->style);
470     info->style = style2;
471     info->styleChanged = TRUE;
472   }
473 }
474
475 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
476    the same tags mean different things in different contexts */
477 void ME_RTFParAttrHook(RTF_Info *info)
478 {
479   PARAFORMAT2 fmt;
480   fmt.cbSize = sizeof(fmt);
481   fmt.dwMask = 0;
482   
483   switch(info->rtfMinor)
484   {
485   case rtfParDef: /* restores default paragraph attributes */
486     if (!info->editor->bEmulateVersion10) /* v4.1 */
487       info->borderType = RTFBorderParaLeft;
488     else /* v1.0 - 3.0 */
489       info->borderType = RTFBorderParaTop;
490     fmt.dwMask = PFM_ALIGNMENT | PFM_BORDER | PFM_LINESPACING | PFM_TABSTOPS |
491         PFM_OFFSET | PFM_RIGHTINDENT | PFM_SPACEAFTER | PFM_SPACEBEFORE |
492         PFM_STARTINDENT;
493     /* TODO: numbering, shading */
494     fmt.wAlignment = PFA_LEFT;
495     fmt.cTabCount = 0;
496     fmt.dxOffset = fmt.dxStartIndent = fmt.dxRightIndent = 0;
497     fmt.wBorderWidth = fmt.wBorders = 0;
498     fmt.wBorderSpace = 0;
499     fmt.bLineSpacingRule = 0;
500     fmt.dySpaceBefore = fmt.dySpaceAfter = 0;
501     fmt.dyLineSpacing = 0;
502     if (!info->editor->bEmulateVersion10) /* v4.1 */
503     {
504       if (info->tableDef && info->tableDef->tableRowStart &&
505           info->tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
506       {
507         ME_Cursor cursor;
508         ME_DisplayItem *para;
509         /* We are just after a table row. */
510         RTFFlushOutputBuffer(info);
511         cursor = info->editor->pCursors[0];
512         para = cursor.pPara;
513         if (para  == info->tableDef->tableRowStart->member.para.next_para
514             && !cursor.nOffset && !cursor.pRun->member.run.nCharOfs)
515         {
516           /* Since the table row end, no text has been inserted, and the \intbl
517            * control word has not be used.  We can confirm that we are not in a
518            * table anymore.
519            */
520           info->tableDef->tableRowStart = NULL;
521           info->canInheritInTbl = FALSE;
522         }
523       }
524     } else { /* v1.0 - v3.0 */
525       fmt.dwMask |= PFM_TABLE;
526       fmt.wEffects &= ~PFE_TABLE;
527     }
528     break;
529   case rtfNestLevel:
530     if (!info->editor->bEmulateVersion10) /* v4.1 */
531     {
532       while (info->rtfParam > info->nestingLevel) {
533         RTFTable *tableDef = ALLOC_OBJ(RTFTable);
534         ZeroMemory(tableDef, sizeof(RTFTable));
535         tableDef->parent = info->tableDef;
536         info->tableDef = tableDef;
537
538         RTFFlushOutputBuffer(info);
539         if (tableDef->tableRowStart &&
540             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
541         {
542           ME_DisplayItem *para = tableDef->tableRowStart;
543           para = para->member.para.next_para;
544           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
545           tableDef->tableRowStart = para;
546         } else {
547           ME_Cursor cursor;
548           WCHAR endl = '\r';
549           cursor = info->editor->pCursors[0];
550           if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
551             ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
552           tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
553         }
554
555         info->nestingLevel++;
556       }
557       info->canInheritInTbl = FALSE;
558     }
559     break;
560   case rtfInTable:
561   {
562     if (!info->editor->bEmulateVersion10) /* v4.1 */
563     {
564       if (info->nestingLevel < 1)
565       {
566         RTFTable *tableDef;
567         if (!info->tableDef)
568         {
569             info->tableDef = ALLOC_OBJ(RTFTable);
570             ZeroMemory(info->tableDef, sizeof(RTFTable));
571         }
572         tableDef = info->tableDef;
573         RTFFlushOutputBuffer(info);
574         if (tableDef->tableRowStart &&
575             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
576         {
577           ME_DisplayItem *para = tableDef->tableRowStart;
578           para = para->member.para.next_para;
579           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
580           tableDef->tableRowStart = para;
581         } else {
582           ME_Cursor cursor;
583           WCHAR endl = '\r';
584           cursor = info->editor->pCursors[0];
585           if (cursor.nOffset || cursor.pRun->member.run.nCharOfs)
586             ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
587           tableDef->tableRowStart = ME_InsertTableRowStartFromCursor(info->editor);
588         }
589         info->nestingLevel = 1;
590         info->canInheritInTbl = TRUE;
591       }
592       return;
593     } else { /* v1.0 - v3.0 */
594       fmt.dwMask |= PFM_TABLE;
595       fmt.wEffects |= PFE_TABLE;
596     }
597     break;
598   }
599   case rtfFirstIndent:
600     ME_GetSelectionParaFormat(info->editor, &fmt);
601     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
602     fmt.dxStartIndent += fmt.dxOffset + info->rtfParam;
603     fmt.dxOffset = -info->rtfParam;
604     break;
605   case rtfLeftIndent:
606     ME_GetSelectionParaFormat(info->editor, &fmt);
607     fmt.dwMask = PFM_STARTINDENT;
608     fmt.dxStartIndent = info->rtfParam - fmt.dxOffset;
609     break;
610   case rtfRightIndent:
611     fmt.dwMask = PFM_RIGHTINDENT;
612     fmt.dxRightIndent = info->rtfParam;
613     break;
614   case rtfQuadLeft:
615   case rtfQuadJust:
616     fmt.dwMask = PFM_ALIGNMENT;
617     fmt.wAlignment = PFA_LEFT;
618     break;
619   case rtfQuadRight:
620     fmt.dwMask = PFM_ALIGNMENT;
621     fmt.wAlignment = PFA_RIGHT;
622     break;
623   case rtfQuadCenter:
624     fmt.dwMask = PFM_ALIGNMENT;
625     fmt.wAlignment = PFA_CENTER;
626     break;
627   case rtfTabPos:
628     ME_GetSelectionParaFormat(info->editor, &fmt);
629     if (!(fmt.dwMask & PFM_TABSTOPS))
630     {
631       fmt.cTabCount = 0;
632     }
633     if (fmt.cTabCount < MAX_TAB_STOPS && info->rtfParam < 0x1000000)
634       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
635     fmt.dwMask = PFM_TABSTOPS;
636     break;
637   case rtfKeep:
638     fmt.dwMask = PFM_KEEP;
639     fmt.wEffects = PFE_KEEP;
640     break;
641   case rtfNoWidowControl:
642     fmt.dwMask = PFM_NOWIDOWCONTROL;
643     fmt.wEffects = PFE_NOWIDOWCONTROL;
644     break;
645   case rtfKeepNext:
646     fmt.dwMask = PFM_KEEPNEXT;
647     fmt.wEffects = PFE_KEEPNEXT;
648     break;
649   case rtfSpaceAfter:
650     fmt.dwMask = PFM_SPACEAFTER;
651     fmt.dySpaceAfter = info->rtfParam;
652     break;
653   case rtfSpaceBefore:
654     fmt.dwMask = PFM_SPACEBEFORE;
655     fmt.dySpaceBefore = info->rtfParam;
656     break;
657   case rtfSpaceBetween:
658     fmt.dwMask = PFM_LINESPACING;
659     if ((int)info->rtfParam > 0)
660     {
661       fmt.dyLineSpacing = info->rtfParam;
662       fmt.bLineSpacingRule = 3;
663     }
664     else
665     {
666       fmt.dyLineSpacing = info->rtfParam;
667       fmt.bLineSpacingRule = 4;
668     }
669   case rtfSpaceMultiply:
670     fmt.dwMask = PFM_LINESPACING;
671     fmt.dyLineSpacing = info->rtfParam * 20;
672     fmt.bLineSpacingRule = 5;
673     break;
674   case rtfParBullet:
675     fmt.dwMask = PFM_NUMBERING;
676     fmt.wNumbering = PFN_BULLET;
677     break;
678   case rtfParSimple:
679     fmt.dwMask = PFM_NUMBERING;
680     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
681     break;
682   case rtfParNumDecimal:
683     fmt.dwMask = PFM_NUMBERING;
684     fmt.wNumbering = 2; /* FIXME: MSDN says it's not used ?? */
685     break;
686   case rtfParNumIndent:
687     fmt.dwMask = PFM_NUMBERINGTAB;
688     fmt.wNumberingTab = info->rtfParam;
689     break;
690   case rtfParNumStartAt:
691     fmt.dwMask = PFM_NUMBERINGSTART;
692     fmt.wNumberingStart = info->rtfParam;
693     break;
694   case rtfBorderLeft:
695     info->borderType = RTFBorderParaLeft;
696     ME_GetSelectionParaFormat(info->editor, &fmt);
697     if (!(fmt.dwMask & PFM_BORDER))
698     {
699       fmt.wBorderSpace = 0;
700       fmt.wBorderWidth = 1;
701       fmt.wBorders = 0;
702     }
703     fmt.wBorders |= 1;
704     fmt.dwMask = PFM_BORDER;
705     break;
706   case rtfBorderRight:
707     info->borderType = RTFBorderParaRight;
708     ME_GetSelectionParaFormat(info->editor, &fmt);
709     if (!(fmt.dwMask & PFM_BORDER))
710     {
711       fmt.wBorderSpace = 0;
712       fmt.wBorderWidth = 1;
713       fmt.wBorders = 0;
714     }
715     fmt.wBorders |= 2;
716     fmt.dwMask = PFM_BORDER;
717     break;
718   case rtfBorderTop:
719     info->borderType = RTFBorderParaTop;
720     ME_GetSelectionParaFormat(info->editor, &fmt);
721     if (!(fmt.dwMask & PFM_BORDER))
722     {
723       fmt.wBorderSpace = 0;
724       fmt.wBorderWidth = 1;
725       fmt.wBorders = 0;
726     }
727     fmt.wBorders |= 4;
728     fmt.dwMask = PFM_BORDER;
729     break;
730   case rtfBorderBottom:
731     info->borderType = RTFBorderParaBottom;
732     ME_GetSelectionParaFormat(info->editor, &fmt);
733     if (!(fmt.dwMask & PFM_BORDER))
734     {
735       fmt.wBorderSpace = 0;
736       fmt.wBorderWidth = 1;
737       fmt.wBorders = 0;
738     }
739     fmt.wBorders |= 8;
740     fmt.dwMask = PFM_BORDER;
741     break;
742   case rtfBorderSingle:
743     ME_GetSelectionParaFormat(info->editor, &fmt);
744     /* we assume that borders have been created before (RTF spec) */
745     fmt.wBorders &= ~0x700;
746     fmt.wBorders |= 1 << 8;
747     fmt.dwMask = PFM_BORDER;
748     break;
749   case rtfBorderThick:
750     ME_GetSelectionParaFormat(info->editor, &fmt);
751     /* we assume that borders have been created before (RTF spec) */
752     fmt.wBorders &= ~0x700;
753     fmt.wBorders |= 2 << 8;
754     fmt.dwMask = PFM_BORDER;
755     break;
756   case rtfBorderShadow:
757     ME_GetSelectionParaFormat(info->editor, &fmt);
758     /* we assume that borders have been created before (RTF spec) */
759     fmt.wBorders &= ~0x700;
760     fmt.wBorders |= 10 << 8;
761     fmt.dwMask = PFM_BORDER;
762     break;
763   case rtfBorderDouble:
764     ME_GetSelectionParaFormat(info->editor, &fmt);
765     /* we assume that borders have been created before (RTF spec) */
766     fmt.wBorders &= ~0x700;
767     fmt.wBorders |= 7 << 8;
768     fmt.dwMask = PFM_BORDER;
769     break;
770   case rtfBorderDot:
771     ME_GetSelectionParaFormat(info->editor, &fmt);
772     /* we assume that borders have been created before (RTF spec) */
773     fmt.wBorders &= ~0x700;
774     fmt.wBorders |= 11 << 8;
775     fmt.dwMask = PFM_BORDER;
776     break;
777   case rtfBorderWidth:
778   {
779     int borderSide = info->borderType & RTFBorderSideMask;
780     RTFTable *tableDef = info->tableDef;
781     ME_GetSelectionParaFormat(info->editor, &fmt);
782     /* we assume that borders have been created before (RTF spec) */
783     fmt.wBorderWidth |= ((info->rtfParam / 15) & 7) << 8;
784     if ((info->borderType & RTFBorderTypeMask) == RTFBorderTypeCell)
785     {
786       RTFBorder *border;
787       if (!tableDef || tableDef->numCellsDefined >= MAX_TABLE_CELLS)
788         break;
789       border = &tableDef->cells[tableDef->numCellsDefined].border[borderSide];
790       border->width = info->rtfParam;
791       break;
792     }
793     fmt.dwMask = PFM_BORDER;
794     break;
795   }
796   case rtfBorderSpace:
797     ME_GetSelectionParaFormat(info->editor, &fmt);
798     /* we assume that borders have been created before (RTF spec) */
799     fmt.wBorderSpace = info->rtfParam;
800     fmt.dwMask = PFM_BORDER;
801     break;
802   case rtfBorderColor:
803   {
804     RTFTable *tableDef = info->tableDef;
805     int borderSide = info->borderType & RTFBorderSideMask;
806     int borderType = info->borderType & RTFBorderTypeMask;
807     switch(borderType)
808     {
809     case RTFBorderTypePara:
810       if (!info->editor->bEmulateVersion10) /* v4.1 */
811         break;
812       /* v1.0 - 3.0 treat paragraph and row borders the same. */
813     case RTFBorderTypeRow:
814       if (tableDef) {
815         tableDef->border[borderSide].color = info->rtfParam;
816       }
817       break;
818     case RTFBorderTypeCell:
819       if (tableDef && tableDef->numCellsDefined < MAX_TABLE_CELLS) {
820         tableDef->cells[tableDef->numCellsDefined].border[borderSide].color = info->rtfParam;
821       }
822       break;
823     }
824     break;
825   }
826   }
827   if (fmt.dwMask) {
828     RTFFlushOutputBuffer(info);
829     /* FIXME too slow ? how come ?*/
830     ME_SetSelectionParaFormat(info->editor, &fmt);
831   }
832 }
833
834 void ME_RTFTblAttrHook(RTF_Info *info)
835 {
836   switch (info->rtfMinor)
837   {
838     case rtfRowDef:
839     {
840       if (!info->editor->bEmulateVersion10) /* v4.1 */
841         info->borderType = 0; /* Not sure */
842       else /* v1.0 - 3.0 */
843         info->borderType = RTFBorderRowTop;
844       if (!info->tableDef) {
845         info->tableDef = ME_MakeTableDef(info->editor);
846       } else {
847         ME_InitTableDef(info->editor, info->tableDef);
848       }
849       break;
850     }
851     case rtfCellPos:
852     {
853       int cellNum;
854       if (!info->tableDef)
855       {
856         info->tableDef = ME_MakeTableDef(info->editor);
857       }
858       cellNum = info->tableDef->numCellsDefined;
859       if (cellNum >= MAX_TABLE_CELLS)
860         break;
861       info->tableDef->cells[cellNum].rightBoundary = info->rtfParam;
862       if (cellNum < MAX_TAB_STOPS) {
863         /* Tab stops were used to store cell positions before v4.1 but v4.1
864          * still seems to set the tabstops without using them. */
865         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
866         PARAFORMAT2 *pFmt = para->member.para.pFmt;
867         pFmt->rgxTabs[cellNum] &= ~0x00FFFFFF;
868         pFmt->rgxTabs[cellNum] = 0x00FFFFFF & info->rtfParam;
869       }
870       info->tableDef->numCellsDefined++;
871       break;
872     }
873     case rtfRowBordTop:
874       info->borderType = RTFBorderRowTop;
875       break;
876     case rtfRowBordLeft:
877       info->borderType = RTFBorderRowLeft;
878       break;
879     case rtfRowBordBottom:
880       info->borderType = RTFBorderRowBottom;
881       break;
882     case rtfRowBordRight:
883       info->borderType = RTFBorderRowRight;
884       break;
885     case rtfCellBordTop:
886       info->borderType = RTFBorderCellTop;
887       break;
888     case rtfCellBordLeft:
889       info->borderType = RTFBorderCellLeft;
890       break;
891     case rtfCellBordBottom:
892       info->borderType = RTFBorderCellBottom;
893       break;
894     case rtfCellBordRight:
895       info->borderType = RTFBorderCellRight;
896       break;
897     case rtfRowGapH:
898       if (info->tableDef)
899         info->tableDef->gapH = info->rtfParam;
900       break;
901     case rtfRowLeftEdge:
902       if (info->tableDef)
903         info->tableDef->leftEdge = info->rtfParam;
904       break;
905   }
906 }
907
908 void ME_RTFSpecialCharHook(RTF_Info *info)
909 {
910   RTFTable *tableDef = info->tableDef;
911   switch (info->rtfMinor)
912   {
913     case rtfNestCell:
914       if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
915         break;
916       /* else fall through since v4.1 treats rtfNestCell and rtfCell the same */
917     case rtfCell:
918       if (!tableDef)
919         break;
920       RTFFlushOutputBuffer(info);
921       if (!info->editor->bEmulateVersion10) { /* v4.1 */
922         if (tableDef->tableRowStart)
923         {
924           if (!info->nestingLevel &&
925               tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
926           {
927             ME_DisplayItem *para = tableDef->tableRowStart;
928             para = para->member.para.next_para;
929             para = ME_InsertTableRowStartAtParagraph(info->editor, para);
930             tableDef->tableRowStart = para;
931             info->nestingLevel = 1;
932           }
933           ME_InsertTableCellFromCursor(info->editor);
934         }
935       } else { /* v1.0 - v3.0 */
936         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
937         PARAFORMAT2 *pFmt = para->member.para.pFmt;
938         if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE &&
939             tableDef->numCellsInserted < tableDef->numCellsDefined)
940         {
941           WCHAR tab = '\t';
942           ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
943           tableDef->numCellsInserted++;
944         }
945       }
946       break;
947     case rtfNestRow:
948       if (info->editor->bEmulateVersion10) /* v1.0 - v3.0 */
949         break;
950       /* else fall through since v4.1 treats rtfNestRow and rtfRow the same */
951     case rtfRow:
952     {
953       ME_DisplayItem *para, *cell, *run;
954       int i;
955
956       if (!tableDef)
957         break;
958       RTFFlushOutputBuffer(info);
959       if (!info->editor->bEmulateVersion10) { /* v4.1 */
960         if (!tableDef->tableRowStart)
961           break;
962         if (!info->nestingLevel &&
963             tableDef->tableRowStart->member.para.nFlags & MEPF_ROWEND)
964         {
965           para = tableDef->tableRowStart;
966           para = para->member.para.next_para;
967           para = ME_InsertTableRowStartAtParagraph(info->editor, para);
968           tableDef->tableRowStart = para;
969           info->nestingLevel++;
970         }
971         para = tableDef->tableRowStart;
972         cell = ME_FindItemFwd(para, diCell);
973         assert(cell && !cell->member.cell.prev_cell);
974         if (tableDef->numCellsDefined < 1)
975         {
976           /* 2000 twips appears to be the cell size that native richedit uses
977            * when no cell sizes are specified. */
978           const int defaultCellSize = 2000;
979           int nRightBoundary = defaultCellSize;
980           cell->member.cell.nRightBoundary = nRightBoundary;
981           while (cell->member.cell.next_cell) {
982             cell = cell->member.cell.next_cell;
983             nRightBoundary += defaultCellSize;
984             cell->member.cell.nRightBoundary = nRightBoundary;
985           }
986           para = ME_InsertTableCellFromCursor(info->editor);
987           cell = para->member.para.pCell;
988           cell->member.cell.nRightBoundary = nRightBoundary;
989         } else {
990           for (i = 0; i < tableDef->numCellsDefined; i++)
991           {
992             RTFCell *cellDef = &tableDef->cells[i];
993             cell->member.cell.nRightBoundary = cellDef->rightBoundary;
994             ME_ApplyBorderProperties(info, &cell->member.cell.border,
995                                      cellDef->border);
996             cell = cell->member.cell.next_cell;
997             if (!cell)
998             {
999               para = ME_InsertTableCellFromCursor(info->editor);
1000               cell = para->member.para.pCell;
1001             }
1002           }
1003           /* Cell for table row delimiter is empty */
1004           cell->member.cell.nRightBoundary = tableDef->cells[i-1].rightBoundary;
1005         }
1006
1007         run = ME_FindItemFwd(cell, diRun);
1008         if (info->editor->pCursors[0].pRun != run ||
1009             info->editor->pCursors[0].nOffset)
1010         {
1011           int nOfs, nChars;
1012           /* Delete inserted cells that aren't defined. */
1013           info->editor->pCursors[1].pRun = run;
1014           info->editor->pCursors[1].pPara = ME_GetParagraph(run);
1015           info->editor->pCursors[1].nOffset = 0;
1016           nOfs = ME_GetCursorOfs(&info->editor->pCursors[1]);
1017           nChars = ME_GetCursorOfs(&info->editor->pCursors[0]) - nOfs;
1018           ME_InternalDeleteText(info->editor, &info->editor->pCursors[1],
1019                                 nChars, TRUE);
1020         }
1021
1022         para = ME_InsertTableRowEndFromCursor(info->editor);
1023         para->member.para.pFmt->dxOffset = abs(info->tableDef->gapH);
1024         para->member.para.pFmt->dxStartIndent = info->tableDef->leftEdge;
1025         ME_ApplyBorderProperties(info, &para->member.para.border,
1026                                  tableDef->border);
1027         info->nestingLevel--;
1028         if (!info->nestingLevel)
1029         {
1030           if (info->canInheritInTbl) {
1031             tableDef->tableRowStart = para;
1032           } else {
1033             while (info->tableDef) {
1034               tableDef = info->tableDef;
1035               info->tableDef = tableDef->parent;
1036               heap_free(tableDef);
1037             }
1038           }
1039         } else {
1040           info->tableDef = tableDef->parent;
1041           heap_free(tableDef);
1042         }
1043       } else { /* v1.0 - v3.0 */
1044         WCHAR endl = '\r';
1045         ME_DisplayItem *para = info->editor->pCursors[0].pPara;
1046         PARAFORMAT2 *pFmt = para->member.para.pFmt;
1047         pFmt->dxOffset = info->tableDef->gapH;
1048         pFmt->dxStartIndent = info->tableDef->leftEdge;
1049
1050         ME_ApplyBorderProperties(info, &para->member.para.border,
1051                                  tableDef->border);
1052         while (tableDef->numCellsInserted < tableDef->numCellsDefined)
1053         {
1054           WCHAR tab = '\t';
1055           ME_InsertTextFromCursor(info->editor, 0, &tab, 1, info->style);
1056           tableDef->numCellsInserted++;
1057         }
1058         pFmt->cTabCount = min(tableDef->numCellsDefined, MAX_TAB_STOPS);
1059         if (!tableDef->numCellsDefined)
1060           pFmt->wEffects &= ~PFE_TABLE;
1061         ME_InsertTextFromCursor(info->editor, 0, &endl, 1, info->style);
1062         tableDef->numCellsInserted = 0;
1063       }
1064       break;
1065     }
1066     case rtfTab:
1067     case rtfPar:
1068       if (info->editor->bEmulateVersion10) { /* v1.0 - 3.0 */
1069         ME_DisplayItem *para;
1070         PARAFORMAT2 *pFmt;
1071         RTFFlushOutputBuffer(info);
1072         para = info->editor->pCursors[0].pPara;
1073         pFmt = para->member.para.pFmt;
1074         if (pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
1075         {
1076           /* rtfPar is treated like a space within a table. */
1077           info->rtfClass = rtfText;
1078           info->rtfMajor = ' ';
1079         }
1080         else if (info->rtfMinor == rtfPar && tableDef)
1081           tableDef->numCellsInserted = 0;
1082       }
1083       break;
1084   }
1085 }
1086
1087 static BOOL ME_RTFInsertOleObject(RTF_Info *info, HENHMETAFILE hemf, HBITMAP hbmp,
1088                                   const SIZEL* sz)
1089 {
1090   LPOLEOBJECT         lpObject = NULL;
1091   LPSTORAGE           lpStorage = NULL;
1092   LPOLECLIENTSITE     lpClientSite = NULL;
1093   LPDATAOBJECT        lpDataObject = NULL;
1094   LPOLECACHE          lpOleCache = NULL;
1095   STGMEDIUM           stgm;
1096   FORMATETC           fm;
1097   CLSID               clsid;
1098   BOOL                ret = FALSE;
1099   DWORD               conn;
1100
1101   if (hemf)
1102   {
1103       stgm.tymed = TYMED_ENHMF;
1104       stgm.u.hEnhMetaFile = hemf;
1105       fm.cfFormat = CF_ENHMETAFILE;
1106   }
1107   else if (hbmp)
1108   {
1109       stgm.tymed = TYMED_GDI;
1110       stgm.u.hBitmap = hbmp;
1111       fm.cfFormat = CF_BITMAP;
1112   }
1113   stgm.pUnkForRelease = NULL;
1114
1115   fm.ptd = NULL;
1116   fm.dwAspect = DVASPECT_CONTENT;
1117   fm.lindex = -1;
1118   fm.tymed = stgm.tymed;
1119
1120   if (!info->lpRichEditOle)
1121   {
1122     CreateIRichEditOle(info->editor, (VOID**)&info->lpRichEditOle);
1123   }
1124
1125   if (OleCreateDefaultHandler(&CLSID_NULL, NULL, &IID_IOleObject, (void**)&lpObject) == S_OK &&
1126 #if 0
1127       /* FIXME: enable it when rich-edit properly implements this method */
1128       IRichEditOle_GetClientSite(info->lpRichEditOle, &lpClientSite) == S_OK &&
1129       IOleObject_SetClientSite(lpObject, lpClientSite) == S_OK &&
1130 #endif
1131       IOleObject_GetUserClassID(lpObject, &clsid) == S_OK &&
1132       IOleObject_QueryInterface(lpObject, &IID_IOleCache, (void**)&lpOleCache) == S_OK &&
1133       IOleCache_Cache(lpOleCache, &fm, 0, &conn) == S_OK &&
1134       IOleObject_QueryInterface(lpObject, &IID_IDataObject, (void**)&lpDataObject) == S_OK &&
1135       IDataObject_SetData(lpDataObject, &fm, &stgm, TRUE) == S_OK)
1136   {
1137     REOBJECT            reobject;
1138
1139     reobject.cbStruct = sizeof(reobject);
1140     reobject.cp = REO_CP_SELECTION;
1141     reobject.clsid = clsid;
1142     reobject.poleobj = lpObject;
1143     reobject.pstg = lpStorage;
1144     reobject.polesite = lpClientSite;
1145     /* convert from twips to .01 mm */
1146     reobject.sizel.cx = MulDiv(sz->cx, 254, 144);
1147     reobject.sizel.cy = MulDiv(sz->cy, 254, 144);
1148     reobject.dvaspect = DVASPECT_CONTENT;
1149     reobject.dwFlags = 0; /* FIXME */
1150     reobject.dwUser = 0;
1151
1152     /* FIXME: could be simpler */
1153     ret = IRichEditOle_InsertObject(info->lpRichEditOle, &reobject) == S_OK;
1154   }
1155
1156   if (lpObject)       IOleObject_Release(lpObject);
1157   if (lpClientSite)   IOleClientSite_Release(lpClientSite);
1158   if (lpStorage)      IStorage_Release(lpStorage);
1159   if (lpDataObject)   IDataObject_Release(lpDataObject);
1160   if (lpOleCache)     IOleCache_Release(lpOleCache);
1161
1162   return ret;
1163 }
1164
1165 static void ME_RTFReadPictGroup(RTF_Info *info)
1166 {
1167   SIZEL         sz;
1168   BYTE*         buffer = NULL;
1169   unsigned      bufsz, bufidx;
1170   BOOL          flip;
1171   BYTE          val;
1172   METAFILEPICT  mfp;
1173   HENHMETAFILE  hemf;
1174   HBITMAP       hbmp;
1175   enum gfxkind {gfx_unknown = 0, gfx_enhmetafile, gfx_metafile, gfx_dib} gfx = gfx_unknown;
1176
1177   RTFGetToken (info);
1178   if (info->rtfClass == rtfEOF)
1179     return;
1180   mfp.mm = MM_TEXT;
1181   /* fetch picture type */
1182   if (RTFCheckMM (info, rtfPictAttr, rtfWinMetafile))
1183   {
1184     mfp.mm = info->rtfParam;
1185     gfx = gfx_metafile;
1186   }
1187   else if (RTFCheckMM (info, rtfPictAttr, rtfDevIndBitmap))
1188   {
1189     if (info->rtfParam != 0) FIXME("dibitmap should be 0 (%d)\n", info->rtfParam);
1190     gfx = gfx_dib;
1191   }
1192   else if (RTFCheckMM (info, rtfPictAttr, rtfEmfBlip))
1193   {
1194     gfx = gfx_enhmetafile;
1195   }
1196   else
1197   {
1198     FIXME("%d %d\n", info->rtfMajor, info->rtfMinor);
1199     goto skip_group;
1200   }
1201   sz.cx = sz.cy = 0;
1202   /* fetch picture attributes */
1203   for (;;)
1204   {
1205     RTFGetToken (info);
1206     if (info->rtfClass == rtfEOF)
1207       return;
1208     if (info->rtfClass == rtfText)
1209       break;
1210     if (!RTFCheckCM (info, rtfControl, rtfPictAttr))
1211     {
1212       ERR("Expected picture attribute (%d %d)\n",
1213         info->rtfClass, info->rtfMajor);
1214       goto skip_group;
1215     }
1216     else if (RTFCheckMM (info, rtfPictAttr, rtfPicWid))
1217     {
1218       if (gfx == gfx_metafile) mfp.xExt = info->rtfParam;
1219     }
1220     else if (RTFCheckMM (info, rtfPictAttr, rtfPicHt))
1221     {
1222       if (gfx == gfx_metafile) mfp.yExt = info->rtfParam;
1223     }
1224     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalWid))
1225       sz.cx = info->rtfParam;
1226     else if (RTFCheckMM (info, rtfPictAttr, rtfPicGoalHt))
1227       sz.cy = info->rtfParam;
1228     else
1229       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1230   }
1231   /* fetch picture data */
1232   bufsz = 1024;
1233   bufidx = 0;
1234   buffer = HeapAlloc(GetProcessHeap(), 0, bufsz);
1235   val = info->rtfMajor;
1236   for (flip = TRUE;; flip = !flip)
1237   {
1238     RTFGetToken (info);
1239     if (info->rtfClass == rtfEOF)
1240     {
1241       HeapFree(GetProcessHeap(), 0, buffer);
1242       return; /* Warn ?? */
1243     }
1244     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1245       break;
1246     if (info->rtfClass != rtfText) goto skip_group;
1247     if (flip)
1248     {
1249       if (bufidx >= bufsz &&
1250           !(buffer = HeapReAlloc(GetProcessHeap(), 0, buffer, bufsz += 1024)))
1251         goto skip_group;
1252       buffer[bufidx++] = RTFCharToHex(val) * 16 + RTFCharToHex(info->rtfMajor);
1253     }
1254     else
1255       val = info->rtfMajor;
1256   }
1257   if (flip) FIXME("wrong hex string\n");
1258
1259   switch (gfx)
1260   {
1261   case gfx_enhmetafile:
1262     if ((hemf = SetEnhMetaFileBits(bufidx, buffer)))
1263       ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1264     break;
1265   case gfx_metafile:
1266     if ((hemf = SetWinMetaFileBits(bufidx, buffer, NULL, &mfp)))
1267         ME_RTFInsertOleObject(info, hemf, NULL, &sz);
1268     break;
1269   case gfx_dib:
1270     {
1271       BITMAPINFO* bi = (BITMAPINFO*)buffer;
1272       HDC         hdc = GetDC(0);
1273       unsigned    nc = bi->bmiHeader.biClrUsed;
1274
1275       /* not quite right, especially for bitfields type of compression */
1276       if (!nc && bi->bmiHeader.biBitCount <= 8)
1277         nc = 1 << bi->bmiHeader.biBitCount;
1278       if ((hbmp = CreateDIBitmap(hdc, &bi->bmiHeader,
1279                                  CBM_INIT, (char*)(bi + 1) + nc * sizeof(RGBQUAD),
1280                                  bi, DIB_RGB_COLORS)))
1281           ME_RTFInsertOleObject(info, NULL, hbmp, &sz);
1282       ReleaseDC(0, hdc);
1283     }
1284     break;
1285   default:
1286     break;
1287   }
1288   HeapFree(GetProcessHeap(), 0, buffer);
1289   RTFRouteToken (info); /* feed "}" back to router */
1290   return;
1291 skip_group:
1292   HeapFree(GetProcessHeap(), 0, buffer);
1293   RTFSkipGroup(info);
1294   RTFRouteToken(info);  /* feed "}" back to router */
1295 }
1296
1297 /* for now, lookup the \result part and use it, whatever the object */
1298 static void ME_RTFReadObjectGroup(RTF_Info *info)
1299 {
1300   for (;;)
1301   {
1302     RTFGetToken (info);
1303     if (info->rtfClass == rtfEOF)
1304       return;
1305     if (RTFCheckCM(info, rtfGroup, rtfEndGroup))
1306       break;
1307     if (RTFCheckCM(info, rtfGroup, rtfBeginGroup))
1308     {
1309       RTFGetToken (info);
1310       if (info->rtfClass == rtfEOF)
1311         return;
1312       if (RTFCheckCMM(info, rtfControl, rtfDestination, rtfObjResult))
1313       {
1314         int     level = 1;
1315
1316         while (RTFGetToken (info) != rtfEOF)
1317         {
1318           if (info->rtfClass == rtfGroup)
1319           {
1320             if (info->rtfMajor == rtfBeginGroup) level++;
1321             else if (info->rtfMajor == rtfEndGroup && --level < 0) break;
1322           }
1323           RTFRouteToken(info);
1324         }
1325       }
1326       else RTFSkipGroup(info);
1327       continue;
1328     }
1329     if (!RTFCheckCM (info, rtfControl, rtfObjAttr))
1330     {
1331       FIXME("Non supported attribute: %d %d %d\n", info->rtfClass, info->rtfMajor, info->rtfMinor);
1332       return;
1333     }
1334   }
1335   RTFRouteToken(info);  /* feed "}" back to router */
1336 }
1337
1338 static void ME_RTFReadHook(RTF_Info *info)
1339 {
1340   switch(info->rtfClass)
1341   {
1342     case rtfGroup:
1343       switch(info->rtfMajor)
1344       {
1345         case rtfBeginGroup:
1346           if (info->stackTop < maxStack) {
1347             info->stack[info->stackTop].style = info->style;
1348             ME_AddRefStyle(info->style);
1349             info->stack[info->stackTop].codePage = info->codePage;
1350             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
1351           }
1352           info->stackTop++;
1353           info->styleChanged = FALSE;
1354           break;
1355         case rtfEndGroup:
1356         {
1357           RTFFlushOutputBuffer(info);
1358           info->stackTop--;
1359           if (info->stackTop <= 0)
1360             info->rtfClass = rtfEOF;
1361           if (info->stackTop < 0)
1362             return;
1363
1364           ME_ReleaseStyle(info->style);
1365           info->style = info->stack[info->stackTop].style;
1366           info->codePage = info->stack[info->stackTop].codePage;
1367           info->unicodeLength = info->stack[info->stackTop].unicodeLength;
1368           break;
1369         }
1370       }
1371       break;
1372   }
1373 }
1374
1375 void
1376 ME_StreamInFill(ME_InStream *stream)
1377 {
1378   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
1379                                                                 (BYTE *)stream->buffer,
1380                                                                 sizeof(stream->buffer),
1381                                                                 (LONG *)&stream->dwSize);
1382   stream->dwUsed = 0;
1383 }
1384
1385 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream, BOOL stripLastCR)
1386 {
1387   RTF_Info parser;
1388   ME_Style *style;
1389   int from, to, nUndoMode;
1390   int nEventMask = editor->nEventMask;
1391   ME_InStream inStream;
1392   BOOL invalidRTF = FALSE;
1393   ME_Cursor *selStart, *selEnd;
1394
1395   TRACE("stream==%p editor==%p format==0x%X\n", stream, editor, format);
1396   editor->nEventMask = 0;
1397
1398   ME_GetSelectionOfs(editor, &from, &to);
1399   if (format & SFF_SELECTION && editor->mode & TM_RICHTEXT)
1400   {
1401     ME_GetSelection(editor, &selStart, &selEnd);
1402     style = ME_GetSelectionInsertStyle(editor);
1403
1404     ME_InternalDeleteText(editor, selStart, to - from, FALSE);
1405
1406     /* Don't insert text at the end of the table row */
1407     if (!editor->bEmulateVersion10) { /* v4.1 */
1408       ME_DisplayItem *para = editor->pCursors->pPara;
1409       if (para->member.para.nFlags & MEPF_ROWEND)
1410       {
1411         para = para->member.para.next_para;
1412         editor->pCursors[0].pPara = para;
1413         editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1414         editor->pCursors[0].nOffset = 0;
1415       }
1416       if (para->member.para.nFlags & MEPF_ROWSTART)
1417       {
1418         para = para->member.para.next_para;
1419         editor->pCursors[0].pPara = para;
1420         editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
1421         editor->pCursors[0].nOffset = 0;
1422       }
1423       editor->pCursors[1] = editor->pCursors[0];
1424     } else { /* v1.0 - 3.0 */
1425       if (editor->pCursors[0].pRun->member.run.nFlags & MERF_ENDPARA &&
1426           ME_IsInTable(editor->pCursors[0].pRun))
1427         return 0;
1428     }
1429   } else {
1430     style = editor->pBuffer->pDefaultStyle;
1431     ME_AddRefStyle(style);
1432     ME_SetSelection(editor, 0, 0);
1433     ME_InternalDeleteText(editor, &editor->pCursors[1],
1434                           ME_GetTextLength(editor), FALSE);
1435     from = to = 0;
1436     ME_ClearTempStyle(editor);
1437     ME_SetDefaultParaFormat(editor->pCursors[0].pPara->member.para.pFmt);
1438   }
1439
1440
1441   /* Back up undo mode to a local variable */
1442   nUndoMode = editor->nUndoMode;
1443
1444   /* Only create an undo if SFF_SELECTION is set */
1445   if (!(format & SFF_SELECTION))
1446     editor->nUndoMode = umIgnore;
1447
1448   inStream.editstream = stream;
1449   inStream.editstream->dwError = 0;
1450   inStream.dwSize = 0;
1451   inStream.dwUsed = 0;
1452
1453   if (format & SF_RTF)
1454   {
1455     /* Check if it's really RTF, and if it is not, use plain text */
1456     ME_StreamInFill(&inStream);
1457     if (!inStream.editstream->dwError)
1458     {
1459       if ((!editor->bEmulateVersion10 && strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
1460         || (editor->bEmulateVersion10 && *inStream.buffer != '{'))
1461       {
1462         invalidRTF = TRUE;
1463         inStream.editstream->dwError = -16;
1464       }
1465     }
1466   }
1467
1468   if (!invalidRTF && !inStream.editstream->dwError)
1469   {
1470     if (format & SF_RTF) {
1471       /* setup the RTF parser */
1472       memset(&parser, 0, sizeof parser);
1473       RTFSetEditStream(&parser, &inStream);
1474       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
1475       parser.editor = editor;
1476       parser.style = style;
1477       WriterInit(&parser);
1478       RTFInit(&parser);
1479       RTFSetReadHook(&parser, ME_RTFReadHook);
1480       RTFSetDestinationCallback(&parser, rtfPict, ME_RTFReadPictGroup);
1481       RTFSetDestinationCallback(&parser, rtfObject, ME_RTFReadObjectGroup);
1482       if (!parser.editor->bEmulateVersion10) /* v4.1 */
1483       {
1484         RTFSetDestinationCallback(&parser, rtfNoNestTables, RTFSkipGroup);
1485         RTFSetDestinationCallback(&parser, rtfNestTableProps, RTFReadGroup);
1486       }
1487       BeginFile(&parser);
1488
1489       /* do the parsing */
1490       RTFRead(&parser);
1491       RTFFlushOutputBuffer(&parser);
1492       if (!editor->bEmulateVersion10) { /* v4.1 */
1493         if (parser.tableDef && parser.tableDef->tableRowStart &&
1494             (parser.nestingLevel > 0 || parser.canInheritInTbl))
1495         {
1496           /* Delete any incomplete table row at the end of the rich text. */
1497           int nOfs, nChars;
1498           ME_DisplayItem *pCell;
1499           ME_DisplayItem *para;
1500
1501           parser.rtfMinor = rtfRow;
1502           /* Complete the table row before deleting it.
1503            * By doing it this way we will have the current paragraph format set
1504            * properly to reflect that is not in the complete table, and undo items
1505            * will be added for this change to the current paragraph format. */
1506           if (parser.nestingLevel > 0)
1507           {
1508             while (parser.nestingLevel > 1)
1509               ME_RTFSpecialCharHook(&parser); /* Decrements nestingLevel */
1510             para = parser.tableDef->tableRowStart;
1511             ME_RTFSpecialCharHook(&parser);
1512           } else {
1513             para = parser.tableDef->tableRowStart;
1514             ME_RTFSpecialCharHook(&parser);
1515             assert(para->member.para.nFlags & MEPF_ROWEND);
1516             para = para->member.para.next_para;
1517           }
1518           pCell = para->member.para.pCell;
1519
1520           editor->pCursors[1].pPara = para;
1521           editor->pCursors[1].pRun = ME_FindItemFwd(para, diRun);
1522           editor->pCursors[1].nOffset = 0;
1523           nOfs = ME_GetCursorOfs(&editor->pCursors[1]);
1524           nChars = ME_GetCursorOfs(&editor->pCursors[0]) - nOfs;
1525           ME_InternalDeleteText(editor, &editor->pCursors[1], nChars, TRUE);
1526           if (parser.tableDef)
1527             parser.tableDef->tableRowStart = NULL;
1528         }
1529       }
1530       ME_CheckTablesForCorruption(editor);
1531       RTFDestroy(&parser);
1532       if (parser.lpRichEditOle)
1533         IRichEditOle_Release(parser.lpRichEditOle);
1534
1535       if (parser.stackTop > 0)
1536       {
1537         while (--parser.stackTop >= 0)
1538         {
1539           ME_ReleaseStyle(parser.style);
1540           parser.style = parser.stack[parser.stackTop].style;
1541         }
1542         if (!inStream.editstream->dwError)
1543           inStream.editstream->dwError = HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
1544       }
1545
1546       /* Remove last line break, as mandated by tests. This is not affected by
1547          CR/LF counters, since RTF streaming presents only \para tokens, which
1548          are converted according to the standard rules: \r for 2.0, \r\n for 1.0
1549        */
1550       if (stripLastCR) {
1551         int newto;
1552         ME_GetSelection(editor, &selStart, &selEnd);
1553         newto = ME_GetCursorOfs(selEnd);
1554         if (newto > to + (editor->bEmulateVersion10 ? 1 : 0)) {
1555           WCHAR lastchar[3] = {'\0', '\0'};
1556           int linebreakSize = editor->bEmulateVersion10 ? 2 : 1;
1557           ME_Cursor linebreakCursor = *selEnd;
1558
1559           ME_MoveCursorChars(editor, &linebreakCursor, -linebreakSize);
1560           ME_GetTextW(editor, lastchar, 2, &linebreakCursor, linebreakSize, 0);
1561           if (lastchar[0] == '\r' && (lastchar[1] == '\n' || lastchar[1] == '\0')) {
1562             ME_InternalDeleteText(editor, &linebreakCursor, linebreakSize, FALSE);
1563           }
1564         }
1565       }
1566
1567       style = parser.style;
1568     }
1569     else if (format & SF_TEXT)
1570       ME_StreamInText(editor, format, &inStream, style);
1571     else
1572       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
1573     /* put the cursor at the top */
1574     if (!(format & SFF_SELECTION))
1575       ME_SetSelection(editor, 0, 0);
1576   }
1577
1578   /* Restore saved undo mode */
1579   editor->nUndoMode = nUndoMode;
1580
1581   /* even if we didn't add an undo, we need to commit anything on the stack */
1582   ME_CommitUndo(editor);
1583
1584   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
1585   if (!(format & SFF_SELECTION))
1586     ME_EmptyUndoStack(editor);
1587
1588   ME_ReleaseStyle(style);
1589   editor->nEventMask = nEventMask;
1590   ME_UpdateRepaint(editor);
1591   if (!(format & SFF_SELECTION)) {
1592     ME_ClearTempStyle(editor);
1593   }
1594   ITextHost_TxShowCaret(editor->texthost, FALSE);
1595   ME_MoveCaret(editor);
1596   ITextHost_TxShowCaret(editor->texthost, TRUE);
1597   ME_SendSelChange(editor);
1598   ME_SendRequestResize(editor, FALSE);
1599
1600   return 0;
1601 }
1602
1603
1604 typedef struct tagME_RTFStringStreamStruct
1605 {
1606   char *string;
1607   int pos;
1608   int length;
1609 } ME_RTFStringStreamStruct;
1610
1611 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1612 {
1613   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
1614   int count;
1615
1616   count = min(cb, pStruct->length - pStruct->pos);
1617   memmove(lpBuff, pStruct->string + pStruct->pos, count);
1618   pStruct->pos += count;
1619   *pcb = count;
1620   return 0;
1621 }
1622
1623 static void
1624 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
1625 {
1626   EDITSTREAM es;
1627   ME_RTFStringStreamStruct data;
1628
1629   data.string = string;
1630   data.length = strlen(string);
1631   data.pos = 0;
1632   es.dwCookie = (DWORD_PTR)&data;
1633   es.pfnCallback = ME_ReadFromRTFString;
1634   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es, FALSE);
1635 }
1636
1637
1638 static int
1639 ME_FindText(ME_TextEditor *editor, DWORD flags, const CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
1640 {
1641   const int nLen = lstrlenW(text);
1642   const int nTextLen = ME_GetTextLength(editor);
1643   int nMin, nMax;
1644   ME_Cursor cursor;
1645   WCHAR wLastChar = ' ';
1646
1647   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
1648         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
1649
1650   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
1651     FIXME("Flags 0x%08x not implemented\n",
1652         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
1653
1654   nMin = chrg->cpMin;
1655   if (chrg->cpMax == -1)
1656     nMax = nTextLen;
1657   else
1658     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
1659
1660   /* In 1.0 emulation, if cpMax reaches end of text, add the FR_DOWN flag */
1661   if (editor->bEmulateVersion10 && nMax == nTextLen)
1662   {
1663     flags |= FR_DOWN;
1664   }
1665
1666   /* In 1.0 emulation, cpMin must always be no greater than cpMax */
1667   if (editor->bEmulateVersion10 && nMax < nMin)
1668   {
1669     if (chrgText)
1670     {
1671       chrgText->cpMin = -1;
1672       chrgText->cpMax = -1;
1673     }
1674     return -1;
1675   }
1676
1677   /* when searching up, if cpMin < cpMax, then instead of searching
1678    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
1679    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
1680    * case, it is always bigger than cpMin.
1681    */
1682   if (!editor->bEmulateVersion10 && !(flags & FR_DOWN))
1683   {
1684     int nSwap = nMax;
1685
1686     nMax = nMin > nTextLen ? nTextLen : nMin;
1687     if (nMin < nSwap || chrg->cpMax == -1)
1688       nMin = 0;
1689     else
1690       nMin = nSwap;
1691   }
1692
1693   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
1694   {
1695     if (chrgText)
1696       chrgText->cpMin = chrgText->cpMax = -1;
1697     return -1;
1698   }
1699
1700   if (flags & FR_DOWN) /* Forward search */
1701   {
1702     /* If possible, find the character before where the search starts */
1703     if ((flags & FR_WHOLEWORD) && nMin)
1704     {
1705       ME_CursorFromCharOfs(editor, nMin - 1, &cursor);
1706       wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1707       ME_MoveCursorChars(editor, &cursor, 1);
1708     } else {
1709       ME_CursorFromCharOfs(editor, nMin, &cursor);
1710     }
1711
1712     while (cursor.pRun && ME_GetCursorOfs(&cursor) + nLen <= nMax)
1713     {
1714       ME_DisplayItem *pCurItem = cursor.pRun;
1715       int nCurStart = cursor.nOffset;
1716       int nMatched = 0;
1717     
1718       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
1719       {
1720         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1721           break;
1722
1723         nMatched++;
1724         if (nMatched == nLen)
1725         {
1726           ME_DisplayItem *pNextItem = pCurItem;
1727           int nNextStart = nCurStart;
1728           WCHAR wNextChar;
1729
1730           /* Check to see if next character is a whitespace */
1731           if (flags & FR_WHOLEWORD)
1732           {
1733             if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1734             {
1735               pNextItem = ME_FindItemFwd(pCurItem, diRun);
1736               nNextStart = -nMatched;
1737             }
1738
1739             if (pNextItem)
1740               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
1741             else
1742               wNextChar = ' ';
1743
1744             if (isalnumW(wNextChar))
1745               break;
1746           }
1747
1748           cursor.nOffset += cursor.pPara->member.para.nCharOfs + cursor.pRun->member.run.nCharOfs;
1749           if (chrgText)
1750           {
1751             chrgText->cpMin = cursor.nOffset;
1752             chrgText->cpMax = cursor.nOffset + nLen;
1753           }
1754           TRACE("found at %d-%d\n", cursor.nOffset, cursor.nOffset + nLen);
1755           return cursor.nOffset;
1756         }
1757         if (nCurStart + nMatched == pCurItem->member.run.strText->nLen)
1758         {
1759           pCurItem = ME_FindItemFwd(pCurItem, diRun);
1760           nCurStart = -nMatched;
1761         }
1762       }
1763       if (pCurItem)
1764         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
1765       else
1766         wLastChar = ' ';
1767
1768       cursor.nOffset++;
1769       if (cursor.nOffset == cursor.pRun->member.run.strText->nLen)
1770       {
1771         ME_NextRun(&cursor.pPara, &cursor.pRun);
1772         cursor.nOffset = 0;
1773       }
1774     }
1775   }
1776   else /* Backward search */
1777   {
1778     /* If possible, find the character after where the search ends */
1779     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
1780     {
1781       ME_CursorFromCharOfs(editor, nMax + 1, &cursor);
1782       wLastChar = cursor.pRun->member.run.strText->szData[cursor.nOffset];
1783       ME_MoveCursorChars(editor, &cursor, -1);
1784     } else {
1785       ME_CursorFromCharOfs(editor, nMax, &cursor);
1786     }
1787
1788     while (cursor.pRun && ME_GetCursorOfs(&cursor) - nLen >= nMin)
1789     {
1790       ME_DisplayItem *pCurItem = cursor.pRun;
1791       ME_DisplayItem *pCurPara = cursor.pPara;
1792       int nCurEnd = cursor.nOffset;
1793       int nMatched = 0;
1794
1795       if (nCurEnd == 0)
1796       {
1797         ME_PrevRun(&pCurPara, &pCurItem);
1798         nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1799       }
1800
1801       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
1802       {
1803         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
1804           break;
1805
1806         nMatched++;
1807         if (nMatched == nLen)
1808         {
1809           ME_DisplayItem *pPrevItem = pCurItem;
1810           int nPrevEnd = nCurEnd;
1811           WCHAR wPrevChar;
1812           int nStart;
1813
1814           /* Check to see if previous character is a whitespace */
1815           if (flags & FR_WHOLEWORD)
1816           {
1817             if (nPrevEnd - nMatched == 0)
1818             {
1819               pPrevItem = ME_FindItemBack(pCurItem, diRun);
1820               if (pPrevItem)
1821                 nPrevEnd = pPrevItem->member.run.strText->nLen + nMatched;
1822             }
1823
1824             if (pPrevItem)
1825               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
1826             else
1827               wPrevChar = ' ';
1828
1829             if (isalnumW(wPrevChar))
1830               break;
1831           }
1832
1833           nStart = pCurPara->member.para.nCharOfs
1834                    + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
1835           if (chrgText)
1836           {
1837             chrgText->cpMin = nStart;
1838             chrgText->cpMax = nStart + nLen;
1839           }
1840           TRACE("found at %d-%d\n", nStart, nStart + nLen);
1841           return nStart;
1842         }
1843         if (nCurEnd - nMatched == 0)
1844         {
1845           ME_PrevRun(&pCurPara, &pCurItem);
1846           /* Don't care about pCurItem becoming NULL here; it's already taken
1847            * care of in the exterior loop condition */
1848           nCurEnd = pCurItem->member.run.strText->nLen + nMatched;
1849         }
1850       }
1851       if (pCurItem)
1852         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1853       else
1854         wLastChar = ' ';
1855
1856       cursor.nOffset--;
1857       if (cursor.nOffset < 0)
1858       {
1859         ME_PrevRun(&cursor.pPara, &cursor.pRun);
1860         cursor.nOffset = cursor.pRun->member.run.strText->nLen;
1861       }
1862     }
1863   }
1864   TRACE("not found\n");
1865   if (chrgText)
1866     chrgText->cpMin = chrgText->cpMax = -1;
1867   return -1;
1868 }
1869
1870 static int ME_GetTextEx(ME_TextEditor *editor, GETTEXTEX *ex, LPARAM pText)
1871 {
1872     int nChars;
1873     ME_Cursor start;
1874
1875     if (!ex->cb || !pText) return 0;
1876
1877     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1878       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1879
1880     if (ex->flags & GT_SELECTION)
1881     {
1882       int from, to;
1883       int nStartCur = ME_GetSelectionOfs(editor, &from, &to);
1884       start = editor->pCursors[nStartCur];
1885       nChars = to - from;
1886     }
1887     else
1888     {
1889       ME_SetCursorToStart(editor, &start);
1890       nChars = INT_MAX;
1891     }
1892     if (ex->codepage == 1200)
1893     {
1894       return ME_GetTextW(editor, (LPWSTR)pText, ex->cb / sizeof(WCHAR) - 1,
1895                          &start, nChars, ex->flags & GT_USECRLF);
1896     }
1897     else
1898     {
1899       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1900         we can just take a bigger buffer? :)
1901         The above assumption still holds with CR/LF counters, since CR->CRLF expansion
1902         occurs only in richedit 2.0 mode, in which line breaks have only one CR
1903        */
1904       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1905       DWORD buflen;
1906       LPWSTR buffer;
1907       LRESULT rc;
1908
1909       buflen = min(crlfmul * nChars, ex->cb - 1);
1910       buffer = heap_alloc((buflen + 1) * sizeof(WCHAR));
1911
1912       nChars = ME_GetTextW(editor, buffer, buflen, &start, nChars, ex->flags & GT_USECRLF);
1913       rc = WideCharToMultiByte(ex->codepage, 0, buffer, nChars + 1,
1914                                (LPSTR)pText, ex->cb, ex->lpDefaultChar, ex->lpUsedDefChar);
1915       if (rc) rc--; /* do not count 0 terminator */
1916
1917       heap_free(buffer);
1918       return rc;
1919     }
1920 }
1921
1922 static int ME_GetTextRange(ME_TextEditor *editor, WCHAR *strText,
1923                            const ME_Cursor *start, int nLen, BOOL unicode)
1924 {
1925     if (!strText) return 0;
1926     if (unicode) {
1927       return ME_GetTextW(editor, strText, INT_MAX, start, nLen, 0);
1928     } else {
1929       int nChars;
1930       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1931       if (!p) return 0;
1932       nChars = ME_GetTextW(editor, p, nLen, start, nLen, 0);
1933       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)strText,
1934                           nLen+1, NULL, NULL);
1935       FREE_OBJ(p);
1936       return nChars;
1937     }
1938 }
1939
1940 typedef struct tagME_GlobalDestStruct
1941 {
1942   HGLOBAL hData;
1943   int nLength;
1944 } ME_GlobalDestStruct;
1945
1946 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1947 {
1948   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1949   int i;
1950   WORD *pSrc, *pDest;
1951
1952   cb = cb >> 1;
1953   pDest = (WORD *)lpBuff;
1954   pSrc = GlobalLock(pData->hData);
1955   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1956     pDest[i] = pSrc[pData->nLength+i];
1957   }
1958   pData->nLength += i;
1959   *pcb = 2*i;
1960   GlobalUnlock(pData->hData);
1961   return 0;
1962 }
1963
1964 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1965 {
1966   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1967   int i;
1968   BYTE *pSrc, *pDest;
1969
1970   pDest = lpBuff;
1971   pSrc = GlobalLock(pData->hData);
1972   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1973     pDest[i] = pSrc[pData->nLength+i];
1974   }
1975   pData->nLength += i;
1976   *pcb = i;
1977   GlobalUnlock(pData->hData);
1978   return 0;
1979 }
1980
1981 static BOOL ME_Paste(ME_TextEditor *editor)
1982 {
1983   DWORD dwFormat = 0;
1984   EDITSTREAM es;
1985   ME_GlobalDestStruct gds;
1986   UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1987   UINT cf = 0;
1988
1989   if (IsClipboardFormatAvailable(nRTFFormat))
1990     cf = nRTFFormat, dwFormat = SF_RTF;
1991   else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1992     cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1993   else
1994     return FALSE;
1995
1996   if (!OpenClipboard(editor->hWnd))
1997     return FALSE;
1998   gds.hData = GetClipboardData(cf);
1999   gds.nLength = 0;
2000   es.dwCookie = (DWORD_PTR)&gds;
2001   es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
2002   ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es, FALSE);
2003
2004   CloseClipboard();
2005   return TRUE;
2006 }
2007
2008 static BOOL ME_Copy(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
2009 {
2010   LPDATAOBJECT dataObj = NULL;
2011   HRESULT hr = S_OK;
2012
2013   if (editor->cPasswordMask)
2014     return FALSE; /* Copying or Cutting masked text isn't allowed */
2015
2016   if(editor->lpOleCallback)
2017   {
2018     CHARRANGE range;
2019     range.cpMin = ME_GetCursorOfs(start);
2020     range.cpMax = range.cpMin + nChars;
2021     hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
2022   }
2023   if(FAILED(hr) || !dataObj)
2024     hr = ME_GetDataObject(editor, start, nChars, &dataObj);
2025   if(SUCCEEDED(hr)) {
2026     hr = OleSetClipboard(dataObj);
2027     IDataObject_Release(dataObj);
2028   }
2029   return SUCCEEDED(hr) != 0;
2030 }
2031
2032 /* helper to send a msg filter notification */
2033 static BOOL
2034 ME_FilterEvent(ME_TextEditor *editor, UINT msg, WPARAM* wParam, LPARAM* lParam)
2035 {
2036     MSGFILTER msgf;
2037
2038     if (!editor->hWnd) return FALSE;
2039     msgf.nmhdr.hwndFrom = editor->hWnd;
2040     msgf.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2041     msgf.nmhdr.code = EN_MSGFILTER;
2042     msgf.msg = msg;
2043     msgf.wParam = *wParam;
2044     msgf.lParam = *lParam;
2045     if (SendMessageW(GetParent(editor->hWnd), WM_NOTIFY, msgf.nmhdr.idFrom, (LPARAM)&msgf))
2046         return FALSE;
2047     *wParam = msgf.wParam;
2048     *lParam = msgf.lParam;
2049     msgf.wParam = *wParam;
2050
2051     return TRUE;
2052 }
2053
2054 static void ME_UpdateSelectionLinkAttribute(ME_TextEditor *editor)
2055 {
2056   ME_DisplayItem *startPara, *endPara;
2057   ME_DisplayItem *prev_para;
2058   ME_Cursor *from, *to;
2059   ME_Cursor start;
2060   int nChars;
2061
2062   if (!editor->AutoURLDetect_bEnable) return;
2063
2064   ME_GetSelection(editor, &from, &to);
2065
2066   /* Find paragraph previous to the one that contains start cursor */
2067   startPara = from->pPara;
2068   prev_para = startPara->member.para.prev_para;
2069   if (prev_para->type == diParagraph) startPara = prev_para;
2070
2071   /* Find paragraph that contains end cursor */
2072   endPara = to->pPara->member.para.next_para;
2073
2074   start.pPara = startPara;
2075   start.pRun = ME_FindItemFwd(startPara, diRun);
2076   start.nOffset = 0;
2077   nChars = endPara->member.para.nCharOfs - startPara->member.para.nCharOfs;
2078
2079   ME_UpdateLinkAttribute(editor, &start, nChars);
2080 }
2081
2082 static BOOL
2083 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
2084 {
2085   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2086   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
2087
2088   if (editor->bMouseCaptured)
2089       return FALSE;
2090   if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey != VK_MENU)
2091       editor->nSelectionType = stPosition;
2092
2093   switch (nKey)
2094   {
2095     case VK_LEFT:
2096     case VK_RIGHT:
2097     case VK_HOME:
2098     case VK_END:
2099         editor->nUDArrowX = -1;
2100         /* fall through */
2101     case VK_UP:
2102     case VK_DOWN:
2103     case VK_PRIOR:
2104     case VK_NEXT:
2105       ME_CommitUndo(editor); /* End coalesced undos for typed characters */
2106       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
2107       return TRUE;
2108     case VK_BACK:
2109     case VK_DELETE:
2110       editor->nUDArrowX = -1;
2111       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
2112       if (editor->styleFlags & ES_READONLY)
2113         return FALSE;
2114       if (ME_IsSelection(editor))
2115       {
2116         ME_DeleteSelection(editor);
2117         ME_CommitUndo(editor);
2118       }
2119       else if (nKey == VK_DELETE)
2120       {
2121         /* Delete stops group typing.
2122          * (See MSDN remarks on EM_STOPGROUPTYPING message) */
2123         ME_DeleteTextAtCursor(editor, 1, 1);
2124         ME_CommitUndo(editor);
2125       }
2126       else if (ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
2127       {
2128         BOOL bDeletionSucceeded;
2129         /* Backspace can be grouped for a single undo */
2130         ME_ContinueCoalescingTransaction(editor);
2131         bDeletionSucceeded = ME_DeleteTextAtCursor(editor, 1, 1);
2132         if (!bDeletionSucceeded && !editor->bEmulateVersion10) { /* v4.1 */
2133           /* Deletion was prevented so the cursor is moved back to where it was.
2134            * (e.g. this happens when trying to delete cell boundaries)
2135            */
2136           ME_ArrowKey(editor, VK_RIGHT, FALSE, FALSE);
2137         }
2138         ME_CommitCoalescingUndo(editor);
2139       }
2140       else
2141         return TRUE;
2142       ME_MoveCursorFromTableRowStartParagraph(editor);
2143       ME_UpdateSelectionLinkAttribute(editor);
2144       ME_UpdateRepaint(editor);
2145       ME_SendRequestResize(editor, FALSE);
2146       return TRUE;
2147     case VK_RETURN:
2148       if (editor->styleFlags & ES_MULTILINE)
2149       {
2150         ME_Cursor cursor = editor->pCursors[0];
2151         ME_DisplayItem *para = cursor.pPara;
2152         int from, to;
2153         const WCHAR endl = '\r';
2154         ME_Style *style;
2155
2156         if (editor->styleFlags & ES_READONLY) {
2157           MessageBeep(MB_ICONERROR);
2158           return TRUE;
2159         }
2160
2161         ME_GetSelectionOfs(editor, &from, &to);
2162         if (editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2163         {
2164           if (!editor->bEmulateVersion10) { /* v4.1 */
2165             if (para->member.para.nFlags & MEPF_ROWEND) {
2166               /* Add a new table row after this row. */
2167               para = ME_AppendTableRow(editor, para);
2168               para = para->member.para.next_para;
2169               editor->pCursors[0].pPara = para;
2170               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2171               editor->pCursors[0].nOffset = 0;
2172               editor->pCursors[1] = editor->pCursors[0];
2173               ME_CommitUndo(editor);
2174               ME_CheckTablesForCorruption(editor);
2175               ME_UpdateRepaint(editor);
2176               return TRUE;
2177             }
2178             else if (para == editor->pCursors[1].pPara &&
2179                      cursor.nOffset + cursor.pRun->member.run.nCharOfs == 0 &&
2180                      para->member.para.prev_para->member.para.nFlags & MEPF_ROWSTART &&
2181                      !para->member.para.prev_para->member.para.nCharOfs)
2182             {
2183               /* Insert a newline before the table. */
2184               para = para->member.para.prev_para;
2185               para->member.para.nFlags &= ~MEPF_ROWSTART;
2186               editor->pCursors[0].pPara = para;
2187               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2188               editor->pCursors[1] = editor->pCursors[0];
2189               ME_InsertTextFromCursor(editor, 0, &endl, 1,
2190                                       editor->pCursors[0].pRun->member.run.style);
2191               para = editor->pBuffer->pFirst->member.para.next_para;
2192               ME_SetDefaultParaFormat(para->member.para.pFmt);
2193               para->member.para.nFlags = MEPF_REWRAP;
2194               editor->pCursors[0].pPara = para;
2195               editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2196               editor->pCursors[1] = editor->pCursors[0];
2197               para->member.para.next_para->member.para.nFlags |= MEPF_ROWSTART;
2198               ME_CommitCoalescingUndo(editor);
2199               ME_CheckTablesForCorruption(editor);
2200               ME_UpdateRepaint(editor);
2201               return TRUE;
2202             }
2203           } else { /* v1.0 - 3.0 */
2204             ME_DisplayItem *para = cursor.pPara;
2205             if (ME_IsInTable(para))
2206             {
2207               if (cursor.pRun->member.run.nFlags & MERF_ENDPARA)
2208               {
2209                 if (from == to) {
2210                   ME_ContinueCoalescingTransaction(editor);
2211                   para = ME_AppendTableRow(editor, para);
2212                   editor->pCursors[0].pPara = para;
2213                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2214                   editor->pCursors[0].nOffset = 0;
2215                   editor->pCursors[1] = editor->pCursors[0];
2216                   ME_CommitCoalescingUndo(editor);
2217                   ME_UpdateRepaint(editor);
2218                   return TRUE;
2219                 }
2220               } else {
2221                 ME_ContinueCoalescingTransaction(editor);
2222                 if (cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2223                     !ME_IsInTable(para->member.para.prev_para))
2224                 {
2225                   /* Insert newline before table */
2226                   cursor.pRun = ME_FindItemBack(para, diRun);
2227                   if (cursor.pRun) {
2228                     editor->pCursors[0].pRun = cursor.pRun;
2229                     editor->pCursors[0].pPara = para->member.para.prev_para;
2230                   }
2231                   editor->pCursors[0].nOffset = 0;
2232                   editor->pCursors[1] = editor->pCursors[0];
2233                   ME_InsertTextFromCursor(editor, 0, &endl, 1,
2234                                           editor->pCursors[0].pRun->member.run.style);
2235                 } else {
2236                   editor->pCursors[1] = editor->pCursors[0];
2237                   para = ME_AppendTableRow(editor, para);
2238                   editor->pCursors[0].pPara = para;
2239                   editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2240                   editor->pCursors[0].nOffset = 0;
2241                   editor->pCursors[1] = editor->pCursors[0];
2242                 }
2243                 ME_CommitCoalescingUndo(editor);
2244                 ME_UpdateRepaint(editor);
2245                 return TRUE;
2246               }
2247             }
2248           }
2249
2250           style = ME_GetInsertStyle(editor, 0);
2251           ME_SaveTempStyle(editor);
2252           ME_ContinueCoalescingTransaction(editor);
2253           if (shift_is_down)
2254             ME_InsertEndRowFromCursor(editor, 0);
2255           else
2256             ME_InsertTextFromCursor(editor, 0, &endl, 1, style);
2257           ME_ReleaseStyle(style);
2258           ME_CommitCoalescingUndo(editor);
2259           SetCursor(NULL);
2260
2261           ME_UpdateSelectionLinkAttribute(editor);
2262           ME_UpdateRepaint(editor);
2263         }
2264         return TRUE;
2265       }
2266       break;
2267     case 'A':
2268       if (ctrl_is_down)
2269       {
2270         ME_SetSelection(editor, 0, -1);
2271         return TRUE;
2272       }
2273       break;
2274     case 'V':
2275       if (ctrl_is_down)
2276         return ME_Paste(editor);
2277       break;
2278     case 'C':
2279     case 'X':
2280       if (ctrl_is_down)
2281       {
2282         BOOL result;
2283         int nOfs, nChars;
2284         int nStartCur = ME_GetSelectionOfs(editor, &nOfs, &nChars);
2285         ME_Cursor *selStart = &editor->pCursors[nStartCur];
2286
2287         nChars -= nOfs;
2288         result = ME_Copy(editor, selStart, nChars);
2289         if (result && nKey == 'X')
2290         {
2291           ME_InternalDeleteText(editor, selStart, nChars, FALSE);
2292           ME_CommitUndo(editor);
2293           ME_UpdateRepaint(editor);
2294         }
2295         return result;
2296       }
2297       break;
2298     case 'Z':
2299       if (ctrl_is_down)
2300       {
2301         ME_Undo(editor);
2302         return TRUE;
2303       }
2304       break;
2305     case 'Y':
2306       if (ctrl_is_down)
2307       {
2308         ME_Redo(editor);
2309         return TRUE;
2310       }
2311       break;
2312
2313     default:
2314       if (nKey != VK_SHIFT && nKey != VK_CONTROL && nKey && nKey != VK_MENU)
2315           editor->nUDArrowX = -1;
2316       if (ctrl_is_down)
2317       {
2318         if (nKey == 'W')
2319         {
2320           CHARFORMAT2W chf;
2321           char buf[2048];
2322           chf.cbSize = sizeof(chf);
2323           
2324           ME_GetSelectionCharFormat(editor, &chf);
2325           ME_DumpStyleToBuf(&chf, buf);
2326           MessageBoxA(NULL, buf, "Style dump", MB_OK);
2327         }
2328         if (nKey == 'Q')
2329         {
2330           ME_CheckCharOffsets(editor);
2331         }
2332       }
2333   }
2334   return FALSE;
2335 }
2336
2337 static LRESULT ME_Char(ME_TextEditor *editor, WPARAM charCode,
2338                        LPARAM flags, BOOL unicode)
2339 {
2340   WCHAR wstr;
2341
2342   if (editor->bMouseCaptured)
2343     return 0;
2344
2345   if (unicode)
2346       wstr = (WCHAR)charCode;
2347   else
2348   {
2349       CHAR charA = charCode;
2350       MultiByteToWideChar(CP_ACP, 0, &charA, 1, &wstr, 1);
2351   }
2352
2353   if (editor->styleFlags & ES_READONLY) {
2354     MessageBeep(MB_ICONERROR);
2355     return 0; /* FIXME really 0 ? */
2356   }
2357
2358   if ((unsigned)wstr >= ' ' || wstr == '\t')
2359   {
2360     ME_Cursor cursor = editor->pCursors[0];
2361     ME_DisplayItem *para = cursor.pPara;
2362     int from, to;
2363     BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
2364     ME_GetSelectionOfs(editor, &from, &to);
2365     if (wstr == '\t' &&
2366         /* v4.1 allows tabs to be inserted with ctrl key down */
2367         !(ctrl_is_down && !editor->bEmulateVersion10))
2368     {
2369       ME_DisplayItem *para;
2370       BOOL bSelectedRow = FALSE;
2371
2372       para = cursor.pPara;
2373       if (ME_IsSelection(editor) &&
2374           cursor.pRun->member.run.nCharOfs + cursor.nOffset == 0 &&
2375           to == ME_GetCursorOfs(&editor->pCursors[0]) &&
2376           para->member.para.prev_para->type == diParagraph)
2377       {
2378         para = para->member.para.prev_para;
2379         bSelectedRow = TRUE;
2380       }
2381       if (ME_IsInTable(para))
2382       {
2383         ME_TabPressedInTable(editor, bSelectedRow);
2384         ME_CommitUndo(editor);
2385         return 0;
2386       }
2387     } else if (!editor->bEmulateVersion10) { /* v4.1 */
2388       if (para->member.para.nFlags & MEPF_ROWEND) {
2389         if (from == to) {
2390           para = para->member.para.next_para;
2391           if (para->member.para.nFlags & MEPF_ROWSTART)
2392             para = para->member.para.next_para;
2393           editor->pCursors[0].pPara = para;
2394           editor->pCursors[0].pRun = ME_FindItemFwd(para, diRun);
2395           editor->pCursors[0].nOffset = 0;
2396           editor->pCursors[1] = editor->pCursors[0];
2397         }
2398       }
2399     } else { /* v1.0 - 3.0 */
2400       if (ME_IsInTable(cursor.pRun) &&
2401           cursor.pRun->member.run.nFlags & MERF_ENDPARA &&
2402           from == to)
2403       {
2404         /* Text should not be inserted at the end of the table. */
2405         MessageBeep(-1);
2406         return 0;
2407       }
2408     }
2409     /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2410     /* WM_CHAR is restricted to nTextLimit */
2411     if(editor->nTextLimit > ME_GetTextLength(editor) - (to-from))
2412     {
2413       ME_Style *style = ME_GetInsertStyle(editor, 0);
2414       ME_SaveTempStyle(editor);
2415       ME_ContinueCoalescingTransaction(editor);
2416       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2417       ME_ReleaseStyle(style);
2418       ME_CommitCoalescingUndo(editor);
2419       ITextHost_TxSetCursor(editor->texthost, NULL, FALSE);
2420     }
2421
2422     ME_UpdateSelectionLinkAttribute(editor);
2423     ME_UpdateRepaint(editor);
2424   }
2425   return 0;
2426 }
2427
2428 /* Process the message and calculate the new click count.
2429  *
2430  * returns: The click count if it is mouse down event, else returns 0. */
2431 static int ME_CalculateClickCount(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2432                                   LPARAM lParam)
2433 {
2434     static int clickNum = 0;
2435     if (msg < WM_MOUSEFIRST || msg > WM_MOUSELAST)
2436         return 0;
2437
2438     if ((msg == WM_LBUTTONDBLCLK) ||
2439         (msg == WM_RBUTTONDBLCLK) ||
2440         (msg == WM_MBUTTONDBLCLK) ||
2441         (msg == WM_XBUTTONDBLCLK))
2442     {
2443         msg -= (WM_LBUTTONDBLCLK - WM_LBUTTONDOWN);
2444     }
2445
2446     if ((msg == WM_LBUTTONDOWN) ||
2447         (msg == WM_RBUTTONDOWN) ||
2448         (msg == WM_MBUTTONDOWN) ||
2449         (msg == WM_XBUTTONDOWN))
2450     {
2451         static MSG prevClickMsg;
2452         MSG clickMsg;
2453         /* Compare the editor instead of the hwnd so that the this
2454          * can still be done for windowless richedit controls. */
2455         clickMsg.hwnd = (HWND)editor;
2456         clickMsg.message = msg;
2457         clickMsg.wParam = wParam;
2458         clickMsg.lParam = lParam;
2459         clickMsg.time = GetMessageTime();
2460         clickMsg.pt.x = (short)LOWORD(lParam);
2461         clickMsg.pt.y = (short)HIWORD(lParam);
2462         if ((clickNum != 0) &&
2463             (clickMsg.message == prevClickMsg.message) &&
2464             (clickMsg.hwnd == prevClickMsg.hwnd) &&
2465             (clickMsg.wParam == prevClickMsg.wParam) &&
2466             (clickMsg.time - prevClickMsg.time < GetDoubleClickTime()) &&
2467             (abs(clickMsg.pt.x - prevClickMsg.pt.x) < GetSystemMetrics(SM_CXDOUBLECLK)/2) &&
2468             (abs(clickMsg.pt.y - prevClickMsg.pt.y) < GetSystemMetrics(SM_CYDOUBLECLK)/2))
2469         {
2470             clickNum++;
2471         } else {
2472             clickNum = 1;
2473         }
2474         prevClickMsg = clickMsg;
2475     } else {
2476         return 0;
2477     }
2478     return clickNum;
2479 }
2480
2481 static BOOL ME_SetCursor(ME_TextEditor *editor)
2482 {
2483   ME_Cursor cursor;
2484   POINT pt;
2485   BOOL isExact;
2486   SCROLLBARINFO sbi;
2487   DWORD messagePos = GetMessagePos();
2488   pt.x = (short)LOWORD(messagePos);
2489   pt.y = (short)HIWORD(messagePos);
2490
2491   if (editor->hWnd)
2492   {
2493     sbi.cbSize = sizeof(sbi);
2494     GetScrollBarInfo(editor->hWnd, OBJID_HSCROLL, &sbi);
2495     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2496         PtInRect(&sbi.rcScrollBar, pt))
2497     {
2498         ITextHost_TxSetCursor(editor->texthost,
2499                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2500         return TRUE;
2501     }
2502     sbi.cbSize = sizeof(sbi);
2503     GetScrollBarInfo(editor->hWnd, OBJID_VSCROLL, &sbi);
2504     if (!(sbi.rgstate[0] & (STATE_SYSTEM_INVISIBLE|STATE_SYSTEM_OFFSCREEN)) &&
2505         PtInRect(&sbi.rcScrollBar, pt))
2506     {
2507         ITextHost_TxSetCursor(editor->texthost,
2508                               LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2509         return TRUE;
2510     }
2511   }
2512   ITextHost_TxScreenToClient(editor->texthost, &pt);
2513
2514   if (editor->nSelectionType == stLine && editor->bMouseCaptured) {
2515       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2516       return TRUE;
2517   }
2518   if (!editor->bEmulateVersion10 /* v4.1 */ &&
2519       pt.y < editor->rcFormat.top &&
2520       pt.x < editor->rcFormat.left)
2521   {
2522       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2523       return TRUE;
2524   }
2525   if (pt.y < editor->rcFormat.top || pt.y > editor->rcFormat.bottom)
2526   {
2527       if (editor->bEmulateVersion10) /* v1.0 - 3.0 */
2528           ITextHost_TxSetCursor(editor->texthost,
2529                                 LoadCursorW(NULL, (WCHAR*)IDC_ARROW), FALSE);
2530       else /* v4.1 */
2531           ITextHost_TxSetCursor(editor->texthost,
2532                                 LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2533       return TRUE;
2534   }
2535   if (pt.x < editor->rcFormat.left)
2536   {
2537       ITextHost_TxSetCursor(editor->texthost, hLeft, FALSE);
2538       return TRUE;
2539   }
2540   ME_CharFromPos(editor, pt.x, pt.y, &cursor, &isExact);
2541   if (isExact)
2542   {
2543       ME_Run *run;
2544
2545       run = &cursor.pRun->member.run;
2546       if (run->style->fmt.dwMask & CFM_LINK &&
2547           run->style->fmt.dwEffects & CFE_LINK)
2548       {
2549           ITextHost_TxSetCursor(editor->texthost,
2550                                 LoadCursorW(NULL, (WCHAR*)IDC_HAND),
2551                                 FALSE);
2552           return TRUE;
2553       }
2554
2555       if (ME_IsSelection(editor))
2556       {
2557           int selStart, selEnd;
2558           int offset = ME_GetCursorOfs(&cursor);
2559
2560           ME_GetSelectionOfs(editor, &selStart, &selEnd);
2561           if (selStart <= offset && selEnd >= offset) {
2562               ITextHost_TxSetCursor(editor->texthost,
2563                                     LoadCursorW(NULL, (WCHAR*)IDC_ARROW),
2564                                     FALSE);
2565               return TRUE;
2566           }
2567       }
2568   }
2569   ITextHost_TxSetCursor(editor->texthost,
2570                         LoadCursorW(NULL, (WCHAR*)IDC_IBEAM), TRUE);
2571   return TRUE;
2572 }
2573
2574 static void ME_SetDefaultFormatRect(ME_TextEditor *editor)
2575 {
2576   ITextHost_TxGetClientRect(editor->texthost, &editor->rcFormat);
2577   editor->rcFormat.top += editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
2578   editor->rcFormat.left += 1 + editor->selofs;
2579   editor->rcFormat.right -= 1;
2580 }
2581
2582 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
2583 {
2584   CHARRANGE selrange;
2585   HMENU menu;
2586   int seltype = 0;
2587   if(!editor->lpOleCallback || !editor->hWnd)
2588     return FALSE;
2589   ME_GetSelectionOfs(editor, &selrange.cpMin, &selrange.cpMax);
2590   if(selrange.cpMin == selrange.cpMax)
2591     seltype |= SEL_EMPTY;
2592   else
2593   {
2594     /* FIXME: Handle objects */
2595     seltype |= SEL_TEXT;
2596     if(selrange.cpMax-selrange.cpMin > 1)
2597       seltype |= SEL_MULTICHAR;
2598   }
2599   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
2600   {
2601     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
2602     DestroyMenu(menu);
2603   }
2604   return TRUE;
2605 }
2606
2607 ME_TextEditor *ME_MakeEditor(ITextHost *texthost, BOOL bEmulateVersion10)
2608 {
2609   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
2610   int i;
2611   DWORD props;
2612   LONG selbarwidth;
2613
2614   ed->hWnd = NULL;
2615   ed->texthost = texthost;
2616   ed->bEmulateVersion10 = bEmulateVersion10;
2617   ITextHost_TxGetPropertyBits(texthost,
2618                               (TXTBIT_RICHTEXT|TXTBIT_MULTILINE|
2619                                TXTBIT_READONLY|TXTBIT_USEPASSWORD|
2620                                TXTBIT_HIDESELECTION|TXTBIT_SAVESELECTION|
2621                                TXTBIT_AUTOWORDSEL|TXTBIT_VERTICAL|
2622                                TXTBIT_WORDWRAP|TXTBIT_DISABLEDRAG),
2623                               &props);
2624   ITextHost_TxGetScrollBars(texthost, &ed->styleFlags);
2625   ed->styleFlags &= (WS_VSCROLL|WS_HSCROLL|ES_AUTOVSCROLL|
2626                      ES_AUTOHSCROLL|ES_DISABLENOSCROLL);
2627   ed->pBuffer = ME_MakeText();
2628   ed->nZoomNumerator = ed->nZoomDenominator = 0;
2629   ed->nAvailWidth = 0; /* wrap to client area */
2630   ME_MakeFirstParagraph(ed);
2631   /* The four cursors are for:
2632    * 0 - The position where the caret is shown
2633    * 1 - The anchored end of the selection (for normal selection)
2634    * 2 & 3 - The anchored start and end respectively for word, line,
2635    * or paragraph selection.
2636    */
2637   ed->nCursors = 4;
2638   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
2639   ME_SetCursorToStart(ed, &ed->pCursors[0]);
2640   ed->pCursors[1] = ed->pCursors[0];
2641   ed->pCursors[2] = ed->pCursors[0];
2642   ed->pCursors[3] = ed->pCursors[1];
2643   ed->nLastTotalLength = ed->nTotalLength = 0;
2644   ed->nLastTotalWidth = ed->nTotalWidth = 0;
2645   ed->nUDArrowX = -1;
2646   ed->nSequence = 0;
2647   ed->rgbBackColor = -1;
2648   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
2649   ed->bCaretAtEnd = FALSE;
2650   ed->nEventMask = 0;
2651   ed->nModifyStep = 0;
2652   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
2653   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
2654   ed->nUndoStackSize = 0;
2655   ed->nUndoLimit = STACK_SIZE_DEFAULT;
2656   ed->nUndoMode = umAddToUndo;
2657   ed->nParagraphs = 1;
2658   ed->nLastSelStart = ed->nLastSelEnd = 0;
2659   ed->pLastSelStartPara = ed->pLastSelEndPara = ed->pCursors[0].pPara;
2660   ed->bHideSelection = FALSE;
2661   ed->pfnWordBreak = NULL;
2662   ed->lpOleCallback = NULL;
2663   ed->mode = TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
2664   ed->mode |= (props & TXTBIT_RICHTEXT) ? TM_RICHTEXT : TM_PLAINTEXT;
2665   ed->AutoURLDetect_bEnable = FALSE;
2666   ed->bHaveFocus = FALSE;
2667   ed->bMouseCaptured = FALSE;
2668   for (i=0; i<HFONT_CACHE_SIZE; i++)
2669   {
2670     ed->pFontCache[i].nRefs = 0;
2671     ed->pFontCache[i].nAge = 0;
2672     ed->pFontCache[i].hFont = NULL;
2673   }
2674
2675   ME_CheckCharOffsets(ed);
2676   ed->bDefaultFormatRect = TRUE;
2677   ITextHost_TxGetSelectionBarWidth(ed->texthost, &selbarwidth);
2678   if (selbarwidth) {
2679     /* FIXME: Convert selbarwidth from HIMETRIC to pixels */
2680     ed->selofs = SELECTIONBAR_WIDTH;
2681     ed->styleFlags |= ES_SELECTIONBAR;
2682   } else {
2683     ed->selofs = 0;
2684   }
2685   ed->nSelectionType = stPosition;
2686
2687   ed->cPasswordMask = 0;
2688   if (props & TXTBIT_USEPASSWORD)
2689     ITextHost_TxGetPasswordChar(texthost, &ed->cPasswordMask);
2690
2691   if (props & TXTBIT_AUTOWORDSEL)
2692     ed->styleFlags |= ECO_AUTOWORDSELECTION;
2693   if (props & TXTBIT_MULTILINE) {
2694     ed->styleFlags |= ES_MULTILINE;
2695     ed->bWordWrap = (props & TXTBIT_WORDWRAP) != 0;
2696   } else {
2697     ed->bWordWrap = FALSE;
2698   }
2699   if (props & TXTBIT_READONLY)
2700     ed->styleFlags |= ES_READONLY;
2701   if (!(props & TXTBIT_HIDESELECTION))
2702     ed->styleFlags |= ES_NOHIDESEL;
2703   if (props & TXTBIT_SAVESELECTION)
2704     ed->styleFlags |= ES_SAVESEL;
2705   if (props & TXTBIT_VERTICAL)
2706     ed->styleFlags |= ES_VERTICAL;
2707   if (props & TXTBIT_DISABLEDRAG)
2708     ed->styleFlags |= ES_NOOLEDRAGDROP;
2709
2710   ed->notified_cr.cpMin = ed->notified_cr.cpMax = 0;
2711
2712   /* Default scrollbar information */
2713   ed->vert_si.cbSize = sizeof(SCROLLINFO);
2714   ed->vert_si.nMin = 0;
2715   ed->vert_si.nMax = 0;
2716   ed->vert_si.nPage = 0;
2717   ed->vert_si.nPos = 0;
2718
2719   ed->horz_si.cbSize = sizeof(SCROLLINFO);
2720   ed->horz_si.nMin = 0;
2721   ed->horz_si.nMax = 0;
2722   ed->horz_si.nPage = 0;
2723   ed->horz_si.nPos = 0;
2724
2725   OleInitialize(NULL);
2726
2727   return ed;
2728 }
2729
2730 static void ME_DestroyEditor(ME_TextEditor *editor)
2731 {
2732   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
2733   ME_DisplayItem *p = pFirst, *pNext = NULL;
2734   int i;
2735
2736   ME_ClearTempStyle(editor);
2737   ME_EmptyUndoStack(editor);
2738   while(p) {
2739     pNext = p->next;
2740     ME_DestroyDisplayItem(p);
2741     p = pNext;
2742   }
2743   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
2744   for (i=0; i<HFONT_CACHE_SIZE; i++)
2745   {
2746     if (editor->pFontCache[i].hFont)
2747       DeleteObject(editor->pFontCache[i].hFont);
2748   }
2749   if (editor->rgbBackColor != -1)
2750     DeleteObject(editor->hbrBackground);
2751   if(editor->lpOleCallback)
2752     IUnknown_Release(editor->lpOleCallback);
2753   IUnknown_Release(editor->texthost);
2754   OleUninitialize();
2755
2756   FREE_OBJ(editor->pBuffer);
2757   FREE_OBJ(editor->pCursors);
2758
2759   FREE_OBJ(editor);
2760 }
2761
2762 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
2763 {
2764     TRACE("\n");
2765     switch (fdwReason)
2766     {
2767     case DLL_PROCESS_ATTACH:
2768       DisableThreadLibraryCalls(hinstDLL);
2769       me_heap = HeapCreate (0, 0x10000, 0);
2770       if (!ME_RegisterEditorClass(hinstDLL)) return FALSE;
2771       hLeft = LoadCursorW(hinstDLL, MAKEINTRESOURCEW(OCR_REVERSE));
2772       LookupInit();
2773       break;
2774
2775     case DLL_PROCESS_DETACH:
2776       UnregisterClassW(RICHEDIT_CLASS20W, 0);
2777       UnregisterClassW(MSFTEDIT_CLASS, 0);
2778       UnregisterClassA(RICHEDIT_CLASS20A, 0);
2779       UnregisterClassA("RichEdit50A", 0);
2780       if (ME_ListBoxRegistered)
2781           UnregisterClassW(REListBox20W, 0);
2782       if (ME_ComboBoxRegistered)
2783           UnregisterClassW(REComboBox20W, 0);
2784       LookupCleanup();
2785       HeapDestroy (me_heap);
2786       me_heap = NULL;
2787       break;
2788     }
2789     return TRUE;
2790 }
2791
2792
2793 static const char * const edit_messages[] = {
2794   "EM_GETSEL",
2795   "EM_SETSEL",
2796   "EM_GETRECT",
2797   "EM_SETRECT",
2798   "EM_SETRECTNP",
2799   "EM_SCROLL",
2800   "EM_LINESCROLL",
2801   "EM_SCROLLCARET",
2802   "EM_GETMODIFY",
2803   "EM_SETMODIFY",
2804   "EM_GETLINECOUNT",
2805   "EM_LINEINDEX",
2806   "EM_SETHANDLE",
2807   "EM_GETHANDLE",
2808   "EM_GETTHUMB",
2809   "EM_UNKNOWN_BF",
2810   "EM_UNKNOWN_C0",
2811   "EM_LINELENGTH",
2812   "EM_REPLACESEL",
2813   "EM_UNKNOWN_C3",
2814   "EM_GETLINE",
2815   "EM_LIMITTEXT",
2816   "EM_CANUNDO",
2817   "EM_UNDO",
2818   "EM_FMTLINES",
2819   "EM_LINEFROMCHAR",
2820   "EM_UNKNOWN_CA",
2821   "EM_SETTABSTOPS",
2822   "EM_SETPASSWORDCHAR",
2823   "EM_EMPTYUNDOBUFFER",
2824   "EM_GETFIRSTVISIBLELINE",
2825   "EM_SETREADONLY",
2826   "EM_SETWORDBREAKPROC",
2827   "EM_GETWORDBREAKPROC",
2828   "EM_GETPASSWORDCHAR",
2829   "EM_SETMARGINS",
2830   "EM_GETMARGINS",
2831   "EM_GETLIMITTEXT",
2832   "EM_POSFROMCHAR",
2833   "EM_CHARFROMPOS",
2834   "EM_SETIMESTATUS",
2835   "EM_GETIMESTATUS"
2836 };
2837
2838 static const char * const richedit_messages[] = {
2839   "EM_CANPASTE",
2840   "EM_DISPLAYBAND",
2841   "EM_EXGETSEL",
2842   "EM_EXLIMITTEXT",
2843   "EM_EXLINEFROMCHAR",
2844   "EM_EXSETSEL",
2845   "EM_FINDTEXT",
2846   "EM_FORMATRANGE",
2847   "EM_GETCHARFORMAT",
2848   "EM_GETEVENTMASK",
2849   "EM_GETOLEINTERFACE",
2850   "EM_GETPARAFORMAT",
2851   "EM_GETSELTEXT",
2852   "EM_HIDESELECTION", 
2853   "EM_PASTESPECIAL",
2854   "EM_REQUESTRESIZE",
2855   "EM_SELECTIONTYPE",
2856   "EM_SETBKGNDCOLOR",
2857   "EM_SETCHARFORMAT",
2858   "EM_SETEVENTMASK",
2859   "EM_SETOLECALLBACK",
2860   "EM_SETPARAFORMAT",
2861   "EM_SETTARGETDEVICE",
2862   "EM_STREAMIN",
2863   "EM_STREAMOUT",
2864   "EM_GETTEXTRANGE",
2865   "EM_FINDWORDBREAK",
2866   "EM_SETOPTIONS",
2867   "EM_GETOPTIONS",
2868   "EM_FINDTEXTEX",
2869   "EM_GETWORDBREAKPROCEX",
2870   "EM_SETWORDBREAKPROCEX",
2871   "EM_SETUNDOLIMIT",
2872   "EM_UNKNOWN_USER_83",
2873   "EM_REDO",
2874   "EM_CANREDO",
2875   "EM_GETUNDONAME",
2876   "EM_GETREDONAME",
2877   "EM_STOPGROUPTYPING",
2878   "EM_SETTEXTMODE",
2879   "EM_GETTEXTMODE",
2880   "EM_AUTOURLDETECT",
2881   "EM_GETAUTOURLDETECT",
2882   "EM_SETPALETTE",
2883   "EM_GETTEXTEX",
2884   "EM_GETTEXTLENGTHEX",
2885   "EM_SHOWSCROLLBAR",
2886   "EM_SETTEXTEX",
2887   "EM_UNKNOWN_USER_98",
2888   "EM_UNKNOWN_USER_99",
2889   "EM_SETPUNCTUATION",
2890   "EM_GETPUNCTUATION",
2891   "EM_SETWORDWRAPMODE",
2892   "EM_GETWORDWRAPMODE",
2893   "EM_SETIMECOLOR",
2894   "EM_GETIMECOLOR",
2895   "EM_SETIMEOPTIONS",
2896   "EM_GETIMEOPTIONS",
2897   "EM_CONVPOSITION",
2898   "EM_UNKNOWN_USER_109",
2899   "EM_UNKNOWN_USER_110",
2900   "EM_UNKNOWN_USER_111",
2901   "EM_UNKNOWN_USER_112",
2902   "EM_UNKNOWN_USER_113",
2903   "EM_UNKNOWN_USER_114",
2904   "EM_UNKNOWN_USER_115",
2905   "EM_UNKNOWN_USER_116",
2906   "EM_UNKNOWN_USER_117",
2907   "EM_UNKNOWN_USER_118",
2908   "EM_UNKNOWN_USER_119",
2909   "EM_SETLANGOPTIONS",
2910   "EM_GETLANGOPTIONS",
2911   "EM_GETIMECOMPMODE",
2912   "EM_FINDTEXTW",
2913   "EM_FINDTEXTEXW",
2914   "EM_RECONVERSION",
2915   "EM_SETIMEMODEBIAS",
2916   "EM_GETIMEMODEBIAS"
2917 };
2918
2919 static const char *
2920 get_msg_name(UINT msg)
2921 {
2922   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
2923     return edit_messages[msg - EM_GETSEL];
2924   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
2925     return richedit_messages[msg - EM_CANPASTE];
2926   return "";
2927 }
2928
2929 static void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2930 {
2931   int x,y;
2932   BOOL isExact;
2933   ME_Cursor cursor; /* The start of the clicked text. */
2934
2935   ENLINK info;
2936   x = (short)LOWORD(lParam);
2937   y = (short)HIWORD(lParam);
2938   ME_CharFromPos(editor, x, y, &cursor, &isExact);
2939   if (!isExact) return;
2940
2941   if (cursor.pRun->member.run.style->fmt.dwMask & CFM_LINK &&
2942       cursor.pRun->member.run.style->fmt.dwEffects & CFE_LINK)
2943   { /* The clicked run has CFE_LINK set */
2944     info.nmhdr.hwndFrom = NULL;
2945     info.nmhdr.idFrom = 0;
2946     info.nmhdr.code = EN_LINK;
2947     info.msg = msg;
2948     info.wParam = wParam;
2949     info.lParam = lParam;
2950     cursor.nOffset = 0;
2951     info.chrg.cpMin = ME_GetCursorOfs(&cursor);
2952     info.chrg.cpMax = info.chrg.cpMin + cursor.pRun->member.run.strText->nLen;
2953     ITextHost_TxNotify(editor->texthost, info.nmhdr.code, &info);
2954   }
2955 }
2956
2957 #define UNSUPPORTED_MSG(e) \
2958   case e:                  \
2959     FIXME(#e ": stub\n");  \
2960     *phresult = S_FALSE;   \
2961     return 0;
2962
2963 /* Handle messages for windowless and windoweded richedit controls.
2964  *
2965  * The LRESULT that is returned is a return value for window procs,
2966  * and the phresult parameter is the COM return code needed by the
2967  * text services interface. */
2968 LRESULT ME_HandleMessage(ME_TextEditor *editor, UINT msg, WPARAM wParam,
2969                          LPARAM lParam, BOOL unicode, HRESULT* phresult)
2970 {
2971   *phresult = S_OK;
2972
2973   switch(msg) {
2974
2975   UNSUPPORTED_MSG(EM_DISPLAYBAND)
2976   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
2977   UNSUPPORTED_MSG(EM_FMTLINES)
2978   UNSUPPORTED_MSG(EM_FORMATRANGE)
2979   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
2980   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
2981   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
2982   UNSUPPORTED_MSG(EM_GETIMESTATUS)
2983   UNSUPPORTED_MSG(EM_SETIMESTATUS)
2984   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
2985   UNSUPPORTED_MSG(EM_GETREDONAME)
2986   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
2987   UNSUPPORTED_MSG(EM_GETUNDONAME)
2988   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
2989   UNSUPPORTED_MSG(EM_PASTESPECIAL)
2990   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
2991   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
2992   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
2993   UNSUPPORTED_MSG(EM_SETFONTSIZE)
2994   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
2995   UNSUPPORTED_MSG(EM_SETMARGINS)
2996   UNSUPPORTED_MSG(EM_SETPALETTE)
2997   UNSUPPORTED_MSG(EM_SETTABSTOPS)
2998   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
2999   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
3000
3001 /* Messages specific to Richedit controls */
3002
3003   case EM_STREAMIN:
3004    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam, TRUE);
3005   case EM_STREAMOUT:
3006    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
3007   case WM_GETDLGCODE:
3008   {
3009     UINT code = DLGC_WANTCHARS|DLGC_WANTTAB|DLGC_WANTARROWS|DLGC_HASSETSEL;
3010     if (editor->styleFlags & ES_MULTILINE)
3011       code |= DLGC_WANTMESSAGE;
3012     return code;
3013   }
3014   case EM_EMPTYUNDOBUFFER:
3015     ME_EmptyUndoStack(editor);
3016     return 0;
3017   case EM_GETSEL:
3018   {
3019     /* Note: wParam/lParam can be NULL */
3020     UINT from, to;
3021     PUINT pfrom = wParam ? (PUINT)wParam : &from;
3022     PUINT pto = lParam ? (PUINT)lParam : &to;
3023     ME_GetSelectionOfs(editor, (int *)pfrom, (int *)pto);
3024     if ((*pfrom|*pto) & 0xFFFF0000)
3025       return -1;
3026     return MAKELONG(*pfrom,*pto);
3027   }
3028   case EM_EXGETSEL:
3029   {
3030     CHARRANGE *pRange = (CHARRANGE *)lParam;
3031     ME_GetSelectionOfs(editor, &pRange->cpMin, &pRange->cpMax);
3032     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
3033     return 0;
3034   }
3035   case EM_SETUNDOLIMIT:
3036   {
3037     if ((int)wParam < 0)
3038       editor->nUndoLimit = STACK_SIZE_DEFAULT;
3039     else
3040       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
3041     /* Setting a max stack size keeps wine from getting killed 
3042       for hogging memory. Windows allocates all this memory at once, so
3043       no program would realistically set a value above our maximum. */
3044     return editor->nUndoLimit;
3045   }
3046   case EM_CANUNDO:
3047     return editor->pUndoStack != NULL;
3048   case EM_CANREDO:
3049     return editor->pRedoStack != NULL;
3050   case WM_UNDO: /* FIXME: actually not the same */
3051   case EM_UNDO:
3052     return ME_Undo(editor);
3053   case EM_REDO:
3054     return ME_Redo(editor);
3055   case EM_GETOPTIONS:
3056   {
3057     /* these flags are equivalent to the ES_* counterparts */
3058     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3059                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN | ECO_SELECTIONBAR;
3060     DWORD settings = editor->styleFlags & mask;
3061
3062     return settings;
3063   }
3064   case EM_SETOPTIONS:
3065   {
3066     /* these flags are equivalent to ES_* counterparts, except for
3067      * ECO_AUTOWORDSELECTION that doesn't have an ES_* counterpart,
3068      * but is still stored in editor->styleFlags. */
3069     const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
3070                        ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
3071                        ECO_SELECTIONBAR | ECO_AUTOWORDSELECTION;
3072     DWORD settings = mask & editor->styleFlags;
3073     DWORD oldSettings = settings;
3074     DWORD changedSettings;
3075
3076     switch(wParam)
3077     {
3078       case ECOOP_SET:
3079         settings = lParam;
3080         break;
3081       case ECOOP_OR:
3082         settings |= lParam;
3083         break;
3084       case ECOOP_AND:
3085         settings &= lParam;
3086         break;
3087       case ECOOP_XOR:
3088         settings ^= lParam;
3089     }
3090     changedSettings = oldSettings ^ settings;
3091
3092     if (changedSettings) {
3093       editor->styleFlags = (editor->styleFlags & ~mask) | (settings & mask);
3094
3095       if (changedSettings & ECO_SELECTIONBAR)
3096       {
3097         ITextHost_TxInvalidateRect(editor->texthost, &editor->rcFormat, TRUE);
3098         if (settings & ECO_SELECTIONBAR) {
3099           assert(!editor->selofs);
3100           editor->selofs = SELECTIONBAR_WIDTH;
3101           editor->rcFormat.left += editor->selofs;
3102         } else {
3103           editor->rcFormat.left -= editor->selofs;
3104           editor->selofs = 0;
3105         }
3106         ME_RewrapRepaint(editor);
3107       }
3108
3109       if (changedSettings & settings & ECO_VERTICAL)
3110         FIXME("ECO_VERTICAL not implemented yet!\n");
3111       if (changedSettings & settings & ECO_AUTOHSCROLL)
3112         FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
3113       if (changedSettings & settings & ECO_AUTOVSCROLL)
3114         FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
3115       if (changedSettings & settings & ECO_NOHIDESEL)
3116         FIXME("ECO_NOHIDESEL not implemented yet!\n");
3117       if (changedSettings & settings & ECO_WANTRETURN)
3118         FIXME("ECO_WANTRETURN not implemented yet!\n");
3119       if (changedSettings & settings & ECO_AUTOWORDSELECTION)
3120         FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
3121     }
3122
3123     return settings;
3124   }
3125   case EM_SETSEL:
3126   {
3127     ME_InvalidateSelection(editor);
3128     ME_SetSelection(editor, wParam, lParam);
3129     ME_InvalidateSelection(editor);
3130     ITextHost_TxShowCaret(editor->texthost, FALSE);
3131     ME_ShowCaret(editor);
3132     ME_SendSelChange(editor);
3133     return 0;
3134   }
3135   case EM_SETSCROLLPOS:
3136   {
3137     POINT *point = (POINT *)lParam;
3138     ME_ScrollAbs(editor, point->x, point->y);
3139     return 0;
3140   }
3141   case EM_AUTOURLDETECT:
3142   {
3143     if (wParam==1 || wParam ==0)
3144     {
3145         editor->AutoURLDetect_bEnable = (BOOL)wParam;
3146         return 0;
3147     }
3148     return E_INVALIDARG;
3149   }
3150   case EM_GETAUTOURLDETECT:
3151   {
3152     return editor->AutoURLDetect_bEnable;
3153   }
3154   case EM_EXSETSEL:
3155   {
3156     int end;
3157     CHARRANGE range = *(CHARRANGE *)lParam;
3158
3159     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
3160
3161     ME_InvalidateSelection(editor);
3162     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
3163     ME_InvalidateSelection(editor);
3164     ITextHost_TxShowCaret(editor->texthost, FALSE);
3165     ME_ShowCaret(editor);
3166     ME_SendSelChange(editor);
3167
3168     return end;
3169   }
3170   case EM_SHOWSCROLLBAR:
3171   {
3172     DWORD flags;
3173
3174     switch (wParam)
3175     {
3176       case SB_HORZ:
3177         flags = WS_HSCROLL;
3178         break;
3179       case SB_VERT:
3180         flags = WS_VSCROLL;
3181         break;
3182       case SB_BOTH:
3183         flags = WS_HSCROLL|WS_VSCROLL;
3184         break;
3185       default:
3186         return 0;
3187     }
3188
3189     if (lParam) {
3190       editor->styleFlags |= flags;
3191       if (flags & WS_HSCROLL)
3192         ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ,
3193                           editor->nTotalWidth > editor->sizeWindow.cx);
3194       if (flags & WS_VSCROLL)
3195         ITextHost_TxShowScrollBar(editor->texthost, SB_VERT,
3196                           editor->nTotalLength > editor->sizeWindow.cy);
3197     } else {
3198       editor->styleFlags &= ~flags;
3199       ITextHost_TxShowScrollBar(editor->texthost, wParam, FALSE);
3200     }
3201     return 0;
3202   }
3203   case EM_SETTEXTEX:
3204   {
3205     LPWSTR wszText;
3206     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
3207     size_t len = 0;
3208     int from, to;
3209     ME_Style *style;
3210     BOOL bRtf, bUnicode, bSelection;
3211     int oldModify = editor->nModifyStep;
3212
3213     if (!pStruct) return 0;
3214
3215     /* If we detect ascii rtf at the start of the string,
3216      * we know it isn't unicode. */
3217     bRtf = (lParam && (!strncmp((char *)lParam, "{\\rtf", 5) ||
3218                          !strncmp((char *)lParam, "{\\urtf", 6)));
3219     bUnicode = !bRtf && pStruct->codepage == 1200;
3220
3221     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n",
3222           bUnicode ? debugstr_w((LPCWSTR)lParam) : debugstr_a((LPCSTR)lParam),
3223           pStruct->flags, pStruct->codepage);
3224
3225     bSelection = (pStruct->flags & ST_SELECTION) != 0;
3226     if (bSelection) {
3227       int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3228       style = ME_GetSelectionInsertStyle(editor);
3229       ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to - from, FALSE);
3230     } else {
3231       ME_Cursor start;
3232       ME_SetCursorToStart(editor, &start);
3233       ME_InternalDeleteText(editor, &start, ME_GetTextLength(editor), FALSE);
3234       style = editor->pBuffer->pDefaultStyle;
3235     }
3236
3237     if (bRtf) {
3238       ME_StreamInRTFString(editor, bSelection, (char *)lParam);
3239       if (bSelection) {
3240         /* FIXME: The length returned is doesn't include the rtf control
3241          * characters, only the actual text. */
3242         len = lParam ? strlen((char *)lParam) : 0;
3243       }
3244     } else {
3245       /* FIXME: make use of pStruct->codepage in the to unicode translation */
3246       wszText = lParam ? ME_ToUnicode(bUnicode, (void *)lParam) : NULL;
3247       len = wszText ? lstrlenW(wszText) : 0;
3248       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3249     }
3250
3251     if (bSelection) {
3252       ME_ReleaseStyle(style);
3253       ME_UpdateSelectionLinkAttribute(editor);
3254     } else {
3255       ME_Cursor cursor;
3256       len = 1;
3257       ME_SetCursorToStart(editor, &cursor);
3258       ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3259     }
3260     ME_CommitUndo(editor);
3261     if (!(pStruct->flags & ST_KEEPUNDO))
3262     {
3263       editor->nModifyStep = oldModify;
3264       ME_EmptyUndoStack(editor);
3265     }
3266     ME_UpdateRepaint(editor);
3267     return len;
3268   }
3269   case EM_SETBKGNDCOLOR:
3270   {
3271     LRESULT lColor;
3272     if (editor->rgbBackColor != -1) {
3273       DeleteObject(editor->hbrBackground);
3274       lColor = editor->rgbBackColor;
3275     }
3276     else lColor = ITextHost_TxGetSysColor(editor->texthost, COLOR_WINDOW);
3277
3278     if (wParam)
3279     {
3280       editor->rgbBackColor = -1;
3281       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
3282     }
3283     else
3284     {
3285       editor->rgbBackColor = lParam;
3286       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
3287     }
3288     ITextHost_TxInvalidateRect(editor->texthost, NULL, TRUE);
3289     ITextHost_TxViewChange(editor->texthost, TRUE);
3290     return lColor;
3291   }
3292   case EM_GETMODIFY:
3293     return editor->nModifyStep == 0 ? 0 : -1;
3294   case EM_SETMODIFY:
3295   {
3296     if (wParam)
3297       editor->nModifyStep = 1;
3298     else
3299       editor->nModifyStep = 0;
3300     
3301     return 0;
3302   }
3303   case EM_SETREADONLY:
3304   {
3305     if (wParam)
3306       editor->styleFlags |= ES_READONLY;
3307     else
3308       editor->styleFlags &= ~ES_READONLY;
3309     return 0;
3310   }
3311   case EM_SETEVENTMASK:
3312   {
3313     DWORD nOldMask = editor->nEventMask;
3314     
3315     editor->nEventMask = lParam;
3316     return nOldMask;
3317   }
3318   case EM_GETEVENTMASK:
3319     return editor->nEventMask;
3320   case EM_SETCHARFORMAT:
3321   {
3322     CHARFORMAT2W buf, *p;
3323     BOOL bRepaint = TRUE;
3324     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
3325     if (p == NULL) return 0;
3326     if (!wParam)
3327       ME_SetDefaultCharFormat(editor, p);
3328     else if (wParam == (SCF_WORD | SCF_SELECTION)) {
3329       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
3330       return 0;
3331     } else if (wParam == SCF_ALL) {
3332       if (editor->mode & TM_PLAINTEXT)
3333         ME_SetDefaultCharFormat(editor, p);
3334       else {
3335         ME_Cursor start;
3336         ME_SetCursorToStart(editor, &start);
3337         ME_SetCharFormat(editor, &start, NULL, p);
3338         editor->nModifyStep = 1;
3339       }
3340     } else if (editor->mode & TM_PLAINTEXT) {
3341       return 0;
3342     } else {
3343       bRepaint = ME_IsSelection(editor);
3344       ME_SetSelectionCharFormat(editor, p);
3345       if (bRepaint) editor->nModifyStep = 1;
3346     }
3347     ME_CommitUndo(editor);
3348     if (bRepaint)
3349     {
3350       ME_WrapMarkedParagraphs(editor);
3351       ME_UpdateScrollBar(editor);
3352       ME_Repaint(editor);
3353     }
3354     return 1;
3355   }
3356   case EM_GETCHARFORMAT:
3357   {
3358     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
3359     if (dst->cbSize != sizeof(CHARFORMATA) &&
3360         dst->cbSize != sizeof(CHARFORMATW) &&
3361         dst->cbSize != sizeof(CHARFORMAT2A) &&
3362         dst->cbSize != sizeof(CHARFORMAT2W))
3363       return 0;
3364     tmp.cbSize = sizeof(tmp);
3365     if (!wParam)
3366       ME_GetDefaultCharFormat(editor, &tmp);
3367     else
3368       ME_GetSelectionCharFormat(editor, &tmp);
3369     ME_CopyToCFAny(dst, &tmp);
3370     return tmp.dwMask;
3371   }
3372   case EM_SETPARAFORMAT:
3373   {
3374     BOOL result = ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3375     ME_WrapMarkedParagraphs(editor);
3376     ME_UpdateScrollBar(editor);
3377     ME_Repaint(editor);
3378     ME_CommitUndo(editor);
3379     return result;
3380   }
3381   case EM_GETPARAFORMAT:
3382     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
3383     return ((PARAFORMAT2 *)lParam)->dwMask;
3384   case EM_GETFIRSTVISIBLELINE:
3385   {
3386     ME_DisplayItem *p = editor->pBuffer->pFirst;
3387     int y = editor->vert_si.nPos;
3388     int ypara = 0;
3389     int count = 0;
3390     int ystart, yend;
3391     while(p) {
3392       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
3393       if (p->type == diTextEnd)
3394         break;
3395       if (p->type == diParagraph) {
3396         ypara = p->member.para.pt.y;
3397         continue;
3398       }
3399       ystart = ypara + p->member.row.pt.y;
3400       yend = ystart + p->member.row.nHeight;
3401       if (y < yend) {
3402         break;
3403       }
3404       count++;
3405     }
3406     return count;
3407   }
3408   case EM_HIDESELECTION:
3409   {
3410      editor->bHideSelection = (wParam != 0);
3411      ME_InvalidateSelection(editor);
3412      return 0;
3413   }
3414   case EM_LINESCROLL:
3415   {
3416     if (!(editor->styleFlags & ES_MULTILINE))
3417       return FALSE;
3418     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
3419     return TRUE;
3420   }
3421   case WM_CLEAR:
3422   {
3423     int from, to;
3424     int nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3425     ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3426     ME_CommitUndo(editor);
3427     ME_UpdateRepaint(editor);
3428     return 0;
3429   }
3430   case EM_REPLACESEL:
3431   {
3432     int from, to, nStartCursor;
3433     ME_Style *style;
3434     LPWSTR wszText = lParam ? ME_ToUnicode(unicode, (void *)lParam) : NULL;
3435     size_t len = wszText ? lstrlenW(wszText) : 0;
3436     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
3437
3438     nStartCursor = ME_GetSelectionOfs(editor, &from, &to);
3439     style = ME_GetSelectionInsertStyle(editor);
3440     ME_InternalDeleteText(editor, &editor->pCursors[nStartCursor], to-from, FALSE);
3441     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
3442     ME_ReleaseStyle(style);
3443     /* drop temporary style if line end */
3444     /*
3445      * FIXME question: does abc\n mean: put abc,
3446      * clear temp style, put \n? (would require a change)
3447      */
3448     if (len>0 && wszText[len-1] == '\n')
3449       ME_ClearTempStyle(editor);
3450     ME_EndToUnicode(unicode, wszText);
3451     ME_CommitUndo(editor);
3452     ME_UpdateSelectionLinkAttribute(editor);
3453     if (!wParam)
3454       ME_EmptyUndoStack(editor);
3455     ME_UpdateRepaint(editor);
3456     return len;
3457   }
3458   case EM_SCROLLCARET:
3459     ME_EnsureVisible(editor, &editor->pCursors[0]);
3460     return 0;
3461   case WM_SETFONT:
3462   {
3463     LOGFONTW lf;
3464     CHARFORMAT2W fmt;
3465     HDC hDC;
3466     BOOL bRepaint = LOWORD(lParam);
3467     ME_Cursor start;
3468
3469     if (!wParam)
3470       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
3471     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
3472     hDC = ITextHost_TxGetDC(editor->texthost);
3473     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
3474     ITextHost_TxReleaseDC(editor->texthost, hDC);
3475     ME_SetCursorToStart(editor, &start);
3476     ME_SetCharFormat(editor, &start, NULL, &fmt);
3477     ME_SetDefaultCharFormat(editor, &fmt);
3478
3479     ME_CommitUndo(editor);
3480     ME_MarkAllForWrapping(editor);
3481     ME_WrapMarkedParagraphs(editor);
3482     ME_UpdateScrollBar(editor);
3483     if (bRepaint)
3484       ME_Repaint(editor);
3485     return 0;
3486   }
3487   case WM_SETTEXT:
3488   {
3489     ME_Cursor cursor;
3490     ME_SetCursorToStart(editor, &cursor);
3491     ME_InternalDeleteText(editor, &cursor, ME_GetTextLength(editor), FALSE);
3492     if (lParam)
3493     {
3494       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
3495       if (!strncmp((char *)lParam, "{\\rtf", 5) ||
3496           !strncmp((char *)lParam, "{\\urtf", 6))
3497       {
3498         /* Undocumented: WM_SETTEXT supports RTF text */
3499         ME_StreamInRTFString(editor, 0, (char *)lParam);
3500       }
3501       else
3502       {
3503         LPWSTR wszText = ME_ToUnicode(unicode, (void *)lParam);
3504         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
3505         if (lstrlenW(wszText) > 0)
3506         {
3507           int len = -1;
3508
3509           /* uses default style! */
3510           if (!(editor->styleFlags & ES_MULTILINE))
3511           {
3512             WCHAR * p;
3513
3514             p = wszText;
3515             while (*p != '\0' && *p != '\r' && *p != '\n') p++;
3516             len = p - wszText;
3517           }
3518           ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
3519         }
3520         ME_EndToUnicode(unicode, wszText);
3521       }
3522     }
3523     else
3524       TRACE("WM_SETTEXT - NULL\n");
3525     ME_SetCursorToStart(editor, &cursor);
3526     ME_UpdateLinkAttribute(editor, &cursor, INT_MAX);
3527     ME_SetSelection(editor, 0, 0);
3528     editor->nModifyStep = 0;
3529     ME_CommitUndo(editor);
3530     ME_EmptyUndoStack(editor);
3531     ME_UpdateRepaint(editor);
3532     return 1;
3533   }
3534   case EM_CANPASTE:
3535   {
3536     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
3537     if (IsClipboardFormatAvailable(nRTFFormat))
3538       return TRUE;
3539     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
3540       return TRUE;
3541     return FALSE;
3542   }
3543   case WM_PASTE:
3544     ME_Paste(editor);
3545     return 0;
3546   case WM_CUT:
3547   case WM_COPY:
3548   {
3549     int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3550     int nChars = nTo - nFrom;
3551     ME_Cursor *selStart = &editor->pCursors[nStartCur];
3552
3553     if (ME_Copy(editor, selStart, nChars) && msg == WM_CUT)
3554     {
3555       ME_InternalDeleteText(editor, selStart, nChars, FALSE);
3556       ME_CommitUndo(editor);
3557       ME_UpdateRepaint(editor);
3558     }
3559     return 0;
3560   }
3561   case WM_GETTEXTLENGTH:
3562   {
3563     GETTEXTLENGTHEX how;
3564
3565     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
3566     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
3567     how.codepage = unicode ? 1200 : CP_ACP;
3568     return ME_GetTextLengthEx(editor, &how);
3569   }
3570   case EM_GETTEXTLENGTHEX:
3571     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
3572   case WM_GETTEXT:
3573   {
3574     GETTEXTEX ex;
3575     ex.cb = wParam * (unicode ? sizeof(WCHAR) : sizeof(CHAR));
3576     ex.flags = GT_USECRLF;
3577     ex.codepage = unicode ? 1200 : CP_ACP;
3578     ex.lpDefaultChar = NULL;
3579     ex.lpUsedDefChar = NULL;
3580     return ME_GetTextEx(editor, &ex, lParam);
3581   }
3582   case EM_GETTEXTEX:
3583     return ME_GetTextEx(editor, (GETTEXTEX*)wParam, lParam);
3584   case EM_GETSELTEXT:
3585   {
3586     int nFrom, nTo, nStartCur = ME_GetSelectionOfs(editor, &nFrom, &nTo);
3587     ME_Cursor *from = &editor->pCursors[nStartCur];
3588     return ME_GetTextRange(editor, (WCHAR *)lParam, from,
3589                            nTo - nFrom, unicode);
3590   }
3591   case EM_GETSCROLLPOS:
3592   {
3593     POINT *point = (POINT *)lParam;
3594     point->x = editor->horz_si.nPos;
3595     point->y = editor->vert_si.nPos;
3596     /* 16-bit scaled value is returned as stored in scrollinfo */
3597     if (editor->horz_si.nMax > 0xffff)
3598       point->x = MulDiv(point->x, 0xffff, editor->horz_si.nMax);
3599     if (editor->vert_si.nMax > 0xffff)
3600       point->y = MulDiv(point->y, 0xffff, editor->vert_si.nMax);
3601     return 1;
3602   }
3603   case EM_GETTEXTRANGE:
3604   {
3605     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
3606     ME_Cursor start;
3607     int nStart = rng->chrg.cpMin;
3608     int nEnd = rng->chrg.cpMax;
3609     int textlength = ME_GetTextLength(editor);
3610
3611     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d textlength=%d\n",
3612           rng->chrg.cpMin, rng->chrg.cpMax, unicode, textlength);
3613     if (nStart < 0) return 0;
3614     if ((nStart == 0 && nEnd == -1) || nEnd > textlength)
3615       nEnd = textlength;
3616     if (nStart >= nEnd) return 0;
3617
3618     ME_CursorFromCharOfs(editor, nStart, &start);
3619     return ME_GetTextRange(editor, rng->lpstrText, &start, nEnd - nStart, unicode);
3620   }
3621   case EM_GETLINE:
3622   {
3623     ME_DisplayItem *run;
3624     const unsigned int nMaxChars = *(WORD *) lParam;
3625     unsigned int nCharsLeft = nMaxChars;
3626     char *dest = (char *) lParam;
3627     BOOL wroteNull = FALSE;
3628
3629     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
3630           unicode ? "Unicode" : "Ansi");
3631
3632     run = ME_FindRowWithNumber(editor, wParam);
3633     if (run == NULL)
3634       return 0;
3635
3636     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
3637            && run->type == diRun)
3638     {
3639       unsigned int nCopy;
3640       ME_String *strText;
3641
3642       strText = run->member.run.strText;
3643       nCopy = min(nCharsLeft, strText->nLen);
3644
3645       if (unicode)
3646         memcpy(dest, strText->szData, nCopy * sizeof(WCHAR));
3647       else
3648         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
3649                                     nCharsLeft, NULL, NULL);
3650       dest += nCopy * (unicode ? sizeof(WCHAR) : 1);
3651       nCharsLeft -= nCopy;
3652     }
3653
3654     /* append line termination, space allowing */
3655     if (nCharsLeft > 0)
3656     {
3657       if (unicode)
3658         *((WCHAR *)dest) = '\0';
3659       else
3660         *dest = '\0';
3661       nCharsLeft--;
3662       wroteNull = TRUE;
3663     }
3664
3665     TRACE("EM_GETLINE: got %u characters\n", nMaxChars - nCharsLeft);
3666     return nMaxChars - nCharsLeft - (wroteNull ? 1 : 0);
3667   }
3668   case EM_GETLINECOUNT:
3669   {
3670     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
3671     int nRows = 0;
3672
3673     ME_DisplayItem *prev_para = NULL, *last_para = NULL;
3674
3675     while (item != editor->pBuffer->pLast)
3676     {
3677       assert(item->type == diParagraph);
3678       prev_para = ME_FindItemBack(item, diRun);
3679       if (prev_para) {
3680         assert(prev_para->member.run.nFlags & MERF_ENDPARA);
3681       }
3682       nRows += item->member.para.nRows;
3683       item = item->member.para.next_para;
3684     }
3685     last_para = ME_FindItemBack(item, diRun);
3686     assert(last_para);
3687     assert(last_para->member.run.nFlags & MERF_ENDPARA);
3688     if (editor->bEmulateVersion10 && prev_para &&
3689         last_para->member.run.nCharOfs == 0 &&
3690         prev_para->member.run.strText->nLen == 1 &&
3691         prev_para->member.run.strText->szData[0] == '\r')
3692     {
3693       /* In 1.0 emulation, the last solitary \r at the very end of the text
3694          (if one exists) is NOT a line break.
3695          FIXME: this is an ugly hack. This should have a more regular model. */
3696       nRows--;
3697     }
3698
3699     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
3700     return max(1, nRows);
3701   }
3702   case EM_LINEFROMCHAR:
3703   {
3704     if (wParam == -1)
3705       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3706     else
3707       return ME_RowNumberFromCharOfs(editor, wParam);
3708   }
3709   case EM_EXLINEFROMCHAR:
3710   {
3711     if (lParam == -1)
3712       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(&editor->pCursors[1]));
3713     else    
3714       return ME_RowNumberFromCharOfs(editor, lParam);
3715   }
3716   case EM_LINEINDEX:
3717   {
3718     ME_DisplayItem *item, *para;
3719     int nCharOfs;
3720     
3721     if (wParam == -1)
3722       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
3723     else
3724       item = ME_FindRowWithNumber(editor, wParam);
3725     if (!item)
3726       return -1;
3727     para = ME_GetParagraph(item);
3728     item = ME_FindItemFwd(item, diRun);
3729     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
3730     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
3731     return nCharOfs;
3732   }
3733   case EM_LINELENGTH:
3734   {
3735     ME_DisplayItem *item, *item_end;
3736     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
3737     ME_DisplayItem *para, *run;
3738
3739     if (wParam > ME_GetTextLength(editor))
3740       return 0;
3741     if (wParam == -1)
3742     {
3743       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
3744       return 0;
3745     }
3746     ME_RunOfsFromCharOfs(editor, wParam, &para, &run, NULL);
3747     item = ME_RowStart(run);
3748     nThisLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item, diRun), 0);
3749     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
3750     if (item_end->type == diStartRow) {
3751       nNextLineOfs = ME_CharOfsFromRunOfs(editor, para, ME_FindItemFwd(item_end, diRun), 0);
3752     } else {
3753       ME_DisplayItem *endRun = ME_FindItemBack(item_end, diRun);
3754       assert(endRun && endRun->member.run.nFlags & MERF_ENDPARA);
3755       nNextLineOfs = item_end->member.para.nCharOfs - endRun->member.run.strText->nLen;
3756     }
3757     nChars = nNextLineOfs - nThisLineOfs;
3758     TRACE("EM_LINELENGTH(%ld)==%d\n",wParam, nChars);
3759     return nChars;
3760   }
3761   case EM_EXLIMITTEXT:
3762   {
3763     if ((int)lParam < 0)
3764      return 0;
3765     if (lParam == 0)
3766       editor->nTextLimit = 65536;
3767     else
3768       editor->nTextLimit = (int) lParam;
3769     return 0;
3770   }
3771   case EM_LIMITTEXT:
3772   {
3773     if (wParam == 0)
3774       editor->nTextLimit = 65536;
3775     else
3776       editor->nTextLimit = (int) wParam;
3777     return 0;
3778   }
3779   case EM_GETLIMITTEXT:
3780   {
3781     return editor->nTextLimit;
3782   }
3783   case EM_FINDTEXT:
3784   {
3785     FINDTEXTA *ft = (FINDTEXTA *)lParam;
3786     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
3787     WCHAR *tmp;
3788     LRESULT r;
3789
3790     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3791       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
3792     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
3793     FREE_OBJ( tmp );
3794     return r;
3795   }
3796   case EM_FINDTEXTEX:
3797   {
3798     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
3799     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
3800     WCHAR *tmp;
3801     LRESULT r;
3802
3803     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
3804       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
3805     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
3806     FREE_OBJ( tmp );
3807     return r;
3808   }
3809   case EM_FINDTEXTW:
3810   {
3811     FINDTEXTW *ft = (FINDTEXTW *)lParam;
3812     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
3813   }
3814   case EM_FINDTEXTEXW:
3815   {
3816     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
3817     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
3818   }
3819   case EM_GETZOOM:
3820     if (!wParam || !lParam)
3821       return FALSE;
3822     *(int *)wParam = editor->nZoomNumerator;
3823     *(int *)lParam = editor->nZoomDenominator;
3824     return TRUE;
3825   case EM_SETZOOM:
3826     return ME_SetZoom(editor, wParam, lParam);
3827   case EM_CHARFROMPOS:
3828   {
3829     ME_Cursor cursor;
3830     if (ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y,
3831                        &cursor, NULL))
3832       return ME_GetCursorOfs(&cursor);
3833     else
3834       return -1;
3835   }
3836   case EM_POSFROMCHAR:
3837   {
3838     ME_DisplayItem *pPara, *pRun;
3839     int nCharOfs, nOffset, nLength;
3840     POINTL pt = {0,0};
3841
3842     nCharOfs = wParam;
3843     /* detect which API version we're dealing with */
3844     if (wParam >= 0x40000)
3845         nCharOfs = lParam;
3846     nLength = ME_GetTextLength(editor);
3847     nCharOfs = min(nCharOfs, nLength);
3848     nCharOfs = max(nCharOfs, 0);
3849
3850     ME_RunOfsFromCharOfs(editor, nCharOfs, &pPara, &pRun, &nOffset);
3851     assert(pRun->type == diRun);
3852     pt.y = pRun->member.run.pt.y;
3853     pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
3854     pt.y += pPara->member.para.pt.y + editor->rcFormat.top;
3855     pt.x += editor->rcFormat.left;
3856
3857     pt.x -= editor->horz_si.nPos;
3858     pt.y -= editor->vert_si.nPos;
3859
3860     if (wParam >= 0x40000) {
3861         *(POINTL *)wParam = pt;
3862     }
3863     return (wParam >= 0x40000) ? 0 : MAKELONG( pt.x, pt.y );
3864   }
3865   case WM_CREATE:
3866   {
3867     INT max;
3868
3869     ME_SetDefaultFormatRect(editor);
3870
3871     max = (editor->styleFlags & ES_DISABLENOSCROLL) ? 1 : 0;
3872     if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_VSCROLL)
3873       ITextHost_TxSetScrollRange(editor->texthost, SB_VERT, 0, max, TRUE);
3874
3875     if (~editor->styleFlags & ES_DISABLENOSCROLL || editor->styleFlags & WS_HSCROLL)
3876       ITextHost_TxSetScrollRange(editor->texthost, SB_HORZ, 0, max, TRUE);
3877
3878     if (editor->styleFlags & ES_DISABLENOSCROLL)
3879     {
3880       if (editor->styleFlags & WS_VSCROLL)
3881       {
3882         ITextHost_TxEnableScrollBar(editor->texthost, SB_VERT, ESB_DISABLE_BOTH);
3883         ITextHost_TxShowScrollBar(editor->texthost, SB_VERT, TRUE);
3884       }
3885       if (editor->styleFlags & WS_HSCROLL)
3886       {
3887         ITextHost_TxEnableScrollBar(editor->texthost, SB_HORZ, ESB_DISABLE_BOTH);
3888         ITextHost_TxShowScrollBar(editor->texthost, SB_HORZ, TRUE);
3889       }
3890     }
3891
3892     ME_CommitUndo(editor);
3893     ME_WrapMarkedParagraphs(editor);
3894     ME_MoveCaret(editor);
3895     return 0;
3896   }
3897   case WM_DESTROY:
3898     ME_DestroyEditor(editor);
3899     return 0;
3900   case WM_SETCURSOR:
3901   {
3902     return ME_SetCursor(editor);
3903   }
3904   case WM_LBUTTONDBLCLK:
3905   case WM_LBUTTONDOWN:
3906   {
3907     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3908     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3909         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3910       return 0;
3911     ITextHost_TxSetFocus(editor->texthost);
3912     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam),
3913                    ME_CalculateClickCount(editor, msg, wParam, lParam));
3914     ITextHost_TxSetCapture(editor->texthost, TRUE);
3915     editor->bMouseCaptured = TRUE;
3916     ME_LinkNotify(editor,msg,wParam,lParam);
3917     if (!ME_SetCursor(editor)) goto do_default;
3918     break;
3919   }
3920   case WM_MOUSEMOVE:
3921     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3922         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3923       return 0;
3924     if (editor->bMouseCaptured)
3925       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
3926     ME_LinkNotify(editor,msg,wParam,lParam);
3927     /* Set cursor if mouse is captured, since WM_SETCURSOR won't be received. */
3928     if (editor->bMouseCaptured)
3929         ME_SetCursor(editor);
3930     break;
3931   case WM_LBUTTONUP:
3932     if (editor->bMouseCaptured) {
3933       ITextHost_TxSetCapture(editor->texthost, FALSE);
3934       editor->bMouseCaptured = FALSE;
3935     }
3936     if (editor->nSelectionType == stDocument)
3937       editor->nSelectionType = stPosition;
3938     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3939         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3940       return 0;
3941     else
3942     {
3943       ME_SetCursor(editor);
3944       ME_LinkNotify(editor,msg,wParam,lParam);
3945     }
3946     break;
3947   case WM_RBUTTONUP:
3948   case WM_RBUTTONDOWN:
3949     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3950     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
3951         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3952       return 0;
3953     goto do_default;
3954   case WM_CONTEXTMENU:
3955     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
3956       goto do_default;
3957     break;
3958   case WM_SETFOCUS:
3959     editor->bHaveFocus = TRUE;
3960     ME_ShowCaret(editor);
3961     ME_SendOldNotify(editor, EN_SETFOCUS);
3962     return 0;
3963   case WM_KILLFOCUS:
3964     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
3965     editor->bHaveFocus = FALSE;
3966     ME_HideCaret(editor);
3967     ME_SendOldNotify(editor, EN_KILLFOCUS);
3968     return 0;
3969   case WM_COMMAND:
3970     TRACE("editor wnd command = %d\n", LOWORD(wParam));
3971     return 0;
3972   case WM_KEYUP:
3973     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3974         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3975       return 0;
3976     goto do_default;
3977   case WM_KEYDOWN:
3978     if ((editor->nEventMask & ENM_KEYEVENTS) &&
3979         !ME_FilterEvent(editor, msg, &wParam, &lParam))
3980       return 0;
3981     if (ME_KeyDown(editor, LOWORD(wParam)))
3982       return 0;
3983     goto do_default;
3984   case WM_CHAR:
3985     return ME_Char(editor, wParam, lParam, unicode);
3986   case WM_UNICHAR:
3987     if (unicode)
3988     {
3989         if(wParam == UNICODE_NOCHAR) return TRUE;
3990         if(wParam <= 0x000fffff)
3991         {
3992             if(wParam > 0xffff) /* convert to surrogates */
3993             {
3994                 wParam -= 0x10000;
3995                 ME_Char(editor, (wParam >> 10) + 0xd800, 0, TRUE);
3996                 ME_Char(editor, (wParam & 0x03ff) + 0xdc00, 0, TRUE);
3997             } else {
3998               ME_Char(editor, wParam, 0, TRUE);
3999             }
4000         }
4001         return 0;
4002     }
4003     break;
4004   case EM_STOPGROUPTYPING:
4005     ME_CommitUndo(editor); /* End coalesced undos for typed characters */
4006     return 0;
4007   case WM_HSCROLL:
4008   {
4009     const int scrollUnit = 7;
4010
4011     switch(LOWORD(wParam))
4012     {
4013       case SB_LEFT:
4014         ME_ScrollAbs(editor, 0, 0);
4015         break;
4016       case SB_RIGHT:
4017         ME_ScrollAbs(editor,
4018                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
4019                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
4020         break;
4021       case SB_LINELEFT:
4022         ME_ScrollLeft(editor, scrollUnit);
4023         break;
4024       case SB_LINERIGHT:
4025         ME_ScrollRight(editor, scrollUnit);
4026         break;
4027       case SB_PAGELEFT:
4028         ME_ScrollLeft(editor, editor->sizeWindow.cx);
4029         break;
4030       case SB_PAGERIGHT:
4031         ME_ScrollRight(editor, editor->sizeWindow.cx);
4032         break;
4033       case SB_THUMBTRACK:
4034       case SB_THUMBPOSITION:
4035       {
4036         int pos = HIWORD(wParam);
4037         if (editor->horz_si.nMax > 0xffff)
4038           pos = MulDiv(pos, editor->horz_si.nMax, 0xffff);
4039         ME_HScrollAbs(editor, pos);
4040         break;
4041       }
4042     }
4043     break;
4044   }
4045   case EM_SCROLL: /* fall through */
4046   case WM_VSCROLL:
4047   {
4048     int origNPos;
4049     int lineHeight;
4050
4051     origNPos = editor->vert_si.nPos;
4052     lineHeight = 24;
4053
4054     if (editor->pBuffer && editor->pBuffer->pDefaultStyle)
4055       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
4056     if (lineHeight <= 0) lineHeight = 24;
4057
4058     switch(LOWORD(wParam))
4059     {
4060       case SB_TOP:
4061         ME_ScrollAbs(editor, 0, 0);
4062         break;
4063       case SB_BOTTOM:
4064         ME_ScrollAbs(editor,
4065                      editor->horz_si.nMax - (int)editor->horz_si.nPage,
4066                      editor->vert_si.nMax - (int)editor->vert_si.nPage);
4067         break;
4068       case SB_LINEUP:
4069         ME_ScrollUp(editor,lineHeight);
4070         break;
4071       case SB_LINEDOWN:
4072         ME_ScrollDown(editor,lineHeight);
4073         break;
4074       case SB_PAGEUP:
4075         ME_ScrollUp(editor,editor->sizeWindow.cy);
4076         break;
4077       case SB_PAGEDOWN:
4078         ME_ScrollDown(editor,editor->sizeWindow.cy);
4079         break;
4080       case SB_THUMBTRACK:
4081       case SB_THUMBPOSITION:
4082       {
4083         int pos = HIWORD(wParam);
4084         if (editor->vert_si.nMax > 0xffff)
4085           pos = MulDiv(pos, editor->vert_si.nMax, 0xffff);
4086         ME_VScrollAbs(editor, pos);
4087         break;
4088       }
4089     }
4090     if (msg == EM_SCROLL)
4091       return 0x00010000 | (((editor->vert_si.nPos - origNPos)/lineHeight) & 0xffff);
4092     break;
4093   }
4094   case WM_MOUSEWHEEL:
4095   {
4096     int gcWheelDelta;
4097     UINT pulScrollLines;
4098     BOOL ctrl_is_down;
4099
4100     if ((editor->nEventMask & ENM_MOUSEEVENTS) &&
4101         !ME_FilterEvent(editor, msg, &wParam, &lParam))
4102       return 0;
4103
4104     ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
4105
4106     gcWheelDelta = GET_WHEEL_DELTA_WPARAM(wParam);
4107
4108     if (abs(gcWheelDelta) >= WHEEL_DELTA)
4109     {
4110       if (ctrl_is_down) {
4111         int numerator;
4112         if (!editor->nZoomNumerator || !editor->nZoomDenominator)
4113         {
4114           numerator = 100;
4115         } else {
4116           numerator = editor->nZoomNumerator * 100 / editor->nZoomDenominator;
4117         }
4118         numerator = numerator + (gcWheelDelta / WHEEL_DELTA) * 10;
4119         if (numerator >= 10 && numerator <= 500)
4120           ME_SetZoom(editor, numerator, 100);
4121       } else {
4122         SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
4123         /* FIXME follow the original */
4124         if (pulScrollLines)
4125           ME_ScrollDown(editor,pulScrollLines * (-gcWheelDelta / WHEEL_DELTA) * 8);
4126       }
4127     }
4128     break;
4129   }
4130   case EM_GETRECT:
4131   {
4132     *((RECT *)lParam) = editor->rcFormat;
4133     if (editor->bDefaultFormatRect)
4134       ((RECT *)lParam)->left -= editor->selofs;
4135     return 0;
4136   }
4137   case EM_SETRECT:
4138   case EM_SETRECTNP:
4139   {
4140     if (lParam)
4141     {
4142       int border = 0;
4143       RECT clientRect;
4144       RECT *rc = (RECT *)lParam;
4145
4146       border = editor->exStyleFlags & WS_EX_CLIENTEDGE ? 1 : 0;
4147       ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4148       if (wParam == 0)
4149       {
4150         editor->rcFormat.top = max(0, rc->top - border);
4151         editor->rcFormat.left = max(0, rc->left - border);
4152         editor->rcFormat.bottom = min(clientRect.bottom, rc->bottom);
4153         editor->rcFormat.right = min(clientRect.right, rc->right + border);
4154       } else if (wParam == 1) {
4155         /* MSDN incorrectly says a wParam value of 1 causes the
4156          * lParam rect to be used as a relative offset,
4157          * however, the tests show it just prevents min/max bound
4158          * checking. */
4159         editor->rcFormat.top = rc->top - border;
4160         editor->rcFormat.left = rc->left - border;
4161         editor->rcFormat.bottom = rc->bottom;
4162         editor->rcFormat.right = rc->right + border;
4163       } else {
4164         return 0;
4165       }
4166       editor->bDefaultFormatRect = FALSE;
4167     }
4168     else
4169     {
4170       ME_SetDefaultFormatRect(editor);
4171       editor->bDefaultFormatRect = TRUE;
4172     }
4173     ME_MarkAllForWrapping(editor);
4174     ME_WrapMarkedParagraphs(editor);
4175     ME_UpdateScrollBar(editor);
4176     if (msg != EM_SETRECTNP)
4177       ME_Repaint(editor);
4178     return 0;
4179   }
4180   case EM_REQUESTRESIZE:
4181     ME_SendRequestResize(editor, TRUE);
4182     return 0;
4183   case WM_SETREDRAW:
4184     goto do_default;
4185   case WM_SIZE:
4186   {
4187     RECT clientRect;
4188
4189     ITextHost_TxGetClientRect(editor->texthost, &clientRect);
4190     if (editor->bDefaultFormatRect) {
4191       ME_SetDefaultFormatRect(editor);
4192     } else {
4193       editor->rcFormat.right += clientRect.right - editor->prevClientRect.right;
4194       editor->rcFormat.bottom += clientRect.bottom - editor->prevClientRect.bottom;
4195     }
4196     editor->prevClientRect = clientRect;
4197     ME_RewrapRepaint(editor);
4198     goto do_default;
4199   }
4200   /* IME messages to make richedit controls IME aware */
4201   case WM_IME_SETCONTEXT:
4202   case WM_IME_CONTROL:
4203   case WM_IME_SELECT:
4204   case WM_IME_COMPOSITIONFULL:
4205     return 0;
4206   case WM_IME_STARTCOMPOSITION:
4207   {
4208     editor->imeStartIndex=ME_GetCursorOfs(&editor->pCursors[0]);
4209     ME_DeleteSelection(editor);
4210     ME_CommitUndo(editor);
4211     ME_UpdateRepaint(editor);
4212     return 0;
4213   }
4214   case WM_IME_COMPOSITION:
4215   {
4216     HIMC hIMC;
4217
4218     ME_Style *style = ME_GetInsertStyle(editor, 0);
4219     hIMC = ITextHost_TxImmGetContext(editor->texthost);
4220     ME_DeleteSelection(editor);
4221     ME_CommitUndo(editor);
4222     ME_SaveTempStyle(editor);
4223     if (lParam & GCS_RESULTSTR)
4224     {
4225         LPWSTR lpCompStr = NULL;
4226         DWORD dwBufLen;
4227
4228         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
4229         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4230         ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, lpCompStr, dwBufLen);
4231         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4232         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4233     }
4234     else if (lParam & GCS_COMPSTR)
4235     {
4236         LPWSTR lpCompStr = NULL;
4237         DWORD dwBufLen;
4238
4239         dwBufLen = ImmGetCompositionStringW(hIMC, GCS_COMPSTR, NULL, 0);
4240         lpCompStr = HeapAlloc(GetProcessHeap(),0,dwBufLen + sizeof(WCHAR));
4241         ImmGetCompositionStringW(hIMC, GCS_COMPSTR, lpCompStr, dwBufLen);
4242         lpCompStr[dwBufLen/sizeof(WCHAR)] = 0;
4243
4244         ME_InsertTextFromCursor(editor,0,lpCompStr,dwBufLen/sizeof(WCHAR),style);
4245         ME_SetSelection(editor,editor->imeStartIndex,
4246                         editor->imeStartIndex + dwBufLen/sizeof(WCHAR));
4247     }
4248     ME_ReleaseStyle(style);
4249     ME_UpdateRepaint(editor);
4250     return 0;
4251   }
4252   case WM_IME_ENDCOMPOSITION:
4253   {
4254     ME_DeleteSelection(editor);
4255     editor->imeStartIndex=-1;
4256     return 0;
4257   }
4258   case EM_GETOLEINTERFACE:
4259   {
4260     LPVOID *ppvObj = (LPVOID*) lParam;
4261     return CreateIRichEditOle(editor, ppvObj);
4262   }
4263   case EM_GETPASSWORDCHAR:
4264   {
4265     return editor->cPasswordMask;
4266   }
4267   case EM_SETOLECALLBACK:
4268     if(editor->lpOleCallback)
4269       IUnknown_Release(editor->lpOleCallback);
4270     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
4271     if(editor->lpOleCallback)
4272       IUnknown_AddRef(editor->lpOleCallback);
4273     return TRUE;
4274   case EM_GETWORDBREAKPROC:
4275     return (LRESULT)editor->pfnWordBreak;
4276   case EM_SETWORDBREAKPROC:
4277   {
4278     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
4279
4280     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
4281     return (LRESULT)pfnOld;
4282   }
4283   case EM_GETTEXTMODE:
4284     return editor->mode;
4285   case EM_SETTEXTMODE:
4286   {
4287     LRESULT ret;
4288     int mask = 0;
4289     int changes = 0;
4290     GETTEXTLENGTHEX how;
4291
4292     /* CR/LF conversion required in 2.0 mode, verbatim in 1.0 mode */
4293     how.flags = GTL_CLOSE | (editor->bEmulateVersion10 ? 0 : GTL_USECRLF) | GTL_NUMCHARS;
4294     how.codepage = unicode ? 1200 : CP_ACP;
4295     ret = ME_GetTextLengthEx(editor, &how);
4296     if (!ret)
4297     {
4298       /*Check for valid wParam*/
4299       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
4300           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
4301           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
4302         return 1;
4303       else
4304       {
4305         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
4306         {
4307           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
4308           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
4309         }
4310         /*FIXME: Currently no support for undo level and code page options*/ 
4311         editor->mode = (editor->mode & (~mask)) | changes;
4312         return 0;
4313       }
4314     }
4315     return ret;
4316   }
4317   case EM_SETPASSWORDCHAR:
4318   {
4319     editor->cPasswordMask = wParam;
4320     ME_RewrapRepaint(editor);
4321     return 0;
4322   }
4323   case EM_SETTARGETDEVICE:
4324     if (wParam == 0)
4325     {
4326       BOOL new = (lParam == 0 && (editor->styleFlags & ES_MULTILINE));
4327       if (editor->nAvailWidth || editor->bWordWrap != new)
4328       {
4329         editor->bWordWrap = new;
4330         editor->nAvailWidth = 0; /* wrap to client area */
4331         ME_RewrapRepaint(editor);
4332       }
4333     } else {
4334       int width = max(0, lParam);
4335       if ((editor->styleFlags & ES_MULTILINE) &&
4336           (!editor->bWordWrap || editor->nAvailWidth != width))
4337       {
4338         editor->nAvailWidth = width;
4339         editor->bWordWrap = TRUE;
4340         ME_RewrapRepaint(editor);
4341       }
4342       FIXME("EM_SETTARGETDEVICE doesn't use non-NULL target devices\n");
4343     }
4344     return TRUE;
4345   default:
4346   do_default:
4347     *phresult = S_FALSE;
4348     break;
4349   }
4350   return 0L;
4351 }
4352
4353 static LRESULT RichEditWndProc_common(HWND hWnd, UINT msg, WPARAM wParam,
4354                                       LPARAM lParam, BOOL unicode)
4355 {
4356   ME_TextEditor *editor;
4357   HRESULT hresult;
4358   LRESULT lresult = 0;
4359
4360   TRACE("enter hwnd %p msg %04x (%s) %lx %lx, unicode %d\n",
4361         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode);
4362
4363   editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
4364   if (!editor)
4365   {
4366     if (msg == WM_NCCREATE)
4367     {
4368       CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4369       ITextHost *texthost;
4370
4371       TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4372       texthost = ME_CreateTextHost(hWnd, FALSE);
4373       return texthost != NULL;
4374     }
4375     else if (msg != WM_NCDESTROY)
4376     {
4377       ERR("called with invalid hWnd %p - application bug?\n", hWnd);
4378       return 0;
4379     }
4380   }
4381
4382   switch (msg)
4383   {
4384     case WM_PAINT:
4385     {
4386       HDC hDC;
4387       RECT rc;
4388       PAINTSTRUCT ps;
4389
4390       hDC = BeginPaint(editor->hWnd, &ps);
4391       /* Erase area outside of the formatting rectangle */
4392       if (ps.rcPaint.top < editor->rcFormat.top)
4393       {
4394         rc = ps.rcPaint;
4395         rc.bottom = editor->rcFormat.top;
4396         FillRect(hDC, &rc, editor->hbrBackground);
4397         ps.rcPaint.top = editor->rcFormat.top;
4398       }
4399       if (ps.rcPaint.bottom > editor->rcFormat.bottom) {
4400         rc = ps.rcPaint;
4401         rc.top = editor->rcFormat.bottom;
4402         FillRect(hDC, &rc, editor->hbrBackground);
4403         ps.rcPaint.bottom = editor->rcFormat.bottom;
4404       }
4405       if (ps.rcPaint.left < editor->rcFormat.left) {
4406         rc = ps.rcPaint;
4407         rc.right = editor->rcFormat.left;
4408         FillRect(hDC, &rc, editor->hbrBackground);
4409         ps.rcPaint.left = editor->rcFormat.left;
4410       }
4411       if (ps.rcPaint.right > editor->rcFormat.right) {
4412         rc = ps.rcPaint;
4413         rc.left = editor->rcFormat.right;
4414         FillRect(hDC, &rc, editor->hbrBackground);
4415         ps.rcPaint.right = editor->rcFormat.right;
4416       }
4417
4418       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
4419       EndPaint(editor->hWnd, &ps);
4420       return 0;
4421     }
4422     case WM_ERASEBKGND:
4423     {
4424       HDC hDC = (HDC)wParam;
4425       RECT rc;
4426
4427       if (GetUpdateRect(editor->hWnd, &rc, TRUE))
4428         FillRect(hDC, &rc, editor->hbrBackground);
4429       return 1;
4430     }
4431     case EM_SETOPTIONS:
4432     {
4433       DWORD dwStyle;
4434       const DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
4435                          ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN |
4436                          ECO_SELECTIONBAR;
4437       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4438       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4439       dwStyle = (dwStyle & ~mask) | (lresult & mask);
4440       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4441       return lresult;
4442     }
4443     case EM_SETREADONLY:
4444     {
4445       DWORD dwStyle;
4446       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4447       dwStyle = GetWindowLongW(hWnd, GWL_STYLE);
4448       dwStyle &= ~ES_READONLY;
4449       if (wParam)
4450         dwStyle |= ES_READONLY;
4451       SetWindowLongW(hWnd, GWL_STYLE, dwStyle);
4452       return lresult;
4453     }
4454     default:
4455       lresult = ME_HandleMessage(editor, msg, wParam, lParam, unicode, &hresult);
4456   }
4457
4458   if (hresult == S_FALSE)
4459     lresult = DefWindowProcW(hWnd, msg, wParam, lParam);
4460
4461   TRACE("exit hwnd %p msg %04x (%s) %lx %lx, unicode %d -> %lu\n",
4462         hWnd, msg, get_msg_name(msg), wParam, lParam, unicode, lresult);
4463
4464   return lresult;
4465 }
4466
4467 static LRESULT WINAPI RichEditWndProcW(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4468 {
4469     BOOL unicode = TRUE;
4470
4471     /* Under Win9x RichEdit20W returns ANSI strings, see the tests. */
4472     if (msg == WM_GETTEXT && (GetVersion() & 0x80000000))
4473         unicode = FALSE;
4474
4475     return RichEditWndProc_common(hWnd, msg, wParam, lParam, unicode);
4476 }
4477
4478 static LRESULT WINAPI RichEditWndProcA(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4479 {
4480     return RichEditWndProc_common(hWnd, msg, wParam, lParam, FALSE);
4481 }
4482
4483 /******************************************************************
4484  *        RichEditANSIWndProc (RICHED20.10)
4485  */
4486 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4487 {
4488     return RichEditWndProcA(hWnd, msg, wParam, lParam);
4489 }
4490
4491 /******************************************************************
4492  *        RichEdit10ANSIWndProc (RICHED20.9)
4493  */
4494 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
4495 {
4496   if (msg == WM_NCCREATE && !GetWindowLongPtrW(hWnd, 0))
4497   {
4498     ITextHost *texthost;
4499     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
4500
4501     TRACE("WM_NCCREATE: hWnd %p style 0x%08x\n", hWnd, pcs->style);
4502     texthost = ME_CreateTextHost(hWnd, TRUE);
4503     return texthost != NULL;
4504   }
4505   return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
4506 }
4507
4508 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
4509 {
4510   ITextHost_TxNotify(editor->texthost, nCode, NULL);
4511 }
4512
4513 /* Fill buffer with srcChars unicode characters from the start cursor.
4514  *
4515  * buffer: destination buffer
4516  * buflen: length of buffer in characters excluding the NULL terminator.
4517  * start: start of editor text to copy into buffer.
4518  * srcChars: Number of characters to use from the editor text.
4519  * bCRLF: if true, replaces all end of lines with \r\n pairs.
4520  *
4521  * returns the number of characters written excluding the NULL terminator.
4522  *
4523  * The written text is always NULL terminated.
4524  */
4525 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int buflen,
4526                 const ME_Cursor *start, int srcChars, BOOL bCRLF)
4527 {
4528   ME_DisplayItem *pRun, *pNextRun;
4529   const WCHAR *pStart = buffer;
4530   const WCHAR cr_lf[] = {'\r', '\n', 0};
4531   const WCHAR *str;
4532   int nLen;
4533
4534   /* bCRLF flag is only honored in 2.0 and up. 1.0 must always return text verbatim */
4535   if (editor->bEmulateVersion10) bCRLF = 0;
4536
4537   pRun = start->pRun;
4538   assert(pRun);
4539   pNextRun = ME_FindItemFwd(pRun, diRun);
4540
4541   nLen = pRun->member.run.strText->nLen - start->nOffset;
4542   str = pRun->member.run.strText->szData + start->nOffset;
4543
4544   /* No '\r' is appended to the last paragraph. */
4545   while (srcChars && buflen && pNextRun)
4546   {
4547     int nFlags = pRun->member.run.nFlags;
4548
4549     if (bCRLF && nFlags & MERF_ENDPARA && ~nFlags & MERF_ENDCELL)
4550     {
4551       if (buflen == 1) break;
4552       /* FIXME: native fails to reduce srcChars here for WM_GETTEXT or
4553        *        EM_GETTEXTEX, however, this is done for copying text which
4554        *        also uses this function. */
4555       srcChars -= min(nLen, srcChars);
4556       nLen = 2;
4557       str = cr_lf;
4558     } else {
4559       nLen = min(nLen, srcChars);
4560       srcChars -= nLen;
4561     }
4562
4563     nLen = min(nLen, buflen);
4564     buflen -= nLen;
4565
4566     CopyMemory(buffer, str, sizeof(WCHAR) * nLen);
4567
4568     buffer += nLen;
4569
4570     pRun = pNextRun;
4571     pNextRun = ME_FindItemFwd(pRun, diRun);
4572
4573     nLen = pRun->member.run.strText->nLen;
4574     str = pRun->member.run.strText->szData;
4575   }
4576   *buffer = 0;
4577   return buffer - pStart;
4578 }
4579
4580 static BOOL ME_RegisterEditorClass(HINSTANCE hInstance)
4581 {
4582   WNDCLASSW wcW;
4583   WNDCLASSA wcA;
4584   
4585   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4586   wcW.lpfnWndProc = RichEditWndProcW;
4587   wcW.cbClsExtra = 0;
4588   wcW.cbWndExtra = sizeof(ME_TextEditor *);
4589   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
4590   wcW.hIcon = NULL;
4591   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4592   wcW.hbrBackground = GetStockObject(NULL_BRUSH);
4593   wcW.lpszMenuName = NULL;
4594
4595   if (is_version_nt())
4596   {
4597     wcW.lpszClassName = RICHEDIT_CLASS20W;
4598     if (!RegisterClassW(&wcW)) return FALSE;
4599     wcW.lpszClassName = MSFTEDIT_CLASS;
4600     if (!RegisterClassW(&wcW)) return FALSE;
4601   }
4602   else
4603   {
4604     /* WNDCLASSA/W have the same layout */
4605     wcW.lpszClassName = (LPCWSTR)"RichEdit20W";
4606     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4607     wcW.lpszClassName = (LPCWSTR)"RichEdit50W";
4608     if (!RegisterClassA((WNDCLASSA *)&wcW)) return FALSE;
4609   }
4610
4611   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
4612   wcA.lpfnWndProc = RichEditWndProcA;
4613   wcA.cbClsExtra = 0;
4614   wcA.cbWndExtra = sizeof(ME_TextEditor *);
4615   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
4616   wcA.hIcon = NULL;
4617   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
4618   wcA.hbrBackground = GetStockObject(NULL_BRUSH);
4619   wcA.lpszMenuName = NULL;
4620   wcA.lpszClassName = RICHEDIT_CLASS20A;
4621   if (!RegisterClassA(&wcA)) return FALSE;
4622   wcA.lpszClassName = "RichEdit50A";
4623   if (!RegisterClassA(&wcA)) return FALSE;
4624
4625   return TRUE;
4626 }
4627
4628 static LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4629   /* FIXME: Not implemented */
4630   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4631         hWnd, msg, get_msg_name(msg), wParam, lParam);
4632   return DefWindowProcW(hWnd, msg, wParam, lParam);
4633 }
4634
4635 static LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
4636   /* FIXME: Not implemented */
4637   TRACE("hWnd %p msg %04x (%s) %08lx %08lx\n",
4638         hWnd, msg, get_msg_name(msg), wParam, lParam);
4639   return DefWindowProcW(hWnd, msg, wParam, lParam);
4640 }
4641
4642 /******************************************************************
4643  *        REExtendedRegisterClass (RICHED20.8)
4644  *
4645  * FIXME undocumented
4646  * Need to check for errors and implement controls and callbacks 
4647  */
4648 LRESULT WINAPI REExtendedRegisterClass(void)
4649 {
4650   WNDCLASSW wcW;
4651   UINT result;
4652
4653   FIXME("semi stub\n");
4654
4655   wcW.cbClsExtra = 0;
4656   wcW.cbWndExtra = 4;
4657   wcW.hInstance = NULL;
4658   wcW.hIcon = NULL;
4659   wcW.hCursor = NULL;
4660   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
4661   wcW.lpszMenuName = NULL;
4662
4663   if (!ME_ListBoxRegistered)
4664   {
4665       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
4666       wcW.lpfnWndProc = REListWndProc;
4667       wcW.lpszClassName = REListBox20W;
4668       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
4669   }
4670
4671   if (!ME_ComboBoxRegistered)
4672   {
4673       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
4674       wcW.lpfnWndProc = REComboWndProc;
4675       wcW.lpszClassName = REComboBox20W;
4676       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
4677   }
4678
4679   result = 0;
4680   if (ME_ListBoxRegistered)
4681       result += 1;
4682   if (ME_ComboBoxRegistered)
4683       result += 2;
4684
4685   return result;
4686 }
4687
4688 static BOOL isurlspecial(WCHAR c)
4689 {
4690   static const WCHAR special_chars[] = {'.','/','%','@','*','|','\\','+','#',0};
4691   return strchrW( special_chars, c ) != NULL;
4692 }
4693
4694 /**
4695  * This proc takes a selection, and scans it forward in order to select the span
4696  * of a possible URL candidate. A possible URL candidate must start with isalnum
4697  * or one of the following special characters: *|/\+%#@ and must consist entirely
4698  * of the characters allowed to start the URL, plus : (colon) which may occur
4699  * at most once, and not at either end.
4700  */
4701 static BOOL ME_FindNextURLCandidate(ME_TextEditor *editor,
4702                                     const ME_Cursor *start,
4703                                     int nChars,
4704                                     ME_Cursor *candidate_min,
4705                                     ME_Cursor *candidate_max)
4706 {
4707   ME_Cursor cursor = *start;
4708   BOOL foundColon = FALSE;
4709   BOOL candidateStarted = FALSE;
4710   WCHAR lastAcceptedChar = '\0';
4711
4712   while (nChars > 0)
4713   {
4714     WCHAR *strStart = cursor.pRun->member.run.strText->szData;
4715     WCHAR *str = strStart + cursor.nOffset;
4716     int nLen = cursor.pRun->member.run.strText->nLen - cursor.nOffset;
4717     nChars -= nLen;
4718
4719     if (~cursor.pRun->member.run.nFlags & MERF_ENDPARA)
4720     {
4721       /* Find start of candidate */
4722       if (!candidateStarted)
4723       {
4724         while (nLen)
4725         {
4726           nLen--;
4727           if (isalnumW(*str) || isurlspecial(*str))
4728           {
4729             cursor.nOffset = str - strStart;
4730             *candidate_min = cursor;
4731             candidateStarted = TRUE;
4732             lastAcceptedChar = *str++;
4733             break;
4734           }
4735           str++;
4736         }
4737       }
4738
4739       /* Find end of candidate */
4740       if (candidateStarted) {
4741         while (nLen)
4742         {
4743           nLen--;
4744           if (*str == ':' && !foundColon) {
4745             foundColon = TRUE;
4746           } else if (!isalnumW(*str) && !isurlspecial(*str)) {
4747             cursor.nOffset = str - strStart;
4748             if (lastAcceptedChar == ':')
4749               ME_MoveCursorChars(editor, &cursor, -1);
4750             *candidate_max = cursor;
4751             return TRUE;
4752           }
4753           lastAcceptedChar = *str++;
4754         }
4755       }
4756     } else {
4757       /* End of paragraph: skip it if before candidate span, or terminates
4758          current active span */
4759       if (candidateStarted) {
4760         if (lastAcceptedChar == ':')
4761           ME_MoveCursorChars(editor, &cursor, -1);
4762         *candidate_max = cursor;
4763         return TRUE;
4764       }
4765     }
4766
4767     /* Reaching this point means no span was found, so get next span */
4768     if (!ME_NextRun(&cursor.pPara, &cursor.pRun)) {
4769       if (candidateStarted) {
4770         /* There are no further runs, so take end of text as end of candidate */
4771         cursor.nOffset = str - strStart;
4772         if (lastAcceptedChar == ':')
4773           ME_MoveCursorChars(editor, &cursor, -1);
4774         *candidate_max = cursor;
4775         return TRUE;
4776       }
4777       *candidate_max = *candidate_min = cursor;
4778       return FALSE;
4779     }
4780     cursor.nOffset = 0;
4781   }
4782
4783   if (candidateStarted) {
4784     /* There are no further runs, so take end of text as end of candidate */
4785     if (lastAcceptedChar == ':')
4786       ME_MoveCursorChars(editor, &cursor, -1);
4787     *candidate_max = cursor;
4788     return TRUE;
4789   }
4790   *candidate_max = *candidate_min = cursor;
4791   return FALSE;
4792 }
4793
4794 /**
4795  * This proc evaluates the selection and returns TRUE if it can be considered an URL
4796  */
4797 static BOOL ME_IsCandidateAnURL(ME_TextEditor *editor, const ME_Cursor *start, int nChars)
4798 {
4799 #define MAX_PREFIX_LEN 9
4800   struct prefix_s {
4801     const WCHAR text[MAX_PREFIX_LEN];
4802     int length;
4803   }prefixes[] = {
4804     {{'p','r','o','s','p','e','r','o',':'}, 9},
4805     {{'t','e','l','n','e','t',':'}, 7},
4806     {{'g','o','p','h','e','r',':'}, 7},
4807     {{'m','a','i','l','t','o',':'}, 7},
4808     {{'h','t','t','p','s',':'}, 6},
4809     {{'f','i','l','e',':'}, 5},
4810     {{'n','e','w','s',':'}, 5},
4811     {{'w','a','i','s',':'}, 5},
4812     {{'n','n','t','p',':'}, 5},
4813     {{'h','t','t','p',':'}, 5},
4814     {{'w','w','w','.'}, 4},
4815     {{'f','t','p',':'}, 4},
4816   };
4817   WCHAR bufferW[MAX_PREFIX_LEN + 1];
4818   unsigned int i;
4819
4820   ME_GetTextW(editor, bufferW, MAX_PREFIX_LEN, start, nChars, 0);
4821   for (i = 0; i < sizeof(prefixes) / sizeof(*prefixes); i++)
4822   {
4823     if (nChars < prefixes[i].length) continue;
4824     if (!memcmp(prefixes[i].text, bufferW, prefixes[i].length * sizeof(WCHAR)))
4825       return TRUE;
4826   }
4827   return FALSE;
4828 #undef MAX_PREFIX_LEN
4829 }
4830
4831 /**
4832  * This proc walks through the indicated selection and evaluates whether each
4833  * section identified by ME_FindNextURLCandidate and in-between sections have
4834  * their proper CFE_LINK attributes set or unset. If the CFE_LINK attribute is
4835  * not what it is supposed to be, this proc sets or unsets it as appropriate.
4836  *
4837  * Since this function can cause runs to be split, do not depend on the value
4838  * of the start cursor at the end of the function.
4839  *
4840  * nChars may be set to INT_MAX to update to the end of the text.
4841  *
4842  * Returns TRUE if at least one section was modified.
4843  */
4844 static BOOL ME_UpdateLinkAttribute(ME_TextEditor *editor, ME_Cursor *start, int nChars)
4845 {
4846   BOOL modified = FALSE;
4847   ME_Cursor startCur = *start;
4848
4849   if (!editor->AutoURLDetect_bEnable) return FALSE;
4850
4851   do
4852   {
4853     CHARFORMAT2W link;
4854     ME_Cursor candidateStart, candidateEnd;
4855
4856     if (ME_FindNextURLCandidate(editor, &startCur, nChars,
4857                                 &candidateStart, &candidateEnd))
4858     {
4859       /* Section before candidate is not an URL */
4860       int cMin = ME_GetCursorOfs(&candidateStart);
4861       int cMax = ME_GetCursorOfs(&candidateEnd);
4862
4863       if (!ME_IsCandidateAnURL(editor, &candidateStart, cMax - cMin))
4864         candidateStart = candidateEnd;
4865       nChars -= cMax - ME_GetCursorOfs(&startCur);
4866     }
4867     else
4868     {
4869       /* No more candidates until end of selection */
4870       nChars = 0;
4871     }
4872
4873     if (startCur.pRun != candidateStart.pRun ||
4874         startCur.nOffset != candidateStart.nOffset)
4875     {
4876       /* CFE_LINK effect should be consistently unset */
4877       link.cbSize = sizeof(link);
4878       ME_GetCharFormat(editor, &startCur, &candidateStart, &link);
4879       if (!(link.dwMask & CFM_LINK) || (link.dwEffects & CFE_LINK))
4880       {
4881         /* CFE_LINK must be unset from this range */
4882         memset(&link, 0, sizeof(CHARFORMAT2W));
4883         link.cbSize = sizeof(link);
4884         link.dwMask = CFM_LINK;
4885         link.dwEffects = 0;
4886         ME_SetCharFormat(editor, &startCur, &candidateStart, &link);
4887         /* Update candidateEnd since setting character formats may split
4888          * runs, which can cause a cursor to be at an invalid offset within
4889          * a split run. */
4890         while (candidateEnd.nOffset >= candidateEnd.pRun->member.run.strText->nLen)
4891         {
4892           candidateEnd.nOffset -= candidateEnd.pRun->member.run.strText->nLen;
4893           candidateEnd.pRun = ME_FindItemFwd(candidateEnd.pRun, diRun);
4894         }
4895         modified = TRUE;
4896       }
4897     }
4898     if (candidateStart.pRun != candidateEnd.pRun ||
4899         candidateStart.nOffset != candidateEnd.nOffset)
4900     {
4901       /* CFE_LINK effect should be consistently set */
4902       link.cbSize = sizeof(link);
4903       ME_GetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4904       if (!(link.dwMask & CFM_LINK) || !(link.dwEffects & CFE_LINK))
4905       {
4906         /* CFE_LINK must be set on this range */
4907         memset(&link, 0, sizeof(CHARFORMAT2W));
4908         link.cbSize = sizeof(link);
4909         link.dwMask = CFM_LINK;
4910         link.dwEffects = CFE_LINK;
4911         ME_SetCharFormat(editor, &candidateStart, &candidateEnd, &link);
4912         modified = TRUE;
4913       }
4914     }
4915     startCur = candidateEnd;
4916   } while (nChars > 0);
4917   return modified;
4918 }