dinput: Move SetEventNotification and associated event into base class.
[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
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   ME_UndoItem *pUI;
602   int nEventMask = editor->nEventMask;
603   ME_InStream inStream;
604
605   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
606   editor->nEventMask = 0;
607   
608   ME_GetSelection(editor, &from, &to);
609   if ((format & SFF_SELECTION) && (editor->mode & TM_RICHTEXT)) {
610     style = ME_GetSelectionInsertStyle(editor);
611
612     ME_InternalDeleteText(editor, from, to-from);
613   }
614   else {
615     style = editor->pBuffer->pDefaultStyle;
616     ME_AddRefStyle(style);
617     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
618     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
619     from = to = 0;
620     ME_ClearTempStyle(editor);
621     /* FIXME restore default paragraph formatting ! */
622   }
623   
624   nUndoMode = editor->nUndoMode;
625   editor->nUndoMode = umIgnore;
626
627   inStream.editstream = stream;
628   inStream.editstream->dwError = 0;
629   inStream.dwSize = 0;
630   inStream.dwUsed = 0;
631
632   if (format & SF_RTF)
633   {
634     /* Check if it's really RTF, and if it is not, use plain text */
635     ME_StreamInFill(&inStream);
636     if (!inStream.editstream->dwError)
637     {
638       if (strncmp(inStream.buffer, "{\\rtf", 5) && strncmp(inStream.buffer, "{\\urtf", 6))
639       {
640         format &= ~SF_RTF;
641         format |= SF_TEXT;
642       }
643     }
644   }
645
646   if (!inStream.editstream->dwError)
647   {
648     if (format & SF_RTF) {
649       /* setup the RTF parser */
650       memset(&parser, 0, sizeof parser);
651       RTFSetEditStream(&parser, &inStream);
652       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
653       parser.hwndEdit = editor->hWnd;
654       parser.editor = editor;
655       parser.style = style;
656       WriterInit(&parser);
657       RTFInit(&parser);
658       RTFSetReadHook(&parser, ME_RTFReadHook);
659       BeginFile(&parser);
660   
661       /* do the parsing */
662       RTFRead(&parser);
663       RTFFlushOutputBuffer(&parser);
664       RTFDestroy(&parser);
665
666       style = parser.style;
667     }
668     else if (format & SF_TEXT)
669       ME_StreamInText(editor, format, &inStream, style);
670     else
671       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
672     ME_GetSelection(editor, &to, &to2);
673     /* put the cursor at the top */
674     if (!(format & SFF_SELECTION))
675       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
676   }
677   
678   editor->nUndoMode = nUndoMode;
679   if (format & SFF_SELECTION)
680   {
681     pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
682     TRACE("from %d to %d\n", from, to);
683     if (pUI && from < to)
684     {
685       pUI->nStart = from;
686       pUI->nLen = to-from;
687     }
688     ME_CommitUndo(editor);
689   }
690   else
691   {
692     ME_EmptyUndoStack(editor);
693   }
694
695   ME_ReleaseStyle(style); 
696   editor->nEventMask = nEventMask;
697   if (editor->bRedraw)
698   {
699     ME_UpdateRepaint(editor);
700   }
701   if (!(format & SFF_SELECTION)) {
702     ME_ClearTempStyle(editor);
703   }
704   ME_MoveCaret(editor);
705   ME_SendSelChange(editor);
706   ME_SendRequestResize(editor, FALSE);
707
708   return 0;
709 }
710
711
712 typedef struct tagME_RTFStringStreamStruct
713 {
714   char *string;
715   int pos;
716   int length;
717 } ME_RTFStringStreamStruct;
718
719 static DWORD CALLBACK ME_ReadFromRTFString(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
720 {
721   ME_RTFStringStreamStruct *pStruct = (ME_RTFStringStreamStruct *)dwCookie;
722   int count;
723
724   count = min(cb, pStruct->length - pStruct->pos);
725   memmove(lpBuff, pStruct->string + pStruct->pos, count);
726   pStruct->pos += count;
727   *pcb = count;
728   return 0;
729 }
730
731 static void
732 ME_StreamInRTFString(ME_TextEditor *editor, BOOL selection, char *string)
733 {
734   EDITSTREAM es;
735   ME_RTFStringStreamStruct data;
736
737   data.string = string;
738   data.length = strlen(string);
739   data.pos = 0;
740   es.dwCookie = (DWORD)&data;
741   es.pfnCallback = ME_ReadFromRTFString;
742   ME_StreamIn(editor, SF_RTF | (selection ? SFF_SELECTION : 0), &es);
743 }
744
745
746 ME_DisplayItem *
747 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
748 {
749   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
750   
751   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
752     item = ME_FindItemFwd(item, diParagraph);
753
754   if (!item)
755     return item;
756
757   nOffset -= item->member.para.nCharOfs;
758   if (nItemType == diParagraph) {
759     if (nItemOffset)
760       *nItemOffset = nOffset;
761     return item;
762   }
763   
764   do {
765     item = ME_FindItemFwd(item, diRun);
766   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
767   if (item) {
768     nOffset -= item->member.run.nCharOfs;
769     if (nItemOffset)
770       *nItemOffset = nOffset;
771   }
772   return item;
773 }
774
775
776 static int
777 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, const WCHAR *text, CHARRANGE *chrgText)
778 {
779   const int nLen = lstrlenW(text);
780   const int nTextLen = ME_GetTextLength(editor);
781   int nStart, nEnd;
782   int nMin, nMax;
783   ME_DisplayItem *item;
784   ME_DisplayItem *para;
785   WCHAR wLastChar = ' ';
786
787   TRACE("flags==0x%08x, chrg->cpMin==%d, chrg->cpMax==%d text==%s\n",
788         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
789   
790   if (flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD))
791     FIXME("Flags 0x%08x not implemented\n",
792         flags & ~(FR_DOWN | FR_MATCHCASE | FR_WHOLEWORD));
793
794   nMin = chrg->cpMin;
795   if (chrg->cpMax == -1)
796     nMax = nTextLen;
797   else
798     nMax = chrg->cpMax > nTextLen ? nTextLen : chrg->cpMax;
799   
800   /* when searching up, if cpMin < cpMax, then instead of searching
801    * on [cpMin,cpMax], we search on [0,cpMin], otherwise, search on
802    * [cpMax, cpMin]. The exception is when cpMax is -1, in which
803    * case, it is always bigger than cpMin.
804    */
805   if (!(flags & FR_DOWN))
806   {
807     int nSwap = nMax;
808
809     nMax = nMin > nTextLen ? nTextLen : nMin;
810     if (nMin < nSwap || chrg->cpMax == -1)
811       nMin = 0;
812     else
813       nMin = nSwap;
814   }
815
816   if (!nLen || nMin < 0 || nMax < 0 || nMax < nMin)
817   {
818     if (chrgText)
819       chrgText->cpMin = chrgText->cpMax = -1;
820     return -1;
821   }
822  
823   if (flags & FR_DOWN) /* Forward search */
824   {
825     /* If possible, find the character before where the search starts */
826     if ((flags & FR_WHOLEWORD) && nMin)
827     {
828       nStart = nMin - 1;
829       item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
830       if (!item)
831       {
832         if (chrgText)
833           chrgText->cpMin = chrgText->cpMax = -1;
834         return -1;
835       }
836       wLastChar = item->member.run.strText->szData[nStart];
837     }
838
839     nStart = nMin;
840     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
841     if (!item)
842     {
843       if (chrgText)
844         chrgText->cpMin = chrgText->cpMax = -1;
845       return -1;
846     }
847
848     para = ME_GetParagraph(item);
849     while (item
850            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen <= nMax)
851     {
852       ME_DisplayItem *pCurItem = item;
853       int nCurStart = nStart;
854       int nMatched = 0;
855     
856       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurStart + nMatched], text[nMatched], (flags & FR_MATCHCASE)))
857       {
858         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
859           break;
860
861         nMatched++;
862         if (nMatched == nLen)
863         {
864           ME_DisplayItem *pNextItem = pCurItem;
865           int nNextStart = nCurStart;
866           WCHAR wNextChar;
867
868           /* Check to see if next character is a whitespace */
869           if (flags & FR_WHOLEWORD)
870           {
871             if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
872             {
873               pNextItem = ME_FindItemFwd(pCurItem, diRun);
874               nNextStart = -nMatched;
875             }
876
877             if (pNextItem)
878               wNextChar = pNextItem->member.run.strText->szData[nNextStart + nMatched];
879             else
880               wNextChar = ' ';
881
882             if (isalnumW(wNextChar))
883               break;
884           }
885
886           nStart += para->member.para.nCharOfs + pCurItem->member.run.nCharOfs;
887           if (chrgText)
888           {
889             chrgText->cpMin = nStart;
890             chrgText->cpMax = nStart + nLen;
891           }
892           TRACE("found at %d-%d\n", nStart, nStart + nLen);
893           return nStart;
894         }
895         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
896         {
897           pCurItem = ME_FindItemFwd(pCurItem, diRun);
898           para = ME_GetParagraph(pCurItem);
899           nCurStart = -nMatched;
900         }
901       }
902       if (pCurItem)
903         wLastChar = pCurItem->member.run.strText->szData[nCurStart + nMatched];
904       else
905         wLastChar = ' ';
906
907       nStart++;
908       if (nStart == ME_StrLen(item->member.run.strText))
909       {
910         item = ME_FindItemFwd(item, diRun);
911         para = ME_GetParagraph(item);
912         nStart = 0;
913       }
914     }
915   }
916   else /* Backward search */
917   {
918     /* If possible, find the character after where the search ends */
919     if ((flags & FR_WHOLEWORD) && nMax < nTextLen - 1)
920     {
921       nEnd = nMax + 1;
922       item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
923       if (!item)
924       {
925         if (chrgText)
926           chrgText->cpMin = chrgText->cpMax = -1;
927         return -1;
928       }
929       wLastChar = item->member.run.strText->szData[nEnd];
930     }
931
932     nEnd = nMax;
933     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
934     if (!item)
935     {
936       if (chrgText)
937         chrgText->cpMin = chrgText->cpMax = -1;
938       return -1;
939     }
940     
941     para = ME_GetParagraph(item);
942     
943     while (item
944            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
945     {
946       ME_DisplayItem *pCurItem = item;
947       int nCurEnd = nEnd;
948       int nMatched = 0;
949       
950       if (nCurEnd - nMatched == 0)
951       {
952         pCurItem = ME_FindItemBack(pCurItem, diRun);
953         para = ME_GetParagraph(pCurItem);
954         nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
955       }
956       
957       while (pCurItem && ME_CharCompare(pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1], text[nLen - nMatched - 1], (flags & FR_MATCHCASE)))
958       {
959         if ((flags & FR_WHOLEWORD) && isalnumW(wLastChar))
960           break;
961
962         nMatched++;
963         if (nMatched == nLen)
964         {
965           ME_DisplayItem *pPrevItem = pCurItem;
966           int nPrevEnd = nCurEnd;
967           WCHAR wPrevChar;
968
969           /* Check to see if previous character is a whitespace */
970           if (flags & FR_WHOLEWORD)
971           {
972             if (nPrevEnd - nMatched == 0)
973             {
974               pPrevItem = ME_FindItemBack(pCurItem, diRun);
975               if (pPrevItem)
976                 nPrevEnd = ME_StrLen(pPrevItem->member.run.strText) + nMatched;
977             }
978
979             if (pPrevItem)
980               wPrevChar = pPrevItem->member.run.strText->szData[nPrevEnd - nMatched - 1];
981             else
982               wPrevChar = ' ';
983
984             if (isalnumW(wPrevChar))
985               break;
986           }
987
988           nStart = para->member.para.nCharOfs + pCurItem->member.run.nCharOfs + nCurEnd - nMatched;
989           if (chrgText)
990           {
991             chrgText->cpMin = nStart;
992             chrgText->cpMax = nStart + nLen;
993           }
994           TRACE("found at %d-%d\n", nStart, nStart + nLen);
995           return nStart;
996         }
997         if (nCurEnd - nMatched == 0)
998         {
999           pCurItem = ME_FindItemBack(pCurItem, diRun);
1000           /* Don't care about pCurItem becoming NULL here; it's already taken
1001            * care of in the exterior loop condition */
1002           para = ME_GetParagraph(pCurItem);
1003           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
1004         }
1005       }
1006       if (pCurItem)
1007         wLastChar = pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1];
1008       else
1009         wLastChar = ' ';
1010
1011       nEnd--;
1012       if (nEnd < 0)
1013       {
1014         item = ME_FindItemBack(item, diRun);
1015         para = ME_GetParagraph(item);
1016         nEnd = ME_StrLen(item->member.run.strText);
1017       }
1018     }
1019   }
1020   TRACE("not found\n");
1021   if (chrgText)
1022     chrgText->cpMin = chrgText->cpMax = -1;
1023   return -1;
1024 }
1025
1026
1027 static BOOL
1028 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
1029 {
1030   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
1031   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
1032   
1033   switch (nKey)
1034   {
1035     case VK_LEFT:
1036     case VK_RIGHT:
1037     case VK_UP:
1038     case VK_DOWN:
1039     case VK_HOME:
1040     case VK_END:
1041     case VK_PRIOR:
1042     case VK_NEXT:
1043       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
1044       return TRUE;
1045     case VK_BACK:
1046     case VK_DELETE:
1047       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
1048       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
1049         return FALSE;
1050       if (ME_IsSelection(editor))
1051         ME_DeleteSelection(editor);
1052       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
1053         ME_DeleteTextAtCursor(editor, 1, 1);
1054       else
1055         return TRUE;
1056       ME_CommitUndo(editor);
1057       ME_UpdateRepaint(editor);
1058       ME_SendRequestResize(editor, FALSE);
1059       return TRUE;
1060
1061     default:
1062       if (ctrl_is_down)
1063       {
1064         if (nKey == 'W')
1065         {
1066           CHARFORMAT2W chf;
1067           char buf[2048];
1068           chf.cbSize = sizeof(chf);
1069           
1070           ME_GetSelectionCharFormat(editor, &chf);
1071           ME_DumpStyleToBuf(&chf, buf);
1072           MessageBoxA(NULL, buf, "Style dump", MB_OK);
1073         }
1074         if (nKey == 'Q')
1075         {
1076           ME_CheckCharOffsets(editor);
1077         }
1078       }
1079   }
1080   return FALSE;
1081 }
1082
1083 static BOOL ME_ShowContextMenu(ME_TextEditor *editor, int x, int y)
1084 {
1085   CHARRANGE selrange;
1086   HMENU menu;
1087   int seltype = 0;
1088   if(!editor->lpOleCallback)
1089     return FALSE;
1090   ME_GetSelection(editor, (int *)&selrange.cpMin, (int *)&selrange.cpMax);
1091   if(selrange.cpMin == selrange.cpMax)
1092     seltype |= SEL_EMPTY;
1093   else
1094   {
1095     /* FIXME: Handle objects */
1096     seltype |= SEL_TEXT;
1097     if(selrange.cpMax-selrange.cpMin > 1)
1098       seltype |= SEL_MULTICHAR;
1099   }
1100   if(SUCCEEDED(IRichEditOleCallback_GetContextMenu(editor->lpOleCallback, seltype, NULL, &selrange, &menu)))
1101   {
1102     TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, x, y, 0, GetParent(editor->hWnd), NULL);
1103     DestroyMenu(menu);
1104   }
1105   return TRUE;
1106 }
1107
1108 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
1109   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
1110   HDC hDC;
1111   int i;
1112   ed->hWnd = hWnd;
1113   ed->bEmulateVersion10 = FALSE;
1114   ed->pBuffer = ME_MakeText();
1115   hDC = GetDC(hWnd);
1116   ME_MakeFirstParagraph(hDC, ed->pBuffer);
1117   ReleaseDC(hWnd, hDC);
1118   ed->bCaretShown = FALSE;
1119   ed->nCursors = 3;
1120   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
1121   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1122   ed->pCursors[0].nOffset = 0;
1123   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
1124   ed->pCursors[1].nOffset = 0;
1125   ed->nLastTotalLength = ed->nTotalLength = 0;
1126   ed->nUDArrowX = -1;
1127   ed->nSequence = 0;
1128   ed->rgbBackColor = -1;
1129   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1130   ed->bCaretAtEnd = FALSE;
1131   ed->nEventMask = 0;
1132   ed->nModifyStep = 0;
1133   ed->nTextLimit = TEXT_LIMIT_DEFAULT;
1134   ed->pUndoStack = ed->pRedoStack = ed->pUndoStackBottom = NULL;
1135   ed->nUndoStackSize = 0;
1136   ed->nUndoLimit = STACK_SIZE_DEFAULT;
1137   ed->nUndoMode = umAddToUndo;
1138   ed->nParagraphs = 1;
1139   ed->nLastSelStart = ed->nLastSelEnd = 0;
1140   ed->pLastSelStartPara = ed->pLastSelEndPara = ME_FindItemFwd(ed->pBuffer->pFirst, diParagraph);
1141   ed->nZoomNumerator = ed->nZoomDenominator = 0;
1142   ed->bRedraw = TRUE;
1143   ed->bHideSelection = FALSE;
1144   ed->nInvalidOfs = -1;
1145   ed->pfnWordBreak = NULL;
1146   ed->lpOleCallback = NULL;
1147   ed->mode = TM_RICHTEXT | TM_MULTILEVELUNDO | TM_MULTICODEPAGE;
1148   GetClientRect(hWnd, &ed->rcFormat);
1149   for (i=0; i<HFONT_CACHE_SIZE; i++)
1150   {
1151     ed->pFontCache[i].nRefs = 0;
1152     ed->pFontCache[i].nAge = 0;
1153     ed->pFontCache[i].hFont = NULL;
1154   }
1155   
1156   ME_CheckCharOffsets(ed);
1157   
1158   if (GetWindowLongW(hWnd, GWL_STYLE) & ES_PASSWORD)
1159     ed->cPasswordMask = '*';
1160   else
1161     ed->cPasswordMask = 0;
1162   
1163   return ed;
1164 }
1165
1166 typedef struct tagME_GlobalDestStruct
1167 {
1168   HGLOBAL hData;
1169   int nLength;
1170 } ME_GlobalDestStruct;
1171
1172 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1173 {
1174   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1175   int i;
1176   WORD *pSrc, *pDest;
1177   
1178   cb = cb >> 1;
1179   pDest = (WORD *)lpBuff;
1180   pSrc = (WORD *)GlobalLock(pData->hData);
1181   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1182     pDest[i] = pSrc[pData->nLength+i];
1183   }    
1184   pData->nLength += i;
1185   *pcb = 2*i;
1186   GlobalUnlock(pData->hData);
1187   return 0;
1188 }
1189
1190 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
1191 {
1192   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
1193   int i;
1194   BYTE *pSrc, *pDest;
1195   
1196   pDest = lpBuff;
1197   pSrc = (BYTE *)GlobalLock(pData->hData);
1198   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
1199     pDest[i] = pSrc[pData->nLength+i];
1200   }    
1201   pData->nLength += i;
1202   *pcb = i;
1203   GlobalUnlock(pData->hData);
1204   return 0;
1205 }
1206
1207
1208 void ME_DestroyEditor(ME_TextEditor *editor)
1209 {
1210   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
1211   ME_DisplayItem *p = pFirst, *pNext = NULL;
1212   int i;
1213   
1214   ME_ClearTempStyle(editor);
1215   ME_EmptyUndoStack(editor);
1216   while(p) {
1217     pNext = p->next;
1218     ME_DestroyDisplayItem(p);    
1219     p = pNext;
1220   }
1221   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
1222   for (i=0; i<HFONT_CACHE_SIZE; i++)
1223   {
1224     if (editor->pFontCache[i].hFont)
1225       DeleteObject(editor->pFontCache[i].hFont);
1226   }
1227   DeleteObject(editor->hbrBackground);
1228   if(editor->lpOleCallback)
1229     IUnknown_Release(editor->lpOleCallback);
1230
1231   FREE_OBJ(editor);
1232 }
1233
1234 static const WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
1235 static const WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
1236 static const WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
1237 static const WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
1238
1239 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
1240 {
1241     TRACE("\n");
1242     switch (fdwReason)
1243     {
1244     case DLL_PROCESS_ATTACH:
1245       DisableThreadLibraryCalls(hinstDLL);
1246       me_heap = HeapCreate (0, 0x10000, 0);
1247       ME_RegisterEditorClass(hinstDLL);
1248       break;
1249
1250     case DLL_PROCESS_DETACH:
1251       UnregisterClassW(wszClassName, 0);
1252       UnregisterClassW(wszClassName50, 0);
1253       UnregisterClassA("RichEdit20A", 0);
1254       UnregisterClassA("RichEdit50A", 0);
1255       if (ME_ListBoxRegistered)
1256           UnregisterClassW(wszClassNameListBox, 0);
1257       if (ME_ComboBoxRegistered)
1258           UnregisterClassW(wszClassNameComboBox, 0);
1259       HeapDestroy (me_heap);
1260       me_heap = NULL;
1261       break;
1262     }
1263     return TRUE;
1264 }
1265
1266
1267 #define UNSUPPORTED_MSG(e) \
1268   case e: \
1269     FIXME(#e ": stub\n"); \
1270     return DefWindowProcW(hWnd, msg, wParam, lParam);
1271
1272 static const char * const edit_messages[] = {
1273   "EM_GETSEL",
1274   "EM_SETSEL",
1275   "EM_GETRECT",
1276   "EM_SETRECT",
1277   "EM_SETRECTNP",
1278   "EM_SCROLL",
1279   "EM_LINESCROLL",
1280   "EM_SCROLLCARET",
1281   "EM_GETMODIFY",
1282   "EM_SETMODIFY",
1283   "EM_GETLINECOUNT",
1284   "EM_LINEINDEX",
1285   "EM_SETHANDLE",
1286   "EM_GETHANDLE",
1287   "EM_GETTHUMB",
1288   "EM_UNKNOWN_BF",
1289   "EM_UNKNOWN_C0",
1290   "EM_LINELENGTH",
1291   "EM_REPLACESEL",
1292   "EM_UNKNOWN_C3",
1293   "EM_GETLINE",
1294   "EM_LIMITTEXT",
1295   "EM_CANUNDO",
1296   "EM_UNDO",
1297   "EM_FMTLINES",
1298   "EM_LINEFROMCHAR",
1299   "EM_UNKNOWN_CA",
1300   "EM_SETTABSTOPS",
1301   "EM_SETPASSWORDCHAR",
1302   "EM_EMPTYUNDOBUFFER",
1303   "EM_GETFIRSTVISIBLELINE",
1304   "EM_SETREADONLY",
1305   "EM_SETWORDBREAKPROC",
1306   "EM_GETWORDBREAKPROC",
1307   "EM_GETPASSWORDCHAR",
1308   "EM_SETMARGINS",
1309   "EM_GETMARGINS",
1310   "EM_GETLIMITTEXT",
1311   "EM_POSFROMCHAR",
1312   "EM_CHARFROMPOS"
1313 };
1314
1315 static const char * const richedit_messages[] = {
1316   "EM_CANPASTE",
1317   "EM_DISPLAYBAND",
1318   "EM_EXGETSEL",
1319   "EM_EXLIMITTEXT",
1320   "EM_EXLINEFROMCHAR",
1321   "EM_EXSETSEL",
1322   "EM_FINDTEXT",
1323   "EM_FORMATRANGE",
1324   "EM_GETCHARFORMAT",
1325   "EM_GETEVENTMASK",
1326   "EM_GETOLEINTERFACE",
1327   "EM_GETPARAFORMAT",
1328   "EM_GETSELTEXT",
1329   "EM_HIDESELECTION", 
1330   "EM_PASTESPECIAL",
1331   "EM_REQUESTRESIZE",
1332   "EM_SELECTIONTYPE",
1333   "EM_SETBKGNDCOLOR",
1334   "EM_SETCHARFORMAT",
1335   "EM_SETEVENTMASK",
1336   "EM_SETOLECALLBACK",
1337   "EM_SETPARAFORMAT",
1338   "EM_SETTARGETDEVICE",
1339   "EM_STREAMIN",
1340   "EM_STREAMOUT",
1341   "EM_GETTEXTRANGE",
1342   "EM_FINDWORDBREAK",
1343   "EM_SETOPTIONS",
1344   "EM_GETOPTIONS",
1345   "EM_FINDTEXTEX",
1346   "EM_GETWORDBREAKPROCEX",
1347   "EM_SETWORDBREAKPROCEX",
1348   "EM_SETUNDOLIMIT",
1349   "EM_UNKNOWN_USER_83",
1350   "EM_REDO",
1351   "EM_CANREDO",
1352   "EM_GETUNDONAME",
1353   "EM_GETREDONAME",
1354   "EM_STOPGROUPTYPING",
1355   "EM_SETTEXTMODE",
1356   "EM_GETTEXTMODE",
1357   "EM_AUTOURLDETECT",
1358   "EM_GETAUTOURLDETECT",
1359   "EM_SETPALETTE",
1360   "EM_GETTEXTEX",
1361   "EM_GETTEXTLENGTHEX",
1362   "EM_SHOWSCROLLBAR",
1363   "EM_SETTEXTEX",
1364   "EM_UNKNOWN_USER_98",
1365   "EM_UNKNOWN_USER_99",
1366   "EM_SETPUNCTUATION",
1367   "EM_GETPUNCTUATION",
1368   "EM_SETWORDWRAPMODE",
1369   "EM_GETWORDWRAPMODE",
1370   "EM_SETIMECOLOR",
1371   "EM_GETIMECOLOR",
1372   "EM_SETIMEOPTIONS",
1373   "EM_GETIMEOPTIONS",
1374   "EM_CONVPOSITION",
1375   "EM_UNKNOWN_USER_109",
1376   "EM_UNKNOWN_USER_110",
1377   "EM_UNKNOWN_USER_111",
1378   "EM_UNKNOWN_USER_112",
1379   "EM_UNKNOWN_USER_113",
1380   "EM_UNKNOWN_USER_114",
1381   "EM_UNKNOWN_USER_115",
1382   "EM_UNKNOWN_USER_116",
1383   "EM_UNKNOWN_USER_117",
1384   "EM_UNKNOWN_USER_118",
1385   "EM_UNKNOWN_USER_119",
1386   "EM_SETLANGOPTIONS",
1387   "EM_GETLANGOPTIONS",
1388   "EM_GETIMECOMPMODE",
1389   "EM_FINDTEXTW",
1390   "EM_FINDTEXTEXW",
1391   "EM_RECONVERSION",
1392   "EM_SETIMEMODEBIAS",
1393   "EM_GETIMEMODEBIAS"
1394 };
1395
1396 static const char *
1397 get_msg_name(UINT msg)
1398 {
1399   if (msg >= EM_GETSEL && msg <= EM_CHARFROMPOS)
1400     return edit_messages[msg - EM_GETSEL];
1401   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1402     return richedit_messages[msg - EM_CANPASTE];
1403   return "";
1404 }
1405
1406 /******************************************************************
1407  *        RichEditANSIWndProc (RICHED20.10)
1408  */
1409 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1410   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
1411   
1412   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1413         hWnd, msg, get_msg_name(msg), wParam, lParam);
1414   
1415   if (!editor && msg != WM_NCCREATE && msg != WM_NCDESTROY) {
1416     ERR("RichEditANSIWndProc called with invalid hWnd %p - application bug?\n", hWnd);
1417     return 0; 
1418   }
1419
1420   switch(msg) {
1421   
1422   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1423   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1424   UNSUPPORTED_MSG(EM_FMTLINES)
1425   UNSUPPORTED_MSG(EM_FORMATRANGE)
1426   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1427   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1428   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1429   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1430   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1431   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1432   UNSUPPORTED_MSG(EM_GETREDONAME)
1433   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1434   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1435   UNSUPPORTED_MSG(EM_GETUNDONAME)
1436   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1437   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1438   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1439   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1440   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1441   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1442   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1443   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1444   UNSUPPORTED_MSG(EM_SETPALETTE)
1445   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1446   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1447   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1448   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1449   UNSUPPORTED_MSG(WM_STYLECHANGING)
1450   UNSUPPORTED_MSG(WM_STYLECHANGED)
1451 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1452     
1453 /* Messages specific to Richedit controls */
1454   
1455   case EM_STREAMIN:
1456    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1457   case EM_STREAMOUT:
1458    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1459   case WM_GETDLGCODE:
1460   {
1461     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1462     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1463       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1464     return code;
1465   }
1466   case WM_NCCREATE:
1467   {
1468     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1469     TRACE("WM_NCCREATE: style 0x%08x\n", pcs->style);
1470     editor = ME_MakeEditor(hWnd);
1471     SetWindowLongPtrW(hWnd, 0, (LONG_PTR)editor);
1472     pcs = 0; /* ignore */
1473     return TRUE;
1474   }
1475   case EM_EMPTYUNDOBUFFER:
1476     ME_EmptyUndoStack(editor);
1477     return 0;
1478   case EM_GETSEL:
1479   {
1480     /* Note: wParam/lParam can be NULL */
1481     UINT from, to;
1482     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1483     PUINT pto = lParam ? (PUINT)lParam : &to;
1484     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1485     if ((*pfrom|*pto) & 0xFFFF0000)
1486       return -1;
1487     return MAKELONG(*pfrom,*pto);
1488   }
1489   case EM_EXGETSEL:
1490   {
1491     CHARRANGE *pRange = (CHARRANGE *)lParam;
1492     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1493     TRACE("EM_EXGETSEL = (%d,%d)\n", pRange->cpMin, pRange->cpMax);
1494     return 0;
1495   }
1496   case EM_SETUNDOLIMIT:
1497   {
1498     if ((int)wParam < 0)
1499       editor->nUndoLimit = STACK_SIZE_DEFAULT;
1500     else
1501       editor->nUndoLimit = min(wParam, STACK_SIZE_MAX);
1502     /* Setting a max stack size keeps wine from getting killed 
1503       for hogging memory. Windows allocates all this memory at once, so
1504       no program would realistically set a value above our maxiumum. */  
1505     return editor->nUndoLimit;
1506   }
1507   case EM_CANUNDO:
1508     return editor->pUndoStack != NULL;
1509   case EM_CANREDO:
1510     return editor->pRedoStack != NULL;
1511   case WM_UNDO: /* FIXME: actually not the same */
1512   case EM_UNDO:
1513     ME_Undo(editor);
1514     return 0;
1515   case EM_REDO:
1516     ME_Redo(editor);
1517     return 0;
1518   case EM_GETOPTIONS:
1519   {
1520     /* these flags are equivalent to the ES_* counterparts */
1521     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1522                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1523     DWORD settings = GetWindowLongW(hWnd, GWL_STYLE) & mask;
1524
1525     return settings;
1526   }
1527   case EM_SETOPTIONS:
1528   {
1529     /* these flags are equivalent to ES_* counterparts                      
1530      * ECO_READONLY is already implemented in the code, only requires 
1531      * setting the bit to work                                        
1532      */
1533     DWORD mask = ECO_VERTICAL | ECO_AUTOHSCROLL | ECO_AUTOVSCROLL |
1534                  ECO_NOHIDESEL | ECO_READONLY | ECO_WANTRETURN;
1535     DWORD raw = GetWindowLongW(hWnd, GWL_STYLE);
1536     DWORD settings = mask & raw;
1537
1538     switch(wParam)
1539     {
1540       case ECOOP_SET:
1541         settings = lParam;
1542         break;
1543       case ECOOP_OR:
1544         settings |= lParam;
1545         break;
1546       case ECOOP_AND:
1547         settings &= lParam;
1548         break;
1549       case ECOOP_XOR:
1550         settings ^= lParam;
1551     }
1552     SetWindowLongW(hWnd, GWL_STYLE, (raw & ~mask) | (settings & mask));
1553
1554     if (lParam & ECO_AUTOWORDSELECTION)
1555       FIXME("ECO_AUTOWORDSELECTION not implemented yet!\n");
1556     if (lParam & ECO_SELECTIONBAR)
1557       FIXME("ECO_SELECTIONBAR not implemented yet!\n");
1558     if (lParam & ECO_VERTICAL)
1559       FIXME("ECO_VERTICAL not implemented yet!\n");
1560     if (lParam & ECO_AUTOHSCROLL)
1561       FIXME("ECO_AUTOHSCROLL not implemented yet!\n");
1562     if (lParam & ECO_AUTOVSCROLL)
1563       FIXME("ECO_AUTOVSCROLL not implemented yet!\n");
1564     if (lParam & ECO_NOHIDESEL)
1565       FIXME("ECO_NOHIDESEL not implemented yet!\n");
1566     if (lParam & ECO_WANTRETURN)
1567       FIXME("ECO_WANTRETURN not implemented yet!\n");
1568
1569     return settings;
1570   }
1571   case EM_SETSEL:
1572   {
1573     ME_InvalidateSelection(editor);
1574     ME_SetSelection(editor, wParam, lParam);
1575     ME_InvalidateSelection(editor);
1576     ME_SendSelChange(editor);
1577     return 0;
1578   }
1579   case EM_SETSCROLLPOS:
1580   {
1581     POINT *point = (POINT *)lParam;
1582     ME_ScrollAbs(editor, point->y);
1583     return 0;
1584   }
1585   case EM_AUTOURLDETECT:
1586   {
1587     if (wParam==1 || wParam ==0) 
1588     {
1589         editor->AutoURLDetect_bEnable = (BOOL)wParam;
1590         return 0;
1591     }
1592     return E_INVALIDARG;
1593   }
1594   case EM_GETAUTOURLDETECT:
1595   {
1596     return editor->AutoURLDetect_bEnable;
1597   }
1598   case EM_EXSETSEL:
1599   {
1600     int start, end;
1601     CHARRANGE range = *(CHARRANGE *)lParam;
1602
1603     TRACE("EM_EXSETSEL (%d,%d)\n", range.cpMin, range.cpMax);
1604
1605     /* if cpMin < 0, then selection is deselected and caret moved to end of
1606      * the current selection  */
1607     if (range.cpMin < 0)
1608     {
1609         ME_GetSelection(editor, &start, &end);
1610         range.cpMin = end;
1611         range.cpMax = end;
1612     }  
1613     else if (range.cpMax > ME_GetTextLength(editor) +1)
1614     {
1615       range.cpMax = ME_GetTextLength(editor) + 1;
1616     }
1617
1618     ME_InvalidateSelection(editor);
1619     ME_SetSelection(editor, range.cpMin, range.cpMax);
1620     ME_InvalidateSelection(editor);
1621     ME_SendSelChange(editor);
1622     
1623     return range.cpMax;
1624   }
1625   case EM_SHOWSCROLLBAR:
1626   {
1627     ShowScrollBar(editor->hWnd, wParam, lParam);
1628     return 0;
1629   }
1630   case EM_SETTEXTEX:
1631   {
1632     LPWSTR wszText = (LPWSTR)lParam;
1633     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1634     size_t len = wszText ? lstrlenW(wszText) : 0;
1635     int from, to;
1636     ME_Style *style;
1637     TRACE("EM_SETTEXTEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1638     if (pStruct->codepage != 1200) {
1639       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1640       return 0;
1641     }
1642     /* FIXME: this should support RTF strings too, according to MSDN */
1643     if (pStruct->flags & ST_SELECTION) {
1644       ME_GetSelection(editor, &from, &to);
1645       style = ME_GetSelectionInsertStyle(editor);
1646       ME_InternalDeleteText(editor, from, to - from);
1647       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1648       ME_ReleaseStyle(style);
1649     }
1650     else {
1651       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1652       ME_InsertTextFromCursor(editor, 0, wszText, len, editor->pBuffer->pDefaultStyle);
1653       len = 1;
1654     }
1655     ME_CommitUndo(editor);
1656     if (!(pStruct->flags & ST_KEEPUNDO))
1657       ME_EmptyUndoStack(editor);
1658     ME_UpdateRepaint(editor);
1659     return len;
1660   }
1661   case EM_SETBKGNDCOLOR:
1662   {
1663     LRESULT lColor = ME_GetBackColor(editor);
1664     if (editor->rgbBackColor != -1)
1665       DeleteObject(editor->hbrBackground);
1666     if (wParam)
1667     {
1668       editor->rgbBackColor = -1;
1669       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1670     }
1671     else
1672     {
1673       editor->rgbBackColor = lParam;
1674       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1675     }
1676     if (editor->bRedraw)
1677     {
1678       InvalidateRect(hWnd, NULL, TRUE);
1679       UpdateWindow(hWnd);
1680     }
1681     return lColor;
1682   }
1683   case EM_GETMODIFY:
1684     return editor->nModifyStep == 0 ? 0 : 1;
1685   case EM_SETMODIFY:
1686   {
1687     if (wParam)
1688       editor->nModifyStep = 0x80000000;
1689     else
1690       editor->nModifyStep = 0;
1691     
1692     return 0;
1693   }
1694   case EM_SETREADONLY:
1695   {
1696     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1697     if (wParam)
1698       nStyle |= ES_READONLY;
1699     else
1700       nStyle &= ~ES_READONLY;
1701     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1702     return 0;
1703   }
1704   case EM_SETEVENTMASK:
1705   {
1706     DWORD nOldMask = editor->nEventMask;
1707     
1708     editor->nEventMask = lParam;
1709     return nOldMask;
1710   }
1711   case EM_GETEVENTMASK:
1712     return editor->nEventMask;
1713   case EM_SETCHARFORMAT:
1714   {
1715     CHARFORMAT2W buf, *p;
1716     BOOL bRepaint = TRUE;
1717     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1718     if (!wParam || (editor->mode & TM_PLAINTEXT))
1719       ME_SetDefaultCharFormat(editor, p);
1720     else if (wParam == (SCF_WORD | SCF_SELECTION))
1721       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1722     else if (wParam == SCF_ALL)
1723       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1724     else {
1725       int from, to;
1726       ME_GetSelection(editor, &from, &to);
1727       bRepaint = (from != to);
1728       ME_SetSelectionCharFormat(editor, p);
1729     }
1730     ME_CommitUndo(editor);
1731     if (bRepaint)
1732       ME_UpdateRepaint(editor);
1733     return 0;
1734   }
1735   case EM_GETCHARFORMAT:
1736   {
1737     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1738     if (dst->cbSize != sizeof(CHARFORMATA) &&
1739         dst->cbSize != sizeof(CHARFORMATW) &&
1740         dst->cbSize != sizeof(CHARFORMAT2A) &&
1741         dst->cbSize != sizeof(CHARFORMAT2W))
1742       return 0;
1743     tmp.cbSize = sizeof(tmp);
1744     if (!wParam)
1745       ME_GetDefaultCharFormat(editor, &tmp);
1746     else
1747       ME_GetSelectionCharFormat(editor, &tmp);
1748     ME_CopyToCFAny(dst, &tmp);
1749     return tmp.dwMask;
1750   }
1751   case EM_SETPARAFORMAT:
1752     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1753     ME_UpdateRepaint(editor);
1754     ME_CommitUndo(editor);
1755     return 0;
1756   case EM_GETPARAFORMAT:
1757     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1758     return 0;
1759   case EM_GETFIRSTVISIBLELINE:
1760   {
1761     ME_DisplayItem *p = editor->pBuffer->pFirst;
1762     int y = ME_GetYScrollPos(editor);
1763     int ypara = 0;
1764     int count = 0;
1765     int ystart, yend;
1766     while(p) {
1767       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1768       if (p->type == diTextEnd)
1769         break;
1770       if (p->type == diParagraph) {
1771         ypara = p->member.para.nYPos;
1772         continue;
1773       }
1774       ystart = ypara + p->member.row.nYPos;
1775       yend = ystart + p->member.row.nHeight;
1776       if (y < yend) {
1777         break;
1778       }
1779       count++;
1780     }
1781     return count;
1782   }
1783   case EM_HIDESELECTION:
1784   {
1785      editor->bHideSelection = (wParam != 0);
1786      ME_InvalidateSelection(editor);
1787      return 0;
1788   }
1789   case EM_LINESCROLL:
1790   {
1791     ME_ScrollDown(editor, lParam * 8); /* FIXME follow the original */
1792     return TRUE; /* Should return false if a single line richedit control */
1793   }
1794   case WM_CLEAR:
1795   {
1796     int from, to;
1797     ME_GetSelection(editor, &from, &to);
1798     ME_InternalDeleteText(editor, from, to-from);
1799     ME_CommitUndo(editor);
1800     ME_UpdateRepaint(editor);
1801     return 0;
1802   }
1803   case EM_REPLACESEL:
1804   {
1805     int from, to;
1806     ME_Style *style;
1807     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1808     size_t len = lstrlenW(wszText);
1809     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1810     
1811     ME_GetSelection(editor, &from, &to);
1812     style = ME_GetSelectionInsertStyle(editor);
1813     ME_InternalDeleteText(editor, from, to-from);
1814     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1815     ME_ReleaseStyle(style);
1816     ME_EndToUnicode(hWnd, wszText);
1817     /* drop temporary style if line end */
1818     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1819     if (len>0 && wszText[len-1] == '\n')
1820       ME_ClearTempStyle(editor);
1821       
1822     ME_CommitUndo(editor);
1823     if (!wParam)
1824       ME_EmptyUndoStack(editor);
1825     ME_UpdateRepaint(editor);
1826     return 0;
1827   }
1828   case EM_SCROLLCARET:
1829   {
1830     int top, bottom; /* row's edges relative to document top */
1831     int nPos;
1832     ME_DisplayItem *para, *row;
1833     
1834     nPos = ME_GetYScrollPos(editor);
1835     row = ME_RowStart(editor->pCursors[0].pRun);
1836     para = ME_GetParagraph(row);
1837     top = para->member.para.nYPos + row->member.row.nYPos;
1838     bottom = top + row->member.row.nHeight;
1839     
1840     if (top < nPos) /* caret above window */
1841       ME_ScrollAbs(editor,  top);
1842     else if (nPos + editor->sizeWindow.cy < bottom) /*below*/
1843       ME_ScrollAbs(editor, bottom - editor->sizeWindow.cy);
1844     return 0;
1845   }
1846   case WM_SETFONT:
1847   {
1848     LOGFONTW lf;
1849     CHARFORMAT2W fmt;
1850     HDC hDC;
1851     BOOL bRepaint = LOWORD(lParam);
1852     
1853     if (!wParam)
1854       wParam = (WPARAM)GetStockObject(SYSTEM_FONT); 
1855     GetObjectW((HGDIOBJ)wParam, sizeof(LOGFONTW), &lf);
1856     hDC = GetDC(hWnd);
1857     ME_CharFormatFromLogFont(hDC, &lf, &fmt); 
1858     ReleaseDC(hWnd, hDC);   
1859     ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), &fmt);
1860     ME_SetDefaultCharFormat(editor, &fmt);
1861
1862     ME_CommitUndo(editor);
1863     if (bRepaint)
1864       ME_UpdateRepaint(editor);
1865     return 0;
1866   }
1867   case WM_SETTEXT:
1868   {
1869     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1870     if (lParam)
1871     {
1872       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1873       if (!IsWindowUnicode(hWnd) && !strncmp((char *)lParam, "{\\rtf", 5))
1874       {
1875         /* Undocumented: WM_SETTEXT supports RTF text */
1876         ME_StreamInRTFString(editor, 0, (char *)lParam);
1877       }
1878       else
1879       {
1880         LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1881         TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1882         if (lstrlenW(wszText) > 0)
1883         {
1884           /* uses default style! */
1885           ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1886         }
1887         ME_EndToUnicode(hWnd, wszText);
1888       }
1889     }
1890     else
1891       TRACE("WM_SETTEXT - NULL\n");
1892     ME_CommitUndo(editor);
1893     ME_EmptyUndoStack(editor);
1894     ME_SetSelection(editor, 0, 0);
1895     ME_UpdateRepaint(editor);
1896     return 0;
1897   }
1898   case EM_CANPASTE:
1899   {
1900     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1901     if (IsClipboardFormatAvailable(nRTFFormat))
1902       return TRUE;
1903     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1904       return TRUE;
1905     return FALSE;
1906   }
1907   case WM_PASTE:
1908   {    
1909     DWORD dwFormat = 0;
1910     EDITSTREAM es;
1911     ME_GlobalDestStruct gds;
1912     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1913     UINT cf = 0;
1914
1915     if (IsClipboardFormatAvailable(nRTFFormat))
1916       cf = nRTFFormat, dwFormat = SF_RTF;
1917     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1918       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1919     else
1920       return 0;
1921
1922     if (!OpenClipboard(hWnd))
1923       return 0;
1924     gds.hData = GetClipboardData(cf);
1925     gds.nLength = 0;
1926     es.dwCookie = (DWORD)&gds;
1927     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1928     ME_StreamIn(editor, dwFormat|SFF_SELECTION, &es);
1929
1930     CloseClipboard();
1931     return 0;
1932   }
1933   case WM_CUT:
1934   case WM_COPY:
1935   {
1936     LPDATAOBJECT dataObj = NULL;
1937     CHARRANGE range;
1938     HRESULT hr = S_OK;
1939     
1940     if (editor->cPasswordMask)
1941       return 0; /* Copying or Cutting masked text isn't allowed */
1942     
1943     ME_GetSelection(editor, (int*)&range.cpMin, (int*)&range.cpMax);
1944     if(editor->lpOleCallback)
1945         hr = IRichEditOleCallback_GetClipboardData(editor->lpOleCallback, &range, RECO_COPY, &dataObj);
1946     if(FAILED(hr) || !dataObj)
1947         hr = ME_GetDataObject(editor, &range, &dataObj);
1948     if(SUCCEEDED(hr)) {
1949         hr = OleSetClipboard(dataObj);
1950         IDataObject_Release(dataObj);
1951     }
1952     if (SUCCEEDED(hr) && msg == WM_CUT)
1953     {
1954       ME_InternalDeleteText(editor, range.cpMin, range.cpMax-range.cpMin);
1955       ME_CommitUndo(editor);
1956       ME_UpdateRepaint(editor);
1957     }
1958     return 0;
1959   }
1960   case WM_GETTEXTLENGTH:
1961     return ME_GetTextLength(editor);
1962   case EM_GETTEXTLENGTHEX:
1963     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1964   case WM_GETTEXT:
1965   {
1966     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1967     tr.chrg.cpMin = 0;
1968     tr.chrg.cpMax = wParam-1;
1969     tr.lpstrText = (WCHAR *)lParam;
1970     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1971   }
1972   case EM_GETTEXTEX:
1973   {
1974     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1975     int nStart, nCount;
1976
1977     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1978       FIXME("GETTEXTEX flags 0x%08x not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1979
1980     if (ex->flags & GT_SELECTION)
1981     {
1982       ME_GetSelection(editor, &nStart, &nCount);
1983       nCount -= nStart;
1984       nCount = min(nCount, ex->cb - 1);
1985     }
1986     else
1987     {
1988       nStart = 0;
1989       nCount = ex->cb - 1;
1990     }
1991     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1992     {
1993       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1994       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1995     }
1996     else
1997     {
1998       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1999         we can just take a bigger buffer? :) */
2000       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
2001       LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (crlfmul*nCount + 1) * sizeof(WCHAR));
2002       DWORD buflen = ex->cb;
2003       LRESULT rc;
2004       DWORD flags = 0;
2005
2006       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
2007       rc = WideCharToMultiByte(ex->codepage, flags, buffer, -1, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
2008
2009       HeapFree(GetProcessHeap(),0,buffer);
2010       return rc;
2011     }
2012   }
2013   case EM_GETSELTEXT:
2014   {
2015     int from, to;
2016     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
2017     ME_GetSelection(editor, &from, &to);
2018     tr.chrg.cpMin = from;
2019     tr.chrg.cpMax = to;
2020     tr.lpstrText = (WCHAR *)lParam;
2021     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
2022   }
2023   case EM_GETSCROLLPOS:
2024   {
2025       POINT *point = (POINT *)lParam;
2026       point->x = 0; /* FIXME side scrolling not implemented */
2027       point->y = ME_GetYScrollPos(editor);
2028       return 1;
2029   }
2030   case EM_GETTEXTRANGE:
2031   {
2032     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
2033     TRACE("EM_GETTEXTRANGE min=%d max=%d unicode=%d emul1.0=%d length=%d\n",
2034       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
2035       editor->bEmulateVersion10, ME_GetTextLength(editor));
2036     if (IsWindowUnicode(hWnd))
2037       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
2038     else
2039     {
2040       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
2041       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
2042       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
2043       /* FIXME this is a potential security hole (buffer overrun) 
2044          if you know more about wchar->mbyte conversion please explain
2045       */
2046       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
2047       FREE_OBJ(p);
2048       return nChars;
2049     }
2050   }
2051   case EM_GETLINE:
2052   {
2053     ME_DisplayItem *run;
2054     const BOOL bUnicode = IsWindowUnicode(hWnd);
2055     const unsigned int nMaxChars = *(WORD *) lParam;
2056     unsigned int nEndChars, nCharsLeft = nMaxChars;
2057     char *dest = (char *) lParam;
2058     /* rich text editor 1.0 uses \r\n for line end, 2.0 uses just \r; 
2059     we need to know how if we have the extra \n or not */
2060     int nLF = editor->bEmulateVersion10;
2061
2062     TRACE("EM_GETLINE: row=%d, nMaxChars=%d (%s)\n", (int) wParam, nMaxChars,
2063           bUnicode ? "Unicode" : "Ansi");
2064
2065     run = ME_FindRowWithNumber(editor, wParam);
2066     if (run == NULL)
2067       return 0;
2068
2069     while (nCharsLeft && (run = ME_FindItemFwd(run, diRunOrStartRow))
2070            && !(run->member.run.nFlags & MERF_ENDPARA))
2071     {
2072       unsigned int nCopy;
2073       ME_String *strText;
2074       if (run->type != diRun)
2075         break;
2076       strText = run->member.run.strText;
2077       nCopy = min(nCharsLeft, strText->nLen);
2078
2079       if (bUnicode)
2080         lstrcpynW((LPWSTR) dest, strText->szData, nCopy);
2081       else
2082         nCopy = WideCharToMultiByte(CP_ACP, 0, strText->szData, nCopy, dest,
2083                                     nCharsLeft, NULL, NULL);
2084       dest += nCopy * (bUnicode ? sizeof(WCHAR) : 1);
2085       nCharsLeft -= nCopy;
2086     }
2087
2088     /* append \r\0 (or \r\n\0 in 1.0), space allowing */
2089     nEndChars = min(nCharsLeft, 2 + nLF);
2090     nCharsLeft -= nEndChars;
2091     if (bUnicode)
2092     {
2093       const WCHAR src[] = {'\r', '\0'};
2094       const WCHAR src10[] = {'\r', '\n', '\0'};
2095       lstrcpynW((LPWSTR) dest, nLF ? src10 : src, nEndChars);
2096     }
2097     else
2098       lstrcpynA(dest, nLF ? "\r\n" : "\r", nEndChars);
2099
2100     TRACE("EM_GETLINE: got %u bytes\n", nMaxChars - nCharsLeft);
2101
2102     if (nEndChars == 2 + nLF)
2103       return nMaxChars - nCharsLeft - 1; /* don't count \0 */
2104     else
2105       return nMaxChars - nCharsLeft;
2106   }
2107   case EM_GETLINECOUNT:
2108   {
2109     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
2110     int nRows = 0;
2111
2112     while (item != editor->pBuffer->pLast)
2113     {
2114       assert(item->type == diParagraph);
2115       nRows += item->member.para.nRows;
2116       item = item->member.para.next_para;
2117     }
2118     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
2119     return max(1, nRows);
2120   }
2121   case EM_LINEFROMCHAR:
2122   {
2123     if (wParam == -1)
2124       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
2125     else
2126       return ME_RowNumberFromCharOfs(editor, wParam);
2127   }
2128   case EM_EXLINEFROMCHAR:
2129   {
2130     if (lParam == -1)
2131       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor,1));
2132     else    
2133       return ME_RowNumberFromCharOfs(editor, lParam);
2134   }
2135   case EM_LINEINDEX:
2136   {
2137     ME_DisplayItem *item, *para;
2138     int nCharOfs;
2139     
2140     if (wParam == -1)
2141       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
2142     else
2143       item = ME_FindRowWithNumber(editor, wParam);
2144     if (!item)
2145       return -1;
2146     para = ME_GetParagraph(item);
2147     item = ME_FindItemFwd(item, diRun);
2148     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
2149     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
2150     return nCharOfs;
2151   }
2152   case EM_LINELENGTH:
2153   {
2154     ME_DisplayItem *item, *item_end;
2155     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
2156     
2157     if (wParam > ME_GetTextLength(editor))
2158       return 0;
2159     if (wParam == -1)
2160     {
2161       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
2162       return 0;
2163     }
2164     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
2165     item = ME_RowStart(item);
2166     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
2167     item_end = ME_FindItemFwd(item, diStartRowOrParagraphOrEnd);
2168     if (item_end->type == diStartRow)
2169       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
2170     else
2171       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
2172        - (editor->bEmulateVersion10?2:1);
2173     nChars = nNextLineOfs - nThisLineOfs;
2174     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
2175     return nChars;
2176   }
2177   case EM_EXLIMITTEXT:
2178   {
2179     if (wParam != 0 || lParam < 0)
2180      return 0;
2181     if (lParam == 0)
2182       editor->nTextLimit = 65536;
2183     else
2184       editor->nTextLimit = (int) lParam;
2185     return 0;
2186   }
2187   case EM_GETLIMITTEXT:
2188   {
2189     return editor->nTextLimit;
2190   }
2191   case EM_FINDTEXT:
2192   {
2193     FINDTEXTA *ft = (FINDTEXTA *)lParam;
2194     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
2195     WCHAR *tmp;
2196     
2197     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2198       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
2199     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
2200   }
2201   case EM_FINDTEXTEX:
2202   {
2203     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
2204     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
2205     WCHAR *tmp;
2206     
2207     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
2208       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
2209     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
2210   }
2211   case EM_FINDTEXTW:
2212   {
2213     FINDTEXTW *ft = (FINDTEXTW *)lParam;
2214     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
2215   }
2216   case EM_FINDTEXTEXW:
2217   {
2218     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
2219     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
2220   }
2221   case EM_GETZOOM:
2222     if (!wParam || !lParam)
2223       return FALSE;
2224     *(int *)wParam = editor->nZoomNumerator;
2225     *(int *)lParam = editor->nZoomDenominator;
2226     return TRUE;
2227   case EM_SETZOOM:
2228     return ME_SetZoom(editor, wParam, lParam);
2229   case EM_CHARFROMPOS:
2230     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
2231   case EM_POSFROMCHAR:
2232   {
2233     ME_DisplayItem *pRun;
2234     int nCharOfs, nOffset, nLength;
2235     POINTL pt = {0,0};
2236     
2237     nCharOfs = wParam; 
2238     /* detect which API version we're dealing with */
2239     if (wParam >= 0x40000)
2240         nCharOfs = lParam;
2241     nLength = ME_GetTextLength(editor);
2242     
2243     if (nCharOfs < nLength) { 
2244         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
2245         assert(pRun->type == diRun);
2246         pt.y = pRun->member.run.pt.y;
2247         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
2248         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
2249     } else {
2250         pt.x = 0;
2251         pt.y = editor->pBuffer->pLast->member.para.nYPos;
2252     }
2253     if (wParam >= 0x40000) {
2254         *(POINTL *)wParam = pt;
2255     }
2256     return MAKELONG( pt.x, pt.y );
2257   }
2258   case WM_CREATE:
2259     if (GetWindowLongW(hWnd, GWL_STYLE) & WS_HSCROLL)
2260     { /* Squelch the default horizontal scrollbar it would make */
2261       ShowScrollBar(editor->hWnd, SB_HORZ, FALSE);
2262     }
2263     ME_CommitUndo(editor);
2264     ME_WrapMarkedParagraphs(editor);
2265     ME_MoveCaret(editor);
2266     return 0;
2267   case WM_DESTROY:
2268     ME_DestroyEditor(editor);
2269     SetWindowLongPtrW(hWnd, 0, 0);
2270     return 0;
2271   case WM_LBUTTONDOWN:
2272     SetFocus(hWnd);
2273     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2274     SetCapture(hWnd);
2275     ME_LinkNotify(editor,msg,wParam,lParam);
2276     break;
2277   case WM_MOUSEMOVE:
2278     if (GetCapture() == hWnd)
2279       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
2280     ME_LinkNotify(editor,msg,wParam,lParam);
2281     break;
2282   case WM_LBUTTONUP:
2283     if (GetCapture() == hWnd)
2284       ReleaseCapture();
2285     ME_LinkNotify(editor,msg,wParam,lParam);
2286     break;
2287   case WM_LBUTTONDBLCLK:
2288     ME_LinkNotify(editor,msg,wParam,lParam);
2289     ME_SelectWord(editor);
2290     break;
2291   case WM_CONTEXTMENU:
2292     if (!ME_ShowContextMenu(editor, (short)LOWORD(lParam), (short)HIWORD(lParam)))
2293       goto do_default;
2294     break;
2295   case WM_PAINT:
2296     if (editor->bRedraw)
2297     {
2298       HDC hDC;
2299       PAINTSTRUCT ps;
2300
2301       hDC = BeginPaint(hWnd, &ps);
2302       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
2303       EndPaint(hWnd, &ps);
2304     }
2305     break;
2306   case WM_SETFOCUS:
2307     ME_ShowCaret(editor);
2308     ME_SendOldNotify(editor, EN_SETFOCUS);
2309     return 0;
2310   case WM_KILLFOCUS:
2311     ME_HideCaret(editor);
2312     ME_SendOldNotify(editor, EN_KILLFOCUS);
2313     return 0;
2314   case WM_ERASEBKGND:
2315   {
2316     if (editor->bRedraw)
2317     {
2318       HDC hDC = (HDC)wParam;
2319       RECT rc;
2320       if (GetUpdateRect(hWnd,&rc,TRUE))
2321       {
2322         FillRect(hDC, &rc, editor->hbrBackground);
2323       }
2324     }
2325     return 1;
2326   }
2327   case WM_COMMAND:
2328     TRACE("editor wnd command = %d\n", LOWORD(wParam));
2329     return 0;
2330   case WM_KEYDOWN:
2331     if (ME_KeyDown(editor, LOWORD(wParam)))
2332       return 0;
2333     goto do_default;
2334   case WM_CHAR: 
2335   {
2336     WCHAR wstr = LOWORD(wParam);
2337     if (editor->AutoURLDetect_bEnable)
2338       ME_AutoURLDetect(editor, wstr);
2339         
2340     switch (wstr)
2341     {
2342     case 1: /* Ctrl-A */
2343       ME_SetSelection(editor, 0, -1);
2344       return 0;
2345     case 3: /* Ctrl-C */
2346       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
2347       return 0;
2348     }
2349     
2350     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
2351       MessageBeep(MB_ICONERROR);
2352       return 0; /* FIXME really 0 ? */
2353     }
2354
2355     switch (wstr)
2356     {
2357     case 22: /* Ctrl-V */
2358       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
2359       return 0;
2360     case 24: /* Ctrl-X */
2361       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
2362       return 0;
2363     case 25: /* Ctrl-Y */
2364       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
2365       return 0;
2366     case 26: /* Ctrl-Z */
2367       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
2368       return 0;
2369     }
2370     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
2371       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
2372       ME_Style *style = ME_GetInsertStyle(editor, 0);
2373       ME_SaveTempStyle(editor);
2374       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
2375       ME_ReleaseStyle(style);
2376       ME_CommitUndo(editor);
2377       ME_UpdateRepaint(editor);
2378     }
2379     return 0;
2380   }
2381   case EM_SCROLL: /* fall through */
2382   case WM_VSCROLL: 
2383   {
2384     int origNPos;
2385     int lineHeight;
2386     
2387     origNPos = ME_GetYScrollPos(editor);
2388     lineHeight = 24;
2389     
2390     if (editor && editor->pBuffer && editor->pBuffer->pDefaultStyle)
2391       lineHeight = editor->pBuffer->pDefaultStyle->tm.tmHeight;
2392     if (lineHeight <= 0) lineHeight = 24;
2393     
2394     switch(LOWORD(wParam)) 
2395     {
2396       case SB_LINEUP:
2397         ME_ScrollUp(editor,lineHeight);
2398         break;
2399       case SB_LINEDOWN:
2400         ME_ScrollDown(editor,lineHeight);
2401         break;
2402       case SB_PAGEUP:
2403         ME_ScrollUp(editor,editor->sizeWindow.cy);
2404         break;
2405       case SB_PAGEDOWN:
2406         ME_ScrollDown(editor,editor->sizeWindow.cy);
2407         break;
2408       case SB_THUMBTRACK:
2409       case SB_THUMBPOSITION:
2410         ME_ScrollAbs(editor,HIWORD(wParam));
2411         break;
2412     }
2413     if (msg == EM_SCROLL)
2414       return 0x00010000 | (((ME_GetYScrollPos(editor) - origNPos)/lineHeight) & 0xffff);
2415     break;
2416   }
2417   case WM_MOUSEWHEEL:
2418   {
2419     int gcWheelDelta;
2420     UINT pulScrollLines;
2421     
2422     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
2423     gcWheelDelta = -GET_WHEEL_DELTA_WPARAM(wParam);
2424     
2425     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
2426     {
2427       /* FIXME follow the original */
2428       ME_ScrollDown(editor,pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8); 
2429     }
2430     break;
2431   }
2432   case EM_GETRECT:
2433   {
2434     *((RECT *)lParam) = editor->rcFormat;
2435     return 0;
2436   }
2437   case EM_SETRECT:
2438   case EM_SETRECTNP:
2439   {
2440     if (lParam)
2441     {
2442       RECT *rc = (RECT *)lParam;
2443       
2444       if (wParam)
2445       {
2446         editor->rcFormat.left += rc->left;
2447         editor->rcFormat.top += rc->top;
2448         editor->rcFormat.right += rc->right;
2449         editor->rcFormat.bottom += rc->bottom;
2450       }
2451       else
2452       {
2453         editor->rcFormat = *rc;
2454       }
2455     }
2456     else
2457     {
2458       GetClientRect(hWnd, &editor->rcFormat);
2459     }
2460     if (msg != EM_SETRECTNP)
2461       ME_RewrapRepaint(editor);
2462     return 0;
2463   }
2464   case EM_REQUESTRESIZE:
2465     ME_SendRequestResize(editor, TRUE);
2466     return 0;
2467   case WM_SETREDRAW:
2468     editor->bRedraw = wParam;
2469     return 0;
2470   case WM_SIZE:
2471   {
2472     GetClientRect(hWnd, &editor->rcFormat);
2473     ME_RewrapRepaint(editor);
2474     return DefWindowProcW(hWnd, msg, wParam, lParam);
2475   }
2476   case EM_GETOLEINTERFACE:
2477   {
2478     LPVOID *ppvObj = (LPVOID*) lParam;
2479     return CreateIRichEditOle(editor, ppvObj);
2480   }
2481   case EM_GETPASSWORDCHAR:
2482   {
2483     return editor->cPasswordMask;
2484   }
2485   case EM_SETOLECALLBACK:
2486     if(editor->lpOleCallback)
2487       IUnknown_Release(editor->lpOleCallback);
2488     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2489     if(editor->lpOleCallback)
2490       IUnknown_AddRef(editor->lpOleCallback);
2491     return TRUE;
2492   case EM_GETWORDBREAKPROC:
2493     return (LRESULT)editor->pfnWordBreak;
2494   case EM_SETWORDBREAKPROC:
2495   {
2496     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2497
2498     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2499     return (LRESULT)pfnOld;
2500   }
2501   case EM_SETTEXTMODE:
2502   {
2503     LRESULT ret;
2504     int mask = 0;
2505     int changes = 0;
2506     if ((ret = RichEditANSIWndProc(hWnd, WM_GETTEXTLENGTH, 0, 0)) == 0)
2507     {
2508       /*Check for valid wParam*/
2509       if ((((wParam & TM_RICHTEXT) && ((wParam & TM_PLAINTEXT) << 1))) ||
2510           (((wParam & TM_MULTILEVELUNDO) && ((wParam & TM_SINGLELEVELUNDO) << 1))) ||
2511           (((wParam & TM_MULTICODEPAGE) && ((wParam & TM_SINGLECODEPAGE) << 1))))
2512         return 1;
2513       else
2514       {
2515         if (wParam & (TM_RICHTEXT | TM_PLAINTEXT))
2516         {
2517           mask |= (TM_RICHTEXT | TM_PLAINTEXT);
2518           changes |= (wParam & (TM_RICHTEXT | TM_PLAINTEXT));
2519         }
2520         /*FIXME: Currently no support for undo level and code page options*/ 
2521         editor->mode = (editor->mode & (~mask)) | changes;
2522         return 0;
2523       }
2524     }
2525     return ret;
2526   }
2527   case EM_SETPASSWORDCHAR:
2528   {
2529     editor->cPasswordMask = wParam;
2530     ME_RewrapRepaint(editor);
2531     return 0;
2532   }
2533   default:
2534   do_default:
2535     return DefWindowProcW(hWnd, msg, wParam, lParam);
2536   }
2537   return 0L;
2538 }
2539
2540
2541 /******************************************************************
2542  *        RichEdit10ANSIWndProc (RICHED20.9)
2543  */
2544 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2545 {
2546   LRESULT result;
2547   
2548   /* FIXME: this is NOT the same as 2.0 version */
2549   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2550   if (msg == WM_NCCREATE)
2551   {
2552     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongPtrW(hWnd, 0);
2553     
2554     editor->bEmulateVersion10 = TRUE;
2555     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2556   }
2557   return result;
2558 }
2559
2560 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2561 {
2562   HWND hWnd = editor->hWnd;
2563   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2564 }
2565
2566 void ME_LinkNotify(ME_TextEditor *editor, UINT msg, WPARAM wParam, LPARAM lParam)
2567 {
2568   int x,y;
2569   ME_Cursor tmpCursor;
2570   ME_Run *tmpRun;
2571   BOOL bNothing;
2572   ENLINK info;
2573   x = (short)LOWORD(lParam);
2574   y = (short)HIWORD(lParam);
2575   ME_FindPixelPos(editor, x, y, &tmpCursor, &bNothing);
2576   tmpRun = &tmpCursor.pRun->member.run;
2577         
2578   if ((tmpRun->style->fmt.dwMask & CFM_LINK) 
2579     && (tmpRun->style->fmt.dwEffects & CFE_LINK))
2580   { /* The clicked run has CFE_LINK set */
2581     info.nmhdr.hwndFrom = editor->hWnd;
2582     info.nmhdr.idFrom = GetWindowLongW(editor->hWnd, GWLP_ID);
2583     info.nmhdr.code = EN_LINK;
2584     info.msg = msg;
2585     info.wParam = wParam;
2586     info.lParam = lParam;
2587     info.chrg.cpMin = ME_CharOfsFromRunOfs(editor,tmpCursor.pRun,0);
2588     info.chrg.cpMax = info.chrg.cpMin + ME_StrVLen(tmpRun->strText);
2589     SendMessageW(GetParent(editor->hWnd), WM_NOTIFY,info.nmhdr.idFrom, (LPARAM)&info);
2590   }  
2591 }
2592
2593 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2594 {
2595   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2596   int i = 0;
2597   
2598   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2599     item = item->member.para.next_para;
2600   if (!item)
2601     return 0;
2602   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2603     item = item->member.para.next_para;
2604     i++;
2605   }
2606   return i;
2607 }
2608
2609
2610 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2611 {
2612   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2613   int nWritten = 0;
2614   WCHAR *pStart = buffer;
2615   
2616   if (!item) {
2617     *buffer = L'\0';
2618     return 0;
2619   }
2620   
2621   if (nStart)
2622   {
2623     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2624     if (nLen > nChars)
2625       nLen = nChars;
2626     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2627     nChars -= nLen;
2628     nWritten += nLen;
2629     if (!nChars)
2630       return nWritten;
2631     buffer += nLen;
2632     nStart = 0;
2633     item = ME_FindItemFwd(item, diRun);
2634   }
2635   
2636   while(nChars && item)
2637   {
2638     int nLen = ME_StrLen(item->member.run.strText);
2639     if (nLen > nChars)
2640       nLen = nChars;
2641
2642     if (item->member.run.nFlags & MERF_ENDPARA)
2643     {
2644       if (!ME_FindItemFwd(item, diRun))
2645         /* No '\r' is appended to the last paragraph. */
2646         nLen = 0;
2647       else {
2648         *buffer = '\r';
2649         if (bCRLF)
2650         {
2651           *(++buffer) = '\n';
2652           nWritten++;
2653         }
2654         assert(nLen == 1);
2655         /* our end paragraph consists of 2 characters now */
2656         if (editor->bEmulateVersion10)
2657           nChars--;
2658       }
2659     }
2660     else
2661       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2662     nChars -= nLen;
2663     nWritten += nLen;
2664     buffer += nLen;    
2665       
2666     if (!nChars)
2667     {
2668       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2669       *buffer = L'\0';
2670       return nWritten;
2671     }
2672     item = ME_FindItemFwd(item, diRun);
2673   }
2674   *buffer = L'\0';
2675   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2676   return nWritten;  
2677 }
2678
2679 void ME_RegisterEditorClass(HINSTANCE hInstance)
2680 {
2681   BOOL bResult;
2682   WNDCLASSW wcW;
2683   WNDCLASSA wcA;
2684   
2685   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2686   wcW.lpfnWndProc = RichEditANSIWndProc;
2687   wcW.cbClsExtra = 0;
2688   wcW.cbWndExtra = sizeof(ME_TextEditor *);
2689   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2690   wcW.hIcon = NULL;
2691   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2692   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2693   wcW.lpszMenuName = NULL;
2694   wcW.lpszClassName = wszClassName;
2695   bResult = RegisterClassW(&wcW);  
2696   assert(bResult);
2697   wcW.lpszClassName = wszClassName50;
2698   bResult = RegisterClassW(&wcW);  
2699   assert(bResult);
2700
2701   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2702   wcA.lpfnWndProc = RichEditANSIWndProc;
2703   wcA.cbClsExtra = 0;
2704   wcA.cbWndExtra = sizeof(ME_TextEditor *);
2705   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2706   wcA.hIcon = NULL;
2707   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2708   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2709   wcA.lpszMenuName = NULL;
2710   wcA.lpszClassName = "RichEdit20A";
2711   bResult = RegisterClassA(&wcA);  
2712   assert(bResult);
2713   wcA.lpszClassName = "RichEdit50A";
2714   bResult = RegisterClassA(&wcA);  
2715   assert(bResult);
2716 }
2717
2718 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2719   /* FIXME: Not implemented */
2720   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2721         hWnd, msg, get_msg_name(msg), wParam, lParam);
2722   return DefWindowProcW(hWnd, msg, wParam, lParam);
2723 }
2724
2725 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2726   /* FIXME: Not implemented */
2727   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2728         hWnd, msg, get_msg_name(msg), wParam, lParam);
2729   return DefWindowProcW(hWnd, msg, wParam, lParam);
2730 }
2731
2732 /******************************************************************
2733  *        REExtendedRegisterClass (RICHED20.8)
2734  *
2735  * FIXME undocumented
2736  * Need to check for errors and implement controls and callbacks 
2737  */
2738 LRESULT WINAPI REExtendedRegisterClass(void)
2739 {
2740   WNDCLASSW wcW;
2741   UINT result;
2742
2743   FIXME("semi stub\n");
2744
2745   wcW.cbClsExtra = 0;
2746   wcW.cbWndExtra = 4;
2747   wcW.hInstance = NULL;
2748   wcW.hIcon = NULL;
2749   wcW.hCursor = NULL;
2750   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2751   wcW.lpszMenuName = NULL;
2752
2753   if (!ME_ListBoxRegistered)
2754   {
2755       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2756       wcW.lpfnWndProc = REListWndProc;
2757       wcW.lpszClassName = wszClassNameListBox;
2758       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2759   }
2760
2761   if (!ME_ComboBoxRegistered)
2762   {
2763       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2764       wcW.lpfnWndProc = REComboWndProc;
2765       wcW.lpszClassName = wszClassNameComboBox;
2766       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2767   }
2768
2769   result = 0;
2770   if (ME_ListBoxRegistered)
2771       result += 1;
2772   if (ME_ComboBoxRegistered)
2773       result += 2;
2774
2775   return result;
2776 }
2777
2778 int ME_AutoURLDetect(ME_TextEditor *editor, WCHAR curChar) 
2779 {
2780   struct prefix_s {
2781     const char *text;
2782     int length;
2783   } prefixes[12] = {
2784     {"http:", 5},
2785     {"file:", 6},
2786     {"mailto:", 8},
2787     {"ftp:", 5},
2788     {"https:", 7},
2789     {"gopher:", 8},
2790     {"nntp:", 6},
2791     {"prospero:", 10},
2792     {"telnet:", 8},
2793     {"news:", 6},
2794     {"wais:", 6},
2795     {"www.", 5}
2796   };
2797   CHARRANGE ins_pt;
2798   int curf_ef, link_ef, def_ef;
2799   int cur_prefx, prefx_cnt;
2800   int sel_min, sel_max;
2801   int car_pos = 0;
2802   int text_pos=-1;
2803   int URLmin, URLmax = 0;
2804   CHARRANGE url;
2805   FINDTEXTA ft;
2806   CHARFORMAT2W cur_format;
2807   CHARFORMAT2W default_format;
2808   CHARFORMAT2W link;
2809   RichEditANSIWndProc(editor->hWnd, EM_EXGETSEL, (WPARAM) 0, (LPARAM) &ins_pt);
2810   sel_min = ins_pt.cpMin;
2811   sel_max = ins_pt.cpMax;
2812   if (sel_min==sel_max) 
2813     car_pos = sel_min;
2814   if (sel_min!=sel_max)
2815     car_pos = ME_GetTextLength(editor)+1;   
2816   cur_format.cbSize = sizeof(cur_format);
2817   default_format.cbSize = sizeof(default_format);
2818   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_SELECTION, (LPARAM) &cur_format);
2819   RichEditANSIWndProc(editor->hWnd, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM) &default_format);
2820   link.cbSize = sizeof(link);
2821   link.dwMask = CFM_LINK;
2822   link.dwEffects = CFE_LINK;
2823   curf_ef = cur_format.dwEffects & link.dwEffects;
2824   def_ef = default_format.dwEffects & link.dwEffects;
2825   link_ef = link.dwEffects & link.dwEffects;
2826   if (curf_ef == link_ef) 
2827   {
2828     if( curChar == '\n' || curChar=='\r' || curChar==' ') 
2829     {
2830       ME_SetSelection(editor, car_pos, car_pos);
2831       RichEditANSIWndProc(editor->hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &default_format);
2832       text_pos=-1;
2833       return 0;
2834     }
2835   }
2836   if (curf_ef == def_ef)
2837   {
2838     cur_prefx = 0;
2839     prefx_cnt = (sizeof(prefixes)/sizeof(struct prefix_s))-1;
2840     while (cur_prefx<=prefx_cnt) 
2841     {
2842       if (text_pos == -1) 
2843       {
2844         ft.lpstrText = prefixes[cur_prefx].text;
2845         URLmin=max(0,(car_pos-prefixes[cur_prefx].length));
2846         URLmax=max(0, car_pos);
2847         if ((car_pos == 0) && (ME_GetTextLength(editor) != 0))
2848         {
2849         URLmax = ME_GetTextLength(editor)+1;
2850         }
2851         ft.chrg.cpMin = URLmin;
2852         ft.chrg.cpMax = URLmax;
2853         text_pos=RichEditANSIWndProc(editor->hWnd, EM_FINDTEXT, FR_DOWN, (LPARAM)&ft);   
2854         cur_prefx++;
2855       }
2856       if (text_pos != -1) 
2857       {
2858         url.cpMin=text_pos;
2859         url.cpMax=car_pos-1;
2860         ME_SetCharFormat(editor, text_pos, (URLmax-text_pos), &link);
2861         ME_RewrapRepaint(editor);
2862         break;
2863       }
2864     }
2865   }
2866   return 0;
2867 }