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