ntdll/tests: Add a couple of status values seen on Win2K3.
[wine] / dlls / riched20 / run.c
1 /*
2  * RichEdit - operations on runs (diRun, rectangular pieces of paragraphs).
3  * Splitting/joining runs. Adjusting offsets after deleting/adding content.
4  * Character/pixel conversions.
5  *
6  * Copyright 2004 by Krzysztof Foltman
7  * Copyright 2006 by Phil Krylov
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23
24 #include "editor.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(richedit);
27 WINE_DECLARE_DEBUG_CHANNEL(richedit_check);
28 WINE_DECLARE_DEBUG_CHANNEL(richedit_lists);
29
30 /******************************************************************************
31  * ME_CanJoinRuns
32  *
33  * Returns 1 if two runs can be safely merged into one, 0 otherwise.
34  */ 
35 int ME_CanJoinRuns(const ME_Run *run1, const ME_Run *run2)
36 {
37   if ((run1->nFlags | run2->nFlags) & MERF_NOJOIN)
38     return 0;
39   if (run1->style != run2->style)
40     return 0;
41   if ((run1->nFlags & MERF_STYLEFLAGS) != (run2->nFlags & MERF_STYLEFLAGS))
42     return 0;
43   return 1;
44 }
45
46 void ME_SkipAndPropagateCharOffset(ME_DisplayItem *p, int shift)
47 {
48   p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
49   assert(p);
50   ME_PropagateCharOffset(p, shift);
51 }
52
53 /******************************************************************************
54  * ME_PropagateCharOffsets
55  *
56  * Shifts (increases or decreases) character offset (relative to beginning of 
57  * the document) of the part of the text starting from given place.  
58  */ 
59 void ME_PropagateCharOffset(ME_DisplayItem *p, int shift)
60 {
61         /* Runs in one paragraph contain character offset relative to their owning
62          * paragraph. If we start the shifting from the run, we need to shift
63          * all the relative offsets until the end of the paragraph
64          */                 
65   if (p->type == diRun) /* propagate in all runs in this para */
66   {
67     TRACE("PropagateCharOffset(%s, %d)\n", debugstr_w(p->member.run.strText->szData), shift);
68     do {
69       p->member.run.nCharOfs += shift;
70       assert(p->member.run.nCharOfs >= 0);
71       p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
72     } while(p->type == diRun);
73   }
74         /* Runs in next paragraphs don't need their offsets updated, because they, 
75          * again, those offsets are relative to their respective paragraphs.
76          * Instead of that, we're updating paragraphs' character offsets.         
77          */                 
78   if (p->type == diParagraph) /* propagate in all next paras */
79   {
80     do {
81       p->member.para.nCharOfs += shift;
82       assert(p->member.para.nCharOfs >= 0);
83       p = p->member.para.next_para;
84     } while(p->type == diParagraph);
85   }
86   /* diTextEnd also has character offset in it, which makes finding text length
87    * easier. But it needs to be up to date first.
88    */
89   if (p->type == diTextEnd)
90   {
91     p->member.para.nCharOfs += shift;
92     assert(p->member.para.nCharOfs >= 0);
93   }
94 }
95
96 /******************************************************************************
97  * ME_CheckCharOffsets
98  * 
99  * Checks if editor lists' validity and optionally dumps the document structure
100  */      
101 void ME_CheckCharOffsets(ME_TextEditor *editor)
102 {
103   ME_DisplayItem *p = editor->pBuffer->pFirst;
104   int ofs = 0, ofsp = 0;
105   if(TRACE_ON(richedit_lists))
106   {
107     TRACE_(richedit_lists)("---\n");
108     ME_DumpDocument(editor->pBuffer);
109   }
110   do {
111     p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
112     switch(p->type) {
113       case diTextEnd:
114         TRACE_(richedit_check)("tend, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
115         assert(ofsp+ofs == p->member.para.nCharOfs);
116         return;
117       case diParagraph:
118         TRACE_(richedit_check)("para, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
119         assert(ofsp+ofs == p->member.para.nCharOfs);
120         ofsp = p->member.para.nCharOfs;
121         ofs = 0;
122         break;
123       case diRun:
124         TRACE_(richedit_check)("run, real ofs = %d (+ofsp = %d), counted = %d, len = %d, txt = \"%s\", flags=%08x, fx&mask = %08x\n",
125           p->member.run.nCharOfs, p->member.run.nCharOfs+ofsp, ofsp+ofs,
126           p->member.run.strText->nLen, debugstr_w(p->member.run.strText->szData),
127           p->member.run.nFlags,
128           p->member.run.style->fmt.dwMask & p->member.run.style->fmt.dwEffects);
129         assert(ofs == p->member.run.nCharOfs);
130         assert(p->member.run.strText->nLen);
131         ofs += p->member.run.strText->nLen;
132         break;
133       case diCell:
134         TRACE_(richedit_check)("cell\n");
135         break;
136       default:
137         assert(0);
138     }
139   } while(1);
140 }
141
142 /******************************************************************************
143  * ME_CharOfsFromRunOfs
144  * 
145  * Converts a character position relative to the start of the run, to a
146  * character position relative to the start of the document.
147  * Kind of a "local to global" offset conversion.   
148  */      
149 int ME_CharOfsFromRunOfs(ME_TextEditor *editor, ME_DisplayItem *pRun, int nOfs)
150 {
151   ME_DisplayItem *pPara;
152
153   assert(pRun->type == diRun);
154   assert(pRun->member.run.nCharOfs != -1);
155
156   pPara = ME_FindItemBack(pRun, diParagraph);
157   assert(pPara);
158   assert(pPara->type==diParagraph);
159   return pPara->member.para.nCharOfs + pRun->member.run.nCharOfs
160     + ME_VPosToPos(pRun->member.run.strText, nOfs);
161 }
162
163 /******************************************************************************
164  * ME_CursorFromCharOfs
165  *
166  * Converts a character offset (relative to the start of the document) to
167  * a cursor structure (which contains a run and a position relative to that 
168  * run).
169  */
170 void ME_CursorFromCharOfs(ME_TextEditor *editor, int nCharOfs, ME_Cursor *pCursor)
171 {
172   ME_RunOfsFromCharOfs(editor, nCharOfs, &pCursor->pRun, &pCursor->nOffset);
173 }
174
175 /******************************************************************************
176  * ME_RunOfsFromCharOfs
177  *
178  * Find a run and relative character offset given an absolute character offset
179  * (absolute offset being an offset relative to the start of the document).
180  * Kind of a "global to local" offset conversion.
181  */
182 void ME_RunOfsFromCharOfs(ME_TextEditor *editor, int nCharOfs, ME_DisplayItem **ppRun, int *pOfs)
183 {
184   ME_DisplayItem *item, *next_item;
185
186   assert(ppRun);
187   assert(pOfs);
188
189   nCharOfs = max(nCharOfs, 0);
190   nCharOfs = min(nCharOfs, ME_GetTextLength(editor));
191
192   /* Find the paragraph at the offset. */
193   next_item = editor->pBuffer->pFirst->member.para.next_para;
194   do {
195     item = next_item;
196     next_item = item->member.para.next_para;
197   } while (next_item->member.para.nCharOfs <= nCharOfs);
198   assert(item->type == diParagraph);
199   nCharOfs -= item->member.para.nCharOfs;
200
201   /* Find the run at the offset. */
202   next_item = ME_FindItemFwd(item, diRun);
203   do {
204     item = next_item;
205     next_item = ME_FindItemFwd(item, diRunOrParagraphOrEnd);
206   } while (next_item->type == diRun &&
207            next_item->member.run.nCharOfs <= nCharOfs);
208   assert(item->type == diRun);
209   nCharOfs -= item->member.run.nCharOfs;
210
211   *ppRun = item;
212   *pOfs = nCharOfs;
213 }
214
215 /******************************************************************************
216  * ME_JoinRuns
217  * 
218  * Merges two adjacent runs, the one given as a parameter and the next one.
219  */    
220 void ME_JoinRuns(ME_TextEditor *editor, ME_DisplayItem *p)
221 {
222   ME_DisplayItem *pNext = p->next;
223   int i;
224   assert(p->type == diRun && pNext->type == diRun);
225   assert(p->member.run.nCharOfs != -1);
226   ME_GetParagraph(p)->member.para.nFlags |= MEPF_REWRAP;
227
228   /* Update all cursors so that they don't contain the soon deleted run */
229   for (i=0; i<editor->nCursors; i++) {
230     if (editor->pCursors[i].pRun == pNext) {
231       editor->pCursors[i].pRun = p;
232       editor->pCursors[i].nOffset += ME_StrVLen(p->member.run.strText);
233     }
234   }
235
236   ME_AppendString(p->member.run.strText, pNext->member.run.strText);
237   ME_Remove(pNext);
238   ME_DestroyDisplayItem(pNext);
239   ME_UpdateRunFlags(editor, &p->member.run);
240   if(TRACE_ON(richedit))
241   {
242     TRACE("Before check after join\n");
243     ME_CheckCharOffsets(editor);
244     TRACE("After check after join\n");
245   }
246 }
247
248 /******************************************************************************
249  * ME_SplitRun
250  * 
251  * Splits a run into two in a given place. It also updates the screen position
252  * and size (extent) of the newly generated runs.  
253  */    
254 ME_DisplayItem *ME_SplitRun(ME_WrapContext *wc, ME_DisplayItem *item, int nVChar)
255 {
256   ME_TextEditor *editor = wc->context->editor;
257   ME_DisplayItem *item2 = NULL;
258   ME_Run *run, *run2;
259   ME_Paragraph *para = &ME_GetParagraph(item)->member.para;
260
261   assert(item->member.run.nCharOfs != -1);
262   if(TRACE_ON(richedit))
263   {
264     TRACE("Before check before split\n");
265     ME_CheckCharOffsets(editor);
266     TRACE("After check before split\n");
267   }
268
269   run = &item->member.run;
270
271   TRACE("Before split: %s(%d, %d)\n", debugstr_w(run->strText->szData),
272         run->pt.x, run->pt.y);
273
274   item2 = ME_SplitRunSimple(editor, item, nVChar);
275
276   run2 = &item2->member.run;
277
278   ME_CalcRunExtent(wc->context, para, wc->nRow ? wc->nLeftMargin : wc->nFirstMargin, run);
279   ME_CalcRunExtent(wc->context, para, wc->nRow ? wc->nLeftMargin : wc->nFirstMargin, run2);
280
281   run2->pt.x = run->pt.x+run->nWidth;
282   run2->pt.y = run->pt.y;
283
284   if(TRACE_ON(richedit))
285   {
286     TRACE("Before check after split\n");
287     ME_CheckCharOffsets(editor);
288     TRACE("After check after split\n");
289     TRACE("After split: %s(%d, %d), %s(%d, %d)\n",
290       debugstr_w(run->strText->szData), run->pt.x, run->pt.y,
291       debugstr_w(run2->strText->szData), run2->pt.x, run2->pt.y);
292   }
293
294   return item2;
295 }
296
297 /******************************************************************************
298  * ME_SplitRunSimple
299  * 
300  * Does the most basic job of splitting a run into two - it does not
301  * update the positions and extents.    
302  */    
303 ME_DisplayItem *ME_SplitRunSimple(ME_TextEditor *editor, ME_DisplayItem *item, int nVChar)
304 {
305   ME_Run *run = &item->member.run;
306   ME_DisplayItem *item2;
307   ME_Run *run2;
308   int i;
309   assert(nVChar > 0 && nVChar < ME_StrVLen(run->strText));
310   assert(item->type == diRun);
311   assert(!(item->member.run.nFlags & MERF_NONTEXT));
312   assert(item->member.run.nCharOfs != -1);
313
314   item2 = ME_MakeRun(run->style,
315       ME_VSplitString(run->strText, nVChar), run->nFlags&MERF_SPLITMASK);
316
317   item2->member.run.nCharOfs = item->member.run.nCharOfs+
318     ME_VPosToPos(item->member.run.strText, nVChar);
319
320   run2 = &item2->member.run;
321   ME_InsertBefore(item->next, item2);
322
323   ME_UpdateRunFlags(editor, run);
324   ME_UpdateRunFlags(editor, run2);
325   for (i=0; i<editor->nCursors; i++) {
326     if (editor->pCursors[i].pRun == item &&
327         editor->pCursors[i].nOffset >= nVChar) {
328       assert(item2->type == diRun);
329       editor->pCursors[i].pRun = item2;
330       editor->pCursors[i].nOffset -= nVChar;
331     }
332   }
333   ME_GetParagraph(item)->member.para.nFlags |= MEPF_REWRAP;
334   return item2;
335 }
336
337 /******************************************************************************
338  * ME_MakeRun
339  * 
340  * A helper function to create run structures quickly.
341  */   
342 ME_DisplayItem *ME_MakeRun(ME_Style *s, ME_String *strData, int nFlags)
343 {
344   ME_DisplayItem *item = ME_MakeDI(diRun);
345   item->member.run.style = s;
346   item->member.run.ole_obj = NULL;
347   item->member.run.strText = strData;
348   item->member.run.nFlags = nFlags;
349   item->member.run.nCharOfs = -1;
350   ME_AddRefStyle(s);
351   return item;
352 }
353
354 /******************************************************************************
355  * ME_InsertRun
356  * 
357  * Inserts a run at a given character position (offset).
358  */   
359 ME_DisplayItem *ME_InsertRun(ME_TextEditor *editor, int nCharOfs, ME_DisplayItem *pItem)
360 {
361   ME_Cursor tmp;
362   ME_DisplayItem *pDI;
363
364   assert(pItem->type == diRun || pItem->type == diUndoInsertRun);
365
366   ME_CursorFromCharOfs(editor, nCharOfs, &tmp);
367   pDI = ME_InsertRunAtCursor(editor, &tmp, pItem->member.run.style,
368                              pItem->member.run.strText->szData,
369                              pItem->member.run.strText->nLen,
370                              pItem->member.run.nFlags);
371   
372   return pDI;
373 }
374
375 /******************************************************************************
376  * ME_InsertRunAtCursor
377  * 
378  * Inserts a new run with given style, flags and content at a given position,
379  * which is passed as a cursor structure (which consists of a run and 
380  * a run-relative character offset). 
381  */   
382 ME_DisplayItem *
383 ME_InsertRunAtCursor(ME_TextEditor *editor, ME_Cursor *cursor, ME_Style *style,
384                      const WCHAR *str, int len, int flags)
385 {
386   ME_DisplayItem *pDI;
387   ME_UndoItem *pUI;
388   
389   if (cursor->nOffset) {
390         /* We're inserting at the middle of the existing run, which means that
391                  * that run must be split. It isn't always necessary, but */
392     cursor->pRun = ME_SplitRunSimple(editor, cursor->pRun, cursor->nOffset);
393     cursor->nOffset = 0;
394   }
395   
396   pUI = ME_AddUndoItem(editor, diUndoDeleteRun, NULL);
397   if (pUI) {
398     pUI->nStart = (ME_GetParagraph(cursor->pRun)->member.para.nCharOfs
399                    + cursor->pRun->member.run.nCharOfs);
400     pUI->nLen = len;
401   }
402   
403   pDI = ME_MakeRun(style, ME_MakeStringN(str, len), flags);
404   pDI->member.run.nCharOfs = cursor->pRun->member.run.nCharOfs;
405   ME_InsertBefore(cursor->pRun, pDI);
406   TRACE("Shift length:%d\n", len);
407   ME_PropagateCharOffset(cursor->pRun, len);
408   ME_GetParagraph(cursor->pRun)->member.para.nFlags |= MEPF_REWRAP;
409   return pDI;
410 }
411
412 /******************************************************************************
413  * ME_UpdateRunFlags
414  * 
415  * Determine some of run attributes given its content (style, text content).
416  * Some flags cannot be determined by this function (MERF_GRAPHICS, 
417  * MERF_ENDPARA)     
418  */ 
419 void ME_UpdateRunFlags(ME_TextEditor *editor, ME_Run *run)
420 {
421   assert(run->nCharOfs != -1);
422
423   if (RUN_IS_HIDDEN(run) || run->nFlags & MERF_TABLESTART)
424     run->nFlags |= MERF_HIDDEN;
425   else
426     run->nFlags &= ~MERF_HIDDEN;
427
428   if (ME_IsSplitable(run->strText))
429     run->nFlags |= MERF_SPLITTABLE;
430   else
431     run->nFlags &= ~MERF_SPLITTABLE;
432
433   if (!(run->nFlags & MERF_NOTEXT)) {
434     if (ME_IsWhitespaces(run->strText))
435       run->nFlags |= MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE;
436     else
437     {
438       run->nFlags &= ~MERF_WHITESPACE;
439
440       if (ME_IsWSpace(ME_GetCharFwd(run->strText,0)))
441         run->nFlags |= MERF_STARTWHITE;
442       else
443         run->nFlags &= ~MERF_STARTWHITE;
444
445       if (ME_IsWSpace(ME_GetCharBack(run->strText,0)))
446         run->nFlags |= MERF_ENDWHITE;
447       else
448         run->nFlags &= ~MERF_ENDWHITE;
449     }
450   }
451   else
452     run->nFlags &= ~(MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE);
453 }
454
455 /******************************************************************************
456  * ME_CharFromPoint
457  * 
458  * Returns a character position inside the run given a run-relative
459  * pixel horizontal position. This version rounds left (ie. if the second
460  * character is at pixel position 8, then for cx=0..7 it returns 0).  
461  */     
462 int ME_CharFromPoint(ME_Context *c, int cx, ME_Run *run)
463 {
464   int fit = 0;
465   HGDIOBJ hOldFont;
466   SIZE sz;
467   if (!run->strText->nLen)
468     return 0;
469
470   if (run->nFlags & MERF_TAB ||
471       (run->nFlags & (MERF_ENDCELL|MERF_ENDPARA)) == MERF_ENDCELL)
472   {
473     if (cx < run->nWidth/2) 
474       return 0;
475     return 1;
476   }
477   if (run->nFlags & MERF_GRAPHICS)
478   {
479     SIZE sz;
480     ME_GetOLEObjectSize(c, run, &sz);
481     if (cx < sz.cx)
482       return 0;
483     return 1;
484   }
485   hOldFont = ME_SelectStyleFont(c, run->style);
486   
487   if (c->editor->cPasswordMask)
488   {
489     ME_String *strMasked = ME_MakeStringR(c->editor->cPasswordMask,ME_StrVLen(run->strText));
490     GetTextExtentExPointW(c->hDC, strMasked->szData, run->strText->nLen,
491       cx, &fit, NULL, &sz);
492     ME_DestroyString(strMasked);
493   }
494   else
495   {
496     GetTextExtentExPointW(c->hDC, run->strText->szData, run->strText->nLen,
497       cx, &fit, NULL, &sz);
498   }
499   
500   ME_UnselectStyleFont(c, run->style, hOldFont);
501
502   return fit;
503 }
504
505 /******************************************************************************
506  * ME_CharFromPointCursor
507  * 
508  * Returns a character position inside the run given a run-relative
509  * pixel horizontal position. This version rounds to the nearest character edge 
510  * (ie. if the second character is at pixel position 8, then for cx=0..3 
511  * it returns 0, and for cx=4..7 it returns 1).
512  * 
513  * It is used for mouse click handling, for better usability (and compatibility
514  * with the native control).        
515  */     
516 int ME_CharFromPointCursor(ME_TextEditor *editor, int cx, ME_Run *run)
517 {
518   ME_String *strRunText;
519   /* This could point to either the run's real text, or it's masked form in a password control */
520         
521   int fit = 0, fit1 = 0;
522   ME_Context c;
523   HGDIOBJ hOldFont;
524   SIZE sz, sz2, sz3;
525   if (!run->strText->nLen)
526     return 0;
527
528   if (run->nFlags & (MERF_TAB | MERF_ENDCELL))
529   {
530     if (cx < run->nWidth/2)
531       return 0;
532     return 1;
533   }
534   ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
535   if (run->nFlags & MERF_GRAPHICS)
536   {
537     SIZE sz;
538     ME_GetOLEObjectSize(&c, run, &sz);
539     ME_DestroyContext(&c);
540     if (cx < sz.cx/2)
541       return 0;
542     return 1;
543   }
544
545   if (editor->cPasswordMask)
546     strRunText = ME_MakeStringR(editor->cPasswordMask,ME_StrVLen(run->strText));
547   else
548     strRunText = run->strText;
549
550   hOldFont = ME_SelectStyleFont(&c, run->style);
551   GetTextExtentExPointW(c.hDC, strRunText->szData, strRunText->nLen,
552                         cx, &fit, NULL, &sz);
553   if (fit != strRunText->nLen)
554   {
555     int chars = 1;
556
557     GetTextExtentPoint32W(c.hDC, strRunText->szData, fit, &sz2);
558     fit1 = ME_StrRelPos(strRunText, fit, &chars);
559     GetTextExtentPoint32W(c.hDC, strRunText->szData, fit1, &sz3);
560     if (cx >= (sz2.cx+sz3.cx)/2)
561       fit = fit1;
562   }
563   
564   if (editor->cPasswordMask)
565     ME_DestroyString(strRunText);
566   
567   ME_UnselectStyleFont(&c, run->style, hOldFont);
568   ME_DestroyContext(&c);
569   return fit;
570 }
571
572 /******************************************************************************
573  * ME_GetTextExtent
574  *
575  * Finds a width and a height of the text using a specified style
576  */
577 static void ME_GetTextExtent(ME_Context *c, LPCWSTR szText, int nChars, ME_Style *s, SIZE *size)
578 {
579   HGDIOBJ hOldFont;
580   hOldFont = ME_SelectStyleFont(c, s);
581   GetTextExtentPoint32W(c->hDC, szText, nChars, size);
582   ME_UnselectStyleFont(c, s, hOldFont);
583 }
584
585 /******************************************************************************
586  * ME_PointFromChar
587  * 
588  * Returns a run-relative pixel position given a run-relative character
589  * position (character offset)
590  */     
591 int ME_PointFromChar(ME_TextEditor *editor, ME_Run *pRun, int nOffset)
592 {
593   SIZE size;
594   ME_Context c;
595   ME_String *strRunText;
596   /* This could point to either the run's real text, or it's masked form in a password control */
597
598   ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
599   if (pRun->nFlags & MERF_GRAPHICS)
600   {
601     if (nOffset)
602       ME_GetOLEObjectSize(&c, pRun, &size);
603     ITextHost_TxReleaseDC(editor->texthost, c.hDC);
604     return nOffset != 0;
605   } else if (pRun->nFlags & MERF_ENDPARA) {
606     nOffset = 0;
607   }
608
609   if (editor->cPasswordMask)
610     strRunText = ME_MakeStringR(editor->cPasswordMask,ME_StrVLen(pRun->strText));
611   else
612     strRunText = pRun->strText;
613
614   ME_GetTextExtent(&c,  strRunText->szData, nOffset, pRun->style, &size);
615   ITextHost_TxReleaseDC(editor->texthost, c.hDC);
616   if (editor->cPasswordMask)
617     ME_DestroyString(strRunText);
618   return size.cx;
619 }
620
621 /******************************************************************************
622  * ME_GetRunSizeCommon
623  * 
624  * Finds width, height, ascent and descent of a run, up to given character
625  * (nLen).
626  */
627 static SIZE ME_GetRunSizeCommon(ME_Context *c, const ME_Paragraph *para, ME_Run *run, int nLen,
628                                 int startx, int *pAscent, int *pDescent)
629 {
630   SIZE size;
631   int nMaxLen = ME_StrVLen(run->strText);
632
633   if (nLen>nMaxLen)
634     nLen = nMaxLen;
635
636   /* FIXME the following call also ensures that TEXTMETRIC structure is filled
637    * this is wasteful for MERF_NONTEXT runs, but that shouldn't matter
638    * in practice
639    */
640   
641   if (c->editor->cPasswordMask)
642   {
643     ME_String *szMasked = ME_MakeStringR(c->editor->cPasswordMask,nLen);
644     ME_GetTextExtent(c, szMasked->szData, nLen,run->style, &size); 
645     ME_DestroyString(szMasked);
646   }
647   else
648   {
649     ME_GetTextExtent(c, run->strText->szData, nLen, run->style, &size);
650   }
651   *pAscent = run->style->tm.tmAscent;
652   *pDescent = run->style->tm.tmDescent;
653   size.cy = *pAscent + *pDescent;
654
655   if (run->nFlags & MERF_TAB)
656   {
657     int pos = 0, i = 0, ppos, shift = 0;
658     PARAFORMAT2 *pFmt = para->pFmt;
659
660     if (c->editor->bEmulateVersion10 && /* v1.0 - 3.0 */
661         pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
662       /* The horizontal gap shifts the tab positions to leave the gap. */
663       shift = pFmt->dxOffset * 2;
664     do {
665       if (i < pFmt->cTabCount)
666       {
667         /* Only one side of the horizontal gap is needed at the end of
668          * the table row. */
669         if (i == pFmt->cTabCount -1)
670           shift = shift >> 1;
671         pos = shift + (pFmt->rgxTabs[i]&0x00FFFFFF);
672         i++;
673       }
674       else
675       {
676         pos += lDefaultTab - (pos % lDefaultTab);
677       }
678       ppos = ME_twips2pointsX(c, pos);
679       if (ppos > startx + run->pt.x) {
680         size.cx = ppos - startx - run->pt.x;
681         break;
682       }
683     } while(1);
684     size.cy = *pAscent + *pDescent;
685     return size;
686   }
687   if (run->nFlags & MERF_GRAPHICS)
688   {
689     ME_GetOLEObjectSize(c, run, &size);
690     if (size.cy > *pAscent)
691       *pAscent = size.cy;
692     /* descent is unchanged */
693     return size;
694   }
695   return size;
696 }
697
698 /******************************************************************************
699  * ME_GetRunSize
700  * 
701  * Finds width and height (but not ascent and descent) of a part of the run
702  * up to given character.    
703  */     
704 SIZE ME_GetRunSize(ME_Context *c, const ME_Paragraph *para,
705                    ME_Run *run, int nLen, int startx)
706 {
707   int asc, desc;
708   return ME_GetRunSizeCommon(c, para, run, nLen, startx, &asc, &desc);
709 }
710
711 /******************************************************************************
712  * ME_CalcRunExtent
713  * 
714  * Updates the size of the run (fills width, ascent and descent). The height
715  * is calculated based on whole row's ascent and descent anyway, so no need
716  * to use it here.        
717  */     
718 void ME_CalcRunExtent(ME_Context *c, const ME_Paragraph *para, int startx, ME_Run *run)
719 {
720   if (run->nFlags & MERF_HIDDEN)
721     run->nWidth = 0;
722   else
723   {
724     int nEnd = ME_StrVLen(run->strText);
725     SIZE size = ME_GetRunSizeCommon(c, para, run, nEnd, startx,
726                                     &run->nAscent, &run->nDescent);
727     run->nWidth = size.cx;
728     if (!size.cx)
729       WARN("size.cx == 0\n");
730   }
731 }
732
733 /******************************************************************************
734  * ME_MustBeWrapped
735  * 
736  * This should ensure that the given paragraph is wrapped so that its screen
737  * row structure may be used. But it doesn't, yet. 
738  */     
739 void ME_MustBeWrapped(ME_Context *c, ME_DisplayItem *para)
740 {
741   assert(para->type == diParagraph);
742   /* FIXME */
743 }
744
745 /******************************************************************************
746  * ME_SetSelectionCharFormat
747  * 
748  * Applies a style change, either to a current selection, or to insert cursor
749  * (ie. the style next typed characters will use).
750  */     
751 void ME_SetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
752 {
753   int nFrom, nTo;
754   ME_GetSelection(editor, &nFrom, &nTo);
755   if (nFrom == nTo)
756   {
757     ME_Style *s;
758     if (!editor->pBuffer->pCharStyle)
759       editor->pBuffer->pCharStyle = ME_GetInsertStyle(editor, 0);
760     s = ME_ApplyStyle(editor->pBuffer->pCharStyle, pFmt);
761     ME_ReleaseStyle(editor->pBuffer->pCharStyle);
762     editor->pBuffer->pCharStyle = s;
763   }
764   else
765     ME_SetCharFormat(editor, nFrom, nTo-nFrom, pFmt);
766 }
767
768 /******************************************************************************
769  * ME_SetCharFormat
770  * 
771  * Applies a style change to the specified part of the text
772  */     
773 void ME_SetCharFormat(ME_TextEditor *editor, int nOfs, int nChars, CHARFORMAT2W *pFmt)
774 {
775   ME_Cursor tmp, tmp2;
776   ME_DisplayItem *para;
777
778   ME_CursorFromCharOfs(editor, nOfs, &tmp);
779   if (tmp.nOffset)
780     tmp.pRun = ME_SplitRunSimple(editor, tmp.pRun, tmp.nOffset);
781
782   ME_CursorFromCharOfs(editor, nOfs+nChars, &tmp2);
783   if (tmp2.nOffset)
784     tmp2.pRun = ME_SplitRunSimple(editor, tmp2.pRun, tmp2.nOffset);
785
786   para = ME_GetParagraph(tmp.pRun);
787   para->member.para.nFlags |= MEPF_REWRAP;
788
789   while(tmp.pRun != tmp2.pRun)
790   {
791     ME_UndoItem *undo = NULL;
792     ME_Style *new_style = ME_ApplyStyle(tmp.pRun->member.run.style, pFmt);
793     /* ME_DumpStyle(new_style); */
794     undo = ME_AddUndoItem(editor, diUndoSetCharFormat, NULL);
795     if (undo) {
796       undo->nStart = tmp.pRun->member.run.nCharOfs+para->member.para.nCharOfs;
797       undo->nLen = tmp.pRun->member.run.strText->nLen;
798       undo->di.member.ustyle = tmp.pRun->member.run.style;
799       /* we'd have to addref undo...ustyle and release tmp...style
800          but they'd cancel each other out so we can do nothing instead */
801     }
802     else
803       ME_ReleaseStyle(tmp.pRun->member.run.style);
804     tmp.pRun->member.run.style = new_style;
805     tmp.pRun = ME_FindItemFwd(tmp.pRun, diRunOrParagraph);
806     if (tmp.pRun->type == diParagraph)
807     {
808       para = tmp.pRun;
809       tmp.pRun = ME_FindItemFwd(tmp.pRun, diRun);
810       if (tmp.pRun != tmp2.pRun)
811         para->member.para.nFlags |= MEPF_REWRAP;
812     }
813     assert(tmp.pRun);
814   }
815 }
816
817 /******************************************************************************
818  * ME_SetDefaultCharFormat
819  * 
820  * Applies a style change to the default character style.
821  */     
822 void ME_SetDefaultCharFormat(ME_TextEditor *editor, CHARFORMAT2W *mod)
823 {
824   ME_Style *style;
825
826   assert(mod->cbSize == sizeof(CHARFORMAT2W));
827   style = ME_ApplyStyle(editor->pBuffer->pDefaultStyle, mod);
828   editor->pBuffer->pDefaultStyle->fmt = style->fmt;
829   editor->pBuffer->pDefaultStyle->tm = style->tm;
830   ME_ReleaseStyle(style);
831   ME_MarkAllForWrapping(editor);
832   /*  pcf = editor->pBuffer->pDefaultStyle->fmt; */
833 }
834
835 static void ME_GetRunCharFormat(ME_TextEditor *editor, ME_DisplayItem *run, CHARFORMAT2W *pFmt)
836 {
837   ME_CopyCharFormat(pFmt, &run->member.run.style->fmt);
838   if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_CF1UNDERLINE))
839   {
840     pFmt->dwMask |= CFM_UNDERLINE;
841     pFmt->dwEffects |= CFE_UNDERLINE;
842   }
843   if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_UNDERLINENONE))
844   {
845     pFmt->dwMask |= CFM_UNDERLINE;
846     pFmt->dwEffects &= ~CFE_UNDERLINE;
847   }
848 }
849
850 /******************************************************************************
851  * ME_GetDefaultCharFormat
852  * 
853  * Retrieves the current default character style (the one applied where no
854  * other style was applied) .
855  */     
856 void ME_GetDefaultCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
857 {
858   ME_CopyCharFormat(pFmt, &editor->pBuffer->pDefaultStyle->fmt);
859 }
860
861 /******************************************************************************
862  * ME_GetSelectionCharFormat
863  * 
864  * If selection exists, it returns all style elements that are set consistently
865  * in the whole selection. If not, it just returns the current style.  
866  */     
867 void ME_GetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
868 {
869   int nFrom, nTo;
870   ME_GetSelection(editor, &nFrom, &nTo);
871   if (nFrom == nTo && editor->pBuffer->pCharStyle)
872   {
873     ME_CopyCharFormat(pFmt, &editor->pBuffer->pCharStyle->fmt);
874     return;
875   }
876   ME_GetCharFormat(editor, nFrom, nTo, pFmt);
877 }
878
879 /******************************************************************************
880  * ME_GetCharFormat
881  * 
882  * Returns the style consisting of those attributes which are consistently set
883  * in the whole character range.    
884  */     
885 void ME_GetCharFormat(ME_TextEditor *editor, int nFrom, int nTo, CHARFORMAT2W *pFmt)
886 {
887   ME_DisplayItem *run, *run_end;
888   int nOffset, nOffset2;
889   CHARFORMAT2W tmp;
890
891   ME_RunOfsFromCharOfs(editor, nFrom, &run, &nOffset);
892   if (nFrom == nTo) /* special case - if selection is empty, take previous char's formatting */
893   {
894     if (!nOffset)
895     {
896       ME_DisplayItem *tmp_run = ME_FindItemBack(run, diRunOrParagraph);
897       if (tmp_run->type == diRun) {
898         ME_GetRunCharFormat(editor, tmp_run, pFmt);
899         return;
900       }
901     }
902     ME_GetRunCharFormat(editor, run, pFmt);
903     return;
904   }
905   
906   if (nTo>nFrom) /* selection consists of chars from nFrom up to nTo-1 */
907     nTo--;
908   ME_RunOfsFromCharOfs(editor, nTo, &run_end, &nOffset2);
909
910   ME_GetRunCharFormat(editor, run, pFmt);
911
912   if (run == run_end) return;
913
914   do {
915     /* FIXME add more style feature comparisons */
916     int nAttribs = CFM_SIZE | CFM_FACE | CFM_COLOR | CFM_UNDERLINETYPE;
917     int nEffects = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_PROTECTED | CFM_LINK | CFM_SUPERSCRIPT;
918
919     run = ME_FindItemFwd(run, diRun);
920
921     ZeroMemory(&tmp, sizeof(tmp));
922     tmp.cbSize = sizeof(tmp);
923     ME_GetRunCharFormat(editor, run, &tmp);
924
925     assert((tmp.dwMask & nAttribs) == nAttribs);
926     /* reset flags that differ */
927
928     if (pFmt->yHeight != tmp.yHeight)
929       pFmt->dwMask &= ~CFM_SIZE;
930     if (pFmt->dwMask & CFM_FACE)
931     {
932       if (!(tmp.dwMask & CFM_FACE))
933         pFmt->dwMask &= ~CFM_FACE;
934       else if (lstrcmpW(pFmt->szFaceName, tmp.szFaceName) ||
935           pFmt->bPitchAndFamily != tmp.bPitchAndFamily)
936         pFmt->dwMask &= ~CFM_FACE;
937     }
938     if (pFmt->yHeight != tmp.yHeight)
939       pFmt->dwMask &= ~CFM_SIZE;
940     if (pFmt->bUnderlineType != tmp.bUnderlineType)
941       pFmt->dwMask &= ~CFM_UNDERLINETYPE;
942     if (pFmt->dwMask & CFM_COLOR)
943     {
944       if (!((pFmt->dwEffects&CFE_AUTOCOLOR) & (tmp.dwEffects&CFE_AUTOCOLOR)))
945       {
946         if (pFmt->crTextColor != tmp.crTextColor)
947           pFmt->dwMask &= ~CFM_COLOR;
948       }
949     }
950
951     pFmt->dwMask &= ~((pFmt->dwEffects ^ tmp.dwEffects) & nEffects);
952     pFmt->dwEffects = tmp.dwEffects;
953
954   } while(run != run_end);
955 }