run.c 27.1 KB
Newer Older
1 2 3 4 5 6
/*
 * RichEdit - operations on runs (diRun, rectangular pieces of paragraphs).
 * Splitting/joining runs. Adjusting offsets after deleting/adding content.
 * Character/pixel conversions.
 *
 * Copyright 2004 by Krzysztof Foltman
7
 * Copyright 2006 by Phil Krylov
8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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 25 26
 */

#include "editor.h"

WINE_DEFAULT_DEBUG_CHANNEL(richedit);
27 28
WINE_DECLARE_DEBUG_CHANNEL(richedit_check);
WINE_DECLARE_DEBUG_CHANNEL(richedit_lists);
29

30 31 32
/******************************************************************************
 * ME_CanJoinRuns
 *
33 34 35
 * Returns TRUE if two runs can be safely merged into one, FALSE otherwise.
 */
BOOL ME_CanJoinRuns(const ME_Run *run1, const ME_Run *run2)
36
{
37
  if ((run1->nFlags | run2->nFlags) & MERF_NOJOIN)
38
    return FALSE;
39
  if (run1->style != run2->style)
40
    return FALSE;
41
  if ((run1->nFlags & MERF_STYLEFLAGS) != (run2->nFlags & MERF_STYLEFLAGS))
42 43
    return FALSE;
  return TRUE;
44 45 46 47 48 49 50 51 52
}

void ME_SkipAndPropagateCharOffset(ME_DisplayItem *p, int shift)
{
  p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
  assert(p);
  ME_PropagateCharOffset(p, shift);
}

53 54 55 56 57 58
/******************************************************************************
 * ME_PropagateCharOffsets
 *
 * Shifts (increases or decreases) character offset (relative to beginning of 
 * the document) of the part of the text starting from given place.  
 */ 
59 60
void ME_PropagateCharOffset(ME_DisplayItem *p, int shift)
{
61 62 63 64
	/* Runs in one paragraph contain character offset relative to their owning
	 * paragraph. If we start the shifting from the run, we need to shift
	 * all the relative offsets until the end of the paragraph
	 */	 	    
65 66
  if (p->type == diRun) /* propagate in all runs in this para */
  {
67
    TRACE("PropagateCharOffset(%s, %d)\n", debugstr_run( &p->member.run ), shift);
68 69 70 71 72 73
    do {
      p->member.run.nCharOfs += shift;
      assert(p->member.run.nCharOfs >= 0);
      p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
    } while(p->type == diRun);
  }
74 75 76 77
	/* Runs in next paragraphs don't need their offsets updated, because they, 
	 * again, those offsets are relative to their respective paragraphs.
	 * Instead of that, we're updating paragraphs' character offsets.	  
	 */	 	    
78 79 80 81 82 83 84 85
  if (p->type == diParagraph) /* propagate in all next paras */
  {
    do {
      p->member.para.nCharOfs += shift;
      assert(p->member.para.nCharOfs >= 0);
      p = p->member.para.next_para;
    } while(p->type == diParagraph);
  }
86 87 88
  /* diTextEnd also has character offset in it, which makes finding text length
   * easier. But it needs to be up to date first.
   */
89 90 91 92 93 94 95
  if (p->type == diTextEnd)
  {
    p->member.para.nCharOfs += shift;
    assert(p->member.para.nCharOfs >= 0);
  }
}

96 97 98 99 100
/******************************************************************************
 * ME_CheckCharOffsets
 * 
 * Checks if editor lists' validity and optionally dumps the document structure
 */      
101 102 103 104
void ME_CheckCharOffsets(ME_TextEditor *editor)
{
  ME_DisplayItem *p = editor->pBuffer->pFirst;
  int ofs = 0, ofsp = 0;
105 106

  TRACE_(richedit_check)("Checking begin\n");
107
  if(TRACE_ON(richedit_lists))
108
  {
109
    TRACE_(richedit_lists)("---\n");
110 111 112 113 114 115
    ME_DumpDocument(editor->pBuffer);
  }
  do {
    p = ME_FindItemFwd(p, diRunOrParagraphOrEnd);
    switch(p->type) {
      case diTextEnd:
116
        TRACE_(richedit_check)("tend, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
117
        assert(ofsp+ofs == p->member.para.nCharOfs);
118
        TRACE_(richedit_check)("Checking finished\n");
119 120
        return;
      case diParagraph:
121
        TRACE_(richedit_check)("para, real ofsp = %d, counted = %d\n", p->member.para.nCharOfs, ofsp+ofs);
122 123 124 125 126
        assert(ofsp+ofs == p->member.para.nCharOfs);
        ofsp = p->member.para.nCharOfs;
        ofs = 0;
        break;
      case diRun:
127
        TRACE_(richedit_check)("run, real ofs = %d (+ofsp = %d), counted = %d, len = %d, txt = %s, flags=%08x, fx&mask = %08x\n",
128
          p->member.run.nCharOfs, p->member.run.nCharOfs+ofsp, ofsp+ofs,
129
          p->member.run.len, debugstr_run( &p->member.run ),
130 131 132
          p->member.run.nFlags,
          p->member.run.style->fmt.dwMask & p->member.run.style->fmt.dwEffects);
        assert(ofs == p->member.run.nCharOfs);
133 134
        assert(p->member.run.len);
        ofs += p->member.run.len;
135
        break;
136 137 138
      case diCell:
        TRACE_(richedit_check)("cell\n");
        break;
139 140 141 142
      default:
        assert(0);
    }
  } while(1);
143
  TRACE_(richedit_check)("Checking finished\n");
144 145
}

146 147
/******************************************************************************
 * ME_CharOfsFromRunOfs
148
 *
149 150
 * Converts a character position relative to the start of the run, to a
 * character position relative to the start of the document.
151 152 153 154
 * Kind of a "local to global" offset conversion.
 */
int ME_CharOfsFromRunOfs(ME_TextEditor *editor, const ME_DisplayItem *pPara,
                         const ME_DisplayItem *pRun, int nOfs)
155
{
156 157 158
  assert(pRun && pRun->type == diRun);
  assert(pPara && pPara->type == diParagraph);
  return pPara->member.para.nCharOfs + pRun->member.run.nCharOfs + nOfs;
159 160
}

161 162
/******************************************************************************
 * ME_CursorFromCharOfs
163
 *
164
 * Converts a character offset (relative to the start of the document) to
165
 * a cursor structure (which contains a run and a position relative to that
166 167
 * run).
 */
168 169
void ME_CursorFromCharOfs(ME_TextEditor *editor, int nCharOfs, ME_Cursor *pCursor)
{
170 171
  ME_RunOfsFromCharOfs(editor, nCharOfs, &pCursor->pPara,
                       &pCursor->pRun, &pCursor->nOffset);
172 173
}

174 175
/******************************************************************************
 * ME_RunOfsFromCharOfs
176
 *
177 178
 * Find a run and relative character offset given an absolute character offset
 * (absolute offset being an offset relative to the start of the document).
179 180
 * Kind of a "global to local" offset conversion.
 */
181 182 183 184 185
void ME_RunOfsFromCharOfs(ME_TextEditor *editor,
                          int nCharOfs,
                          ME_DisplayItem **ppPara,
                          ME_DisplayItem **ppRun,
                          int *pOfs)
186
{
187
  ME_DisplayItem *item, *next_item;
188

189 190 191 192 193 194 195 196 197 198 199
  nCharOfs = max(nCharOfs, 0);
  nCharOfs = min(nCharOfs, ME_GetTextLength(editor));

  /* Find the paragraph at the offset. */
  next_item = editor->pBuffer->pFirst->member.para.next_para;
  do {
    item = next_item;
    next_item = item->member.para.next_para;
  } while (next_item->member.para.nCharOfs <= nCharOfs);
  assert(item->type == diParagraph);
  nCharOfs -= item->member.para.nCharOfs;
200
  if (ppPara) *ppPara = item;
201 202 203 204 205 206 207 208 209 210 211

  /* Find the run at the offset. */
  next_item = ME_FindItemFwd(item, diRun);
  do {
    item = next_item;
    next_item = ME_FindItemFwd(item, diRunOrParagraphOrEnd);
  } while (next_item->type == diRun &&
           next_item->member.run.nCharOfs <= nCharOfs);
  assert(item->type == diRun);
  nCharOfs -= item->member.run.nCharOfs;

212 213
  if (ppRun) *ppRun = item;
  if (pOfs) *pOfs = nCharOfs;
214 215
}

216 217 218 219 220
/******************************************************************************
 * ME_JoinRuns
 * 
 * Merges two adjacent runs, the one given as a parameter and the next one.
 */    
221 222 223 224 225 226
void ME_JoinRuns(ME_TextEditor *editor, ME_DisplayItem *p)
{
  ME_DisplayItem *pNext = p->next;
  int i;
  assert(p->type == diRun && pNext->type == diRun);
  assert(p->member.run.nCharOfs != -1);
227
  ME_GetParagraph(p)->member.para.nFlags |= MEPF_REWRAP;
228

229
  /* Update all cursors so that they don't contain the soon deleted run */
230 231 232
  for (i=0; i<editor->nCursors; i++) {
    if (editor->pCursors[i].pRun == pNext) {
      editor->pCursors[i].pRun = p;
233
      editor->pCursors[i].nOffset += p->member.run.len;
234 235
    }
  }
236

237
  p->member.run.len += pNext->member.run.len;
238 239 240
  ME_Remove(pNext);
  ME_DestroyDisplayItem(pNext);
  ME_UpdateRunFlags(editor, &p->member.run);
241
  if(TRACE_ON(richedit_check))
242 243 244
    ME_CheckCharOffsets(editor);
}

245 246
/******************************************************************************
 * ME_SplitRunSimple
247
 *
248
 * Does the most basic job of splitting a run into two - it does not
249 250 251
 * update the positions and extents.
 */
ME_DisplayItem *ME_SplitRunSimple(ME_TextEditor *editor, ME_Cursor *cursor)
252
{
253 254
  ME_DisplayItem *run = cursor->pRun;
  ME_DisplayItem *new_run;
255
  int i;
256
  int nOffset = cursor->nOffset;
257

258
  assert(!(run->member.run.nFlags & MERF_NONTEXT));
259

260 261 262
  new_run = ME_MakeRun(run->member.run.style,
                       run->member.run.nFlags & MERF_SPLITMASK);
  new_run->member.run.nCharOfs = run->member.run.nCharOfs + nOffset;
263
  new_run->member.run.len = run->member.run.len - nOffset;
264
  new_run->member.run.para = run->member.run.para;
265
  run->member.run.len = nOffset;
266 267
  cursor->pRun = new_run;
  cursor->nOffset = 0;
268

269 270 271 272 273 274 275 276 277
  ME_InsertBefore(run->next, new_run);

  ME_UpdateRunFlags(editor, &run->member.run);
  ME_UpdateRunFlags(editor, &new_run->member.run);
  for (i = 0; i < editor->nCursors; i++) {
    if (editor->pCursors[i].pRun == run &&
        editor->pCursors[i].nOffset >= nOffset) {
      editor->pCursors[i].pRun = new_run;
      editor->pCursors[i].nOffset -= nOffset;
278 279
    }
  }
280 281
  cursor->pPara->member.para.nFlags |= MEPF_REWRAP;
  return run;
282 283
}

284 285 286 287 288
/******************************************************************************
 * ME_MakeRun
 * 
 * A helper function to create run structures quickly.
 */   
289
ME_DisplayItem *ME_MakeRun(ME_Style *s, int nFlags)
290 291 292
{
  ME_DisplayItem *item = ME_MakeDI(diRun);
  item->member.run.style = s;
293
  item->member.run.ole_obj = NULL;
294 295
  item->member.run.nFlags = nFlags;
  item->member.run.nCharOfs = -1;
296
  item->member.run.len = 0;
297
  item->member.run.para = NULL;
298 299 300 301 302 303 304 305
  item->member.run.num_glyphs = 0;
  item->member.run.max_glyphs = 0;
  item->member.run.glyphs = NULL;
  item->member.run.vis_attrs = NULL;
  item->member.run.advances = NULL;
  item->member.run.offsets = NULL;
  item->member.run.max_clusters = 0;
  item->member.run.clusters = NULL;
306 307 308 309
  ME_AddRefStyle(s);
  return item;
}

310 311
/******************************************************************************
 * ME_InsertRunAtCursor
312
 *
313 314
 * Inserts a new run with given style, flags and content at a given position,
 * which is passed as a cursor structure (which consists of a run and 
315 316
 * a run-relative character offset).
 */
317 318 319 320
ME_DisplayItem *
ME_InsertRunAtCursor(ME_TextEditor *editor, ME_Cursor *cursor, ME_Style *style,
                     const WCHAR *str, int len, int flags)
{
321
  ME_DisplayItem *pDI, *insert_before = cursor->pRun, *prev;
322

323
  if (cursor->nOffset)
324 325 326 327 328 329 330 331 332 333 334 335
  {
    if (cursor->nOffset == cursor->pRun->member.run.len)
    {
      insert_before = ME_FindItemFwd( cursor->pRun, diRun );
      if (!insert_before) insert_before = cursor->pRun; /* Always insert before the final eop run */
    }
    else
    {
      ME_SplitRunSimple( editor, cursor );
      insert_before = cursor->pRun;
    }
  }
336

337 338
  add_undo_delete_run( editor, insert_before->member.run.para->nCharOfs +
                       insert_before->member.run.nCharOfs, len );
339

340
  pDI = ME_MakeRun(style, flags);
341
  pDI->member.run.nCharOfs = insert_before->member.run.nCharOfs;
342
  pDI->member.run.len = len;
343
  pDI->member.run.para = insert_before->member.run.para;
344
  ME_InsertString( pDI->member.run.para->text, pDI->member.run.nCharOfs, str, len );
345
  ME_InsertBefore( insert_before, pDI );
346
  TRACE("Shift length:%d\n", len);
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
  ME_PropagateCharOffset( insert_before, len );
  insert_before->member.run.para->nFlags |= MEPF_REWRAP;

  /* Move any cursors that were at the end of the previous run to the end of the inserted run */
  prev = ME_FindItemBack( pDI, diRun );
  if (prev)
  {
    int i;

    for (i = 0; i < editor->nCursors; i++)
    {
      if (editor->pCursors[i].pRun == prev &&
          editor->pCursors[i].nOffset == prev->member.run.len)
      {
        editor->pCursors[i].pRun = pDI;
        editor->pCursors[i].nOffset = len;
      }
    }
  }

367 368 369
  return pDI;
}

370 371 372
static BOOL run_is_splittable( const ME_Run *run )
{
    WCHAR *str = get_text( run, 0 ), *p;
373
    int i;
374 375
    BOOL found_ink = FALSE;

376
    for (i = 0, p = str; i < run->len; i++, p++)
377 378 379 380 381 382 383 384 385 386 387
    {
        if (ME_IsWSpace( *p ))
        {
            if (found_ink) return TRUE;
        }
        else
            found_ink = TRUE;
    }
    return FALSE;
}

388 389 390
static BOOL run_is_entirely_ws( const ME_Run *run )
{
    WCHAR *str = get_text( run, 0 ), *p;
391
    int i;
392

393
    for (i = 0, p = str; i < run->len; i++, p++)
394 395 396 397 398
        if (!ME_IsWSpace( *p )) return FALSE;

    return TRUE;
}

399 400
/******************************************************************************
 * ME_UpdateRunFlags
401
 *
402
 * Determine some of run attributes given its content (style, text content).
403 404 405
 * Some flags cannot be determined by this function (MERF_GRAPHICS,
 * MERF_ENDPARA)
 */
406 407
void ME_UpdateRunFlags(ME_TextEditor *editor, ME_Run *run)
{
408
  assert(run->nCharOfs >= 0);
409

410
  if (RUN_IS_HIDDEN(run) || run->nFlags & MERF_TABLESTART)
411 412 413 414
    run->nFlags |= MERF_HIDDEN;
  else
    run->nFlags &= ~MERF_HIDDEN;

415
  if (run_is_splittable( run ))
416 417 418
    run->nFlags |= MERF_SPLITTABLE;
  else
    run->nFlags &= ~MERF_SPLITTABLE;
419

420 421 422
  if (!(run->nFlags & MERF_NOTEXT))
  {
    if (run_is_entirely_ws( run ))
423 424 425 426
      run->nFlags |= MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE;
    else
    {
      run->nFlags &= ~MERF_WHITESPACE;
427

428
      if (ME_IsWSpace( *get_text( run, 0 ) ))
429 430 431
        run->nFlags |= MERF_STARTWHITE;
      else
        run->nFlags &= ~MERF_STARTWHITE;
432

433
      if (ME_IsWSpace( *get_text( run, run->len - 1 ) ))
434 435 436 437 438 439 440 441 442
        run->nFlags |= MERF_ENDWHITE;
      else
        run->nFlags &= ~MERF_ENDWHITE;
    }
  }
  else
    run->nFlags &= ~(MERF_WHITESPACE | MERF_STARTWHITE | MERF_ENDWHITE);
}

443
/******************************************************************************
444
 * ME_CharFromPointContext
445
 *
446
 * Returns a character position inside the run given a run-relative
447
 * pixel horizontal position.
448
 *
449 450 451 452 453
 * If closest is FALSE return the actual character
 * If closest is TRUE will round to the closest leading edge.
 * ie. if the second character is at pixel position 8 and third at 16 then for:
 * closest = FALSE cx = 0..7 return 0, cx = 8..15 return 1
 * closest = TRUE  cx = 0..3 return 0, cx = 4..11 return 1.
454
 */
455
int ME_CharFromPointContext(ME_Context *c, int cx, ME_Run *run, BOOL closest, BOOL visual_order)
456
{
457 458
  ME_String *mask_text = NULL;
  WCHAR *str;
459
  int fit = 0;
460 461
  HGDIOBJ hOldFont;
  SIZE sz, sz2, sz3;
462
  if (!run->len || cx <= 0)
463 464
    return 0;

465
  if (run->nFlags & (MERF_TAB | MERF_ENDCELL))
466
  {
467
    if (!closest || cx < run->nWidth / 2) return 0;
468 469
    return 1;
  }
470

471 472 473
  if (run->nFlags & MERF_GRAPHICS)
  {
    SIZE sz;
474 475
    ME_GetOLEObjectSize(c, run, &sz);
    if (!closest || cx < sz.cx / 2) return 0;
476 477
    return 1;
  }
478

479 480 481 482 483 484 485 486 487 488 489 490
  if (run->para->nFlags & MEPF_COMPLEX)
  {
      int cp, trailing;
      if (visual_order && run->script_analysis.fRTL) cx = run->nWidth - cx - 1;

      ScriptXtoCP( cx, run->len, run->num_glyphs, run->clusters, run->vis_attrs, run->advances, &run->script_analysis,
                   &cp, &trailing );
      TRACE("x %d cp %d trailing %d (run width %d) rtl %d log order %d\n", cx, cp, trailing, run->nWidth,
            run->script_analysis.fRTL, run->script_analysis.fLogicalOrder);
      return closest ? cp + trailing : cp;
  }

491
  if (c->editor->cPasswordMask)
492
  {
493
    mask_text = ME_MakeStringR( c->editor->cPasswordMask, run->len );
494 495
    str = mask_text->szData;
  }
496
  else
497
    str = get_text( run, 0 );
498

499 500
  hOldFont = ME_SelectStyleFont(c, run->style);
  GetTextExtentExPointW(c->hDC, str, run->len,
501
                        cx, &fit, NULL, &sz);
502
  if (closest && fit != run->len)
503
  {
504 505
    GetTextExtentPoint32W(c->hDC, str, fit, &sz2);
    GetTextExtentPoint32W(c->hDC, str, fit + 1, &sz3);
506
    if (cx >= (sz2.cx+sz3.cx)/2)
507
      fit = fit + 1;
508
  }
509

510
  ME_DestroyString( mask_text );
511

512
  ME_UnselectStyleFont(c, run->style, hOldFont);
513 514 515
  return fit;
}

516
int ME_CharFromPoint(ME_TextEditor *editor, int cx, ME_Run *run, BOOL closest, BOOL visual_order)
517 518 519 520 521
{
    ME_Context c;
    int ret;

    ME_InitContext( &c, editor, ITextHost_TxGetDC( editor->texthost ) );
522
    ret = ME_CharFromPointContext( &c, cx, run, closest, visual_order );
523 524 525 526
    ME_DestroyContext(&c);
    return ret;
}

527 528 529 530 531 532 533 534
/******************************************************************************
 * ME_GetTextExtent
 *
 * Finds a width and a height of the text using a specified style
 */
static void ME_GetTextExtent(ME_Context *c, LPCWSTR szText, int nChars, ME_Style *s, SIZE *size)
{
  HGDIOBJ hOldFont;
535 536 537 538 539 540 541 542
  if (c->hDC) {
    hOldFont = ME_SelectStyleFont(c, s);
    GetTextExtentPoint32W(c->hDC, szText, nChars, size);
    ME_UnselectStyleFont(c, s, hOldFont);
  } else {
    size->cx = 0;
    size->cy = 0;
  }
543 544
}

545
/******************************************************************************
546
 * ME_PointFromCharContext
547
 *
548 549
 * Returns a run-relative pixel position given a run-relative character
 * position (character offset)
550
 */
551
int ME_PointFromCharContext(ME_Context *c, ME_Run *pRun, int nOffset, BOOL visual_order)
552 553
{
  SIZE size;
554 555
  ME_String *mask_text = NULL;
  WCHAR *str;
556

557 558
  if (pRun->nFlags & MERF_GRAPHICS)
  {
559
    if (nOffset)
560
      ME_GetOLEObjectSize(c, pRun, &size);
561
    return nOffset != 0;
562 563
  } else if (pRun->nFlags & MERF_ENDPARA) {
    nOffset = 0;
564
  }
565

566 567 568 569 570 571 572 573
  if (pRun->para->nFlags & MEPF_COMPLEX)
  {
      int x;
      ScriptCPtoX( nOffset, FALSE, pRun->len, pRun->num_glyphs, pRun->clusters,
                   pRun->vis_attrs, pRun->advances, &pRun->script_analysis, &x );
      if (visual_order && pRun->script_analysis.fRTL) x = pRun->nWidth - x - 1;
      return x;
  }
574
  if (c->editor->cPasswordMask)
575
  {
576
    mask_text = ME_MakeStringR(c->editor->cPasswordMask, pRun->len);
577 578
    str = mask_text->szData;
  }
579
  else
580
      str = get_text( pRun, 0 );
581

582
  ME_GetTextExtent(c, str, nOffset, pRun->style, &size);
583
  ME_DestroyString( mask_text );
584 585 586
  return size.cx;
}

587 588 589 590 591
/******************************************************************************
 * ME_PointFromChar
 *
 * Calls ME_PointFromCharContext after first creating a context.
 */
592
int ME_PointFromChar(ME_TextEditor *editor, ME_Run *pRun, int nOffset, BOOL visual_order)
593 594 595 596 597
{
    ME_Context c;
    int ret;

    ME_InitContext(&c, editor, ITextHost_TxGetDC(editor->texthost));
598
    ret = ME_PointFromCharContext( &c, pRun, nOffset, visual_order );
599 600 601 602 603
    ME_DestroyContext(&c);

    return ret;
}

604 605 606
/******************************************************************************
 * ME_GetRunSizeCommon
 * 
607 608 609
 * Finds width, height, ascent and descent of a run, up to given character
 * (nLen).
 */
610 611
SIZE ME_GetRunSizeCommon(ME_Context *c, const ME_Paragraph *para, ME_Run *run, int nLen,
                         int startx, int *pAscent, int *pDescent)
612 613
{
  SIZE size;
614
  int nMaxLen = run->len;
615 616 617

  if (nLen>nMaxLen)
    nLen = nMaxLen;
618 619

  /* FIXME the following call also ensures that TEXTMETRIC structure is filled
620
   * this is wasteful for MERF_NONTEXT runs, but that shouldn't matter
621 622
   * in practice
   */
623 624 625 626 627 628

  if (para->nFlags & MEPF_COMPLEX)
  {
      size.cx = run->nWidth;
  }
  else if (c->editor->cPasswordMask)
629 630 631 632 633 634 635
  {
    ME_String *szMasked = ME_MakeStringR(c->editor->cPasswordMask,nLen);
    ME_GetTextExtent(c, szMasked->szData, nLen,run->style, &size); 
    ME_DestroyString(szMasked);
  }
  else
  {
636
    ME_GetTextExtent(c, get_text( run, 0 ), nLen, run->style, &size);
637
  }
638 639 640 641 642 643
  *pAscent = run->style->tm.tmAscent;
  *pDescent = run->style->tm.tmDescent;
  size.cy = *pAscent + *pDescent;

  if (run->nFlags & MERF_TAB)
  {
644
    int pos = 0, i = 0, ppos, shift = 0;
645
    PARAFORMAT2 *pFmt = para->pFmt;
646

647 648 649 650
    if (c->editor->bEmulateVersion10 && /* v1.0 - 3.0 */
        pFmt->dwMask & PFM_TABLE && pFmt->wEffects & PFE_TABLE)
      /* The horizontal gap shifts the tab positions to leave the gap. */
      shift = pFmt->dxOffset * 2;
651 652 653
    do {
      if (i < pFmt->cTabCount)
      {
654 655 656 657 658
        /* Only one side of the horizontal gap is needed at the end of
         * the table row. */
        if (i == pFmt->cTabCount -1)
          shift = shift >> 1;
        pos = shift + (pFmt->rgxTabs[i]&0x00FFFFFF);
659 660 661 662
        i++;
      }
      else
      {
663
        pos += lDefaultTab - (pos % lDefaultTab);
664
      }
665
      ppos = ME_twips2pointsX(c, pos);
666 667
      if (ppos > startx + run->pt.x) {
        size.cx = ppos - startx - run->pt.x;
668 669 670 671 672 673
        break;
      }
    } while(1);
    size.cy = *pAscent + *pDescent;
    return size;
  }
674 675
  if (run->nFlags & MERF_GRAPHICS)
  {
676
    ME_GetOLEObjectSize(c, run, &size);
677 678 679
    if (size.cy > *pAscent)
      *pAscent = size.cy;
    /* descent is unchanged */
680 681 682 683 684
    return size;
  }
  return size;
}

685 686
/******************************************************************************
 * ME_SetSelectionCharFormat
687
 *
688 689
 * Applies a style change, either to a current selection, or to insert cursor
 * (ie. the style next typed characters will use).
690
 */
691 692
void ME_SetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
{
693
  if (!ME_IsSelection(editor))
694 695 696 697
  {
    ME_Style *s;
    if (!editor->pBuffer->pCharStyle)
      editor->pBuffer->pCharStyle = ME_GetInsertStyle(editor, 0);
698
    s = ME_ApplyStyle(editor, editor->pBuffer->pCharStyle, pFmt);
699 700
    ME_ReleaseStyle(editor->pBuffer->pCharStyle);
    editor->pBuffer->pCharStyle = s;
701 702 703 704
  } else {
    ME_Cursor *from, *to;
    ME_GetSelection(editor, &from, &to);
    ME_SetCharFormat(editor, from, to, pFmt);
705 706 707
  }
}

708 709
/******************************************************************************
 * ME_SetCharFormat
710
 *
711
 * Applies a style change to the specified part of the text
712 713 714 715 716 717 718 719 720
 *
 * The start and end cursors specify the part of the text.  These cursors will
 * be updated to stay valid, but this function may invalidate other
 * non-selection cursors. The end cursor may be NULL to specify all the text
 * following the start cursor.
 *
 * If no text is selected, then nothing is done.
 */
void ME_SetCharFormat(ME_TextEditor *editor, ME_Cursor *start, ME_Cursor *end, CHARFORMAT2W *pFmt)
721
{
722
  ME_DisplayItem *run, *start_run = start->pRun, *end_run = NULL;
723

724 725
  if (end && start->pRun == end->pRun && start->nOffset == end->nOffset)
    return;
726

727 728 729
  if (start->nOffset == start->pRun->member.run.len)
    start_run = ME_FindItemFwd( start->pRun, diRun );
  else if (start->nOffset)
730 731 732 733
  {
    /* SplitRunSimple may or may not update the cursors, depending on whether they
     * are selection cursors, but we need to make sure they are valid. */
    int split_offset = start->nOffset;
734
    ME_DisplayItem *split_run = ME_SplitRunSimple(editor, start);
735
    start_run = start->pRun;
736 737 738 739 740 741 742
    if (end && end->pRun == split_run)
    {
      end->pRun = start->pRun;
      end->nOffset -= split_offset;
    }
  }

743 744 745 746 747 748 749 750 751 752
  if (end)
  {
    if (end->nOffset == end->pRun->member.run.len)
      end_run = ME_FindItemFwd( end->pRun, diRun );
    else
    {
      if (end->nOffset) ME_SplitRunSimple(editor, end);
      end_run = end->pRun;
    }
  }
753

754
  for (run = start_run; run != end_run; run = ME_FindItemFwd( run, diRun ))
755
  {
756
    ME_Style *new_style = ME_ApplyStyle(editor, run->member.run.style, pFmt);
757

758
    add_undo_set_char_fmt( editor, run->member.run.para->nCharOfs + run->member.run.nCharOfs,
759
                           run->member.run.len, &run->member.run.style->fmt );
760
    ME_ReleaseStyle(run->member.run.style);
761
    run->member.run.style = new_style;
762
    run->member.run.para->nFlags |= MEPF_REWRAP;
763 764 765
  }
}

766
static void ME_GetRunCharFormat(ME_TextEditor *editor, ME_DisplayItem *run, CHARFORMAT2W *pFmt)
767 768
{
  ME_CopyCharFormat(pFmt, &run->member.run.style->fmt);
769 770 771 772 773 774 775 776 777 778
  if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_CF1UNDERLINE))
  {
    pFmt->dwMask |= CFM_UNDERLINE;
    pFmt->dwEffects |= CFE_UNDERLINE;
  }
  if ((pFmt->dwMask & CFM_UNDERLINETYPE) && (pFmt->bUnderlineType == CFU_UNDERLINENONE))
  {
    pFmt->dwMask |= CFM_UNDERLINE;
    pFmt->dwEffects &= ~CFE_UNDERLINE;
  }
779 780
}

781 782 783 784 785 786
/******************************************************************************
 * ME_GetDefaultCharFormat
 * 
 * Retrieves the current default character style (the one applied where no
 * other style was applied) .
 */     
787 788 789 790 791
void ME_GetDefaultCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
{
  ME_CopyCharFormat(pFmt, &editor->pBuffer->pDefaultStyle->fmt);
}

792 793
/******************************************************************************
 * ME_GetSelectionCharFormat
794
 *
795
 * If selection exists, it returns all style elements that are set consistently
796 797
 * in the whole selection. If not, it just returns the current style.
 */
798 799
void ME_GetSelectionCharFormat(ME_TextEditor *editor, CHARFORMAT2W *pFmt)
{
800 801
  ME_Cursor *from, *to;
  if (!ME_IsSelection(editor) && editor->pBuffer->pCharStyle)
802 803 804 805
  {
    ME_CopyCharFormat(pFmt, &editor->pBuffer->pCharStyle->fmt);
    return;
  }
806 807
  ME_GetSelection(editor, &from, &to);
  ME_GetCharFormat(editor, from, to, pFmt);
808 809
}

810 811
/******************************************************************************
 * ME_GetCharFormat
812
 *
813
 * Returns the style consisting of those attributes which are consistently set
814 815
 * in the whole character range.
 */
816 817
void ME_GetCharFormat(ME_TextEditor *editor, const ME_Cursor *from,
                      const ME_Cursor *to, CHARFORMAT2W *pFmt)
818 819 820
{
  ME_DisplayItem *run, *run_end;
  CHARFORMAT2W tmp;
821

822 823 824
  run = from->pRun;
  /* special case - if selection is empty, take previous char's formatting */
  if (from->pRun == to->pRun && from->nOffset == to->nOffset)
825
  {
826
    if (!from->nOffset)
827 828 829 830 831 832 833 834 835 836
    {
      ME_DisplayItem *tmp_run = ME_FindItemBack(run, diRunOrParagraph);
      if (tmp_run->type == diRun) {
        ME_GetRunCharFormat(editor, tmp_run, pFmt);
        return;
      }
    }
    ME_GetRunCharFormat(editor, run, pFmt);
    return;
  }
837 838 839 840

  run_end = to->pRun;
  if (!to->nOffset)
    run_end = ME_FindItemBack(run_end, diRun);
841

842
  ME_GetRunCharFormat(editor, run, pFmt);
843

844
  if (run == run_end) return;
845

846 847
  do {
    /* FIXME add more style feature comparisons */
848 849
    DWORD dwAttribs = CFM_SIZE | CFM_FACE | CFM_COLOR | CFM_UNDERLINETYPE;
    DWORD dwEffects = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE | CFM_STRIKEOUT | CFM_PROTECTED | CFM_LINK | CFM_SUPERSCRIPT;
850 851

    run = ME_FindItemFwd(run, diRun);
852

853 854 855
    ZeroMemory(&tmp, sizeof(tmp));
    tmp.cbSize = sizeof(tmp);
    ME_GetRunCharFormat(editor, run, &tmp);
856

857
    assert((tmp.dwMask & dwAttribs) == dwAttribs);
858 859 860 861 862 863 864 865
    /* reset flags that differ */

    if (pFmt->yHeight != tmp.yHeight)
      pFmt->dwMask &= ~CFM_SIZE;
    if (pFmt->dwMask & CFM_FACE)
    {
      if (!(tmp.dwMask & CFM_FACE))
        pFmt->dwMask &= ~CFM_FACE;
866 867
      else if (lstrcmpW(pFmt->szFaceName, tmp.szFaceName) ||
          pFmt->bPitchAndFamily != tmp.bPitchAndFamily)
868 869 870 871
        pFmt->dwMask &= ~CFM_FACE;
    }
    if (pFmt->yHeight != tmp.yHeight)
      pFmt->dwMask &= ~CFM_SIZE;
872 873
    if (pFmt->bUnderlineType != tmp.bUnderlineType)
      pFmt->dwMask &= ~CFM_UNDERLINETYPE;
874 875 876 877 878 879 880 881
    if (pFmt->dwMask & CFM_COLOR)
    {
      if (!((pFmt->dwEffects&CFE_AUTOCOLOR) & (tmp.dwEffects&CFE_AUTOCOLOR)))
      {
        if (pFmt->crTextColor != tmp.crTextColor)
          pFmt->dwMask &= ~CFM_COLOR;
      }
    }
882

883
    pFmt->dwMask &= ~((pFmt->dwEffects ^ tmp.dwEffects) & dwEffects);
884
    pFmt->dwEffects = tmp.dwEffects;
885

886 887
  } while(run != run_end);
}