riched20: Implement EM_SETOLECALLBACK.
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
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
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 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
234
235 int me_debug = 0;
236 HANDLE me_heap = NULL;
237
238 static BOOL ME_ListBoxRegistered = FALSE;
239 static BOOL ME_ComboBoxRegistered = FALSE;
240
241 static ME_TextBuffer *ME_MakeText(void) {
242   
243   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
244
245   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
246   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
247   
248   p1->prev = NULL;
249   p1->next = p2;
250   p2->prev = p1;
251   p2->next = NULL;
252   p1->member.para.next_para = p2;
253   p2->member.para.prev_para = p1;
254   p2->member.para.nCharOfs = 0;  
255   
256   buf->pFirst = p1;
257   buf->pLast = p2;
258   buf->pCharStyle = NULL;
259   
260   return buf;
261 }
262
263
264 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
265 {
266   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
267   WCHAR *pText;
268   
269   TRACE("%08lx %p\n", dwFormat, stream);
270   
271   do {
272     long nWideChars = 0;
273
274     if (!stream->dwSize)
275     {
276       ME_StreamInFill(stream);
277       if (stream->editstream->dwError)
278         break;
279       if (!stream->dwSize)
280         break;
281     }
282       
283     if (!(dwFormat & SF_UNICODE))
284     {
285       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
286       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
287       pText = wszText;
288     }
289     else
290     {
291       nWideChars = stream->dwSize >> 1;
292       pText = (WCHAR *)stream->buffer;
293     }
294     
295     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
296     if (stream->dwSize == 0)
297       break;
298     stream->dwSize = 0;
299   } while(1);
300   ME_CommitUndo(editor);
301   ME_UpdateRepaint(editor);
302   return 0;
303 }
304
305 static void ME_RTFCharAttrHook(RTF_Info *info)
306 {
307   CHARFORMAT2W fmt;
308   fmt.cbSize = sizeof(fmt);
309   fmt.dwMask = 0;
310   
311   switch(info->rtfMinor)
312   {
313     case rtfPlain:
314       /* FIXME add more flags once they're implemented */
315       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
316       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
317       fmt.yHeight = 12*20; /* 12pt */
318       fmt.wWeight = 400;
319       break;
320     case rtfBold:
321       fmt.dwMask = CFM_BOLD;
322       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
323       break;
324     case rtfItalic:
325       fmt.dwMask = CFM_ITALIC;
326       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
327       break;
328     case rtfUnderline:
329       fmt.dwMask = CFM_UNDERLINE;
330       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
331       fmt.bUnderlineType = CFU_CF1UNDERLINE;
332       break;
333     case rtfNoUnderline:
334       fmt.dwMask = CFM_UNDERLINE;
335       fmt.dwEffects = 0;
336       break;
337     case rtfStrikeThru:
338       fmt.dwMask = CFM_STRIKEOUT;
339       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
340       break;
341     case rtfSubScript:
342     case rtfSuperScript:
343     case rtfSubScrShrink:
344     case rtfSuperScrShrink:
345     case rtfNoSuperSub:
346       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
347       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
348       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
349       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
350       break;
351     case rtfInvisible:
352       fmt.dwMask = CFM_HIDDEN;
353       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
354       break;
355     case rtfBackColor:
356       fmt.dwMask = CFM_BACKCOLOR;
357       fmt.dwEffects = 0;
358       if (info->rtfParam == 0)
359         fmt.dwEffects = CFE_AUTOBACKCOLOR;
360       else if (info->rtfParam != rtfNoParam)
361       {
362         RTFColor *c = RTFGetColor(info, info->rtfParam);
363         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
364       }
365       break;
366     case rtfForeColor:
367       fmt.dwMask = CFM_COLOR;
368       fmt.dwEffects = 0;
369       if (info->rtfParam == 0)
370         fmt.dwEffects = CFE_AUTOCOLOR;
371       else if (info->rtfParam != rtfNoParam)
372       {
373         RTFColor *c = RTFGetColor(info, info->rtfParam);
374         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
375       }
376       break;
377     case rtfFontNum:
378       if (info->rtfParam != rtfNoParam)
379       {
380         RTFFont *f = RTFGetFont(info, info->rtfParam);
381         if (f)
382         {
383           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
384           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
385           fmt.bCharSet = f->rtfFCharSet;
386           fmt.dwMask = CFM_FACE | CFM_CHARSET;
387         }
388       }
389       break;
390     case rtfFontSize:
391       fmt.dwMask = CFM_SIZE;
392       if (info->rtfParam != rtfNoParam)
393         fmt.yHeight = info->rtfParam*10;
394       break;
395   }
396   if (fmt.dwMask) {
397     ME_Style *style2;
398     RTFFlushOutputBuffer(info);
399     /* FIXME too slow ? how come ? */
400     style2 = ME_ApplyStyle(info->style, &fmt);
401     ME_ReleaseStyle(info->style);
402     info->style = style2;
403     info->styleChanged = TRUE;
404   }
405 }
406
407 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
408    the same tags mean different things in different contexts */
409 static void ME_RTFParAttrHook(RTF_Info *info)
410 {
411   PARAFORMAT2 fmt;
412   fmt.cbSize = sizeof(fmt);
413   fmt.dwMask = 0;
414   
415   switch(info->rtfMinor)
416   {
417   case rtfParDef: /* I'm not 100% sure what does it do, but I guess it restores default paragraph attributes */
418     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
419     fmt.wAlignment = PFA_LEFT;
420     fmt.cTabCount = 0;
421     fmt.dxOffset = fmt.dxStartIndent = 0;
422     break;
423   case rtfFirstIndent:
424     ME_GetSelectionParaFormat(info->editor, &fmt);
425     fmt.dwMask = PFM_STARTINDENT | PFM_OFFSET;
426     fmt.dxStartIndent += info->rtfParam + fmt.dxOffset;
427     fmt.dxOffset = -info->rtfParam;
428     break;
429   case rtfLeftIndent:
430     ME_GetSelectionParaFormat(info->editor, &fmt);
431     fmt.dwMask = PFM_STARTINDENT;
432     fmt.dxStartIndent = -fmt.dxOffset + info->rtfParam;
433     break;
434   case rtfRightIndent:
435     fmt.dwMask = PFM_RIGHTINDENT;
436     fmt.dxRightIndent = info->rtfParam;
437     break;
438   case rtfQuadLeft:
439   case rtfQuadJust:
440     fmt.dwMask = PFM_ALIGNMENT;
441     fmt.wAlignment = PFA_LEFT;
442     break;
443   case rtfQuadRight:
444     fmt.dwMask = PFM_ALIGNMENT;
445     fmt.wAlignment = PFA_RIGHT;
446     break;
447   case rtfQuadCenter:
448     fmt.dwMask = PFM_ALIGNMENT;
449     fmt.wAlignment = PFA_CENTER;
450     break;
451   case rtfTabPos:
452     ME_GetSelectionParaFormat(info->editor, &fmt);
453     if (!(fmt.dwMask & PFM_TABSTOPS))
454     {
455       fmt.dwMask |= PFM_TABSTOPS;
456       fmt.cTabCount = 0;
457     }
458     if (fmt.cTabCount < MAX_TAB_STOPS)
459       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
460     break;
461   }  
462   if (fmt.dwMask) {
463     RTFFlushOutputBuffer(info);
464     /* FIXME too slow ? how come ?*/
465     ME_SetSelectionParaFormat(info->editor, &fmt);
466   }
467 }
468
469 static void ME_RTFReadHook(RTF_Info *info) {
470   switch(info->rtfClass)
471   {
472     case rtfGroup:
473       switch(info->rtfMajor)
474       {
475         case rtfBeginGroup:
476           if (info->stackTop < maxStack) {
477             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
478             info->stack[info->stackTop].codePage = info->codePage;
479             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
480           }
481           info->stackTop++;
482           info->styleChanged = FALSE;
483           break;
484         case rtfEndGroup:
485         {
486           ME_Style *s;
487           RTFFlushOutputBuffer(info);
488           if (info->stackTop<=1) {
489             info->rtfClass = rtfEOF;
490             return;
491           }
492           info->stackTop--;
493           assert(info->stackTop >= 0);
494           if (info->styleChanged)
495           {
496             /* FIXME too slow ? how come ? */
497             s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
498             ME_ReleaseStyle(info->style);
499             info->style = s;
500             info->codePage = info->stack[info->stackTop].codePage;
501             info->unicodeLength = info->stack[info->stackTop].unicodeLength;
502           }
503           break;
504         }
505       }
506       break;
507     case rtfControl:
508       switch(info->rtfMajor)
509       {
510         case rtfCharAttr:
511           ME_RTFCharAttrHook(info);
512           break;
513         case rtfParAttr:
514           ME_RTFParAttrHook(info);
515           break;
516       }
517       break;
518   }
519 }
520
521 void
522 ME_StreamInFill(ME_InStream *stream)
523 {
524   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
525                                                                 (BYTE *)stream->buffer,
526                                                                 sizeof(stream->buffer),
527                                                                 (LONG *)&stream->dwSize);
528   stream->dwUsed = 0;
529 }
530
531 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
532 {
533   RTF_Info parser;
534   ME_Style *style;
535   int from, to, to2, nUndoMode;
536   ME_UndoItem *pUI;
537   int nEventMask = editor->nEventMask;
538   ME_InStream inStream;
539
540   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
541   editor->nEventMask = 0;
542   
543   ME_GetSelection(editor, &from, &to);
544   if (format & SFF_SELECTION) {
545     style = ME_GetSelectionInsertStyle(editor);
546
547     ME_InternalDeleteText(editor, from, to-from);
548   }
549   else {
550     style = editor->pBuffer->pDefaultStyle;
551     ME_AddRefStyle(style);
552     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
553     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
554     from = to = 0;
555     ME_ClearTempStyle(editor);
556     /* FIXME restore default paragraph formatting ! */
557   }
558   
559   nUndoMode = editor->nUndoMode;
560   editor->nUndoMode = umIgnore;
561
562   inStream.editstream = stream;
563   inStream.editstream->dwError = 0;
564   inStream.dwSize = 0;
565   inStream.dwUsed = 0;
566
567   if (format & SF_RTF)
568   {
569     /* Check if it's really RTF, and if it is not, use plain text */
570     ME_StreamInFill(&inStream);
571     if (!inStream.editstream->dwError)
572     {
573       if (strncmp(inStream.buffer, "{\\rtf1", 6) && strncmp(inStream.buffer, "{\\urtf", 6))
574       {
575         format &= ~SF_RTF;
576         format |= SF_TEXT;
577       }
578     }
579   }
580
581   if (!inStream.editstream->dwError)
582   {
583     if (format & SF_RTF) {
584       /* setup the RTF parser */
585       memset(&parser, 0, sizeof parser);
586       RTFSetEditStream(&parser, &inStream);
587       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
588       parser.hwndEdit = editor->hWnd;
589       parser.editor = editor;
590       parser.style = style;
591       WriterInit(&parser);
592       RTFInit(&parser);
593       RTFSetReadHook(&parser, ME_RTFReadHook);
594       BeginFile(&parser);
595   
596       /* do the parsing */
597       RTFRead(&parser);
598       RTFFlushOutputBuffer(&parser);
599       RTFDestroy(&parser);
600
601       style = parser.style;
602     }
603     else if (format & SF_TEXT)
604       ME_StreamInText(editor, format, &inStream, style);
605     else
606       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
607     ME_GetSelection(editor, &to, &to2);
608     /* put the cursor at the top */
609     if (!(format & SFF_SELECTION))
610       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
611   }
612   
613   editor->nUndoMode = nUndoMode;
614   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
615   TRACE("from %d to %d\n", from, to);
616   if (pUI && from < to)
617   {
618     pUI->nStart = from;
619     pUI->nLen = to-from;
620   }
621   ME_CommitUndo(editor);
622   ME_ReleaseStyle(style); 
623   editor->nEventMask = nEventMask;
624   if (editor->bRedraw)
625   {
626     ME_UpdateRepaint(editor);
627   }
628   if (!(format & SFF_SELECTION)) {
629     ME_ClearTempStyle(editor);
630   }
631   ME_MoveCaret(editor);
632   ME_SendSelChange(editor);
633   ME_SendRequestResize(editor, FALSE);
634
635   return 0;
636 }
637
638
639 ME_DisplayItem *
640 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
641 {
642   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
643   
644   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
645     item = ME_FindItemFwd(item, diParagraph);
646
647   if (!item)
648     return item;
649
650   nOffset -= item->member.para.nCharOfs;
651   if (nItemType == diParagraph) {
652     if (nItemOffset)
653       *nItemOffset = nOffset;
654     return item;
655   }
656   
657   do {
658     item = ME_FindItemFwd(item, diRun);
659   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
660   if (item) {
661     nOffset -= item->member.run.nCharOfs;
662     if (nItemOffset)
663       *nItemOffset = nOffset;
664   }
665   return item;
666 }
667
668
669 static int
670 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, WCHAR *text, CHARRANGE *chrgText)
671 {
672   int nStart, nEnd;
673   int nLen = lstrlenW(text);
674   int nMin, nMax;
675   ME_DisplayItem *item;
676   ME_DisplayItem *para;
677
678   TRACE("flags==0x%08lx, chrg->cpMin==%ld, chrg->cpMax==%ld text==%s\n",
679         flags, chrg->cpMin, chrg->cpMax, debugstr_w(text));
680   
681   if (!(flags & FR_MATCHCASE))
682     FIXME("Case-insensitive search not implemented\n");
683   if (flags & ~(FR_DOWN | FR_MATCHCASE))
684     FIXME("Flags 0x%08lx not implemented\n", flags & ~(FR_DOWN | FR_MATCHCASE));
685
686   if (chrg->cpMax == -1)
687   {
688     nMin = chrg->cpMin;
689     nMax = ME_GetTextLength(editor);
690   }
691   else
692   {
693     nMin = min(chrg->cpMin, chrg->cpMax);
694     nMax = max(chrg->cpMin, chrg->cpMax);
695   }
696   
697   if (!nLen)
698   {
699     if (chrgText)
700       chrgText->cpMin = chrgText->cpMax = ((flags & FR_DOWN) ? nMin : nMax);
701     return chrgText->cpMin;
702   }
703  
704   if (flags & FR_DOWN) /* Forward search */
705   {
706     nStart = nMin;
707     item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
708     if (!item)
709       return -1;
710
711     para = ME_GetParagraph(item);
712     while (item
713            && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen < nMax)
714     {
715       ME_DisplayItem *pCurItem = item;
716       int nCurStart = nStart;
717       int nMatched = 0;
718     
719       while (pCurItem && pCurItem->member.run.strText->szData[nCurStart + nMatched] == text[nMatched])
720       {
721         nMatched++;
722         if (nMatched == nLen)
723         {
724           nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
725           if (chrgText)
726           {
727             chrgText->cpMin = nStart;
728             chrgText->cpMax = nStart + nLen;
729           }
730           TRACE("found at %d-%d\n", nStart, nStart + nLen);
731           return nStart;
732         }
733         if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
734         {
735           pCurItem = ME_FindItemFwd(pCurItem, diRun);
736           para = ME_GetParagraph(pCurItem);
737           nCurStart = -nMatched;
738         }
739       }
740       nStart++;
741       if (nStart == ME_StrLen(item->member.run.strText))
742       {
743         item = ME_FindItemFwd(item, diRun);
744         para = ME_GetParagraph(item);
745         nStart = 0;
746       }
747     }
748   }
749   else /* Backward search */
750   {
751     nEnd = nMax;
752     item = ME_FindItemAtOffset(editor, diRun, nEnd, &nEnd);
753     if (!item)
754       return -1;
755     
756     para = ME_GetParagraph(item);
757     
758     while (item
759            && para->member.para.nCharOfs + item->member.run.nCharOfs + nEnd - nLen >= nMin)
760     {
761       ME_DisplayItem *pCurItem = item;
762       int nCurEnd = nEnd;
763       int nMatched = 0;
764       
765       while (pCurItem && pCurItem->member.run.strText->szData[nCurEnd - nMatched - 1] == text[nLen - nMatched - 1])
766       {
767         nMatched++;
768         if (nMatched == nLen)
769         {
770           nStart = para->member.para.nCharOfs + item->member.run.nCharOfs + nCurEnd - nMatched;
771           if (chrgText)
772           {
773             chrgText->cpMin = nStart;
774             chrgText->cpMax = nStart + nLen;
775           }
776           TRACE("found at %d-%d\n", nStart, nStart + nLen);
777           return nStart;
778         }
779         if (nCurEnd - nMatched == 0)
780         {
781           pCurItem = ME_FindItemBack(pCurItem, diRun);
782           para = ME_GetParagraph(pCurItem);
783           nCurEnd = ME_StrLen(pCurItem->member.run.strText) + nMatched;
784         }
785       }
786       nEnd--;
787       if (nEnd < 0)
788       {
789         item = ME_FindItemBack(item, diRun);
790         para = ME_GetParagraph(item);
791         nEnd = ME_StrLen(item->member.run.strText);
792       }
793     }
794   }
795   TRACE("not found\n");
796   return -1;
797 }
798
799
800 static BOOL
801 ME_KeyDown(ME_TextEditor *editor, WORD nKey)
802 {
803   BOOL ctrl_is_down = GetKeyState(VK_CONTROL) & 0x8000;
804   BOOL shift_is_down = GetKeyState(VK_SHIFT) & 0x8000;
805   
806   switch (nKey)
807   {
808     case VK_LEFT:
809     case VK_RIGHT:
810     case VK_UP:
811     case VK_DOWN:
812     case VK_HOME:
813     case VK_END:
814     case VK_PRIOR:
815     case VK_NEXT:
816       ME_ArrowKey(editor, nKey, shift_is_down, ctrl_is_down);
817       return TRUE;
818     case VK_BACK:
819     case VK_DELETE:
820       /* FIXME backspace and delete aren't the same, they act different wrt paragraph style of the merged paragraph */
821       if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY)
822         return FALSE;
823       if (ME_IsSelection(editor))
824         ME_DeleteSelection(editor);
825       else if (nKey == VK_DELETE || ME_ArrowKey(editor, VK_LEFT, FALSE, FALSE))
826         ME_DeleteTextAtCursor(editor, 1, 1);
827       else
828         return TRUE;
829       ME_QueueInvalidateFromCursor(editor, 1);
830       ME_UpdateRepaint(editor);
831       ME_SendRequestResize(editor, FALSE);
832       return TRUE;
833
834     default:
835       if (ctrl_is_down)
836       {
837         if (nKey == 'W')
838         {
839           CHARFORMAT2W chf;
840           char buf[2048];
841           
842           ME_GetSelectionCharFormat(editor, &chf);
843           ME_DumpStyleToBuf(&chf, buf);
844           MessageBoxA(NULL, buf, "Style dump", MB_OK);
845         }
846         if (nKey == 'Q')
847         {
848           ME_CheckCharOffsets(editor);
849         }
850       }
851   }
852   return FALSE;
853 }
854
855
856 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
857   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
858   HDC hDC;
859   int i;
860   ed->hWnd = hWnd;
861   ed->bEmulateVersion10 = FALSE;
862   ed->pBuffer = ME_MakeText();
863   hDC = GetDC(hWnd);
864   ME_MakeFirstParagraph(hDC, ed->pBuffer);
865   ReleaseDC(hWnd, hDC);
866   ed->bCaretShown = FALSE;
867   ed->nCursors = 3;
868   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
869   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
870   ed->pCursors[0].nOffset = 0;
871   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
872   ed->pCursors[1].nOffset = 0;
873   ed->nLastTotalLength = ed->nTotalLength = 0;
874   ed->nUDArrowX = -1;
875   ed->nSequence = 0;
876   ed->rgbBackColor = -1;
877   ed->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
878   ed->bCaretAtEnd = FALSE;
879   ed->nEventMask = 0;
880   ed->nModifyStep = 0;
881   ed->pUndoStack = ed->pRedoStack = NULL;
882   ed->nUndoMode = umAddToUndo;
883   ed->nParagraphs = 1;
884   ed->nLastSelStart = ed->nLastSelEnd = 0;
885   ed->nScrollPosY = 0;
886   ed->nZoomNumerator = ed->nZoomDenominator = 0;
887   ed->bRedraw = TRUE;
888   ed->nInvalidOfs = -1;
889   ed->pfnWordBreak = NULL;
890   ed->lpOleCallback = NULL;
891   GetClientRect(hWnd, &ed->rcFormat);
892   for (i=0; i<HFONT_CACHE_SIZE; i++)
893   {
894     ed->pFontCache[i].nRefs = 0;
895     ed->pFontCache[i].nAge = 0;
896     ed->pFontCache[i].hFont = NULL;
897   }
898   ME_CheckCharOffsets(ed);
899   return ed;
900 }
901
902 typedef struct tagME_GlobalDestStruct
903 {
904   HGLOBAL hData;
905   int nLength;
906 } ME_GlobalDestStruct;
907
908 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
909 {
910   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
911   int nMaxSize;
912   BYTE *pDest;
913   
914   nMaxSize = GlobalSize(pData->hData);
915   if (pData->nLength+cb+1 >= cb)
916   {
917     /* round up to 2^17 */
918     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
919     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
920   }
921   pDest = (BYTE *)GlobalLock(pData->hData);
922   memcpy(pDest + pData->nLength, lpBuff, cb);
923   pData->nLength += cb;
924   pDest[pData->nLength] = '\0';
925   GlobalUnlock(pData->hData);
926   *pcb = cb;
927   
928   return 0;
929 }
930
931 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
932 {
933   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
934   int i;
935   WORD *pSrc, *pDest;
936   
937   cb = cb >> 1;
938   pDest = (WORD *)lpBuff;
939   pSrc = (WORD *)GlobalLock(pData->hData);
940   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
941     pDest[i] = pSrc[pData->nLength+i];
942   }    
943   pData->nLength += i;
944   *pcb = 2*i;
945   GlobalUnlock(pData->hData);
946   return 0;
947 }
948
949 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
950 {
951   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
952   int i;
953   BYTE *pSrc, *pDest;
954   
955   pDest = lpBuff;
956   pSrc = (BYTE *)GlobalLock(pData->hData);
957   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
958     pDest[i] = pSrc[pData->nLength+i];
959   }    
960   pData->nLength += i;
961   *pcb = i;
962   GlobalUnlock(pData->hData);
963   return 0;
964 }
965
966
967 void ME_DestroyEditor(ME_TextEditor *editor)
968 {
969   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
970   ME_DisplayItem *p = pFirst, *pNext = NULL;
971   int i;
972   
973   ME_ClearTempStyle(editor);
974   ME_EmptyUndoStack(editor);
975   while(p) {
976     pNext = p->next;
977     ME_DestroyDisplayItem(p);    
978     p = pNext;
979   }
980   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
981   for (i=0; i<HFONT_CACHE_SIZE; i++)
982   {
983     if (editor->pFontCache[i].hFont)
984       DeleteObject(editor->pFontCache[i].hFont);
985   }
986   DeleteObject(editor->hbrBackground);
987   if(editor->lpOleCallback)
988     IUnknown_Release(editor->lpOleCallback);
989
990   FREE_OBJ(editor);
991 }
992
993 static const WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
994 static const WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
995 static const WCHAR wszClassNameListBox[] = {'R','E','L','i','s','t','B','o','x','2','0','W', 0};
996 static const WCHAR wszClassNameComboBox[] = {'R','E','C','o','m','b','o','B','o','x','2','0','W', 0};
997
998 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
999 {
1000     TRACE("\n");
1001     switch (fdwReason)
1002     {
1003     case DLL_PROCESS_ATTACH:
1004       DisableThreadLibraryCalls(hinstDLL);
1005       me_heap = HeapCreate (0, 0x10000, 0);
1006       ME_RegisterEditorClass(hinstDLL);
1007       break;
1008
1009     case DLL_PROCESS_DETACH:
1010       UnregisterClassW(wszClassName, 0);
1011       UnregisterClassW(wszClassName50, 0);
1012       UnregisterClassA("RichEdit20A", 0);
1013       UnregisterClassA("RichEdit50A", 0);
1014       if (ME_ListBoxRegistered)
1015           UnregisterClassW(wszClassNameListBox, 0);
1016       if (ME_ComboBoxRegistered)
1017           UnregisterClassW(wszClassNameComboBox, 0);
1018       HeapDestroy (me_heap);
1019       me_heap = NULL;
1020       break;
1021     }
1022     return TRUE;
1023 }
1024
1025
1026 #define UNSUPPORTED_MSG(e) \
1027   case e: \
1028     FIXME(#e ": stub\n"); \
1029     return DefWindowProcW(hWnd, msg, wParam, lParam);
1030
1031 static const char * const edit_messages[] = {
1032   "EM_GETSEL",
1033   "EM_SETSEL",
1034   "EM_GETRECT",
1035   "EM_SETRECT",
1036   "EM_SETRECTNP",
1037   "EM_SCROLL",
1038   "EM_LINESCROLL",
1039   "EM_SCROLLCARET",
1040   "EM_GETMODIFY",
1041   "EM_SETMODIFY",
1042   "EM_GETLINECOUNT",
1043   "EM_LINEINDEX",
1044   "EM_SETHANDLE",
1045   "EM_GETHANDLE",
1046   "EM_GETTHUMB",
1047   "EM_UNKNOWN_BF",
1048   "EM_UNKNOWN_C0",
1049   "EM_LINELENGTH",
1050   "EM_REPLACESEL",
1051   "EM_UNKNOWN_C3",
1052   "EM_GETLINE",
1053   "EM_LIMITTEXT",
1054   "EM_CANUNDO",
1055   "EM_UNDO",
1056   "EM_FMTLINES",
1057   "EM_LINEFROMCHAR",
1058   "EM_UNKNOWN_CA",
1059   "EM_SETTABSTOPS",
1060   "EM_SETPASSWORDCHAR",
1061   "EM_EMPTYUNDOBUFFER",
1062   "EM_GETFIRSTVISIBLELINE",
1063   "EM_SETREADONLY",
1064   "EM_SETWORDBREAKPROC",
1065   "EM_GETWORDBREAKPROC",
1066   "EM_GETPASSWORDCHAR",
1067   "EM_SETMARGINS",
1068   "EM_GETMARGINS",
1069   "EM_GETLIMITTEXT",
1070   "EM_POSFROMCHAR",
1071   "EM_CHARFROMPOS"
1072 };
1073
1074 static const char * const richedit_messages[] = {
1075   "EM_CANPASTE",
1076   "EM_DISPLAYBAND",
1077   "EM_EXGETSEL",
1078   "EM_EXLIMITTEXT",
1079   "EM_EXLINEFROMCHAR",
1080   "EM_EXSETSEL",
1081   "EM_FINDTEXT",
1082   "EM_FORMATRANGE",
1083   "EM_GETCHARFORMAT",
1084   "EM_GETEVENTMASK",
1085   "EM_GETOLEINTERFACE",
1086   "EM_GETPARAFORMAT",
1087   "EM_GETSELTEXT",
1088   "EM_HIDESELECTION",
1089   "EM_PASTESPECIAL",
1090   "EM_REQUESTRESIZE",
1091   "EM_SELECTIONTYPE",
1092   "EM_SETBKGNDCOLOR",
1093   "EM_SETCHARFORMAT",
1094   "EM_SETEVENTMASK",
1095   "EM_SETOLECALLBACK",
1096   "EM_SETPARAFORMAT",
1097   "EM_SETTARGETDEVICE",
1098   "EM_STREAMIN",
1099   "EM_STREAMOUT",
1100   "EM_GETTEXTRANGE",
1101   "EM_FINDWORDBREAK",
1102   "EM_SETOPTIONS",
1103   "EM_GETOPTIONS",
1104   "EM_FINDTEXTEX",
1105   "EM_GETWORDBREAKPROCEX",
1106   "EM_SETWORDBREAKPROCEX",
1107   "EM_SETUNDOLIMIT",
1108   "EM_UNKNOWN_USER_83",
1109   "EM_REDO",
1110   "EM_CANREDO",
1111   "EM_GETUNDONAME",
1112   "EM_GETREDONAME",
1113   "EM_STOPGROUPTYPING",
1114   "EM_SETTEXTMODE",
1115   "EM_GETTEXTMODE",
1116   "EM_AUTOURLDETECT",
1117   "EM_GETAUTOURLDETECT",
1118   "EM_SETPALETTE",
1119   "EM_GETTEXTEX",
1120   "EM_GETTEXTLENGTHEX",
1121   "EM_SHOWSCROLLBAR",
1122   "EM_SETTEXTEX",
1123   "EM_UNKNOWN_USER_98",
1124   "EM_UNKNOWN_USER_99",
1125   "EM_SETPUNCTUATION",
1126   "EM_GETPUNCTUATION",
1127   "EM_SETWORDWRAPMODE",
1128   "EM_GETWORDWRAPMODE",
1129   "EM_SETIMECOLOR",
1130   "EM_GETIMECOLOR",
1131   "EM_SETIMEOPTIONS",
1132   "EM_GETIMEOPTIONS",
1133   "EM_CONVPOSITION",
1134   "EM_UNKNOWN_USER_109",
1135   "EM_UNKNOWN_USER_110",
1136   "EM_UNKNOWN_USER_111",
1137   "EM_UNKNOWN_USER_112",
1138   "EM_UNKNOWN_USER_113",
1139   "EM_UNKNOWN_USER_114",
1140   "EM_UNKNOWN_USER_115",
1141   "EM_UNKNOWN_USER_116",
1142   "EM_UNKNOWN_USER_117",
1143   "EM_UNKNOWN_USER_118",
1144   "EM_UNKNOWN_USER_119",
1145   "EM_SETLANGOPTIONS",
1146   "EM_GETLANGOPTIONS",
1147   "EM_GETIMECOMPMODE",
1148   "EM_FINDTEXTW",
1149   "EM_FINDTEXTEXW",
1150   "EM_RECONVERSION",
1151   "EM_SETIMEMODEBIAS",
1152   "EM_GETIMEMODEBIAS"
1153 };
1154
1155 static const char *
1156 get_msg_name(UINT msg)
1157 {
1158   if (msg >= EM_GETSEL && msg <= EM_SETLIMITTEXT)
1159     return edit_messages[msg - EM_GETSEL];
1160   if (msg >= EM_CANPASTE && msg <= EM_GETIMEMODEBIAS)
1161     return richedit_messages[msg - EM_CANPASTE];
1162   return "";
1163 }
1164
1165 /******************************************************************
1166  *        RichEditANSIWndProc (RICHED20.10)
1167  */
1168 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
1169   SCROLLINFO si;
1170   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
1171   
1172   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
1173         hWnd, msg, get_msg_name(msg), wParam, lParam);
1174   
1175   switch(msg) {
1176   
1177   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
1178   UNSUPPORTED_MSG(EM_DISPLAYBAND)
1179   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
1180   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
1181   UNSUPPORTED_MSG(EM_FMTLINES)
1182   UNSUPPORTED_MSG(EM_FORMATRANGE)
1183   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
1184   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
1185   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
1186   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
1187   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
1188   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
1189   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
1190   UNSUPPORTED_MSG(EM_GETLINE)
1191   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
1192   UNSUPPORTED_MSG(EM_GETOPTIONS)
1193   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
1194   UNSUPPORTED_MSG(EM_GETREDONAME)
1195   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
1196   UNSUPPORTED_MSG(EM_GETTEXTMODE)
1197   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
1198   UNSUPPORTED_MSG(EM_GETUNDONAME)
1199   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
1200   UNSUPPORTED_MSG(EM_HIDESELECTION)
1201   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
1202   UNSUPPORTED_MSG(EM_PASTESPECIAL)
1203   UNSUPPORTED_MSG(EM_SCROLL)
1204   UNSUPPORTED_MSG(EM_SCROLLCARET)
1205   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
1206   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
1207   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
1208   UNSUPPORTED_MSG(EM_SETFONTSIZE)
1209   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
1210   UNSUPPORTED_MSG(EM_SETOPTIONS)
1211   UNSUPPORTED_MSG(EM_SETPALETTE)
1212   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
1213   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
1214   UNSUPPORTED_MSG(EM_SETTABSTOPS)
1215   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
1216   UNSUPPORTED_MSG(EM_SETTEXTMODE)
1217   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
1218   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
1219   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
1220   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
1221   UNSUPPORTED_MSG(WM_SETFONT)
1222   UNSUPPORTED_MSG(WM_STYLECHANGING)
1223   UNSUPPORTED_MSG(WM_STYLECHANGED)
1224 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
1225     
1226 /* Messages specific to Richedit controls */
1227   
1228   case EM_STREAMIN:
1229    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
1230   case EM_STREAMOUT:
1231    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
1232   case WM_GETDLGCODE:
1233   {
1234     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
1235     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
1236       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
1237     return code;
1238   }
1239   case WM_NCCREATE:
1240   {
1241     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
1242     TRACE("WM_NCCREATE: style 0x%08lx\n", pcs->style);
1243     editor = ME_MakeEditor(hWnd);
1244     SetWindowLongW(hWnd, 0, (long)editor);
1245     pcs = 0; /* ignore */
1246     return TRUE;
1247   }
1248   case EM_EMPTYUNDOBUFFER:
1249     ME_EmptyUndoStack(editor);
1250     return 0;
1251   case EM_GETSEL:
1252   {
1253     /* Note: wParam/lParam can be NULL */
1254     UINT from, to;
1255     PUINT pfrom = wParam ? (PUINT)wParam : &from;
1256     PUINT pto = lParam ? (PUINT)lParam : &to;
1257     ME_GetSelection(editor, (int *)pfrom, (int *)pto);
1258     if ((*pfrom|*pto) & 0xFFFF0000)
1259       return -1;
1260     return MAKELONG(*pfrom,*pto);
1261   }
1262   case EM_EXGETSEL:
1263   {
1264     CHARRANGE *pRange = (CHARRANGE *)lParam;
1265     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
1266     TRACE("EM_EXGETSEL = (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1267     return 0;
1268   }
1269   case EM_CANUNDO:
1270     return editor->pUndoStack != NULL;
1271   case EM_CANREDO:
1272     return editor->pRedoStack != NULL;
1273   case WM_UNDO: /* FIXME: actually not the same */
1274   case EM_UNDO:
1275     ME_Undo(editor);
1276     return 0;
1277   case EM_REDO:
1278     ME_Redo(editor);
1279     return 0;
1280   case EM_SETSEL:
1281   {
1282     ME_InvalidateSelection(editor);
1283     ME_SetSelection(editor, wParam, lParam);
1284     ME_InvalidateSelection(editor);
1285     ME_SendSelChange(editor);
1286     return 0;
1287   }
1288   case EM_EXSETSEL:
1289   {
1290     CHARRANGE *pRange = (CHARRANGE *)lParam;
1291     TRACE("EM_EXSETSEL (%ld,%ld)\n", pRange->cpMin, pRange->cpMax);
1292     ME_InvalidateSelection(editor);
1293     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
1294     ME_InvalidateSelection(editor);
1295     ME_SendSelChange(editor);
1296     return 0;
1297   }
1298   case EM_SETTEXTEX:
1299   {
1300     LPWSTR wszText = (LPWSTR)lParam;
1301     SETTEXTEX *pStruct = (SETTEXTEX *)wParam;
1302     size_t len = lstrlenW(wszText);
1303     int from, to;
1304     ME_Style *style;
1305     TRACE("EM_SETTEXEX - %s, flags %d, cp %d\n", debugstr_w(wszText), (int)pStruct->flags, pStruct->codepage);
1306     if (pStruct->codepage != 1200) {
1307       FIXME("EM_SETTEXTEX only supports unicode right now!\n"); 
1308       return 0;
1309     }
1310     /* FIXME: this should support RTF strings too, according to MSDN */
1311     if (pStruct->flags & ST_SELECTION) {
1312       ME_GetSelection(editor, &from, &to);
1313       style = ME_GetSelectionInsertStyle(editor);
1314       ME_InternalDeleteText(editor, from, to - from);
1315       ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1316       ME_ReleaseStyle(style);
1317     }
1318     else {
1319       ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1320       ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1321       len = 1;
1322     }
1323     ME_CommitUndo(editor);
1324     if (!(pStruct->flags & ST_KEEPUNDO))
1325       ME_EmptyUndoStack(editor);
1326     ME_UpdateRepaint(editor);
1327     return len;
1328   }
1329   case EM_SETBKGNDCOLOR:
1330   {
1331     LRESULT lColor = ME_GetBackColor(editor);
1332     if (editor->rgbBackColor != -1)
1333       DeleteObject(editor->hbrBackground);
1334     if (wParam)
1335     {
1336       editor->rgbBackColor = -1;
1337       editor->hbrBackground = GetSysColorBrush(COLOR_WINDOW);
1338     }
1339     else
1340     {
1341       editor->rgbBackColor = lParam;
1342       editor->hbrBackground = CreateSolidBrush(editor->rgbBackColor);
1343     }
1344     if (editor->bRedraw)
1345     {
1346       InvalidateRect(hWnd, NULL, TRUE);
1347       UpdateWindow(hWnd);
1348     }
1349     return lColor;
1350   }
1351   case EM_GETMODIFY:
1352     return editor->nModifyStep == 0 ? 0 : 1;
1353   case EM_SETMODIFY:
1354   {
1355     if (wParam)
1356       editor->nModifyStep = 0x80000000;
1357     else
1358       editor->nModifyStep = 0;
1359     
1360     return 0;
1361   }
1362   case EM_SETREADONLY:
1363   {
1364     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1365     if (wParam)
1366       nStyle |= ES_READONLY;
1367     else
1368       nStyle &= ~ES_READONLY;
1369     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1370     return 0;
1371   }
1372   case EM_SETEVENTMASK:
1373   {
1374     DWORD nOldMask = editor->nEventMask;
1375     
1376     editor->nEventMask = lParam;
1377     return nOldMask;
1378   }
1379   case EM_GETEVENTMASK:
1380     return editor->nEventMask;
1381   case EM_SETCHARFORMAT:
1382   {
1383     CHARFORMAT2W buf, *p;
1384     BOOL bRepaint = TRUE;
1385     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1386     if (!wParam)
1387       ME_SetDefaultCharFormat(editor, p);
1388     else if (wParam == (SCF_WORD | SCF_SELECTION))
1389       FIXME("EM_SETCHARFORMAT: word selection not supported\n");
1390     else if (wParam == SCF_ALL)
1391       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1392     else {
1393       int from, to;
1394       ME_GetSelection(editor, &from, &to);
1395       bRepaint = (from != to);
1396       ME_SetSelectionCharFormat(editor, p);
1397     }
1398     ME_CommitUndo(editor);
1399     if (bRepaint)
1400       ME_UpdateRepaint(editor);
1401     return 0;
1402   }
1403   case EM_GETCHARFORMAT:
1404   {
1405     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1406     if (dst->cbSize != sizeof(CHARFORMATA) &&
1407         dst->cbSize != sizeof(CHARFORMATW) &&
1408         dst->cbSize != sizeof(CHARFORMAT2A) &&
1409         dst->cbSize != sizeof(CHARFORMAT2W))
1410       return 0;
1411     tmp.cbSize = sizeof(tmp);
1412     if (!wParam)
1413       ME_GetDefaultCharFormat(editor, &tmp);
1414     else
1415       ME_GetSelectionCharFormat(editor, &tmp);
1416     ME_CopyToCFAny(dst, &tmp);
1417     return tmp.dwMask;
1418   }
1419   case EM_SETPARAFORMAT:
1420     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1421     ME_UpdateRepaint(editor);
1422     ME_CommitUndo(editor);
1423     return 0;
1424   case EM_GETPARAFORMAT:
1425     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1426     return 0;
1427   case EM_GETFIRSTVISIBLELINE:
1428   {
1429     ME_DisplayItem *p = editor->pBuffer->pFirst;
1430     int y = editor->nScrollPosY;
1431     int ypara = 0;
1432     int count = 0;
1433     int ystart, yend;
1434     while(p) {
1435       p = ME_FindItemFwd(p, diStartRowOrParagraphOrEnd);
1436       if (p->type == diTextEnd)
1437         break;
1438       if (p->type == diParagraph) {
1439         ypara = p->member.para.nYPos;
1440         continue;
1441       }
1442       ystart = ypara + p->member.row.nYPos;
1443       yend = ystart + p->member.row.nHeight;
1444       if (y < yend) {
1445         break;
1446       }
1447       count++;
1448     }
1449     return count;
1450   }
1451   case EM_LINESCROLL:
1452   {
1453     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1454     nPos += 8 * lParam; /* FIXME follow the original */
1455     if (nPos>=nEnd)
1456       nPos = nEnd;
1457     if (nPos<0)
1458       nPos = 0;
1459     if (nPos != editor->nScrollPosY) {
1460       int dy = editor->nScrollPosY - nPos;
1461       editor->nScrollPosY = nPos;
1462       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1463       if (editor->bRedraw)
1464       {
1465         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1466         UpdateWindow(hWnd);
1467       }
1468     }
1469     return TRUE; /* Should return false if a single line richedit control */
1470   }
1471   case WM_CLEAR:
1472   {
1473     int from, to;
1474     ME_GetSelection(editor, &from, &to);
1475     ME_InternalDeleteText(editor, from, to-from);
1476     ME_CommitUndo(editor);
1477     ME_UpdateRepaint(editor);
1478     return 0;
1479   }
1480   case EM_REPLACESEL:
1481   {
1482     int from, to;
1483     ME_Style *style;
1484     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1485     size_t len = lstrlenW(wszText);
1486     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1487     
1488     ME_GetSelection(editor, &from, &to);
1489     style = ME_GetSelectionInsertStyle(editor);
1490     ME_InternalDeleteText(editor, from, to-from);
1491     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1492     ME_ReleaseStyle(style);
1493     ME_EndToUnicode(hWnd, wszText);
1494     /* drop temporary style if line end */
1495     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1496     if (len>0 && wszText[len-1] == '\n')
1497       ME_ClearTempStyle(editor);
1498       
1499     ME_CommitUndo(editor);
1500     if (!wParam)
1501       ME_EmptyUndoStack(editor);
1502     ME_UpdateRepaint(editor);
1503     return 0;
1504   }
1505   case WM_SETTEXT:
1506   {
1507     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1508     if (lParam)
1509     {
1510       LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1511       TRACE("WM_SETTEXT lParam==%lx\n",lParam);
1512       TRACE("WM_SETTEXT - %s\n", debugstr_w(wszText)); /* debugstr_w() */
1513       if (lstrlenW(wszText) > 0)
1514       {
1515         /* uses default style! */
1516         ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1517       }
1518       ME_EndToUnicode(hWnd, wszText);
1519     }
1520     else
1521       TRACE("WM_SETTEXT - NULL\n");
1522     ME_CommitUndo(editor);
1523     ME_EmptyUndoStack(editor);
1524     ME_SetSelection(editor, 0, 0);
1525     ME_UpdateRepaint(editor);
1526     return 0;
1527   }
1528   case EM_CANPASTE:
1529   {
1530     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1531     if (IsClipboardFormatAvailable(nRTFFormat))
1532       return TRUE;
1533     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1534       return TRUE;
1535     return FALSE;
1536   }
1537   case WM_PASTE:
1538   {    
1539     DWORD dwFormat = 0;
1540     EDITSTREAM es;
1541     ME_GlobalDestStruct gds;
1542     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1543     UINT cf = 0;
1544
1545     if (IsClipboardFormatAvailable(nRTFFormat))
1546       cf = nRTFFormat, dwFormat = SF_RTF;
1547     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1548       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1549     else
1550       return 0;
1551
1552     if (!OpenClipboard(hWnd))
1553       return 0;
1554     gds.hData = GetClipboardData(cf);
1555     gds.nLength = 0;
1556     es.dwCookie = (DWORD)&gds;
1557     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1558     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1559     
1560     CloseClipboard();
1561     return 0;
1562   }
1563   case WM_CUT:
1564   case WM_COPY:
1565   {
1566     int from, to, pars;
1567     WCHAR *data;
1568     HANDLE hData;
1569     EDITSTREAM es;
1570     ME_GlobalDestStruct gds;
1571     
1572     if (!OpenClipboard(hWnd))
1573       return 0;
1574       
1575     EmptyClipboard();
1576     ME_GetSelection(editor, &from, &to);
1577     pars = ME_CountParagraphsBetween(editor, from, to);
1578     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1579     data = (WCHAR *)GlobalLock(hData);
1580     ME_GetTextW(editor, data, from, to-from, TRUE);
1581     GlobalUnlock(hData);
1582
1583     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1584     gds.nLength = 0;
1585     es.dwCookie = (DWORD)&gds;
1586     es.pfnCallback = ME_AppendToHGLOBAL;
1587     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1588     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1589     
1590     SetClipboardData(CF_UNICODETEXT, hData);    
1591     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1592     
1593     CloseClipboard();
1594     if (msg == WM_CUT)
1595     {
1596       ME_InternalDeleteText(editor, from, to-from);
1597       ME_CommitUndo(editor);
1598       ME_UpdateRepaint(editor);
1599     }
1600     return 0;
1601   }
1602   case WM_GETTEXTLENGTH:
1603     return ME_GetTextLength(editor);
1604   case EM_GETTEXTLENGTHEX:
1605     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1606   case WM_GETTEXT:
1607   {
1608     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1609     tr.chrg.cpMin = 0;
1610     tr.chrg.cpMax = wParam-1;
1611     tr.lpstrText = (WCHAR *)lParam;
1612     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1613   }
1614   case EM_GETTEXTEX:
1615   {
1616     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1617     int nStart, nCount;
1618
1619     if (ex->flags & ~(GT_SELECTION | GT_USECRLF))
1620       FIXME("GETTEXTEX flags 0x%08lx not supported\n", ex->flags & ~(GT_SELECTION | GT_USECRLF));
1621
1622     if (ex->flags & GT_SELECTION)
1623     {
1624       ME_GetSelection(editor, &nStart, &nCount);
1625       nCount -= nStart;
1626       nCount = min(nCount, ex->cb - 1);
1627     }
1628     else
1629     {
1630       nStart = 0;
1631       nCount = ex->cb - 1;
1632     }
1633     if (ex->codepage == 1200 || IsWindowUnicode(hWnd))
1634     {
1635       nCount = min(nCount, ex->cb / sizeof(WCHAR) - 1);
1636       return ME_GetTextW(editor, (LPWSTR)lParam, nStart, nCount, ex->flags & GT_USECRLF);
1637     }
1638     else
1639     {
1640       /* potentially each char may be a CR, why calculate the exact value with O(N) when
1641         we can just take a bigger buffer? :) */
1642       int crlfmul = (ex->flags & GT_USECRLF) ? 2 : 1;
1643       LPWSTR buffer = HeapAlloc(GetProcessHeap(), 0, (crlfmul*nCount + 1) * sizeof(WCHAR));
1644       DWORD buflen = ex->cb;
1645       LRESULT rc;
1646       DWORD flags = 0;
1647
1648       buflen = ME_GetTextW(editor, buffer, nStart, nCount, ex->flags & GT_USECRLF);
1649       rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
1650
1651       HeapFree(GetProcessHeap(),0,buffer);
1652       return rc;
1653     }
1654   }
1655   case EM_GETSELTEXT:
1656   {
1657     int from, to;
1658     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1659     ME_GetSelection(editor, &from, &to);
1660     tr.chrg.cpMin = from;
1661     tr.chrg.cpMax = to;
1662     tr.lpstrText = (WCHAR *)lParam;
1663     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1664   }
1665   case EM_GETTEXTRANGE:
1666   {
1667     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1668     TRACE("EM_GETTEXTRANGE min=%ld max=%ld unicode=%d emul1.0=%d length=%d\n",
1669       rng->chrg.cpMin, rng->chrg.cpMax, IsWindowUnicode(hWnd), 
1670       editor->bEmulateVersion10, ME_GetTextLength(editor));
1671     if (IsWindowUnicode(hWnd))
1672       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, editor->bEmulateVersion10);
1673     else
1674     {
1675       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1676       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1677       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, editor->bEmulateVersion10);
1678       /* FIXME this is a potential security hole (buffer overrun) 
1679          if you know more about wchar->mbyte conversion please explain
1680       */
1681       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1682       FREE_OBJ(p);
1683       return nChars;
1684     }
1685   }
1686   case EM_GETLINECOUNT:
1687   {
1688     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
1689     int nRows = 0;
1690
1691     while (item != editor->pBuffer->pLast)
1692     {
1693       assert(item->type == diParagraph);
1694       nRows += item->member.para.nRows;
1695       item = item->member.para.next_para;
1696     }
1697     TRACE("EM_GETLINECOUNT: nRows==%d\n", nRows);
1698     return max(1, nRows);
1699   }
1700   case EM_LINEFROMCHAR:
1701   {
1702     if (wParam == -1)
1703       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
1704     else
1705       return ME_RowNumberFromCharOfs(editor, wParam);
1706   }
1707   case EM_EXLINEFROMCHAR:
1708   {
1709     return ME_RowNumberFromCharOfs(editor, lParam);
1710   }
1711   case EM_LINEINDEX:
1712   {
1713     ME_DisplayItem *item, *para;
1714     int nCharOfs;
1715     
1716     if (wParam == -1)
1717       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
1718     else
1719       item = ME_FindRowWithNumber(editor, wParam);
1720     if (!item)
1721       return -1;
1722     para = ME_GetParagraph(item);
1723     item = ME_FindItemFwd(item, diRun);
1724     nCharOfs = para->member.para.nCharOfs + item->member.run.nCharOfs;
1725     TRACE("EM_LINEINDEX: nCharOfs==%d\n", nCharOfs);
1726     return nCharOfs;
1727   }
1728   case EM_LINELENGTH:
1729   {
1730     ME_DisplayItem *item, *item_end;
1731     int nChars = 0, nThisLineOfs = 0, nNextLineOfs = 0;
1732     
1733     if (wParam > ME_GetTextLength(editor))
1734       return 0;
1735     if (wParam == -1)
1736     {
1737       FIXME("EM_LINELENGTH: returning number of unselected characters on lines with selection unsupported.\n");
1738       return 0;
1739     }
1740     item = ME_FindItemAtOffset(editor, diRun, wParam, NULL);
1741     item = ME_RowStart(item);
1742     nThisLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item, diRun), 0);
1743     item_end = ME_FindItemFwd(item, diStartRow);
1744     if (item_end)
1745       nNextLineOfs = ME_CharOfsFromRunOfs(editor, ME_FindItemFwd(item_end, diRun), 0);
1746     else
1747       nNextLineOfs = ME_FindItemFwd(item, diParagraphOrEnd)->member.para.nCharOfs
1748        - (editor->bEmulateVersion10?2:1);
1749     nChars = nNextLineOfs - nThisLineOfs;
1750     TRACE("EM_LINELENGTH(%d)==%d\n",wParam, nChars);
1751     return nChars;
1752   }
1753   case EM_FINDTEXT:
1754   {
1755     FINDTEXTA *ft = (FINDTEXTA *)lParam;
1756     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
1757     WCHAR *tmp;
1758     
1759     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1760       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
1761     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
1762   }
1763   case EM_FINDTEXTEX:
1764   {
1765     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
1766     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
1767     WCHAR *tmp;
1768     
1769     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1770       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
1771     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
1772   }
1773   case EM_FINDTEXTW:
1774   {
1775     FINDTEXTW *ft = (FINDTEXTW *)lParam;
1776     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
1777   }
1778   case EM_FINDTEXTEXW:
1779   {
1780     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
1781     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
1782   }
1783   case EM_GETZOOM:
1784     if (!wParam || !lParam)
1785       return FALSE;
1786     *(int *)wParam = editor->nZoomNumerator;
1787     *(int *)lParam = editor->nZoomDenominator;
1788     return TRUE;
1789   case EM_SETZOOM:
1790     return ME_SetZoom(editor, wParam, lParam);
1791   case EM_CHARFROMPOS:
1792     return ME_CharFromPos(editor, ((POINTL *)lParam)->x, ((POINTL *)lParam)->y);
1793   case EM_POSFROMCHAR:
1794   {
1795     ME_DisplayItem *pRun;
1796     int nCharOfs, nOffset, nLength;
1797     POINTL pt = {0,0};
1798     
1799     nCharOfs = wParam; 
1800     /* detect which API version we're dealing with */
1801     if (wParam >= 0x40000)
1802         nCharOfs = lParam;
1803     nLength = ME_GetTextLength(editor);
1804     
1805     if (nCharOfs < nLength) { 
1806         ME_RunOfsFromCharOfs(editor, nCharOfs, &pRun, &nOffset);
1807         assert(pRun->type == diRun);
1808         pt.y = pRun->member.run.pt.y;
1809         pt.x = pRun->member.run.pt.x + ME_PointFromChar(editor, &pRun->member.run, nOffset);
1810         pt.y += ME_GetParagraph(pRun)->member.para.nYPos;
1811     } else {
1812         pt.x = 0;
1813         pt.y = editor->pBuffer->pLast->member.para.nYPos;
1814     }
1815     if (wParam >= 0x40000) {
1816         *(POINTL *)wParam = pt;
1817     }
1818     return MAKELONG( pt.x, pt.y );
1819   }
1820   case WM_CREATE:
1821     ME_CommitUndo(editor);
1822     ME_WrapMarkedParagraphs(editor);
1823     ME_MoveCaret(editor);
1824     return 0;
1825   case WM_DESTROY:
1826     ME_DestroyEditor(editor);
1827     SetWindowLongW(hWnd, 0, 0);
1828     return 0;
1829   case WM_LBUTTONDOWN:
1830     SetFocus(hWnd);
1831     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1832     SetCapture(hWnd);
1833     break;
1834   case WM_MOUSEMOVE:
1835     if (GetCapture() == hWnd)
1836       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1837     break;
1838   case WM_LBUTTONUP:
1839     if (GetCapture() == hWnd)
1840       ReleaseCapture();
1841     break;
1842   case WM_LBUTTONDBLCLK:
1843     ME_SelectWord(editor);
1844     break;
1845   case WM_PAINT:
1846     if (editor->bRedraw)
1847     {
1848       HDC hDC;
1849       PAINTSTRUCT ps;
1850
1851       hDC = BeginPaint(hWnd, &ps);
1852       ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1853       EndPaint(hWnd, &ps);
1854     }
1855     break;
1856   case WM_SETFOCUS:
1857     ME_ShowCaret(editor);
1858     ME_SendOldNotify(editor, EN_SETFOCUS);
1859     return 0;
1860   case WM_KILLFOCUS:
1861     ME_HideCaret(editor);
1862     ME_SendOldNotify(editor, EN_KILLFOCUS);
1863     return 0;
1864   case WM_ERASEBKGND:
1865   {
1866     if (editor->bRedraw)
1867     {
1868       HDC hDC = (HDC)wParam;
1869       RECT rc;
1870       if (GetUpdateRect(hWnd,&rc,TRUE))
1871       {
1872         FillRect(hDC, &rc, editor->hbrBackground);
1873       }
1874     }
1875     return 1;
1876   }
1877   case WM_COMMAND:
1878     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1879     return 0;
1880   case WM_KEYDOWN:
1881     if (ME_KeyDown(editor, LOWORD(wParam)))
1882       return 0;
1883     goto do_default;
1884   case WM_CHAR: 
1885   {
1886     WCHAR wstr = LOWORD(wParam);
1887
1888     switch (wstr)
1889     {
1890     case 3: /* Ctrl-C */
1891       SendMessageW(editor->hWnd, WM_COPY, 0, 0);
1892       return 0;
1893     }
1894     
1895     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1896       MessageBeep(MB_ICONERROR);
1897       return 0; /* FIXME really 0 ? */
1898     }
1899
1900     switch (wstr)
1901     {
1902     case 1: /* Ctrl-A */
1903       ME_SetSelection(editor, 0, -1);
1904       return 0;
1905     case 22: /* Ctrl-V */
1906       SendMessageW(editor->hWnd, WM_PASTE, 0, 0);
1907       return 0;
1908     case 24: /* Ctrl-X */
1909       SendMessageW(editor->hWnd, WM_CUT, 0, 0);
1910       return 0;
1911     case 25: /* Ctrl-Y */
1912       SendMessageW(editor->hWnd, EM_REDO, 0, 0);
1913       return 0;
1914     case 26: /* Ctrl-Z */
1915       SendMessageW(editor->hWnd, EM_UNDO, 0, 0);
1916       return 0;
1917     }
1918     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1919       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1920       ME_Style *style = ME_GetInsertStyle(editor, 0);
1921       ME_SaveTempStyle(editor);
1922       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1923       ME_ReleaseStyle(style);
1924       ME_CommitUndo(editor);
1925       ME_UpdateRepaint(editor);
1926     }
1927     return 0;
1928   }
1929   case WM_VSCROLL: 
1930   {
1931     int nPos = editor->nScrollPosY;
1932     si.cbSize = sizeof(SCROLLINFO);
1933     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1934     GetScrollInfo(hWnd, SB_VERT, &si);
1935     switch(LOWORD(wParam)) {
1936     case SB_LINEUP:
1937       nPos -= 24; /* FIXME follow the original */
1938       if (nPos<0) nPos = 0;
1939       break;
1940     case SB_LINEDOWN:
1941     {
1942       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1943       nPos += 24; /* FIXME follow the original */
1944       if (nPos>=nEnd) nPos = nEnd;
1945       break;
1946     }
1947     case SB_PAGEUP:
1948       nPos -= editor->sizeWindow.cy;
1949       if (nPos<0) nPos = 0;
1950       break;
1951     case SB_PAGEDOWN:
1952       nPos += editor->sizeWindow.cy;
1953       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1954       break;
1955     case SB_THUMBTRACK:
1956     case SB_THUMBPOSITION:
1957       nPos = si.nTrackPos;
1958       break;
1959     }
1960     if (nPos != editor->nScrollPosY) {
1961       int dy = editor->nScrollPosY - nPos;
1962       editor->nScrollPosY = nPos;
1963       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1964       if (editor->bRedraw)
1965       {
1966         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1967         UpdateWindow(hWnd);
1968       }
1969     }
1970     break;
1971   }
1972   case WM_MOUSEWHEEL:
1973   {
1974     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1975     UINT pulScrollLines;
1976     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1977     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1978     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1979       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1980     if (nPos>=nEnd)
1981       nPos = nEnd;
1982     if (nPos<0)
1983       nPos = 0;
1984     if (nPos != editor->nScrollPosY) {
1985       int dy = editor->nScrollPosY - nPos;
1986       editor->nScrollPosY = nPos;
1987       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1988       if (editor->bRedraw)
1989       {
1990         ScrollWindow(hWnd, 0, dy, NULL, NULL);
1991         UpdateWindow(hWnd);
1992       }
1993     }
1994     break;
1995   }
1996   case EM_GETRECT:
1997   {
1998     *((RECT *)lParam) = editor->rcFormat;
1999     return 0;
2000   }
2001   case EM_SETRECT:
2002   case EM_SETRECTNP:
2003   {
2004     if (lParam)
2005     {
2006       RECT *rc = (RECT *)lParam;
2007       
2008       if (wParam)
2009       {
2010         editor->rcFormat.left += rc->left;
2011         editor->rcFormat.top += rc->top;
2012         editor->rcFormat.right += rc->right;
2013         editor->rcFormat.bottom += rc->bottom;
2014       }
2015       else
2016       {
2017         editor->rcFormat = *rc;
2018       }
2019     }
2020     else
2021     {
2022       GetClientRect(hWnd, &editor->rcFormat);
2023     }
2024     if (msg != EM_SETRECTNP)
2025       ME_RewrapRepaint(editor);
2026     return 0;
2027   }
2028   case EM_REQUESTRESIZE:
2029     ME_SendRequestResize(editor, TRUE);
2030     return 0;
2031   case WM_SETREDRAW:
2032     editor->bRedraw = wParam;
2033     return 0;
2034   case WM_SIZE:
2035   {
2036     GetClientRect(hWnd, &editor->rcFormat);
2037     ME_RewrapRepaint(editor);
2038     return DefWindowProcW(hWnd, msg, wParam, lParam);
2039   }
2040   case EM_GETOLEINTERFACE:
2041   {
2042     LPVOID *ppvObj = (LPVOID*) lParam;
2043     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
2044     return CreateIRichEditOle(ppvObj);
2045   }
2046   case EM_SETOLECALLBACK:
2047     if(editor->lpOleCallback)
2048       IUnknown_Release(editor->lpOleCallback);
2049     editor->lpOleCallback = (LPRICHEDITOLECALLBACK)lParam;
2050     if(editor->lpOleCallback)
2051       IUnknown_AddRef(editor->lpOleCallback);
2052     return TRUE;
2053   case EM_GETWORDBREAKPROC:
2054     return (LRESULT)editor->pfnWordBreak;
2055   case EM_SETWORDBREAKPROC:
2056   {
2057     EDITWORDBREAKPROCW pfnOld = editor->pfnWordBreak;
2058
2059     editor->pfnWordBreak = (EDITWORDBREAKPROCW)lParam;
2060     return (LRESULT)pfnOld;
2061   }
2062   default:
2063   do_default:
2064     return DefWindowProcW(hWnd, msg, wParam, lParam);
2065   }
2066   return 0L;
2067 }
2068
2069
2070 /******************************************************************
2071  *        RichEdit10ANSIWndProc (RICHED20.9)
2072  */
2073 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
2074 {
2075   LRESULT result;
2076   
2077   /* FIXME: this is NOT the same as 2.0 version */
2078   result = RichEditANSIWndProc(hWnd, msg, wParam, lParam);
2079   if (msg == WM_NCCREATE)
2080   {
2081     ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
2082     
2083     editor->bEmulateVersion10 = TRUE;
2084     editor->pBuffer->pLast->member.para.nCharOfs = 2;
2085   }
2086   return result;
2087 }
2088
2089 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
2090 {
2091   HWND hWnd = editor->hWnd;
2092   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
2093 }
2094
2095 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
2096 {
2097   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
2098   int i = 0;
2099   
2100   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
2101     item = item->member.para.next_para;
2102   if (!item)
2103     return 0;
2104   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
2105     item = item->member.para.next_para;
2106     i++;
2107   }
2108   return i;
2109 }
2110
2111
2112 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
2113 {
2114   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
2115   int nWritten = 0;
2116   WCHAR *pStart = buffer;
2117   
2118   if (!item) {
2119     *buffer = L'\0';
2120     return 0;
2121   }
2122   
2123   if (nStart)
2124   {
2125     int nLen = ME_StrLen(item->member.run.strText) - nStart;
2126     if (nLen > nChars)
2127       nLen = nChars;
2128     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
2129     nChars -= nLen;
2130     nWritten += nLen;
2131     if (!nChars)
2132       return nWritten;
2133     buffer += nLen;
2134     nStart = 0;
2135     item = ME_FindItemFwd(item, diRun);
2136   }
2137   
2138   while(nChars && item)
2139   {
2140     int nLen = ME_StrLen(item->member.run.strText);
2141     if (nLen > nChars)
2142       nLen = nChars;
2143       
2144     if (item->member.run.nFlags & MERF_ENDPARA)
2145     {
2146       *buffer = '\r';
2147       if (bCRLF)
2148       {
2149         *(++buffer) = '\n';
2150         nWritten++;
2151       }
2152       assert(nLen == 1);
2153       /* our end paragraph consists of 2 characters now */
2154       if (editor->bEmulateVersion10)
2155         nChars--;
2156     }
2157     else      
2158       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
2159     nChars -= nLen;
2160     nWritten += nLen;
2161     buffer += nLen;    
2162       
2163     if (!nChars)
2164     {
2165       TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2166       *buffer = L'\0';
2167       return nWritten;
2168     }
2169     item = ME_FindItemFwd(item, diRun);
2170   }
2171   *buffer = L'\0';
2172   TRACE("nWritten=%d, actual=%d\n", nWritten, buffer-pStart);
2173   return nWritten;  
2174 }
2175
2176 void ME_RegisterEditorClass(HINSTANCE hInstance)
2177 {
2178   BOOL bResult;
2179   WNDCLASSW wcW;
2180   WNDCLASSA wcA;
2181   
2182   wcW.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2183   wcW.lpfnWndProc = RichEditANSIWndProc;
2184   wcW.cbClsExtra = 0;
2185   wcW.cbWndExtra = 4;
2186   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
2187   wcW.hIcon = NULL;
2188   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2189   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2190   wcW.lpszMenuName = NULL;
2191   wcW.lpszClassName = wszClassName;
2192   bResult = RegisterClassW(&wcW);  
2193   assert(bResult);
2194   wcW.lpszClassName = wszClassName50;
2195   bResult = RegisterClassW(&wcW);  
2196   assert(bResult);
2197
2198   wcA.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
2199   wcA.lpfnWndProc = RichEditANSIWndProc;
2200   wcA.cbClsExtra = 0;
2201   wcA.cbWndExtra = 4;
2202   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
2203   wcA.hIcon = NULL;
2204   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
2205   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
2206   wcA.lpszMenuName = NULL;
2207   wcA.lpszClassName = "RichEdit20A";
2208   bResult = RegisterClassA(&wcA);  
2209   assert(bResult);
2210   wcA.lpszClassName = "RichEdit50A";
2211   bResult = RegisterClassA(&wcA);  
2212   assert(bResult);
2213 }
2214
2215 LRESULT WINAPI REComboWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2216   /* FIXME: Not implemented */
2217   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2218         hWnd, msg, get_msg_name(msg), wParam, lParam);
2219   return DefWindowProcW(hWnd, msg, wParam, lParam);
2220 }
2221
2222 LRESULT WINAPI REListWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
2223   /* FIXME: Not implemented */
2224   TRACE("hWnd %p msg %04x (%s) %08x %08lx\n",
2225         hWnd, msg, get_msg_name(msg), wParam, lParam);
2226   return DefWindowProcW(hWnd, msg, wParam, lParam);
2227 }
2228
2229 /******************************************************************
2230  *        REExtendedRegisterClass (RICHED20.8)
2231  *
2232  * FIXME undocumented
2233  * Need to check for errors and implement controls and callbacks 
2234  */
2235 LRESULT WINAPI REExtendedRegisterClass(void)
2236 {
2237   WNDCLASSW wcW;
2238   UINT result;
2239
2240   FIXME("semi stub\n");
2241
2242   wcW.cbClsExtra = 0;
2243   wcW.cbWndExtra = 4;
2244   wcW.hInstance = NULL;
2245   wcW.hIcon = NULL;
2246   wcW.hCursor = NULL;
2247   wcW.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
2248   wcW.lpszMenuName = NULL;
2249
2250   if (!ME_ListBoxRegistered)
2251   {
2252       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS;
2253       wcW.lpfnWndProc = REListWndProc;
2254       wcW.lpszClassName = wszClassNameListBox;
2255       if (RegisterClassW(&wcW)) ME_ListBoxRegistered = TRUE;
2256   }
2257
2258   if (!ME_ComboBoxRegistered)
2259   {
2260       wcW.style = CS_PARENTDC | CS_DBLCLKS | CS_GLOBALCLASS | CS_VREDRAW | CS_HREDRAW;
2261       wcW.lpfnWndProc = REComboWndProc;
2262       wcW.lpszClassName = wszClassNameComboBox;
2263       if (RegisterClassW(&wcW)) ME_ComboBoxRegistered = TRUE;  
2264   }
2265
2266   result = 0;
2267   if (ME_ListBoxRegistered)
2268       result += 1;
2269   if (ME_ComboBoxRegistered)
2270       result += 2;
2271
2272   return result;
2273 }