richedit: Each cell can contain multiple paragraphs in msftedit.
[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   do {
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   } while (nStart < pStream->pos);
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, const ME_DisplayItem *pLastRun)
200 {
201   ME_DisplayItem *item = pFirstRun;
202   ME_FontTableItem *table = pStream->fonttbl;
203   int i;
204   
205   do {
206     CHARFORMAT2W *fmt = &item->member.run.style->fmt;
207     COLORREF crColor;
208
209     if (fmt->dwMask & CFM_FACE) {
210       WCHAR *face = fmt->szFaceName;
211       BYTE bCharSet = (fmt->dwMask & CFM_CHARSET) ? fmt->bCharSet : DEFAULT_CHARSET;
212   
213       for (i = 0; i < pStream->nFontTblLen; i++)
214         if (table[i].bCharSet == bCharSet
215             && (table[i].szFaceName == face || !lstrcmpW(table[i].szFaceName, face)))
216           break;
217       if (i == pStream->nFontTblLen) {
218         table[i].bCharSet = bCharSet;
219         table[i].szFaceName = face;
220         pStream->nFontTblLen++;
221       }
222     }
223     
224     if (fmt->dwMask & CFM_COLOR && !(fmt->dwEffects & CFE_AUTOCOLOR)) {
225       crColor = fmt->crTextColor;
226       for (i = 1; i < pStream->nColorTblLen; i++)
227         if (pStream->colortbl[i] == crColor)
228           break;
229       if (i == pStream->nColorTblLen) {
230         pStream->colortbl[i] = crColor;
231         pStream->nColorTblLen++;
232       }
233     }
234     if (fmt->dwMask & CFM_BACKCOLOR && !(fmt->dwEffects & CFE_AUTOBACKCOLOR)) {
235       crColor = fmt->crBackColor;
236       for (i = 1; i < pStream->nColorTblLen; i++)
237         if (pStream->colortbl[i] == crColor)
238           break;
239       if (i == pStream->nColorTblLen) {
240         pStream->colortbl[i] = crColor;
241         pStream->nColorTblLen++;
242       }
243     }
244
245     if (item == pLastRun)
246       break;
247     item = ME_FindItemFwd(item, diRun);
248   } while (item);
249         
250   if (!ME_StreamOutPrint(pStream, "{\\fonttbl"))
251     return FALSE;
252   
253   for (i = 0; i < pStream->nFontTblLen; i++) {
254     if (table[i].bCharSet != DEFAULT_CHARSET) {
255       if (!ME_StreamOutPrint(pStream, "{\\f%u\\fcharset%u ", i, table[i].bCharSet))
256         return FALSE;
257     } else {
258       if (!ME_StreamOutPrint(pStream, "{\\f%u ", i))
259         return FALSE;
260     }
261     if (!ME_StreamOutRTFText(pStream, table[i].szFaceName, -1))
262       return FALSE;
263     if (!ME_StreamOutPrint(pStream, ";}\r\n"))
264       return FALSE;
265   }
266   if (!ME_StreamOutPrint(pStream, "}"))
267     return FALSE;
268
269   /* Output colors table if not empty */
270   if (pStream->nColorTblLen > 1) {
271     if (!ME_StreamOutPrint(pStream, "{\\colortbl;"))
272       return FALSE;
273     for (i = 1; i < pStream->nColorTblLen; i++) {
274       if (!ME_StreamOutPrint(pStream, "\\red%u\\green%u\\blue%u;",
275                              pStream->colortbl[i] & 0xFF,
276                              (pStream->colortbl[i] >> 8) & 0xFF,
277                              (pStream->colortbl[i] >> 16) & 0xFF))
278         return FALSE;
279     }
280     if (!ME_StreamOutPrint(pStream, "}"))
281       return FALSE;
282   }
283
284   return TRUE;
285 }
286
287 static BOOL
288 ME_StreamOutRTFTableProps(ME_TextEditor *editor, ME_OutStream *pStream,
289                           const ME_DisplayItem *para)
290 {
291   ME_DisplayItem *cell;
292   char props[STREAMOUT_BUFFER_SIZE] = "";
293
294   if (!ME_StreamOutPrint(pStream, "\\trowd"))
295     return FALSE;
296   if (!editor->bEmulateVersion10) { /* v4.1 */
297     assert(para->member.para.nFlags & MEPF_ROWSTART);
298     cell = para->member.para.next_para->member.para.pCell;
299     assert(cell);
300     do {
301       sprintf(props, "\\cellx%d", cell->member.cell.nRightBoundary);
302       if (!ME_StreamOutPrint(pStream, props))
303         return FALSE;
304       cell = cell->member.cell.next_cell;
305     } while (cell->member.cell.next_cell);
306   } else { /* v1.0 - 3.0 */
307     PARAFORMAT2 *pFmt = para->member.para.pFmt;
308     int i;
309
310     assert(!(para->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)));
311     for (i = 0; i < pFmt->cTabCount; i++)
312     {
313       sprintf(props, "\\cellx%d", pFmt->rgxTabs[i] & 0x00FFFFFF);
314       if (!ME_StreamOutPrint(pStream, props))
315         return FALSE;
316     }
317   }
318   props[0] = '\0';
319   return TRUE;
320 }
321
322 static BOOL
323 ME_StreamOutRTFParaProps(ME_TextEditor *editor, ME_OutStream *pStream,
324                          const ME_DisplayItem *para)
325 {
326   PARAFORMAT2 *fmt = para->member.para.pFmt;
327   char props[STREAMOUT_BUFFER_SIZE] = "";
328   int i;
329   
330   /* TODO: Don't emit anything if the last PARAFORMAT2 is inherited */
331   if (!ME_StreamOutPrint(pStream, "\\pard"))
332     return FALSE;
333
334   if (!editor->bEmulateVersion10) { /* v4.1 */
335     if (pStream->nNestingLevel > 0)
336       strcat(props, "\\intbl");
337   } else { /* v1.0 - 3.0 */
338     if (fmt->dwMask & PFM_TABLE && fmt->wEffects & PFE_TABLE)
339       strcat(props, "\\intbl");
340   }
341   
342   /* TODO: PFM_BORDER. M$ does not emit any keywords for these properties, and
343    * when streaming border keywords in, PFM_BORDER is set, but wBorder field is
344    * set very different from the documentation.
345    * (Tested with RichEdit 5.50.25.0601) */
346   
347   if (fmt->dwMask & PFM_ALIGNMENT) {
348     switch (fmt->wAlignment) {
349       case PFA_LEFT:
350         /* Default alignment: not emitted */
351         break;
352       case PFA_RIGHT:
353         strcat(props, "\\qr");
354         break;
355       case PFA_CENTER:
356         strcat(props, "\\qc");
357         break;
358       case PFA_JUSTIFY:
359         strcat(props, "\\qj");
360         break;
361     }
362   }
363   
364   if (fmt->dwMask & PFM_LINESPACING) {
365     /* FIXME: MSDN says that the bLineSpacingRule field is controlled by the
366      * PFM_SPACEAFTER flag. Is that true? I don't believe so. */
367     switch (fmt->bLineSpacingRule) {
368       case 0: /* Single spacing */
369         strcat(props, "\\sl-240\\slmult1");
370         break;
371       case 1: /* 1.5 spacing */
372         strcat(props, "\\sl-360\\slmult1");
373         break;
374       case 2: /* Double spacing */
375         strcat(props, "\\sl-480\\slmult1");
376         break;
377       case 3:
378         sprintf(props + strlen(props), "\\sl%d\\slmult0", fmt->dyLineSpacing);
379         break;
380       case 4:
381         sprintf(props + strlen(props), "\\sl-%d\\slmult0", fmt->dyLineSpacing);
382         break;
383       case 5:
384         sprintf(props + strlen(props), "\\sl-%d\\slmult1", fmt->dyLineSpacing * 240 / 20);
385         break;
386     }
387   }
388
389   if (fmt->dwMask & PFM_DONOTHYPHEN && fmt->wEffects & PFE_DONOTHYPHEN)
390     strcat(props, "\\hyph0");
391   if (fmt->dwMask & PFM_KEEP && fmt->wEffects & PFE_KEEP)
392     strcat(props, "\\keep");
393   if (fmt->dwMask & PFM_KEEPNEXT && fmt->wEffects & PFE_KEEPNEXT)
394     strcat(props, "\\keepn");
395   if (fmt->dwMask & PFM_NOLINENUMBER && fmt->wEffects & PFE_NOLINENUMBER)
396     strcat(props, "\\noline");
397   if (fmt->dwMask & PFM_NOWIDOWCONTROL && fmt->wEffects & PFE_NOWIDOWCONTROL)
398     strcat(props, "\\nowidctlpar");
399   if (fmt->dwMask & PFM_PAGEBREAKBEFORE && fmt->wEffects & PFE_PAGEBREAKBEFORE)
400     strcat(props, "\\pagebb");
401   if (fmt->dwMask & PFM_RTLPARA && fmt->wEffects & PFE_RTLPARA)
402     strcat(props, "\\rtlpar");
403   if (fmt->dwMask & PFM_SIDEBYSIDE && fmt->wEffects & PFE_SIDEBYSIDE)
404     strcat(props, "\\sbys");
405   
406   if (fmt->dwMask & PFM_OFFSET)
407     sprintf(props + strlen(props), "\\li%d", fmt->dxOffset);
408   if (fmt->dwMask & PFM_OFFSETINDENT || fmt->dwMask & PFM_STARTINDENT)
409     sprintf(props + strlen(props), "\\fi%d", fmt->dxStartIndent);
410   if (fmt->dwMask & PFM_RIGHTINDENT)
411     sprintf(props + strlen(props), "\\ri%d", fmt->dxRightIndent);
412   if (fmt->dwMask & PFM_SPACEAFTER)
413     sprintf(props + strlen(props), "\\sa%d", fmt->dySpaceAfter);
414   if (fmt->dwMask & PFM_SPACEBEFORE)
415     sprintf(props + strlen(props), "\\sb%d", fmt->dySpaceBefore);
416   if (fmt->dwMask & PFM_STYLE)
417     sprintf(props + strlen(props), "\\s%d", fmt->sStyle);
418
419   if (fmt->dwMask & PFM_TABSTOPS) {
420     static const char * const leader[6] = { "", "\\tldot", "\\tlhyph", "\\tlul", "\\tlth", "\\tleq" };
421     
422     for (i = 0; i < fmt->cTabCount; i++) {
423       switch ((fmt->rgxTabs[i] >> 24) & 0xF) {
424         case 1:
425           strcat(props, "\\tqc");
426           break;
427         case 2:
428           strcat(props, "\\tqr");
429           break;
430         case 3:
431           strcat(props, "\\tqdec");
432           break;
433         case 4:
434           /* Word bar tab (vertical bar). Handled below */
435           break;
436       }
437       if (fmt->rgxTabs[i] >> 28 <= 5)
438         strcat(props, leader[fmt->rgxTabs[i] >> 28]);
439       sprintf(props+strlen(props), "\\tx%d", fmt->rgxTabs[i]&0x00FFFFFF);
440     }
441   }
442     
443   
444   if (fmt->dwMask & PFM_SHADING) {
445     static const char * const style[16] = { "", "\\bgdkhoriz", "\\bgdkvert", "\\bgdkfdiag",
446                                      "\\bgdkbdiag", "\\bgdkcross", "\\bgdkdcross",
447                                      "\\bghoriz", "\\bgvert", "\\bgfdiag",
448                                      "\\bgbdiag", "\\bgcross", "\\bgdcross",
449                                      "", "", "" };
450     if (fmt->wShadingWeight)
451       sprintf(props + strlen(props), "\\shading%d", fmt->wShadingWeight);
452     if (fmt->wShadingStyle & 0xF)
453       strcat(props, style[fmt->wShadingStyle & 0xF]);
454     sprintf(props + strlen(props), "\\cfpat%d\\cbpat%d",
455             (fmt->wShadingStyle >> 4) & 0xF, (fmt->wShadingStyle >> 8) & 0xF);
456   }
457   
458   if (*props && !ME_StreamOutPrint(pStream, props))
459     return FALSE;
460
461   return TRUE;
462 }
463
464
465 static BOOL
466 ME_StreamOutRTFCharProps(ME_OutStream *pStream, CHARFORMAT2W *fmt)
467 {
468   char props[STREAMOUT_BUFFER_SIZE] = "";
469   int i;
470
471   if (fmt->dwMask & CFM_ALLCAPS && fmt->dwEffects & CFE_ALLCAPS)
472     strcat(props, "\\caps");
473   if (fmt->dwMask & CFM_ANIMATION)
474     sprintf(props + strlen(props), "\\animtext%u", fmt->bAnimation);
475   if (fmt->dwMask & CFM_BACKCOLOR) {
476     if (!(fmt->dwEffects & CFE_AUTOBACKCOLOR)) {
477       for (i = 1; i < pStream->nColorTblLen; i++)
478         if (pStream->colortbl[i] == fmt->crBackColor) {
479           sprintf(props + strlen(props), "\\cb%u", i);
480           break;
481         }
482     }
483   }
484   if (fmt->dwMask & CFM_BOLD && fmt->dwEffects & CFE_BOLD)
485     strcat(props, "\\b");
486   if (fmt->dwMask & CFM_COLOR) {
487     if (!(fmt->dwEffects & CFE_AUTOCOLOR)) {
488       for (i = 1; i < pStream->nColorTblLen; i++)
489         if (pStream->colortbl[i] == fmt->crTextColor) {
490           sprintf(props + strlen(props), "\\cf%u", i);
491           break;
492         }
493     }
494   }
495   /* TODO: CFM_DISABLED */
496   if (fmt->dwMask & CFM_EMBOSS && fmt->dwEffects & CFE_EMBOSS)
497     strcat(props, "\\embo");
498   if (fmt->dwMask & CFM_HIDDEN && fmt->dwEffects & CFE_HIDDEN)
499     strcat(props, "\\v");
500   if (fmt->dwMask & CFM_IMPRINT && fmt->dwEffects & CFE_IMPRINT)
501     strcat(props, "\\impr");
502   if (fmt->dwMask & CFM_ITALIC && fmt->dwEffects & CFE_ITALIC)
503     strcat(props, "\\i");
504   if (fmt->dwMask & CFM_KERNING)
505     sprintf(props + strlen(props), "\\kerning%u", fmt->wKerning);
506   if (fmt->dwMask & CFM_LCID) {
507     /* TODO: handle SFF_PLAINRTF */
508     if (LOWORD(fmt->lcid) == 1024)
509       strcat(props, "\\noproof\\lang1024\\langnp1024\\langfe1024\\langfenp1024");
510     else
511       sprintf(props + strlen(props), "\\lang%u", LOWORD(fmt->lcid));
512   }
513   /* CFM_LINK is not streamed out by M$ */
514   if (fmt->dwMask & CFM_OFFSET) {
515     if (fmt->yOffset >= 0)
516       sprintf(props + strlen(props), "\\up%d", fmt->yOffset);
517     else
518       sprintf(props + strlen(props), "\\dn%d", -fmt->yOffset);
519   }
520   if (fmt->dwMask & CFM_OUTLINE && fmt->dwEffects & CFE_OUTLINE)
521     strcat(props, "\\outl");
522   if (fmt->dwMask & CFM_PROTECTED && fmt->dwEffects & CFE_PROTECTED)
523     strcat(props, "\\protect");
524   /* TODO: CFM_REVISED CFM_REVAUTHOR - probably using rsidtbl? */
525   if (fmt->dwMask & CFM_SHADOW && fmt->dwEffects & CFE_SHADOW)
526     strcat(props, "\\shad");
527   if (fmt->dwMask & CFM_SIZE)
528     sprintf(props + strlen(props), "\\fs%d", fmt->yHeight / 10);
529   if (fmt->dwMask & CFM_SMALLCAPS && fmt->dwEffects & CFE_SMALLCAPS)
530     strcat(props, "\\scaps");
531   if (fmt->dwMask & CFM_SPACING)
532     sprintf(props + strlen(props), "\\expnd%u\\expndtw%u", fmt->sSpacing / 5, fmt->sSpacing);
533   if (fmt->dwMask & CFM_STRIKEOUT && fmt->dwEffects & CFE_STRIKEOUT)
534     strcat(props, "\\strike");
535   if (fmt->dwMask & CFM_STYLE) {
536     sprintf(props + strlen(props), "\\cs%u", fmt->sStyle);
537     /* TODO: emit style contents here */
538   }
539   if (fmt->dwMask & (CFM_SUBSCRIPT | CFM_SUPERSCRIPT)) {
540     if (fmt->dwEffects & CFE_SUBSCRIPT)
541       strcat(props, "\\sub");
542     else if (fmt->dwEffects & CFE_SUPERSCRIPT)
543       strcat(props, "\\super");
544   }
545   if (fmt->dwMask & CFM_UNDERLINE || fmt->dwMask & CFM_UNDERLINETYPE) {
546     if (fmt->dwMask & CFM_UNDERLINETYPE)
547       switch (fmt->bUnderlineType) {
548         case CFU_CF1UNDERLINE:
549         case CFU_UNDERLINE:
550           strcat(props, "\\ul");
551           break;
552         case CFU_UNDERLINEDOTTED:
553           strcat(props, "\\uld");
554           break;
555         case CFU_UNDERLINEDOUBLE:
556           strcat(props, "\\uldb");
557           break;
558         case CFU_UNDERLINEWORD:
559           strcat(props, "\\ulw");
560           break;
561         case CFU_UNDERLINENONE:
562         default:
563           strcat(props, "\\ul0");
564           break;
565       }
566     else if (fmt->dwEffects & CFE_UNDERLINE)
567       strcat(props, "\\ul");
568   }
569   /* FIXME: How to emit CFM_WEIGHT? */
570   
571   if (fmt->dwMask & CFM_FACE || fmt->dwMask & CFM_CHARSET) {
572     WCHAR *szFaceName;
573     
574     if (fmt->dwMask & CFM_FACE)
575       szFaceName = fmt->szFaceName;
576     else
577       szFaceName = pStream->fonttbl[0].szFaceName;
578     for (i = 0; i < pStream->nFontTblLen; i++) {
579       if (szFaceName == pStream->fonttbl[i].szFaceName
580           || !lstrcmpW(szFaceName, pStream->fonttbl[i].szFaceName))
581         if (!(fmt->dwMask & CFM_CHARSET)
582             || fmt->bCharSet == pStream->fonttbl[i].bCharSet)
583           break;
584     }
585     if (i < pStream->nFontTblLen)
586     {
587       if (i != pStream->nDefaultFont)
588         sprintf(props + strlen(props), "\\f%u", i);
589
590       /* In UTF-8 mode, charsets/codepages are not used */
591       if (pStream->nDefaultCodePage != CP_UTF8)
592       {
593         if (pStream->fonttbl[i].bCharSet == DEFAULT_CHARSET)
594           pStream->nCodePage = pStream->nDefaultCodePage;
595         else
596           pStream->nCodePage = RTFCharSetToCodePage(NULL, pStream->fonttbl[i].bCharSet);
597       }
598     }
599   }
600   if (*props)
601     strcat(props, " ");
602   if (!ME_StreamOutPrint(pStream, props))
603     return FALSE;
604   return TRUE;
605 }
606
607
608 static BOOL
609 ME_StreamOutRTFText(ME_OutStream *pStream, const WCHAR *text, LONG nChars)
610 {
611   char buffer[STREAMOUT_BUFFER_SIZE];
612   int pos = 0;
613   int fit, nBytes, i;
614
615   if (nChars == -1)
616     nChars = lstrlenW(text);
617   
618   while (nChars) {
619     /* In UTF-8 mode, font charsets are not used. */
620     if (pStream->nDefaultCodePage == CP_UTF8) {
621       /* 6 is the maximum character length in UTF-8 */
622       fit = min(nChars, STREAMOUT_BUFFER_SIZE / 6);
623       nBytes = WideCharToMultiByte(CP_UTF8, 0, text, fit, buffer,
624                                    STREAMOUT_BUFFER_SIZE, NULL, NULL);
625       nChars -= fit;
626       text += fit;
627       for (i = 0; i < nBytes; i++)
628         if (buffer[i] == '{' || buffer[i] == '}' || buffer[i] == '\\') {
629           if (!ME_StreamOutPrint(pStream, "%.*s\\", i - pos, buffer + pos))
630             return FALSE;
631           pos = i;
632         }
633       if (pos < nBytes)
634         if (!ME_StreamOutMove(pStream, buffer + pos, nBytes - pos))
635           return FALSE;
636       pos = 0;
637     } else if (*text < 128) {
638       if (*text == '{' || *text == '}' || *text == '\\')
639         buffer[pos++] = '\\';
640       buffer[pos++] = (char)(*text++);
641       nChars--;
642     } else {
643       BOOL unknown = FALSE;
644       char letter[3];
645
646       /* FIXME: In the MS docs for WideCharToMultiByte there is a big list of
647        * codepages including CP_SYMBOL for which the last parameter must be set
648        * to NULL for the function to succeed. But in Wine we need to care only
649        * about CP_SYMBOL */
650       nBytes = WideCharToMultiByte(pStream->nCodePage, 0, text, 1,
651                                    letter, 3, NULL,
652                                    (pStream->nCodePage == CP_SYMBOL) ? NULL : &unknown);
653       if (unknown)
654         pos += sprintf(buffer + pos, "\\u%d?", (short)*text);
655       else if ((BYTE)*letter < 128) {
656         if (*letter == '{' || *letter == '}' || *letter == '\\')
657           buffer[pos++] = '\\';
658         buffer[pos++] = *letter;
659       } else {
660          for (i = 0; i < nBytes; i++)
661            pos += sprintf(buffer + pos, "\\'%02x", (BYTE)letter[i]);
662       }
663       text++;
664       nChars--;
665     }
666     if (pos >= STREAMOUT_BUFFER_SIZE - 11) {
667       if (!ME_StreamOutMove(pStream, buffer, pos))
668         return FALSE;
669       pos = 0;
670     }
671   }
672   return ME_StreamOutMove(pStream, buffer, pos);
673 }
674
675
676 static BOOL
677 ME_StreamOutRTF(ME_TextEditor *editor, ME_OutStream *pStream, int nStart, int nChars, int dwFormat)
678 {
679   ME_DisplayItem *p, *pEnd, *pPara;
680   int nOffset, nEndLen; 
681   
682   ME_RunOfsFromCharOfs(editor, nStart, &p, &nOffset);
683   ME_RunOfsFromCharOfs(editor, nStart+nChars, &pEnd, &nEndLen);
684   
685   pPara = ME_GetParagraph(p);
686   
687   if (!ME_StreamOutRTFHeader(pStream, dwFormat))
688     return FALSE;
689
690   if (!ME_StreamOutRTFFontAndColorTbl(pStream, p, pEnd))
691     return FALSE;
692   
693   /* TODO: stylesheet table */
694   
695   /* FIXME: maybe emit something smarter for the generator? */
696   if (!ME_StreamOutPrint(pStream, "{\\*\\generator Wine Riched20 2.0.????;}"))
697     return FALSE;
698
699   /* TODO: information group */
700
701   /* TODO: document formatting properties */
702
703   /* FIXME: We have only one document section */
704
705   /* TODO: section formatting properties */
706
707   if (!ME_StreamOutRTFParaProps(editor, pStream, ME_GetParagraph(p)))
708     return FALSE;
709
710   while(1)
711   {
712     switch(p->type)
713     {
714       case diParagraph:
715         if (!editor->bEmulateVersion10) { /* v4.1 */
716           if (p->member.para.nFlags & MEPF_ROWSTART) {
717             pStream->nNestingLevel++;
718             if (!ME_StreamOutRTFTableProps(editor, pStream, p))
719               return FALSE;
720           } else if (p->member.para.nFlags & MEPF_ROWEND) {
721             pStream->nNestingLevel--;
722             if (!ME_StreamOutPrint(pStream, "\\row \r\n"))
723               return FALSE;
724           } else if (!ME_StreamOutRTFParaProps(editor, pStream, p)) {
725             return FALSE;
726           }
727         } else { /* v1.0 - 3.0 */
728           if (p->member.para.pFmt->dwMask & PFM_TABLE &&
729               p->member.para.pFmt->wEffects & PFE_TABLE)
730           {
731             if (!ME_StreamOutRTFTableProps(editor, pStream, p))
732               return FALSE;
733           }
734           if (!ME_StreamOutRTFParaProps(editor, pStream, p))
735             return FALSE;
736         }
737         pPara = p;
738         break;
739       case diRun:
740         if (p == pEnd && !nEndLen)
741           break;
742         TRACE("flags %xh\n", p->member.run.nFlags);
743         /* TODO: emit embedded objects */
744         if (pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
745           break;
746         if (p->member.run.nFlags & MERF_GRAPHICS) {
747           FIXME("embedded objects are not handled\n");
748         } else if (p->member.run.nFlags & MERF_TAB) {
749           if (editor->bEmulateVersion10 && /* v1.0 - 3.0 */
750               pPara->member.para.pFmt->dwMask & PFM_TABLE &&
751               pPara->member.para.pFmt->wEffects & PFE_TABLE)
752           {
753             if (!ME_StreamOutPrint(pStream, "\\cell "))
754               return FALSE;
755           } else {
756             if (!ME_StreamOutPrint(pStream, "\\tab "))
757               return FALSE;
758           }
759         } else if (p->member.run.nFlags & MERF_ENDCELL) {
760           if (!ME_StreamOutPrint(pStream, "\\cell "))
761             return FALSE;
762           nChars--;
763         } else if (p->member.run.nFlags & MERF_ENDPARA) {
764           if (pPara->member.para.pFmt->dwMask & PFM_TABLE &&
765               pPara->member.para.pFmt->wEffects & PFE_TABLE &&
766               !(pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)))
767           {
768             if (!ME_StreamOutPrint(pStream, "\\row \r\n"))
769               return FALSE;
770           } else {
771             if (!ME_StreamOutPrint(pStream, "\r\n\\par"))
772               return FALSE;
773           }
774           /* Skip as many characters as required by current line break */
775           nChars -= (p->member.run.nCR <= nChars) ? p->member.run.nCR : nChars;
776           nChars -= (p->member.run.nLF <= nChars) ? p->member.run.nLF : nChars;
777         } else if (p->member.run.nFlags & MERF_ENDROW) {
778           if (!ME_StreamOutPrint(pStream, "\\line \r\n"))
779             return FALSE;
780           nChars--;
781         } else {
782           int nEnd;
783           
784           if (!ME_StreamOutPrint(pStream, "{"))
785             return FALSE;
786           TRACE("style %p\n", p->member.run.style);
787           if (!ME_StreamOutRTFCharProps(pStream, &p->member.run.style->fmt))
788             return FALSE;
789         
790           nEnd = (p == pEnd) ? nEndLen : ME_StrLen(p->member.run.strText);
791           if (!ME_StreamOutRTFText(pStream, p->member.run.strText->szData + nOffset, nEnd - nOffset))
792             return FALSE;
793           nOffset = 0;
794           if (!ME_StreamOutPrint(pStream, "}"))
795             return FALSE;
796         }
797         break;
798       default: /* we missed the last item */
799         assert(0);
800     }
801     if (p == pEnd)
802       break;
803     p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
804   }
805   if (!ME_StreamOutPrint(pStream, "}"))
806     return FALSE;
807   return TRUE;
808 }
809
810
811 static BOOL
812 ME_StreamOutText(ME_TextEditor *editor, ME_OutStream *pStream, int nStart, int nChars, DWORD dwFormat)
813 {
814   /* FIXME: use ME_RunOfsFromCharOfs */
815   ME_DisplayItem *item = ME_FindItemAtOffset(editor, diRun, nStart, &nStart);
816   int nLen;
817   UINT nCodePage = CP_ACP;
818   char *buffer = NULL;
819   int nBufLen = 0;
820   BOOL success = TRUE;
821
822   if (!item)
823     return FALSE;
824    
825   if (dwFormat & SF_USECODEPAGE)
826     nCodePage = HIWORD(dwFormat);
827
828   /* TODO: Handle SF_TEXTIZED */
829   
830   while (success && nChars && item) {
831     nLen = ME_StrLen(item->member.run.strText) - nStart;
832     if (nLen > nChars)
833       nLen = nChars;
834
835     if (item->member.run.nFlags & MERF_ENDPARA) {
836       static const WCHAR szEOL[2] = { '\r', '\n' };
837       
838       if (!editor->bEmulateVersion10) {
839         /* richedit 2.0 - all line breaks are \r\n */
840         if (dwFormat & SF_UNICODE)
841           success = ME_StreamOutMove(pStream, (const char *)szEOL, sizeof(szEOL));
842         else
843           success = ME_StreamOutMove(pStream, "\r\n", 2);
844         assert(nLen == 1);
845       } else {
846         int i; int tnLen;
847
848         /* richedit 1.0 - need to honor actual \r and \n amounts */
849         nLen = item->member.run.nCR + item->member.run.nLF;
850         if (nLen > nChars)
851           nLen = nChars;
852         tnLen = nLen;
853
854         i = 0;
855         while (tnLen > 0 && i < item->member.run.nCR) {
856           if (dwFormat & SF_UNICODE)
857             success = ME_StreamOutMove(pStream, (const char *)(&szEOL[0]), sizeof(WCHAR));
858           else
859             success = ME_StreamOutMove(pStream, "\r", 1);
860           tnLen--; i++;
861         }
862         i = 0;
863         while (tnLen > 0 && i < item->member.run.nLF) {
864           if (dwFormat & SF_UNICODE)
865             success = ME_StreamOutMove(pStream, (const char *)(&szEOL[1]), sizeof(WCHAR));
866           else
867             success = ME_StreamOutMove(pStream, "\n", 1);
868           tnLen--; i++;
869         }
870       }
871     } else {
872       if (dwFormat & SF_UNICODE)
873         success = ME_StreamOutMove(pStream, (const char *)(item->member.run.strText->szData + nStart),
874                                    sizeof(WCHAR) * nLen);
875       else {
876         int nSize;
877
878         nSize = WideCharToMultiByte(nCodePage, 0, item->member.run.strText->szData + nStart,
879                                     nLen, NULL, 0, NULL, NULL);
880         if (nSize > nBufLen) {
881           FREE_OBJ(buffer);
882           buffer = ALLOC_N_OBJ(char, nSize);
883           nBufLen = nSize;
884         }
885         WideCharToMultiByte(nCodePage, 0, item->member.run.strText->szData + nStart,
886                             nLen, buffer, nSize, NULL, NULL);
887         success = ME_StreamOutMove(pStream, buffer, nSize);
888       }
889     }
890     
891     nChars -= nLen;
892     nStart = 0;
893     item = ME_FindItemFwd(item, diRun);
894   }
895   
896   FREE_OBJ(buffer);
897   return success;
898 }
899
900
901 LRESULT
902 ME_StreamOutRange(ME_TextEditor *editor, DWORD dwFormat, int nStart, int nTo, EDITSTREAM *stream)
903 {
904   ME_OutStream *pStream = ME_StreamOutInit(editor, stream);
905
906   if (nTo == -1)
907   {
908     nTo = ME_GetTextLength(editor);
909     /* Generate an end-of-paragraph at the end of SCF_ALL RTF output */
910     if (dwFormat & SF_RTF)
911       nTo++;
912   }
913   TRACE("from %d to %d\n", nStart, nTo);
914
915   if (dwFormat & SF_RTF)
916     ME_StreamOutRTF(editor, pStream, nStart, nTo - nStart, dwFormat);
917   else if (dwFormat & SF_TEXT || dwFormat & SF_TEXTIZED)
918     ME_StreamOutText(editor, pStream, nStart, nTo - nStart, dwFormat);
919   if (!pStream->stream->dwError)
920     ME_StreamOutFlush(pStream);
921   return ME_StreamOutFree(pStream);
922 }
923
924 LRESULT
925 ME_StreamOut(ME_TextEditor *editor, DWORD dwFormat, EDITSTREAM *stream)
926 {
927   int nStart, nTo;
928
929   if (dwFormat & SFF_SELECTION)
930     ME_GetSelection(editor, &nStart, &nTo);
931   else {
932     nStart = 0;
933     nTo = -1;
934   }
935   return ME_StreamOutRange(editor, dwFormat, nStart, nTo, stream);
936 }