kernel32: Make event/mutex/semaphore functions hotpatchable.
[wine] / dlls / riched20 / writer.c
1 /*
2  * RichEdit - RTF writer module
3  *
4  * Copyright 2005 by Phil Krylov
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include "editor.h"
25 #include "rtf.h"
26
27 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
28
29
30 static BOOL
31 ME_StreamOutRTFText(ME_OutStream *pStream, const WCHAR *text, LONG nChars);
32
33
34 static ME_OutStream*
35 ME_StreamOutInit(ME_TextEditor *editor, EDITSTREAM *stream)
36 {
37   ME_OutStream *pStream = ALLOC_OBJ(ME_OutStream);
38   pStream->stream = stream;
39   pStream->stream->dwError = 0;
40   pStream->pos = 0;
41   pStream->written = 0;
42   pStream->nFontTblLen = 0;
43   pStream->nColorTblLen = 1;
44   pStream->nNestingLevel = 0;
45   return pStream;
46 }
47
48
49 static BOOL
50 ME_StreamOutFlush(ME_OutStream *pStream)
51 {
52   LONG nStart = 0;
53   LONG nWritten = 0;
54   LONG nRemaining = 0;
55   EDITSTREAM *stream = pStream->stream;
56
57   while (nStart < pStream->pos) {
58     TRACE("sending %u bytes\n", pStream->pos - nStart);
59     /* Some apps seem not to set *pcb unless a problem arises, relying
60       on initial random nWritten value, which is usually >STREAMOUT_BUFFER_SIZE */
61     nRemaining = pStream->pos - nStart;
62     nWritten = 0xDEADBEEF;
63     stream->dwError = stream->pfnCallback(stream->dwCookie, (LPBYTE)pStream->buffer + nStart,
64                                           pStream->pos - nStart, &nWritten);
65     TRACE("error=%u written=%u\n", stream->dwError, nWritten);
66     if (nWritten > (pStream->pos - nStart) || nWritten<0) {
67       FIXME("Invalid returned written size *pcb: 0x%x (%d) instead of %d\n", 
68             (unsigned)nWritten, nWritten, nRemaining);
69       nWritten = nRemaining;
70     }
71     if (nWritten == 0 || stream->dwError)
72       return FALSE;
73     pStream->written += nWritten;
74     nStart += nWritten;
75   }
76   pStream->pos = 0;
77   return TRUE;
78 }
79
80
81 static LONG
82 ME_StreamOutFree(ME_OutStream *pStream)
83 {
84   LONG written = pStream->written;
85   TRACE("total length = %u\n", written);
86
87   FREE_OBJ(pStream);
88   return written;
89 }
90
91
92 static BOOL
93 ME_StreamOutMove(ME_OutStream *pStream, const char *buffer, int len)
94 {
95   while (len) {
96     int space = STREAMOUT_BUFFER_SIZE - pStream->pos;
97     int fit = min(space, len);
98
99     TRACE("%u:%u:%s\n", pStream->pos, fit, debugstr_an(buffer,fit));
100     memmove(pStream->buffer + pStream->pos, buffer, fit);
101     len -= fit;
102     buffer += fit;
103     pStream->pos += fit;
104     if (pStream->pos == STREAMOUT_BUFFER_SIZE) {
105       if (!ME_StreamOutFlush(pStream))
106         return FALSE;
107     }
108   }
109   return TRUE;
110 }
111
112
113 static BOOL
114 ME_StreamOutPrint(ME_OutStream *pStream, const char *format, ...)
115 {
116   char string[STREAMOUT_BUFFER_SIZE]; /* This is going to be enough */
117   int len;
118   va_list valist;
119
120   va_start(valist, format);
121   len = vsnprintf(string, sizeof(string), format, valist);
122   va_end(valist);
123   
124   return ME_StreamOutMove(pStream, string, len);
125 }
126
127
128 static BOOL
129 ME_StreamOutRTFHeader(ME_OutStream *pStream, int dwFormat)
130 {
131   const char *cCharSet = NULL;
132   UINT nCodePage;
133   LANGID language;
134   BOOL success;
135   
136   if (dwFormat & SF_USECODEPAGE) {
137     CPINFOEXW info;
138     
139     switch (HIWORD(dwFormat)) {
140       case CP_ACP:
141         cCharSet = "ansi";
142         nCodePage = GetACP();
143         break;
144       case CP_OEMCP:
145         nCodePage = GetOEMCP();
146         if (nCodePage == 437)
147           cCharSet = "pc";
148         else if (nCodePage == 850)
149           cCharSet = "pca";
150         else
151           cCharSet = "ansi";
152         break;
153       case CP_UTF8:
154         nCodePage = CP_UTF8;
155         break;
156       default:
157         if (HIWORD(dwFormat) == CP_MACCP) {
158           cCharSet = "mac";
159           nCodePage = 10000; /* MacRoman */
160         } else {
161           cCharSet = "ansi";
162           nCodePage = 1252; /* Latin-1 */
163         }
164         if (GetCPInfoExW(HIWORD(dwFormat), 0, &info))
165           nCodePage = info.CodePage;
166     }
167   } else {
168     cCharSet = "ansi";
169     /* TODO: If the original document contained an \ansicpg value, retain it.
170      * Otherwise, M$ richedit emits a codepage number determined from the
171      * charset of the default font here. Anyway, this value is not used by
172      * the reader... */
173     nCodePage = GetACP();
174   }
175   if (nCodePage == CP_UTF8)
176     success = ME_StreamOutPrint(pStream, "{\\urtf");
177   else
178     success = ME_StreamOutPrint(pStream, "{\\rtf1\\%s\\ansicpg%u\\uc1", cCharSet, nCodePage);
179
180   if (!success)
181     return FALSE;
182
183   pStream->nDefaultCodePage = nCodePage;
184   
185   /* FIXME: This should be a document property */
186   /* TODO: handle SFF_PLAINRTF */
187   language = GetUserDefaultLangID(); 
188   if (!ME_StreamOutPrint(pStream, "\\deff0\\deflang%u\\deflangfe%u", language, language))
189     return FALSE;
190
191   /* FIXME: This should be a document property */
192   pStream->nDefaultFont = 0;
193
194   return TRUE;
195 }
196
197
198 static BOOL
199 ME_StreamOutRTFFontAndColorTbl(ME_OutStream *pStream, ME_DisplayItem *pFirstRun,
200                                ME_DisplayItem *pLastRun)
201 {
202   ME_DisplayItem *item = pFirstRun;
203   ME_FontTableItem *table = pStream->fonttbl;
204   unsigned int i;
205   ME_DisplayItem *pLastPara = ME_GetParagraph(pLastRun);
206   ME_DisplayItem *pCell = NULL;
207   
208   do {
209     CHARFORMAT2W *fmt = &item->member.run.style->fmt;
210     COLORREF crColor;
211
212     if (fmt->dwMask & CFM_FACE) {
213       WCHAR *face = fmt->szFaceName;
214       BYTE bCharSet = (fmt->dwMask & CFM_CHARSET) ? fmt->bCharSet : DEFAULT_CHARSET;
215   
216       for (i = 0; i < pStream->nFontTblLen; i++)
217         if (table[i].bCharSet == bCharSet
218             && (table[i].szFaceName == face || !lstrcmpW(table[i].szFaceName, face)))
219           break;
220       if (i == pStream->nFontTblLen && i < STREAMOUT_FONTTBL_SIZE) {
221         table[i].bCharSet = bCharSet;
222         table[i].szFaceName = face;
223         pStream->nFontTblLen++;
224       }
225     }
226     
227     if (fmt->dwMask & CFM_COLOR && !(fmt->dwEffects & CFE_AUTOCOLOR)) {
228       crColor = fmt->crTextColor;
229       for (i = 1; i < pStream->nColorTblLen; i++)
230         if (pStream->colortbl[i] == crColor)
231           break;
232       if (i == pStream->nColorTblLen && i < STREAMOUT_COLORTBL_SIZE) {
233         pStream->colortbl[i] = crColor;
234         pStream->nColorTblLen++;
235       }
236     }
237     if (fmt->dwMask & CFM_BACKCOLOR && !(fmt->dwEffects & CFE_AUTOBACKCOLOR)) {
238       crColor = fmt->crBackColor;
239       for (i = 1; i < pStream->nColorTblLen; i++)
240         if (pStream->colortbl[i] == crColor)
241           break;
242       if (i == pStream->nColorTblLen && i < STREAMOUT_COLORTBL_SIZE) {
243         pStream->colortbl[i] = crColor;
244         pStream->nColorTblLen++;
245       }
246     }
247
248     if (item == pLastRun)
249       break;
250     item = ME_FindItemFwd(item, diRun);
251   } while (item);
252   item = ME_GetParagraph(pFirstRun);
253   do {
254     if ((pCell = item->member.para.pCell))
255     {
256         ME_Border* borders[4] = { &pCell->member.cell.border.top,
257                                   &pCell->member.cell.border.left,
258                                   &pCell->member.cell.border.bottom,
259                                   &pCell->member.cell.border.right };
260         for (i = 0; i < 4; i++)
261         {
262           if (borders[i]->width > 0)
263           {
264             unsigned int j;
265             COLORREF crColor = borders[i]->colorRef;
266             for (j = 1; j < pStream->nColorTblLen; j++)
267               if (pStream->colortbl[j] == crColor)
268                 break;
269             if (j == pStream->nColorTblLen && j < STREAMOUT_COLORTBL_SIZE) {
270               pStream->colortbl[j] = crColor;
271               pStream->nColorTblLen++;
272             }
273           }
274         }
275     }
276     if (item == pLastPara)
277       break;
278     item = item->member.para.next_para;
279   } while (item);
280         
281   if (!ME_StreamOutPrint(pStream, "{\\fonttbl"))
282     return FALSE;
283   
284   for (i = 0; i < pStream->nFontTblLen; i++) {
285     if (table[i].bCharSet != DEFAULT_CHARSET) {
286       if (!ME_StreamOutPrint(pStream, "{\\f%u\\fcharset%u ", i, table[i].bCharSet))
287         return FALSE;
288     } else {
289       if (!ME_StreamOutPrint(pStream, "{\\f%u ", i))
290         return FALSE;
291     }
292     if (!ME_StreamOutRTFText(pStream, table[i].szFaceName, -1))
293       return FALSE;
294     if (!ME_StreamOutPrint(pStream, ";}"))
295       return FALSE;
296   }
297   if (!ME_StreamOutPrint(pStream, "}\r\n"))
298     return FALSE;
299
300   /* Output the color table */
301   if (!ME_StreamOutPrint(pStream, "{\\colortbl;")) return FALSE; /* first entry is auto-color */
302   for (i = 1; i < pStream->nColorTblLen; i++)
303   {
304     if (!ME_StreamOutPrint(pStream, "\\red%u\\green%u\\blue%u;", pStream->colortbl[i] & 0xFF,
305                            (pStream->colortbl[i] >> 8) & 0xFF, (pStream->colortbl[i] >> 16) & 0xFF))
306       return FALSE;
307   }
308   if (!ME_StreamOutPrint(pStream, "}")) return FALSE;
309
310   return TRUE;
311 }
312
313 static BOOL
314 ME_StreamOutRTFTableProps(ME_TextEditor *editor, ME_OutStream *pStream,
315                           ME_DisplayItem *para)
316 {
317   ME_DisplayItem *cell;
318   char props[STREAMOUT_BUFFER_SIZE] = "";
319   int i;
320   const char sideChar[4] = {'t','l','b','r'};
321
322   if (!ME_StreamOutPrint(pStream, "\\trowd"))
323     return FALSE;
324   if (!editor->bEmulateVersion10) { /* v4.1 */
325     PARAFORMAT2 *pFmt = ME_GetTableRowEnd(para)->member.para.pFmt;
326     para = ME_GetTableRowStart(para);
327     cell = para->member.para.next_para->member.para.pCell;
328     assert(cell);
329     if (pFmt->dxOffset)
330       sprintf(props + strlen(props), "\\trgaph%d", pFmt->dxOffset);
331     if (pFmt->dxStartIndent)
332       sprintf(props + strlen(props), "\\trleft%d", pFmt->dxStartIndent);
333     do {
334       ME_Border* borders[4] = { &cell->member.cell.border.top,
335                                 &cell->member.cell.border.left,
336                                 &cell->member.cell.border.bottom,
337                                 &cell->member.cell.border.right };
338       for (i = 0; i < 4; i++)
339       {
340         if (borders[i]->width)
341         {
342           unsigned int j;
343           COLORREF crColor = borders[i]->colorRef;
344           sprintf(props + strlen(props), "\\clbrdr%c", sideChar[i]);
345           sprintf(props + strlen(props), "\\brdrs");
346           sprintf(props + strlen(props), "\\brdrw%d", borders[i]->width);
347           for (j = 1; j < pStream->nColorTblLen; j++) {
348             if (pStream->colortbl[j] == crColor) {
349               sprintf(props + strlen(props), "\\brdrcf%u", j);
350               break;
351             }
352           }
353         }
354       }
355       sprintf(props + strlen(props), "\\cellx%d", cell->member.cell.nRightBoundary);
356       cell = cell->member.cell.next_cell;
357     } while (cell->member.cell.next_cell);
358   } else { /* v1.0 - 3.0 */
359     const ME_Border* borders[4] = { &para->member.para.border.top,
360                                     &para->member.para.border.left,
361                                     &para->member.para.border.bottom,
362                                     &para->member.para.border.right };
363     PARAFORMAT2 *pFmt = para->member.para.pFmt;
364
365     assert(!(para->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)));
366     if (pFmt->dxOffset)
367       sprintf(props + strlen(props), "\\trgaph%d", pFmt->dxOffset);
368     if (pFmt->dxStartIndent)
369       sprintf(props + strlen(props), "\\trleft%d", pFmt->dxStartIndent);
370     for (i = 0; i < 4; i++)
371     {
372       if (borders[i]->width)
373       {
374         unsigned int j;
375         COLORREF crColor = borders[i]->colorRef;
376         sprintf(props + strlen(props), "\\trbrdr%c", sideChar[i]);
377         sprintf(props + strlen(props), "\\brdrs");
378         sprintf(props + strlen(props), "\\brdrw%d", borders[i]->width);
379         for (j = 1; j < pStream->nColorTblLen; j++) {
380           if (pStream->colortbl[j] == crColor) {
381             sprintf(props + strlen(props), "\\brdrcf%u", j);
382             break;
383           }
384         }
385       }
386     }
387     for (i = 0; i < pFmt->cTabCount; i++)
388     {
389       sprintf(props + strlen(props), "\\cellx%d", pFmt->rgxTabs[i] & 0x00FFFFFF);
390     }
391   }
392   if (!ME_StreamOutPrint(pStream, props))
393     return FALSE;
394   props[0] = '\0';
395   return TRUE;
396 }
397
398 static BOOL
399 ME_StreamOutRTFParaProps(ME_TextEditor *editor, ME_OutStream *pStream,
400                          ME_DisplayItem *para)
401 {
402   PARAFORMAT2 *fmt = para->member.para.pFmt;
403   char props[STREAMOUT_BUFFER_SIZE] = "";
404   int i;
405
406   if (!editor->bEmulateVersion10) { /* v4.1 */
407     if (para->member.para.nFlags & MEPF_ROWSTART) {
408       pStream->nNestingLevel++;
409       if (pStream->nNestingLevel == 1) {
410         if (!ME_StreamOutRTFTableProps(editor, pStream, para))
411           return FALSE;
412       }
413       return TRUE;
414     } else if (para->member.para.nFlags & MEPF_ROWEND) {
415       pStream->nNestingLevel--;
416       if (pStream->nNestingLevel >= 1) {
417         if (!ME_StreamOutPrint(pStream, "{\\*\\nesttableprops"))
418           return FALSE;
419         if (!ME_StreamOutRTFTableProps(editor, pStream, para))
420           return FALSE;
421         if (!ME_StreamOutPrint(pStream, "\\nestrow}{\\nonesttables\\par}\r\n"))
422           return FALSE;
423       } else {
424         if (!ME_StreamOutPrint(pStream, "\\row \r\n"))
425           return FALSE;
426       }
427       return TRUE;
428     }
429   } else { /* v1.0 - 3.0 */
430     if (para->member.para.pFmt->dwMask & PFM_TABLE &&
431         para->member.para.pFmt->wEffects & PFE_TABLE)
432     {
433       if (!ME_StreamOutRTFTableProps(editor, pStream, para))
434         return FALSE;
435     }
436   }
437
438   /* TODO: Don't emit anything if the last PARAFORMAT2 is inherited */
439   if (!ME_StreamOutPrint(pStream, "\\pard"))
440     return FALSE;
441
442   if (!editor->bEmulateVersion10) { /* v4.1 */
443     if (pStream->nNestingLevel > 0)
444       strcat(props, "\\intbl");
445     if (pStream->nNestingLevel > 1)
446       sprintf(props + strlen(props), "\\itap%d", pStream->nNestingLevel);
447   } else { /* v1.0 - 3.0 */
448     if (fmt->dwMask & PFM_TABLE && fmt->wEffects & PFE_TABLE)
449       strcat(props, "\\intbl");
450   }
451   
452   /* TODO: PFM_BORDER. M$ does not emit any keywords for these properties, and
453    * when streaming border keywords in, PFM_BORDER is set, but wBorder field is
454    * set very different from the documentation.
455    * (Tested with RichEdit 5.50.25.0601) */
456   
457   if (fmt->dwMask & PFM_ALIGNMENT) {
458     switch (fmt->wAlignment) {
459       case PFA_LEFT:
460         /* Default alignment: not emitted */
461         break;
462       case PFA_RIGHT:
463         strcat(props, "\\qr");
464         break;
465       case PFA_CENTER:
466         strcat(props, "\\qc");
467         break;
468       case PFA_JUSTIFY:
469         strcat(props, "\\qj");
470         break;
471     }
472   }
473   
474   if (fmt->dwMask & PFM_LINESPACING) {
475     /* FIXME: MSDN says that the bLineSpacingRule field is controlled by the
476      * PFM_SPACEAFTER flag. Is that true? I don't believe so. */
477     switch (fmt->bLineSpacingRule) {
478       case 0: /* Single spacing */
479         strcat(props, "\\sl-240\\slmult1");
480         break;
481       case 1: /* 1.5 spacing */
482         strcat(props, "\\sl-360\\slmult1");
483         break;
484       case 2: /* Double spacing */
485         strcat(props, "\\sl-480\\slmult1");
486         break;
487       case 3:
488         sprintf(props + strlen(props), "\\sl%d\\slmult0", fmt->dyLineSpacing);
489         break;
490       case 4:
491         sprintf(props + strlen(props), "\\sl-%d\\slmult0", fmt->dyLineSpacing);
492         break;
493       case 5:
494         sprintf(props + strlen(props), "\\sl-%d\\slmult1", fmt->dyLineSpacing * 240 / 20);
495         break;
496     }
497   }
498
499   if (fmt->dwMask & PFM_DONOTHYPHEN && fmt->wEffects & PFE_DONOTHYPHEN)
500     strcat(props, "\\hyph0");
501   if (fmt->dwMask & PFM_KEEP && fmt->wEffects & PFE_KEEP)
502     strcat(props, "\\keep");
503   if (fmt->dwMask & PFM_KEEPNEXT && fmt->wEffects & PFE_KEEPNEXT)
504     strcat(props, "\\keepn");
505   if (fmt->dwMask & PFM_NOLINENUMBER && fmt->wEffects & PFE_NOLINENUMBER)
506     strcat(props, "\\noline");
507   if (fmt->dwMask & PFM_NOWIDOWCONTROL && fmt->wEffects & PFE_NOWIDOWCONTROL)
508     strcat(props, "\\nowidctlpar");
509   if (fmt->dwMask & PFM_PAGEBREAKBEFORE && fmt->wEffects & PFE_PAGEBREAKBEFORE)
510     strcat(props, "\\pagebb");
511   if (fmt->dwMask & PFM_RTLPARA && fmt->wEffects & PFE_RTLPARA)
512     strcat(props, "\\rtlpar");
513   if (fmt->dwMask & PFM_SIDEBYSIDE && fmt->wEffects & PFE_SIDEBYSIDE)
514     strcat(props, "\\sbys");
515   
516   if (!(editor->bEmulateVersion10 && /* v1.0 - 3.0 */
517         fmt->dwMask & PFM_TABLE && fmt->wEffects & PFE_TABLE))
518   {
519     if (fmt->dwMask & PFM_OFFSET)
520       sprintf(props + strlen(props), "\\li%d", fmt->dxOffset);
521     if (fmt->dwMask & PFM_OFFSETINDENT || fmt->dwMask & PFM_STARTINDENT)
522       sprintf(props + strlen(props), "\\fi%d", fmt->dxStartIndent);
523     if (fmt->dwMask & PFM_RIGHTINDENT)
524       sprintf(props + strlen(props), "\\ri%d", fmt->dxRightIndent);
525     if (fmt->dwMask & PFM_TABSTOPS) {
526       static const char * const leader[6] = { "", "\\tldot", "\\tlhyph", "\\tlul", "\\tlth", "\\tleq" };
527
528       for (i = 0; i < fmt->cTabCount; i++) {
529         switch ((fmt->rgxTabs[i] >> 24) & 0xF) {
530           case 1:
531             strcat(props, "\\tqc");
532             break;
533           case 2:
534             strcat(props, "\\tqr");
535             break;
536           case 3:
537             strcat(props, "\\tqdec");
538             break;
539           case 4:
540             /* Word bar tab (vertical bar). Handled below */
541             break;
542         }
543         if (fmt->rgxTabs[i] >> 28 <= 5)
544           strcat(props, leader[fmt->rgxTabs[i] >> 28]);
545         sprintf(props+strlen(props), "\\tx%d", fmt->rgxTabs[i]&0x00FFFFFF);
546       }
547     }
548   }
549   if (fmt->dwMask & PFM_SPACEAFTER)
550     sprintf(props + strlen(props), "\\sa%d", fmt->dySpaceAfter);
551   if (fmt->dwMask & PFM_SPACEBEFORE)
552     sprintf(props + strlen(props), "\\sb%d", fmt->dySpaceBefore);
553   if (fmt->dwMask & PFM_STYLE)
554     sprintf(props + strlen(props), "\\s%d", fmt->sStyle);
555   
556   if (fmt->dwMask & PFM_SHADING) {
557     static const char * const style[16] = { "", "\\bgdkhoriz", "\\bgdkvert", "\\bgdkfdiag",
558                                      "\\bgdkbdiag", "\\bgdkcross", "\\bgdkdcross",
559                                      "\\bghoriz", "\\bgvert", "\\bgfdiag",
560                                      "\\bgbdiag", "\\bgcross", "\\bgdcross",
561                                      "", "", "" };
562     if (fmt->wShadingWeight)
563       sprintf(props + strlen(props), "\\shading%d", fmt->wShadingWeight);
564     if (fmt->wShadingStyle & 0xF)
565       strcat(props, style[fmt->wShadingStyle & 0xF]);
566     sprintf(props + strlen(props), "\\cfpat%d\\cbpat%d",
567             (fmt->wShadingStyle >> 4) & 0xF, (fmt->wShadingStyle >> 8) & 0xF);
568   }
569   
570   if (*props && !ME_StreamOutPrint(pStream, props))
571     return FALSE;
572
573   return TRUE;
574 }
575
576
577 static BOOL
578 ME_StreamOutRTFCharProps(ME_OutStream *pStream, CHARFORMAT2W *fmt)
579 {
580   char props[STREAMOUT_BUFFER_SIZE] = "";
581   unsigned int i;
582
583   if (fmt->dwMask & CFM_ALLCAPS && fmt->dwEffects & CFE_ALLCAPS)
584     strcat(props, "\\caps");
585   if (fmt->dwMask & CFM_ANIMATION)
586     sprintf(props + strlen(props), "\\animtext%u", fmt->bAnimation);
587   if (fmt->dwMask & CFM_BACKCOLOR) {
588     if (!(fmt->dwEffects & CFE_AUTOBACKCOLOR)) {
589       for (i = 1; i < pStream->nColorTblLen; i++)
590         if (pStream->colortbl[i] == fmt->crBackColor) {
591           sprintf(props + strlen(props), "\\cb%u", i);
592           break;
593         }
594     }
595   }
596   if (fmt->dwMask & CFM_BOLD && fmt->dwEffects & CFE_BOLD)
597     strcat(props, "\\b");
598   if (fmt->dwMask & CFM_COLOR) {
599     if (!(fmt->dwEffects & CFE_AUTOCOLOR)) {
600       for (i = 1; i < pStream->nColorTblLen; i++)
601         if (pStream->colortbl[i] == fmt->crTextColor) {
602           sprintf(props + strlen(props), "\\cf%u", i);
603           break;
604         }
605     }
606   }
607   /* TODO: CFM_DISABLED */
608   if (fmt->dwMask & CFM_EMBOSS && fmt->dwEffects & CFE_EMBOSS)
609     strcat(props, "\\embo");
610   if (fmt->dwMask & CFM_HIDDEN && fmt->dwEffects & CFE_HIDDEN)
611     strcat(props, "\\v");
612   if (fmt->dwMask & CFM_IMPRINT && fmt->dwEffects & CFE_IMPRINT)
613     strcat(props, "\\impr");
614   if (fmt->dwMask & CFM_ITALIC && fmt->dwEffects & CFE_ITALIC)
615     strcat(props, "\\i");
616   if (fmt->dwMask & CFM_KERNING)
617     sprintf(props + strlen(props), "\\kerning%u", fmt->wKerning);
618   if (fmt->dwMask & CFM_LCID) {
619     /* TODO: handle SFF_PLAINRTF */
620     if (LOWORD(fmt->lcid) == 1024)
621       strcat(props, "\\noproof\\lang1024\\langnp1024\\langfe1024\\langfenp1024");
622     else
623       sprintf(props + strlen(props), "\\lang%u", LOWORD(fmt->lcid));
624   }
625   /* CFM_LINK is not streamed out by M$ */
626   if (fmt->dwMask & CFM_OFFSET) {
627     if (fmt->yOffset >= 0)
628       sprintf(props + strlen(props), "\\up%d", fmt->yOffset);
629     else
630       sprintf(props + strlen(props), "\\dn%d", -fmt->yOffset);
631   }
632   if (fmt->dwMask & CFM_OUTLINE && fmt->dwEffects & CFE_OUTLINE)
633     strcat(props, "\\outl");
634   if (fmt->dwMask & CFM_PROTECTED && fmt->dwEffects & CFE_PROTECTED)
635     strcat(props, "\\protect");
636   /* TODO: CFM_REVISED CFM_REVAUTHOR - probably using rsidtbl? */
637   if (fmt->dwMask & CFM_SHADOW && fmt->dwEffects & CFE_SHADOW)
638     strcat(props, "\\shad");
639   if (fmt->dwMask & CFM_SIZE)
640     sprintf(props + strlen(props), "\\fs%d", fmt->yHeight / 10);
641   if (fmt->dwMask & CFM_SMALLCAPS && fmt->dwEffects & CFE_SMALLCAPS)
642     strcat(props, "\\scaps");
643   if (fmt->dwMask & CFM_SPACING)
644     sprintf(props + strlen(props), "\\expnd%u\\expndtw%u", fmt->sSpacing / 5, fmt->sSpacing);
645   if (fmt->dwMask & CFM_STRIKEOUT && fmt->dwEffects & CFE_STRIKEOUT)
646     strcat(props, "\\strike");
647   if (fmt->dwMask & CFM_STYLE) {
648     sprintf(props + strlen(props), "\\cs%u", fmt->sStyle);
649     /* TODO: emit style contents here */
650   }
651   if (fmt->dwMask & (CFM_SUBSCRIPT | CFM_SUPERSCRIPT)) {
652     if (fmt->dwEffects & CFE_SUBSCRIPT)
653       strcat(props, "\\sub");
654     else if (fmt->dwEffects & CFE_SUPERSCRIPT)
655       strcat(props, "\\super");
656   }
657   if (fmt->dwMask & CFM_UNDERLINE || fmt->dwMask & CFM_UNDERLINETYPE) {
658     if (fmt->dwMask & CFM_UNDERLINETYPE)
659       switch (fmt->bUnderlineType) {
660         case CFU_CF1UNDERLINE:
661         case CFU_UNDERLINE:
662           strcat(props, "\\ul");
663           break;
664         case CFU_UNDERLINEDOTTED:
665           strcat(props, "\\uld");
666           break;
667         case CFU_UNDERLINEDOUBLE:
668           strcat(props, "\\uldb");
669           break;
670         case CFU_UNDERLINEWORD:
671           strcat(props, "\\ulw");
672           break;
673         case CFU_UNDERLINENONE:
674         default:
675           strcat(props, "\\ul0");
676           break;
677       }
678     else if (fmt->dwEffects & CFE_UNDERLINE)
679       strcat(props, "\\ul");
680   }
681   /* FIXME: How to emit CFM_WEIGHT? */
682   
683   if (fmt->dwMask & CFM_FACE || fmt->dwMask & CFM_CHARSET) {
684     WCHAR *szFaceName;
685     
686     if (fmt->dwMask & CFM_FACE)
687       szFaceName = fmt->szFaceName;
688     else
689       szFaceName = pStream->fonttbl[0].szFaceName;
690     for (i = 0; i < pStream->nFontTblLen; i++) {
691       if (szFaceName == pStream->fonttbl[i].szFaceName
692           || !lstrcmpW(szFaceName, pStream->fonttbl[i].szFaceName))
693         if (!(fmt->dwMask & CFM_CHARSET)
694             || fmt->bCharSet == pStream->fonttbl[i].bCharSet)
695           break;
696     }
697     if (i < pStream->nFontTblLen)
698     {
699       if (i != pStream->nDefaultFont)
700         sprintf(props + strlen(props), "\\f%u", i);
701
702       /* In UTF-8 mode, charsets/codepages are not used */
703       if (pStream->nDefaultCodePage != CP_UTF8)
704       {
705         if (pStream->fonttbl[i].bCharSet == DEFAULT_CHARSET)
706           pStream->nCodePage = pStream->nDefaultCodePage;
707         else
708           pStream->nCodePage = RTFCharSetToCodePage(NULL, pStream->fonttbl[i].bCharSet);
709       }
710     }
711   }
712   if (*props)
713     strcat(props, " ");
714   if (!ME_StreamOutPrint(pStream, props))
715     return FALSE;
716   return TRUE;
717 }
718
719
720 static BOOL
721 ME_StreamOutRTFText(ME_OutStream *pStream, const WCHAR *text, LONG nChars)
722 {
723   char buffer[STREAMOUT_BUFFER_SIZE];
724   int pos = 0;
725   int fit, nBytes, i;
726
727   if (nChars == -1)
728     nChars = lstrlenW(text);
729   
730   while (nChars) {
731     /* In UTF-8 mode, font charsets are not used. */
732     if (pStream->nDefaultCodePage == CP_UTF8) {
733       /* 6 is the maximum character length in UTF-8 */
734       fit = min(nChars, STREAMOUT_BUFFER_SIZE / 6);
735       nBytes = WideCharToMultiByte(CP_UTF8, 0, text, fit, buffer,
736                                    STREAMOUT_BUFFER_SIZE, NULL, NULL);
737       nChars -= fit;
738       text += fit;
739       for (i = 0; i < nBytes; i++)
740         if (buffer[i] == '{' || buffer[i] == '}' || buffer[i] == '\\') {
741           if (!ME_StreamOutPrint(pStream, "%.*s\\", i - pos, buffer + pos))
742             return FALSE;
743           pos = i;
744         }
745       if (pos < nBytes)
746         if (!ME_StreamOutMove(pStream, buffer + pos, nBytes - pos))
747           return FALSE;
748       pos = 0;
749     } else if (*text < 128) {
750       if (*text == '{' || *text == '}' || *text == '\\')
751         buffer[pos++] = '\\';
752       buffer[pos++] = (char)(*text++);
753       nChars--;
754     } else {
755       BOOL unknown = FALSE;
756       char letter[3];
757
758       /* FIXME: In the MS docs for WideCharToMultiByte there is a big list of
759        * codepages including CP_SYMBOL for which the last parameter must be set
760        * to NULL for the function to succeed. But in Wine we need to care only
761        * about CP_SYMBOL */
762       nBytes = WideCharToMultiByte(pStream->nCodePage, 0, text, 1,
763                                    letter, 3, NULL,
764                                    (pStream->nCodePage == CP_SYMBOL) ? NULL : &unknown);
765       if (unknown)
766         pos += sprintf(buffer + pos, "\\u%d?", (short)*text);
767       else if ((BYTE)*letter < 128) {
768         if (*letter == '{' || *letter == '}' || *letter == '\\')
769           buffer[pos++] = '\\';
770         buffer[pos++] = *letter;
771       } else {
772          for (i = 0; i < nBytes; i++)
773            pos += sprintf(buffer + pos, "\\'%02x", (BYTE)letter[i]);
774       }
775       text++;
776       nChars--;
777     }
778     if (pos >= STREAMOUT_BUFFER_SIZE - 11) {
779       if (!ME_StreamOutMove(pStream, buffer, pos))
780         return FALSE;
781       pos = 0;
782     }
783   }
784   return ME_StreamOutMove(pStream, buffer, pos);
785 }
786
787
788 static BOOL ME_StreamOutRTF(ME_TextEditor *editor, ME_OutStream *pStream,
789                             const ME_Cursor *start, int nChars, int dwFormat)
790 {
791   ME_Cursor cursor = *start;
792   ME_DisplayItem *prev_para = cursor.pPara;
793   ME_Cursor endCur = cursor;
794
795   ME_MoveCursorChars(editor, &endCur, nChars);
796
797   if (!ME_StreamOutRTFHeader(pStream, dwFormat))
798     return FALSE;
799
800   if (!ME_StreamOutRTFFontAndColorTbl(pStream, cursor.pRun, endCur.pRun))
801     return FALSE;
802
803   /* TODO: stylesheet table */
804
805   /* FIXME: maybe emit something smarter for the generator? */
806   if (!ME_StreamOutPrint(pStream, "{\\*\\generator Wine Riched20 2.0.????;}"))
807     return FALSE;
808
809   /* TODO: information group */
810
811   /* TODO: document formatting properties */
812
813   /* FIXME: We have only one document section */
814
815   /* TODO: section formatting properties */
816
817   if (!ME_StreamOutRTFParaProps(editor, pStream, cursor.pPara))
818     return FALSE;
819
820   do {
821     if (cursor.pPara != prev_para)
822     {
823       prev_para = cursor.pPara;
824       if (!ME_StreamOutRTFParaProps(editor, pStream, cursor.pPara))
825         return FALSE;
826     }
827
828     if (cursor.pRun == endCur.pRun && !endCur.nOffset)
829       break;
830     TRACE("flags %xh\n", cursor.pRun->member.run.nFlags);
831     /* TODO: emit embedded objects */
832     if (cursor.pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
833       continue;
834     if (cursor.pRun->member.run.nFlags & MERF_GRAPHICS) {
835       FIXME("embedded objects are not handled\n");
836     } else if (cursor.pRun->member.run.nFlags & MERF_TAB) {
837       if (editor->bEmulateVersion10 && /* v1.0 - 3.0 */
838           cursor.pPara->member.para.pFmt->dwMask & PFM_TABLE &&
839           cursor.pPara->member.para.pFmt->wEffects & PFE_TABLE)
840       {
841         if (!ME_StreamOutPrint(pStream, "\\cell "))
842           return FALSE;
843       } else {
844         if (!ME_StreamOutPrint(pStream, "\\tab "))
845           return FALSE;
846       }
847     } else if (cursor.pRun->member.run.nFlags & MERF_ENDCELL) {
848       if (pStream->nNestingLevel > 1) {
849         if (!ME_StreamOutPrint(pStream, "\\nestcell "))
850           return FALSE;
851       } else {
852         if (!ME_StreamOutPrint(pStream, "\\cell "))
853           return FALSE;
854       }
855       nChars--;
856     } else if (cursor.pRun->member.run.nFlags & MERF_ENDPARA) {
857       if (cursor.pPara->member.para.pFmt->dwMask & PFM_TABLE &&
858           cursor.pPara->member.para.pFmt->wEffects & PFE_TABLE &&
859           !(cursor.pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)))
860       {
861         if (!ME_StreamOutPrint(pStream, "\\row \r\n"))
862           return FALSE;
863       } else {
864         if (!ME_StreamOutPrint(pStream, "\r\n\\par"))
865           return FALSE;
866       }
867       /* Skip as many characters as required by current line break */
868       nChars = max(0, nChars - cursor.pRun->member.run.len);
869     } else if (cursor.pRun->member.run.nFlags & MERF_ENDROW) {
870       if (!ME_StreamOutPrint(pStream, "\\line \r\n"))
871         return FALSE;
872       nChars--;
873     } else {
874       int nEnd;
875
876       if (!ME_StreamOutPrint(pStream, "{"))
877         return FALSE;
878       TRACE("style %p\n", cursor.pRun->member.run.style);
879       if (!ME_StreamOutRTFCharProps(pStream, &cursor.pRun->member.run.style->fmt))
880         return FALSE;
881
882       nEnd = (cursor.pRun == endCur.pRun) ? endCur.nOffset : cursor.pRun->member.run.len;
883       if (!ME_StreamOutRTFText(pStream, get_text( &cursor.pRun->member.run, cursor.nOffset ),
884                                nEnd - cursor.nOffset))
885         return FALSE;
886       cursor.nOffset = 0;
887       if (!ME_StreamOutPrint(pStream, "}"))
888         return FALSE;
889     }
890   } while (cursor.pRun != endCur.pRun && ME_NextRun(&cursor.pPara, &cursor.pRun));
891
892   if (!ME_StreamOutMove(pStream, "}\0", 2))
893     return FALSE;
894   return TRUE;
895 }
896
897
898 static BOOL ME_StreamOutText(ME_TextEditor *editor, ME_OutStream *pStream,
899                              const ME_Cursor *start, int nChars, DWORD dwFormat)
900 {
901   ME_Cursor cursor = *start;
902   int nLen;
903   UINT nCodePage = CP_ACP;
904   char *buffer = NULL;
905   int nBufLen = 0;
906   BOOL success = TRUE;
907
908   if (!cursor.pRun)
909     return FALSE;
910
911   if (dwFormat & SF_USECODEPAGE)
912     nCodePage = HIWORD(dwFormat);
913
914   /* TODO: Handle SF_TEXTIZED */
915
916   while (success && nChars && cursor.pRun) {
917     nLen = min(nChars, cursor.pRun->member.run.len - cursor.nOffset);
918
919     if (!editor->bEmulateVersion10 && cursor.pRun->member.run.nFlags & MERF_ENDPARA)
920     {
921       static const WCHAR szEOL[] = { '\r', '\n' };
922
923       /* richedit 2.0 - all line breaks are \r\n */
924       if (dwFormat & SF_UNICODE)
925         success = ME_StreamOutMove(pStream, (const char *)szEOL, sizeof(szEOL));
926       else
927         success = ME_StreamOutMove(pStream, "\r\n", 2);
928     } else {
929       if (dwFormat & SF_UNICODE)
930         success = ME_StreamOutMove(pStream, (const char *)(get_text( &cursor.pRun->member.run, cursor.nOffset )),
931                                    sizeof(WCHAR) * nLen);
932       else {
933         int nSize;
934
935         nSize = WideCharToMultiByte(nCodePage, 0, get_text( &cursor.pRun->member.run, cursor.nOffset ),
936                                     nLen, NULL, 0, NULL, NULL);
937         if (nSize > nBufLen) {
938           FREE_OBJ(buffer);
939           buffer = ALLOC_N_OBJ(char, nSize);
940           nBufLen = nSize;
941         }
942         WideCharToMultiByte(nCodePage, 0, get_text( &cursor.pRun->member.run, cursor.nOffset ),
943                             nLen, buffer, nSize, NULL, NULL);
944         success = ME_StreamOutMove(pStream, buffer, nSize);
945       }
946     }
947
948     nChars -= nLen;
949     cursor.nOffset = 0;
950     cursor.pRun = ME_FindItemFwd(cursor.pRun, diRun);
951   }
952
953   FREE_OBJ(buffer);
954   return success;
955 }
956
957
958 LRESULT ME_StreamOutRange(ME_TextEditor *editor, DWORD dwFormat,
959                           const ME_Cursor *start,
960                           int nChars, EDITSTREAM *stream)
961 {
962   ME_OutStream *pStream = ME_StreamOutInit(editor, stream);
963
964   if (dwFormat & SF_RTF)
965     ME_StreamOutRTF(editor, pStream, start, nChars, dwFormat);
966   else if (dwFormat & SF_TEXT || dwFormat & SF_TEXTIZED)
967     ME_StreamOutText(editor, pStream, start, nChars, dwFormat);
968   if (!pStream->stream->dwError)
969     ME_StreamOutFlush(pStream);
970   return ME_StreamOutFree(pStream);
971 }
972
973 LRESULT
974 ME_StreamOut(ME_TextEditor *editor, DWORD dwFormat, EDITSTREAM *stream)
975 {
976   ME_Cursor start;
977   int nChars;
978
979   if (dwFormat & SFF_SELECTION) {
980     int nStart, nTo;
981     start = editor->pCursors[ME_GetSelectionOfs(editor, &nStart, &nTo)];
982     nChars = nTo - nStart;
983   } else {
984     ME_SetCursorToStart(editor, &start);
985     nChars = ME_GetTextLength(editor);
986     /* Generate an end-of-paragraph at the end of SCF_ALL RTF output */
987     if (dwFormat & SF_RTF)
988       nChars++;
989   }
990   return ME_StreamOutRange(editor, dwFormat, &start, nChars, stream);
991 }