wmvcore/tests: Make test_profile_manager_interfaces() static.
[wine.git] / dlls / riched20 / writer.c
blob1cd293c662b854070e67cd88c5eb27ec953d03f2
1 /*
2 * RichEdit - RTF writer module
4 * Copyright 2005 by Phil Krylov
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.
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.
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
21 #include "config.h"
22 #include "wine/port.h"
24 #define NONAMELESSUNION
26 #include "editor.h"
27 #include "rtf.h"
29 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
31 #define STREAMOUT_BUFFER_SIZE 4096
32 #define STREAMOUT_FONTTBL_SIZE 8192
33 #define STREAMOUT_COLORTBL_SIZE 1024
35 typedef struct tagME_OutStream
37 EDITSTREAM *stream;
38 char buffer[STREAMOUT_BUFFER_SIZE];
39 UINT pos, written;
40 UINT nCodePage;
41 UINT nFontTblLen;
42 ME_FontTableItem fonttbl[STREAMOUT_FONTTBL_SIZE];
43 UINT nColorTblLen;
44 COLORREF colortbl[STREAMOUT_COLORTBL_SIZE];
45 UINT nDefaultFont;
46 UINT nDefaultCodePage;
47 /* nNestingLevel = 0 means we aren't in a cell, 1 means we are in a cell,
48 * an greater numbers mean we are in a cell nested within a cell. */
49 UINT nNestingLevel;
50 CHARFORMAT2W cur_fmt; /* current character format */
51 } ME_OutStream;
53 static BOOL
54 ME_StreamOutRTFText(ME_OutStream *pStream, const WCHAR *text, LONG nChars);
57 static ME_OutStream*
58 ME_StreamOutInit(ME_TextEditor *editor, EDITSTREAM *stream)
60 ME_OutStream *pStream = ALLOC_OBJ(ME_OutStream);
61 pStream->stream = stream;
62 pStream->stream->dwError = 0;
63 pStream->pos = 0;
64 pStream->written = 0;
65 pStream->nFontTblLen = 0;
66 pStream->nColorTblLen = 1;
67 pStream->nNestingLevel = 0;
68 memset(&pStream->cur_fmt, 0, sizeof(pStream->cur_fmt));
69 pStream->cur_fmt.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;
70 pStream->cur_fmt.bUnderlineType = CFU_UNDERLINE;
71 return pStream;
75 static BOOL
76 ME_StreamOutFlush(ME_OutStream *pStream)
78 LONG nWritten = 0;
79 EDITSTREAM *stream = pStream->stream;
81 if (pStream->pos) {
82 TRACE("sending %u bytes\n", pStream->pos);
83 nWritten = pStream->pos;
84 stream->dwError = stream->pfnCallback(stream->dwCookie, (LPBYTE)pStream->buffer,
85 pStream->pos, &nWritten);
86 TRACE("error=%u written=%u\n", stream->dwError, nWritten);
87 if (nWritten == 0 || stream->dwError)
88 return FALSE;
89 /* Don't resend partial chunks if nWritten < pStream->pos */
91 if (nWritten == pStream->pos)
92 pStream->written += nWritten;
93 pStream->pos = 0;
94 return TRUE;
98 static LONG
99 ME_StreamOutFree(ME_OutStream *pStream)
101 LONG written = pStream->written;
102 TRACE("total length = %u\n", written);
104 FREE_OBJ(pStream);
105 return written;
109 static BOOL
110 ME_StreamOutMove(ME_OutStream *pStream, const char *buffer, int len)
112 while (len) {
113 int space = STREAMOUT_BUFFER_SIZE - pStream->pos;
114 int fit = min(space, len);
116 TRACE("%u:%u:%s\n", pStream->pos, fit, debugstr_an(buffer,fit));
117 memmove(pStream->buffer + pStream->pos, buffer, fit);
118 len -= fit;
119 buffer += fit;
120 pStream->pos += fit;
121 if (pStream->pos == STREAMOUT_BUFFER_SIZE) {
122 if (!ME_StreamOutFlush(pStream))
123 return FALSE;
126 return TRUE;
130 static BOOL
131 ME_StreamOutPrint(ME_OutStream *pStream, const char *format, ...)
133 char string[STREAMOUT_BUFFER_SIZE]; /* This is going to be enough */
134 int len;
135 va_list valist;
137 va_start(valist, format);
138 len = vsnprintf(string, sizeof(string), format, valist);
139 va_end(valist);
141 return ME_StreamOutMove(pStream, string, len);
144 #define HEX_BYTES_PER_LINE 40
146 static BOOL
147 ME_StreamOutHexData(ME_OutStream *stream, const BYTE *data, UINT len)
150 char line[HEX_BYTES_PER_LINE * 2 + 1];
151 UINT size, i;
152 static const char hex[] = "0123456789abcdef";
154 while (len)
156 size = min( len, HEX_BYTES_PER_LINE );
157 for (i = 0; i < size; i++)
159 line[i * 2] = hex[(*data >> 4) & 0xf];
160 line[i * 2 + 1] = hex[*data & 0xf];
161 data++;
163 line[size * 2] = '\n';
164 if (!ME_StreamOutMove( stream, line, size * 2 + 1 ))
165 return FALSE;
166 len -= size;
168 return TRUE;
171 static BOOL
172 ME_StreamOutRTFHeader(ME_OutStream *pStream, int dwFormat)
174 const char *cCharSet = NULL;
175 UINT nCodePage;
176 LANGID language;
177 BOOL success;
179 if (dwFormat & SF_USECODEPAGE) {
180 CPINFOEXW info;
182 switch (HIWORD(dwFormat)) {
183 case CP_ACP:
184 cCharSet = "ansi";
185 nCodePage = GetACP();
186 break;
187 case CP_OEMCP:
188 nCodePage = GetOEMCP();
189 if (nCodePage == 437)
190 cCharSet = "pc";
191 else if (nCodePage == 850)
192 cCharSet = "pca";
193 else
194 cCharSet = "ansi";
195 break;
196 case CP_UTF8:
197 nCodePage = CP_UTF8;
198 break;
199 default:
200 if (HIWORD(dwFormat) == CP_MACCP) {
201 cCharSet = "mac";
202 nCodePage = 10000; /* MacRoman */
203 } else {
204 cCharSet = "ansi";
205 nCodePage = 1252; /* Latin-1 */
207 if (GetCPInfoExW(HIWORD(dwFormat), 0, &info))
208 nCodePage = info.CodePage;
210 } else {
211 cCharSet = "ansi";
212 /* TODO: If the original document contained an \ansicpg value, retain it.
213 * Otherwise, M$ richedit emits a codepage number determined from the
214 * charset of the default font here. Anyway, this value is not used by
215 * the reader... */
216 nCodePage = GetACP();
218 if (nCodePage == CP_UTF8)
219 success = ME_StreamOutPrint(pStream, "{\\urtf");
220 else
221 success = ME_StreamOutPrint(pStream, "{\\rtf1\\%s\\ansicpg%u\\uc1", cCharSet, nCodePage);
223 if (!success)
224 return FALSE;
226 pStream->nDefaultCodePage = nCodePage;
228 /* FIXME: This should be a document property */
229 /* TODO: handle SFF_PLAINRTF */
230 language = GetUserDefaultLangID();
231 if (!ME_StreamOutPrint(pStream, "\\deff0\\deflang%u\\deflangfe%u", language, language))
232 return FALSE;
234 /* FIXME: This should be a document property */
235 pStream->nDefaultFont = 0;
237 return TRUE;
240 static void add_font_to_fonttbl( ME_OutStream *stream, ME_Style *style )
242 ME_FontTableItem *table = stream->fonttbl;
243 CHARFORMAT2W *fmt = &style->fmt;
244 WCHAR *face = fmt->szFaceName;
245 BYTE charset = (fmt->dwMask & CFM_CHARSET) ? fmt->bCharSet : DEFAULT_CHARSET;
246 int i;
248 if (fmt->dwMask & CFM_FACE)
250 for (i = 0; i < stream->nFontTblLen; i++)
251 if (table[i].bCharSet == charset
252 && (table[i].szFaceName == face || !lstrcmpW(table[i].szFaceName, face)))
253 break;
255 if (i == stream->nFontTblLen && i < STREAMOUT_FONTTBL_SIZE)
257 table[i].bCharSet = charset;
258 table[i].szFaceName = face;
259 stream->nFontTblLen++;
264 static BOOL find_font_in_fonttbl( ME_OutStream *stream, CHARFORMAT2W *fmt, unsigned int *idx )
266 WCHAR *facename;
267 int i;
269 *idx = 0;
270 if (fmt->dwMask & CFM_FACE)
271 facename = fmt->szFaceName;
272 else
273 facename = stream->fonttbl[0].szFaceName;
274 for (i = 0; i < stream->nFontTblLen; i++)
276 if (facename == stream->fonttbl[i].szFaceName
277 || !lstrcmpW(facename, stream->fonttbl[i].szFaceName))
278 if (!(fmt->dwMask & CFM_CHARSET)
279 || fmt->bCharSet == stream->fonttbl[i].bCharSet)
281 *idx = i;
282 break;
286 return i < stream->nFontTblLen;
289 static void add_color_to_colortbl( ME_OutStream *stream, COLORREF color )
291 int i;
293 for (i = 1; i < stream->nColorTblLen; i++)
294 if (stream->colortbl[i] == color)
295 break;
297 if (i == stream->nColorTblLen && i < STREAMOUT_COLORTBL_SIZE)
299 stream->colortbl[i] = color;
300 stream->nColorTblLen++;
304 static BOOL find_color_in_colortbl( ME_OutStream *stream, COLORREF color, unsigned int *idx )
306 int i;
308 *idx = 0;
309 for (i = 1; i < stream->nColorTblLen; i++)
311 if (stream->colortbl[i] == color)
313 *idx = i;
314 break;
318 return i < stream->nFontTblLen;
321 static BOOL
322 ME_StreamOutRTFFontAndColorTbl(ME_OutStream *pStream, ME_DisplayItem *pFirstRun,
323 ME_DisplayItem *pLastRun)
325 ME_DisplayItem *item = pFirstRun;
326 ME_FontTableItem *table = pStream->fonttbl;
327 unsigned int i;
328 ME_DisplayItem *pCell = NULL;
329 ME_Paragraph *prev_para = NULL;
331 do {
332 CHARFORMAT2W *fmt = &item->member.run.style->fmt;
334 add_font_to_fonttbl( pStream, item->member.run.style );
336 if (fmt->dwMask & CFM_COLOR && !(fmt->dwEffects & CFE_AUTOCOLOR))
337 add_color_to_colortbl( pStream, fmt->crTextColor );
338 if (fmt->dwMask & CFM_BACKCOLOR && !(fmt->dwEffects & CFE_AUTOBACKCOLOR))
339 add_color_to_colortbl( pStream, fmt->crBackColor );
341 if (item->member.run.para != prev_para)
343 /* check for any para numbering text */
344 if (item->member.run.para->fmt.wNumbering)
345 add_font_to_fonttbl( pStream, item->member.run.para->para_num.style );
347 if ((pCell = item->member.para.pCell))
349 ME_Border* borders[4] = { &pCell->member.cell.border.top,
350 &pCell->member.cell.border.left,
351 &pCell->member.cell.border.bottom,
352 &pCell->member.cell.border.right };
353 for (i = 0; i < 4; i++)
354 if (borders[i]->width > 0)
355 add_color_to_colortbl( pStream, borders[i]->colorRef );
358 prev_para = item->member.run.para;
361 if (item == pLastRun)
362 break;
363 item = ME_FindItemFwd(item, diRun);
364 } while (item);
366 if (!ME_StreamOutPrint(pStream, "{\\fonttbl"))
367 return FALSE;
369 for (i = 0; i < pStream->nFontTblLen; i++) {
370 if (table[i].bCharSet != DEFAULT_CHARSET) {
371 if (!ME_StreamOutPrint(pStream, "{\\f%u\\fcharset%u ", i, table[i].bCharSet))
372 return FALSE;
373 } else {
374 if (!ME_StreamOutPrint(pStream, "{\\f%u ", i))
375 return FALSE;
377 if (!ME_StreamOutRTFText(pStream, table[i].szFaceName, -1))
378 return FALSE;
379 if (!ME_StreamOutPrint(pStream, ";}"))
380 return FALSE;
382 if (!ME_StreamOutPrint(pStream, "}\r\n"))
383 return FALSE;
385 /* Output the color table */
386 if (!ME_StreamOutPrint(pStream, "{\\colortbl;")) return FALSE; /* first entry is auto-color */
387 for (i = 1; i < pStream->nColorTblLen; i++)
389 if (!ME_StreamOutPrint(pStream, "\\red%u\\green%u\\blue%u;", pStream->colortbl[i] & 0xFF,
390 (pStream->colortbl[i] >> 8) & 0xFF, (pStream->colortbl[i] >> 16) & 0xFF))
391 return FALSE;
393 if (!ME_StreamOutPrint(pStream, "}\r\n")) return FALSE;
395 return TRUE;
398 static BOOL
399 ME_StreamOutRTFTableProps(ME_TextEditor *editor, ME_OutStream *pStream,
400 ME_DisplayItem *para)
402 ME_DisplayItem *cell;
403 char props[STREAMOUT_BUFFER_SIZE] = "";
404 int i;
405 const char sideChar[4] = {'t','l','b','r'};
407 if (!ME_StreamOutPrint(pStream, "\\trowd"))
408 return FALSE;
409 if (!editor->bEmulateVersion10) { /* v4.1 */
410 PARAFORMAT2 *pFmt = &ME_GetTableRowEnd(para)->member.para.fmt;
411 para = ME_GetTableRowStart(para);
412 cell = para->member.para.next_para->member.para.pCell;
413 assert(cell);
414 if (pFmt->dxOffset)
415 sprintf(props + strlen(props), "\\trgaph%d", pFmt->dxOffset);
416 if (pFmt->dxStartIndent)
417 sprintf(props + strlen(props), "\\trleft%d", pFmt->dxStartIndent);
418 do {
419 ME_Border* borders[4] = { &cell->member.cell.border.top,
420 &cell->member.cell.border.left,
421 &cell->member.cell.border.bottom,
422 &cell->member.cell.border.right };
423 for (i = 0; i < 4; i++)
425 if (borders[i]->width)
427 unsigned int idx;
428 COLORREF crColor = borders[i]->colorRef;
429 sprintf(props + strlen(props), "\\clbrdr%c", sideChar[i]);
430 sprintf(props + strlen(props), "\\brdrs");
431 sprintf(props + strlen(props), "\\brdrw%d", borders[i]->width);
432 if (find_color_in_colortbl( pStream, crColor, &idx ))
433 sprintf(props + strlen(props), "\\brdrcf%u", idx);
436 sprintf(props + strlen(props), "\\cellx%d", cell->member.cell.nRightBoundary);
437 cell = cell->member.cell.next_cell;
438 } while (cell->member.cell.next_cell);
439 } else { /* v1.0 - 3.0 */
440 const ME_Border* borders[4] = { &para->member.para.border.top,
441 &para->member.para.border.left,
442 &para->member.para.border.bottom,
443 &para->member.para.border.right };
444 PARAFORMAT2 *pFmt = &para->member.para.fmt;
446 assert(!(para->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)));
447 if (pFmt->dxOffset)
448 sprintf(props + strlen(props), "\\trgaph%d", pFmt->dxOffset);
449 if (pFmt->dxStartIndent)
450 sprintf(props + strlen(props), "\\trleft%d", pFmt->dxStartIndent);
451 for (i = 0; i < 4; i++)
453 if (borders[i]->width)
455 unsigned int idx;
456 COLORREF crColor = borders[i]->colorRef;
457 sprintf(props + strlen(props), "\\trbrdr%c", sideChar[i]);
458 sprintf(props + strlen(props), "\\brdrs");
459 sprintf(props + strlen(props), "\\brdrw%d", borders[i]->width);
460 if (find_color_in_colortbl( pStream, crColor, &idx ))
461 sprintf(props + strlen(props), "\\brdrcf%u", idx);
464 for (i = 0; i < pFmt->cTabCount; i++)
466 sprintf(props + strlen(props), "\\cellx%d", pFmt->rgxTabs[i] & 0x00FFFFFF);
469 if (!ME_StreamOutPrint(pStream, props))
470 return FALSE;
471 props[0] = '\0';
472 return TRUE;
475 static BOOL stream_out_para_num( ME_OutStream *stream, ME_Paragraph *para, BOOL pn_dest )
477 static const char fmt_label[] = "{\\*\\pn\\pnlvlbody\\pnf%u\\pnindent%d\\pnstart%d%s%s}";
478 static const char fmt_bullet[] = "{\\*\\pn\\pnlvlblt\\pnf%u\\pnindent%d{\\pntxtb\\'b7}}";
479 static const char dec[] = "\\pndec";
480 static const char lcltr[] = "\\pnlcltr";
481 static const char ucltr[] = "\\pnucltr";
482 static const char lcrm[] = "\\pnlcrm";
483 static const char ucrm[] = "\\pnucrm";
484 static const char period[] = "{\\pntxta.}";
485 static const char paren[] = "{\\pntxta)}";
486 static const char parens[] = "{\\pntxtb(}{\\pntxta)}";
487 const char *type, *style = "";
488 unsigned int idx;
490 find_font_in_fonttbl( stream, &para->para_num.style->fmt, &idx );
492 if (!ME_StreamOutPrint( stream, "{\\pntext\\f%u ", idx )) return FALSE;
493 if (!ME_StreamOutRTFText( stream, para->para_num.text->szData, para->para_num.text->nLen ))
494 return FALSE;
495 if (!ME_StreamOutPrint( stream, "\\tab}" )) return FALSE;
497 if (!pn_dest) return TRUE;
499 if (para->fmt.wNumbering == PFN_BULLET)
501 if (!ME_StreamOutPrint( stream, fmt_bullet, idx, para->fmt.wNumberingTab ))
502 return FALSE;
504 else
506 switch (para->fmt.wNumbering)
508 case PFN_ARABIC:
509 default:
510 type = dec;
511 break;
512 case PFN_LCLETTER:
513 type = lcltr;
514 break;
515 case PFN_UCLETTER:
516 type = ucltr;
517 break;
518 case PFN_LCROMAN:
519 type = lcrm;
520 break;
521 case PFN_UCROMAN:
522 type = ucrm;
523 break;
525 switch (para->fmt.wNumberingStyle & 0xf00)
527 case PFNS_PERIOD:
528 style = period;
529 break;
530 case PFNS_PAREN:
531 style = paren;
532 break;
533 case PFNS_PARENS:
534 style = parens;
535 break;
538 if (!ME_StreamOutPrint( stream, fmt_label, idx, para->fmt.wNumberingTab,
539 para->fmt.wNumberingStart, type, style ))
540 return FALSE;
542 return TRUE;
545 static BOOL
546 ME_StreamOutRTFParaProps(ME_TextEditor *editor, ME_OutStream *pStream,
547 ME_DisplayItem *para)
549 PARAFORMAT2 *fmt = &para->member.para.fmt;
550 char props[STREAMOUT_BUFFER_SIZE] = "";
551 int i;
552 ME_Paragraph *prev_para = NULL;
554 if (para->member.para.prev_para->type == diParagraph)
555 prev_para = &para->member.para.prev_para->member.para;
557 if (!editor->bEmulateVersion10) { /* v4.1 */
558 if (para->member.para.nFlags & MEPF_ROWSTART) {
559 pStream->nNestingLevel++;
560 if (pStream->nNestingLevel == 1) {
561 if (!ME_StreamOutRTFTableProps(editor, pStream, para))
562 return FALSE;
564 return TRUE;
565 } else if (para->member.para.nFlags & MEPF_ROWEND) {
566 pStream->nNestingLevel--;
567 if (pStream->nNestingLevel >= 1) {
568 if (!ME_StreamOutPrint(pStream, "{\\*\\nesttableprops"))
569 return FALSE;
570 if (!ME_StreamOutRTFTableProps(editor, pStream, para))
571 return FALSE;
572 if (!ME_StreamOutPrint(pStream, "\\nestrow}{\\nonesttables\\par}\r\n"))
573 return FALSE;
574 } else {
575 if (!ME_StreamOutPrint(pStream, "\\row\r\n"))
576 return FALSE;
578 return TRUE;
580 } else { /* v1.0 - 3.0 */
581 if (para->member.para.fmt.dwMask & PFM_TABLE &&
582 para->member.para.fmt.wEffects & PFE_TABLE)
584 if (!ME_StreamOutRTFTableProps(editor, pStream, para))
585 return FALSE;
589 if (prev_para && !memcmp( fmt, &prev_para->fmt, sizeof(*fmt) ))
591 if (fmt->wNumbering)
592 return stream_out_para_num( pStream, &para->member.para, FALSE );
593 return TRUE;
596 if (!ME_StreamOutPrint(pStream, "\\pard"))
597 return FALSE;
599 if (fmt->wNumbering)
600 if (!stream_out_para_num( pStream, &para->member.para, TRUE )) return FALSE;
602 if (!editor->bEmulateVersion10) { /* v4.1 */
603 if (pStream->nNestingLevel > 0)
604 strcat(props, "\\intbl");
605 if (pStream->nNestingLevel > 1)
606 sprintf(props + strlen(props), "\\itap%d", pStream->nNestingLevel);
607 } else { /* v1.0 - 3.0 */
608 if (fmt->dwMask & PFM_TABLE && fmt->wEffects & PFE_TABLE)
609 strcat(props, "\\intbl");
612 /* TODO: PFM_BORDER. M$ does not emit any keywords for these properties, and
613 * when streaming border keywords in, PFM_BORDER is set, but wBorder field is
614 * set very different from the documentation.
615 * (Tested with RichEdit 5.50.25.0601) */
617 if (fmt->dwMask & PFM_ALIGNMENT) {
618 switch (fmt->wAlignment) {
619 case PFA_LEFT:
620 /* Default alignment: not emitted */
621 break;
622 case PFA_RIGHT:
623 strcat(props, "\\qr");
624 break;
625 case PFA_CENTER:
626 strcat(props, "\\qc");
627 break;
628 case PFA_JUSTIFY:
629 strcat(props, "\\qj");
630 break;
634 if (fmt->dwMask & PFM_LINESPACING) {
635 /* FIXME: MSDN says that the bLineSpacingRule field is controlled by the
636 * PFM_SPACEAFTER flag. Is that true? I don't believe so. */
637 switch (fmt->bLineSpacingRule) {
638 case 0: /* Single spacing */
639 strcat(props, "\\sl-240\\slmult1");
640 break;
641 case 1: /* 1.5 spacing */
642 strcat(props, "\\sl-360\\slmult1");
643 break;
644 case 2: /* Double spacing */
645 strcat(props, "\\sl-480\\slmult1");
646 break;
647 case 3:
648 sprintf(props + strlen(props), "\\sl%d\\slmult0", fmt->dyLineSpacing);
649 break;
650 case 4:
651 sprintf(props + strlen(props), "\\sl-%d\\slmult0", fmt->dyLineSpacing);
652 break;
653 case 5:
654 sprintf(props + strlen(props), "\\sl-%d\\slmult1", fmt->dyLineSpacing * 240 / 20);
655 break;
659 if (fmt->dwMask & PFM_DONOTHYPHEN && fmt->wEffects & PFE_DONOTHYPHEN)
660 strcat(props, "\\hyph0");
661 if (fmt->dwMask & PFM_KEEP && fmt->wEffects & PFE_KEEP)
662 strcat(props, "\\keep");
663 if (fmt->dwMask & PFM_KEEPNEXT && fmt->wEffects & PFE_KEEPNEXT)
664 strcat(props, "\\keepn");
665 if (fmt->dwMask & PFM_NOLINENUMBER && fmt->wEffects & PFE_NOLINENUMBER)
666 strcat(props, "\\noline");
667 if (fmt->dwMask & PFM_NOWIDOWCONTROL && fmt->wEffects & PFE_NOWIDOWCONTROL)
668 strcat(props, "\\nowidctlpar");
669 if (fmt->dwMask & PFM_PAGEBREAKBEFORE && fmt->wEffects & PFE_PAGEBREAKBEFORE)
670 strcat(props, "\\pagebb");
671 if (fmt->dwMask & PFM_RTLPARA && fmt->wEffects & PFE_RTLPARA)
672 strcat(props, "\\rtlpar");
673 if (fmt->dwMask & PFM_SIDEBYSIDE && fmt->wEffects & PFE_SIDEBYSIDE)
674 strcat(props, "\\sbys");
676 if (!(editor->bEmulateVersion10 && /* v1.0 - 3.0 */
677 fmt->dwMask & PFM_TABLE && fmt->wEffects & PFE_TABLE))
679 if (fmt->dxOffset)
680 sprintf(props + strlen(props), "\\li%d", fmt->dxOffset);
681 if (fmt->dxStartIndent)
682 sprintf(props + strlen(props), "\\fi%d", fmt->dxStartIndent);
683 if (fmt->dxRightIndent)
684 sprintf(props + strlen(props), "\\ri%d", fmt->dxRightIndent);
685 if (fmt->dwMask & PFM_TABSTOPS) {
686 static const char * const leader[6] = { "", "\\tldot", "\\tlhyph", "\\tlul", "\\tlth", "\\tleq" };
688 for (i = 0; i < fmt->cTabCount; i++) {
689 switch ((fmt->rgxTabs[i] >> 24) & 0xF) {
690 case 1:
691 strcat(props, "\\tqc");
692 break;
693 case 2:
694 strcat(props, "\\tqr");
695 break;
696 case 3:
697 strcat(props, "\\tqdec");
698 break;
699 case 4:
700 /* Word bar tab (vertical bar). Handled below */
701 break;
703 if (fmt->rgxTabs[i] >> 28 <= 5)
704 strcat(props, leader[fmt->rgxTabs[i] >> 28]);
705 sprintf(props+strlen(props), "\\tx%d", fmt->rgxTabs[i]&0x00FFFFFF);
709 if (fmt->dySpaceAfter)
710 sprintf(props + strlen(props), "\\sa%d", fmt->dySpaceAfter);
711 if (fmt->dySpaceBefore)
712 sprintf(props + strlen(props), "\\sb%d", fmt->dySpaceBefore);
713 if (fmt->sStyle != -1)
714 sprintf(props + strlen(props), "\\s%d", fmt->sStyle);
716 if (fmt->dwMask & PFM_SHADING) {
717 static const char * const style[16] = { "", "\\bgdkhoriz", "\\bgdkvert", "\\bgdkfdiag",
718 "\\bgdkbdiag", "\\bgdkcross", "\\bgdkdcross",
719 "\\bghoriz", "\\bgvert", "\\bgfdiag",
720 "\\bgbdiag", "\\bgcross", "\\bgdcross",
721 "", "", "" };
722 if (fmt->wShadingWeight)
723 sprintf(props + strlen(props), "\\shading%d", fmt->wShadingWeight);
724 if (fmt->wShadingStyle & 0xF)
725 strcat(props, style[fmt->wShadingStyle & 0xF]);
726 if ((fmt->wShadingStyle >> 4) & 0xf)
727 sprintf(props + strlen(props), "\\cfpat%d", (fmt->wShadingStyle >> 4) & 0xf);
728 if ((fmt->wShadingStyle >> 8) & 0xf)
729 sprintf(props + strlen(props), "\\cbpat%d", (fmt->wShadingStyle >> 8) & 0xf);
731 if (*props)
732 strcat(props, " ");
734 if (*props && !ME_StreamOutPrint(pStream, props))
735 return FALSE;
737 return TRUE;
741 static BOOL
742 ME_StreamOutRTFCharProps(ME_OutStream *pStream, CHARFORMAT2W *fmt)
744 char props[STREAMOUT_BUFFER_SIZE] = "";
745 unsigned int i;
746 CHARFORMAT2W *old_fmt = &pStream->cur_fmt;
747 static const struct
749 DWORD effect;
750 const char *on, *off;
751 } effects[] =
753 { CFE_ALLCAPS, "\\caps", "\\caps0" },
754 { CFE_BOLD, "\\b", "\\b0" },
755 { CFE_DISABLED, "\\disabled", "\\disabled0" },
756 { CFE_EMBOSS, "\\embo", "\\embo0" },
757 { CFE_HIDDEN, "\\v", "\\v0" },
758 { CFE_IMPRINT, "\\impr", "\\impr0" },
759 { CFE_ITALIC, "\\i", "\\i0" },
760 { CFE_OUTLINE, "\\outl", "\\outl0" },
761 { CFE_PROTECTED, "\\protect", "\\protect0" },
762 { CFE_SHADOW, "\\shad", "\\shad0" },
763 { CFE_SMALLCAPS, "\\scaps", "\\scaps0" },
764 { CFE_STRIKEOUT, "\\strike", "\\strike0" },
767 for (i = 0; i < sizeof(effects) / sizeof(effects[0]); i++)
769 if ((old_fmt->dwEffects ^ fmt->dwEffects) & effects[i].effect)
770 strcat( props, fmt->dwEffects & effects[i].effect ? effects[i].on : effects[i].off );
773 if ((old_fmt->dwEffects ^ fmt->dwEffects) & CFE_AUTOBACKCOLOR ||
774 (!(fmt->dwEffects & CFE_AUTOBACKCOLOR) && old_fmt->crBackColor != fmt->crBackColor))
776 if (fmt->dwEffects & CFE_AUTOBACKCOLOR) i = 0;
777 else find_color_in_colortbl( pStream, fmt->crBackColor, &i );
778 sprintf(props + strlen(props), "\\cb%u", i);
780 if ((old_fmt->dwEffects ^ fmt->dwEffects) & CFE_AUTOCOLOR ||
781 (!(fmt->dwEffects & CFE_AUTOCOLOR) && old_fmt->crTextColor != fmt->crTextColor))
783 if (fmt->dwEffects & CFE_AUTOCOLOR) i = 0;
784 else find_color_in_colortbl( pStream, fmt->crTextColor, &i );
785 sprintf(props + strlen(props), "\\cf%u", i);
788 if (old_fmt->bAnimation != fmt->bAnimation)
789 sprintf(props + strlen(props), "\\animtext%u", fmt->bAnimation);
790 if (old_fmt->wKerning != fmt->wKerning)
791 sprintf(props + strlen(props), "\\kerning%u", fmt->wKerning);
793 if (old_fmt->lcid != fmt->lcid)
795 /* TODO: handle SFF_PLAINRTF */
796 if (LOWORD(fmt->lcid) == 1024)
797 strcat(props, "\\noproof\\lang1024\\langnp1024\\langfe1024\\langfenp1024");
798 else
799 sprintf(props + strlen(props), "\\lang%u", LOWORD(fmt->lcid));
802 if (old_fmt->yOffset != fmt->yOffset)
804 if (fmt->yOffset >= 0)
805 sprintf(props + strlen(props), "\\up%d", fmt->yOffset);
806 else
807 sprintf(props + strlen(props), "\\dn%d", -fmt->yOffset);
809 if (old_fmt->yHeight != fmt->yHeight)
810 sprintf(props + strlen(props), "\\fs%d", fmt->yHeight / 10);
811 if (old_fmt->sSpacing != fmt->sSpacing)
812 sprintf(props + strlen(props), "\\expnd%u\\expndtw%u", fmt->sSpacing / 5, fmt->sSpacing);
813 if ((old_fmt->dwEffects ^ fmt->dwEffects) & (CFM_SUBSCRIPT | CFM_SUPERSCRIPT))
815 if (fmt->dwEffects & CFE_SUBSCRIPT)
816 strcat(props, "\\sub");
817 else if (fmt->dwEffects & CFE_SUPERSCRIPT)
818 strcat(props, "\\super");
819 else
820 strcat(props, "\\nosupersub");
822 if ((old_fmt->dwEffects ^ fmt->dwEffects) & CFE_UNDERLINE ||
823 old_fmt->bUnderlineType != fmt->bUnderlineType)
825 BYTE type = (fmt->dwEffects & CFE_UNDERLINE) ? fmt->bUnderlineType : CFU_UNDERLINENONE;
826 switch (type)
828 case CFU_UNDERLINE:
829 strcat(props, "\\ul");
830 break;
831 case CFU_UNDERLINEDOTTED:
832 strcat(props, "\\uld");
833 break;
834 case CFU_UNDERLINEDOUBLE:
835 strcat(props, "\\uldb");
836 break;
837 case CFU_UNDERLINEWORD:
838 strcat(props, "\\ulw");
839 break;
840 case CFU_CF1UNDERLINE:
841 case CFU_UNDERLINENONE:
842 default:
843 strcat(props, "\\ulnone");
844 break;
848 if (strcmpW(old_fmt->szFaceName, fmt->szFaceName) ||
849 old_fmt->bCharSet != fmt->bCharSet)
851 if (find_font_in_fonttbl( pStream, fmt, &i ))
853 sprintf(props + strlen(props), "\\f%u", i);
855 /* In UTF-8 mode, charsets/codepages are not used */
856 if (pStream->nDefaultCodePage != CP_UTF8)
858 if (pStream->fonttbl[i].bCharSet == DEFAULT_CHARSET)
859 pStream->nCodePage = pStream->nDefaultCodePage;
860 else
861 pStream->nCodePage = RTFCharSetToCodePage(NULL, pStream->fonttbl[i].bCharSet);
865 if (*props)
866 strcat(props, " ");
867 if (!ME_StreamOutPrint(pStream, props))
868 return FALSE;
869 *old_fmt = *fmt;
870 return TRUE;
874 static BOOL
875 ME_StreamOutRTFText(ME_OutStream *pStream, const WCHAR *text, LONG nChars)
877 char buffer[STREAMOUT_BUFFER_SIZE];
878 int pos = 0;
879 int fit, nBytes, i;
881 if (nChars == -1)
882 nChars = lstrlenW(text);
884 while (nChars) {
885 /* In UTF-8 mode, font charsets are not used. */
886 if (pStream->nDefaultCodePage == CP_UTF8) {
887 /* 6 is the maximum character length in UTF-8 */
888 fit = min(nChars, STREAMOUT_BUFFER_SIZE / 6);
889 nBytes = WideCharToMultiByte(CP_UTF8, 0, text, fit, buffer,
890 STREAMOUT_BUFFER_SIZE, NULL, NULL);
891 nChars -= fit;
892 text += fit;
893 for (i = 0; i < nBytes; i++)
894 if (buffer[i] == '{' || buffer[i] == '}' || buffer[i] == '\\') {
895 if (!ME_StreamOutPrint(pStream, "%.*s\\", i - pos, buffer + pos))
896 return FALSE;
897 pos = i;
899 if (pos < nBytes)
900 if (!ME_StreamOutMove(pStream, buffer + pos, nBytes - pos))
901 return FALSE;
902 pos = 0;
903 } else if (*text < 128) {
904 if (*text == '{' || *text == '}' || *text == '\\')
905 buffer[pos++] = '\\';
906 buffer[pos++] = (char)(*text++);
907 nChars--;
908 } else {
909 BOOL unknown = FALSE;
910 char letter[3];
912 /* FIXME: In the MS docs for WideCharToMultiByte there is a big list of
913 * codepages including CP_SYMBOL for which the last parameter must be set
914 * to NULL for the function to succeed. But in Wine we need to care only
915 * about CP_SYMBOL */
916 nBytes = WideCharToMultiByte(pStream->nCodePage, 0, text, 1,
917 letter, 3, NULL,
918 (pStream->nCodePage == CP_SYMBOL) ? NULL : &unknown);
919 if (unknown)
920 pos += sprintf(buffer + pos, "\\u%d?", (short)*text);
921 else if ((BYTE)*letter < 128) {
922 if (*letter == '{' || *letter == '}' || *letter == '\\')
923 buffer[pos++] = '\\';
924 buffer[pos++] = *letter;
925 } else {
926 for (i = 0; i < nBytes; i++)
927 pos += sprintf(buffer + pos, "\\'%02x", (BYTE)letter[i]);
929 text++;
930 nChars--;
932 if (pos >= STREAMOUT_BUFFER_SIZE - 11) {
933 if (!ME_StreamOutMove(pStream, buffer, pos))
934 return FALSE;
935 pos = 0;
938 return ME_StreamOutMove(pStream, buffer, pos);
941 static BOOL stream_out_graphics( ME_TextEditor *editor, ME_OutStream *stream,
942 ME_Run *run )
944 IDataObject *data;
945 HRESULT hr;
946 FORMATETC fmt = { CF_ENHMETAFILE, NULL, DVASPECT_CONTENT, -1, TYMED_ENHMF };
947 STGMEDIUM med = { TYMED_NULL };
948 BOOL ret = FALSE;
949 ENHMETAHEADER *emf_bits = NULL;
950 UINT size;
951 SIZE goal, pic;
952 ME_Context c;
954 hr = IOleObject_QueryInterface( run->ole_obj->poleobj, &IID_IDataObject, (void **)&data );
955 if (FAILED(hr)) return FALSE;
957 ME_InitContext( &c, editor, ITextHost_TxGetDC( editor->texthost ) );
958 hr = IDataObject_QueryGetData( data, &fmt );
959 if (hr != S_OK) goto done;
961 hr = IDataObject_GetData( data, &fmt, &med );
962 if (FAILED(hr)) goto done;
963 if (med.tymed != TYMED_ENHMF) goto done;
965 size = GetEnhMetaFileBits( med.u.hEnhMetaFile, 0, NULL );
966 if (size < FIELD_OFFSET(ENHMETAHEADER, cbPixelFormat)) goto done;
968 emf_bits = HeapAlloc( GetProcessHeap(), 0, size );
969 if (!emf_bits) goto done;
971 size = GetEnhMetaFileBits( med.u.hEnhMetaFile, size, (BYTE *)emf_bits );
972 if (size < FIELD_OFFSET(ENHMETAHEADER, cbPixelFormat)) goto done;
974 /* size_in_pixels = (frame_size / 100) * szlDevice / szlMillimeters
975 pic = size_in_pixels * 2540 / dpi */
976 pic.cx = MulDiv( emf_bits->rclFrame.right - emf_bits->rclFrame.left, emf_bits->szlDevice.cx * 254,
977 emf_bits->szlMillimeters.cx * c.dpi.cx * 10 );
978 pic.cy = MulDiv( emf_bits->rclFrame.bottom - emf_bits->rclFrame.top, emf_bits->szlDevice.cy * 254,
979 emf_bits->szlMillimeters.cy * c.dpi.cy * 10 );
981 /* convert goal size to twips */
982 goal.cx = MulDiv( run->ole_obj->sizel.cx, 144, 254 );
983 goal.cy = MulDiv( run->ole_obj->sizel.cy, 144, 254 );
985 if (!ME_StreamOutPrint( stream, "{\\*\\shppict{\\pict\\emfblip\\picw%d\\pich%d\\picwgoal%d\\pichgoal%d\n",
986 pic.cx, pic.cy, goal.cx, goal.cy ))
987 goto done;
989 if (!ME_StreamOutHexData( stream, (BYTE *)emf_bits, size ))
990 goto done;
992 if (!ME_StreamOutPrint( stream, "}}\n" ))
993 goto done;
995 ret = TRUE;
997 done:
998 ME_DestroyContext( &c );
999 HeapFree( GetProcessHeap(), 0, emf_bits );
1000 ReleaseStgMedium( &med );
1001 IDataObject_Release( data );
1002 return ret;
1005 static BOOL ME_StreamOutRTF(ME_TextEditor *editor, ME_OutStream *pStream,
1006 const ME_Cursor *start, int nChars, int dwFormat)
1008 ME_Cursor cursor = *start;
1009 ME_DisplayItem *prev_para = NULL;
1010 ME_Cursor endCur = cursor;
1012 ME_MoveCursorChars(editor, &endCur, nChars, TRUE);
1014 if (!ME_StreamOutRTFHeader(pStream, dwFormat))
1015 return FALSE;
1017 if (!ME_StreamOutRTFFontAndColorTbl(pStream, cursor.pRun, endCur.pRun))
1018 return FALSE;
1020 /* TODO: stylesheet table */
1022 if (!ME_StreamOutPrint(pStream, "{\\*\\generator Wine Riched20 2.0;}\r\n"))
1023 return FALSE;
1025 /* TODO: information group */
1027 /* TODO: document formatting properties */
1029 /* FIXME: We have only one document section */
1031 /* TODO: section formatting properties */
1033 do {
1034 if (cursor.pPara != prev_para)
1036 prev_para = cursor.pPara;
1037 if (!ME_StreamOutRTFParaProps(editor, pStream, cursor.pPara))
1038 return FALSE;
1041 if (cursor.pRun == endCur.pRun && !endCur.nOffset)
1042 break;
1043 TRACE("flags %xh\n", cursor.pRun->member.run.nFlags);
1044 /* TODO: emit embedded objects */
1045 if (cursor.pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND))
1046 continue;
1047 if (cursor.pRun->member.run.nFlags & MERF_GRAPHICS) {
1048 if (!stream_out_graphics(editor, pStream, &cursor.pRun->member.run))
1049 return FALSE;
1050 } else if (cursor.pRun->member.run.nFlags & MERF_TAB) {
1051 if (editor->bEmulateVersion10 && /* v1.0 - 3.0 */
1052 cursor.pPara->member.para.fmt.dwMask & PFM_TABLE &&
1053 cursor.pPara->member.para.fmt.wEffects & PFE_TABLE)
1055 if (!ME_StreamOutPrint(pStream, "\\cell "))
1056 return FALSE;
1057 } else {
1058 if (!ME_StreamOutPrint(pStream, "\\tab "))
1059 return FALSE;
1061 } else if (cursor.pRun->member.run.nFlags & MERF_ENDCELL) {
1062 if (pStream->nNestingLevel > 1) {
1063 if (!ME_StreamOutPrint(pStream, "\\nestcell "))
1064 return FALSE;
1065 } else {
1066 if (!ME_StreamOutPrint(pStream, "\\cell "))
1067 return FALSE;
1069 nChars--;
1070 } else if (cursor.pRun->member.run.nFlags & MERF_ENDPARA) {
1071 if (!ME_StreamOutRTFCharProps(pStream, &cursor.pRun->member.run.style->fmt))
1072 return FALSE;
1074 if (cursor.pPara->member.para.fmt.dwMask & PFM_TABLE &&
1075 cursor.pPara->member.para.fmt.wEffects & PFE_TABLE &&
1076 !(cursor.pPara->member.para.nFlags & (MEPF_ROWSTART|MEPF_ROWEND|MEPF_CELL)))
1078 if (!ME_StreamOutPrint(pStream, "\\row\r\n"))
1079 return FALSE;
1080 } else {
1081 if (!ME_StreamOutPrint(pStream, "\\par\r\n"))
1082 return FALSE;
1084 /* Skip as many characters as required by current line break */
1085 nChars = max(0, nChars - cursor.pRun->member.run.len);
1086 } else if (cursor.pRun->member.run.nFlags & MERF_ENDROW) {
1087 if (!ME_StreamOutPrint(pStream, "\\line\r\n"))
1088 return FALSE;
1089 nChars--;
1090 } else {
1091 int nEnd;
1093 TRACE("style %p\n", cursor.pRun->member.run.style);
1094 if (!ME_StreamOutRTFCharProps(pStream, &cursor.pRun->member.run.style->fmt))
1095 return FALSE;
1097 nEnd = (cursor.pRun == endCur.pRun) ? endCur.nOffset : cursor.pRun->member.run.len;
1098 if (!ME_StreamOutRTFText(pStream, get_text( &cursor.pRun->member.run, cursor.nOffset ),
1099 nEnd - cursor.nOffset))
1100 return FALSE;
1101 cursor.nOffset = 0;
1103 } while (cursor.pRun != endCur.pRun && ME_NextRun(&cursor.pPara, &cursor.pRun, TRUE));
1105 if (!ME_StreamOutMove(pStream, "}\0", 2))
1106 return FALSE;
1107 return TRUE;
1111 static BOOL ME_StreamOutText(ME_TextEditor *editor, ME_OutStream *pStream,
1112 const ME_Cursor *start, int nChars, DWORD dwFormat)
1114 ME_Cursor cursor = *start;
1115 int nLen;
1116 UINT nCodePage = CP_ACP;
1117 char *buffer = NULL;
1118 int nBufLen = 0;
1119 BOOL success = TRUE;
1121 if (!cursor.pRun)
1122 return FALSE;
1124 if (dwFormat & SF_USECODEPAGE)
1125 nCodePage = HIWORD(dwFormat);
1127 /* TODO: Handle SF_TEXTIZED */
1129 while (success && nChars && cursor.pRun) {
1130 nLen = min(nChars, cursor.pRun->member.run.len - cursor.nOffset);
1132 if (!editor->bEmulateVersion10 && cursor.pRun->member.run.nFlags & MERF_ENDPARA)
1134 static const WCHAR szEOL[] = { '\r', '\n' };
1136 /* richedit 2.0 - all line breaks are \r\n */
1137 if (dwFormat & SF_UNICODE)
1138 success = ME_StreamOutMove(pStream, (const char *)szEOL, sizeof(szEOL));
1139 else
1140 success = ME_StreamOutMove(pStream, "\r\n", 2);
1141 } else {
1142 if (dwFormat & SF_UNICODE)
1143 success = ME_StreamOutMove(pStream, (const char *)(get_text( &cursor.pRun->member.run, cursor.nOffset )),
1144 sizeof(WCHAR) * nLen);
1145 else {
1146 int nSize;
1148 nSize = WideCharToMultiByte(nCodePage, 0, get_text( &cursor.pRun->member.run, cursor.nOffset ),
1149 nLen, NULL, 0, NULL, NULL);
1150 if (nSize > nBufLen) {
1151 FREE_OBJ(buffer);
1152 buffer = ALLOC_N_OBJ(char, nSize);
1153 nBufLen = nSize;
1155 WideCharToMultiByte(nCodePage, 0, get_text( &cursor.pRun->member.run, cursor.nOffset ),
1156 nLen, buffer, nSize, NULL, NULL);
1157 success = ME_StreamOutMove(pStream, buffer, nSize);
1161 nChars -= nLen;
1162 cursor.nOffset = 0;
1163 cursor.pRun = ME_FindItemFwd(cursor.pRun, diRun);
1166 FREE_OBJ(buffer);
1167 return success;
1171 LRESULT ME_StreamOutRange(ME_TextEditor *editor, DWORD dwFormat,
1172 const ME_Cursor *start,
1173 int nChars, EDITSTREAM *stream)
1175 ME_OutStream *pStream = ME_StreamOutInit(editor, stream);
1177 if (dwFormat & SF_RTF)
1178 ME_StreamOutRTF(editor, pStream, start, nChars, dwFormat);
1179 else if (dwFormat & SF_TEXT || dwFormat & SF_TEXTIZED)
1180 ME_StreamOutText(editor, pStream, start, nChars, dwFormat);
1181 if (!pStream->stream->dwError)
1182 ME_StreamOutFlush(pStream);
1183 return ME_StreamOutFree(pStream);
1186 LRESULT
1187 ME_StreamOut(ME_TextEditor *editor, DWORD dwFormat, EDITSTREAM *stream)
1189 ME_Cursor start;
1190 int nChars;
1192 if (dwFormat & SFF_SELECTION) {
1193 int nStart, nTo;
1194 start = editor->pCursors[ME_GetSelectionOfs(editor, &nStart, &nTo)];
1195 nChars = nTo - nStart;
1196 } else {
1197 ME_SetCursorToStart(editor, &start);
1198 nChars = ME_GetTextLength(editor);
1199 /* Generate an end-of-paragraph at the end of SCF_ALL RTF output */
1200 if (dwFormat & SF_RTF)
1201 nChars++;
1203 return ME_StreamOutRange(editor, dwFormat, &start, nChars, stream);