aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
blob: 1512f4eb9f15ca12c496f9bb1860dc444101338d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.render.awt.viewer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.area.PageViewport;

import org.apache.fop.render.awt.AWTRenderer;


/**
 * <p>Holds a scrollpane with the rendered page(s) and handles actions performed
 * to alter the display of the page.
 * </p>
 * <p>Use PreviewPanel when you want to embed a preview in your own application
 * with your own controls. Use PreviewDialog when you want to use the standard
 * Fop controls.
 * </p>   
 * <p>In order to embed a PreviewPanel in your own app, create your own renderer,
 * and your own agent. In order to support reloads, you may also implement your
 * own Renderable extension or the default InputHandler. Setting the Renderable
 * to null works fine though.
 * Then call setPreviewDialogDisplayed(false) to hide the
 * default dialog. Finally create a preview panel with the agent, renderable and
 * renderer and add it to your gui:
 * </p>
 * <pre>
 * AWTRenderer renderer = new AWTRenderer();
 * FOUserAgent agent = new FOUserAgent();
 * agent.setRendererOverride(renderer);
 * renderer.setPreviewDialogDisplayed(false);
 * renderer.setUserAgent(agent);
 * previewPanel = new PreviewPanel(agent, null, renderer);
 * previewPanel = new PreviewPanel(ua);
 * myGui.add(previewPanel);
 * </pre>
 *
 * In order to set options and display a page do:
 * <pre>
 * renderer.clearViewportList();
 * // build report xml here
 * reload(); // optional if setting changed
 * </pre>
 *
 * If you wan't to change settings, don't call reload. A good example is
 * to set the page to fill the screen and set the scrolling mode:
 * <pre>
 * double scale = previewPanel.getScaleToFitWindow();
 * previewPanel.setScaleFactor(scale);
 * previewPanel.setDisplayMode(PreviewPanel.CONTINUOUS);
 * </pre>
 */
public class PreviewPanel extends JPanel {

    /** Constant for setting single page display. */
    public static final int SINGLE = 1;
    /** Constant for setting continuous page display. */
    public static final int CONTINUOUS = 2;
    /** Constant for displaying even/odd pages side by side in continuous form. */
    public static final int CONT_FACING = 3;

    /** The number of pixels left empty at the top bottom and sides of the page. */
    private static final int BORDER_SPACING = 10;

    /** The main display area */
    private JScrollPane previewArea;

    /** The AWT renderer - often shared with PreviewDialog */
    private AWTRenderer renderer;

    /** The FOUserAgent associated with this panel - often shared with PreviewDialog */
    protected FOUserAgent foUserAgent;
    /**
     * Renderable instance that can be used to reload and re-render a document after 
     * modifications.
     */
    protected Renderable renderable;
    /** The number of the page which is currently selected */
    private int currentPage = 0;

    /** The index of the first page displayed on screen. */
    private int firstPage = 0;

    /** The number of pages concurrently displayed on screen. */
    private int pageRange = 1;

    /** The display mode. One of SINGLE, CONTINUOUS or CONT_FACING. */
    private int displayMode = SINGLE;

    /** The component(s) that hold the rendered page(s) */
    private ImageProxyPanel[] pagePanels = null;

    /**
     * Panel showing the page panels in a grid. Usually the dimensions
     * of the grid are 1x1, nx1 or nx2.
     */
    private JPanel gridPanel = null;

    /** Asynchronous reloader thread, used when reload() method is called. */
    private Reloader reloader;

    /**
     * Allows any mouse drag on the page area to scroll the display window.
     */
    private ViewportScroller scroller;

        
    /**
     * Creates a new PreviewPanel instance.
     * @param foUserAgent the user agent
     * @param renderable the Renderable instance that is used to reload/re-render a document
     *                   after modifications.
     * @param renderer the AWT Renderer instance to paint with
     */
    public PreviewPanel(FOUserAgent foUserAgent, Renderable renderable, AWTRenderer renderer) {
        super(new GridLayout(1, 1));
        this.renderable = renderable;
        this.renderer = renderer;
        this.foUserAgent = foUserAgent;

        gridPanel = new JPanel();
        gridPanel.setLayout(new GridLayout(0, 1)); // rows, cols

        previewArea = new JScrollPane(gridPanel);
        previewArea.getViewport().setBackground(Color.gray);

        // FIXME should add scroll wheel support here at some point.
        scroller = new ViewportScroller(previewArea.getViewport());
        previewArea.addMouseListener(scroller);
        previewArea.addMouseMotionListener(scroller);

        previewArea.setMinimumSize(new Dimension(50, 50));
        add(previewArea);
    }
        
    /**
     * @return the currently visible page
     */
    public int getPage() {
        return currentPage;
    }

    /**
     * Selects the given page, displays it on screen and notifies
     * listeners about the change in selection.
     * @param number the page number
     */
    public void setPage(int number) {
        if (displayMode == CONTINUOUS || displayMode == CONT_FACING) {
            // FIXME Should scroll so page is visible
            currentPage = number;
        } else { // single page mode
            currentPage = number;
            firstPage = currentPage;
        }
        showPage();
    }

    /**
     * Sets the display mode.
     * @param mode One of SINGLE, CONTINUOUS or CONT_FACING.
     */
    public void setDisplayMode(int mode) {
        if (mode != displayMode) {
            displayMode = mode;
            gridPanel.setLayout(new GridLayout(0, displayMode == CONT_FACING ? 2 : 1));
            reload();
        }
    }

    /**
     * Returns the display mode.
     * @return mode One of SINGLE, CONTINUOUS or CONT_FACING.
     */
    public int getDisplayMode() {
        return displayMode;
    }

    /**
     * Reloads and reformats document.
     */
    public synchronized void reload() {
        if (reloader == null || !reloader.isAlive()) {
            reloader = new Reloader();
            reloader.start();
        }
    }

    /**
     * Allows a (yet) simple visual debug of the document.
     */
    void debug() {
        renderer.debug = !renderer.debug;
        reload();
    }

    /**
     * Allows any mouse drag on the page area to scroll the display window.
     */
    private class ViewportScroller implements MouseListener, MouseMotionListener {
        /** The viewport to be scrolled */
        private final JViewport viewport;
        /** Starting position of a mouse drag - X co-ordinate */
        private int startPosX = 0;
        /** Starting position of a mouse drag - Y co-ordinate */
        private int startPosY = 0;
        
        ViewportScroller(JViewport vp) {
            viewport = vp;
        }

        // ***** MouseMotionListener *****              

        public synchronized void mouseDragged(MouseEvent e) {
            if (viewport == null) {
                return;
            }
            int x = e.getX();
            int y = e.getY();
            int xmove = x - startPosX;
            int ymove = y - startPosY;
            int viewWidth = viewport.getExtentSize().width;
            int viewHeight = viewport.getExtentSize().height;
            int imageWidth = viewport.getViewSize().width;
            int imageHeight = viewport.getViewSize().height;
            
            Point viewPoint = viewport.getViewPosition();
            int viewX = Math.max(0, Math.min(imageWidth - viewWidth, viewPoint.x - xmove));
            int viewY = Math.max(0, Math.min(imageHeight - viewHeight, viewPoint.y - ymove));

            viewport.setViewPosition(new Point(viewX, viewY));

            startPosX = x;
            startPosY = y;
        }

        public void mouseMoved(MouseEvent e) { }

        // ***** MouseListener *****

        public void mousePressed(MouseEvent e) {
            startPosX = e.getX();
            startPosY = e.getY();
        }

        public void mouseExited(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseClicked(MouseEvent e) { }
        public void mouseReleased(MouseEvent e) {   }
    }

    /**
     * This class is used to reload document in a thread safe way.
     */
    private class Reloader extends Thread {

        public void run() {
            if (!renderer.isRenderingDone()) {
                // do not allow the reloading while FOP is still rendering
                JOptionPane.showMessageDialog(previewArea,
                        "Cannot perform the requested operation until "
                                + "all page are rendered. Please wait",
                        "Please wait ", 1 /* INFORMATION_MESSAGE */);
                return;
            }

            pagePanels = null;

            int savedCurrentPage = currentPage;
            currentPage = 0;

            gridPanel.removeAll();
            switch(displayMode) {
                case CONT_FACING:
                    // This page intentionally left blank
                    // Makes 0th/1st page on rhs
                    gridPanel.add(new JLabel(""));
                case CONTINUOUS:
                    currentPage = 0;
                    firstPage = 0;
                    pageRange = renderer.getNumberOfPages();
                    break;
                case SINGLE:
                default:
                    currentPage = 0;
                    firstPage = 0;
                    pageRange = 1;
                    break;
            }

            pagePanels = new ImageProxyPanel[pageRange];
            for (int pg = 0; pg < pageRange; pg++) {
                pagePanels[pg] = new ImageProxyPanel(renderer, pg + firstPage);
                pagePanels[pg].setBorder(new EmptyBorder(
                        BORDER_SPACING, BORDER_SPACING, BORDER_SPACING, BORDER_SPACING));
                gridPanel.add(pagePanels[pg]);
            }

            try {
                if (renderable != null) {
                    renderer.clearViewportList();
                    renderable.renderTo(foUserAgent, MimeConstants.MIME_FOP_AWT_PREVIEW);
                }
            } catch (FOPException e) {
                e.printStackTrace();
                // FIXME Should show exception in gui - was reportException(e);
            }

            setPage(savedCurrentPage);
        }
    }

    /**
     * Scales page image
     * @param scale [0;1]
     */
    public void setScaleFactor(double scale) {
        renderer.setScaleFactor(scale);
        reload();
    }

    /**
     * Returns the scale factor required in order to fit either the current
     * page within the current window or to fit two adjacent pages within
     * the display if the displaymode is continuous.
     * @return the requested scale factor
     * @throws FOPException in case of an error while fetching the PageViewport
     */
    public double getScaleToFitWindow() throws FOPException {
        Dimension extents = previewArea.getViewport().getExtentSize();
        return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING,
                    extents.getHeight() - 2 * BORDER_SPACING);
    }

    /**
     * As getScaleToFitWindow, but ignoring the Y axis.
     * @return the requested scale factor
     * @throws FOPException in case of an error while fetching the PageViewport
     */
    public double getScaleToFitWidth() throws FOPException {
        Dimension extents = previewArea.getViewport().getExtentSize();
        return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, Double.MAX_VALUE);
    }

    /**
     * Returns the scale factor required in order to fit either the current page or
     * two adjacent pages within a window of the given height and width, depending
     * on the display mode. In order to ignore either dimension,
     * just specify it as Double.MAX_VALUE.
     * @param viewWidth width of the view
     * @param viewHeight height of the view
     * @return the requested scale factor
     * @throws FOPException in case of an error while fetching the PageViewport
     */
    public double getScaleToFit(double viewWidth, double viewHeight) throws FOPException {
        PageViewport pageViewport = renderer.getPageViewport(currentPage);
        Rectangle2D pageSize = pageViewport.getViewArea();
        double widthScale = viewWidth / (pageSize.getWidth() / 1000f);
        double heightScale = viewHeight / (pageSize.getHeight() / 1000f);
        return Math.min(displayMode == CONT_FACING ? widthScale / 2 : widthScale, heightScale);
    }

    /** Starts rendering process and shows the current page. */
    public synchronized void showPage() {
        ShowPageImage viewer = new ShowPageImage();

        if (SwingUtilities.isEventDispatchThread()) {
            viewer.run();
        } else {
            SwingUtilities.invokeLater(viewer);
        }
    }

    /** This class is used to render the page image in a thread safe way. */
    private class ShowPageImage implements Runnable {

        /**
         * The run method that does the actual rendering of the viewed page
         */
        public void run() {
            for (int pg = firstPage; pg < firstPage + pageRange; pg++) {
                pagePanels[pg - firstPage].setPage(pg);
            }
            revalidate();
        }
    }
}