CairoOutputDev.cc 56.2 KB
Newer Older
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1 2 3 4 5 6 7 8
//========================================================================
//
// CairoOutputDev.cc
//
// Copyright 2003 Glyph & Cog, LLC
// Copyright 2004 Red Hat, Inc
//
//========================================================================
9 10 11 12 13

//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
14 15 16
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
17 18
// Copyright (C) 2005-2008 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
19
// Copyright (C) 2005, 2009 Albert Astals Cid <aacid@kde.org>
20
// Copyright (C) 2005 Nickolay V. Shmyrev <nshmyrev@yandex.ru>
21
// Copyright (C) 2006-2009 Carlos Garcia Campos <carlosgc@gnome.org>
22 23 24 25
// Copyright (C) 2008 Carl Worth <cworth@cworth.org>
// Copyright (C) 2008 Adrian Johnson <ajohnson@redneon.com>
// Copyright (C) 2008 Michael Vrable <mvrable@cs.ucsd.edu>
// Copyright (C) 2008 Chris Wilson <chris@chris-wilson.co.uk>
26
// Copyright (C) 2008 Hib Eris <hib@hiberis.nl>
27 28 29 30 31
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
Kristian Høgsberg's avatar
Kristian Høgsberg committed
32 33 34 35 36 37 38 39 40

#include <config.h>

#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif

#include <string.h>
#include <math.h>
41
#include <assert.h>
Kristian Høgsberg's avatar
Kristian Høgsberg committed
42 43 44 45 46 47 48 49 50 51 52
#include <cairo.h>

#include "goo/gfile.h"
#include "GlobalParams.h"
#include "Error.h"
#include "Object.h"
#include "GfxState.h"
#include "GfxFont.h"
#include "Link.h"
#include "CharCodeToUnicode.h"
#include "FontEncodingTables.h"
53
#include "PDFDocEncoding.h"
Kristian Høgsberg's avatar
Kristian Høgsberg committed
54 55 56 57 58 59
#include <fofi/FoFiTrueType.h>
#include <splash/SplashBitmap.h>
#include "CairoOutputDev.h"
#include "CairoFontEngine.h"
//------------------------------------------------------------------------

60
// #define LOG_CAIRO
Kristian Høgsberg's avatar
Kristian Høgsberg committed
61 62 63 64 65 66 67

#ifdef LOG_CAIRO
#define LOG(x) (x)
#else
#define LOG(x)
#endif

68 69 70 71 72 73
static inline void printMatrix(cairo_matrix_t *matrix){
	printf("%f %f, %f %f (%f %f)\n", matrix->xx, matrix->yx,
			matrix->xy, matrix->yy,
			matrix->x0, matrix->y0);
}

74 75 76 77
//------------------------------------------------------------------------
// CairoImage
//------------------------------------------------------------------------

78 79
CairoImage::CairoImage (double x1, double y1, double x2, double y2) {
  this->image = NULL;
80 81 82 83 84 85 86 87 88 89
  this->x1 = x1;
  this->y1 = y1;
  this->x2 = x2;
  this->y2 = y2;
}

CairoImage::~CairoImage () {
  if (image)
    cairo_surface_destroy (image);
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
90

91 92 93 94 95 96
void CairoImage::setImage (cairo_surface_t *image) {
  if (this->image)
    cairo_surface_destroy (this->image);
  this->image = cairo_surface_reference (image);
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
97 98 99 100
//------------------------------------------------------------------------
// CairoOutputDev
//------------------------------------------------------------------------

101 102 103 104 105 106 107 108 109
// We cannot tie the lifetime of an FT_Library object to that of
// CairoOutputDev, since any FT_Faces created with it may end up with a
// reference by Cairo which can be held long after the CairoOutputDev is
// deleted.  The simplest way to avoid problems is to never tear down the
// FT_Library instance; to avoid leaks, just use a single global instance
// initialized the first time it is needed.
FT_Library CairoOutputDev::ft_lib;
GBool CairoOutputDev::ft_lib_initialized = gFalse;

110
CairoOutputDev::CairoOutputDev() {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
111
  xref = NULL;
112
  catalog = NULL;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
113

114 115 116 117 118
  if (!ft_lib_initialized) {
    FT_Init_FreeType(&ft_lib);
    ft_lib_initialized = gTrue;
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
119
  fontEngine = NULL;
120
  fontEngine_owner = gFalse;
121
  glyphs = NULL;
122 123
  fill_pattern = NULL;
  stroke_pattern = NULL;
124 125
  stroke_opacity = 1.0;
  fill_opacity = 1.0;
126
  textClipPath = NULL;
127
  haveCSPattern = gFalse;
128
  cairo = NULL;
129
  currentFont = NULL;
130
  prescaleImages = gTrue;
131
  printing = gTrue;
132
  inType3Char = gFalse;
133
  t3_glyph_has_bbox = gFalse;
134 135

  groupColorSpaceStack = NULL;
136
  maskStack = NULL;
137 138
  group = NULL;
  mask = NULL;
139 140 141
  shape = NULL;
  cairo_shape = NULL;
  knockoutCount = 0;
142 143

  text = NULL;
144
  actualText = NULL;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
145 146 147
}

CairoOutputDev::~CairoOutputDev() {
148
  if (fontEngine_owner && fontEngine) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
149 150
    delete fontEngine;
  }
151

152 153
  if (cairo)
    cairo_destroy (cairo);
154 155
  cairo_pattern_destroy (stroke_pattern);
  cairo_pattern_destroy (fill_pattern);
156 157
  if (group)
    cairo_pattern_destroy (group);
Chris Wilson's avatar
Chris Wilson committed
158 159
  if (mask)
    cairo_pattern_destroy (mask);
160 161
  if (shape)
    cairo_pattern_destroy (shape);
162
  if (text) 
163 164 165
    text->decRefCnt();
  if (actualText)
    delete actualText;  
166
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
167

168
void CairoOutputDev::setCairo(cairo_t *cairo)
169
{
170 171 172 173 174
  if (this->cairo != NULL) {
    cairo_status_t status = cairo_status (this->cairo);
    if (status) {
      warning("cairo context error: %s\n", cairo_status_to_string(status));
    }
175
    cairo_destroy (this->cairo);
176
    assert(!cairo_shape);
177
  }
178
  if (cairo != NULL) {
179
    this->cairo = cairo_reference (cairo);
180 181 182 183
	/* save the initial matrix so that we can use it for type3 fonts. */
	//XXX: is this sufficient? could we miss changes to the matrix somehow?
	cairo_get_matrix(cairo, &orig_matrix);
  } else {
184
    this->cairo = NULL;
185
    this->cairo_shape = NULL;
186
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
187 188
}

189 190 191 192
void CairoOutputDev::setTextPage(TextPage *text)
{
  if (this->text) 
    this->text->decRefCnt();
193 194
  if (actualText)
    delete actualText;
195 196 197
  if (text) {
    this->text = text;
    this->text->incRefCnt();
198
    actualText = new ActualText(text);
199 200
  } else {
    this->text = NULL;
201
    actualText = NULL;
202 203 204
  }
}

205 206
void CairoOutputDev::startDoc(XRef *xrefA, Catalog *catalogA,
			      CairoFontEngine *parentFontEngine) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
207
  xref = xrefA;
208
  catalog = catalogA;
209 210 211 212 213 214 215 216
  if (parentFontEngine) {
    fontEngine = parentFontEngine;
  } else {
    if (fontEngine) {
      delete fontEngine;
    }
    fontEngine = new CairoFontEngine(ft_lib);
    fontEngine_owner = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
217 218 219
  }
}

220 221 222 223 224 225 226
void CairoOutputDev::startPage(int pageNum, GfxState *state) {
  /* set up some per page defaults */
  cairo_pattern_destroy(fill_pattern);
  fill_pattern = cairo_pattern_create_rgb(0., 0., 0.);

  cairo_pattern_destroy(stroke_pattern);
  stroke_pattern = cairo_pattern_create_rgb(0., 0., 0.);
227 228 229 230 231 232 233 234 235 236

  if (text)
    text->startPage(state);
}

void CairoOutputDev::endPage() {
  if (text) {
    text->endPage();
    text->coalesce(gTrue, gFalse);
  }
237 238
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
239 240 241 242 243 244
void CairoOutputDev::drawLink(Link *link, Catalog *catalog) {
}

void CairoOutputDev::saveState(GfxState *state) {
  LOG(printf ("save\n"));
  cairo_save (cairo);
245 246
  if (cairo_shape)
      cairo_save (cairo_shape);
247 248 249 250 251

  MaskStack *ms = new MaskStack;
  ms->mask = cairo_pattern_reference(mask);
  ms->next = maskStack;
  maskStack = ms;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
252 253 254 255 256
}

void CairoOutputDev::restoreState(GfxState *state) {
  LOG(printf ("restore\n"));
  cairo_restore (cairo);
257 258
  if (cairo_shape)
      cairo_restore (cairo_shape);
259 260 261 262 263 264 265

  /* These aren't restored by cairo_restore() since we keep them in
   * the output device. */
  updateFillColor(state);
  updateStrokeColor(state);
  updateFillOpacity(state);
  updateStrokeOpacity(state);
266 267 268 269 270 271 272 273

  MaskStack* ms = maskStack;
  if (mask)
    cairo_pattern_destroy(mask);

  mask = ms->mask;
  maskStack = ms->next;
  delete ms;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
274 275 276 277 278 279 280 281 282 283 284
}

void CairoOutputDev::updateAll(GfxState *state) {
  updateLineDash(state);
  updateLineJoin(state);
  updateLineCap(state);
  updateLineWidth(state);
  updateFlatness(state);
  updateMiterLimit(state);
  updateFillColor(state);
  updateStrokeColor(state);
285 286
  updateFillOpacity(state);
  updateStrokeOpacity(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
287 288 289
  needFontUpdate = gTrue;
}

290 291 292 293 294 295 296 297 298
void CairoOutputDev::setDefaultCTM(double *ctm) {
  cairo_matrix_t matrix;
  matrix.xx = ctm[0];
  matrix.yx = ctm[1];
  matrix.xy = ctm[2];
  matrix.yy = ctm[3];
  matrix.x0 = ctm[4];
  matrix.y0 = ctm[5];

299
  cairo_transform (cairo, &matrix);
300
  if (cairo_shape)
301
      cairo_transform (cairo_shape, &matrix);
302 303 304 305

  OutputDev::setDefaultCTM(ctm);
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
306 307 308
void CairoOutputDev::updateCTM(GfxState *state, double m11, double m12,
				double m21, double m22,
				double m31, double m32) {
309
  cairo_matrix_t matrix, invert_matrix;
310 311 312 313 314 315 316
  matrix.xx = m11;
  matrix.yx = m12;
  matrix.xy = m21;
  matrix.yy = m22;
  matrix.x0 = m31;
  matrix.y0 = m32;

317 318 319 320 321 322 323 324
  /* Make sure the matrix is invertible before setting it.
   * cairo will blow up if we give it a matrix that's not
   * invertible, so we need to check before passing it
   * to cairo_transform. Ignoring it is likely to give better
   * results than not rendering anything at all. See #14398
   *
   * Ideally, we could do the cairo_transform
   * and then check if anything went wrong and fix it then
325 326 327
   * instead of having to invert the matrix. */
  invert_matrix = matrix;
  if (cairo_matrix_invert(&invert_matrix)) {
328 329 330 331
    warning("matrix not invertible\n");
    return;
  }

332
  cairo_transform (cairo, &matrix);
333 334
  if (cairo_shape)
    cairo_transform (cairo_shape, &matrix);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
335 336 337 338 339 340 341 342 343 344 345 346
  updateLineDash(state);
  updateLineJoin(state);
  updateLineCap(state);
  updateLineWidth(state);
}

void CairoOutputDev::updateLineDash(GfxState *state) {
  double *dashPattern;
  int dashLength;
  double dashStart;

  state->getLineDash(&dashPattern, &dashLength, &dashStart);
347
  cairo_set_dash (cairo, dashPattern, dashLength, dashStart);
348 349
  if (cairo_shape)
    cairo_set_dash (cairo_shape, dashPattern, dashLength, dashStart);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
350 351 352
}

void CairoOutputDev::updateFlatness(GfxState *state) {
353
  // cairo_set_tolerance (cairo, state->getFlatness());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367
}

void CairoOutputDev::updateLineJoin(GfxState *state) {
  switch (state->getLineJoin()) {
  case 0:
    cairo_set_line_join (cairo, CAIRO_LINE_JOIN_MITER);
    break;
  case 1:
    cairo_set_line_join (cairo, CAIRO_LINE_JOIN_ROUND);
    break;
  case 2:
    cairo_set_line_join (cairo, CAIRO_LINE_JOIN_BEVEL);
    break;
  }
368 369
  if (cairo_shape)
    cairo_set_line_join (cairo_shape, cairo_get_line_join(cairo));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383
}

void CairoOutputDev::updateLineCap(GfxState *state) {
  switch (state->getLineCap()) {
  case 0:
    cairo_set_line_cap (cairo, CAIRO_LINE_CAP_BUTT);
    break;
  case 1:
    cairo_set_line_cap (cairo, CAIRO_LINE_CAP_ROUND);
    break;
  case 2:
    cairo_set_line_cap (cairo, CAIRO_LINE_CAP_SQUARE);
    break;
  }
384 385
  if (cairo_shape)
    cairo_set_line_cap (cairo_shape, cairo_get_line_cap(cairo));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
386 387 388 389
}

void CairoOutputDev::updateMiterLimit(GfxState *state) {
  cairo_set_miter_limit (cairo, state->getMiterLimit());
390 391
  if (cairo_shape)
    cairo_set_miter_limit (cairo_shape, state->getMiterLimit());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
392 393
}

394
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
395

Kristian Høgsberg's avatar
Kristian Høgsberg committed
396
void CairoOutputDev::updateLineWidth(GfxState *state) {
397 398
  LOG(printf ("line width: %f\n", state->getLineWidth()));
  if (state->getLineWidth() == 0.0) {
399 400 401 402 403
    /* find out how big pixels (device unit) are in the x and y directions
     * choose the smaller of the two as our line width */
    double x = 1.0, y = 1.0;
    cairo_device_to_user_distance(cairo, &x, &y);
    cairo_set_line_width (cairo, MIN(fabs(x),fabs(y)));
404
  } else {
405
    cairo_set_line_width (cairo, state->getLineWidth());
406
  }
407 408
  if (cairo_shape)
    cairo_set_line_width (cairo_shape, cairo_get_line_width (cairo));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
409 410 411 412
}

void CairoOutputDev::updateFillColor(GfxState *state) {
  state->getFillRGB(&fill_color);
413 414 415 416 417 418 419 420 421

  cairo_pattern_destroy(fill_pattern);
  fill_pattern = cairo_pattern_create_rgba(fill_color.r / 65535.0,
					   fill_color.g / 65535.0,
					   fill_color.b / 65535.0,
					   fill_opacity);

  LOG(printf ("fill color: %d %d %d\n",
	      fill_color.r, fill_color.g, fill_color.b));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
422 423 424 425
}

void CairoOutputDev::updateStrokeColor(GfxState *state) {
  state->getStrokeRGB(&stroke_color);
426 427 428 429 430 431 432 433 434

  cairo_pattern_destroy(stroke_pattern);
  stroke_pattern = cairo_pattern_create_rgba(stroke_color.r / 65535.0,
					     stroke_color.g / 65535.0,
					     stroke_color.b / 65535.0,
					     stroke_opacity);
  
  LOG(printf ("stroke color: %d %d %d\n",
	      stroke_color.r, stroke_color.g, stroke_color.b));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
435 436
}

437 438
void CairoOutputDev::updateFillOpacity(GfxState *state) {
  fill_opacity = state->getFillOpacity();
439 440 441 442 443 444 445

  cairo_pattern_destroy(fill_pattern);
  fill_pattern = cairo_pattern_create_rgba(fill_color.r / 65535.0,
					   fill_color.g / 65535.0,
					   fill_color.b / 65535.0,
					   fill_opacity);

446 447 448 449 450
  LOG(printf ("fill opacity: %f\n", fill_opacity));
}

void CairoOutputDev::updateStrokeOpacity(GfxState *state) {
  stroke_opacity = state->getStrokeOpacity();
451 452 453 454 455 456 457

  cairo_pattern_destroy(stroke_pattern);
  stroke_pattern = cairo_pattern_create_rgba(stroke_color.r / 65535.0,
					     stroke_color.g / 65535.0,
					     stroke_color.b / 65535.0,
					     stroke_opacity);
  
458 459 460
  LOG(printf ("stroke opacity: %f\n", stroke_opacity));
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
461
void CairoOutputDev::updateFont(GfxState *state) {
462
  cairo_font_face_t *font_face;
463
  cairo_matrix_t matrix, invert_matrix;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
464 465

  LOG(printf ("updateFont() font=%s\n", state->getFont()->getName()->getCString()));
466

Kristian Høgsberg's avatar
Kristian Høgsberg committed
467 468
  needFontUpdate = gFalse;

469 470 471 472
  //FIXME: use cairo font engine?
  if (text)
    text->updateFont(state);
  
473
  currentFont = fontEngine->getFont (state->getFont(), xref, catalog, printing);
474

475 476
  if (!currentFont)
    return;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
477

478
  LOG(printf ("font matrix: %f %f %f %f\n", m11, m12, m21, m22));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
479
  
480 481
  font_face = currentFont->getFontFace();
  cairo_set_font_face (cairo, font_face);
482 483 484
 
  double fontSize = state->getFontSize();
  double *m = state->getTextMat();
485 486 487 488 489 490
  /* NOTE: adjusting by a constant is hack. The correct solution
   * is probably to use user-fonts and compute the scale on a per
   * glyph basis instead of for the entire font */
  double w = currentFont->getSubstitutionCorrection(state->getFont());
  matrix.xx = m[0] * fontSize * state->getHorizScaling() * w;
  matrix.yx = m[1] * fontSize * state->getHorizScaling() * w;
491 492
  matrix.xy = -m[2] * fontSize;
  matrix.yy = -m[3] * fontSize;
493 494
  matrix.x0 = 0;
  matrix.y0 = 0;
495 496 497 498 499 500 501 502 503 504 505 506 507

 /* Make sure the font matrix is invertible before setting it.  cairo
  * will blow up if we give it a matrix that's not invertible, so we
  * need to check before passing it to cairo_set_font_matrix. Ignoring it
  * is likely to give better results than not rendering anything at
  * all. See #18254.
  */
  invert_matrix = matrix;
  if (cairo_matrix_invert(&invert_matrix)) {
    warning("font matrix not invertible\n");
    return;
  }

508
  cairo_set_font_matrix (cairo, &matrix);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
509 510
}

511 512 513 514 515 516 517 518 519
void CairoOutputDev::updateRender(GfxState *state) {
  int rm;
  rm = state->getRender();
  if (rm == 7 && haveCSPattern) {
    haveCSPattern = gFalse;
    restoreState(state);
  }
}

520
void CairoOutputDev::doPath(cairo_t *cairo, GfxState *state, GfxPath *path) {
Kristian Høgsberg's avatar
Kristian Høgsberg committed
521 522 523 524 525
  GfxSubpath *subpath;
  int i, j;
  for (i = 0; i < path->getNumSubpaths(); ++i) {
    subpath = path->getSubpath(i);
    if (subpath->getNumPoints() > 0) {
526 527
      cairo_move_to (cairo, subpath->getX(0), subpath->getY(0));
         j = 1;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
528 529
      while (j < subpath->getNumPoints()) {
	if (subpath->getCurve(j)) {
530 531 532 533 534
	  cairo_curve_to( cairo,
			  subpath->getX(j), subpath->getY(j),
			  subpath->getX(j+1), subpath->getY(j+1),
			  subpath->getX(j+2), subpath->getY(j+2));

Kristian Høgsberg's avatar
Kristian Høgsberg committed
535 536
	  j += 3;
	} else {
537
	  cairo_line_to (cairo, subpath->getX(j), subpath->getY(j));
Kristian Høgsberg's avatar
Kristian Høgsberg committed
538 539 540 541 542 543 544 545 546 547 548 549
	  ++j;
	}
      }
      if (subpath->isClosed()) {
	LOG (printf ("close\n"));
	cairo_close_path (cairo);
      }
    }
  }
}

void CairoOutputDev::stroke(GfxState *state) {
550
  doPath (cairo, state, state->getPath());
551
  cairo_set_source (cairo, stroke_pattern);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
552 553
  LOG(printf ("stroke\n"));
  cairo_stroke (cairo);
554 555 556 557
  if (cairo_shape) {
    doPath (cairo_shape, state, state->getPath());
    cairo_stroke (cairo_shape);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
558 559 560
}

void CairoOutputDev::fill(GfxState *state) {
561
  doPath (cairo, state, state->getPath());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
562
  cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_WINDING);
563
  cairo_set_source (cairo, fill_pattern);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
564
  LOG(printf ("fill\n"));
565
  //XXX: how do we get the path
Kristian Høgsberg's avatar
Kristian Høgsberg committed
566
  cairo_fill (cairo);
567 568 569 570 571
  if (cairo_shape) {
    cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_WINDING);
    doPath (cairo_shape, state, state->getPath());
    cairo_fill (cairo_shape);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
572 573 574
}

void CairoOutputDev::eoFill(GfxState *state) {
575
  doPath (cairo, state, state->getPath());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
576
  cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_EVEN_ODD);
577
  cairo_set_source (cairo, fill_pattern);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
578 579
  LOG(printf ("fill-eo\n"));
  cairo_fill (cairo);
580 581 582 583 584 585 586

  if (cairo_shape) {
    cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_EVEN_ODD);
    doPath (cairo_shape, state, state->getPath());
    cairo_fill (cairo_shape);
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
587 588
}

589
void CairoOutputDev::clip(GfxState *state) {
590
  doPath (cairo, state, state->getPath());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
591 592 593
  cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_WINDING);
  cairo_clip (cairo);
  LOG (printf ("clip\n"));
594 595 596 597 598
  if (cairo_shape) {
    doPath (cairo_shape, state, state->getPath());
    cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_WINDING);
    cairo_clip (cairo_shape);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
599 600 601
}

void CairoOutputDev::eoClip(GfxState *state) {
602
  doPath (cairo, state, state->getPath());
Kristian Høgsberg's avatar
Kristian Høgsberg committed
603 604 605
  cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_EVEN_ODD);
  cairo_clip (cairo);
  LOG (printf ("clip-eo\n"));
606 607 608 609 610 611
  if (cairo_shape) {
    doPath (cairo_shape, state, state->getPath());
    cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_EVEN_ODD);
    cairo_clip (cairo_shape);
  }

Kristian Høgsberg's avatar
Kristian Høgsberg committed
612 613
}

614
void CairoOutputDev::beginString(GfxState *state, GooString *s)
615 616
{
  int len = s->getLength();
617

618 619 620
  if (needFontUpdate)
    updateFont(state);

621 622 623
  if (!currentFont)
    return;

624
  glyphs = (cairo_glyph_t *) gmallocn (len, sizeof (cairo_glyph_t));
625 626 627 628 629 630
  glyphCount = 0;
}

void CairoOutputDev::drawChar(GfxState *state, double x, double y,
			      double dx, double dy,
			      double originX, double originY,
631
			      CharCode code, int nBytes, Unicode *u, int uLen)
632
{
633 634 635 636 637 638 639 640
  if (currentFont) {
    glyphs[glyphCount].index = currentFont->getGlyph (code, u, uLen);
    glyphs[glyphCount].x = x - originX;
    glyphs[glyphCount].y = y - originY;
    glyphCount++;
  }

  if (!text)
641
    return;
642
  actualText->addChar (state, x, y, dx, dy, code, nBytes, u, uLen);
643 644 645 646 647 648 649
}

void CairoOutputDev::endString(GfxState *state)
{
  int render;

  if (!currentFont)
Kristian Høgsberg's avatar
Kristian Høgsberg committed
650
    return;
651 652 653 654 655 656 657

  // endString can be called without a corresponding beginString. If this
  // happens glyphs will be null so don't draw anything, just return.
  // XXX: OutputDevs should probably not have to deal with this...
  if (!glyphs)
    return;

658 659
  // ignore empty strings and invisible text -- this is used by
  // Acrobat Capture
Kristian Høgsberg's avatar
Kristian Høgsberg committed
660
  render = state->getRender();
661
  if (render == 3 || glyphCount == 0) {
662 663
    gfree(glyphs);
    glyphs = NULL;
664
    return;
665
  }
666
  
Kristian Høgsberg's avatar
Kristian Høgsberg committed
667
  if (!(render & 1)) {
668
    LOG (printf ("fill string\n"));
669
    cairo_set_source (cairo, fill_pattern);
670
    cairo_show_glyphs (cairo, glyphs, glyphCount);
671 672
    if (cairo_shape)
      cairo_show_glyphs (cairo_shape, glyphs, glyphCount);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
673
  }
674
  
Kristian Høgsberg's avatar
Kristian Høgsberg committed
675 676
  // stroke
  if ((render & 3) == 1 || (render & 3) == 2) {
677
    LOG (printf ("stroke string\n"));
678
    cairo_set_source (cairo, stroke_pattern);
679
    cairo_glyph_path (cairo, glyphs, glyphCount);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
680
    cairo_stroke (cairo);
681 682 683 684
    if (cairo_shape) {
      cairo_glyph_path (cairo_shape, glyphs, glyphCount);
      cairo_stroke (cairo_shape);
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
685 686 687 688
  }

  // clip
  if (render & 4) {
689
    LOG (printf ("clip string\n"));
690 691 692 693 694
    // append the glyph path to textClipPath.

    // set textClipPath as the currentPath
    if (textClipPath) {
      cairo_append_path (cairo, textClipPath);
695 696 697
      if (cairo_shape) {
	cairo_append_path (cairo_shape, textClipPath);
      }
698 699 700 701
      cairo_path_destroy (textClipPath);
    }
    
    // append the glyph path
702
    cairo_glyph_path (cairo, glyphs, glyphCount);
703 704 705 706 707
   
    // move the path back into textClipPath 
    // and clear the current path
    textClipPath = cairo_copy_path (cairo);
    cairo_new_path (cairo);
708 709 710
    if (cairo_shape) {
      cairo_new_path (cairo_shape);
    }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
711
  }
712

713
  gfree (glyphs);
714
  glyphs = NULL;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
715 716
}

717

Kristian Høgsberg's avatar
Kristian Høgsberg committed
718 719 720
GBool CairoOutputDev::beginType3Char(GfxState *state, double x, double y,
				      double dx, double dy,
				      CharCode code, Unicode *u, int uLen) {
721 722 723 724 725 726 727 728 729 730 731 732

  cairo_save (cairo);
  double *ctm;
  cairo_matrix_t matrix;

  ctm = state->getCTM();
  matrix.xx = ctm[0];
  matrix.yx = ctm[1];
  matrix.xy = ctm[2];
  matrix.yy = ctm[3];
  matrix.x0 = ctm[4];
  matrix.y0 = ctm[5];
733 734 735 736
  /* Restore the original matrix and then transform to matrix needed for the
   * type3 font. This is ugly but seems to work. Perhaps there is a better way to do it?*/
  cairo_set_matrix(cairo, &orig_matrix);
  cairo_transform(cairo, &matrix);
737 738 739 740 741
  if (cairo_shape) {
    cairo_save (cairo_shape);
    cairo_set_matrix(cairo_shape, &orig_matrix);
    cairo_transform(cairo_shape, &matrix);
  }
742 743
  cairo_pattern_destroy(stroke_pattern);
  cairo_pattern_reference(fill_pattern);
744
  stroke_pattern = fill_pattern;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
745 746 747 748
  return gFalse;
}

void CairoOutputDev::endType3Char(GfxState *state) {
749
  cairo_restore (cairo);
750 751 752
  if (cairo_shape) {
    cairo_restore (cairo_shape);
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
753 754 755
}

void CairoOutputDev::type3D0(GfxState *state, double wx, double wy) {
756 757
  t3_glyph_wx = wx;
  t3_glyph_wy = wy;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
758 759 760
}

void CairoOutputDev::type3D1(GfxState *state, double wx, double wy,
761
			     double llx, double lly, double urx, double ury) {
762 763 764 765 766 767 768
  t3_glyph_wx = wx;
  t3_glyph_wy = wy;
  t3_glyph_bbox[0] = llx;
  t3_glyph_bbox[1] = lly;
  t3_glyph_bbox[2] = urx;
  t3_glyph_bbox[3] = ury;
  t3_glyph_has_bbox = gTrue;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
769 770
}

771 772 773 774 775 776 777 778 779
void CairoOutputDev::beginTextObject(GfxState *state) {
  if (state->getFillColorSpace()->getMode() == csPattern) {
    haveCSPattern = gTrue;
    saveState(state);
    savedRender = state->getRender();
    state->setRender(7); // Set clip to text path
  }
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
780
void CairoOutputDev::endTextObject(GfxState *state) {
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  if (haveCSPattern) {
    state->setRender(savedRender);
    haveCSPattern = gFalse;
    if (state->getFillColorSpace()->getMode() != csPattern) {
      if (textClipPath) {
	cairo_new_path (cairo);
	cairo_append_path (cairo, textClipPath);
	cairo_set_fill_rule (cairo, CAIRO_FILL_RULE_WINDING);
	cairo_set_source (cairo, fill_pattern);
	cairo_fill (cairo);
	if (cairo_shape) {
	  cairo_new_path (cairo_shape);
	  cairo_append_path (cairo_shape, textClipPath);
	  cairo_set_fill_rule (cairo_shape, CAIRO_FILL_RULE_WINDING);
	  cairo_fill (cairo_shape);
	}
	cairo_path_destroy (textClipPath);
	textClipPath = NULL;
      }
      restoreState(state);
      updateFillColor(state);
    }
  }

805 806 807 808
  if (textClipPath) {
    // clip the accumulated text path
    cairo_append_path (cairo, textClipPath);
    cairo_clip (cairo);
809 810 811 812
    if (cairo_shape) {
      cairo_append_path (cairo_shape, textClipPath);
      cairo_clip (cairo_shape);
    }
813 814 815
    cairo_path_destroy (textClipPath);
    textClipPath = NULL;
  }
816
}
817

818 819
void CairoOutputDev::beginMarkedContent(char *name, Dict *properties)
{
820 821
  if (text)
    actualText->beginMC(properties);
822 823 824 825
}

void CairoOutputDev::endMarkedContent(GfxState *state)
{
826 827
  if (text)
    actualText->endMC(state);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
828 829
}

830 831 832 833 834 835 836 837 838 839 840 841
static inline int splashRound(SplashCoord x) {
  return (int)floor(x + 0.5);
}

static inline int splashCeil(SplashCoord x) {
  return (int)ceil(x);
}

static inline int splashFloor(SplashCoord x) {
  return (int)floor(x);
}

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
static
cairo_surface_t *cairo_surface_create_similar_clip (cairo_t *cairo, cairo_content_t content)
{
  double x1, y1, x2, y2;
  int width, height;
  cairo_clip_extents (cairo, &x1, &y1, &x2, &y2);
  cairo_matrix_t matrix;
  cairo_get_matrix (cairo, &matrix);
  //cairo_matrix_transform_point(&matrix, &x1, &y1);
  //cairo_matrix_transform_point(&matrix, &x2, &y2);*/
  cairo_user_to_device(cairo, &x1, &y1);
  cairo_user_to_device(cairo, &x2, &y2);
  width = splashCeil(x2) - splashFloor(x1);
  //XXX: negative matrix
  ////height = splashCeil(y2) - splashFloor(y1);
  height = splashFloor(y1) - splashCeil(y2);
  cairo_surface_t *target = cairo_get_target (cairo);
  cairo_surface_t *result;

  result = cairo_surface_create_similar (target, content, width, height);
  double x_offset, y_offset;
    cairo_surface_get_device_offset(target, &x_offset, &y_offset);
    cairo_surface_set_device_offset(result, x_offset, y_offset);

 
  return result;
}



872 873
void CairoOutputDev::beginTransparencyGroup(GfxState * /*state*/, double * /*bbox*/,
                                      GfxColorSpace * blendingColorSpace,
874
                                      GBool /*isolated*/, GBool knockout,
875 876 877 878
				      GBool forSoftMask) {
  /* push color space */
  ColorSpaceStack* css = new ColorSpaceStack;
  css->cs = blendingColorSpace;
879
  css->knockout = knockout;
880 881
  css->next = groupColorSpaceStack;
  groupColorSpaceStack = css;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
  if (knockout) {
    knockoutCount++;
    if (!cairo_shape) {
      /* create a surface for tracking the shape */
      cairo_surface_t *cairo_shape_surface = cairo_surface_create_similar_clip (cairo, CAIRO_CONTENT_ALPHA);
      cairo_shape = cairo_create (cairo_shape_surface);
      cairo_surface_destroy (cairo_shape_surface);

      /* the color doesn't matter as long as it is opaque */
      cairo_set_source_rgb (cairo_shape, 0, 0, 0);
      cairo_matrix_t matrix;
      cairo_get_matrix (cairo, &matrix);
      //printMatrix(&matrix);
      cairo_set_matrix (cairo_shape, &matrix);
    } else {
      cairo_reference (cairo_shape);
    }
  }
  if (groupColorSpaceStack->next && groupColorSpaceStack->next->knockout) {
    /* we need to track the shape */
    cairo_push_group (cairo_shape);
  }
904 905 906 907
  if (0 && forSoftMask)
    cairo_push_group_with_content (cairo, CAIRO_CONTENT_ALPHA);
  else
    cairo_push_group (cairo);
908 909 910 911 912 913 914 915

  /* push_group has an implicit cairo_save() */
  if (knockout) {
    /*XXX: let's hope this matches the semantics needed */
    cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE);
  } else {
    cairo_set_operator(cairo, CAIRO_OPERATOR_OVER);
  }
916
}
917

918
void CairoOutputDev::endTransparencyGroup(GfxState * /*state*/) {
919

920 921 922
  if (group)
    cairo_pattern_destroy(group);
  group = cairo_pop_group (cairo);
923 924 925 926 927 928

  if (groupColorSpaceStack->next && groupColorSpaceStack->next->knockout) {
    if (shape)
      cairo_pattern_destroy(shape);
    shape = cairo_pop_group (cairo_shape);
  }
929
}
930

931 932 933 934
void CairoOutputDev::paintTransparencyGroup(GfxState * /*state*/, double * /*bbox*/) {
  cairo_set_source (cairo, group);

  if (!mask) {
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
    //XXX: deal with mask && shape case
    if (shape) {
      cairo_save (cairo);

      /* OPERATOR_SOURCE w/ a mask is defined as (src IN mask) ADD (dest OUT mask)
       * however our source has already been clipped to mask so we only need to
       * do ADD and OUT */

      /* clear the shape mask */
      cairo_set_source (cairo, shape);
      cairo_set_operator (cairo, CAIRO_OPERATOR_DEST_OUT);
      cairo_paint (cairo);

      cairo_set_operator (cairo, CAIRO_OPERATOR_ADD);
      cairo_set_source (cairo, group);
      cairo_paint (cairo);

      cairo_restore (cairo);

      cairo_pattern_destroy (shape);
      shape = NULL;
    } else {
      cairo_paint_with_alpha (cairo, fill_opacity);
    }
    cairo_status_t status = cairo_status(cairo);
    if (status)
      printf("BAD status: %s\n", cairo_status_to_string(status));
962 963 964 965 966 967 968
  } else {
    cairo_mask(cairo, mask);

    cairo_pattern_destroy(mask);
    mask = NULL;
  }

969
  popTransparencyGroup();
970 971 972 973 974 975 976 977 978
}

typedef unsigned int uint32_t;

static uint32_t luminocity(uint32_t x)
{
  int r = (x >> 16) & 0xff;
  int g = (x >>  8) & 0xff;
  int b = (x >>  0) & 0xff;
979 980
  // an arbitrary integer approximation of .3*r + .59*g + .11*b
  int y = (r*19661+g*38666+b*7209 + 32829)>>16;
981 982 983 984
  return y << 24;
}


985
/* XXX: do we need to deal with shape here? */
986 987
void CairoOutputDev::setSoftMask(GfxState * state, double * bbox, GBool alpha,
                                 Function * transferFunc, GfxColor * backdropColor) {
Chris Wilson's avatar
Chris Wilson committed
988 989
  cairo_pattern_destroy(mask);

990 991 992 993 994
  if (alpha == false) {
    /* We need to mask according to the luminocity of the group.
     * So we paint the group to an image surface convert it to a luminocity map
     * and then use that as the mask. */

995
    double x1, y1, x2, y2, tmp;
996
    cairo_clip_extents(cairo, &x1, &y1, &x2, &y2);
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    cairo_user_to_device(cairo, &x1, &y1);
    cairo_user_to_device(cairo, &x2, &y2);
    if (x1 > x2) {
      tmp = x1;
      x1 = x2;
      x2 = tmp;
    }

    if (y1 > y2) {
      tmp = y1;
      y1 = y2;
      y2 = tmp;
    }

1011 1012
    int width = (int)(ceil(x2) - floor(x1));
    int height = (int)(ceil(y2) - floor(y1));
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040

    cairo_surface_t *source = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
    cairo_t *maskCtx = cairo_create(source);

    //XXX: hopefully this uses the correct color space */
    GfxRGB backdropColorRGB;
    groupColorSpaceStack->cs->getRGB(backdropColor, &backdropColorRGB);
    /* paint the backdrop */
    cairo_set_source_rgb(maskCtx, backdropColorRGB.r / 65535.0,
			 backdropColorRGB.g / 65535.0,
			 backdropColorRGB.b / 65535.0);


    cairo_matrix_t mat;
    cairo_get_matrix(cairo, &mat);
    cairo_set_matrix(maskCtx, &mat);

    /* make the device offset of the new mask match that of the group */
    double x_offset, y_offset;
    cairo_surface_t *pats;
    cairo_pattern_get_surface(group, &pats);
    cairo_surface_get_device_offset(pats, &x_offset, &y_offset);
    cairo_surface_set_device_offset(source, x_offset, y_offset);

    /* paint the group */
    cairo_set_source(maskCtx, group);
    cairo_paint(maskCtx);

Chris Wilson's avatar
Chris Wilson committed
1041 1042 1043
    /* XXX status = cairo_status(maskCtx); */
    cairo_destroy(maskCtx);

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    /* convert to a luminocity map */
    uint32_t *source_data = (uint32_t*)cairo_image_surface_get_data(source);
    /* get stride in units of 32 bits */
    int stride = cairo_image_surface_get_stride(source)/4;
    for (int y=0; y<height; y++) {
      for (int x=0; x<width; x++) {
	source_data[y*stride + x] = luminocity(source_data[y*stride + x]);

#if 0
	here is how splash deals with the transferfunction we should deal with this
	  at some point
	if (transferFunc) {
	  transferFunc->transform(&lum, &lum2);
	} else {
	  lum2 = lum;
	}
	p[x] = (int)(lum2 * 255.0 + 0.5);
#endif

      }
    }

    /* setup the new mask pattern */
    mask = cairo_pattern_create_for_surface(source);
    cairo_matrix_t patMatrix;
    cairo_pattern_get_matrix(group, &patMatrix);
    cairo_pattern_set_matrix(mask, &patMatrix);

    cairo_surface_destroy(source);
  } else {
Chris Wilson's avatar
Chris Wilson committed
1074
    mask = cairo_pattern_reference(group);
1075
  }
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

  popTransparencyGroup();
}

void CairoOutputDev::popTransparencyGroup() {
  /* pop color space */
  ColorSpaceStack *css = groupColorSpaceStack;
  if (css->knockout) {
    knockoutCount--;
    if (!knockoutCount) {
      /* we don't need to track the shape anymore because
       * we are not above any knockout groups */
      cairo_destroy(cairo_shape);
      cairo_shape = NULL;
    }
  }
  groupColorSpaceStack = css->next;
  delete css;
1094 1095
}

1096

1097
void CairoOutputDev::clearSoftMask(GfxState * /*state*/) {
1098 1099 1100
  if (mask)
    cairo_pattern_destroy(mask);
  mask = NULL;
1101
}
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1102

1103 1104 1105 1106
void CairoOutputDev::endMaskClip(GfxState *state) {
  clearSoftMask(state);
}

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1107 1108 1109
void CairoOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
				    int width, int height, GBool invert,
				    GBool inlineImg) {
1110

1111 1112 1113 1114
  /* FIXME: Doesn't the image mask support any colorspace? */
  cairo_set_source (cairo, fill_pattern);

  /* work around a cairo bug when scaling 1x1 surfaces */
1115 1116
  if (width == 1 && height == 1) {
    cairo_save (cairo);
1117
    cairo_rectangle (cairo, 0., 0., width, height);
1118 1119
    cairo_fill (cairo);
    cairo_restore (cairo);
1120 1121 1122 1123 1124 1125
    if (cairo_shape) {
      cairo_save (cairo_shape);
      cairo_rectangle (cairo_shape, 0., 0., width, height);
      cairo_fill (cairo_shape);
      cairo_restore (cairo_shape);
    }
1126 1127 1128
    return;
  }

1129 1130
  /* shape is 1.0 for painted areas, 0.0 for unpainted ones */

1131 1132
  cairo_matrix_t matrix;
  cairo_get_matrix (cairo, &matrix);
1133 1134
  //XXX: it is possible that we should only do sub pixel positioning if 
  // we are rendering fonts */
1135
  if (!printing && prescaleImages && matrix.xy == 0.0 && matrix.yx == 0.0) {
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    drawImageMaskPrescaled(state, ref, str, width, height, invert, inlineImg);
  } else {
    drawImageMaskRegular(state, ref, str, width, height, invert, inlineImg);
  }
}

void CairoOutputDev::drawImageMaskRegular(GfxState *state, Object *ref, Stream *str,
				    int width, int height, GBool invert,
				    GBool inlineImg) {
  unsigned char *buffer;
  unsigned char *dest;
  cairo_surface_t *image;
  cairo_pattern_t *pattern;
  int x, y;
  ImageStream *imgStr;
  Guchar *pix;
  cairo_matrix_t matrix;
  int invert_bit;
  int row_stride;

1156 1157
  row_stride = (width + 3) & ~3;
  buffer = (unsigned char *) malloc (height * row_stride);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1158 1159 1160 1161 1162 1163
  if (buffer == NULL) {
    error(-1, "Unable to allocate memory for image.");
    return;
  }

  /* TODO: Do we want to cache these? */
1164
  imgStr = new ImageStream(str, width, 1, 1);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1165 1166
  imgStr->reset();

1167 1168
  invert_bit = invert ? 1 : 0;

Kristian Høgsberg's avatar
Kristian Høgsberg committed
1169
  for (y = 0; y < height; y++) {
1170
    pix = imgStr->getLine();
1171
    dest = buffer + y * row_stride;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1172
    for (x = 0; x < width; x++) {
1173 1174

      if (pix[x] ^ invert_bit)
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1175
	*dest++ = 0;
1176 1177
      else
	*dest++ = 255;
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1178 1179 1180
    }
  }

1181
  image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_A8,
1182
					       width, height, row_stride);
1183
  if (image == NULL) {
1184
    imgStr->close();
1185
    delete imgStr;
1186
    return;
1187
  }
1188
  pattern = cairo_pattern_create_for_surface (image);
1189
  if (pattern == NULL) {
1190
    imgStr->close();
1191
    delete imgStr;
1192
    return;
1193
  }
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1194

1195 1196 1197
  cairo_matrix_init_translate (&matrix, 0, height);
  cairo_matrix_scale (&matrix, width, -height);

1198
  cairo_pattern_set_matrix (pattern, &matrix);
Kristian Høgsberg's avatar
Kristian Høgsberg committed
1199

1200 1201 1202
  /* we should actually be using CAIRO_FILTER_NEAREST here. However,
   * cairo doesn't yet do minifaction filtering causing scaled down
   * images with CAIRO_FILTER_NEAREST to look really bad */
1203
  cairo_pattern_set_filter (pattern, CAIRO_FILTER_BEST);
1204

1205
  cairo_mask (cairo, pattern);
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
  if (cairo_shape) {
#if 0
    cairo_rectangle (cairo_shape, 0., 0., width, height);
    cairo_fill (cairo_shape);
#else
    cairo_save (cairo_shape);
    /* this should draw a rectangle the size of the image
     * we use this instead of rect,fill because of the lack
     * of EXTEND_PAD */
    /* NOTE: this will multiply the edges of the image twice */
    cairo_set_source (cairo_shape, pattern);
    cairo_mask (cairo_shape, pattern);
    cairo_restore (cairo_shape);
#endif
  }


1224
  cairo_pattern_destroy (pattern);
1225 1226
  cairo_surface_destroy (image);
  free (buffer);
1227
  imgStr->close();
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
  delete imgStr;
}


void CairoOutputDev::drawImageMaskPrescaled(GfxState *state, Object *ref, Stream *str,
				    int width, int height, GBool invert,
				    GBool inlineImg) {
  unsigned char *buffer;
  cairo_surface_t *image;
  cairo_pattern_t *pattern;
  ImageStream *imgStr;
  Guchar *pix;
  cairo_matrix_t matrix;
  int invert_bit;
  int row_stride;

  /* cairo does a very poor job of scaling down images so we scale them ourselves */

  /* this scaling code is adopted from the splash image scaling code */
  cairo_get_matrix(cairo, &matrix);
#if 0
  printf("[%f %f], [%f %f], %f %f\n", matrix.xx, matrix.xy, matrix.yx, matrix.yy, matrix.x0, matrix.y0);
#endif
1251
  /* this whole computation should be factored out */
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
  double xScale = matrix.xx;
  double yScale = matrix.yy;
  int tx, tx2, ty, ty2; /* the integer co-oridinates of the resulting image */
  int scaledHeight;
  int scaledWidth;
  if (xScale >= 0) {
    tx = splashRound(matrix.x0 - 0.01);
    tx2 = splashRound(matrix.x0 + xScale + 0.01) - 1;
  } else {
    tx = splashRound(matrix.x0 + 0.01) - 1;
    tx2 = splashRound(matrix.x0 + xScale - 0.01);
  }
  scaledWidth = abs(tx2 - tx) + 1;
  //scaledWidth = splashRound(fabs(xScale));
  if (scaledWidth == 0) {
    // technically, this should draw nothing, but it generally seems
    // better to draw a one-pixel-wide stripe rather than throwing it
    // away
    scaledWidth = 1;
  }
  if (yScale >= 0) {
    ty = splashFloor(matrix.y0 + 0.01);
    ty2 = splashCeil(matrix.y0 + yScale - 0.01);
  } else {
    ty = splashCeil(matrix.y0 - 0.01);
    ty2 = splashFloor(matrix.y0 + yScale + 0.01);
  }
  scaledHeight = abs(ty2 - ty);
1280 1281 1282
  if (scaledHeight == 0) {
    scaledHeight = 1;
  }
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
#if 0
  printf("xscale: %g, yscale: %g\n", xScale, yScale);
  printf("width: %d, height: %d\n", width, height);
  printf("scaledWidth: %d, scaledHeight: %d\n", scaledWidth, scaledHeight);
#endif

  /* compute the required padding */
  /* Padding is used to preserve the aspect ratio.
     We compute total_pad to make (height+total_pad)/scaledHeight as close to height/yScale as possible */
  int head_pad = 0;
  int tail_pad = 0;
  int total_pad = splashRound(height*(scaledHeight/fabs(yScale)) - height);

  /* compute the two pieces of padding */
  if (total_pad > 0) {
1298 1299 1300
    //XXX: i'm not positive fabs() is correct
    float tail_error = fabs(matrix.y0 - ty);
    float head_error = fabs(ty2 - (matrix.y0 + yScale));
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    float tail_fraction = tail_error/(tail_error + head_error);
    tail_pad = splashRound(total_pad*tail_fraction);
    head_pad = total_pad - tail_pad;
  } else {
    tail_pad = 0;
    head_pad = 0;
  }
  int origHeight = height;
  height += tail_pad;
  height += head_pad;
#if 0
  printf("head_pad: %d tail_pad: %d\n", head_pad, tail_pad);
  printf("origHeight: %d height: %d\n", origHeight, height);
  printf("ty: %d, ty2: %d\n", ty, ty2);
#endif

  /* TODO: Do we want to cache these? */
  imgStr = new ImageStream(str, width, 1, 1);
  imgStr->reset();

  invert_bit = invert ? 1 : 0;

  row_stride = (scaledWidth + 3) & ~3;
  buffer = (unsigned char *) malloc (scaledHeight * row_stride);
  if (buffer == NULL) {
    error(-1, "Unable to allocate memory for image.");
    return;
  }

  int yp = height / scaledHeight;
  int yq = height % scaledHeight;
  int xp = width / scaledWidth;
  int xq = width % scaledWidth;
  int yt = 0;
  int origHeight_c = origHeight;
  /* use MIN() because yp might be > origHeight because of padding */
  unsigned char *pixBuf = (unsigned char *)malloc(MIN(yp+1, origHeight)*width);
  int lastYStep = 1;
  int total = 0;
  for (int y = 0; y < scaledHeight; y++) {
    // y scale Bresenham
    int yStep = yp;
    yt += yq;

    if (yt >= scaledHeight) {
      yt -= scaledHeight;
      ++yStep;
    }

    // read row (s) from image ignoring the padding as appropriate
    {
      int n = (yp > 0) ? yStep : lastYStep;
      total += n;
      if (n > 0) {
	unsigned char *p = pixBuf;
	int head_pad_count = head_pad;
	int origHeight_count = origHeight;
	int tail_pad_count = tail_pad;
	for (int i=0; i<n; i++) {
	  // get row
	  if (head_pad_count) {
	    head_pad_count--;
	  } else if (origHeight_count) {
	    pix = imgStr->getLine();
	    for (int j=0; j<width; j++) {
	      if (pix[j] ^ invert_bit)
		p[j] = 0;
	      else
		p[j] = 255;
	    }
	    origHeight_count--;
	    p += width;
	  } else if (tail_pad_count) {
	    tail_pad_count--;
	  } else {
	    printf("%d %d\n", n, total);
	    assert(0 && "over run\n");
	  }
	}
      }
    }

    lastYStep = yStep;
    int k1 = y;

    int xt = 0;
    int xSrc = 0;
    int x1 = k1;
    int n = yStep > 0 ? yStep : 1;
    int origN = n;

    /* compute the size of padding and pixels that will be used for this row */
    int head_pad_size = MIN(n, head_pad);
    n -= head_pad_size;
    head_pad -= MIN(head_pad_size, yStep);

    int pix_size = MIN(n, origHeight);
    n -= pix_size;
    origHeight -= MIN(pix_size, yStep);

    int tail_pad_size = MIN(n, tail_pad);
    n -= tail_pad_size;
    tail_pad -= MIN(tail_pad_size, yStep);
    if (n != 0) {
      printf("n = %d (%d %d %d)\n", n, head_pad_size, pix_size, tail_pad_size);
      assert(n == 0);
    }

    for (int x = 0; x < scaledWidth; ++x) {
      int xStep = xp;
      xt += xq;
      if (xt >= scaledWidth) {
	xt -= scaledWidth;
	++xStep;
      }
      int m = xStep > 0 ? xStep : 1;
      float pixAcc0 = 0;
      /* could m * head_pad_size * tail_pad_size  overflow? */
      if (invert_bit) {
	pixAcc0 += m * head_pad_size * tail_pad_size * 255;
      } else {
	pixAcc0 += m * head_pad_size * tail_pad_size * 0;
      }
      /* Accumulate all of the source pixels for the destination pixel */
      for (int i = 0; i < pix_size; ++i) {
	for (int j = 0; j< m; ++j) {
	  if (xSrc + i*width + j > MIN(yp + 1, origHeight_c)*width) {
	    printf("%d > %d (%d %d %d %d) (%d %d %d)\n", xSrc + i*width + j, MIN(yp + 1, origHeight_c)*width, xSrc, i , width, j, yp, origHeight_c, width);
	    printf("%d %d %d\n", head_pad_size, pix_size, tail_pad_size);
	    assert(0 && "bad access\n");
	  }
	  pixAcc0 += pixBuf[xSrc + i*width + j];
	}
      }
      buffer[y * row_stride + x] = splashFloor(pixAcc0 / (origN*m));
      xSrc += xStep;
      x1 += 1;
    }

  }
  free(pixBuf);

  //XXX: we should handle error's better than this
  image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_A8,
      scaledWidth, scaledHeight, row_stride);
  if (image == NULL) {
1447
    imgStr->close();
1448 1449 1450 1451 1452
    delete imgStr;
    return;
  }
  pattern = cairo_pattern_create_for_surface (image);
  if (pattern == NULL) {
1453
    imgStr->close();
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    delete imgStr;
    return;
  }

  /* we should actually be using CAIRO_FILTER_NEAREST here. However,
   * cairo doesn't yet do minifaction filtering causing scaled down
   * images with CAIRO_FILTER_NEAREST to look really bad */
  cairo_pattern_set_filter (pattern, CAIRO_FILTER_BEST);

  cairo_save (cairo);

  /* modify our current transformation so that the prescaled image
   * goes where it is supposed to */
  cairo_get_matrix(cairo, &matrix);
  cairo_scale(cairo, 1.0/matrix.xx, 1.0/matrix.yy);
  // get integer co-ords
  cairo_translate (cairo, tx - matrix.x0, ty2 - matrix.y0);
  if (yScale > 0)
    cairo_scale