Do filename postprocessing in GetDisplayNameOf (Hide filename
[wine] / dlls / riched20 / editor.c
1 /*
2  * RichEdit - functions dealing with editor object
3  *
4  * Copyright 2004 by Krzysztof Foltman
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /* 
22   API implementation status:
23   
24   Messages (ANSI versions not done yet)
25   - EM_AUTOURLDETECT 2.0
26   + EM_CANPASTE
27   + EM_CANREDO 2.0
28   + EM_CANUNDO
29   - EM_CHARFROMPOS
30   - EM_DISPLAYBAND
31   + EM_EMPTYUNDOBUFFER
32   + EM_EXGETSEL
33   - EM_EXLIMITTEXT
34   + EM_EXLINEFROMCHAR
35   + EM_EXSETSEL
36   + EM_FINDTEXT (only FR_DOWN flag implemented)
37   + EM_FINDTEXTEX (only FR_DOWN flag implemented)
38   - EM_FINDWORDBREAK
39   - EM_FMTLINES
40   - EM_FORMATRANGE
41   - EM_GETAUTOURLDETECT 2.0
42   - EM_GETBIDIOPTIONS 3.0
43   - EM_GETCHARFORMAT (partly done)
44   - EM_GETEDITSTYLE
45   + EM_GETEVENTMASK
46   - EM_GETFIRSTVISIBLELINE
47   - EM_GETIMECOLOR 1.0asian
48   - EM_GETIMECOMPMODE 2.0
49   - EM_GETIMEOPTIONS 1.0asian
50   - EM_GETIMESTATUS
51   - EM_GETLANGOPTIONS 2.0
52   - EM_GETLIMITTEXT
53   - EM_GETLINE        
54   + EM_GETLINECOUNT   returns number of rows, not of paragraphs
55   + EM_GETMODIFY
56   - EM_GETOLEINTERFACE
57   - EM_GETOPTIONS
58   + EM_GETPARAFORMAT
59   - EM_GETPASSWORDCHAR 2.0
60   - EM_GETPUNCTUATION 1.0asian
61   - EM_GETRECT
62   - EM_GETREDONAME 2.0
63   + EM_GETSEL
64   + EM_GETSELTEXT (ANSI&Unicode)
65   - EM_GETSCROLLPOS 3.0
66 ! - EM_GETTHUMB
67   - EM_GETTEXTEX 2.0
68   + EM_GETTEXTLENGTHEX (GTL_PRECISE unimplemented)
69   - EM_GETTEXTMODE 2.0
70 ? + EM_GETTEXTRANGE (ANSI&Unicode)
71   - EM_GETTYPOGRAPHYOPTIONS 3.0
72   - EM_GETUNDONAME
73   - EM_GETWORDBREAKPROC
74   - EM_GETWORDBREAKPROCEX
75   - EM_GETWORDWRAPMODE 1.0asian
76   - EM_SETZOOM 3.0
77   - EM_HIDESELECTION
78   - EM_LIMITTEXT
79   + EM_LINEFROMCHAR
80   + EM_LINEINDEX
81   - EM_LINELENGTH
82   + EM_LINESCROLL
83   - EM_PASTESPECIAL
84   - EM_POSFROMCHARS
85   + EM_REDO 2.0
86   - EM_REQUESTRESIZE
87   + EM_REPLACESEL (proper style?) ANSI&Unicode
88   - EM_SCROLL
89   - EM_SCROLLCARET
90   - EM_SELECTIONTYPE
91   - EM_SETBIDIOPTIONS 3.0
92   + EM_SETBKGNDCOLOR
93   - EM_SETCHARFORMAT (partly done, no ANSI)
94   - EM_SETEDITSTYLE
95   + EM_SETEVENTMASK (few notifications supported)
96   - EM_SETFONTSIZE
97   - EM_SETIMECOLOR 1.0asian
98   - EM_SETIMEOPTIONS 1.0asian
99   - EM_SETLANGOPTIONS 2.0
100   - EM_SETLIMITTEXT
101   + EM_SETMODIFY (not sure if implementation is correct)
102   - EM_SETOLECALLBACK
103   - EM_SETOPTIONS
104   - EM_SETPALETTE 2.0
105   + EM_SETPARAFORMAT
106   - EM_SETPASSWORDCHAR 2.0
107   - EM_SETPUNCTUATION 1.0asian
108   + EM_SETREADONLY no beep on modification attempt
109   - EM_SETRECT
110   - EM_SETRECTNP (EM_SETRECT without repainting) - not supported in RICHEDIT
111   + EM_SETSEL
112   - EM_SETSCROLLPOS 3.0
113   - EM_SETTABSTOPS 3.0
114   - EM_SETTARGETDEVICE
115   - EM_SETTEXTEX 3.0
116   - EM_SETTEXTMODE 2.0
117   - EM_SETTYPOGRAPHYOPTIONS 3.0
118   - EM_SETUNDOLIMIT 2.0
119   - EM_SETWORDBREAKPROC
120   - EM_SETWORDBREAKPROCEX
121   - EM_SETWORDWRAPMODE 1.0asian
122   - EM_SETZOOM 3.0
123   - EM_SHOWSCROLLBAR 2.0
124   - EM_STOPGROUPTYPING 2.0
125   + EM_STREAMIN
126   + EM_STREAMOUT
127   + EM_UNDO
128   + WM_CHAR
129   + WM_CLEAR
130   + WM_COPY
131   + WM_CUT
132   + WM_GETDLGCODE (the current implementation is incomplete)
133   + WM_GETTEXT (ANSI&Unicode)
134   + WM_GETTEXTLENGTH (ANSI version sucks)
135   + WM_PASTE
136   - WM_SETFONT
137   + WM_SETTEXT (resets undo stack !) (proper style?) ANSI&Unicode
138   - WM_STYLECHANGING
139   - WM_STYLECHANGED (things like read-only flag)
140   - WM_UNICHAR
141   
142   Notifications
143   
144   * EN_CHANGE (sent from the wrong place)
145   - EN_CORRECTTEXT
146   - EN_DROPFILES
147   - EN_ERRSPACE
148   - EN_HSCROLL
149   - EN_IMECHANGE
150   + EN_KILLFOCUS
151   - EN_LINK
152   - EN_MAXTEXT
153   - EN_MSGFILTER
154   - EN_OLEOPFAILED
155   - EN_PROTECTED
156   - EN_REQUESTRESIZE
157   - EN_SAVECLIPBOARD
158   + EN_SELCHANGE 
159   + EN_SETFOCUS
160   - EN_STOPNOUNDO
161   * EN_UPDATE (sent from the wrong place)
162   - EN_VSCROLL
163   
164   Styles
165   
166   - ES_AUTOHSCROLL
167   - ES_AUTOVSCROLL
168   - ES_CENTER
169   - ES_DISABLENOSCROLL (scrollbar is always visible)
170   - ES_EX_NOCALLOLEINIT
171   - ES_LEFT
172   - ES_MULTILINE (currently single line controls aren't supported)
173   - ES_NOIME
174   - ES_READONLY (I'm not sure if beeping is the proper behaviour)
175   - ES_RIGHT
176   - ES_SAVESEL
177   - ES_SELFIME
178   - ES_SUNKEN
179   - ES_VERTICAL
180   - ES_WANTRETURN (don't know how to do WM_GETDLGCODE part)
181   - WS_SETFONT
182   - WS_HSCROLL
183   - WS_VSCROLL
184 */
185
186 /*
187  * RICHED20 TODO (incomplete):
188  *
189  * - messages/styles/notifications listed above 
190  * - Undo coalescing 
191  * - add remaining CHARFORMAT/PARAFORMAT fields
192  * - right/center align should strip spaces from the beginning
193  * - more advanced navigation (Ctrl-arrows)
194  * - tabs
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  *
209  * Bugs that are probably fixed, but not so easy to verify:
210  * - EN_UPDATE/EN_CHANGE are handled very incorrectly (should be OK now)
211  * - undo for ME_JoinParagraphs doesn't store paragraph format ? (it does)
212  * - check/fix artificial EOL logic (bCursorAtEnd, hardly logical)
213  * - caret shouldn't be displayed when selection isn't empty
214  * - check refcounting in style management functions (looks perfect now, but no bugs is suspicious)
215  * - undo for setting default format (done, might be buggy)
216  * - styles might be not released properly (looks like they work like charm, but who knows?
217  *
218  */
219
220 #include "editor.h"
221 #include "commdlg.h"
222 #include "ole2.h"
223 #include "richole.h"
224 #include "winreg.h"
225 #define NO_SHLWAPI_STREAM 
226 #include "shlwapi.h"
227
228 #include "rtf.h"
229  
230 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
231
232 int me_debug = 0;
233 HANDLE me_heap = NULL;
234
235 static ME_TextBuffer *ME_MakeText(void) {
236   
237   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
238
239   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
240   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
241   
242   p1->prev = NULL;
243   p1->next = p2;
244   p2->prev = p1;
245   p2->next = NULL;
246   p1->member.para.next_para = p2;
247   p2->member.para.prev_para = p1;
248   p2->member.para.nCharOfs = 0;  
249   
250   buf->pFirst = p1;
251   buf->pLast = p2;
252   buf->pCharStyle = NULL;
253   
254   return buf;
255 }
256
257
258 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
259 {
260   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
261   WCHAR *pText;
262   
263   TRACE("%08lx %p\n", dwFormat, stream);
264   
265   do {
266     long nWideChars = 0;
267
268     if (!stream->dwSize)
269     {
270       ME_StreamInFill(stream);
271       if (stream->editstream->dwError)
272         break;
273       if (!stream->dwSize)
274         break;
275     }
276       
277     if (!(dwFormat & SF_UNICODE))
278     {
279       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
280       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
281       pText = wszText;
282     }
283     else
284     {
285       nWideChars = stream->dwSize >> 1;
286       pText = (WCHAR *)stream->buffer;
287     }
288     
289     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
290     if (stream->dwSize < STREAMIN_BUFFER_SIZE)
291       break;
292     stream->dwSize = 0;
293   } while(1);
294   ME_CommitUndo(editor);
295   ME_Repaint(editor);
296   return 0;
297 }
298
299 static void ME_RTFCharAttrHook(RTF_Info *info)
300 {
301   CHARFORMAT2W fmt;
302   fmt.cbSize = sizeof(fmt);
303   fmt.dwMask = 0;
304   
305   switch(info->rtfMinor)
306   {
307     case rtfPlain:
308       /* FIXME add more flags once they're implemented */
309       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
310       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
311       fmt.yHeight = 12*20; /* 12pt */
312       fmt.wWeight = 400;
313       break;
314     case rtfBold:
315       fmt.dwMask = CFM_BOLD;
316       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
317       break;
318     case rtfItalic:
319       fmt.dwMask = CFM_ITALIC;
320       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
321       break;
322     case rtfUnderline:
323       fmt.dwMask = CFM_UNDERLINE;
324       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
325       fmt.bUnderlineType = CFU_CF1UNDERLINE;
326       break;
327     case rtfNoUnderline:
328       fmt.dwMask = CFM_UNDERLINE;
329       fmt.dwEffects = 0;
330       break;
331     case rtfStrikeThru:
332       fmt.dwMask = CFM_STRIKEOUT;
333       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
334       break;
335     case rtfSubScript:
336     case rtfSuperScript:
337     case rtfSubScrShrink:
338     case rtfSuperScrShrink:
339     case rtfNoSuperSub:
340       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
341       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
342       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
343       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
344       break;
345     case rtfBackColor:
346       fmt.dwMask = CFM_BACKCOLOR;
347       fmt.dwEffects = 0;
348       if (info->rtfParam == 0)
349         fmt.dwEffects = CFE_AUTOBACKCOLOR;
350       else if (info->rtfParam != rtfNoParam)
351       {
352         RTFColor *c = RTFGetColor(info, info->rtfParam);
353         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
354       }
355       break;
356     case rtfForeColor:
357       fmt.dwMask = CFM_COLOR;
358       fmt.dwEffects = 0;
359       if (info->rtfParam == 0)
360         fmt.dwEffects = CFE_AUTOCOLOR;
361       else if (info->rtfParam != rtfNoParam)
362       {
363         RTFColor *c = RTFGetColor(info, info->rtfParam);
364         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
365       }
366       break;
367     case rtfFontNum:
368       if (info->rtfParam != rtfNoParam)
369       {
370         RTFFont *f = RTFGetFont(info, info->rtfParam);
371         if (f)
372         {
373           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
374           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
375           fmt.bCharSet = f->rtfFCharSet;
376           fmt.dwMask = CFM_FACE | CFM_CHARSET;
377         }
378       }
379       break;
380     case rtfFontSize:
381       fmt.dwMask = CFM_SIZE;
382       if (info->rtfParam != rtfNoParam)
383         fmt.yHeight = info->rtfParam*10;
384       break;
385   }
386   if (fmt.dwMask) {
387     ME_Style *style2;
388     RTFFlushOutputBuffer(info);
389     /* FIXME too slow ? how come ? */
390     style2 = ME_ApplyStyle(info->style, &fmt);
391     ME_ReleaseStyle(info->style);
392     info->style = style2;
393   }
394 }
395
396 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
397    the same tags mean different things in different contexts */
398 static void ME_RTFParAttrHook(RTF_Info *info)
399 {
400   PARAFORMAT2 fmt;
401   fmt.cbSize = sizeof(fmt);
402   fmt.dwMask = 0;
403   
404   switch(info->rtfMinor)
405   {
406   case rtfParDef: /* I'm not 100% sure what does it do, but I guess it restores default paragraph attributes */
407     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
408     fmt.wAlignment = PFA_LEFT;
409     fmt.cTabCount = 0;
410     fmt.dxOffset = fmt.dxStartIndent = 0;
411     break;
412   case rtfFirstIndent:
413     ME_GetSelectionParaFormat(info->editor, &fmt);
414     fmt.dwMask = PFM_STARTINDENT;
415     fmt.dxStartIndent = info->rtfParam + fmt.dxOffset;
416     break;
417   case rtfLeftIndent:
418   {
419     int first, left;
420     ME_GetSelectionParaFormat(info->editor, &fmt);
421     first = fmt.dxStartIndent;
422     left = info->rtfParam;
423     fmt.dwMask = PFM_STARTINDENT|PFM_OFFSET;
424     fmt.dxStartIndent = first + left;
425     fmt.dxOffset = -first;
426     break;
427   }
428   case rtfRightIndent:
429     fmt.dwMask = PFM_RIGHTINDENT;
430     fmt.dxRightIndent = info->rtfParam;
431     break;
432   case rtfQuadLeft:
433   case rtfQuadJust:
434     fmt.dwMask = PFM_ALIGNMENT;
435     fmt.wAlignment = PFA_LEFT;
436     break;
437   case rtfQuadRight:
438     fmt.dwMask = PFM_ALIGNMENT;
439     fmt.wAlignment = PFA_RIGHT;
440     break;
441   case rtfQuadCenter:
442     fmt.dwMask = PFM_ALIGNMENT;
443     fmt.wAlignment = PFA_CENTER;
444     break;
445   case rtfTabPos:
446     ME_GetSelectionParaFormat(info->editor, &fmt);
447     if (!(fmt.dwMask & PFM_TABSTOPS))
448     {
449       fmt.dwMask |= PFM_TABSTOPS;
450       fmt.cTabCount = 0;
451     }
452     if (fmt.cTabCount < MAX_TAB_STOPS)
453       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
454     break;
455   }  
456   if (fmt.dwMask) {
457     RTFFlushOutputBuffer(info);
458     /* FIXME too slow ? how come ?*/
459     ME_SetSelectionParaFormat(info->editor, &fmt);
460   }
461 }
462
463 static void ME_RTFReadHook(RTF_Info *info) {
464   switch(info->rtfClass)
465   {
466     case rtfGroup:
467       switch(info->rtfMajor)
468       {
469         case rtfBeginGroup:
470           if (info->stackTop < maxStack) {
471             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
472             info->stack[info->stackTop].codePage = info->codePage;
473             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
474           }
475           info->stackTop++;
476           break;
477         case rtfEndGroup:
478         {
479           ME_Style *s;
480           RTFFlushOutputBuffer(info);
481           info->stackTop--;
482           /* FIXME too slow ? how come ? */
483           s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
484           ME_ReleaseStyle(info->style);
485           info->style = s;
486           info->codePage = info->stack[info->stackTop].codePage;
487           info->unicodeLength = info->stack[info->stackTop].unicodeLength;
488           break;
489         }
490       }
491       break;
492     case rtfControl:
493       switch(info->rtfMajor)
494       {
495         case rtfCharAttr:
496           ME_RTFCharAttrHook(info);
497           break;
498         case rtfParAttr:
499           ME_RTFParAttrHook(info);
500           break;
501       }
502       break;
503   }
504 }
505
506 void
507 ME_StreamInFill(ME_InStream *stream)
508 {
509   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
510                                                                 stream->buffer,
511                                                                 sizeof(stream->buffer),
512                                                                 &stream->dwSize);
513   stream->dwUsed = 0;
514 }
515
516 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
517 {
518   RTF_Info parser;
519   ME_Style *style;
520   int from, to, to2, nUndoMode;
521   ME_UndoItem *pUI;
522   int nEventMask = editor->nEventMask;
523   ME_InStream inStream;
524
525   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
526   editor->nEventMask = 0;
527   
528   ME_GetSelection(editor, &from, &to);
529   if (format & SFF_SELECTION) {
530     style = ME_GetSelectionInsertStyle(editor);
531
532     ME_InternalDeleteText(editor, from, to-from);
533   }
534   else {
535     style = editor->pBuffer->pDefaultStyle;
536     ME_AddRefStyle(style);
537     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
538     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
539     from = to = 0;
540     ME_ClearTempStyle(editor);
541     /* FIXME restore default paragraph formatting ! */
542   }
543   
544   nUndoMode = editor->nUndoMode;
545   editor->nUndoMode = umIgnore;
546
547   inStream.editstream = stream;
548   inStream.editstream->dwError = 0;
549   inStream.dwSize = 0;
550   inStream.dwUsed = 0;
551
552   if (format & SF_RTF)
553   {
554     /* Check if it's really RTF, and if it is not, use plain text */
555     ME_StreamInFill(&inStream);
556     if (!inStream.editstream->dwError)
557     {
558       if (strncmp(inStream.buffer, "{\\rtf1", 6) && strncmp(inStream.buffer, "{\\urtf", 6))
559       {
560         format &= ~SF_RTF;
561         format |= SF_TEXT;
562       }
563     }
564   }
565
566   if (!inStream.editstream->dwError)
567   {
568     if (format & SF_RTF) {
569       /* setup the RTF parser */
570       memset(&parser, 0, sizeof parser);
571       RTFSetEditStream(&parser, &inStream);
572       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
573       parser.hwndEdit = editor->hWnd;
574       parser.editor = editor;
575       parser.style = style;
576       WriterInit(&parser);
577       RTFInit(&parser);
578       RTFSetReadHook(&parser, ME_RTFReadHook);
579       BeginFile(&parser);
580   
581       /* do the parsing */
582       RTFRead(&parser);
583       RTFFlushOutputBuffer(&parser);
584       RTFDestroy(&parser);
585
586       style = parser.style;
587     }
588     else if (format & SF_TEXT)
589       ME_StreamInText(editor, format, &inStream, style);
590     else
591       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
592     ME_GetSelection(editor, &to, &to2);
593     /* put the cursor at the top */
594     if (!(format & SFF_SELECTION))
595       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
596     else
597     {
598       /* FIXME where to put cursor now ? */
599     }
600   }
601   
602   editor->nUndoMode = nUndoMode;
603   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
604   TRACE("from %d to %d\n", from, to);
605   if (pUI && from < to)
606   {
607     pUI->nStart = from;
608     pUI->nLen = to-from;
609   }
610   ME_CommitUndo(editor);
611   ME_ReleaseStyle(style); 
612   editor->nEventMask = nEventMask;
613   InvalidateRect(editor->hWnd, NULL, TRUE);
614   ME_UpdateRepaint(editor);
615   if (!(format & SFF_SELECTION)) {
616     ME_ClearTempStyle(editor);
617   }
618   ME_MoveCaret(editor);
619   ME_SendSelChange(editor);
620
621   return 0;
622 }
623
624
625 ME_DisplayItem *
626 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
627 {
628   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
629   
630   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
631     item = ME_FindItemFwd(item, diParagraph);
632
633   if (!item)
634     return item;
635
636   nOffset -= item->member.para.nCharOfs;
637   if (nItemType == diParagraph) {
638     if (nItemOffset)
639       *nItemOffset = nOffset;
640     return item;
641   }
642   
643   do {
644     item = ME_FindItemFwd(item, diRun);
645   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
646   if (item) {
647     nOffset -= item->member.run.nCharOfs;
648     if (nItemOffset)
649       *nItemOffset = nOffset;
650   }
651   return item;
652 }
653
654
655 static int
656 ME_FindText(ME_TextEditor *editor, DWORD flags, CHARRANGE *chrg, WCHAR *text, CHARRANGE *chrgText)
657 {
658   int nStart = chrg->cpMin;
659   int nLen = lstrlenW(text);
660   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
661   ME_DisplayItem *para;
662   
663   if (!item)
664     return -1;
665
666   if (!nLen)
667   {
668     if (chrgText)
669       chrgText->cpMin = chrgText->cpMax = chrg->cpMin;
670     return chrg->cpMin;
671   }
672  
673   if (!(flags & FR_DOWN))
674     FIXME("Backward search not implemented\n");
675   if (!(flags & FR_MATCHCASE))
676     FIXME("Case-insensitive search not implemented\n");
677   if (flags & ~(FR_DOWN | FR_MATCHCASE))
678     FIXME("Flags 0x%08lx not implemented\n", flags & ~(FR_DOWN | FR_MATCHCASE));
679   
680   para = ME_GetParagraph(item);
681   while (item && para->member.para.nCharOfs + item->member.run.nCharOfs + nStart + nLen < chrg->cpMax)
682   {
683     ME_DisplayItem *pCurItem = item;
684     int nCurStart = nStart;
685     int nMatched = 0;
686     
687     while (pCurItem->member.run.strText->szData[nCurStart + nMatched] == text[nMatched])
688     {
689       nMatched++;
690       if (nMatched == nLen)
691       {
692         nStart += para->member.para.nCharOfs + item->member.run.nCharOfs;
693         if (chrgText)
694         {
695           chrgText->cpMin = nStart;
696           chrgText->cpMax = nStart + nLen;
697         }
698         return nStart;
699       }
700       if (nCurStart + nMatched == ME_StrLen(pCurItem->member.run.strText))
701       {
702         pCurItem = ME_FindItemFwd(pCurItem, diRun);
703         nCurStart = -nMatched;
704       }
705     }
706     nStart++;
707     if (nStart == ME_StrLen(item->member.run.strText))
708     {
709       item = ME_FindItemFwd(item, diRun);
710       para = ME_GetParagraph(item);
711       nStart = 0;
712     }
713   }
714   return -1;
715 }
716
717
718 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
719   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
720   HDC hDC;
721   int i;
722   ed->hWnd = hWnd;
723   ed->pBuffer = ME_MakeText();
724   hDC = GetDC(hWnd);
725   ME_MakeFirstParagraph(hDC, ed->pBuffer);
726   ReleaseDC(hWnd, hDC);
727   ed->bCaretShown = FALSE;
728   ed->nCursors = 3;
729   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
730   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
731   ed->pCursors[0].nOffset = 0;
732   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
733   ed->pCursors[1].nOffset = 0;
734   ed->nLastTotalLength = ed->nTotalLength = 0;
735   ed->nUDArrowX = -1;
736   ed->nSequence = 0;
737   ed->rgbBackColor = -1;
738   ed->bCaretAtEnd = FALSE;
739   ed->nEventMask = 0;
740   ed->nModifyStep = 0;
741   ed->pUndoStack = ed->pRedoStack = NULL;
742   ed->nUndoMode = umAddToUndo;
743   ed->nParagraphs = 1;
744   ed->nLastSelStart = ed->nLastSelEnd = 0;
745   ed->nScrollPosY = 0;
746   for (i=0; i<HFONT_CACHE_SIZE; i++)
747   {
748     ed->pFontCache[i].nRefs = 0;
749     ed->pFontCache[i].nAge = 0;
750     ed->pFontCache[i].hFont = NULL;
751   }
752   ME_CheckCharOffsets(ed);
753   return ed;
754 }
755
756 typedef struct tagME_GlobalDestStruct
757 {
758   HGLOBAL hData;
759   int nLength;
760 } ME_GlobalDestStruct;
761
762 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
763 {
764   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
765   int nMaxSize;
766   BYTE *pDest;
767   
768   nMaxSize = GlobalSize(pData->hData);
769   if (pData->nLength+cb+1 >= cb)
770   {
771     /* round up to 2^17 */
772     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
773     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
774   }
775   pDest = (BYTE *)GlobalLock(pData->hData);
776   memcpy(pDest + pData->nLength, lpBuff, cb);
777   pData->nLength += cb;
778   pDest[pData->nLength] = '\0';
779   GlobalUnlock(pData->hData);
780   *pcb = cb;
781   
782   return 0;
783 }
784
785 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
786 {
787   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
788   int i;
789   WORD *pSrc, *pDest;
790   
791   cb = cb >> 1;
792   pDest = (WORD *)lpBuff;
793   pSrc = (WORD *)GlobalLock(pData->hData);
794   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
795     pDest[i] = pSrc[pData->nLength+i];
796   }    
797   pData->nLength += i;
798   *pcb = 2*i;
799   GlobalUnlock(pData->hData);
800   return 0;
801 }
802
803 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
804 {
805   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
806   int i;
807   BYTE *pSrc, *pDest;
808   
809   pDest = lpBuff;
810   pSrc = (BYTE *)GlobalLock(pData->hData);
811   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
812     pDest[i] = pSrc[pData->nLength+i];
813   }    
814   pData->nLength += i;
815   *pcb = i;
816   GlobalUnlock(pData->hData);
817   return 0;
818 }
819
820
821 void ME_DestroyEditor(ME_TextEditor *editor)
822 {
823   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
824   ME_DisplayItem *p = pFirst, *pNext = NULL;
825   int i;
826   
827   ME_ClearTempStyle(editor);
828   ME_EmptyUndoStack(editor);
829   while(p) {
830     pNext = p->next;
831     ME_DestroyDisplayItem(p);    
832     p = pNext;
833   }
834   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
835   for (i=0; i<HFONT_CACHE_SIZE; i++)
836   {
837     if (editor->pFontCache[i].hFont)
838       DeleteObject(editor->pFontCache[i].hFont);
839   }
840     
841   FREE_OBJ(editor);
842 }
843
844 static WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
845 static WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
846
847 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
848 {
849     TRACE("\n");
850     switch (fdwReason)
851     {
852     case DLL_PROCESS_ATTACH:
853       DisableThreadLibraryCalls(hinstDLL);
854       me_heap = HeapCreate (0, 0x10000, 0);
855       ME_RegisterEditorClass(hinstDLL);
856       break;
857
858     case DLL_PROCESS_DETACH:
859       UnregisterClassW(wszClassName, 0);
860       UnregisterClassW(wszClassName50, 0);
861       UnregisterClassA("RichEdit20A", 0);
862       UnregisterClassA("RichEdit50A", 0);
863       HeapDestroy (me_heap);
864       me_heap = NULL;
865       break;
866     }
867     return TRUE;
868 }
869
870
871 #define UNSUPPORTED_MSG(e) \
872   case e: \
873     FIXME(#e ": stub\n"); \
874     return DefWindowProcW(hWnd, msg, wParam, lParam);
875
876 /******************************************************************
877  *        RichEditANSIWndProc (RICHED20.10)
878  */
879 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
880   HDC hDC;
881   PAINTSTRUCT ps;
882   SCROLLINFO si;
883   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
884   TRACE("msg %d %08x %08lx\n", msg, wParam, lParam);
885   switch(msg) {
886   
887   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
888   UNSUPPORTED_MSG(EM_CHARFROMPOS)
889   UNSUPPORTED_MSG(EM_DISPLAYBAND)
890   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
891   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
892   UNSUPPORTED_MSG(EM_FMTLINES)
893   UNSUPPORTED_MSG(EM_FORMATRANGE)
894   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
895   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
896   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
897   UNSUPPORTED_MSG(EM_GETFIRSTVISIBLELINE)
898   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
899   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
900   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
901   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
902   UNSUPPORTED_MSG(EM_GETLINE)
903   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
904   UNSUPPORTED_MSG(EM_GETOPTIONS)
905   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
906   UNSUPPORTED_MSG(EM_GETRECT)
907   UNSUPPORTED_MSG(EM_GETREDONAME)
908   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
909   UNSUPPORTED_MSG(EM_GETTEXTMODE)
910   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
911   UNSUPPORTED_MSG(EM_GETUNDONAME)
912   UNSUPPORTED_MSG(EM_GETWORDBREAKPROC)
913   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
914   UNSUPPORTED_MSG(EM_GETZOOM)
915   UNSUPPORTED_MSG(EM_HIDESELECTION)
916   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
917   UNSUPPORTED_MSG(EM_LINELENGTH)
918   UNSUPPORTED_MSG(EM_PASTESPECIAL)
919 /*  UNSUPPORTED_MSG(EM_POSFROMCHARS) missing in Wine headers */
920   UNSUPPORTED_MSG(EM_REQUESTRESIZE)
921   UNSUPPORTED_MSG(EM_SCROLL)
922   UNSUPPORTED_MSG(EM_SCROLLCARET)
923   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
924   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
925   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
926   UNSUPPORTED_MSG(EM_SETFONTSIZE)
927   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
928   UNSUPPORTED_MSG(EM_SETOLECALLBACK)
929   UNSUPPORTED_MSG(EM_SETOPTIONS)
930   UNSUPPORTED_MSG(EM_SETPALETTE)
931   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
932   UNSUPPORTED_MSG(EM_SETRECT)
933   UNSUPPORTED_MSG(EM_SETRECTNP)
934   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
935   UNSUPPORTED_MSG(EM_SETTABSTOPS)
936   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
937   UNSUPPORTED_MSG(EM_SETTEXTEX)
938   UNSUPPORTED_MSG(EM_SETTEXTMODE)
939   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
940   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
941   UNSUPPORTED_MSG(EM_SETWORDBREAKPROC)
942   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
943   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
944   UNSUPPORTED_MSG(EM_SETZOOM)
945   UNSUPPORTED_MSG(WM_SETFONT)
946   UNSUPPORTED_MSG(WM_STYLECHANGING)
947   UNSUPPORTED_MSG(WM_STYLECHANGED)
948 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
949     
950 /* Messages specific to Richedit controls */
951   
952   case EM_STREAMIN:
953    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
954   case EM_STREAMOUT:
955    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
956   case WM_GETDLGCODE:
957   {
958     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
959     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
960       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
961     return code;
962   }
963   case WM_NCCREATE:
964   {
965     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
966     editor = ME_MakeEditor(hWnd);
967     SetWindowLongW(hWnd, 0, (long)editor);
968     pcs = 0; /* ignore */
969     return TRUE;
970   }
971   case EM_EMPTYUNDOBUFFER:
972     ME_EmptyUndoStack(editor);
973     return 0;
974   case EM_GETSEL:
975   {
976     /* Note: wParam/lParam can be NULL */
977     UINT from, to;
978     PUINT pfrom = wParam ? (PUINT)wParam : &from;
979     PUINT pto = lParam ? (PUINT)lParam : &to;
980     ME_GetSelection(editor, pfrom, pto);
981     if ((*pfrom|*pto) & 0xFFFF0000)
982       return -1;
983     return MAKELONG(*pfrom,*pto);
984   }
985   case EM_EXGETSEL:
986   {
987     CHARRANGE *pRange = (CHARRANGE *)lParam;
988     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
989     return 0;
990   }
991   case EM_CANUNDO:
992     return editor->pUndoStack != NULL;
993   case EM_CANREDO:
994     return editor->pRedoStack != NULL;
995   case EM_UNDO:
996     ME_Undo(editor);
997     return 0;
998   case EM_REDO:
999     ME_Redo(editor);
1000     return 0;
1001   case EM_SETSEL:
1002   {
1003     ME_SetSelection(editor, wParam, lParam);
1004     ME_Repaint(editor);
1005     ME_SendSelChange(editor);
1006     return 0;
1007   }
1008   case EM_EXSETSEL:
1009   {
1010     CHARRANGE *pRange = (CHARRANGE *)lParam;
1011     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
1012     /* FIXME optimize */
1013     ME_Repaint(editor);
1014     ME_SendSelChange(editor);
1015     return 0;
1016   }
1017   case EM_SETBKGNDCOLOR:
1018   {
1019     LRESULT lColor = ME_GetBackColor(editor);
1020     if (wParam)
1021       editor->rgbBackColor = -1;
1022     else
1023       editor->rgbBackColor = lParam; 
1024     InvalidateRect(hWnd, NULL, TRUE);
1025     UpdateWindow(hWnd);
1026     return lColor;
1027   }
1028   case EM_GETMODIFY:
1029     return editor->nModifyStep == 0 ? 0 : 1;
1030   case EM_SETMODIFY:
1031   {
1032     if (wParam)
1033       editor->nModifyStep = 0x80000000;
1034     else
1035       editor->nModifyStep = 0;
1036     
1037     return 0;
1038   }
1039   case EM_SETREADONLY:
1040   {
1041     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
1042     if (wParam)
1043       nStyle |= ES_READONLY;
1044     else
1045       nStyle &= ~ES_READONLY;
1046     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
1047     ME_Repaint(editor);
1048     return 0;
1049   }
1050   case EM_SETEVENTMASK:
1051     editor->nEventMask = lParam;
1052     return 0;
1053   case EM_GETEVENTMASK:
1054     return editor->nEventMask;
1055   case EM_SETCHARFORMAT:
1056   {
1057     CHARFORMAT2W buf, *p;
1058     BOOL bRepaint = TRUE;
1059     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1060     if (!wParam)
1061       ME_SetDefaultCharFormat(editor, p);
1062     else if (wParam == (SCF_WORD | SCF_SELECTION))
1063       FIXME("word selection not supported\n");
1064     else if (wParam == SCF_ALL)
1065       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1066     else {
1067       int from, to;
1068       ME_GetSelection(editor, &from, &to);
1069       bRepaint = (from != to);
1070       ME_SetSelectionCharFormat(editor, p);
1071     }
1072     ME_CommitUndo(editor);
1073     if (bRepaint)
1074       ME_UpdateRepaint(editor);
1075     return 0;
1076   }
1077   case EM_GETCHARFORMAT:
1078   {
1079     CHARFORMAT2W tmp, *dst = (CHARFORMAT2W *)lParam;
1080     if (dst->cbSize != sizeof(CHARFORMATA) &&
1081         dst->cbSize != sizeof(CHARFORMATW) &&
1082         dst->cbSize != sizeof(CHARFORMAT2A) &&
1083         dst->cbSize != sizeof(CHARFORMAT2W))
1084       return 0;
1085     tmp.cbSize = sizeof(tmp);
1086     if (!wParam)
1087       ME_GetDefaultCharFormat(editor, &tmp);
1088     else
1089       ME_GetSelectionCharFormat(editor, &tmp);
1090     ME_CopyToCFAny(dst, &tmp);
1091     return tmp.dwMask;
1092   }
1093   case EM_SETPARAFORMAT:
1094     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1095     ME_UpdateRepaint(editor);
1096     ME_CommitUndo(editor);
1097     return 0;
1098   case EM_GETPARAFORMAT:
1099     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1100     return 0;
1101   case EM_LINESCROLL:
1102   {
1103     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1104     nPos += 8 * lParam; /* FIXME follow the original */
1105     if (nPos>=nEnd)
1106       nPos = nEnd;
1107     if (nPos<0)
1108       nPos = 0;
1109     if (nPos != editor->nScrollPosY) {
1110       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1111       editor->nScrollPosY = nPos;
1112       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1113       UpdateWindow(hWnd);
1114     }
1115     return TRUE; /* Should return false if a single line richedit control */
1116   }
1117   case WM_CLEAR:
1118   {
1119     int from, to;
1120     ME_GetSelection(editor, &from, &to);
1121     ME_InternalDeleteText(editor, from, to-from);
1122     ME_CommitUndo(editor);
1123     ME_UpdateRepaint(editor);
1124     return 0;
1125   }
1126   case EM_REPLACESEL:
1127   {
1128     int from, to;
1129     ME_Style *style;
1130     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1131     size_t len = lstrlenW(wszText);
1132     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1133     
1134     ME_GetSelection(editor, &from, &to);
1135     style = ME_GetSelectionInsertStyle(editor);
1136     ME_InternalDeleteText(editor, from, to-from);
1137     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1138     ME_ReleaseStyle(style);
1139     ME_EndToUnicode(hWnd, wszText);
1140     /* drop temporary style if line end */
1141     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1142     if (len>0 && wszText[len-1] == '\n')
1143       ME_ClearTempStyle(editor);
1144       
1145     ME_CommitUndo(editor);
1146     if (!wParam)
1147       ME_EmptyUndoStack(editor);
1148     ME_UpdateRepaint(editor);
1149     return 0;
1150   }
1151   case WM_SETTEXT:
1152   {
1153     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1154     TRACE("WM_SETTEXT - %s\n", (char *)(wszText)); /* debugstr_w() */
1155     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1156     /* uses default style! */
1157     ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1158     ME_EndToUnicode(hWnd, wszText);
1159     ME_CommitUndo(editor);
1160     ME_EmptyUndoStack(editor);
1161     ME_UpdateRepaint(editor);
1162     return 0;
1163   }
1164   case EM_CANPASTE:
1165   {
1166     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1167     if (IsClipboardFormatAvailable(nRTFFormat))
1168       return TRUE;
1169     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1170       return TRUE;
1171     return FALSE;
1172   }
1173   case WM_PASTE:
1174   {    
1175     DWORD dwFormat = 0;
1176     EDITSTREAM es;
1177     ME_GlobalDestStruct gds;
1178     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1179     UINT cf = 0;
1180
1181     if (IsClipboardFormatAvailable(nRTFFormat))
1182       cf = nRTFFormat, dwFormat = SF_RTF;
1183     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1184       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1185     else
1186       return 0;
1187
1188     if (!OpenClipboard(hWnd))
1189       return 0;
1190     gds.hData = GetClipboardData(cf);
1191     gds.nLength = 0;
1192     es.dwCookie = (DWORD)&gds;
1193     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1194     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1195     
1196     CloseClipboard();
1197     return 0;
1198   }
1199   case WM_CUT:
1200   case WM_COPY:
1201   {
1202     int from, to, pars;
1203     WCHAR *data;
1204     HANDLE hData;
1205     EDITSTREAM es;
1206     ME_GlobalDestStruct gds;
1207     
1208     if (!OpenClipboard(hWnd))
1209       return 0;
1210       
1211     EmptyClipboard();
1212     ME_GetSelection(editor, &from, &to);
1213     pars = ME_CountParagraphsBetween(editor, from, to);
1214     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1215     data = (WCHAR *)GlobalLock(hData);
1216     ME_GetTextW(editor, data, from, to-from, TRUE);
1217     GlobalUnlock(hData);
1218
1219     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1220     gds.nLength = 0;
1221     es.dwCookie = (DWORD)&gds;
1222     es.pfnCallback = ME_AppendToHGLOBAL;
1223     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1224     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1225     
1226     SetClipboardData(CF_UNICODETEXT, hData);    
1227     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1228     
1229     CloseClipboard();
1230     if (msg == WM_CUT)
1231     {
1232       ME_InternalDeleteText(editor, from, to-from);
1233       ME_CommitUndo(editor);
1234       ME_UpdateRepaint(editor);
1235     }
1236     return 0;
1237   }
1238   case WM_GETTEXTLENGTH:
1239     return ME_GetTextLength(editor);
1240   case EM_GETTEXTLENGTHEX:
1241     return ME_GetTextLengthEx(editor, (GETTEXTLENGTHEX *)wParam);
1242   case WM_GETTEXT:
1243   {
1244     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1245     tr.chrg.cpMin = 0;
1246     tr.chrg.cpMax = wParam-1;
1247     tr.lpstrText = (WCHAR *)lParam;
1248     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1249   }
1250   case EM_GETTEXTEX:
1251   {
1252     GETTEXTEX *ex = (GETTEXTEX*)wParam;
1253
1254     if (ex->flags != 0)
1255         FIXME("Unhandled EM_GETTEXTEX flags 0x%lx\n",ex->flags);
1256
1257     if (IsWindowUnicode(hWnd))
1258       return ME_GetTextW(editor, (LPWSTR)lParam, 0, ex->cb, FALSE);
1259     else
1260     {
1261         LPWSTR buffer = HeapAlloc(GetProcessHeap(),0,ex->cb*sizeof(WCHAR));
1262         DWORD buflen = ex->cb;
1263         LRESULT rc;
1264         DWORD flags = 0;
1265
1266         buflen = ME_GetTextW(editor, buffer, 0, buflen, FALSE);
1267         rc = WideCharToMultiByte(ex->codepage, flags, buffer, buflen, (LPSTR)lParam, ex->cb, ex->lpDefaultChar, ex->lpUsedDefaultChar);
1268
1269         HeapFree(GetProcessHeap(),0,buffer);
1270         return rc;
1271     }
1272   }
1273   case EM_GETSELTEXT:
1274   {
1275     int from, to;
1276     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1277     ME_GetSelection(editor, &from, &to);
1278     tr.chrg.cpMin = from;
1279     tr.chrg.cpMax = to;
1280     tr.lpstrText = (WCHAR *)lParam;
1281     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1282   }
1283   case EM_GETTEXTRANGE:
1284   {
1285     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1286     if (IsWindowUnicode(hWnd))
1287       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, FALSE);
1288     else
1289     {
1290       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1291       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1292       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, FALSE);
1293       /* FIXME this is a potential security hole (buffer overrun) 
1294          if you know more about wchar->mbyte conversion please explain
1295       */
1296       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1297       FREE_OBJ(p);
1298       return nChars;
1299     }
1300     return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, FALSE);
1301   }
1302   case EM_GETLINECOUNT:
1303   {
1304     ME_DisplayItem *item = editor->pBuffer->pFirst->next;
1305     int nRows = 0;
1306
1307     while (item != editor->pBuffer->pLast)
1308     {
1309       assert(item->type == diParagraph);
1310       nRows += item->member.para.nRows;
1311       item = item->member.para.next_para;
1312     }
1313     return max(1, nRows);
1314   }
1315   case EM_LINEFROMCHAR:
1316   {
1317     if (wParam == -1)
1318       return ME_RowNumberFromCharOfs(editor, ME_GetCursorOfs(editor, 1));
1319     else
1320       return ME_RowNumberFromCharOfs(editor, wParam);
1321   }
1322   case EM_EXLINEFROMCHAR:
1323   {
1324     return ME_RowNumberFromCharOfs(editor, lParam);
1325   }
1326   case EM_LINEINDEX:
1327   {
1328     ME_DisplayItem *item, *para;
1329     
1330     if (wParam == -1)
1331       item = ME_FindItemBack(editor->pCursors[0].pRun, diStartRow);
1332     else
1333       item = ME_FindRowWithNumber(editor, wParam);
1334     if (!item)
1335       return -1;
1336     para = ME_GetParagraph(item);
1337     item = ME_FindItemFwd(item, diRun);
1338     return para->member.para.nCharOfs + item->member.run.nCharOfs;
1339   }
1340   case EM_FINDTEXT:
1341   {
1342     FINDTEXTA *ft = (FINDTEXTA *)lParam;
1343     int nChars = MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, NULL, 0);
1344     WCHAR *tmp;
1345     
1346     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1347       MultiByteToWideChar(CP_ACP, 0, ft->lpstrText, -1, tmp, nChars);
1348     return ME_FindText(editor, wParam, &ft->chrg, tmp, NULL);
1349   }
1350   case EM_FINDTEXTEX:
1351   {
1352     FINDTEXTEXA *ex = (FINDTEXTEXA *)lParam;
1353     int nChars = MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, NULL, 0);
1354     WCHAR *tmp;
1355     
1356     if ((tmp = ALLOC_N_OBJ(WCHAR, nChars)) != NULL)
1357       MultiByteToWideChar(CP_ACP, 0, ex->lpstrText, -1, tmp, nChars);
1358     return ME_FindText(editor, wParam, &ex->chrg, tmp, &ex->chrgText);
1359   }
1360   case EM_FINDTEXTW:
1361   {
1362     FINDTEXTW *ft = (FINDTEXTW *)lParam;
1363     return ME_FindText(editor, wParam, &ft->chrg, ft->lpstrText, NULL);
1364   }
1365   case EM_FINDTEXTEXW:
1366   {
1367     FINDTEXTEXW *ex = (FINDTEXTEXW *)lParam;
1368     return ME_FindText(editor, wParam, &ex->chrg, ex->lpstrText, &ex->chrgText);
1369   }
1370   case WM_CREATE:
1371     ME_CommitUndo(editor);
1372     ME_WrapMarkedParagraphs(editor);
1373     ME_MoveCaret(editor);
1374     return 0;
1375   case WM_DESTROY:
1376     ME_DestroyEditor(editor);
1377     SetWindowLongW(hWnd, 0, 0);
1378     return 0;
1379   case WM_LBUTTONDOWN:
1380     SetFocus(hWnd);
1381     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1382     SetCapture(hWnd);
1383     break;
1384   case WM_MOUSEMOVE:
1385     if (GetCapture() == hWnd)
1386       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1387     break;
1388   case WM_LBUTTONUP:
1389     if (GetCapture() == hWnd)
1390       ReleaseCapture();
1391     break;
1392   case WM_PAINT:
1393     hDC = BeginPaint(hWnd, &ps);
1394     ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1395     EndPaint(hWnd, &ps);
1396     break;
1397   case WM_SETFOCUS:
1398     ME_ShowCaret(editor);
1399     ME_SendOldNotify(editor, EN_SETFOCUS);
1400     return 0;
1401   case WM_KILLFOCUS:
1402     ME_HideCaret(editor);
1403     ME_SendOldNotify(editor, EN_KILLFOCUS);
1404     return 0;
1405   case WM_ERASEBKGND:
1406   {
1407     HDC hDC = (HDC)wParam;
1408     RECT rc;
1409     COLORREF rgbBG = ME_GetBackColor(editor);
1410     if (GetUpdateRect(hWnd,&rc,TRUE))
1411     {
1412       HBRUSH hbr = CreateSolidBrush(rgbBG);
1413       FillRect(hDC, &rc, hbr);
1414       DeleteObject(hbr);
1415     }
1416     return 1;
1417   }
1418   case WM_COMMAND:
1419     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1420     return 0;
1421   case WM_KEYDOWN:
1422     if (ME_ArrowKey(editor, LOWORD(wParam), GetKeyState(VK_CONTROL)<0)) {
1423       ME_CommitUndo(editor);
1424       ME_EnsureVisible(editor, editor->pCursors[0].pRun);
1425       HideCaret(hWnd);
1426       ME_MoveCaret(editor);
1427       ShowCaret(hWnd);
1428       return 0;
1429     }
1430     if (GetKeyState(VK_CONTROL)<0)
1431     {
1432       if (LOWORD(wParam)=='W')
1433       {
1434         CHARFORMAT2W chf;
1435         char buf[2048];
1436         ME_GetSelectionCharFormat(editor, &chf);
1437         ME_DumpStyleToBuf(&chf, buf);
1438         MessageBoxA(NULL, buf, "Style dump", MB_OK);
1439       }
1440       if (LOWORD(wParam)=='Q')
1441       {
1442         ME_CheckCharOffsets(editor);
1443       }
1444     }
1445     goto do_default;
1446   case WM_CHAR: 
1447   {
1448     WCHAR wstr;
1449     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1450       MessageBeep(MB_ICONERROR);
1451       return 0; /* FIXME really 0 ? */
1452     }
1453     wstr = LOWORD(wParam);
1454     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1455       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1456       ME_Style *style = ME_GetInsertStyle(editor, 0);
1457       ME_SaveTempStyle(editor);
1458       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1459       ME_ReleaseStyle(style);
1460       ME_CommitUndo(editor);
1461       ME_UpdateRepaint(editor);
1462     }
1463     return 0;
1464   }
1465   case WM_VSCROLL: 
1466   {
1467     int nPos = editor->nScrollPosY;
1468     si.cbSize = sizeof(SCROLLINFO);
1469     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1470     GetScrollInfo(hWnd, SB_VERT, &si);
1471     switch(LOWORD(wParam)) {
1472     case SB_LINEUP:
1473       nPos -= 24; /* FIXME follow the original */
1474       if (nPos<0) nPos = 0;
1475       break;
1476     case SB_LINEDOWN:
1477     {
1478       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1479       nPos += 24; /* FIXME follow the original */
1480       if (nPos>=nEnd) nPos = nEnd;
1481       break;
1482     }
1483     case SB_PAGEUP:
1484       nPos -= editor->sizeWindow.cy;
1485       if (nPos<0) nPos = 0;
1486       break;
1487     case SB_PAGEDOWN:
1488       nPos += editor->sizeWindow.cy;
1489       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1490       break;
1491     case SB_THUMBTRACK:
1492     case SB_THUMBPOSITION:
1493       nPos = si.nTrackPos;
1494       break;
1495     }
1496     if (nPos != editor->nScrollPosY) {
1497       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1498       editor->nScrollPosY = nPos;
1499       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1500       UpdateWindow(hWnd);
1501     }
1502     break;
1503   }
1504   case WM_MOUSEWHEEL:
1505   {
1506     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1507     UINT pulScrollLines;
1508     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1509     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1510     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1511       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1512     if (nPos>=nEnd)
1513       nPos = nEnd;
1514     if (nPos<0)
1515       nPos = 0;
1516     if (nPos != editor->nScrollPosY) {
1517       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1518       editor->nScrollPosY = nPos;
1519       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1520       UpdateWindow(hWnd);
1521     }
1522     break;
1523   }
1524   case WM_SIZE:
1525   {
1526     ME_MarkAllForWrapping(editor);
1527     ME_WrapMarkedParagraphs(editor);
1528     ME_UpdateScrollBar(editor);
1529     ME_Repaint(editor);
1530     return DefWindowProcW(hWnd, msg, wParam, lParam);
1531   }
1532   case EM_GETOLEINTERFACE:
1533   {
1534     LPVOID *ppvObj = (LPVOID*) lParam;
1535     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
1536     return CreateIRichEditOle(ppvObj);
1537   }
1538   default:
1539   do_default:
1540     return DefWindowProcW(hWnd, msg, wParam, lParam);
1541   }
1542   return 0L;
1543 }
1544
1545 /******************************************************************
1546  *        RichEdit10ANSIWndProc (RICHED20.9)
1547  */
1548 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1549 {
1550   /* FIXME: this is NOT the same as 2.0 version */
1551   return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
1552 }
1553
1554 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
1555 {
1556   HWND hWnd = editor->hWnd;
1557   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
1558 }
1559
1560 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
1561 {
1562   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1563   int i = 0;
1564   
1565   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
1566     item = item->member.para.next_para;
1567   if (!item)
1568     return 0;
1569   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
1570     item = item->member.para.next_para;
1571     i++;
1572   }
1573   return i;
1574 }
1575
1576
1577 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
1578 {
1579   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1580   int nWritten = 0;
1581   
1582   if (!item) {
1583     *buffer = L'\0';
1584     return 0;
1585   }
1586   assert(item);    
1587   
1588   if (nStart)
1589   {
1590     int nLen = ME_StrLen(item->member.run.strText) - nStart;
1591     if (nLen > nChars)
1592       nLen = nChars;
1593     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
1594     nChars -= nLen;
1595     nWritten += nLen;
1596     if (!nChars)
1597       return nWritten;
1598     buffer += nLen;
1599     nStart = 0;
1600     item = ME_FindItemFwd(item, diRun);
1601   }
1602   
1603   while(nChars && item)
1604   {
1605     int nLen = ME_StrLen(item->member.run.strText);
1606     if (nLen > nChars)
1607       nLen = nChars;
1608       
1609     if (item->member.run.nFlags & MERF_ENDPARA)
1610     {
1611       if (bCRLF) {
1612         *buffer++ = '\r';
1613         nWritten++;
1614       }        
1615       *buffer = '\n';
1616       assert(nLen == 1);
1617     }
1618     else      
1619       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
1620     nChars -= nLen;
1621     nWritten += nLen;
1622     buffer += nLen;    
1623       
1624     if (!nChars)
1625     {
1626       *buffer = L'\0';
1627       return nWritten;
1628     }
1629     item = ME_FindItemFwd(item, diRun);
1630   }
1631   *buffer = L'\0';
1632   return nWritten;  
1633 }
1634
1635 void ME_RegisterEditorClass(HINSTANCE hInstance)
1636 {
1637   BOOL bResult;
1638   WNDCLASSW wcW;
1639   WNDCLASSA wcA;
1640   
1641   wcW.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1642   wcW.lpfnWndProc = RichEditANSIWndProc;
1643   wcW.cbClsExtra = 0;
1644   wcW.cbWndExtra = 4;
1645   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
1646   wcW.hIcon = NULL;
1647   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1648   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1649   wcW.lpszMenuName = NULL;
1650   wcW.lpszClassName = wszClassName;
1651   bResult = RegisterClassW(&wcW);  
1652   assert(bResult);
1653   wcW.lpszClassName = wszClassName50;
1654   bResult = RegisterClassW(&wcW);  
1655   assert(bResult);
1656
1657   wcA.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1658   wcA.lpfnWndProc = RichEditANSIWndProc;
1659   wcA.cbClsExtra = 0;
1660   wcA.cbWndExtra = 4;
1661   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
1662   wcA.hIcon = NULL;
1663   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1664   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1665   wcA.lpszMenuName = NULL;
1666   wcA.lpszClassName = "RichEdit20A";
1667   bResult = RegisterClassA(&wcA);  
1668   assert(bResult);
1669   wcA.lpszClassName = "RichEdit50A";
1670   bResult = RegisterClassA(&wcA);  
1671   assert(bResult);
1672 }
1673 /******************************************************************
1674  *        CreateTextServices (RICHED20.4)
1675  *
1676  * FIXME should be ITextHost instead of void*
1677  */
1678 HRESULT WINAPI CreateTextServices(IUnknown *punkOuter, void *pITextHost,
1679     IUnknown **ppUnk)
1680 {
1681   FIXME("stub\n");
1682   /* FIXME should support aggregation */
1683   if (punkOuter)
1684     return CLASS_E_NOAGGREGATION;
1685     
1686   return E_FAIL; /* E_NOTIMPL isn't allowed by MSDN */
1687 }
1688
1689 /******************************************************************
1690  *        REExtendedRegisterClass (RICHED20.8)
1691  *
1692  * FIXME undocumented
1693  */
1694 void WINAPI REExtendedRegisterClass(void)
1695 {
1696   FIXME("stub\n");
1697 }