msi: Only insert entries into listbox if property value matches.
[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  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /* 
24   API implementation status:
25   
26   Messages (ANSI versions not done yet)
27   + EM_AUTOURLDETECT 2.0
28   + EM_CANPASTE
29   + EM_CANREDO 2.0
30   + EM_CANUNDO
31   + EM_CHARFROMPOS
32   - EM_DISPLAYBAND
33   + EM_EMPTYUNDOBUFFER
34   + EM_EXGETSEL
35   + EM_EXLIMITTEXT
36   + EM_EXLINEFROMCHAR
37   + EM_EXSETSEL
38   + EM_FINDTEXT (only FR_DOWN flag implemented)
39   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
40   - EM_FINDWORDBREAK
41   - EM_FMTLINES
42   - EM_FORMATRANGE
43   + EM_GETAUTOURLDETECT 2.0
44   - EM_GETBIDIOPTIONS 3.0
45   - EM_GETCHARFORMAT (partly done)
46   - EM_GETEDITSTYLE
47   + EM_GETEVENTMASK
48   + EM_GETFIRSTVISIBLELINE (can be optimized if needed)
49   - EM_GETIMECOLOR 1.0asian
50   - EM_GETIMECOMPMODE 2.0
51   - EM_GETIMEOPTIONS 1.0asian
52   - EM_GETIMESTATUS
53   - EM_GETLANGOPTIONS 2.0
54   + EM_GETLIMITTEXT
55   + EM_GETLINE
56   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
57   + EM_GETMODIFY
58   - EM_GETOLEINTERFACE
59   + EM_GETOPTIONS
60   + EM_GETPARAFORMAT
61   + EM_GETPASSWORDCHAR 2.0
62   - EM_GETPUNCTUATION 1.0asian
63   + EM_GETRECT
64   - EM_GETREDONAME 2.0
65   + EM_GETSEL
66   + EM_GETSELTEXT (ANSI&Unicode)
67   + EM_GETSCROLLPOS 3.0 (only Y value valid)
68 ! - EM_GETTHUMB
69   - EM_GETTEXTEX 2.0
70   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
71   - EM_GETTEXTMODE 2.0
72 ? + EM_GETTEXTRANGE (ANSI&Unicode)
73   - EM_GETTYPOGRAPHYOPTIONS 3.0
74   - EM_GETUNDONAME
75   + EM_GETWORDBREAKPROC
76   - EM_GETWORDBREAKPROCEX
77   - EM_GETWORDWRAPMODE 1.0asian
78   + EM_GETZOOM 3.0
79   + EM_HIDESELECTION
80   + EM_LIMITTEXT (Also called EM_SETLIMITTEXT)
81   + EM_LINEFROMCHAR
82   + EM_LINEINDEX
83   + EM_LINELENGTH
84   + EM_LINESCROLL
85   - EM_PASTESPECIAL
86   + EM_POSFROMCHAR
87   + EM_REDO 2.0
88   + EM_REQUESTRESIZE
89   + EM_REPLACESEL (proper style?) ANSI&Unicode
90   + EM_SCROLL
91   + EM_SCROLLCARET
92   - EM_SELECTIONTYPE
93   - EM_SETBIDIOPTIONS 3.0
94   + EM_SETBKGNDCOLOR
95   + EM_SETCHARFORMAT (partly done, no ANSI)
96   - EM_SETEDITSTYLE
97   + EM_SETEVENTMASK (few notifications supported)
98   - EM_SETFONTSIZE
99   - EM_SETIMECOLOR 1.0asian
100   - EM_SETIMEOPTIONS 1.0asian
101   - EM_SETLANGOPTIONS 2.0
102   - EM_SETLIMITTEXT
103   + EM_SETMODIFY (not sure if implementation is correct)
104   - EM_SETOLECALLBACK
105   + EM_SETOPTIONS (partially implemented)
106   - EM_SETPALETTE 2.0
107   + EM_SETPARAFORMAT
108   + EM_SETPASSWORDCHAR 2.0
109   - EM_SETPUNCTUATION 1.0asian
110   + EM_SETREADONLY no beep on modification attempt
111   + EM_SETRECT
112   + EM_SETRECTNP (EM_SETRECT without repainting)
113   + EM_SETSEL
114   + EM_SETSCROLLPOS 3.0
115   - EM_SETTABSTOPS 3.0
116   - EM_SETTARGETDEVICE
117   + EM_SETTEXTEX 3.0 (unicode only, no rich text insertion handling, proper style?)
118   - EM_SETTEXTMODE 2.0
119   - EM_SETTYPOGRAPHYOPTIONS 3.0
120   + EM_SETUNDOLIMIT 2.0
121   + EM_SETWORDBREAKPROC (used only for word movement at the moment)
122   - EM_SETWORDBREAKPROCEX
123   - EM_SETWORDWRAPMODE 1.0asian
124   + EM_SETZOOM 3.0
125   + EM_SHOWSCROLLBAR 2.0
126   - EM_STOPGROUPTYPING 2.0
127   + EM_STREAMIN
128   + EM_STREAMOUT
129   + EM_UNDO
130   + WM_CHAR
131   + WM_CLEAR
132   + WM_COPY
133   + WM_CUT
134   + WM_GETDLGCODE (the current implementation is incomplete)
135   + WM_GETTEXT (ANSI&Unicode)
136   + WM_GETTEXTLENGTH (ANSI version sucks)
137   + WM_PASTE
138   + WM_SETFONT
139   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
140   - WM_STYLECHANGING
141   - WM_STYLECHANGED (things like read-only flag)
142   - WM_UNICHAR
143   
144   Notifications
145   
146   * EN_CHANGE (sent from the wrong place)
147   - EN_CORRECTTEXT
148   - EN_DROPFILES
149   - EN_ERRSPACE
150   - EN_HSCROLL
151   - EN_IMECHANGE
152   + EN_KILLFOCUS
153   - EN_LINK
154   - EN_MAXTEXT
155   - EN_MSGFILTER
156   - EN_OLEOPFAILED
157   - EN_PROTECTED
158   + EN_REQUESTRESIZE
159   - EN_SAVECLIPBOARD
160   + EN_SELCHANGE 
161   + EN_SETFOCUS
162   - EN_STOPNOUNDO
163   * EN_UPDATE (sent from the wrong place)
164   - EN_VSCROLL
165   
166   Styles
167   
168   - ES_AUTOHSCROLL
169   - ES_AUTOVSCROLL
170   - ES_CENTER
171   + ES_DISABLENOSCROLL (scrollbar is always visible)
172   - ES_EX_NOCALLOLEINIT
173   - ES_LEFT
174   - ES_MULTILINE (currently single line controls aren't supported)
175   - ES_NOIME
176   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
177   - ES_RIGHT
178   - ES_SAVESEL
179   - ES_SELFIME
180   - ES_SUNKEN
181   - ES_VERTICAL
182   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
183   - WS_SETFONT
184   - WS_HSCROLL
185   + WS_VSCROLL
186 */
187
188 /*
189  * RICHED20 TODO (incomplete):
190  *
191  * - messages/styles/notifications listed above 
192  * - Undo coalescing 
193  * - add remaining CHARFORMAT/PARAFORMAT fields
194  * - right/center align should strip spaces from the beginning
195  * - pictures/OLE objects (not just smiling faces that lack API support ;-) )
196  * - COM interface (looks like a major pain in the TODO list)
197  * - calculate heights of pictures (half-done)
198  * - horizontal scrolling (not even started)
199  * - hysteresis during wrapping (related to scrollbars appearing/disappearing)
200  * - find/replace
201  * - how to implement EM_FORMATRANGE and EM_DISPLAYBAND ? (Mission Impossible)
202  * - italic caret with italic fonts
203  * - IME
204  * - most notifications aren't sent at all (the most important ones are)
205  * - when should EN_SELCHANGE be sent after text change ? (before/after EN_UPDATE?)
206  * - WM_SETTEXT may use wrong style (but I'm 80% sure it's OK)
207  * - EM_GETCHARFORMAT with SCF_SELECTION may not behave 100% like in original (but very close)
208  * - full justification
209  * - hyphenation
210  * - tables
211  * - ListBox & ComboBox not implemented
212  *
213  * Bugs that are probably fixed, but not so easy to verify:
214  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
215  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
216  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
217  * - caret shouldn't be displayed when selection isn't empty
218  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
219  * - undo for setting default format (done, might be buggy)
220  * - styles might be not released properly (looks like they work like charm, but who knows?
221  *
222  */
223
224 #include "editor.h"
225 #include "commdlg.h"
226 #include "winreg.h"
227 #define NO_SHLWAPI_STREAM 
228 #include "shlwapi.h"
229 #include "imm.h"
230 #include "textserv.h"
231 #include "rtf.h"
232
233 #define STACK_SIZE_DEFAULT  100
234 #define STACK_SIZE_MAX     1000
235
236 #define TEXT_LIMIT_DEFAULT 32767
237  
238 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
239
240 int me_debug = 0;
241 HANDLE me_heap = NULL;
242
243 static BOOL ME_ListBoxRegistered = FALSE;
244 static BOOL ME_ComboBoxRegistered = FALSE;
245
246 static ME_TextBuffer *ME_MakeText(void) {
247   
248   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
249
250   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
251   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
252   
253   p1->prev = NULL;
254   p1->next = p2;
255   p2->prev = p1;
256   p2->next = NULL;
257   p1->member.para.next_para = p2;
258   p2->member.para.prev_para = p1;
259   p2->member.para.nCharOfs = 0;  
260   
261   buf->pFirst = p1;
262   buf->pLast = p2;
263   buf->pCharStyle = NULL;
264   
265   return buf;
266 }
267
268
269 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
270 {
271   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
272   WCHAR *pText;
273   
274   TRACE("%08x %p\n", dwFormat, stream);
275   
276   do {
277     long nWideChars = 0;
278
279     if (!stream->dwSize)
280     {
281       ME_StreamInFill(stream);
282       if (stream->editstream->dwError)
283         break;
284       if (!stream->dwSize)
285         break;
286     }
287       
288     if (!(dwFormat & SF_UNICODE))
289     {
290       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
291       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
292       pText = wszText;
293     }
294     else
295     {
296       nWideChars = stream->dwSize >> 1;
297       pText = (WCHAR *)stream->buffer;
298     }
299     
300     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
301     if (stream->dwSize == 0)
302       break;
303     stream->dwSize = 0;
304   } while(1);
305   ME_CommitUndo(editor);
306   ME_UpdateRepaint(editor);
307   return 0;
308 }
309
310 static void ME_RTFCharAttrHook(RTF_Info *info)
311 {
312   CHARFORMAT2W fmt;
313   fmt.cbSize = sizeof(fmt);
314   fmt.dwMask = 0;
315   fmt.dwEffects = 0;
316
317   switch(info->rtfMinor)
318   {
319     case rtfPlain:
320       /* FIXME add more flags once they're implemented */
321       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
322       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
323       fmt.yHeight = 12*20; /* 12pt */
324       fmt.wWeight = 400;
325       break;
326     case rtfBold:
327       fmt.dwMask = CFM_BOLD;
328       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
329       break;
330     case rtfItalic:
331       fmt.dwMask = CFM_ITALIC;
332       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
333       break;
334     case rtfUnderline:
335       fmt.dwMask = CFM_UNDERLINE;
336       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
337       fmt.bUnderlineType = CFU_CF1UNDERLINE;
338       break;
339     case rtfNoUnderline:
340       fmt.dwMask = CFM_UNDERLINE;
341       fmt.dwEffects = 0;
342       break;
343     case rtfStrikeThru:
344       fmt.dwMask = CFM_STRIKEOUT;
345       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
346       break;
347     case rtfSubScript:
348     case rtfSuperScript:
349     case rtfSubScrShrink:
350     case rtfSuperScrShrink:
351     case rtfNoSuperSub:
352       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
353       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
354       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
355       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
356       break;
357     case rtfInvisible:
358       fmt.dwMask = CFM_HIDDEN;
359       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
360       break;
361     case rtfBackColor:
362       fmt.dwMask = CFM_BACKCOLOR;
363       fmt.dwEffects = 0;
364       if (info->rtfParam == 0)
365         fmt.dwEffects = CFE_AUTOBACKCOLOR;
366       else if (info->rtfParam != rtfNoParam)
367       {
368         RTFColor *c = RTFGetColor(info, info->rtfParam);
369         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
370       }
371       break;
372     case rtfForeColor:
373       fmt.dwMask = CFM_COLOR;
374       fmt.dwEffects = 0;
375       if (info->rtfParam == 0)
376         fmt.dwEffects = CFE_AUTOCOLOR;
377       else if (info->rtfParam != rtfNoParam)
378       {
379         RTFColor *c = RTFGetColor(info, info->rtfParam);
380         if (c)
381           fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
382         else
383           fmt.crTextColor = 0;
384       }
385       break;
386     case rtfFontNum:
387       if (info->rtfParam != rtfNoParam)
388       {
389         RTFFont *f = RTFGetFont(info, info->rtfParam);
390         if (f)
391         {
392           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
393           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
394           fmt.bCharSet = f->rtfFCharSet;
395           fmt.dwMask = CFM_FACE | CFM_CHARSET;
396         }
397       }
398       break;
399     case rtfFontSize:
400       fmt.dwMask = CFM_SIZE;
401       if (info->rtfParam != rtfNoParam)
402         fmt.yHeight = info->rtfParam*10;
403       break;
404   }
405   if (fmt.dwMask) {
406     ME_Style *style2;
407     RTFFlushOutputBuffer(info);
408     /* FIXME too slow ? how come ? */
409     style2 = ME_ApplyStyle(info->style, &fmt);
410     ME_ReleaseStyle(info->style);
411     info->style = style2;
412     info->styleChanged = TRUE;
413   }
414 }
415
416 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
417    the same tags mean different things in different contexts */
418 static void ME_RTFParAttrHook(RTF_Info *info)
419 {
420   PARAFORMAT2 fmt;
421   fmt.cbSize = sizeof(fmt);
422   fmt.dwMask = 0;
423   
424   switch(info->rtfMinor)
425   {
426   case rtfParDef: /* restores default paragraph attributes */
427     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
428     fmt.wAlignment = PFA_LEFT;
429     fmt.cTabCount = 0;
430     fmt.dxOffset = fmt.dxStartIndent = 0;
431     RTFFlushOutputBuffer(info);
432     ME_GetParagraph(info->editor->pCursors[0].pRun)->member.para.bTable = FALSE;
433     break;
434   case rtfInTable:
435   {
436     ME_DisplayItem *para;
437     
438     RTFFlushOutputBuffer(info);
439     para = ME_GetParagraph(info->editor->pCursors[0].pRun);
440     assert(para->member.para.pCells);
441     para->member.para.bTable = TRUE;
442     return;
443   }
444   case rtfFirstIndent:
445     ME_GetSelectionParaFormat(info->editor, &fmt);
446     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
447     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
448     fmt.dxOffset = -info->rtfParam;
449     break;
450   case rtfLeftIndent:
451     ME_GetSelectionParaFormat(info->editor, &fmt);
452     fmt.dwMask = PFM_STARTINDENT;
453     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
454     break;
455   case rtfRightIndent:
456     fmt.dwMask = PFM_RIGHTINDENT;
457     fmt.dxRightIndent = info->rtfParam;
458     break;
459   case rtfQuadLeft:
460   case rtfQuadJust:
461     fmt.dwMask = PFM_ALIGNMENT;
462     fmt.wAlignment = PFA_LEFT;
463     break;
464   case rtfQuadRight:
465     fmt.dwMask = PFM_ALIGNMENT;
466     fmt.wAlignment = PFA_RIGHT;
467     break;
468   case rtfQuadCenter:
469     fmt.dwMask = PFM_ALIGNMENT;
470     fmt.wAlignment = PFA_CENTER;
471     break;
472   case rtfTabPos:
473     ME_GetSelectionParaFormat(info->editor, &fmt);
474     if (!(fmt.dwMask & PFM_TABSTOPS))
475     {
476       fmt.dwMask |= PFM_TABSTOPS;
477       fmt.cTabCount = 0;
478     }
479     if (fmt.cTabCount < MAX_TAB_STOPS)
480       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
481     break;
482   }  
483   if (fmt.dwMask) {
484     RTFFlushOutputBuffer(info);
485     /* FIXME too slow ? how come ?*/
486     ME_SetSelectionParaFormat(info->editor, &fmt);
487   }
488 }
489
490 static void ME_RTFTblAttrHook(RTF_Info *info)
491 {
492   ME_DisplayItem *para;
493   
494   switch (info->rtfMinor)
495   {
496     case rtfRowDef:
497       RTFFlushOutputBuffer(info);
498       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
499       
500       /* Release possibly inherited cell definitions */
501       ME_DestroyTableCellList(para);
502       
503       para->member.para.pCells = ALLOC_OBJ(ME_TableCell);
504       para->member.para.pCells->nRightBoundary = 0;
505       para->member.para.pCells->next = NULL;
506       para->member.para.pLastCell = para->member.para.pCells;
507       break;
508     case rtfCellPos:
509       RTFFlushOutputBuffer(info);
510       para = ME_GetParagraph(info->editor->pCursors[0].pRun);
511       
512       if (para->member.para.pLastCell->nRightBoundary)
513       {
514         ME_TableCell *pCell = ALLOC_OBJ(ME_TableCell);
515         
516         pCell->next = NULL;
517         para->member.para.pLastCell->next = pCell;
518         para->member.para.pLastCell = pCell;
519       }
520       para->member.para.pLastCell->nRightBoundary = info->rtfParam;
521       break;
522   }
523 }
524
525 static void ME_RTFReadHook(RTF_Info *info) {
526   switch(info->rtfClass)
527   {
528     case rtfGroup:
529       switch(info->rtfMajor)
530       {
531         case rtfBeginGroup:
532           if (info->stackTop < maxStack) {
533             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
534             info->stack[info->stackTop].codePage = info->codePage;
535             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
536           }
537           info->stackTop++;
538           info->styleChanged = FALSE;
539           break;
540         case rtfEndGroup:
541         {
542           ME_Style *s;
543           RTFFlushOutputBuffer(info);
544           if (info->stackTop<=1) {
545             info->rtfClass = rtfEOF;
546             return;
547           }
548           info->stackTop--;
549           assert(info->stackTop >= 0);
550           if (info->styleChanged)
551           {
552             /* FIXME too slow ? how come ? */
553             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
554             ME_ReleaseStyle(info->style);
555             info->style = s;
556             info->codePage = info->stack[info->stackTop].codePage;
557             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
558           }
559           break;
560         }
561       }
562       break;
563     case rtfControl:
564       switch(info->rtfMajor)
565       {
566         case rtfCharAttr:
567           ME_RTFCharAttrHook(info);
568           break;
569         case rtfParAttr:
570           ME_RTFParAttrHook(info);
571           break;
572         case rtfTblAttr:
573           ME_RTFTblAttrHook(info);
574           break;
575         case rtfSpecialChar:
576           if (info->rtfMinor == rtfCell)
577           {
578             RTFFlushOutputBuffer(info);
579             ME_InsertTableCellFromCursor(info->editor, 0);
580           }
581       }
582       break;
583   }
584 }
585
586 void
587 ME_StreamInFill(ME_InStream *stream)
588 {
589   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
590                                                                 (BYTE *)stream->buffer,
591                                                                 sizeof(stream->buffer),
592                                                                 (LONG *)&stream->dwSize);
593   stream->dwUsed = 0;
594 }
595
596 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
597 {
598   RTF_Info parser;
599   ME_Style *style;
600   int from, to, to2, nUndoMode;
601   int nEventMask = editor->nEventMask;
602   ME_InStream inStream;
603
604   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
605   editor->nEventMask = 0;
606   
607   ME_GetSelection(editor, &from, &to);
608   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
609     style = ME_GetSelectionInsertStyle(editor);
610
611     ME_InternalDeleteText(editor, from, to-from);
612   }
613   else {
614     style = editor->pBuffer->pDefaultStyle;
615     ME_AddRefStyle(style);
616     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
617     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
618     from = to = 0;
619     ME_ClearTempStyle(editor);
620     /* FIXME restore default paragraph formatting ! */
621   }
622
623
624   /* Back up undo mode to a local variable */
625   nUndoMode = editor->nUndoMode;
626
627   /* Only create an undo if SFF_SELECTION is set */
628   if (!(format & SFF_SELECTION))
629     editor->nUndoMode = umIgnore;
630
631   inStream.editstream = stream;
632   inStream.editstream->dwError = 0;
633   inStream.dwSize = 0;
634   inStream.dwUsed = 0;
635
636   if (format & SF_RTF)
637   {
638     /* Check if it's really RTF, and if it is not, use plain text */
639     ME_StreamInFill(&inStream);
640     if (!inStream.editstream->dwError)
641     {
642       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
643       {
644         format &= ~SF_RTF;
645         format |= SF_TEXT;
646       }
647     }
648   }
649
650   if (!inStream.editstream->dwError)
651   {
652     if (format & SF_RTF) {
653       /* setup the RTF parser */
654       memset(&parser, 0, sizeof parser);
655       RTFSetEditStream(&parser, &inStream);
656       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
657       parser.hwndEdit = editor->hWnd;
658       parser.editor = editor;
659       parser.style = style;
660       WriterInit(&parser);
661       RTFInit(&parser);
662       RTFSetReadHook(&parser, ME_RTFReadHook);
663       BeginFile(&parser);
664   
665       /* do the parsing */
666       RTFRead(&parser);
667       RTFFlushOutputBuffer(&parser);
668       RTFDestroy(&parser);
669
670       style = parser.style;
671     }
672     else if (format & SF_TEXT)
673       ME_StreamInText(editor, format, &inStream, style);
674     else
675       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
676     ME_GetSelection(editor, &to, &to2);
677     /* put the cursor at the top */
678     if (!(format & SFF_SELECTION))
679       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
680   }
681
682   /* Restore saved undo mode */
683   editor->nUndoMode = nUndoMode;
684
685   /* even if we didn't add an undo, we need to commit anything on the stack */
686   ME_CommitUndo(editor);
687
688   /* If SFF_SELECTION isn't set, delete any undos from before we started too */
689   if (!(format & SFF_SELECTION))
690     ME_EmptyUndoStack(editor);
691
692   ME_ReleaseStyle(style);
693   editor->nEventMask = nEventMask;
694   if (editor->bRedraw)
695   {
696     ME_UpdateRepaint(editor);
697   }
698   if (!(format & SFF_SELECTION)) {
699     ME_ClearTempStyle(editor);
700   }
701   ME_MoveCaret(editor);
702   ME_SendSelChange(editor);
703   ME_SendRequestResize(editor, FALSE);
704
705   return 0;
706 }
707
708
709 typedef struct tagME_RTFStringStreamStruct
710 {
711   char *string;
712   int pos;
713   int length;
714 } ME_RTFStringStreamStruct;
715
716 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
717 {
718   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
719   int count;
720
721   count = min(cb, pStruct->length - pStruct->pos);
722   memmove(lpBuff, pStruct->string + pStruct->pos, count);
723   pStruct->pos += count;
724   *pcb = count;
725   return 0;
726 }
727
728 static void
729 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
730 {
731   EDITSTREAM es;
732   ME_RTFStringStreamStruct data;
733
734   data.string = string;
735   data.length = strlen(string);
736   data.pos = 0;
737   es.dwCookie = (DWORD)&data;
738   es.pfnCallback = ME_ReadFromRTFString;
739   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
740 }
741
742
743 ME_DisplayItem *
744 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
745 {
746   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
747   
748   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
749     item = ME_FindItemFwd(item, diParagraph);
750
751   if (!item)
752     return item;
753
754   nOffset -= item->member.para.nCharOfs;
755   if (nItemType == diParagraph) {
756     if (nItemOffset)
757       *nItemOffset = nOffset;
758     return item;
759   }
760   
761   do {
762     item = ME_FindItemFwd(item, diRun);
763   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
764   if (item) {
765     nOffset -= item->member.run.nCharOfs;
766     if (nItemOffset)
767       *nItemOffset = nOffset;
768   }
769   return item;
770 }
771
772
773 static int
774 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
775 {
776   const int nLen = lstrlenW(text);
777   const int nTextLen = ME_GetTextLength(editor);
778   int nStart, nEnd;
779   int nMin, nMax;
780   ME_DisplayItem *item;
781   ME_DisplayItem *para;
782   WCHAR wLastChar = ' ';
783
784   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
785         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
786   
787   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
788     FIXME("Flags 0x%08x not implemented\n",
789         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
790
791   nMin = chrg->cpMin;
792   if (chrg->cpMax == -1)
793     nMax = nTextLen;
794   else
795     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
796   
797   /* when searching up, if cpMin < cpMax, then instead of searching
798    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
799    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
800    * case, it is always bigger than cpMin.
801    */
802   if (!(flags & FR_DOWN))
803   {
804     int nSwap = nMax;
805
806     nMax = nMin > nTextLen ? nTextLen : nMin;
807     if (nMin < nSwap || chrg->cpMax == -1)
808       nMin = 0;
809     else
810       nMin = nSwap;
811   }
812
813   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
814   {
815     if (chrgText)
816       chrgText->cpMin = chrgText->cpMax = -1;
817     return -1;
818   }
819  
820   if (flags & FR_DOWN) /* Forward search */
821   {
822     /* If possible, find the character before where the search starts */
823     if ((flags & FR_WHOLEWORD) && nMin)
824     {
825       nStart = nMin - 1;
826       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
827       if (!item)
828       {
829         if (chrgText)
830           chrgText->cpMin = chrgText->cpMax = -1;
831         return -1;
832       }
833       wLastChar = item->member.run.strText->szData[nStart];
834     }
835
836     nStart = nMin;
837     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
838     if (!item)
839     {
840       if (chrgText)
841         chrgText->cpMin = chrgText->cpMax = -1;
842       return -1;
843     }
844
845     para = ME_GetParagraph(item);
846     while (item
847            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
848     {
849       ME_DisplayItem *pCurItem = item;
850       int nCurStart = nStart;
851       int nMatched = 0;
852     
853       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
854       {
855         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
856           break;
857
858         nMatched++;
859         if (nMatched == nLen)
860         {
861           ME_DisplayItem *pNextItem = pCurItem;
862           int nNextStart = nCurStart;
863           WCHAR wNextChar;
864
865           /* Check to see if next character is a whitespace */
866           if (flags & FR_WHOLEWORD)
867           {
868             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
869             {
870               pNextItem = ME_FindItemFwd(pCurItem, diRun);
871               nNextStart = -nMatched;
872             }
873
874             if (pNextItem)
875               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
876             else
877               wNextChar = ' ';
878
879             if (isalnumW(wNextChar))
880               break;
881           }
882
883           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
884           if (chrgText)
885           {
886             chrgText->cpMin = nStart;
887             chrgText->cpMax = nStart + nLen;
888           }
889           TRACE("found at %d-%d\n", nStart, nStart + nLen);
890           return nStart;
891         }
892         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
893         {
894           pCurItem = ME_FindItemFwd(pCurItem, diRun);
895           para = ME_GetParagraph(pCurItem);
896           nCurStart = -nMatched;
897         }
898       }
899       if (pCurItem)
900         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
901       else
902         wLastChar = ' ';
903
904       nStart++;
905       if (nStart == ME_StrLen(item->member.run.strText))
906       {
907         item = ME_FindItemFwd(item, diRun);
908         para = ME_GetParagraph(item);
909         nStart = 0;
910       }
911     }
912   }
913   else /* Backward search */
914   {
915     /* If possible, find the character after where the search ends */
916     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
917     {
918       nEnd = nMax + 1;
919       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
920       if (!item)
921       {
922         if (chrgText)
923           chrgText->cpMin = chrgText->cpMax = -1;
924         return -1;
925       }
926       wLastChar = item->member.run.strText->szData[nEnd];
927     }
928
929     nEnd = nMax;
930     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
931     if (!item)
932     {
933       if (chrgText)
934         chrgText->cpMin = chrgText->cpMax = -1;
935       return -1;
936     }
937     
938     para = ME_GetParagraph(item);
939     
940     while (item
941            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
942     {
943       ME_DisplayItem *pCurItem = item;
944       int nCurEnd = nEnd;
945       int nMatched = 0;
946       
947       if (nCurEnd - nMatched == 0)
948       {
949         pCurItem = ME_FindItemBack(pCurItem, diRun);
950         para = ME_GetParagraph(pCurItem);
951         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
952       }
953       
954       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
955       {
956         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
957           break;
958
959         nMatched++;
960         if (nMatched == nLen)
961         {
962           ME_DisplayItem *pPrevItem = pCurItem;
963           int nPrevEnd = nCurEnd;
964           WCHAR wPrevChar;
965
966           /* Check to see if previous character is a whitespace */
967           if (flags & FR_WHOLEWORD)
968           {
969             if (nPrevEnd - nMatched == 0)
970             {
971               pPrevItem = ME_FindItemBack(pCurItem, diRun);
972               if (pPrevItem)
973                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
974             }
975
976             if (pPrevItem)
977               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
978             else
979               wPrevChar = ' ';
980
981             if (isalnumW(wPrevChar))
982               break;
983           }
984
985           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
986           if (chrgText)
987           {
988             chrgText->cpMin = nStart;
989             chrgText->cpMax = nStart + nLen;
990           }
991           TRACE("found at %d-%d\n", nStart, nStart + nLen);
992           return nStart;
993         }
994         if (nCurEnd - nMatched == 0)
995         {
996           pCurItem = ME_FindItemBack(pCurItem, diRun);
997           /* Don't care about pCurItem becoming NULL here; it's already taken
998            * care of in the exterior loop condition */
999           para = ME_GetParagraph(pCurItem);
1000           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1001         }
1002       }
1003       if (pCurItem)
1004         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1005       else
1006         wLastChar = ' ';
1007
1008       nEnd--;
1009       if (nEnd < 0)
1010       {
1011         item = ME_FindItemBack(item, diRun);
1012         para = ME_GetParagraph(item);
1013         nEnd = ME_StrLen(item->member.run.strText);
1014       }
1015     }
1016   }
1017   TRACE("not found\n");
1018   if (chrgText)
1019     chrgText->cpMin = chrgText->cpMax = -1;
1020   return -1;
1021 }
1022
1023
1024 static BOOL
1025 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1026 {
1027   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1028   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1029   
1030   switch (nKey)
1031   {
1032     case VK_LEFT:
1033     case VK_RIGHT:
1034     case VK_UP:
1035     case VK_DOWN:
1036     case VK_HOME:
1037     case VK_END:
1038     case VK_PRIOR:
1039     case VK_NEXT:
1040       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1041       return TRUE;
1042     case VK_BACK:
1043     case VK_DELETE:
1044       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1045       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1046         return FALSE;
1047       if (ME_IsSelection(editor))
1048         ME_DeleteSelection(editor);
1049       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1050         ME_DeleteTextAtCursor(editor, 1, 1);
1051       else
1052         return TRUE;
1053       ME_CommitUndo(editor);
1054       ME_UpdateRepaint(editor);
1055       ME_SendRequestResize(editor, FALSE);
1056       return TRUE;
1057
1058     default:
1059       if (ctrl_is_down)
1060       {
1061         if (nKey == 'W')
1062         {
1063           CHARFORMAT2W chf;
1064           char buf[2048];
1065           chf.cbSize = sizeof(chf);
1066           
1067           ME_GetSelectionCharFormat(editor, &chf);
1068           ME_DumpStyleToBuf(&chf, buf);
1069           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1070         }
1071         if (nKey == 'Q')
1072         {
1073           ME_CheckCharOffsets(editor);
1074         }
1075       }
1076   }
1077   return FALSE;
1078 }
1079
1080 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1081 {
1082   CHARRANGE selrange;
1083   HMENU menu;
1084   int seltype = 0;
1085   if(!editor->lpOleCallback)
1086     return FALSE;
1087   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1088   if(selrange.cpMin == selrange.cpMax)
1089     seltype |= SEL_EMPTY;
1090   else
1091   {
1092     /* FIXME: Handle objects */
1093     seltype |= SEL_TEXT;
1094     if(selrange.cpMax-selrange.cpMin > 1)
1095       seltype |= SEL_MULTICHAR;
1096   }
1097   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1098   {
1099     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1100     DestroyMenu(menu);
1101   }
1102   return TRUE;
1103 }
1104
1105 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1106   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1107   HDC hDC;
1108   int i;
1109   ed->hWnd = hWnd;
1110   ed->bEmulateVersion10 = FALSE;
1111   ed->pBuffer = ME_MakeText();
1112   hDC = GetDC(hWnd);
1113   ME_MakeFirstParagraph(hDC, ed->pBuffer);
1114   ReleaseDC(hWnd, hDC);
1115   ed->bCaretShown = FALSE;
1116   ed->nCursors = 2;
1117   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1118   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1119   ed->pCursors[0].nOffset = 0;
1120   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1121   ed->pCursors[1].nOffset = 0;
1122   ed->nLastTotalLength = ed->nTotalLength = 0;
1123   ed->nUDArrowX = -1;
1124   ed->nSequence = 0;
1125   ed->rgbBackColor = -1;
1126   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1127   ed->bCaretAtEnd = FALSE;
1128   ed->nEventMask = 0;
1129   ed->nModifyStep = 0;
1130   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1131   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1132   ed->nUndoStackSize = 0;
1133   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1134   ed->nUndoMode = umAddToUndo;
1135   ed->nParagraphs = 1;
1136   ed->nLastSelStart = ed->nLastSelEnd = 0;
1137   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1138   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1139   ed->bRedraw = TRUE;
1140   ed->bHideSelection = FALSE;
1141   ed->nInvalidOfs = -1;
1142   ed->pfnWordBreak = NULL;
1143   ed->lpOleCallback = NULL;
1144   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1145   ed->AutoURLDetect_bEnable = FALSE;
1146   GetClientRect(hWnd, &ed->rcFormat);
1147   for (i=0; i<HFONT_CACHE_SIZE; i++)
1148   {
1149     ed->pFontCache[i].nRefs = 0;
1150     ed->pFontCache[i].nAge = 0;
1151     ed->pFontCache[i].hFont = NULL;
1152   }
1153   
1154   ME_CheckCharOffsets(ed);
1155   
1156   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1157     ed->cPasswordMask = '*';
1158   else
1159     ed->cPasswordMask = 0;
1160   
1161   return ed;
1162 }
1163
1164 typedef struct tagME_GlobalDestStruct
1165 {
1166   HGLOBAL hData;
1167   int nLength;
1168 } ME_GlobalDestStruct;
1169
1170 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1171 {
1172   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1173   int i;
1174   WORD *pSrc, *pDest;
1175   
1176   cb = cb >> 1;
1177   pDest = (WORD *)lpBuff;
1178   pSrc = (WORD *)GlobalLock(pData->hData);
1179   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1180     pDest[i] = pSrc[pData->nLength+i];
1181   }    
1182   pData->nLength += i;
1183   *pcb = 2*i;
1184   GlobalUnlock(pData->hData);
1185   return 0;
1186 }
1187
1188 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1189 {
1190   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1191   int i;
1192   BYTE *pSrc, *pDest;
1193   
1194   pDest = lpBuff;
1195   pSrc = (BYTE *)GlobalLock(pData->hData);
1196   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1197     pDest[i] = pSrc[pData->nLength+i];
1198   }    
1199   pData->nLength += i;
1200   *pcb = i;
1201   GlobalUnlock(pData->hData);
1202   return 0;
1203 }
1204
1205
1206 void ME_DestroyEditor(ME_TextEditor *editor)
1207 {
1208   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1209   ME_DisplayItem *p = pFirst, *pNext = NULL;
1210   int i;
1211
1212   ME_ClearTempStyle(editor);
1213   ME_EmptyUndoStack(editor);
1214   while(p) {
1215     pNext = p->next;
1216     ME_DestroyDisplayItem(p);
1217     p = pNext;
1218   }
1219   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1220   for (i=0; i<HFONT_CACHE_SIZE; i++)
1221   {
1222     if (editor->pFontCache[i].hFont)
1223       DeleteObject(editor->pFontCache[i].hFont);
1224   }
1225   DeleteObject(editor->hbrBackground);
1226   if(editor->lpOleCallback)
1227     IUnknown_Release(editor->lpOleCallback);
1228
1229   FREE_OBJ(editor->pBuffer);
1230   FREE_OBJ(editor->pCursors);
1231
1232   FREE_OBJ(editor);
1233 }
1234
1235 static const WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
1236 static const WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
1237 static const WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
1238 static const WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
1239
1240 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1241 {
1242     TRACE("\n");
1243     switch (fdwReason)
1244     {
1245     case DLL_PROCESS_ATTACH:
1246       DisableThreadLibraryCalls(hinstDLL);
1247       me_heap = HeapCreate (0, 0x10000, 0);
1248       ME_RegisterEditorClass(hinstDLL);
1249       LookupInit();
1250       break;
1251
1252     case DLL_PROCESS_DETACH:
1253       UnregisterClassW(wszClassName, 0);
1254       UnregisterClassW(wszClassName50, 0);
1255       UnregisterClassA("RichEdit20A", 0);
1256       UnregisterClassA("RichEdit50A", 0);
1257       if (ME_ListBoxRegistered)
1258           UnregisterClassW(wszClassNameListBox, 0);
1259       if (ME_ComboBoxRegistered)
1260           UnregisterClassW(wszClassNameComboBox, 0);
1261       LookupCleanup();
1262       HeapDestroy (me_heap);
1263       me_heap = NULL;
1264       break;
1265     }
1266     return TRUE;
1267 }
1268
1269
1270 #define UNSUPPORTED_MSG(e) \
1271   case e: \
1272     FIXME(#e ": stub\n"); \
1273     return DefWindowProcW(hWnd, msg, wParam, lParam);
1274
1275 static const char * const edit_messages[] = {
1276   "EM_GETSEL",
1277   "EM_SETSEL",
1278   "EM_GETRECT",
1279   "EM_SETRECT",
1280   "EM_SETRECTNP",
1281   "EM_SCROLL",
1282   "EM_LINESCROLL",
1283   "EM_SCROLLCARET",
1284   "EM_GETMODIFY",
1285   "EM_SETMODIFY",
1286   "EM_GETLINECOUNT",
1287   "EM_LINEINDEX",
1288   "EM_SETHANDLE",
1289   "EM_GETHANDLE",
1290   "EM_GETTHUMB",
1291   "EM_UNKNOWN_BF",
1292   "EM_UNKNOWN_C0",
1293   "EM_LINELENGTH",
1294   "EM_REPLACESEL",
1295   "EM_UNKNOWN_C3",
1296   "EM_GETLINE",
1297   "EM_LIMITTEXT",
1298   "EM_CANUNDO",
1299   "EM_UNDO",
1300   "EM_FMTLINES",
1301   "EM_LINEFROMCHAR",
1302   "EM_UNKNOWN_CA",
1303   "EM_SETTABSTOPS",
1304   "EM_SETPASSWORDCHAR",
1305   "EM_EMPTYUNDOBUFFER",
1306   "EM_GETFIRSTVISIBLELINE",
1307   "EM_SETREADONLY",
1308   "EM_SETWORDBREAKPROC",
1309   "EM_GETWORDBREAKPROC",
1310   "EM_GETPASSWORDCHAR",
1311   "EM_SETMARGINS",
1312   "EM_GETMARGINS",
1313   "EM_GETLIMITTEXT",
1314   "EM_POSFROMCHAR",
1315   "EM_CHARFROMPOS"
1316 };
1317
1318 static const char * const richedit_messages[] = {
1319   "EM_CANPASTE",
1320   "EM_DISPLAYBAND",
1321   "EM_EXGETSEL",
1322   "EM_EXLIMITTEXT",
1323   "EM_EXLINEFROMCHAR",
1324   "EM_EXSETSEL",
1325   "EM_FINDTEXT",
1326   "EM_FORMATRANGE",
1327   "EM_GETCHARFORMAT",
1328   "EM_GETEVENTMASK",
1329   "EM_GETOLEINTERFACE",
1330   "EM_GETPARAFORMAT",
1331   "EM_GETSELTEXT",
1332   "EM_HIDESELECTION", 
1333   "EM_PASTESPECIAL",
1334   "EM_REQUESTRESIZE",
1335   "EM_SELECTIONTYPE",
1336   "EM_SETBKGNDCOLOR",
1337   "EM_SETCHARFORMAT",
1338   "EM_SETEVENTMASK",
1339   "EM_SETOLECALLBACK",
1340   "EM_SETPARAFORMAT",
1341   "EM_SETTARGETDEVICE",
1342   "EM_STREAMIN",
1343   "EM_STREAMOUT",
1344   "EM_GETTEXTRANGE",
1345   "EM_FINDWORDBREAK",
1346   "EM_SETOPTIONS",
1347   "EM_GETOPTIONS",
1348   "EM_FINDTEXTEX",
1349   "EM_GETWORDBREAKPROCEX",
1350   "EM_SETWORDBREAKPROCEX",
1351   "EM_SETUNDOLIMIT",
1352   "EM_UNKNOWN_USER_83",
1353   "EM_REDO",
1354   "EM_CANREDO",
1355   "EM_GETUNDONAME",
1356   "EM_GETREDONAME",
1357   "EM_STOPGROUPTYPING",
1358   "EM_SETTEXTMODE",
1359   "EM_GETTEXTMODE",
1360   "EM_AUTOURLDETECT",
1361   "EM_GETAUTOURLDETECT",
1362   "EM_SETPALETTE",
1363   "EM_GETTEXTEX",
1364   "EM_GETTEXTLENGTHEX",
1365   "EM_SHOWSCROLLBAR",
1366   "EM_SETTEXTEX",
1367   "EM_UNKNOWN_USER_98",
1368   "EM_UNKNOWN_USER_99",
1369   "EM_SETPUNCTUATION",
1370   "EM_GETPUNCTUATION",
1371   "EM_SETWORDWRAPMODE",
1372   "EM_GETWORDWRAPMODE",
1373   "EM_SETIMECOLOR",
1374   "EM_GETIMECOLOR",
1375   "EM_SETIMEOPTIONS",
1376   "EM_GETIMEOPTIONS",
1377   "EM_CONVPOSITION",
1378   "EM_UNKNOWN_USER_109",
1379   "EM_UNKNOWN_USER_110",
1380   "EM_UNKNOWN_USER_111",
1381   "EM_UNKNOWN_USER_112",
1382   "EM_UNKNOWN_USER_113",
1383   "EM_UNKNOWN_USER_114",
1384   "EM_UNKNOWN_USER_115",
1385   "EM_UNKNOWN_USER_116",
1386   "EM_UNKNOWN_USER_117",
1387   "EM_UNKNOWN_USER_118",
1388   "EM_UNKNOWN_USER_119",
1389   "EM_SETLANGOPTIONS",
1390   "EM_GETLANGOPTIONS",
1391   "EM_GETIMECOMPMODE",
1392   "EM_FINDTEXTW",
1393   "EM_FINDTEXTEXW",
1394   "EM_RECONVERSION",
1395   "EM_SETIMEMODEBIAS",
1396   "EM_GETIMEMODEBIAS"
1397 };
1398
1399 static const char *
1400 get_msg_name(UINT msg)
1401 {
1402   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1403     return edit_messages[msg - EM_GETSEL];
1404   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1405     return richedit_messages[msg - EM_CANPASTE];
1406   return "";
1407 }
1408
1409 /******************************************************************
1410  *        RichEditANSIWndProc (RICHED20.10)
1411  */
1412 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1413   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1414   
1415   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1416         hWnd, msg, get_msg_name(msg), wParam, lParam);
1417   
1418   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1419     ERR("RichEditANSIWndProc called with invalid hWnd %p - application bug?\n", hWnd);
1420     return 0; 
1421   }
1422
1423   switch(msg) {
1424   
1425   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1426   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1427   UNSUPPORTED_MSG(EM_FMTLINES)
1428   UNSUPPORTED_MSG(EM_FORMATRANGE)
1429   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1430   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1431   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1432   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1433   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1434   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1435   UNSUPPORTED_MSG(EM_GETREDONAME)
1436   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1437   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1438   UNSUPPORTED_MSG(EM_GETUNDONAME)
1439   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1440   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1441   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1442   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1443   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1444   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1445   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1446   UNSUPPORTED_MSG(EM_SETPALETTE)
1447   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1448   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1449   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1450   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1451   UNSUPPORTED_MSG(WM_STYLECHANGING)
1452   UNSUPPORTED_MSG(WM_STYLECHANGED)
1453 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1454     
1455 /* Messages specific to Richedit controls */
1456   
1457   case EM_STREAMIN:
1458    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1459   case EM_STREAMOUT:
1460    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1461   case WM_GETDLGCODE:
1462   {
1463     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1464     if(lParam && (((LPMSG)lParam)->message == WM_KEYDOWN))
1465     {
1466       int vk = (int)((LPMSG)lParam)->wParam;
1467       /* if style says we want return key */
1468       if((vk == VK_RETURN) && (GetWindowLongW(hWnd, GWL_STYLE) & ES_WANTRETURN))
1469       {
1470         code |= DLGC_WANTMESSAGE;
1471       }
1472       /* we always handle ctrl-tab */
1473       if((vk == VK_TAB) && (GetKeyState(VK_CONTROL) & 0x8000))
1474       {
1475         code |= DLGC_WANTMESSAGE;
1476       }
1477     }
1478     return code;
1479   }
1480   case WM_NCCREATE:
1481   {
1482     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1483     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1484     editor = ME_MakeEditor(hWnd);
1485     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1486     pcs = 0; /* ignore */
1487     return TRUE;
1488   }
1489   case EM_EMPTYUNDOBUFFER:
1490     ME_EmptyUndoStack(editor);
1491     return 0;
1492   case EM_GETSEL:
1493   {
1494     /* Note: wParam/lParam can be NULL */
1495     UINT from, to;
1496     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1497     PUINT pto = lParam ? (PUINT)lParam : &to;
1498     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1499     if ((*pfrom|*pto) & 0xFFFF0000)
1500       return -1;
1501     return MAKELONG(*pfrom,*pto);
1502   }
1503   case EM_EXGETSEL:
1504   {
1505     CHARRANGE *pRange = (CHARRANGE *)lParam;
1506     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1507     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
1508     return 0;
1509   }
1510   case EM_SETUNDOLIMIT:
1511   {
1512     if ((int)wParam < 0)
1513       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1514     else
1515       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1516     /* Setting a max stack size keeps wine from getting killed 
1517       for hogging memory. Windows allocates all this memory at once, so
1518       no program would realistically set a value above our maxiumum. */  
1519     return editor->nUndoLimit;
1520   }
1521   case EM_CANUNDO:
1522     return editor->pUndoStack != NULL;
1523   case EM_CANREDO:
1524     return editor->pRedoStack != NULL;
1525   case WM_UNDO: /* FIXME: actually not the same */
1526   case EM_UNDO:
1527     ME_Undo(editor);
1528     return 0;
1529   case EM_REDO:
1530     ME_Redo(editor);
1531     return 0;
1532   case EM_GETOPTIONS:
1533   {
1534     /* these flags are equivalent to the ES_* counterparts */
1535     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1536                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1537     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1538
1539     return settings;
1540   }
1541   case EM_SETOPTIONS:
1542   {
1543     /* these flags are equivalent to ES_* counterparts                      
1544      * ECO_READONLY is already implemented in the code, only requires 
1545      * setting the bit to work                                        
1546      */
1547     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1548                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1549     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1550     DWORD settings = mask & raw;
1551
1552     switch(wParam)
1553     {
1554       case ECOOP_SET:
1555         settings = lParam;
1556         break;
1557       case ECOOP_OR:
1558         settings |= lParam;
1559         break;
1560       case ECOOP_AND:
1561         settings &= lParam;
1562         break;
1563       case ECOOP_XOR:
1564         settings ^= lParam;
1565     }
1566     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1567
1568     if (lParam & ECO_AUTOWORDSELECTION)
1569       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1570     if (lParam & ECO_SELECTIONBAR)
1571       FIXME("ECO_SELECTIONBAR not implemented yet!\n");
1572     if (lParam & ECO_VERTICAL)
1573       FIXME("ECO_VERTICAL not implemented yet!\n");
1574     if (lParam & ECO_AUTOHSCROLL)
1575       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1576     if (lParam & ECO_AUTOVSCROLL)
1577       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1578     if (lParam & ECO_NOHIDESEL)
1579       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1580     if (lParam & ECO_WANTRETURN)
1581       FIXME("ECO_WANTRETURN not implemented yet!\n");
1582
1583     return settings;
1584   }
1585   case EM_SETSEL:
1586   {
1587     ME_InvalidateSelection(editor);
1588     ME_SetSelection(editor, wParam, lParam);
1589     ME_InvalidateSelection(editor);
1590     ME_SendSelChange(editor);
1591     return 0;
1592   }
1593   case EM_SETSCROLLPOS:
1594   {
1595     POINT *point = (POINT *)lParam;
1596     ME_ScrollAbs(editor, point->y);
1597     return 0;
1598   }
1599   case EM_AUTOURLDETECT:
1600   {
1601     if (wParam==1 || wParam ==0) 
1602     {
1603         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1604         return 0;
1605     }
1606     return E_INVALIDARG;
1607   }
1608   case EM_GETAUTOURLDETECT:
1609   {
1610     return editor->AutoURLDetect_bEnable;
1611   }
1612   case EM_EXSETSEL:
1613   {
1614     int end;
1615     CHARRANGE range = *(CHARRANGE *)lParam;
1616
1617     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
1618
1619     ME_InvalidateSelection(editor);
1620     end = ME_SetSelection(editor, range.cpMin, range.cpMax);
1621     ME_InvalidateSelection(editor);
1622     ME_SendSelChange(editor);
1623
1624     return end;
1625   }
1626   case EM_SHOWSCROLLBAR:
1627   {
1628     ShowScrollBar(editor->hWnd, wParam, lParam);
1629     return 0;
1630   }
1631   case EM_SETTEXTEX:
1632   {
1633     LPWSTR wszText = (LPWSTR)lParam;
1634     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1635     size_t len = wszText ? lstrlenW(wszText) : 0;
1636     int from, to;
1637     ME_Style *style;
1638     int oldModify = editor->nModifyStep;
1639     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1640     if (pStruct->codepage != 1200) {
1641       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1642       return 0;
1643     }
1644     /* FIXME: this should support RTF strings too, according to MSDN */
1645     if (pStruct->flags & ST_SELECTION) {
1646       ME_GetSelection(editor, &from, &to);
1647       style = ME_GetSelectionInsertStyle(editor);
1648       ME_InternalDeleteText(editor, from, to - from);
1649       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1650       ME_ReleaseStyle(style);
1651     }
1652     else {
1653       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1654       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1655       len = 1;
1656     }
1657     ME_CommitUndo(editor);
1658     if (!(pStruct->flags & ST_KEEPUNDO))
1659     {
1660       editor->nModifyStep = oldModify;
1661       ME_EmptyUndoStack(editor);
1662     }
1663     ME_UpdateRepaint(editor);
1664     return len;
1665   }
1666   case EM_SETBKGNDCOLOR:
1667   {
1668     LRESULT lColor = ME_GetBackColor(editor);
1669     if (editor->rgbBackColor != -1)
1670       DeleteObject(editor->hbrBackground);
1671     if (wParam)
1672     {
1673       editor->rgbBackColor = -1;
1674       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1675     }
1676     else
1677     {
1678       editor->rgbBackColor = lParam;
1679       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1680     }
1681     if (editor->bRedraw)
1682     {
1683       InvalidateRect(hWnd, NULL, TRUE);
1684       UpdateWindow(hWnd);
1685     }
1686     return lColor;
1687   }
1688   case EM_GETMODIFY:
1689     return editor->nModifyStep == 0 ? 0 : 1;
1690   case EM_SETMODIFY:
1691   {
1692     if (wParam)
1693       editor->nModifyStep = 1;
1694     else
1695       editor->nModifyStep = 0;
1696     
1697     return 0;
1698   }
1699   case EM_SETREADONLY:
1700   {
1701     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1702     if (wParam)
1703       nStyle |= ES_READONLY;
1704     else
1705       nStyle &= ~ES_READONLY;
1706     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1707     return 0;
1708   }
1709   case EM_SETEVENTMASK:
1710   {
1711     DWORD nOldMask = editor->nEventMask;
1712     
1713     editor->nEventMask = lParam;
1714     return nOldMask;
1715   }
1716   case EM_GETEVENTMASK:
1717     return editor->nEventMask;
1718   case EM_SETCHARFORMAT:
1719   {
1720     CHARFORMAT2W buf, *p;
1721     BOOL bRepaint = TRUE;
1722     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1723     if (!wParam || (editor->mode & TM_PLAINTEXT))
1724       ME_SetDefaultCharFormat(editor, p);
1725     else if (wParam == (SCF_WORD | SCF_SELECTION))
1726       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1727     else if (wParam == SCF_ALL)
1728       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1729     else {
1730       int from, to;
1731       ME_GetSelection(editor, &from, &to);
1732       bRepaint = (from != to);
1733       ME_SetSelectionCharFormat(editor, p);
1734     }
1735     editor->nModifyStep = 1;
1736     ME_CommitUndo(editor);
1737     if (bRepaint)
1738       ME_RewrapRepaint(editor);
1739     return 0;
1740   }
1741   case EM_GETCHARFORMAT:
1742   {
1743     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1744     if (dst->cbSize != sizeof(CHARFORMATA) &&
1745         dst->cbSize != sizeof(CHARFORMATW) &&
1746         dst->cbSize != sizeof(CHARFORMAT2A) &&
1747         dst->cbSize != sizeof(CHARFORMAT2W))
1748       return 0;
1749     tmp.cbSize = sizeof(tmp);
1750     if (!wParam)
1751       ME_GetDefaultCharFormat(editor, &tmp);
1752     else
1753       ME_GetSelectionCharFormat(editor, &tmp);
1754     ME_CopyToCFAny(dst, &tmp);
1755     return tmp.dwMask;
1756   }
1757   case EM_SETPARAFORMAT:
1758     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1759     ME_RewrapRepaint(editor);
1760     ME_CommitUndo(editor);
1761     return 0;
1762   case EM_GETPARAFORMAT:
1763     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1764     return 0;
1765   case EM_GETFIRSTVISIBLELINE:
1766   {
1767     ME_DisplayItem *p = editor->pBuffer->pFirst;
1768     int y = ME_GetYScrollPos(editor);
1769     int ypara = 0;
1770     int count = 0;
1771     int ystart, yend;
1772     while(p) {
1773       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1774       if (p->type == diTextEnd)
1775         break;
1776       if (p->type == diParagraph) {
1777         ypara = p->member.para.nYPos;
1778         continue;
1779       }
1780       ystart = ypara + p->member.row.nYPos;
1781       yend = ystart + p->member.row.nHeight;
1782       if (y < yend) {
1783         break;
1784       }
1785       count++;
1786     }
1787     return count;
1788   }
1789   case EM_HIDESELECTION:
1790   {
1791      editor->bHideSelection = (wParam != 0);
1792      ME_InvalidateSelection(editor);
1793      return 0;
1794   }
1795   case EM_LINESCROLL:
1796   {
1797     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1798     return TRUE; /* Should return false if a single line richedit control */
1799   }
1800   case WM_CLEAR:
1801   {
1802     int from, to;
1803     ME_GetSelection(editor, &from, &to);
1804     ME_InternalDeleteText(editor, from, to-from);
1805     ME_CommitUndo(editor);
1806     ME_UpdateRepaint(editor);
1807     return 0;
1808   }
1809   case EM_REPLACESEL:
1810   {
1811     int from, to;
1812     ME_Style *style;
1813     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1814     size_t len = lstrlenW(wszText);
1815     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1816
1817     ME_GetSelection(editor, &from, &to);
1818     style = ME_GetSelectionInsertStyle(editor);
1819     ME_InternalDeleteText(editor, from, to-from);
1820     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1821     ME_ReleaseStyle(style);
1822     /* drop temporary style if line end */
1823     /*
1824      * FIXME question: does abc\n mean: put abc,
1825      * clear temp style, put \n? (would require a change)
1826      */
1827     if (len>0 && wszText[len-1] == '\n')
1828       ME_ClearTempStyle(editor);
1829     ME_EndToUnicode(hWnd, wszText);
1830     ME_CommitUndo(editor);
1831     if (!wParam)
1832       ME_EmptyUndoStack(editor);
1833     ME_UpdateRepaint(editor);
1834     return 0;
1835   }
1836   case EM_SCROLLCARET:
1837   {
1838     int top, bottom; /* row's edges relative to document top */
1839     int nPos;
1840     ME_DisplayItem *para, *row;
1841     
1842     nPos = ME_GetYScrollPos(editor);
1843     row = ME_RowStart(editor->pCursors[0].pRun);
1844     para = ME_GetParagraph(row);
1845     top = para->member.para.nYPos + row->member.row.nYPos;
1846     bottom = top + row->member.row.nHeight;
1847     
1848     if (top < nPos) /* caret above window */
1849       ME_ScrollAbs(editor,  top);
1850     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1851       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1852     return 0;
1853   }
1854   case WM_SETFONT:
1855   {
1856     LOGFONTW lf;
1857     CHARFORMAT2W fmt;
1858     HDC hDC;
1859     BOOL bRepaint = LOWORD(lParam);
1860     
1861     if (!wParam)
1862       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1863     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1864     hDC = GetDC(hWnd);
1865     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1866     ReleaseDC(hWnd, hDC);   
1867     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1868     ME_SetDefaultCharFormat(editor, &fmt);
1869
1870     ME_CommitUndo(editor);
1871     if (bRepaint)
1872       ME_RewrapRepaint(editor);
1873     return 0;
1874   }
1875   case WM_SETTEXT:
1876   {
1877     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1878     if (lParam)
1879     {
1880       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1881       if (!IsWindowUnicode(hWnd) && !strncmp((char *)lParam, "{\\rtf", 5))
1882       {
1883         /* Undocumented: WM_SETTEXT supports RTF text */
1884         ME_StreamInRTFString(editor, 0, (char *)lParam);
1885       }
1886       else
1887       {
1888         LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1889         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1890         if (lstrlenW(wszText) > 0)
1891         {
1892           /* uses default style! */
1893           ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1894         }
1895         ME_EndToUnicode(hWnd, wszText);
1896       }
1897     }
1898     else
1899       TRACE("WM_SETTEXT - NULL\n");
1900     ME_CommitUndo(editor);
1901     ME_EmptyUndoStack(editor);
1902     ME_SetSelection(editor, 0, 0);
1903     ME_UpdateRepaint(editor);
1904     return 0;
1905   }
1906   case EM_CANPASTE:
1907   {
1908     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1909     if (IsClipboardFormatAvailable(nRTFFormat))
1910       return TRUE;
1911     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1912       return TRUE;
1913     return FALSE;
1914   }
1915   case WM_PASTE:
1916   {    
1917     DWORD dwFormat = 0;
1918     EDITSTREAM es;
1919     ME_GlobalDestStruct gds;
1920     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1921     UINT cf = 0;
1922
1923     if (IsClipboardFormatAvailable(nRTFFormat))
1924       cf = nRTFFormat, dwFormat = SF_RTF;
1925     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1926       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1927     else
1928       return 0;
1929
1930     if (!OpenClipboard(hWnd))
1931       return 0;
1932     gds.hData = GetClipboardData(cf);
1933     gds.nLength = 0;
1934     es.dwCookie = (DWORD)&gds;
1935     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1936     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
1937
1938     CloseClipboard();
1939     return 0;
1940   }
1941   case WM_CUT:
1942   case WM_COPY:
1943   {
1944     LPDATAOBJECT dataObj = NULL;
1945     CHARRANGE range;
1946     HRESULT hr = S_OK;
1947     
1948     if (editor->cPasswordMask)
1949       return 0; /* Copying or Cutting masked text isn't allowed */
1950     
1951     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
1952     if(editor->lpOleCallback)
1953         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
1954     if(FAILED(hr) || !dataObj)
1955         hr = ME_GetDataObject(editor, &range, &dataObj);
1956     if(SUCCEEDED(hr)) {
1957         hr = OleSetClipboard(dataObj);
1958         IDataObject_Release(dataObj);
1959     }
1960     if (SUCCEEDED(hr) && msg == WM_CUT)
1961     {
1962       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
1963       ME_CommitUndo(editor);
1964       ME_UpdateRepaint(editor);
1965     }
1966     return 0;
1967   }
1968   case WM_GETTEXTLENGTH:
1969     return ME_GetTextLength(editor);
1970   case EM_GETTEXTLENGTHEX:
1971     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1972   case WM_GETTEXT:
1973   {
1974     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1975     tr.chrg.cpMin = 0;
1976     tr.chrg.cpMax = wParam-1;
1977     tr.lpstrText = (WCHAR *)lParam;
1978     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1979   }
1980   case EM_GETTEXTEX:
1981   {
1982     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1983     int nStart, nCount;
1984
1985     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1986       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1987
1988     if (ex->flags & GT_SELECTION)
1989     {
1990       ME_GetSelection(editor, &nStart, &nCount);
1991       nCount -= nStart;
1992       nCount = min(nCount, ex->cb - 1);
1993     }
1994     else
1995     {
1996       nStart = 0;
1997       nCount = ex->cb - 1;
1998     }
1999     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
2000     {
2001       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
2002       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
2003     }
2004     else
2005     {
2006       /* potentially each char may be a CR, why calculate the exact value with O(N) when
2007         we can just take a bigger buffer? :) */
2008       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2009       LPWSTR buffer = richedit_alloc((crlfmul*nCount + 1) * sizeof(WCHAR));
2010       DWORD buflen = ex->cb;
2011       LRESULT rc;
2012       DWORD flags = 0;
2013
2014       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2015       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2016
2017       richedit_free(buffer);
2018       return rc;
2019     }
2020   }
2021   case EM_GETSELTEXT:
2022   {
2023     int from, to;
2024     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2025     ME_GetSelection(editor, &from, &to);
2026     tr.chrg.cpMin = from;
2027     tr.chrg.cpMax = to;
2028     tr.lpstrText = (WCHAR *)lParam;
2029     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2030   }
2031   case EM_GETSCROLLPOS:
2032   {
2033       POINT *point = (POINT *)lParam;
2034       point->x = 0; /* FIXME side scrolling not implemented */
2035       point->y = ME_GetYScrollPos(editor);
2036       return 1;
2037   }
2038   case EM_GETTEXTRANGE:
2039   {
2040     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2041     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2042       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
2043       editor->bEmulateVersion10, ME_GetTextLength(editor));
2044     if (IsWindowUnicode(hWnd))
2045       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2046     else
2047     {
2048       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2049       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2050       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2051       /* FIXME this is a potential security hole (buffer overrun) 
2052          if you know more about wchar->mbyte conversion please explain
2053       */
2054       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2055       FREE_OBJ(p);
2056       return nChars;
2057     }
2058   }
2059   case EM_GETLINE:
2060   {
2061     ME_DisplayItem *run;
2062     const BOOL bUnicode = IsWindowUnicode(hWnd);
2063     const unsigned int nMaxChars = *(WORD *) lParam;
2064     unsigned int nEndChars, nCharsLeft = nMaxChars;
2065     char *dest = (char *) lParam;
2066     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2067     we need to know how if we have the extra \n or not */
2068     int nLF = editor->bEmulateVersion10;
2069
2070     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2071           bUnicode ? "Unicode" : "Ansi");
2072
2073     run = ME_FindRowWithNumber(editor, wParam);
2074     if (run == NULL)
2075       return 0;
2076
2077     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2078            && !(run->member.run.nFlags & MERF_ENDPARA))
2079     {
2080       unsigned int nCopy;
2081       ME_String *strText;
2082       if (run->type != diRun)
2083         break;
2084       strText = run->member.run.strText;
2085       nCopy = min(nCharsLeft, strText->nLen);
2086
2087       if (bUnicode)
2088         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2089       else
2090         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2091                                     nCharsLeft, NULL, NULL);
2092       dest += nCopy * (bUnicode ? sizeof(WCHAR) : 1);
2093       nCharsLeft -= nCopy;
2094     }
2095
2096     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2097     nEndChars = min(nCharsLeft, 2 + nLF);
2098     nCharsLeft -= nEndChars;
2099     if (bUnicode)
2100     {
2101       const WCHAR src[] = {'\r', '\0'};
2102       const WCHAR src10[] = {'\r', '\n', '\0'};
2103       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2104     }
2105     else
2106       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2107
2108     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2109
2110     if (nEndChars == 2 + nLF)
2111       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2112     else
2113       return nMaxChars - nCharsLeft;
2114   }
2115   case EM_GETLINECOUNT:
2116   {
2117     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2118     int nRows = 0;
2119
2120     while (item != editor->pBuffer->pLast)
2121     {
2122       assert(item->type == diParagraph);
2123       nRows += item->member.para.nRows;
2124       item = item->member.para.next_para;
2125     }
2126     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2127     return max(1, nRows);
2128   }
2129   case EM_LINEFROMCHAR:
2130   {
2131     if (wParam == -1)
2132       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2133     else
2134       return ME_RowNumberFromCharOfs(editor, wParam);
2135   }
2136   case EM_EXLINEFROMCHAR:
2137   {
2138     if (lParam == -1)
2139       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2140     else    
2141       return ME_RowNumberFromCharOfs(editor, lParam);
2142   }
2143   case EM_LINEINDEX:
2144   {
2145     ME_DisplayItem *item, *para;
2146     int nCharOfs;
2147     
2148     if (wParam == -1)
2149       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2150     else
2151       item = ME_FindRowWithNumber(editor, wParam);
2152     if (!item)
2153       return -1;
2154     para = ME_GetParagraph(item);
2155     item = ME_FindItemFwd(item, diRun);
2156     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2157     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2158     return nCharOfs;
2159   }
2160   case EM_LINELENGTH:
2161   {
2162     ME_DisplayItem *item, *item_end;
2163     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2164     
2165     if (wParam > ME_GetTextLength(editor))
2166       return 0;
2167     if (wParam == -1)
2168     {
2169       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2170       return 0;
2171     }
2172     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2173     item = ME_RowStart(item);
2174     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2175     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2176     if (item_end->type == diStartRow)
2177       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2178     else
2179       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2180        - (editor->bEmulateVersion10?2:1);
2181     nChars = nNextLineOfs - nThisLineOfs;
2182     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
2183     return nChars;
2184   }
2185   case EM_EXLIMITTEXT:
2186   {
2187     if ((int)lParam < 0)
2188      return 0;
2189     if (lParam == 0)
2190       editor->nTextLimit = 65536;
2191     else
2192       editor->nTextLimit = (int) lParam;
2193     return 0;
2194   }
2195   case EM_LIMITTEXT:
2196   {
2197     if (wParam == 0)
2198       editor->nTextLimit = 65536;
2199     else
2200       editor->nTextLimit = (int) wParam;
2201     return 0;
2202   }
2203   case EM_GETLIMITTEXT:
2204   {
2205     return editor->nTextLimit;
2206   }
2207   case EM_FINDTEXT:
2208   {
2209     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2210     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2211     WCHAR *tmp;
2212     LRESULT r;
2213
2214     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2215       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2216     r = ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2217     FREE_OBJ( tmp );
2218     return r;
2219   }
2220   case EM_FINDTEXTEX:
2221   {
2222     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2223     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2224     WCHAR *tmp;
2225     LRESULT r;
2226
2227     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2228       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2229     r = ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2230     FREE_OBJ( tmp );
2231     return r;
2232   }
2233   case EM_FINDTEXTW:
2234   {
2235     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2236     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2237   }
2238   case EM_FINDTEXTEXW:
2239   {
2240     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2241     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2242   }
2243   case EM_GETZOOM:
2244     if (!wParam || !lParam)
2245       return FALSE;
2246     *(int *)wParam = editor->nZoomNumerator;
2247     *(int *)lParam = editor->nZoomDenominator;
2248     return TRUE;
2249   case EM_SETZOOM:
2250     return ME_SetZoom(editor, wParam, lParam);
2251   case EM_CHARFROMPOS:
2252     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2253   case EM_POSFROMCHAR:
2254   {
2255     ME_DisplayItem *pRun;
2256     int nCharOfs, nOffset, nLength;
2257     POINTL pt = {0,0};
2258     
2259     nCharOfs = wParam; 
2260     /* detect which API version we're dealing with */
2261     if (wParam >= 0x40000)
2262         nCharOfs = lParam;
2263     nLength = ME_GetTextLength(editor);
2264     
2265     if (nCharOfs < nLength) { 
2266         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2267         assert(pRun->type == diRun);
2268         pt.y = pRun->member.run.pt.y;
2269         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2270         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2271     } else {
2272         pt.x = 0;
2273         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2274     }
2275     if (wParam >= 0x40000) {
2276         *(POINTL *)wParam = pt;
2277     }
2278     return MAKELONG( pt.x, pt.y );
2279   }
2280   case WM_CREATE:
2281     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2282     { /* Squelch the default horizontal scrollbar it would make */
2283       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2284     }
2285     ME_CommitUndo(editor);
2286     ME_WrapMarkedParagraphs(editor);
2287     ME_MoveCaret(editor);
2288     return 0;
2289   case WM_DESTROY:
2290     ME_DestroyEditor(editor);
2291     SetWindowLongPtrW(hWnd, 0, 0);
2292     return 0;
2293   case WM_LBUTTONDOWN:
2294     SetFocus(hWnd);
2295     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2296     SetCapture(hWnd);
2297     ME_LinkNotify(editor,msg,wParam,lParam);
2298     break;
2299   case WM_MOUSEMOVE:
2300     if (GetCapture() == hWnd)
2301       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2302     ME_LinkNotify(editor,msg,wParam,lParam);
2303     break;
2304   case WM_LBUTTONUP:
2305     if (GetCapture() == hWnd)
2306       ReleaseCapture();
2307     ME_LinkNotify(editor,msg,wParam,lParam);
2308     break;
2309   case WM_LBUTTONDBLCLK:
2310     ME_LinkNotify(editor,msg,wParam,lParam);
2311     ME_SelectWord(editor);
2312     break;
2313   case WM_CONTEXTMENU:
2314     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2315       goto do_default;
2316     break;
2317   case WM_PAINT:
2318     if (editor->bRedraw)
2319     {
2320       HDC hDC;
2321       PAINTSTRUCT ps;
2322
2323       hDC = BeginPaint(hWnd, &ps);
2324       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2325       EndPaint(hWnd, &ps);
2326     }
2327     break;
2328   case WM_SETFOCUS:
2329     ME_ShowCaret(editor);
2330     ME_SendOldNotify(editor, EN_SETFOCUS);
2331     return 0;
2332   case WM_KILLFOCUS:
2333     ME_HideCaret(editor);
2334     ME_SendOldNotify(editor, EN_KILLFOCUS);
2335     return 0;
2336   case WM_ERASEBKGND:
2337   {
2338     if (editor->bRedraw)
2339     {
2340       HDC hDC = (HDC)wParam;
2341       RECT rc;
2342       if (GetUpdateRect(hWnd,&rc,TRUE))
2343       {
2344         FillRect(hDC, &rc, editor->hbrBackground);
2345       }
2346     }
2347     return 1;
2348   }
2349   case WM_COMMAND:
2350     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2351     return 0;
2352   case WM_KEYDOWN:
2353     if (ME_KeyDown(editor, LOWORD(wParam)))
2354       return 0;
2355     goto do_default;
2356   case WM_CHAR: 
2357   {
2358     WCHAR wstr = LOWORD(wParam);
2359     if (editor->AutoURLDetect_bEnable)
2360       ME_AutoURLDetect(editor, wstr);
2361         
2362     switch (wstr)
2363     {
2364     case 1: /* Ctrl-A */
2365       ME_SetSelection(editor, 0, -1);
2366       return 0;
2367     case 3: /* Ctrl-C */
2368       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2369       return 0;
2370     }
2371     
2372     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2373       MessageBeep(MB_ICONERROR);
2374       return 0; /* FIXME really 0 ? */
2375     }
2376
2377     switch (wstr)
2378     {
2379     case 22: /* Ctrl-V */
2380       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2381       return 0;
2382     case 24: /* Ctrl-X */
2383       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2384       return 0;
2385     case 25: /* Ctrl-Y */
2386       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2387       return 0;
2388     case 26: /* Ctrl-Z */
2389       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2390       return 0;
2391     }
2392     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
2393       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2394       ME_Style *style = ME_GetInsertStyle(editor, 0);
2395       ME_SaveTempStyle(editor);
2396       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2397       ME_ReleaseStyle(style);
2398       ME_CommitUndo(editor);
2399       ME_UpdateRepaint(editor);
2400     }
2401     return 0;
2402   }
2403   case EM_SCROLL: /* fall through */
2404   case WM_VSCROLL: 
2405   {
2406     int origNPos;
2407     int lineHeight;
2408     
2409     origNPos = ME_GetYScrollPos(editor);
2410     lineHeight = 24;
2411     
2412     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2413       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2414     if (lineHeight <= 0) lineHeight = 24;
2415     
2416     switch(LOWORD(wParam)) 
2417     {
2418       case SB_LINEUP:
2419         ME_ScrollUp(editor,lineHeight);
2420         break;
2421       case SB_LINEDOWN:
2422         ME_ScrollDown(editor,lineHeight);
2423         break;
2424       case SB_PAGEUP:
2425         ME_ScrollUp(editor,editor->sizeWindow.cy);
2426         break;
2427       case SB_PAGEDOWN:
2428         ME_ScrollDown(editor,editor->sizeWindow.cy);
2429         break;
2430       case SB_THUMBTRACK:
2431       case SB_THUMBPOSITION:
2432         ME_ScrollAbs(editor,HIWORD(wParam));
2433         break;
2434     }
2435     if (msg == EM_SCROLL)
2436       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2437     break;
2438   }
2439   case WM_MOUSEWHEEL:
2440   {
2441     int gcWheelDelta;
2442     UINT pulScrollLines;
2443     
2444     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2445     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2446     
2447     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2448     {
2449       /* FIXME follow the original */
2450       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2451     }
2452     break;
2453   }
2454   case EM_GETRECT:
2455   {
2456     *((RECT *)lParam) = editor->rcFormat;
2457     return 0;
2458   }
2459   case EM_SETRECT:
2460   case EM_SETRECTNP:
2461   {
2462     if (lParam)
2463     {
2464       RECT *rc = (RECT *)lParam;
2465       
2466       if (wParam)
2467       {
2468         editor->rcFormat.left += rc->left;
2469         editor->rcFormat.top += rc->top;
2470         editor->rcFormat.right += rc->right;
2471         editor->rcFormat.bottom += rc->bottom;
2472       }
2473       else
2474       {
2475         editor->rcFormat = *rc;
2476       }
2477     }
2478     else
2479     {
2480       GetClientRect(hWnd, &editor->rcFormat);
2481     }
2482     if (msg != EM_SETRECTNP)
2483       ME_RewrapRepaint(editor);
2484     return 0;
2485   }
2486   case EM_REQUESTRESIZE:
2487     ME_SendRequestResize(editor, TRUE);
2488     return 0;
2489   case WM_SETREDRAW:
2490     editor->bRedraw = wParam;
2491     return 0;
2492   case WM_SIZE:
2493   {
2494     GetClientRect(hWnd, &editor->rcFormat);
2495     ME_RewrapRepaint(editor);
2496     return DefWindowProcW(hWnd, msg, wParam, lParam);
2497   }
2498   case EM_GETOLEINTERFACE:
2499   {
2500     LPVOID *ppvObj = (LPVOID*) lParam;
2501     return CreateIRichEditOle(editor, ppvObj);
2502   }
2503   case EM_GETPASSWORDCHAR:
2504   {
2505     return editor->cPasswordMask;
2506   }
2507   case EM_SETOLECALLBACK:
2508     if(editor->lpOleCallback)
2509       IUnknown_Release(editor->lpOleCallback);
2510     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2511     if(editor->lpOleCallback)
2512       IUnknown_AddRef(editor->lpOleCallback);
2513     return TRUE;
2514   case EM_GETWORDBREAKPROC:
2515     return (LRESULT)editor->pfnWordBreak;
2516   case EM_SETWORDBREAKPROC:
2517   {
2518     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2519
2520     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2521     return (LRESULT)pfnOld;
2522   }
2523   case EM_SETTEXTMODE:
2524   {
2525     LRESULT ret;
2526     int mask = 0;
2527     int changes = 0;
2528     if ((ret = RichEditANSIWndProc(hWnd, WM_GETTEXTLENGTH, 0, 0)) == 0)
2529     {
2530       /*Check for valid wParam*/
2531       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2532           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2533           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2534         return 1;
2535       else
2536       {
2537         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2538         {
2539           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2540           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2541         }
2542         /*FIXME: Currently no support for undo level and code page options*/ 
2543         editor->mode = (editor->mode & (~mask)) | changes;
2544         return 0;
2545       }
2546     }
2547     return ret;
2548   }
2549   case EM_SETPASSWORDCHAR:
2550   {
2551     editor->cPasswordMask = wParam;
2552     ME_RewrapRepaint(editor);
2553     return 0;
2554   }
2555   default:
2556   do_default:
2557     return DefWindowProcW(hWnd, msg, wParam, lParam);
2558   }
2559   return 0L;
2560 }
2561
2562
2563 /******************************************************************
2564  *        RichEdit10ANSIWndProc (RICHED20.9)
2565  */
2566 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2567 {
2568   LRESULT result;
2569   
2570   /* FIXME: this is NOT the same as 2.0 version */
2571   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2572   if (msg == WM_NCCREATE)
2573   {
2574     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2575     
2576     editor->bEmulateVersion10 = TRUE;
2577     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2578   }
2579   return result;
2580 }
2581
2582 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2583 {
2584   HWND hWnd = editor->hWnd;
2585   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2586 }
2587
2588 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2589 {
2590   int x,y;
2591   ME_Cursor tmpCursor;
2592   int nCharOfs; /* The start of the clicked text. Absolute character offset */
2593
2594   ME_Run *tmpRun;
2595
2596   ENLINK info;
2597   x = (short)LOWORD(lParam);
2598   y = (short)HIWORD(lParam);
2599   nCharOfs = ME_CharFromPos(editor, x, y);
2600   ME_CursorFromCharOfs(editor, nCharOfs, &tmpCursor);
2601   tmpRun = &tmpCursor.pRun->member.run;
2602
2603   if ((tmpRun->style->fmt.dwMask & CFM_LINK)
2604     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2605   { /* The clicked run has CFE_LINK set */
2606     info.nmhdr.hwndFrom = editor->hWnd;
2607     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2608     info.nmhdr.code = EN_LINK;
2609     info.msg = msg;
2610     info.wParam = wParam;
2611     info.lParam = lParam;
2612     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2613     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2614     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2615   }  
2616 }
2617
2618 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2619 {
2620   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2621   int i = 0;
2622   
2623   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2624     item = item->member.para.next_para;
2625   if (!item)
2626     return 0;
2627   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2628     item = item->member.para.next_para;
2629     i++;
2630   }
2631   return i;
2632 }
2633
2634
2635 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2636 {
2637   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2638   int nWritten = 0;
2639   WCHAR *pStart = buffer;
2640   
2641   if (!item) {
2642     *buffer = L'\0';
2643     return 0;
2644   }
2645   
2646   if (nStart)
2647   {
2648     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2649     if (nLen > nChars)
2650       nLen = nChars;
2651     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2652     nChars -= nLen;
2653     nWritten += nLen;
2654     if (!nChars)
2655       return nWritten;
2656     buffer += nLen;
2657     nStart = 0;
2658     item = ME_FindItemFwd(item, diRun);
2659   }
2660   
2661   while(nChars && item)
2662   {
2663     int nLen = ME_StrLen(item->member.run.strText);
2664     if (nLen > nChars)
2665       nLen = nChars;
2666
2667     if (item->member.run.nFlags & MERF_ENDPARA)
2668     {
2669       if (!ME_FindItemFwd(item, diRun))
2670         /* No '\r' is appended to the last paragraph. */
2671         nLen = 0;
2672       else {
2673         *buffer = '\r';
2674         if (bCRLF)
2675         {
2676           *(++buffer) = '\n';
2677           nWritten++;
2678         }
2679         assert(nLen == 1);
2680         /* our end paragraph consists of 2 characters now */
2681         if (editor->bEmulateVersion10)
2682           nChars--;
2683       }
2684     }
2685     else
2686       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2687     nChars -= nLen;
2688     nWritten += nLen;
2689     buffer += nLen;    
2690       
2691     if (!nChars)
2692     {
2693       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2694       *buffer = L'\0';
2695       return nWritten;
2696     }
2697     item = ME_FindItemFwd(item, diRun);
2698   }
2699   *buffer = L'\0';
2700   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2701   return nWritten;  
2702 }
2703
2704 void ME_RegisterEditorClass(HINSTANCE hInstance)
2705 {
2706   BOOL bResult;
2707   WNDCLASSW wcW;
2708   WNDCLASSA wcA;
2709   
2710   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2711   wcW.lpfnWndProc = RichEditANSIWndProc;
2712   wcW.cbClsExtra = 0;
2713   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2714   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2715   wcW.hIcon = NULL;
2716   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2717   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2718   wcW.lpszMenuName = NULL;
2719   wcW.lpszClassName = wszClassName;
2720   bResult = RegisterClassW(&wcW);  
2721   assert(bResult);
2722   wcW.lpszClassName = wszClassName50;
2723   bResult = RegisterClassW(&wcW);  
2724   assert(bResult);
2725
2726   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2727   wcA.lpfnWndProc = RichEditANSIWndProc;
2728   wcA.cbClsExtra = 0;
2729   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2730   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2731   wcA.hIcon = NULL;
2732   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2733   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2734   wcA.lpszMenuName = NULL;
2735   wcA.lpszClassName = "RichEdit20A";
2736   bResult = RegisterClassA(&wcA);  
2737   assert(bResult);
2738   wcA.lpszClassName = "RichEdit50A";
2739   bResult = RegisterClassA(&wcA);  
2740   assert(bResult);
2741 }
2742
2743 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2744   /* FIXME: Not implemented */
2745   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2746         hWnd, msg, get_msg_name(msg), wParam, lParam);
2747   return DefWindowProcW(hWnd, msg, wParam, lParam);
2748 }
2749
2750 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2751   /* FIXME: Not implemented */
2752   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2753         hWnd, msg, get_msg_name(msg), wParam, lParam);
2754   return DefWindowProcW(hWnd, msg, wParam, lParam);
2755 }
2756
2757 /******************************************************************
2758  *        REExtendedRegisterClass (RICHED20.8)
2759  *
2760  * FIXME undocumented
2761  * Need to check for errors and implement controls and callbacks 
2762  */
2763 LRESULT WINAPI REExtendedRegisterClass(void)
2764 {
2765   WNDCLASSW wcW;
2766   UINT result;
2767
2768   FIXME("semi stub\n");
2769
2770   wcW.cbClsExtra = 0;
2771   wcW.cbWndExtra = 4;
2772   wcW.hInstance = NULL;
2773   wcW.hIcon = NULL;
2774   wcW.hCursor = NULL;
2775   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2776   wcW.lpszMenuName = NULL;
2777
2778   if (!ME_ListBoxRegistered)
2779   {
2780       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2781       wcW.lpfnWndProc = REListWndProc;
2782       wcW.lpszClassName = wszClassNameListBox;
2783       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2784   }
2785
2786   if (!ME_ComboBoxRegistered)
2787   {
2788       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2789       wcW.lpfnWndProc = REComboWndProc;
2790       wcW.lpszClassName = wszClassNameComboBox;
2791       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2792   }
2793
2794   result = 0;
2795   if (ME_ListBoxRegistered)
2796       result += 1;
2797   if (ME_ComboBoxRegistered)
2798       result += 2;
2799
2800   return result;
2801 }
2802
2803 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
2804 {
2805   struct prefix_s {
2806     const char *text;
2807     int length;
2808   } prefixes[12] = {
2809     {"http:", 5},
2810     {"file:", 6},
2811     {"mailto:", 8},
2812     {"ftp:", 5},
2813     {"https:", 7},
2814     {"gopher:", 8},
2815     {"nntp:", 6},
2816     {"prospero:", 10},
2817     {"telnet:", 8},
2818     {"news:", 6},
2819     {"wais:", 6},
2820     {"www.", 5}
2821   };
2822   CHARRANGE ins_pt;
2823   int curf_ef, link_ef, def_ef;
2824   int cur_prefx, prefx_cnt;
2825   int sel_min, sel_max;
2826   int car_pos = 0;
2827   int text_pos=-1;
2828   int URLmin, URLmax = 0;
2829   CHARRANGE url;
2830   FINDTEXTA ft;
2831   CHARFORMAT2W cur_format;
2832   CHARFORMAT2W default_format;
2833   CHARFORMAT2W link;
2834   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
2835   sel_min = ins_pt.cpMin;
2836   sel_max = ins_pt.cpMax;
2837   if (sel_min==sel_max) 
2838     car_pos = sel_min;
2839   if (sel_min!=sel_max)
2840     car_pos = ME_GetTextLength(editor)+1;   
2841   cur_format.cbSize = sizeof(cur_format);
2842   default_format.cbSize = sizeof(default_format);
2843   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
2844   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
2845   link.cbSize = sizeof(link);
2846   link.dwMask = CFM_LINK;
2847   link.dwEffects = CFE_LINK;
2848   curf_ef = cur_format.dwEffects & link.dwEffects;
2849   def_ef = default_format.dwEffects & link.dwEffects;
2850   link_ef = link.dwEffects & link.dwEffects;
2851   if (curf_ef == link_ef) 
2852   {
2853     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
2854     {
2855       ME_SetSelection(editor, car_pos, car_pos);
2856       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
2857       text_pos=-1;
2858       return 0;
2859     }
2860   }
2861   if (curf_ef == def_ef)
2862   {
2863     cur_prefx = 0;
2864     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
2865     while (cur_prefx<=prefx_cnt) 
2866     {
2867       if (text_pos == -1) 
2868       {
2869         ft.lpstrText = prefixes[cur_prefx].text;
2870         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
2871         URLmax=max(0, car_pos);
2872         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
2873         {
2874         URLmax = ME_GetTextLength(editor)+1;
2875         }
2876         ft.chrg.cpMin = URLmin;
2877         ft.chrg.cpMax = URLmax;
2878         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
2879         cur_prefx++;
2880       }
2881       if (text_pos != -1) 
2882       {
2883         url.cpMin=text_pos;
2884         url.cpMax=car_pos-1;
2885         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
2886         ME_RewrapRepaint(editor);
2887         break;
2888       }
2889     }
2890   }
2891   return 0;
2892 }