Moved the audio driver configuration to HKCU\Software\Wine\Drivers and
[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
37   - EM_FINDTEXTEX
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
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 (can't fall back to text when the RTF isn't really RTF)
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 "ole2.h"
222 #include "richole.h"
223 #include "winreg.h"
224 #define NO_SHLWAPI_STREAM 
225 #include "shlwapi.h"
226
227 #include "rtf.h"
228  
229 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
230
231 int me_debug = 0;
232 HANDLE me_heap = NULL;
233
234 ME_TextBuffer *ME_MakeText() {
235   
236   ME_TextBuffer *buf = ALLOC_OBJ(ME_TextBuffer);
237
238   ME_DisplayItem *p1 = ME_MakeDI(diTextStart);
239   ME_DisplayItem *p2 = ME_MakeDI(diTextEnd);
240   
241   p1->prev = NULL;
242   p1->next = p2;
243   p2->prev = p1;
244   p2->next = NULL;
245   p1->member.para.next_para = p2;
246   p2->member.para.prev_para = p1;
247   p2->member.para.nCharOfs = 0;  
248   
249   buf->pFirst = p1;
250   buf->pLast = p2;
251   buf->pCharStyle = NULL;
252   
253   return buf;
254 }
255
256
257 static LRESULT ME_StreamInText(ME_TextEditor *editor, DWORD dwFormat, ME_InStream *stream, ME_Style *style)
258 {
259   WCHAR wszText[STREAMIN_BUFFER_SIZE+1];
260   WCHAR *pText;
261   
262   TRACE("%08lx %p\n", dwFormat, stream);
263   
264   do {
265     long nWideChars = 0;
266
267     if (!stream->dwSize)
268     {
269       ME_StreamInFill(stream);
270       if (stream->editstream->dwError)
271         break;
272       if (!stream->dwSize)
273         break;
274     }
275       
276     if (!(dwFormat & SF_UNICODE))
277     {
278       /* FIXME? this is doomed to fail on true MBCS like UTF-8, luckily they're unlikely to be used as CP_ACP */
279       nWideChars = MultiByteToWideChar(CP_ACP, 0, stream->buffer, stream->dwSize, wszText, STREAMIN_BUFFER_SIZE);
280       pText = wszText;
281     }
282     else
283     {
284       nWideChars = stream->dwSize >> 1;
285       pText = (WCHAR *)stream->buffer;
286     }
287     
288     ME_InsertTextFromCursor(editor, 0, pText, nWideChars, style);
289     if (stream->dwSize < STREAMIN_BUFFER_SIZE)
290       break;
291     stream->dwSize = 0;
292   } while(1);
293   ME_CommitUndo(editor);
294   ME_Repaint(editor);
295   return 0;
296 }
297
298 void ME_RTFCharAttrHook(RTF_Info *info)
299 {
300   CHARFORMAT2W fmt;
301   fmt.cbSize = sizeof(fmt);
302   fmt.dwMask = 0;
303   
304   switch(info->rtfMinor)
305   {
306     case rtfPlain:
307       /* FIXME add more flags once they're implemented */
308       fmt.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR | CFM_BACKCOLOR | CFM_SIZE | CFM_WEIGHT;
309       fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
310       fmt.yHeight = 12*20; /* 12pt */
311       fmt.wWeight = 400;
312       break;
313     case rtfBold:
314       fmt.dwMask = CFM_BOLD;
315       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
316       break;
317     case rtfItalic:
318       fmt.dwMask = CFM_ITALIC;
319       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
320       break;
321     case rtfUnderline:
322       fmt.dwMask = CFM_UNDERLINE;
323       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
324       fmt.bUnderlineType = CFU_CF1UNDERLINE;
325       break;
326     case rtfNoUnderline:
327       fmt.dwMask = CFM_UNDERLINE;
328       fmt.dwEffects = 0;
329       break;
330     case rtfStrikeThru:
331       fmt.dwMask = CFM_STRIKEOUT;
332       fmt.dwEffects = info->rtfParam ? fmt.dwMask : 0;
333       break;
334     case rtfSubScript:
335     case rtfSuperScript:
336     case rtfSubScrShrink:
337     case rtfSuperScrShrink:
338     case rtfNoSuperSub:
339       fmt.dwMask = CFM_SUBSCRIPT|CFM_SUPERSCRIPT;
340       if (info->rtfMinor == rtfSubScrShrink) fmt.dwEffects = CFE_SUBSCRIPT;
341       if (info->rtfMinor == rtfSuperScrShrink) fmt.dwEffects = CFE_SUPERSCRIPT;
342       if (info->rtfMinor == rtfNoSuperSub) fmt.dwEffects = 0;
343       break;
344     case rtfBackColor:
345       fmt.dwMask = CFM_BACKCOLOR;
346       fmt.dwEffects = 0;
347       if (info->rtfParam == 0)
348         fmt.dwEffects = CFE_AUTOBACKCOLOR;
349       else if (info->rtfParam != rtfNoParam)
350       {
351         RTFColor *c = RTFGetColor(info, info->rtfParam);
352         fmt.crTextColor = (c->rtfCBlue<<16)|(c->rtfCGreen<<8)|(c->rtfCRed);
353       }
354       break;
355     case rtfForeColor:
356       fmt.dwMask = CFM_COLOR;
357       fmt.dwEffects = 0;
358       if (info->rtfParam == 0)
359         fmt.dwEffects = CFE_AUTOCOLOR;
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 rtfFontNum:
367       if (info->rtfParam != rtfNoParam)
368       {
369         RTFFont *f = RTFGetFont(info, info->rtfParam);
370         if (f)
371         {
372           MultiByteToWideChar(CP_ACP, 0, f->rtfFName, -1, fmt.szFaceName, sizeof(fmt.szFaceName)/sizeof(WCHAR));
373           fmt.szFaceName[sizeof(fmt.szFaceName)/sizeof(WCHAR)-1] = '\0';
374           fmt.bCharSet = f->rtfFCharSet;
375           fmt.dwMask = CFM_FACE | CFM_CHARSET;
376         }
377       }
378       break;
379     case rtfFontSize:
380       fmt.dwMask = CFM_SIZE;
381       if (info->rtfParam != rtfNoParam)
382         fmt.yHeight = info->rtfParam*10;
383       break;
384   }
385   if (fmt.dwMask) {
386     ME_Style *style2;
387     RTFFlushOutputBuffer(info);
388     /* FIXME too slow ? how come ? */
389     style2 = ME_ApplyStyle(info->style, &fmt);
390     ME_ReleaseStyle(info->style);
391     info->style = style2;
392   }
393 }
394
395 /* FIXME this function doesn't get any information about context of the RTF tag, which is very bad,
396    the same tags mean different things in different contexts */
397 void ME_RTFParAttrHook(RTF_Info *info)
398 {
399   PARAFORMAT2 fmt;
400   fmt.cbSize = sizeof(fmt);
401   fmt.dwMask = 0;
402   
403   switch(info->rtfMinor)
404   {
405   case rtfParDef: /* I'm not 100% sure what does it do, but I guess it restores default paragraph attributes */
406     fmt.dwMask = PFM_ALIGNMENT | PFM_TABSTOPS | PFM_OFFSET | PFM_STARTINDENT;
407     fmt.wAlignment = PFA_LEFT;
408     fmt.cTabCount = 0;
409     fmt.dxOffset = fmt.dxStartIndent = 0;
410     break;
411   case rtfFirstIndent:
412     ME_GetSelectionParaFormat(info->editor, &fmt);
413     fmt.dwMask = PFM_STARTINDENT;
414     fmt.dxStartIndent = info->rtfParam + fmt.dxOffset;
415     break;
416   case rtfLeftIndent:
417   {
418     int first, left;
419     ME_GetSelectionParaFormat(info->editor, &fmt);
420     first = fmt.dxStartIndent;
421     left = info->rtfParam;
422     fmt.dwMask = PFM_STARTINDENT|PFM_OFFSET;
423     fmt.dxStartIndent = first + left;
424     fmt.dxOffset = -first;
425     break;
426   }
427   case rtfRightIndent:
428     fmt.dwMask = PFM_RIGHTINDENT;
429     fmt.dxRightIndent = info->rtfParam;
430     break;
431   case rtfQuadLeft:
432   case rtfQuadJust:
433     fmt.dwMask = PFM_ALIGNMENT;
434     fmt.wAlignment = PFA_LEFT;
435     break;
436   case rtfQuadRight:
437     fmt.dwMask = PFM_ALIGNMENT;
438     fmt.wAlignment = PFA_RIGHT;
439     break;
440   case rtfQuadCenter:
441     fmt.dwMask = PFM_ALIGNMENT;
442     fmt.wAlignment = PFA_CENTER;
443     break;
444   case rtfTabPos:
445     ME_GetSelectionParaFormat(info->editor, &fmt);
446     if (!(fmt.dwMask & PFM_TABSTOPS))
447     {
448       fmt.dwMask |= PFM_TABSTOPS;
449       fmt.cTabCount = 0;
450     }
451     if (fmt.cTabCount < MAX_TAB_STOPS)
452       fmt.rgxTabs[fmt.cTabCount++] = info->rtfParam;
453     break;
454   }  
455   if (fmt.dwMask) {
456     RTFFlushOutputBuffer(info);
457     /* FIXME too slow ? how come ?*/
458     ME_SetSelectionParaFormat(info->editor, &fmt);
459   }
460 }
461
462 void ME_RTFReadHook(RTF_Info *info) {
463   switch(info->rtfClass)
464   {
465     case rtfGroup:
466       switch(info->rtfMajor)
467       {
468         case rtfBeginGroup:
469           if (info->stackTop < maxStack) {
470             memcpy(&info->stack[info->stackTop].fmt, &info->style->fmt, sizeof(CHARFORMAT2W));
471             info->stack[info->stackTop].codePage = info->codePage;
472             info->stack[info->stackTop].unicodeLength = info->unicodeLength;
473           }
474           info->stackTop++;
475           break;
476         case rtfEndGroup:
477         {
478           ME_Style *s;
479           RTFFlushOutputBuffer(info);
480           info->stackTop--;
481           /* FIXME too slow ? how come ? */
482           s = ME_ApplyStyle(info->style, &info->stack[info->stackTop].fmt);
483           ME_ReleaseStyle(info->style);
484           info->style = s;
485           info->codePage = info->stack[info->stackTop].codePage;
486           info->unicodeLength = info->stack[info->stackTop].unicodeLength;
487           break;
488         }
489       }
490       break;
491     case rtfControl:
492       switch(info->rtfMajor)
493       {
494         case rtfCharAttr:
495           ME_RTFCharAttrHook(info);
496           break;
497         case rtfParAttr:
498           ME_RTFParAttrHook(info);
499           break;
500       }
501       break;
502   }
503 }
504
505 void
506 ME_StreamInFill(ME_InStream *stream)
507 {
508   stream->editstream->dwError = stream->editstream->pfnCallback(stream->editstream->dwCookie,
509                                                                 stream->buffer,
510                                                                 sizeof(stream->buffer),
511                                                                 &stream->dwSize);
512   stream->dwUsed = 0;
513 }
514
515 static LRESULT ME_StreamIn(ME_TextEditor *editor, DWORD format, EDITSTREAM *stream)
516 {
517   RTF_Info parser;
518   ME_Style *style;
519   int from, to, to2, nUndoMode;
520   ME_UndoItem *pUI;
521   int nEventMask = editor->nEventMask;
522   ME_InStream inStream;
523
524   TRACE("stream==%p hWnd==%p format==0x%X\n", stream, editor->hWnd, (UINT)format);
525   editor->nEventMask = 0;
526   
527   ME_GetSelection(editor, &from, &to);
528   if (format & SFF_SELECTION) {
529     style = ME_GetSelectionInsertStyle(editor);
530
531     ME_InternalDeleteText(editor, from, to-from);
532   }
533   else {
534     style = editor->pBuffer->pDefaultStyle;
535     ME_AddRefStyle(style);
536     SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);    
537     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
538     from = to = 0;
539     ME_ClearTempStyle(editor);
540     /* FIXME restore default paragraph formatting ! */
541   }
542   
543   nUndoMode = editor->nUndoMode;
544   editor->nUndoMode = umIgnore;
545
546   inStream.editstream = stream;
547   inStream.editstream->dwError = 0;
548   inStream.dwSize = 0;
549   inStream.dwUsed = 0;
550
551   if (format & SF_RTF)
552   {
553     /* Check if it's really RTF, and if it is not, use plain text */
554     ME_StreamInFill(&inStream);
555     if (!inStream.editstream->dwError)
556     {
557       if (strncmp(inStream.buffer, "{\\rtf1", 6) && strncmp(inStream.buffer, "{\\urtf", 6))
558       {
559         format &= ~SF_RTF;
560         format |= SF_TEXT;
561       }
562     }
563   }
564
565   if (!inStream.editstream->dwError)
566   {
567     if (format & SF_RTF) {
568       /* setup the RTF parser */
569       memset(&parser, 0, sizeof parser);
570       RTFSetEditStream(&parser, &inStream);
571       parser.rtfFormat = format&(SF_TEXT|SF_RTF);
572       parser.hwndEdit = editor->hWnd;
573       parser.editor = editor;
574       parser.style = style;
575       WriterInit(&parser);
576       RTFInit(&parser);
577       RTFSetReadHook(&parser, ME_RTFReadHook);
578       BeginFile(&parser);
579   
580       /* do the parsing */
581       RTFRead(&parser);
582       RTFFlushOutputBuffer(&parser);
583       RTFDestroy(&parser);
584
585       style = parser.style;
586     }
587     else if (format & SF_TEXT)
588       ME_StreamInText(editor, format, &inStream, style);
589     else
590       ERR("EM_STREAMIN without SF_TEXT or SF_RTF\n");
591     ME_GetSelection(editor, &to, &to2);
592     /* put the cursor at the top */
593     if (!(format & SFF_SELECTION))
594       SendMessageA(editor->hWnd, EM_SETSEL, 0, 0);
595     else
596     {
597       /* FIXME where to put cursor now ? */
598     }
599   }
600   
601   editor->nUndoMode = nUndoMode;
602   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
603   TRACE("from %d to %d\n", from, to);
604   if (pUI && from < to)
605   {
606     pUI->nStart = from;
607     pUI->nLen = to-from;
608   }
609   ME_CommitUndo(editor);
610   ME_ReleaseStyle(style); 
611   editor->nEventMask = nEventMask;
612   InvalidateRect(editor->hWnd, NULL, TRUE);
613   ME_UpdateRepaint(editor);
614   if (!(format & SFF_SELECTION)) {
615     ME_ClearTempStyle(editor);
616   }
617   ME_MoveCaret(editor);
618   ME_SendSelChange(editor);
619
620   return 0;
621 }
622
623
624 ME_DisplayItem *
625 ME_FindItemAtOffset(ME_TextEditor *editor, ME_DIType nItemType, int nOffset, int *nItemOffset)
626 {
627   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
628   
629   while (item && item->member.para.next_para->member.para.nCharOfs <= nOffset)
630     item = ME_FindItemFwd(item, diParagraph);
631
632   if (!item)
633     return item;
634
635   nOffset -= item->member.para.nCharOfs;
636   if (nItemType == diParagraph) {
637     if (nItemOffset)
638       *nItemOffset = nOffset;
639     return item;
640   }
641   
642   do {
643     item = ME_FindItemFwd(item, diRun);
644   } while (item && (item->member.run.nCharOfs + ME_StrLen(item->member.run.strText) <= nOffset));
645   if (item) {
646     nOffset -= item->member.run.nCharOfs;
647     if (nItemOffset)
648       *nItemOffset = nOffset;
649   }
650   return item;
651 }
652
653
654 ME_TextEditor *ME_MakeEditor(HWND hWnd) {
655   ME_TextEditor *ed = ALLOC_OBJ(ME_TextEditor);
656   HDC hDC;
657   int i;
658   ed->hWnd = hWnd;
659   ed->pBuffer = ME_MakeText();
660   hDC = GetDC(hWnd);
661   ME_MakeFirstParagraph(hDC, ed->pBuffer);
662   ReleaseDC(hWnd, hDC);
663   ed->bCaretShown = FALSE;
664   ed->nCursors = 3;
665   ed->pCursors = ALLOC_N_OBJ(ME_Cursor, ed->nCursors);
666   ed->pCursors[0].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
667   ed->pCursors[0].nOffset = 0;
668   ed->pCursors[1].pRun = ME_FindItemFwd(ed->pBuffer->pFirst, diRun);
669   ed->pCursors[1].nOffset = 0;
670   ed->nLastTotalLength = ed->nTotalLength = 0;
671   ed->nUDArrowX = -1;
672   ed->nSequence = 0;
673   ed->rgbBackColor = -1;
674   ed->bCaretAtEnd = FALSE;
675   ed->nEventMask = 0;
676   ed->nModifyStep = 0;
677   ed->pUndoStack = ed->pRedoStack = NULL;
678   ed->nUndoMode = umAddToUndo;
679   ed->nParagraphs = 1;
680   ed->nLastSelStart = ed->nLastSelEnd = 0;
681   ed->nScrollPosY = 0;
682   for (i=0; i<HFONT_CACHE_SIZE; i++)
683   {
684     ed->pFontCache[i].nRefs = 0;
685     ed->pFontCache[i].nAge = 0;
686     ed->pFontCache[i].hFont = NULL;
687   }
688   ME_CheckCharOffsets(ed);
689   return ed;
690 }
691
692 typedef struct tagME_GlobalDestStruct
693 {
694   HGLOBAL hData;
695   int nLength;
696 } ME_GlobalDestStruct;
697
698 static DWORD CALLBACK ME_AppendToHGLOBAL(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
699 {
700   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
701   int nMaxSize;
702   BYTE *pDest;
703   
704   nMaxSize = GlobalSize(pData->hData);
705   if (pData->nLength+cb+1 >= cb)
706   {
707     /* round up to 2^17 */
708     int nNewSize = (((nMaxSize+cb+1)|0x1FFFF)+1) & 0xFFFE0000;
709     pData->hData = GlobalReAlloc(pData->hData, nNewSize, 0);
710   }
711   pDest = (BYTE *)GlobalLock(pData->hData);
712   memcpy(pDest + pData->nLength, lpBuff, cb);
713   pData->nLength += cb;
714   pDest[pData->nLength] = '\0';
715   GlobalUnlock(pData->hData);
716   *pcb = cb;
717   
718   return 0;
719 }
720
721 static DWORD CALLBACK ME_ReadFromHGLOBALUnicode(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
722 {
723   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
724   int i;
725   WORD *pSrc, *pDest;
726   
727   cb = cb >> 1;
728   pDest = (WORD *)lpBuff;
729   pSrc = (WORD *)GlobalLock(pData->hData);
730   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
731     pDest[i] = pSrc[pData->nLength+i];
732   }    
733   pData->nLength += i;
734   *pcb = 2*i;
735   GlobalUnlock(pData->hData);
736   return 0;
737 }
738
739 static DWORD CALLBACK ME_ReadFromHGLOBALRTF(DWORD_PTR dwCookie, LPBYTE lpBuff, LONG cb, LONG *pcb)
740 {
741   ME_GlobalDestStruct *pData = (ME_GlobalDestStruct *)dwCookie;
742   int i;
743   BYTE *pSrc, *pDest;
744   
745   pDest = lpBuff;
746   pSrc = (BYTE *)GlobalLock(pData->hData);
747   for (i = 0; i<cb && pSrc[pData->nLength+i]; i++) {
748     pDest[i] = pSrc[pData->nLength+i];
749   }    
750   pData->nLength += i;
751   *pcb = i;
752   GlobalUnlock(pData->hData);
753   return 0;
754 }
755
756 void ME_DestroyEditor(ME_TextEditor *editor)
757 {
758   ME_DisplayItem *pFirst = editor->pBuffer->pFirst;
759   ME_DisplayItem *p = pFirst, *pNext = NULL;
760   int i;
761   
762   ME_ClearTempStyle(editor);
763   ME_EmptyUndoStack(editor);
764   while(p) {
765     pNext = p->next;
766     ME_DestroyDisplayItem(p);    
767     p = pNext;
768   }
769   ME_ReleaseStyle(editor->pBuffer->pDefaultStyle);
770   for (i=0; i<HFONT_CACHE_SIZE; i++)
771   {
772     if (editor->pFontCache[i].hFont)
773       DeleteObject(editor->pFontCache[i].hFont);
774   }
775     
776   FREE_OBJ(editor);
777 }
778
779 static WCHAR wszClassName[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '2', '0', 'W', 0};
780 static WCHAR wszClassName50[] = {'R', 'i', 'c', 'h', 'E', 'd', 'i', 't', '5', '0', 'W', 0};
781
782 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
783 {
784     TRACE("\n");
785     switch (fdwReason)
786     {
787     case DLL_PROCESS_ATTACH:
788       DisableThreadLibraryCalls(hinstDLL);
789       me_heap = HeapCreate (0, 0x10000, 0);
790       ME_RegisterEditorClass(hinstDLL);
791       break;
792
793     case DLL_PROCESS_DETACH:
794       UnregisterClassW(wszClassName, 0);
795       UnregisterClassW(wszClassName50, 0);
796       UnregisterClassA("RichEdit20A", 0);
797       UnregisterClassA("RichEdit50A", 0);
798       HeapDestroy (me_heap);
799       me_heap = NULL;
800       break;
801     }
802     return TRUE;
803 }
804
805
806 #define UNSUPPORTED_MSG(e) \
807   case e: \
808     FIXME(#e ": stub\n"); \
809     return DefWindowProcW(hWnd, msg, wParam, lParam);
810
811 /******************************************************************
812  *        RichEditANSIWndProc (RICHED20.10)
813  */
814 LRESULT WINAPI RichEditANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
815   HDC hDC;
816   PAINTSTRUCT ps;
817   SCROLLINFO si;
818   ME_TextEditor *editor = (ME_TextEditor *)GetWindowLongW(hWnd, 0);
819   TRACE("msg %d %08x %08lx\n", msg, wParam, lParam);
820   switch(msg) {
821   
822   UNSUPPORTED_MSG(EM_AUTOURLDETECT)
823   UNSUPPORTED_MSG(EM_CHARFROMPOS)
824   UNSUPPORTED_MSG(EM_DISPLAYBAND)
825   UNSUPPORTED_MSG(EM_EXLIMITTEXT)
826   UNSUPPORTED_MSG(EM_EXLINEFROMCHAR)
827   UNSUPPORTED_MSG(EM_FINDTEXT)
828   UNSUPPORTED_MSG(EM_FINDTEXTEX)
829   UNSUPPORTED_MSG(EM_FINDWORDBREAK)
830   UNSUPPORTED_MSG(EM_FMTLINES)
831   UNSUPPORTED_MSG(EM_FORMATRANGE)
832   UNSUPPORTED_MSG(EM_GETAUTOURLDETECT)
833   UNSUPPORTED_MSG(EM_GETBIDIOPTIONS)
834   UNSUPPORTED_MSG(EM_GETEDITSTYLE)
835   UNSUPPORTED_MSG(EM_GETFIRSTVISIBLELINE)
836   UNSUPPORTED_MSG(EM_GETIMECOMPMODE)
837   /* UNSUPPORTED_MSG(EM_GETIMESTATUS) missing in Wine headers */
838   UNSUPPORTED_MSG(EM_GETLANGOPTIONS)
839   UNSUPPORTED_MSG(EM_GETLIMITTEXT)
840   UNSUPPORTED_MSG(EM_GETLINE)
841   UNSUPPORTED_MSG(EM_GETLINECOUNT)
842   /* UNSUPPORTED_MSG(EM_GETOLEINTERFACE) separate stub */
843   UNSUPPORTED_MSG(EM_GETOPTIONS)
844   UNSUPPORTED_MSG(EM_GETPASSWORDCHAR)
845   UNSUPPORTED_MSG(EM_GETRECT)
846   UNSUPPORTED_MSG(EM_GETREDONAME)
847   UNSUPPORTED_MSG(EM_GETSCROLLPOS)
848   UNSUPPORTED_MSG(EM_GETTEXTEX)
849   UNSUPPORTED_MSG(EM_GETTEXTLENGTHEX)
850   UNSUPPORTED_MSG(EM_GETTEXTMODE)
851   UNSUPPORTED_MSG(EM_GETTYPOGRAPHYOPTIONS)
852   UNSUPPORTED_MSG(EM_GETUNDONAME)
853   UNSUPPORTED_MSG(EM_GETWORDBREAKPROC)
854   UNSUPPORTED_MSG(EM_GETWORDBREAKPROCEX)
855   UNSUPPORTED_MSG(EM_GETZOOM)
856   UNSUPPORTED_MSG(EM_HIDESELECTION)
857   UNSUPPORTED_MSG(EM_LIMITTEXT) /* also known as EM_SETLIMITTEXT */
858   UNSUPPORTED_MSG(EM_LINEFROMCHAR)
859   UNSUPPORTED_MSG(EM_LINEINDEX)
860   UNSUPPORTED_MSG(EM_LINELENGTH)
861   UNSUPPORTED_MSG(EM_PASTESPECIAL)
862 /*  UNSUPPORTED_MSG(EM_POSFROMCHARS) missing in Wine headers */
863   UNSUPPORTED_MSG(EM_REQUESTRESIZE)
864   UNSUPPORTED_MSG(EM_SCROLL)
865   UNSUPPORTED_MSG(EM_SCROLLCARET)
866   UNSUPPORTED_MSG(EM_SELECTIONTYPE)
867   UNSUPPORTED_MSG(EM_SETBIDIOPTIONS)
868   UNSUPPORTED_MSG(EM_SETEDITSTYLE)
869   UNSUPPORTED_MSG(EM_SETFONTSIZE)
870   UNSUPPORTED_MSG(EM_SETLANGOPTIONS)
871   UNSUPPORTED_MSG(EM_SETOLECALLBACK)
872   UNSUPPORTED_MSG(EM_SETOPTIONS)
873   UNSUPPORTED_MSG(EM_SETPALETTE)
874   UNSUPPORTED_MSG(EM_SETPASSWORDCHAR)
875   UNSUPPORTED_MSG(EM_SETRECT)
876   UNSUPPORTED_MSG(EM_SETRECTNP)
877   UNSUPPORTED_MSG(EM_SETSCROLLPOS)
878   UNSUPPORTED_MSG(EM_SETTABSTOPS)
879   UNSUPPORTED_MSG(EM_SETTARGETDEVICE)
880   UNSUPPORTED_MSG(EM_SETTEXTEX)
881   UNSUPPORTED_MSG(EM_SETTEXTMODE)
882   UNSUPPORTED_MSG(EM_SETTYPOGRAPHYOPTIONS)
883   UNSUPPORTED_MSG(EM_SETUNDOLIMIT)
884   UNSUPPORTED_MSG(EM_SETWORDBREAKPROC)
885   UNSUPPORTED_MSG(EM_SETWORDBREAKPROCEX)
886   UNSUPPORTED_MSG(EM_SHOWSCROLLBAR)
887   UNSUPPORTED_MSG(EM_SETZOOM)
888   UNSUPPORTED_MSG(WM_SETFONT)
889   UNSUPPORTED_MSG(WM_STYLECHANGING)
890   UNSUPPORTED_MSG(WM_STYLECHANGED)
891 /*  UNSUPPORTED_MSG(WM_UNICHAR) FIXME missing in Wine headers */
892     
893 /* Messages specific to Richedit controls */
894   
895   case EM_STREAMIN:
896    return ME_StreamIn(editor, wParam, (EDITSTREAM*)lParam);
897   case EM_STREAMOUT:
898    return ME_StreamOut(editor, wParam, (EDITSTREAM *)lParam);
899   case WM_GETDLGCODE:
900   {
901     UINT code = DLGC_WANTCHARS|DLGC_WANTARROWS;
902     if (GetWindowLongW(hWnd, GWL_STYLE)&ES_WANTRETURN)
903       code |= 0; /* FIXME what can we do here ? ask for messages and censor them ? */
904     return code;
905   }
906   case WM_NCCREATE:
907   {
908     CREATESTRUCTW *pcs = (CREATESTRUCTW *)lParam;
909     editor = ME_MakeEditor(hWnd);
910     SetWindowLongW(hWnd, 0, (long)editor);
911     pcs = 0; /* ignore */
912     return TRUE;
913   }
914   case EM_EMPTYUNDOBUFFER:
915     ME_EmptyUndoStack(editor);
916     return 0;
917   case EM_GETSEL:
918   {
919     /* Note: wParam/lParam can be NULL */
920     UINT from, to;
921     PUINT pfrom = wParam ? (PUINT)wParam : &from;
922     PUINT pto = lParam ? (PUINT)lParam : &to;
923     ME_GetSelection(editor, pfrom, pto);
924     if ((*pfrom|*pto) & 0xFFFF0000)
925       return -1;
926     return MAKELONG(*pfrom,*pto);
927   }
928   case EM_EXGETSEL:
929   {
930     CHARRANGE *pRange = (CHARRANGE *)lParam;
931     ME_GetSelection(editor, (int *)&pRange->cpMin, (int *)&pRange->cpMax);
932     return 0;
933   }
934   case EM_CANUNDO:
935     return editor->pUndoStack != NULL;
936   case EM_CANREDO:
937     return editor->pRedoStack != NULL;
938   case EM_UNDO:
939     ME_Undo(editor);
940     return 0;
941   case EM_REDO:
942     ME_Redo(editor);
943     return 0;
944   case EM_SETSEL:
945   {
946     ME_SetSelection(editor, wParam, lParam);
947     ME_Repaint(editor);
948     ME_SendSelChange(editor);
949     return 0;
950   }
951   case EM_EXSETSEL:
952   {
953     CHARRANGE *pRange = (CHARRANGE *)lParam;
954     ME_SetSelection(editor, pRange->cpMin, pRange->cpMax);
955     /* FIXME optimize */
956     ME_Repaint(editor);
957     ME_SendSelChange(editor);
958     return 0;
959   }
960   case EM_SETBKGNDCOLOR:
961   {
962     LRESULT lColor = ME_GetBackColor(editor);
963     if (wParam)
964       editor->rgbBackColor = -1;
965     else
966       editor->rgbBackColor = lParam; 
967     InvalidateRect(hWnd, NULL, TRUE);
968     UpdateWindow(hWnd);
969     return lColor;
970   }
971   case EM_GETMODIFY:
972     return editor->nModifyStep == 0 ? 0 : 1;
973   case EM_SETMODIFY:
974   {
975     if (wParam)
976       editor->nModifyStep = 0x80000000;
977     else
978       editor->nModifyStep = 0;
979     
980     return 0;
981   }
982   case EM_SETREADONLY:
983   {
984     long nStyle = GetWindowLongW(hWnd, GWL_STYLE);
985     if (wParam)
986       nStyle |= ES_READONLY;
987     else
988       nStyle &= ~ES_READONLY;
989     SetWindowLongW(hWnd, GWL_STYLE, nStyle);
990     ME_Repaint(editor);
991     return 0;
992   }
993   case EM_SETEVENTMASK:
994     editor->nEventMask = lParam;
995     return 0;
996   case EM_GETEVENTMASK:
997     return editor->nEventMask;
998   case EM_SETCHARFORMAT:
999   {
1000     CHARFORMAT2W buf, *p;
1001     BOOL bRepaint = TRUE;
1002     p = ME_ToCF2W(&buf, (CHARFORMAT2W *)lParam);
1003     if (!wParam)
1004       ME_SetDefaultCharFormat(editor, p);
1005     else if (wParam == (SCF_WORD | SCF_SELECTION))
1006       FIXME("word selection not supported\n");
1007     else if (wParam == SCF_ALL)
1008       ME_SetCharFormat(editor, 0, ME_GetTextLength(editor), p);
1009     else {
1010       int from, to;
1011       ME_GetSelection(editor, &from, &to);
1012       bRepaint = (from != to);
1013       ME_SetSelectionCharFormat(editor, p);
1014     }
1015     ME_CommitUndo(editor);
1016     if (bRepaint)
1017       ME_UpdateRepaint(editor);
1018     return 0;
1019   }
1020   case EM_GETCHARFORMAT:
1021   {
1022     CHARFORMAT2W tmp;
1023     tmp.cbSize = sizeof(tmp);
1024     if (!wParam)
1025       ME_GetDefaultCharFormat(editor, &tmp);
1026     else
1027       ME_GetSelectionCharFormat(editor, &tmp);
1028     ME_CopyToCFAny((CHARFORMAT2W *)lParam, &tmp);
1029     return 0;
1030   }
1031   case EM_SETPARAFORMAT:
1032     ME_SetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1033     ME_UpdateRepaint(editor);
1034     ME_CommitUndo(editor);
1035     return 0;
1036   case EM_GETPARAFORMAT:
1037     ME_GetSelectionParaFormat(editor, (PARAFORMAT2 *)lParam);
1038     return 0;
1039   case EM_LINESCROLL:
1040   {
1041     int nPos = editor->nScrollPosY, nEnd= editor->nTotalLength - editor->sizeWindow.cy;
1042     nPos += 8 * lParam; /* FIXME follow the original */
1043     if (nPos>=nEnd)
1044       nPos = nEnd;
1045     if (nPos<0)
1046       nPos = 0;
1047     if (nPos != editor->nScrollPosY) {
1048       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1049       editor->nScrollPosY = nPos;
1050       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1051       UpdateWindow(hWnd);
1052     }
1053     return TRUE; /* Should return false if a single line richedit control */
1054   }
1055   case WM_CLEAR:
1056   {
1057     int from, to;
1058     ME_GetSelection(editor, &from, &to);
1059     ME_InternalDeleteText(editor, from, to-from);
1060     ME_CommitUndo(editor);
1061     ME_UpdateRepaint(editor);
1062     return 0;
1063   }
1064   case EM_REPLACESEL:
1065   {
1066     int from, to;
1067     ME_Style *style;
1068     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1069     size_t len = lstrlenW(wszText);
1070     TRACE("EM_REPLACESEL - %s\n", debugstr_w(wszText));
1071     
1072     ME_GetSelection(editor, &from, &to);
1073     style = ME_GetSelectionInsertStyle(editor);
1074     ME_InternalDeleteText(editor, from, to-from);
1075     ME_InsertTextFromCursor(editor, 0, wszText, len, style);
1076     ME_ReleaseStyle(style);
1077     ME_EndToUnicode(hWnd, wszText);
1078     /* drop temporary style if line end */
1079     /* FIXME question: does abc\n mean: put abc, clear temp style, put \n? (would require a change) */  
1080     if (len>0 && wszText[len-1] == '\n')
1081       ME_ClearTempStyle(editor);
1082       
1083     ME_CommitUndo(editor);
1084     if (!wParam)
1085       ME_EmptyUndoStack(editor);
1086     ME_UpdateRepaint(editor);
1087     return 0;
1088   }
1089   case WM_SETTEXT:
1090   {
1091     LPWSTR wszText = ME_ToUnicode(hWnd, (void *)lParam);
1092     TRACE("WM_SETTEXT - %s\n", (char *)(wszText)); /* debugstr_w() */
1093     ME_InternalDeleteText(editor, 0, ME_GetTextLength(editor));
1094     /* uses default style! */
1095     ME_InsertTextFromCursor(editor, 0, wszText, -1, editor->pBuffer->pDefaultStyle);
1096     ME_EndToUnicode(hWnd, wszText);
1097     ME_CommitUndo(editor);
1098     ME_EmptyUndoStack(editor);
1099     ME_UpdateRepaint(editor);
1100     return 0;
1101   }
1102   case EM_CANPASTE:
1103   {
1104     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1105     if (IsClipboardFormatAvailable(nRTFFormat))
1106       return TRUE;
1107     if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1108       return TRUE;
1109     return FALSE;
1110   }
1111   case WM_PASTE:
1112   {    
1113     DWORD dwFormat = 0;
1114     EDITSTREAM es;
1115     ME_GlobalDestStruct gds;
1116     UINT nRTFFormat = RegisterClipboardFormatA("Rich Text Format");
1117     UINT cf = 0;
1118
1119     if (IsClipboardFormatAvailable(nRTFFormat))
1120       cf = nRTFFormat, dwFormat = SF_RTF;
1121     else if (IsClipboardFormatAvailable(CF_UNICODETEXT))
1122       cf = CF_UNICODETEXT, dwFormat = SF_TEXT|SF_UNICODE;
1123     else
1124       return 0;
1125
1126     if (!OpenClipboard(hWnd))
1127       return 0;
1128     gds.hData = GetClipboardData(cf);
1129     gds.nLength = 0;
1130     es.dwCookie = (DWORD)&gds;
1131     es.pfnCallback = dwFormat == SF_RTF ? ME_ReadFromHGLOBALRTF : ME_ReadFromHGLOBALUnicode;
1132     SendMessageW(hWnd, EM_STREAMIN, dwFormat|SFF_SELECTION, (LPARAM)&es);
1133     
1134     CloseClipboard();
1135     return 0;
1136   }
1137   case WM_CUT:
1138   case WM_COPY:
1139   {
1140     int from, to, pars;
1141     WCHAR *data;
1142     HANDLE hData;
1143     EDITSTREAM es;
1144     ME_GlobalDestStruct gds;
1145     
1146     if (!OpenClipboard(hWnd))
1147       return 0;
1148       
1149     EmptyClipboard();
1150     ME_GetSelection(editor, &from, &to);
1151     pars = ME_CountParagraphsBetween(editor, from, to);
1152     hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(WCHAR)*(to-from+pars+1));
1153     data = (WCHAR *)GlobalLock(hData);
1154     ME_GetTextW(editor, data, from, to-from, TRUE);
1155     GlobalUnlock(hData);
1156
1157     gds.hData = GlobalAlloc(GMEM_MOVEABLE, 0);
1158     gds.nLength = 0;
1159     es.dwCookie = (DWORD)&gds;
1160     es.pfnCallback = ME_AppendToHGLOBAL;
1161     SendMessageW(hWnd, EM_STREAMOUT, SFF_SELECTION|SF_RTF, (LPARAM)&es);
1162     GlobalReAlloc(gds.hData, gds.nLength+1, 0);
1163     
1164     SetClipboardData(CF_UNICODETEXT, hData);    
1165     SetClipboardData(RegisterClipboardFormatA("Rich Text Format"), gds.hData);
1166     
1167     CloseClipboard();
1168     if (msg == WM_CUT)
1169     {
1170       ME_InternalDeleteText(editor, from, to-from);
1171       ME_CommitUndo(editor);
1172       ME_UpdateRepaint(editor);
1173     }
1174     return 0;
1175   }
1176   case WM_GETTEXTLENGTH:
1177     return ME_GetTextLength(editor);
1178   case WM_GETTEXT:
1179   {
1180     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1181     tr.chrg.cpMin = 0;
1182     tr.chrg.cpMax = wParam-1;
1183     tr.lpstrText = (WCHAR *)lParam;
1184     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1185   }
1186   case EM_GETSELTEXT:
1187   {
1188     int from, to;
1189     TEXTRANGEW tr; /* W and A differ only by rng->lpstrText */
1190     ME_GetSelection(editor, &from, &to);
1191     tr.chrg.cpMin = from;
1192     tr.chrg.cpMax = to;
1193     tr.lpstrText = (WCHAR *)lParam;
1194     return RichEditANSIWndProc(hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
1195   }
1196   case EM_GETTEXTRANGE:
1197   {
1198     TEXTRANGEW *rng = (TEXTRANGEW *)lParam;
1199     if (IsWindowUnicode(hWnd))
1200       return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, FALSE);
1201     else
1202     {
1203       int nLen = rng->chrg.cpMax-rng->chrg.cpMin;
1204       WCHAR *p = ALLOC_N_OBJ(WCHAR, nLen+1);
1205       int nChars = ME_GetTextW(editor, p, rng->chrg.cpMin, nLen, FALSE);
1206       /* FIXME this is a potential security hole (buffer overrun) 
1207          if you know more about wchar->mbyte conversion please explain
1208       */
1209       WideCharToMultiByte(CP_ACP, 0, p, nChars+1, (char *)rng->lpstrText, nLen+1, NULL, NULL);
1210       FREE_OBJ(p);
1211       return nChars;
1212     }
1213     return ME_GetTextW(editor, rng->lpstrText, rng->chrg.cpMin, rng->chrg.cpMax-rng->chrg.cpMin, FALSE);
1214   }
1215   case WM_CREATE:
1216     ME_CommitUndo(editor);
1217     ME_WrapMarkedParagraphs(editor);
1218     ME_MoveCaret(editor);
1219     return 0;
1220   case WM_DESTROY:
1221     ME_DestroyEditor(editor);
1222     SetWindowLongW(hWnd, 0, 0);
1223     return 0;
1224   case WM_LBUTTONDOWN:
1225     SetFocus(hWnd);
1226     ME_LButtonDown(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1227     SetCapture(hWnd);
1228     break;
1229   case WM_MOUSEMOVE:
1230     if (GetCapture() == hWnd)
1231       ME_MouseMove(editor, (short)LOWORD(lParam), (short)HIWORD(lParam));
1232     break;
1233   case WM_LBUTTONUP:
1234     if (GetCapture() == hWnd)
1235       ReleaseCapture();
1236     break;
1237   case WM_PAINT:
1238     hDC = BeginPaint(hWnd, &ps);
1239     ME_PaintContent(editor, hDC, FALSE, &ps.rcPaint);
1240     EndPaint(hWnd, &ps);
1241     break;
1242   case WM_SETFOCUS:
1243     ME_ShowCaret(editor);
1244     ME_SendOldNotify(editor, EN_SETFOCUS);
1245     return 0;
1246   case WM_KILLFOCUS:
1247     ME_HideCaret(editor);
1248     ME_SendOldNotify(editor, EN_KILLFOCUS);
1249     return 0;
1250   case WM_ERASEBKGND:
1251   {
1252     HDC hDC = (HDC)wParam;
1253     RECT rc;
1254     COLORREF rgbBG = ME_GetBackColor(editor);
1255     if (GetUpdateRect(hWnd,&rc,TRUE))
1256     {
1257       HBRUSH hbr = CreateSolidBrush(rgbBG);
1258       FillRect(hDC, &rc, hbr);
1259       DeleteObject(hbr);
1260     }
1261     return 1;
1262   }
1263   case WM_COMMAND:
1264     TRACE("editor wnd command = %d\n", LOWORD(wParam));
1265     return 0;
1266   case WM_KEYDOWN:
1267     if (ME_ArrowKey(editor, LOWORD(wParam), GetKeyState(VK_CONTROL)<0)) {
1268       ME_CommitUndo(editor);
1269       ME_EnsureVisible(editor, editor->pCursors[0].pRun);
1270       HideCaret(hWnd);
1271       ME_MoveCaret(editor);
1272       ShowCaret(hWnd);
1273       return 0;
1274     }
1275     if (GetKeyState(VK_CONTROL)<0)
1276     {
1277       if (LOWORD(wParam)=='W')
1278       {
1279         CHARFORMAT2W chf;
1280         char buf[2048];
1281         ME_GetSelectionCharFormat(editor, &chf);
1282         ME_DumpStyleToBuf(&chf, buf);
1283         MessageBoxA(NULL, buf, "Style dump", MB_OK);
1284       }
1285       if (LOWORD(wParam)=='Q')
1286       {
1287         ME_CheckCharOffsets(editor);
1288       }
1289     }
1290     goto do_default;
1291   case WM_CHAR: 
1292   {
1293     WCHAR wstr;
1294     if (GetWindowLongW(editor->hWnd, GWL_STYLE) & ES_READONLY) {
1295       MessageBeep(MB_ICONERROR);
1296       return 0; /* FIXME really 0 ? */
1297     }
1298     wstr = LOWORD(wParam);
1299     if (((unsigned)wstr)>=' ' || wstr=='\r' || wstr=='\t') {
1300       /* FIXME maybe it would make sense to call EM_REPLACESEL instead ? */
1301       ME_Style *style = ME_GetInsertStyle(editor, 0);
1302       ME_SaveTempStyle(editor);
1303       ME_InsertTextFromCursor(editor, 0, &wstr, 1, style);
1304       ME_ReleaseStyle(style);
1305       ME_CommitUndo(editor);
1306       ME_UpdateRepaint(editor);
1307     }
1308     return 0;
1309   }
1310   case WM_VSCROLL: 
1311   {
1312     int nPos = editor->nScrollPosY;
1313     si.cbSize = sizeof(SCROLLINFO);
1314     si.fMask = SIF_PAGE|SIF_POS|SIF_RANGE|SIF_TRACKPOS;
1315     GetScrollInfo(hWnd, SB_VERT, &si);
1316     switch(LOWORD(wParam)) {
1317     case SB_LINEUP:
1318       nPos -= 24; /* FIXME follow the original */
1319       if (nPos<0) nPos = 0;
1320       break;
1321     case SB_LINEDOWN:
1322     {
1323       int nEnd = editor->nTotalLength - editor->sizeWindow.cy;
1324       nPos += 24; /* FIXME follow the original */
1325       if (nPos>=nEnd) nPos = nEnd;
1326       break;
1327     }
1328     case SB_PAGEUP:
1329       nPos -= editor->sizeWindow.cy;
1330       if (nPos<0) nPos = 0;
1331       break;
1332     case SB_PAGEDOWN:
1333       nPos += editor->sizeWindow.cy;
1334       if (nPos>=editor->nTotalLength) nPos = editor->nTotalLength-1;
1335       break;
1336     case SB_THUMBTRACK:
1337     case SB_THUMBPOSITION:
1338       nPos = si.nTrackPos;
1339       break;
1340     }
1341     if (nPos != editor->nScrollPosY) {
1342       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1343       editor->nScrollPosY = nPos;
1344       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1345       UpdateWindow(hWnd);
1346     }
1347     break;
1348   }
1349   case WM_MOUSEWHEEL:
1350   {
1351     int gcWheelDelta = 0, nPos = editor->nScrollPosY, nEnd = editor->nTotalLength - editor->sizeWindow.cy; 
1352     UINT pulScrollLines;
1353     SystemParametersInfoW(SPI_GETWHEELSCROLLLINES,0, &pulScrollLines, 0);
1354     gcWheelDelta -= GET_WHEEL_DELTA_WPARAM(wParam);
1355     if (abs(gcWheelDelta) >= WHEEL_DELTA && pulScrollLines)
1356       nPos += pulScrollLines * (gcWheelDelta / WHEEL_DELTA) * 8; /* FIXME follow the original */
1357     if (nPos>=nEnd)
1358       nPos = nEnd;
1359     if (nPos<0)
1360       nPos = 0;
1361     if (nPos != editor->nScrollPosY) {
1362       ScrollWindow(hWnd, 0, editor->nScrollPosY-nPos, NULL, NULL);
1363       editor->nScrollPosY = nPos;
1364       SetScrollPos(hWnd, SB_VERT, nPos, TRUE);
1365       UpdateWindow(hWnd);
1366     }
1367     break;
1368   }
1369   case WM_SIZE:
1370   {
1371     ME_MarkAllForWrapping(editor);
1372     ME_WrapMarkedParagraphs(editor);
1373     ME_UpdateScrollBar(editor);
1374     ME_Repaint(editor);
1375     return DefWindowProcW(hWnd, msg, wParam, lParam);
1376   }
1377   case EM_GETOLEINTERFACE:
1378   {
1379     LPVOID *ppvObj = (LPVOID*) lParam;
1380     FIXME("EM_GETOLEINTERFACE %p: stub\n", ppvObj);
1381     return CreateIRichEditOle(ppvObj);
1382   }
1383   default:
1384   do_default:
1385     return DefWindowProcW(hWnd, msg, wParam, lParam);
1386   }
1387   return 0L;
1388 }
1389
1390 /******************************************************************
1391  *        RichEdit10ANSIWndProc (RICHED20.9)
1392  */
1393 LRESULT WINAPI RichEdit10ANSIWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1394 {
1395   /* FIXME: this is NOT the same as 2.0 version */
1396   return RichEditANSIWndProc(hWnd, msg, wParam, lParam);
1397 }
1398
1399 void ME_SendOldNotify(ME_TextEditor *editor, int nCode)
1400 {
1401   HWND hWnd = editor->hWnd;
1402   SendMessageA(GetParent(hWnd), WM_COMMAND, (nCode<<16)|GetWindowLongW(hWnd, GWLP_ID), (LPARAM)hWnd);
1403 }
1404
1405 int ME_CountParagraphsBetween(ME_TextEditor *editor, int from, int to)
1406 {
1407   ME_DisplayItem *item = ME_FindItemFwd(editor->pBuffer->pFirst, diParagraph);
1408   int i = 0;
1409   
1410   while(item && item->member.para.next_para->member.para.nCharOfs <= from)
1411     item = item->member.para.next_para;
1412   if (!item)
1413     return 0;
1414   while(item && item->member.para.next_para->member.para.nCharOfs <= to) {
1415     item = item->member.para.next_para;
1416     i++;
1417   }
1418   return i;
1419 }
1420
1421
1422 int ME_GetTextW(ME_TextEditor *editor, WCHAR *buffer, int nStart, int nChars, int bCRLF)
1423 {
1424   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
1425   int nWritten = 0;
1426   
1427   if (!item) {
1428     *buffer = L'\0';
1429     return 0;
1430   }
1431   assert(item);    
1432   
1433   if (nStart)
1434   {
1435     int nLen = ME_StrLen(item->member.run.strText) - nStart;
1436     if (nLen > nChars)
1437       nLen = nChars;
1438     CopyMemory(buffer, item->member.run.strText->szData + nStart, sizeof(WCHAR)*nLen);
1439     nChars -= nLen;
1440     nWritten += nLen;
1441     if (!nChars)
1442       return nWritten;
1443     buffer += nLen;
1444     nStart = 0;
1445     item = ME_FindItemFwd(item, diRun);
1446   }
1447   
1448   while(nChars && item)
1449   {
1450     int nLen = ME_StrLen(item->member.run.strText);
1451     if (nLen > nChars)
1452       nLen = nChars;
1453       
1454     if (item->member.run.nFlags & MERF_ENDPARA)
1455     {
1456       if (bCRLF) {
1457         *buffer++ = '\r';
1458         nWritten++;
1459       }        
1460       *buffer = '\n';
1461       assert(nLen == 1);
1462     }
1463     else      
1464       CopyMemory(buffer, item->member.run.strText->szData, sizeof(WCHAR)*nLen);
1465     nChars -= nLen;
1466     nWritten += nLen;
1467     buffer += nLen;    
1468       
1469     if (!nChars)
1470     {
1471       *buffer = L'\0';
1472       return nWritten;
1473     }
1474     item = ME_FindItemFwd(item, diRun);
1475   }
1476   *buffer = L'\0';
1477   return nWritten;  
1478 }
1479
1480 void ME_RegisterEditorClass(HINSTANCE hInstance)
1481 {
1482   BOOL bResult;
1483   WNDCLASSW wcW;
1484   WNDCLASSA wcA;
1485   
1486   wcW.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1487   wcW.lpfnWndProc = RichEditANSIWndProc;
1488   wcW.cbClsExtra = 0;
1489   wcW.cbWndExtra = 4;
1490   wcW.hInstance = NULL; /* hInstance would register DLL-local class */
1491   wcW.hIcon = NULL;
1492   wcW.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1493   wcW.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1494   wcW.lpszMenuName = NULL;
1495   wcW.lpszClassName = wszClassName;
1496   bResult = RegisterClassW(&wcW);  
1497   assert(bResult);
1498   wcW.lpszClassName = wszClassName50;
1499   bResult = RegisterClassW(&wcW);  
1500   assert(bResult);
1501
1502   wcA.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS;
1503   wcA.lpfnWndProc = RichEditANSIWndProc;
1504   wcA.cbClsExtra = 0;
1505   wcA.cbWndExtra = 4;
1506   wcA.hInstance = NULL; /* hInstance would register DLL-local class */
1507   wcA.hIcon = NULL;
1508   wcA.hCursor = LoadCursorW(NULL, MAKEINTRESOURCEW(IDC_IBEAM));
1509   wcA.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
1510   wcA.lpszMenuName = NULL;
1511   wcA.lpszClassName = "RichEdit20A";
1512   bResult = RegisterClassA(&wcA);  
1513   assert(bResult);
1514   wcA.lpszClassName = "RichEdit50A";
1515   bResult = RegisterClassA(&wcA);  
1516   assert(bResult);
1517 }
1518 /******************************************************************
1519  *        CreateTextServices (RICHED20.4)
1520  *
1521  * FIXME should be ITextHost instead of void*
1522  */
1523 HRESULT WINAPI CreateTextServices(IUnknown *punkOuter, void *pITextHost,
1524     IUnknown **ppUnk)
1525 {
1526   FIXME("stub\n");
1527   /* FIXME should support aggregation */
1528   if (punkOuter)
1529     return CLASS_E_NOAGGREGATION;
1530     
1531   return E_FAIL; /* E_NOTIMPL isn't allowed by MSDN */
1532 }
1533
1534 /******************************************************************
1535  *        REExtendedRegisterClass (RICHED20.8)
1536  *
1537  * FIXME undocumented
1538  */
1539 void WINAPI REExtendedRegisterClass(void)
1540 {
1541   FIXME("stub\n");
1542 }