TextOutputDev.cc 30.4 KB
Newer Older
1 2 3 4 5 6 7 8
//========================================================================
//
// TextOutputDev.cc
//
// Copyright 1997-2002 Glyph & Cog, LLC
//
//========================================================================

Wilco Greven's avatar
Wilco Greven committed
9 10 11
#include <aconf.h>

#ifdef USE_GCC_PRAGMAS
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#pragma implementation
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <math.h>
#include <ctype.h>
#include "GString.h"
#include "gmem.h"
#include "config.h"
#include "Error.h"
#include "GlobalParams.h"
#include "UnicodeMap.h"
#include "GfxState.h"
#include "TextOutputDev.h"

#ifdef MACOS
// needed for setting type/creator of MacOS files
#include "ICSupport.h"
#endif

Wilco Greven's avatar
Wilco Greven committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
//------------------------------------------------------------------------

#define textOutSpace    0.2
#define textOutColSpace 0.2

//------------------------------------------------------------------------

struct TextOutColumnEdge {
  double x, y0, y1;
};

//------------------------------------------------------------------------
// TextBlock
//------------------------------------------------------------------------

class TextBlock {
public:

  TextBlock();
  ~TextBlock();

  double xMin, xMax;
  double yMin, yMax;
  TextString *strings;		// list of strings in the block
  TextBlock *next;		// next block in line
  TextBlock *xyNext;		// next block on xyBlocks list
  Unicode *text;		// Unicode text of the block, including
				//   spaces between strings
  double *xRight;		// right-hand x coord of each char
  int len;			// total number of Unicode characters
  int convertedLen;		// total number of converted characters
  int *col;			// starting column number for each
				//   Unicode character
};

TextBlock::TextBlock() {
  strings = NULL;
  next = NULL;
  xyNext = NULL;
  text = NULL;
  xRight = NULL;
  col = NULL;
}

TextBlock::~TextBlock() {
  TextString *p1, *p2;

  for (p1 = strings; p1; p1 = p2) {
    p2 = p1->next;
    delete p1;
  }
  gfree(text);
  gfree(xRight);
  gfree(col);
}

//------------------------------------------------------------------------
// TextLine
//------------------------------------------------------------------------

class TextLine {
public:

  TextLine();
  ~TextLine();

  TextBlock *blocks;
  TextLine *next;
  double yMin, yMax;
};

TextLine::TextLine() {
  blocks = NULL;
  next = NULL;
}

TextLine::~TextLine() {
  TextBlock *p1, *p2;

  for (p1 = blocks; p1; p1 = p2) {
    p2 = p1->next;
    delete p1;
  }
}

119 120 121 122
//------------------------------------------------------------------------
// TextString
//------------------------------------------------------------------------

Wilco Greven's avatar
Wilco Greven committed
123 124
TextString::TextString(GfxState *state, double x0, double y0,
		       double fontSize) {
125 126 127
  GfxFont *font;
  double x, y;

Wilco Greven's avatar
Wilco Greven committed
128
  state->transform(x0, y0, &x, &y);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  if ((font = state->getFont())) {
    yMin = y - font->getAscent() * fontSize;
    yMax = y - font->getDescent() * fontSize;
  } else {
    // this means that the PDF file draws text without a current font,
    // which should never happen
    yMin = y - 0.95 * fontSize;
    yMax = y + 0.35 * fontSize;
  }
  if (yMin == yMax) {
    // this is a sanity check for a case that shouldn't happen -- but
    // if it does happen, we want to avoid dividing by zero later
    yMin = y;
    yMax = y + 1;
  }
Wilco Greven's avatar
Wilco Greven committed
144
  marked = gFalse;
145 146 147
  text = NULL;
  xRight = NULL;
  len = size = 0;
Wilco Greven's avatar
Wilco Greven committed
148
  next = NULL;
149 150
}

Wilco Greven's avatar
Wilco Greven committed
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
TextString::~TextString() {
  gfree(text);
  gfree(xRight);
}

void TextString::addChar(GfxState *state, double x, double y,
			 double dx, double dy, Unicode u) {
  if (len == size) {
    size += 16;
    text = (Unicode *)grealloc(text, size * sizeof(Unicode));
    xRight = (double *)grealloc(xRight, size * sizeof(double));
  }
  text[len] = u;
  if (len == 0) {
    xMin = x;
  }
  xMax = xRight[len] = x + dx;
  ++len;
}

//------------------------------------------------------------------------
// TextPage
//------------------------------------------------------------------------

TextPage::TextPage(GBool rawOrderA) {
  rawOrder = rawOrderA;
  curStr = NULL;
  fontSize = 0;
  xyStrings = NULL;
Wilco Greven's avatar
Wilco Greven committed
181 182
  xyCur1 = xyCur2 = NULL;
  lines = NULL;
183
  nest = 0;
Wilco Greven's avatar
Wilco Greven committed
184
  nTinyChars = 0;
185 186 187 188 189 190 191 192 193 194
}

TextPage::~TextPage() {
  clear();
}

void TextPage::updateFont(GfxState *state) {
  GfxFont *font;
  double *fm;
  char *name;
Wilco Greven's avatar
Wilco Greven committed
195
  int code, mCode, letterCode, anyCode;
196 197 198 199 200 201 202 203 204 205 206
  double w;

  // adjust the font size
  fontSize = state->getTransformedFontSize();
  if ((font = state->getFont()) && font->getType() == fontType3) {
    // This is a hack which makes it possible to deal with some Type 3
    // fonts.  The problem is that it's impossible to know what the
    // base coordinate system used in the font is without actually
    // rendering the font.  This code tries to guess by looking at the
    // width of the character 'm' (which breaks if the font is a
    // subset that doesn't contain 'm').
Wilco Greven's avatar
Wilco Greven committed
207
    mCode = letterCode = anyCode = -1;
208
    for (code = 0; code < 256; ++code) {
Wilco Greven's avatar
Wilco Greven committed
209 210 211 212 213 214 215 216 217 218 219
      name = ((Gfx8BitFont *)font)->getCharName(code);
      if (name && name[0] == 'm' && name[1] == '\0') {
	mCode = code;
      }
      if (letterCode < 0 && name && name[1] == '\0' &&
	  ((name[0] >= 'A' && name[0] <= 'Z') ||
	   (name[0] >= 'a' && name[0] <= 'z'))) {
	letterCode = code;
      }
      if (anyCode < 0 && name && ((Gfx8BitFont *)font)->getWidth(code) > 0) {
	anyCode = code;
220 221
      }
    }
Wilco Greven's avatar
Wilco Greven committed
222 223 224
    if (mCode >= 0 &&
	(w = ((Gfx8BitFont *)font)->getWidth(mCode)) > 0) {
      // 0.6 is a generic average 'm' width -- yes, this is a hack
225
	fontSize *= w / 0.6;
Wilco Greven's avatar
Wilco Greven committed
226 227 228 229 230 231 232 233
    } else if (letterCode >= 0 &&
	       (w = ((Gfx8BitFont *)font)->getWidth(letterCode)) > 0) {
      // even more of a hack: 0.5 is a generic letter width
      fontSize *= w / 0.5;
    } else if (anyCode >= 0 &&
	       (w = ((Gfx8BitFont *)font)->getWidth(anyCode)) > 0) {
      // better than nothing: 0.5 is a generic character width
      fontSize *= w / 0.5;
234 235 236 237 238 239 240 241
    }
    fm = font->getFontMatrix();
    if (fm[0] != 0) {
      fontSize *= fabs(fm[3] / fm[0]);
    }
  }
}

Wilco Greven's avatar
Wilco Greven committed
242
void TextPage::beginString(GfxState *state, double x0, double y0) {
243 244 245 246 247 248 249
  // This check is needed because Type 3 characters can contain
  // text-drawing operations.
  if (curStr) {
    ++nest;
    return;
  }

Wilco Greven's avatar
Wilco Greven committed
250
  curStr = new TextString(state, x0, y0, fontSize);
251 252 253 254
}

void TextPage::addChar(GfxState *state, double x, double y,
		       double dx, double dy, Unicode *u, int uLen) {
255 256
    if (! curStr) return;

257 258 259 260
  double x1, y1, w1, h1, dx2, dy2;
  int n, i;

  state->transform(x, y, &x1, &y1);
Wilco Greven's avatar
Wilco Greven committed
261 262 263
  if (x1 < 0 || x1 > state->getPageWidth() ||
      y1 < 0 || y1 > state->getPageHeight()) {
    return;
264 265 266 267 268 269
  }
  state->textTransformDelta(state->getCharSpace() * state->getHorizScaling(),
			    0, &dx2, &dy2);
  dx -= dx2;
  dy -= dy2;
  state->transformDelta(dx, dy, &w1, &h1);
Wilco Greven's avatar
Wilco Greven committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  if (!globalParams->getTextKeepTinyChars() &&
      fabs(w1) < 3 && fabs(h1) < 3) {
    if (++nTinyChars > 20000) {
      return;
    }
  }
  n = curStr->len;
  if (n > 0 && x1 - curStr->xRight[n-1] >
               0.1 * (curStr->yMax - curStr->yMin)) {
    // large char spacing is sometimes used to move text around
    endString();
    beginString(state, x, y);
  }
  if (uLen == 1 && u[0] == (Unicode)0x20 &&
      w1 > 0.5 * (curStr->yMax - curStr->yMin)) {
    // large word spacing is sometimes used to move text around
    return;
  }
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  if (uLen != 0) {
    w1 /= uLen;
    h1 /= uLen;
  }
  for (i = 0; i < uLen; ++i) {
    curStr->addChar(state, x1 + i*w1, y1 + i*h1, w1, h1, u[i]);
  }
}

void TextPage::endString() {
  // This check is needed because Type 3 characters can contain
  // text-drawing operations.
  if (nest > 0) {
    --nest;
    return;
  }

Wilco Greven's avatar
Wilco Greven committed
305 306 307 308 309
  addString(curStr);
  curStr = NULL;
}

void TextPage::addString(TextString *str) {
310 311
    if (! str) return;

Wilco Greven's avatar
Wilco Greven committed
312 313
  TextString *p1, *p2;

314 315
  // throw away zero-length strings -- they don't have valid xMin/xMax
  // values, and they're useless anyway
Wilco Greven's avatar
Wilco Greven committed
316 317
  if (str->len == 0) {
    delete str;
318 319 320
    return;
  }

Wilco Greven's avatar
Wilco Greven committed
321
  // insert string in xy list
322
  if (rawOrder) {
Wilco Greven's avatar
Wilco Greven committed
323
    p1 = xyCur1;
324
    p2 = NULL;
Wilco Greven's avatar
Wilco Greven committed
325 326 327 328 329 330 331 332 333 334 335
  } else if ((!xyCur1 || xyBefore(xyCur1, str)) &&
	     (!xyCur2 || xyBefore(str, xyCur2))) {
    p1 = xyCur1;
    p2 = xyCur2;
  } else if (xyCur1 && xyBefore(xyCur1, str)) {
    for (p1 = xyCur1, p2 = xyCur2; p2; p1 = p2, p2 = p2->next) {
      if (xyBefore(str, p2)) {
	break;
      }
    }
    xyCur2 = p2;
336
  } else {
Wilco Greven's avatar
Wilco Greven committed
337 338
    for (p1 = NULL, p2 = xyStrings; p2; p1 = p2, p2 = p2->next) {
      if (xyBefore(str, p2)) {
339 340 341
	break;
      }
    }
Wilco Greven's avatar
Wilco Greven committed
342
    xyCur2 = p2;
343
  }
Wilco Greven's avatar
Wilco Greven committed
344
  xyCur1 = str;
345
  if (p1) {
Wilco Greven's avatar
Wilco Greven committed
346
    p1->next = str;
347
  } else {
Wilco Greven's avatar
Wilco Greven committed
348
    xyStrings = str;
349
  }
Wilco Greven's avatar
Wilco Greven committed
350
  str->next = p2;
351 352 353
}

void TextPage::coalesce() {
Wilco Greven's avatar
Wilco Greven committed
354 355 356 357 358 359 360 361 362 363 364 365 366
  TextLine *line, *line0;
  TextBlock *yxBlocks, *xyBlocks, *blk, *blk0, *blk1, *blk2;
  TextString *str0, *str1, *str2, *str3, *str4;
  TextString *str1prev, *str2prev, *str3prev;
  TextOutColumnEdge *edges;
  UnicodeMap *uMap;
  GBool isUnicode;
  char buf[8];
  int edgesLength, edgesSize;
  double x, yMin, yMax;
  double space, fit1, fit2, h;
  int col1, col2, d;
  int i, j;
367 368

#if 0 //~ for debugging
Wilco Greven's avatar
Wilco Greven committed
369 370 371 372
  for (str1 = xyStrings; str1; str1 = str1->next) {
    printf("x=%.2f..%.2f  y=%.2f..%.2f  size=%.2f '",
	   str1->xMin, str1->xMax, str1->yMin, str1->yMax,
	   (str1->yMax - str1->yMin));
373 374 375 376 377 378 379
    for (i = 0; i < str1->len; ++i) {
      fputc(str1->text[i] & 0xff, stdout);
    }
    printf("'\n");
  }
  printf("\n------------------------------------------------------------\n\n");
#endif
Wilco Greven's avatar
Wilco Greven committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709

  // build the list of column edges
  edges = NULL;
  edgesLength = edgesSize = 0;
  if (!rawOrder) {
    for (str1prev = NULL, str1 = xyStrings;
	 str1;
	 str1prev = str1, str1 = str1->next) {
      if (str1->marked) {
	continue;
      }
      h = str1->yMax - str1->yMin;
      if (str1prev && (str1->xMin - str1prev->xMax) / h < textOutColSpace) {
	continue;
      }
      x = str1->xMin;
      yMin = str1->yMin;
      yMax = str1->yMax;
      for (str2prev = str1, str2 = str1->next;
	   str2;
	   str2prev = str2, str2 = str2->next) {
	h = str2->yMax - str2->yMin;
	if (!str2->marked &&
	    (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
	    fabs(str2->xMin - x) < 0.5 &&
	    str2->yMin - yMax < 0.3 * h &&
	    yMin - str2->yMax < 0.3 * h) {
	  break;
	}
      }
      if (str2) {
	if (str2->yMin < yMin) {
	  yMin = str2->yMin;
	}
	if (str2->yMax > yMax) {
	  yMax = str2->yMax;
	}
	str2->marked = gTrue;
	for (str3prev = str1, str3 = str1->next;
	     str3;
	     str3prev = str3, str3 = str3->next) {
	  h = str3->yMax - str3->yMin;
	  if (!str3->marked &&
	      (str3->xMin - str3prev->xMax) / h > textOutColSpace &&
	      fabs(str3->xMin - x) < 0.5 &&
	      str3->yMin - yMax < 0.3 * h &&
	      yMin - str3->yMax < 0.3 * h) {
	    break;
	  }
	}
	if (str3) {
	  if (str3->yMin < yMin) {
	    yMin = str3->yMin;
	  }
	  if (str3->yMax > yMax) {
	    yMax = str3->yMax;
	  }
	  str3->marked = gTrue;
	  do {
	    for (str2prev = str1, str2 = str1->next;
		 str2;
		 str2prev = str2, str2 = str2->next) {
	      h = str2->yMax - str2->yMin;
	      if (!str2->marked &&
		  (str2->xMin - str2prev->xMax) / h > textOutColSpace &&
		  fabs(str2->xMin - x) < 0.5 &&
		  str2->yMin - yMax < 0.3 * h &&
		  yMin - str2->yMax < 0.3 * h) {
		if (str2->yMin < yMin) {
		  yMin = str2->yMin;
		}
		if (str2->yMax > yMax) {
		  yMax = str2->yMax;
		}
		str2->marked = gTrue;
		break;
	      }
	    }
	  } while (str2);
	  if (edgesLength == edgesSize) {
	    edgesSize = edgesSize ? 2 * edgesSize : 16;
	    edges = (TextOutColumnEdge *)
	      grealloc(edges, edgesSize * sizeof(TextOutColumnEdge));
	  }
	  edges[edgesLength].x = x;
	  edges[edgesLength].y0 = yMin;
	  edges[edgesLength].y1 = yMax;
	  ++edgesLength;
	} else {
	  str2->marked = gFalse;
	}
      }
      str1->marked = gTrue;
    }
  }

#if 0 //~ for debugging
  printf("column edges:\n");
  for (i = 0; i < edgesLength; ++i) {
    printf("%d: x=%.2f y0=%.2f y1=%.2f\n",
	   i, edges[i].x, edges[i].y0, edges[i].y1);
  }
  printf("\n------------------------------------------------------------\n\n");
#endif

  // build the blocks
  yxBlocks = NULL;
  blk1 = blk2 = NULL;
  while (xyStrings) {

    // build the block
    str0 = xyStrings;
    xyStrings = xyStrings->next;
    str0->next = NULL;
    blk = new TextBlock();
    blk->strings = str0;
    blk->xMin = str0->xMin;
    blk->xMax = str0->xMax;
    blk->yMin = str0->yMin;
    blk->yMax = str0->yMax;
    while (xyStrings) {
      str1 = NULL;
      str2 = xyStrings;
      fit1 = coalesceFit(str0, str2);
      if (!rawOrder) {
	// look for best-fitting string
	space = str0->yMax - str0->yMin;
	for (str3 = xyStrings, str4 = xyStrings->next;
	     str4 && str4->xMin - str0->xMax <= space;
	     str3 = str4, str4 = str4->next) {
	  fit2 = coalesceFit(str0, str4);
	  if (fit2 < fit1) {
	    str1 = str3;
	    str2 = str4;
	    fit1 = fit2;
	  }
	}
      }
      if (fit1 > 1) {
	// no fit - we're done with this block
	break;
      }

      // if we've hit a column edge we're done with this block
      if (fit1 > 0.2) {
	for (i = 0; i < edgesLength; ++i) {
	  if (str0->xMax < edges[i].x + 0.5 && edges[i].x - 0.5 < str2->xMin &&
	      str0->yMin < edges[i].y1 && str0->yMax > edges[i].y0 &&
	      str2->yMin < edges[i].y1 && str2->yMax > edges[i].y0) {
	    break;
	  }
	}
	if (i < edgesLength) {
	  break;
	}
      }

      if (str1) {
	str1->next = str2->next;
      } else {
	xyStrings = str2->next;
      }
      str0->next = str2;
      str2->next = NULL;
      if (str2->xMax > blk->xMax) {
	blk->xMax = str2->xMax;
      }
      if (str2->yMin < blk->yMin) {
	blk->yMin = str2->yMin;
      }
      if (str2->yMax > blk->yMax) {
	blk->yMax = str2->yMax;
      }
      str0 = str2;
    }

    // insert block on list
    if (!rawOrder) {
      // insert block on list in yx order
      for (blk1 = NULL, blk2 = yxBlocks;
	   blk2 && !yxBefore(blk, blk2);
	   blk1 = blk2, blk2 = blk2->next) ;
    }
    blk->next = blk2;
    if (blk1) {
      blk1->next = blk;
    } else {
      yxBlocks = blk;
    }
    blk1 = blk;
  }

  gfree(edges);

  // the strings are now owned by the lines/blocks tree
  xyStrings = NULL;

  // build the block text
  uMap = globalParams->getTextEncoding();
  isUnicode = uMap ? uMap->isUnicode() : gFalse;
  for (blk = yxBlocks; blk; blk = blk->next) {
    blk->len = 0;
    for (str1 = blk->strings; str1; str1 = str1->next) {
      blk->len += str1->len;
      if (str1->next && str1->next->xMin - str1->xMax >
	                textOutSpace * (str1->yMax - str1->yMin)) {
	str1->spaceAfter = gTrue;
	++blk->len;
      } else {
	str1->spaceAfter = gFalse;
      }
    }
    blk->text = (Unicode *)gmalloc(blk->len * sizeof(Unicode));
    blk->xRight = (double *)gmalloc(blk->len * sizeof(double));
    blk->col = (int *)gmalloc(blk->len * sizeof(int));
    i = 0;
    for (str1 = blk->strings; str1; str1 = str1->next) {
      for (j = 0; j < str1->len; ++j) {
	blk->text[i] = str1->text[j];
	blk->xRight[i] = str1->xRight[j];
	++i;
      }
      if (str1->spaceAfter) {
	blk->text[i] = (Unicode)0x0020;
	blk->xRight[i] = str1->next->xMin;
	++i;
      }
    }
    blk->convertedLen = 0;
    for (j = 0; j < blk->len; ++j) {
      blk->col[j] = blk->convertedLen;
      if (isUnicode) {
	++blk->convertedLen;
      } else if (uMap) {
	blk->convertedLen += uMap->mapUnicode(blk->text[j], buf, sizeof(buf));
      }
    }
  }
  if (uMap) {
    uMap->decRefCnt();
  }

#if 0 //~ for debugging
  for (blk = yxBlocks; blk; blk = blk->next) {
    printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
	   blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
    TextString *str;
    for (str = blk->strings; str; str = str->next) {
      printf("    x=%.2f..%.2f  y=%.2f..%.2f  size=%.2f'",
	     str->xMin, str->xMax, str->yMin, str->yMax,
	     (str->yMax - str->yMin));
      for (i = 0; i < str->len; ++i) {
	fputc(str->text[i] & 0xff, stdout);
      }
      if (str->spaceAfter) {
	fputc(' ', stdout);
      }
      printf("'\n");
    }
  }
  printf("\n------------------------------------------------------------\n\n");
#endif

  // build the lines
  lines = NULL;
  line0 = NULL;
  while (yxBlocks) {
    blk0 = yxBlocks;
    yxBlocks = yxBlocks->next;
    blk0->next = NULL;
    line = new TextLine();
    line->blocks = blk0;
    line->yMin = blk0->yMin;
    line->yMax = blk0->yMax;
    while (yxBlocks) {

      // remove duplicated text (fake boldface, shadowed text)
      h = blk0->yMax - blk0->yMin;
      if (yxBlocks->len == blk0->len &&
	  !memcmp(yxBlocks->text, blk0->text,
		  yxBlocks->len * sizeof(Unicode)) &&
	  fabs(yxBlocks->yMin - blk0->yMin) / h < 0.2 &&
	  fabs(yxBlocks->yMax - blk0->yMax) / h < 0.2 &&
	  fabs(yxBlocks->xMin - blk0->xMin) / h < 0.2 &&
	  fabs(yxBlocks->xMax - blk0->xMax) / h < 0.2) {
	blk1 = yxBlocks;
	yxBlocks = yxBlocks->next;
	delete blk1;
	continue;
      }

      if (rawOrder && yxBlocks->yMax < blk0->yMin) {
	break;
      }
      if (yxBlocks->yMin > 0.2*blk0->yMin + 0.8*blk0->yMax ||
	  yxBlocks->xMin < blk0->xMax) {
	break;
      }
      blk1 = yxBlocks;
      yxBlocks = yxBlocks->next;
      blk0->next = blk1;
      blk1->next = NULL;
      if (blk1->yMin < line->yMin) {
	line->yMin = blk1->yMin;
      }
      if (blk1->yMax > line->yMax) {
	line->yMax = blk1->yMax;
      }
      blk0 = blk1;
      }
    if (line0) {
      line0->next = line;
    } else {
      lines = line;
    }
    line->next = NULL;
    line0 = line;
      }


  // sort the blocks into xy order
  xyBlocks = NULL;
  for (line = lines; line; line = line->next) {
    for (blk = line->blocks; blk; blk = blk->next) {
      for (blk1 = NULL, blk2 = xyBlocks;
	   blk2 && !xyBefore(blk, blk2);
	   blk1 = blk2, blk2 = blk2->xyNext) ;
      blk->xyNext = blk2;
      if (blk1) {
	blk1->xyNext = blk;
710
    } else {
Wilco Greven's avatar
Wilco Greven committed
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	xyBlocks = blk;
      }
    }
  }

#if 0 //~ for debugging
  for (blk = xyBlocks; blk; blk = blk->xyNext) {
    printf("[block: x=%.2f..%.2f y=%.2f..%.2f len=%d]\n",
	   blk->xMin, blk->xMax, blk->yMin, blk->yMax, blk->len);
    TextString *str;
    for (str = blk->strings; str; str = str->next) {
      printf("    x=%.2f..%.2f  y=%.2f..%.2f  size=%.2f '",
	     str->xMin, str->xMax, str->yMin, str->yMax,
	     (str->yMax - str->yMin));
      for (i = 0; i < str->len; ++i) {
	fputc(str->text[i] & 0xff, stdout);
      }
      printf("'\n");
    }
  }
  printf("\n------------------------------------------------------------\n\n");
#endif

  // do column assignment
  for (blk1 = xyBlocks; blk1; blk1 = blk1->xyNext) {
    col1 = 0;
    for (blk2 = xyBlocks; blk2 != blk1; blk2 = blk2->xyNext) {
      if (blk1->xMin >= blk2->xMax) {
	d = (int)((blk1->xMin - blk2->xMax) /
		  (0.4 * (blk1->yMax - blk1->yMin)));
	if (d > 4) {
	  d = 4;
	}
	col2 = blk2->col[0] + blk2->convertedLen + d;
	if (col2 > col1) {
	  col1 = col2;
	}
      } else if (blk1->xMin > blk2->xMin) {
	for (i = 0; i < blk2->len && blk1->xMin >= blk2->xRight[i]; ++i) ;
	col2 = blk2->col[i];
	if (col2 > col1) {
	  col1 = col2;
	}
      }
    }
    for (j = 0; j < blk1->len; ++j) {
      blk1->col[j] += col1;
758 759
    }
  }
Wilco Greven's avatar
Wilco Greven committed
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

#if 0 //~ for debugging
  for (line = lines; line; line = line->next) {
    printf("[line]\n");
    for (blk = line->blocks; blk; blk = blk->next) {
      printf("[block: col=%d, len=%d]\n", blk->col[0], blk->len);
      TextString *str;
      for (str = blk->strings; str; str = str->next) {
	printf("    x=%.2f..%.2f  y=%.2f..%.2f  size=%.2f '",
	       str->xMin, str->xMax, str->yMin, str->yMax,
	       (str->yMax - str->yMin));
	for (i = 0; i < str->len; ++i) {
	  fputc(str->text[i] & 0xff, stdout);
	}
	if (str->spaceAfter) {
	  printf(" [space]\n");
	}
	printf("'\n");
      }
    }
  }
  printf("\n------------------------------------------------------------\n\n");
#endif
783 784
}

Wilco Greven's avatar
Wilco Greven committed
785

786 787 788 789
GBool TextPage::findText(Unicode *s, int len,
			 GBool top, GBool bottom,
			 double *xMin, double *yMin,
			 double *xMax, double *yMax) {
Wilco Greven's avatar
Wilco Greven committed
790 791
  TextLine *line;
  TextBlock *blk;
792 793 794
  Unicode *p;
  Unicode u1, u2;
  int m, i, j;
Wilco Greven's avatar
Wilco Greven committed
795
  double x0, x1, x;
796

Wilco Greven's avatar
Wilco Greven committed
797 798 799
  // scan all blocks on page
  for (line = lines; line; line = line->next) {
    for (blk = line->blocks; blk; blk = blk->next) {
800 801

    // check: above top limit?
Wilco Greven's avatar
Wilco Greven committed
802 803
      if (!top && (blk->yMax < *yMin ||
		   (blk->yMin < *yMin && blk->xMax <= *xMin))) {
804 805 806 807
      continue;
    }

    // check: below bottom limit?
Wilco Greven's avatar
Wilco Greven committed
808 809
      if (!bottom && (blk->yMin > *yMax ||
		      (blk->yMax > *yMax && blk->xMin >= *xMax))) {
810 811 812
      return gFalse;
    }

Wilco Greven's avatar
Wilco Greven committed
813 814 815 816 817 818 819
      // search each position in this block
      m = blk->len;
      for (i = 0, p = blk->text; i <= m - len; ++i, ++p) {

	x0 = (i == 0) ? blk->xMin : blk->xRight[i-1];
	x1 = blk->xRight[i];
	x = 0.5 * (x0 + x1);
820 821

      // check: above top limit?
Wilco Greven's avatar
Wilco Greven committed
822
	if (!top && blk->yMin < *yMin) {
823 824 825 826 827 828
	if (x < *xMin) {
	  continue;
	}
      }

      // check: below bottom limit?
Wilco Greven's avatar
Wilco Greven committed
829
	if (!bottom && blk->yMax > *yMax) {
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
	if (x > *xMax) {
	  return gFalse;
	}
      }

      // compare the strings
      for (j = 0; j < len; ++j) {
#if 1 //~ this lowercases Latin A-Z only -- this will eventually be
      //~ extended to handle other character sets
	if (p[j] >= 0x41 && p[j] <= 0x5a) {
	  u1 = p[j] + 0x20;
	} else {
	  u1 = p[j];
	}
	if (s[j] >= 0x41 && s[j] <= 0x5a) {
	  u2 = s[j] + 0x20;
	} else {
	  u2 = s[j];
	}
#endif
	if (u1 != u2) {
	  break;
	}
      }

      // found it
      if (j == len) {
Wilco Greven's avatar
Wilco Greven committed
857 858 859 860
	  *xMin = x0;
	  *xMax = blk->xRight[i + len - 1];
	  *yMin = blk->yMin;
	  *yMax = blk->yMax;
861 862 863 864
	return gTrue;
      }
    }
  }
Wilco Greven's avatar
Wilco Greven committed
865 866
  }

867 868 869 870 871 872 873
  return gFalse;
}

GString *TextPage::getText(double xMin, double yMin,
			   double xMax, double yMax) {
  GString *s;
  UnicodeMap *uMap;
Wilco Greven's avatar
Wilco Greven committed
874
  GBool isUnicode;
875
  char space[8], eol[16], buf[8];
Wilco Greven's avatar
Wilco Greven committed
876 877 878 879 880
  int spaceLen, eolLen, len;
  TextLine *line;
  TextBlock *blk;
  double x0, x1, y;
  int firstCol, col, i;
881 882 883
  GBool multiLine;

  s = new GString();
Wilco Greven's avatar
Wilco Greven committed
884 885

  // get the output encoding
886 887 888
  if (!(uMap = globalParams->getTextEncoding())) {
    return s;
  }
Wilco Greven's avatar
Wilco Greven committed
889
  isUnicode = uMap->isUnicode();
890 891 892 893 894 895 896 897 898 899 900 901 902 903
  spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
  eolLen = 0; // make gcc happy
  switch (globalParams->getTextEOL()) {
  case eolUnix:
    eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
    break;
  case eolDOS:
    eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
    eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
    break;
  case eolMac:
    eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
    break;
  }
Wilco Greven's avatar
Wilco Greven committed
904 905

  // find the leftmost column
906
  multiLine = gFalse;
Wilco Greven's avatar
Wilco Greven committed
907 908 909
  firstCol = -1;
  for (line = lines; line; line = line->next) {
    if (line->yMin > yMax) {
910 911
      break;
    }
Wilco Greven's avatar
Wilco Greven committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    if (line->yMax < yMin) {
      continue;
    }

    for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
    if (!blk || blk->xMin > xMax) {
      continue;
    }

    y = 0.5 * (blk->yMin + blk->yMax);
    if (y < yMin || y > yMax) {
      continue;
    }

    if (firstCol >= 0) {
      multiLine = gTrue;
    }

    i = 0;
    while (1) {
      x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
      x1 = blk->xRight[i];
      if (0.5 * (x0 + x1) > xMin) {
935 936
	  break;
	}
Wilco Greven's avatar
Wilco Greven committed
937 938 939 940 941 942 943
      ++i;
    }
    col = blk->col[i];

    if (firstCol < 0 || col < firstCol) {
      firstCol = col;
    }
944
      }
Wilco Greven's avatar
Wilco Greven committed
945 946 947 948

  // extract the text
  for (line = lines; line; line = line->next) {
    if (line->yMin > yMax) {
949 950
	  break;
	}
Wilco Greven's avatar
Wilco Greven committed
951 952
    if (line->yMax < yMin) {
      continue;
953
      }
Wilco Greven's avatar
Wilco Greven committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

    for (blk = line->blocks; blk && blk->xMax < xMin; blk = blk->next) ;
    if (!blk || blk->xMin > xMax) {
      continue;
    }

    y = 0.5 * (blk->yMin + blk->yMax);
    if (y < yMin || y > yMax) {
      continue;
    }

    i = 0;
    while (1) {
      x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
      x1 = blk->xRight[i];
      if (0.5 * (x0 + x1) > xMin) {
	break;
971
	  }
Wilco Greven's avatar
Wilco Greven committed
972
      ++i;
973
	}
Wilco Greven's avatar
Wilco Greven committed
974 975 976 977 978 979 980 981

    col = firstCol;

    do {

      // line this block up with the correct column
      for (; col < blk->col[i]; ++col) {
	s->append(space, spaceLen);
982
      }
Wilco Greven's avatar
Wilco Greven committed
983 984 985 986 987 988 989 990

      // print the block
      for (; i < blk->len; ++i) {

	x0 = (i==0) ? blk->xMin : blk->xRight[i-1];
	x1 = blk->xRight[i];
	if (0.5 * (x0 + x1) > xMax) {
	  break;
991
      }
Wilco Greven's avatar
Wilco Greven committed
992 993 994 995

	len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
	s->append(buf, len);
	col += isUnicode ? 1 : len;
996
    }
Wilco Greven's avatar
Wilco Greven committed
997 998
      if (i < blk->len) {
	break;
999
  }
Wilco Greven's avatar
Wilco Greven committed
1000 1001 1002 1003 1004 1005 1006

      // next block
      blk = blk->next;
      i = 0;

    } while (blk && blk->xMin < xMax);

1007 1008 1009
  if (multiLine) {
    s->append(eol, eolLen);
  }
Wilco Greven's avatar
Wilco Greven committed
1010 1011
  }

1012
  uMap->decRefCnt();
Wilco Greven's avatar
Wilco Greven committed
1013

1014 1015 1016 1017 1018 1019
  return s;
}

void TextPage::dump(void *outputStream, TextOutputFunc outputFunc) {
  UnicodeMap *uMap;
  char space[8], eol[16], eop[8], buf[8];
Wilco Greven's avatar
Wilco Greven committed
1020 1021 1022 1023
  int spaceLen, eolLen, eopLen, len;
  TextLine *line;
  TextBlock *blk;
  int col, d, i;
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

  // get the output encoding
  if (!(uMap = globalParams->getTextEncoding())) {
    return;
  }
  spaceLen = uMap->mapUnicode(0x20, space, sizeof(space));
  eolLen = 0; // make gcc happy
  switch (globalParams->getTextEOL()) {
  case eolUnix:
    eolLen = uMap->mapUnicode(0x0a, eol, sizeof(eol));
    break;
  case eolDOS:
    eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
    eolLen += uMap->mapUnicode(0x0a, eol + eolLen, sizeof(eol) - eolLen);
    break;
  case eolMac:
    eolLen = uMap->mapUnicode(0x0d, eol, sizeof(eol));
    break;
  }
  eopLen = uMap->mapUnicode(0x0c, eop, sizeof(eop));

  // output
Wilco Greven's avatar
Wilco Greven committed
1046 1047 1048
  for (line = lines; line; line = line->next) {
    col = 0;
    for (blk = line->blocks; blk; blk = blk->next) {
1049

Wilco Greven's avatar
Wilco Greven committed
1050 1051 1052
      // line this block up with the correct column
      if (rawOrder && col == 0) {
	col = blk->col[0];
1053
    } else {
Wilco Greven's avatar
Wilco Greven committed
1054
	for (; col < blk->col[0]; ++col) {
1055 1056 1057 1058
	(*outputFunc)(outputStream, space, spaceLen);
      }
    }

Wilco Greven's avatar
Wilco Greven committed
1059 1060 1061 1062
      // print the block
      for (i = 0; i < blk->len; ++i) {
	len = uMap->mapUnicode(blk->text[i], buf, sizeof(buf));
	(*outputFunc)(outputStream, buf, len);
1063
    }
Wilco Greven's avatar
Wilco Greven committed
1064
      col += blk->convertedLen;
1065 1066 1067 1068 1069 1070
    }

      // print a return
      (*outputFunc)(outputStream, eol, eolLen);

      // print extra vertical space if necessary
Wilco Greven's avatar
Wilco Greven committed
1071 1072 1073 1074
    if (line->next) {
      d = (int)((line->next->yMin - line->yMax) /
		(line->blocks->strings->yMax - lines->blocks->strings->yMin)
		+ 0.5);
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
	// various things (weird font matrices) can result in bogus
	// values here, so do a sanity check
	if (rawOrder && d > 2) {
	  d = 2;
	} else if (!rawOrder && d > 5) {
	  d = 5;
	}
	for (; d > 0; --d) {
	  (*outputFunc)(outputStream, eol, eolLen);
	}
      }
  }

  // end of page
  (*outputFunc)(outputStream, eol, eolLen);
  (*outputFunc)(outputStream, eop, eopLen);
  (*outputFunc)(outputStream, eol, eolLen);

  uMap->decRefCnt();
}

Wilco Greven's avatar
Wilco Greven committed
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
// Returns true if <str1> should be inserted before <str2> in xy
// order.
GBool TextPage::xyBefore(TextString *str1, TextString *str2) {
  return str1->xMin < str2->xMin ||
	 (str1->xMin == str2->xMin && str1->yMin < str2->yMin);
}

// Returns true if <blk1> should be inserted before <blk2> in xy
// order.
GBool TextPage::xyBefore(TextBlock *blk1, TextBlock *blk2) {
  return blk1->xMin < blk2->xMin ||
	 (blk1->xMin == blk2->xMin && blk1->yMin < blk2->yMin);
}

// Returns true if <blk1> should be inserted before <blk2> in yx
// order, allowing a little slack for vertically overlapping text.
GBool TextPage::yxBefore(TextBlock *blk1, TextBlock *blk2) {
  double h1, h2, overlap;

  h1 = blk1->yMax - blk1->yMin;
  h2 = blk2->yMax - blk2->yMin;
  overlap = ((blk1->yMax < blk2->yMax ? blk1->yMax : blk2->yMax) -
	     (blk1->yMin > blk2->yMin ? blk1->yMin : blk2->yMin)) /
            (h1 < h2 ? h1 : h2);
  if (overlap > 0.6) {
    return blk1->xMin < blk2->xMin;
  }
  return blk1->yMin < blk2->yMin;
}

double TextPage::coalesceFit(TextString *str1, TextString *str2) {
  double h1, h2, w1, w2, r, overlap, spacing;

  h1 = str1->yMax - str1->yMin;
  h2 = str2->yMax - str2->yMin;
  w1 = str1->xMax - str1->xMin;
  w2 = str2->xMax - str2->xMin;
  r = h1 / h2;
  if (r < (1.0 / 3.0) || r > 3) {
    return 10;
  }
  overlap = ((str1->yMax < str2->yMax ? str1->yMax : str2->yMax) -
	     (str1->yMin > str2->yMin ? str1->yMin : str2->yMin)) /
            (h1 < h2 ? h1 : h2);
  if (overlap < 0.5) {
    return 10;
  }
  spacing = (str2->xMin - str1->xMax) / (h1 > h2 ? h1 : h2);
  if (spacing < -0.5) {
    return 10;
  }
  // separate text that overlaps - duplicated text (so that fake
  // boldface and shadowed text can be cleanly removed)
  if ((str2->xMin - str1->xMax) / (w1 < w2 ? w1 : w2) < -0.7) {
    return 10;
  }
  return spacing;
}

1155
void TextPage::clear() {
Wilco Greven's avatar
Wilco Greven committed
1156 1157
  TextLine *p1, *p2;
  TextString *s1, *s2;
1158 1159 1160 1161 1162

  if (curStr) {
    delete curStr;
    curStr = NULL;
  }
Wilco Greven's avatar
Wilco Greven committed
1163 1164 1165
  if (lines) {
    for (p1 = lines; p1; p1 = p2) {
      p2 = p1->next;
1166 1167
    delete p1;
  }
Wilco Greven's avatar
Wilco Greven committed
1168 1169 1170 1171 1172 1173
  } else if (xyStrings) {
    for (s1 = xyStrings; s1; s1 = s2) {
      s2 = s1->next;
      delete s1;
    }
  }
1174
  xyStrings = NULL;
Wilco Greven's avatar
Wilco Greven committed
1175 1176 1177 1178
  xyCur1 = xyCur2 = NULL;
  lines = NULL;
  nest = 0;
  nTinyChars = 0;
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
}

//------------------------------------------------------------------------
// TextOutputDev
//------------------------------------------------------------------------

static void outputToFile(void *stream, char *text, int len) {
  fwrite(text, 1, len, (FILE *)stream);
}

TextOutputDev::TextOutputDev(char *fileName, GBool rawOrderA, GBool append) {
  text = NULL;
  rawOrder = rawOrderA;
  ok = gTrue;

  // open file
  needClose = gFalse;
  if (fileName) {
    if (!strcmp(fileName, "-")) {
      outputStream = stdout;
    } else if ((outputStream = fopen(fileName, append ? "ab" : "wb"))) {
      needClose = gTrue;
    } else {
      error(-1, "Couldn't open text file '%s'", fileName);
      ok = gFalse;
      return;
    }
    outputFunc = &outputToFile;
  } else {
    outputStream = NULL;
  }

  // set up text object
  text = new TextPage(rawOrder);
}

TextOutputDev::TextOutputDev(TextOutputFunc func, void *stream,
			     GBool rawOrderA) {
  outputFunc = func;
  outputStream = stream;
  needClose = gFalse;
  rawOrder = rawOrderA;
  text = new TextPage(rawOrder);
  ok = gTrue;
}

TextOutputDev::~TextOutputDev() {
  if (needClose) {
#ifdef MACOS
    ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
#endif
    fclose((FILE *)outputStream);
  }
  if (text) {
    delete text;
  }
}

void TextOutputDev::startPage(int pageNum, GfxState *state) {
  text->clear();
}

void TextOutputDev::endPage() {
  text->coalesce();
  if (outputStream) {
    text->dump(outputStream, outputFunc);
  }
}

void TextOutputDev::updateFont(GfxState *state) {
  text->updateFont(state);
}

void TextOutputDev::beginString(GfxState *state, GString *s) {
Wilco Greven's avatar
Wilco Greven committed
1253
  text->beginString(state, state->getCurX(), state->getCurY());
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
}

void TextOutputDev::endString(GfxState *state) {
  text->endString();
}

void TextOutputDev::drawChar(GfxState *state, double x, double y,
			     double dx, double dy,
			     double originX, double originY,
			     CharCode c, Unicode *u, int uLen) {
  text->addChar(state, x, y, dx, dy, u, uLen);
}

GBool TextOutputDev::findText(Unicode *s, int len,
			      GBool top, GBool bottom,
			      double *xMin, double *yMin,
			      double *xMax, double *yMax) {
  return text->findText(s, len, top, bottom, xMin, yMin, xMax, yMax);
}
Wilco Greven's avatar
Wilco Greven committed
1273 1274 1275 1276 1277 1278

GString *TextOutputDev::getText(double xMin, double yMin,
				double xMax, double yMax) {
  return text->getText(xMin, yMin, xMax, yMax);
}