1/*
2 * Copyright (C) 2007 Alp Toker <alp@atoker.com>
3 * Copyright (C) 2007 Apple Inc.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 * Library General Public License for more details.
14 *
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB.  If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
19 */
20
21#include "config.h"
22#include "PrintContext.h"
23
24#include "GraphicsContext.h"
25#include "Frame.h"
26#include "FrameView.h"
27#include "RenderView.h"
28#include "StyleInheritedData.h"
29#include <wtf/text/WTFString.h>
30
31namespace WebCore {
32
33// By imaging to a width a little wider than the available pixels,
34// thin pages will be scaled down a little, matching the way they
35// print in IE and Camino. This lets them use fewer sheets than they
36// would otherwise, which is presumably why other browsers do this.
37// Wide pages will be scaled down more than this.
38const float printingMinimumShrinkFactor = 1.25f;
39
40// This number determines how small we are willing to reduce the page content
41// in order to accommodate the widest line. If the page would have to be
42// reduced smaller to make the widest line fit, we just clip instead (this
43// behavior matches MacIE and Mozilla, at least)
44const float printingMaximumShrinkFactor = 2;
45
46PrintContext::PrintContext(Frame* frame)
47    : m_frame(frame)
48    , m_isPrinting(false)
49{
50}
51
52PrintContext::~PrintContext()
53{
54    if (m_isPrinting)
55        end();
56}
57
58void PrintContext::computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight, bool allowHorizontalTiling)
59{
60    m_pageRects.clear();
61    outPageHeight = 0;
62
63    if (!m_frame->document() || !m_frame->view() || !m_frame->document()->renderView())
64        return;
65
66    if (userScaleFactor <= 0) {
67        LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor);
68        return;
69    }
70
71    RenderView* view = m_frame->document()->renderView();
72    const IntRect& documentRect = view->documentRect();
73    FloatSize pageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(printRect.width(), printRect.height()), FloatSize(documentRect.width(), documentRect.height()));
74    float pageWidth = pageSize.width();
75    float pageHeight = pageSize.height();
76
77    outPageHeight = pageHeight; // this is the height of the page adjusted by margins
78    pageHeight -= headerHeight + footerHeight;
79
80    if (pageHeight <= 0) {
81        LOG_ERROR("pageHeight has bad value %.2f", pageHeight);
82        return;
83    }
84
85    computePageRectsWithPageSizeInternal(FloatSize(pageWidth / userScaleFactor, pageHeight / userScaleFactor), allowHorizontalTiling);
86}
87
88void PrintContext::computePageRectsWithPageSize(const FloatSize& pageSizeInPixels, bool allowHorizontalTiling)
89{
90    m_pageRects.clear();
91    computePageRectsWithPageSizeInternal(pageSizeInPixels, allowHorizontalTiling);
92}
93
94void PrintContext::computePageRectsWithPageSizeInternal(const FloatSize& pageSizeInPixels, bool allowInlineDirectionTiling)
95{
96    if (!m_frame->document() || !m_frame->view() || !m_frame->document()->renderView())
97        return;
98
99    RenderView* view = m_frame->document()->renderView();
100
101    IntRect docRect = view->documentRect();
102
103    int pageWidth = pageSizeInPixels.width();
104    int pageHeight = pageSizeInPixels.height();
105
106    bool isHorizontal = view->style()->isHorizontalWritingMode();
107
108    int docLogicalHeight = isHorizontal ? docRect.height() : docRect.width();
109    int pageLogicalHeight = isHorizontal ? pageHeight : pageWidth;
110    int pageLogicalWidth = isHorizontal ? pageWidth : pageHeight;
111
112    int inlineDirectionStart;
113    int inlineDirectionEnd;
114    int blockDirectionStart;
115    int blockDirectionEnd;
116    if (isHorizontal) {
117        if (view->style()->isFlippedBlocksWritingMode()) {
118            blockDirectionStart = docRect.maxY();
119            blockDirectionEnd = docRect.y();
120        } else {
121            blockDirectionStart = docRect.y();
122            blockDirectionEnd = docRect.maxY();
123        }
124        inlineDirectionStart = view->style()->isLeftToRightDirection() ? docRect.x() : docRect.maxX();
125        inlineDirectionEnd = view->style()->isLeftToRightDirection() ? docRect.maxX() : docRect.x();
126    } else {
127        if (view->style()->isFlippedBlocksWritingMode()) {
128            blockDirectionStart = docRect.maxX();
129            blockDirectionEnd = docRect.x();
130        } else {
131            blockDirectionStart = docRect.x();
132            blockDirectionEnd = docRect.maxX();
133        }
134        inlineDirectionStart = view->style()->isLeftToRightDirection() ? docRect.y() : docRect.maxY();
135        inlineDirectionEnd = view->style()->isLeftToRightDirection() ? docRect.maxY() : docRect.y();
136    }
137
138    unsigned pageCount = ceilf((float)docLogicalHeight / pageLogicalHeight);
139    for (unsigned i = 0; i < pageCount; ++i) {
140        int pageLogicalTop = blockDirectionEnd > blockDirectionStart ?
141                                blockDirectionStart + i * pageLogicalHeight :
142                                blockDirectionStart - (i + 1) * pageLogicalHeight;
143        if (allowInlineDirectionTiling) {
144            for (int currentInlinePosition = inlineDirectionStart;
145                 inlineDirectionEnd > inlineDirectionStart ? currentInlinePosition < inlineDirectionEnd : currentInlinePosition > inlineDirectionEnd;
146                 currentInlinePosition += (inlineDirectionEnd > inlineDirectionStart ? pageLogicalWidth : -pageLogicalWidth)) {
147                int pageLogicalLeft = inlineDirectionEnd > inlineDirectionStart ? currentInlinePosition : currentInlinePosition - pageLogicalWidth;
148                IntRect pageRect(pageLogicalLeft, pageLogicalTop, pageLogicalWidth, pageLogicalHeight);
149                if (!isHorizontal)
150                    pageRect = pageRect.transposedRect();
151                m_pageRects.append(pageRect);
152            }
153        } else {
154            int pageLogicalLeft = inlineDirectionEnd > inlineDirectionStart ? inlineDirectionStart : inlineDirectionStart - pageLogicalWidth;
155            IntRect pageRect(pageLogicalLeft, pageLogicalTop, pageLogicalWidth, pageLogicalHeight);
156            if (!isHorizontal)
157                pageRect = pageRect.transposedRect();
158            m_pageRects.append(pageRect);
159        }
160    }
161}
162
163void PrintContext::begin(float width, float height)
164{
165    // This function can be called multiple times to adjust printing parameters without going back to screen mode.
166    m_isPrinting = true;
167
168    FloatSize originalPageSize = FloatSize(width, height);
169    FloatSize minLayoutSize = m_frame->resizePageRectsKeepingRatio(originalPageSize, FloatSize(width * printingMinimumShrinkFactor, height * printingMinimumShrinkFactor));
170
171    // This changes layout, so callers need to make sure that they don't paint to screen while in printing mode.
172    m_frame->setPrinting(true, minLayoutSize, originalPageSize, printingMaximumShrinkFactor / printingMinimumShrinkFactor, AdjustViewSize);
173}
174
175float PrintContext::computeAutomaticScaleFactor(const FloatSize& availablePaperSize)
176{
177    if (!m_frame->view())
178        return 1;
179
180    bool useViewWidth = true;
181    if (m_frame->document() && m_frame->document()->renderView())
182        useViewWidth = m_frame->document()->renderView()->style()->isHorizontalWritingMode();
183
184    float viewLogicalWidth = useViewWidth ? m_frame->view()->contentsWidth() : m_frame->view()->contentsHeight();
185    if (viewLogicalWidth < 1)
186        return 1;
187
188    float maxShrinkToFitScaleFactor = 1 / printingMaximumShrinkFactor;
189    float shrinkToFitScaleFactor = (useViewWidth ? availablePaperSize.width() : availablePaperSize.height()) / viewLogicalWidth;
190    return max(maxShrinkToFitScaleFactor, shrinkToFitScaleFactor);
191}
192
193void PrintContext::spoolPage(GraphicsContext& ctx, int pageNumber, float width)
194{
195    // FIXME: Not correct for vertical text.
196    IntRect pageRect = m_pageRects[pageNumber];
197    float scale = width / pageRect.width();
198
199    ctx.save();
200    ctx.scale(FloatSize(scale, scale));
201    ctx.translate(-pageRect.x(), -pageRect.y());
202    ctx.clip(pageRect);
203    m_frame->view()->paintContents(&ctx, pageRect);
204    ctx.restore();
205}
206
207void PrintContext::spoolRect(GraphicsContext& ctx, const IntRect& rect)
208{
209    // FIXME: Not correct for vertical text.
210    ctx.save();
211    ctx.translate(-rect.x(), -rect.y());
212    ctx.clip(rect);
213    m_frame->view()->paintContents(&ctx, rect);
214    ctx.restore();
215}
216
217void PrintContext::end()
218{
219    ASSERT(m_isPrinting);
220    m_isPrinting = false;
221    m_frame->setPrinting(false, FloatSize(), FloatSize(), 0, AdjustViewSize);
222}
223
224static RenderBoxModelObject* enclosingBoxModelObject(RenderObject* object)
225{
226
227    while (object && !object->isBoxModelObject())
228        object = object->parent();
229    if (!object)
230        return 0;
231    return toRenderBoxModelObject(object);
232}
233
234int PrintContext::pageNumberForElement(Element* element, const FloatSize& pageSizeInPixels)
235{
236    // Make sure the element is not freed during the layout.
237    RefPtr<Element> elementRef(element);
238    element->document()->updateLayout();
239
240    RenderBoxModelObject* box = enclosingBoxModelObject(element->renderer());
241    if (!box)
242        return -1;
243
244    Frame* frame = element->document()->frame();
245    FloatRect pageRect(FloatPoint(0, 0), pageSizeInPixels);
246    PrintContext printContext(frame);
247    printContext.begin(pageRect.width(), pageRect.height());
248    FloatSize scaledPageSize = pageSizeInPixels;
249    scaledPageSize.scale(frame->view()->contentsSize().width() / pageRect.width());
250    printContext.computePageRectsWithPageSize(scaledPageSize, false);
251
252    int top = box->pixelSnappedOffsetTop();
253    int left = box->pixelSnappedOffsetLeft();
254    size_t pageNumber = 0;
255    for (; pageNumber < printContext.pageCount(); pageNumber++) {
256        const IntRect& page = printContext.pageRect(pageNumber);
257        if (page.x() <= left && left < page.maxX() && page.y() <= top && top < page.maxY())
258            return pageNumber;
259    }
260    return -1;
261}
262
263String PrintContext::pageProperty(Frame* frame, const char* propertyName, int pageNumber)
264{
265    Document* document = frame->document();
266    PrintContext printContext(frame);
267    printContext.begin(800); // Any width is OK here.
268    document->updateLayout();
269    RefPtr<RenderStyle> style = document->styleForPage(pageNumber);
270
271    // Implement formatters for properties we care about.
272    if (!strcmp(propertyName, "margin-left")) {
273        if (style->marginLeft().isAuto())
274            return String("auto");
275        return String::number(style->marginLeft().value());
276    }
277    if (!strcmp(propertyName, "line-height"))
278        return String::number(style->lineHeight().value());
279    if (!strcmp(propertyName, "font-size"))
280        return String::number(style->fontDescription().computedPixelSize());
281    if (!strcmp(propertyName, "font-family"))
282        return style->fontDescription().firstFamily();
283    if (!strcmp(propertyName, "size"))
284        return String::number(style->pageSize().width().value()) + ' ' + String::number(style->pageSize().height().value());
285
286    return String("pageProperty() unimplemented for: ") + propertyName;
287}
288
289bool PrintContext::isPageBoxVisible(Frame* frame, int pageNumber)
290{
291    return frame->document()->isPageBoxVisible(pageNumber);
292}
293
294String PrintContext::pageSizeAndMarginsInPixels(Frame* frame, int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft)
295{
296    IntSize pageSize(width, height);
297    frame->document()->pageSizeAndMarginsInPixels(pageNumber, pageSize, marginTop, marginRight, marginBottom, marginLeft);
298
299    return "(" + String::number(pageSize.width()) + ", " + String::number(pageSize.height()) + ") " +
300           String::number(marginTop) + ' ' + String::number(marginRight) + ' ' + String::number(marginBottom) + ' ' + String::number(marginLeft);
301}
302
303int PrintContext::numberOfPages(Frame* frame, const FloatSize& pageSizeInPixels)
304{
305    frame->document()->updateLayout();
306
307    FloatRect pageRect(FloatPoint(0, 0), pageSizeInPixels);
308    PrintContext printContext(frame);
309    printContext.begin(pageRect.width(), pageRect.height());
310    // Account for shrink-to-fit.
311    FloatSize scaledPageSize = pageSizeInPixels;
312    scaledPageSize.scale(frame->view()->contentsSize().width() / pageRect.width());
313    printContext.computePageRectsWithPageSize(scaledPageSize, false);
314    return printContext.pageCount();
315}
316
317void PrintContext::spoolAllPagesWithBoundaries(Frame* frame, GraphicsContext& graphicsContext, const FloatSize& pageSizeInPixels)
318{
319    if (!frame->document() || !frame->view() || !frame->document()->renderer())
320        return;
321
322    frame->document()->updateLayout();
323
324    PrintContext printContext(frame);
325    printContext.begin(pageSizeInPixels.width(), pageSizeInPixels.height());
326
327    float pageHeight;
328    printContext.computePageRects(FloatRect(FloatPoint(0, 0), pageSizeInPixels), 0, 0, 1, pageHeight);
329
330    const float pageWidth = pageSizeInPixels.width();
331    const Vector<IntRect>& pageRects = printContext.pageRects();
332    int totalHeight = pageRects.size() * (pageSizeInPixels.height() + 1) - 1;
333
334    // Fill the whole background by white.
335    graphicsContext.setFillColor(Color(255, 255, 255), ColorSpaceDeviceRGB);
336    graphicsContext.fillRect(FloatRect(0, 0, pageWidth, totalHeight));
337
338    graphicsContext.save();
339    graphicsContext.translate(0, totalHeight);
340    graphicsContext.scale(FloatSize(1, -1));
341
342    int currentHeight = 0;
343    for (size_t pageIndex = 0; pageIndex < pageRects.size(); pageIndex++) {
344        // Draw a line for a page boundary if this isn't the first page.
345        if (pageIndex > 0) {
346            graphicsContext.save();
347            graphicsContext.setStrokeColor(Color(0, 0, 255), ColorSpaceDeviceRGB);
348            graphicsContext.setFillColor(Color(0, 0, 255), ColorSpaceDeviceRGB);
349            graphicsContext.drawLine(IntPoint(0, currentHeight),
350                                     IntPoint(pageWidth, currentHeight));
351            graphicsContext.restore();
352        }
353
354        graphicsContext.save();
355        graphicsContext.translate(0, currentHeight);
356        printContext.spoolPage(graphicsContext, pageIndex, pageWidth);
357        graphicsContext.restore();
358
359        currentHeight += pageSizeInPixels.height() + 1;
360    }
361
362    graphicsContext.restore();
363}
364
365}
366