aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
blob: b1e6e0c2964432d2b217474ad35f4aa88c01ba69 (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
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
/*
 * Copyright 1999-2005 The Apache Software Foundation.
 *
 * Licensed 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$ */

// Originally contributed by:
// Juergen Verwohlt: Juergen.Verwohlt@jCatalog.com,
// Rainer Steinkuhle: Rainer.Steinkuhle@jCatalog.com,
// Stanislav Gorkhover: Stanislav.Gorkhover@jCatalog.com
package org.apache.fop.render.awt.viewer;

// Java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.fo.Constants;
import org.apache.fop.render.awt.AWTRenderer;

/** AWT Viewer main window. */
public class PreviewDialog extends JFrame {

    /** The Translator for localization */
    protected Translator translator;
    /** The AWT renderer */
    protected AWTRenderer renderer;
    /** The FOUserAgent associated with this window */
    protected FOUserAgent foUserAgent;
    /** The Fop object used for refreshing/reloading the view */
    protected Fop fop;

    /** The number of the page which is currently visible */
    private int currentPage = 0;

    /** The Reloader, when the user clicks on menu "reload" */
    private Reloader reloader;

    /** The JCombobox to rescale the rendered page view */
    private JComboBox scale;

    /** The JLabel for the process status bar */
    private JLabel processStatus;

    /** The JLabel that holds the rendered page */
    private JLabel pageLabel;

    /** The JLabel information status bar */
    private JLabel infoStatus;

    /**
     * Creates a new PreviewDialog that uses the given renderer.
     * @param aRenderer the to use renderer
     */
    public PreviewDialog(FOUserAgent foUserAgent) {
        renderer = (AWTRenderer) foUserAgent.getRendererOverride();
        this.foUserAgent = foUserAgent;
        translator = renderer.getTranslator();

        //Commands aka Actions
        Command printAction = new Command(translator.getString("Menu.Print"), "Print") {
            public void doit() {
                startPrinterJob();
            }
        };
        Command firstPageAction = new Command(translator.getString("Menu.First.page"),
                                      "firstpg") {
            public void doit() {
                goToFirstPage();
            }
        };
        Command previousPageAction = new Command(translator.getString("Menu.Prev.page"),
                                         "prevpg") {
            public void doit() {
                goToPreviousPage();
            }
        };
        Command nextPageAction = new Command(translator.getString("Menu.Next.page"), "nextpg") {
            public void doit() {
                goToNextPage();
            }

        };
        Command lastPageAction = new Command(translator.getString("Menu.Last.page"), "lastpg") {
            public void doit() {
                goToLastPage();
            }
        };
        Command reloadAction = new Command(translator.getString("Menu.Reload"), "reload") {
            public void doit() {
                reload();
            }
        };
        Command debugAction = new Command("   Debug") {
            // TODO use Translator
            public void doit() {
                debug();
            }
        };
        Command aboutAction = new Command("About FOP", "fopLogo") {
            public void doit() {
                startHelpAbout();
            }
        };

        //set the system look&feel
        try {
            UIManager.setLookAndFeel(
                UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) { }

        setTitle("FOP: AWT-" + translator.getString("Title.Preview"));
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //Sets size to be 61%x90% of the screen size
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        //Rather frivolous size - fits A4 page width in 1024x768 screen on my desktop
        setSize(screen.width * 61 / 100, screen.height * 9 / 10);

        //Page view stuff
        pageLabel = new JLabel();
        pageLabel.setHorizontalAlignment(0 /* CENTER */);
        pageLabel.setBorder(new EmptyBorder(20, 0, 20, 0));
        JScrollPane previewArea = new JScrollPane(pageLabel);
        previewArea.getViewport().setBackground(Color.gray);
        previewArea.setMinimumSize(new Dimension(50, 50));
        getContentPane().add(previewArea, BorderLayout.CENTER);

        //Scaling combobox
        scale = new JComboBox();
        scale.addItem("25%");
        scale.addItem("50%");
        scale.addItem("75%");
        scale.addItem("100%");
        scale.addItem("150%");
        scale.addItem("200%");
        scale.addItem("400%");
        scale.setMaximumSize(new Dimension(80, 24));
        scale.setPreferredSize(new Dimension(80, 24));
        scale.setSelectedItem("100%");
        scale.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                scaleActionPerformed(e);
            }
        });

        //Menu
        setJMenuBar(setupMenu());

        // Toolbar
        JToolBar toolBar = new JToolBar();
        toolBar.add(printAction);
        toolBar.add(reloadAction);
        toolBar.addSeparator();
        toolBar.add(firstPageAction);
        toolBar.add(previousPageAction);
        toolBar.add(nextPageAction);
        toolBar.add(lastPageAction);
        toolBar.addSeparator(new Dimension(20,0));
        toolBar.add(new JLabel(translator.getString("Menu.Zoom")));
        toolBar.add(scale);
        toolBar.addSeparator();
        toolBar.add(debugAction);
        toolBar.addSeparator(new Dimension(60,0));
        toolBar.add(aboutAction);
        getContentPane().add(toolBar, BorderLayout.NORTH);

        // Status bar
        JPanel statusBar = new JPanel();
        processStatus = new JLabel();
        processStatus.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEtchedBorder(),
                BorderFactory.createEmptyBorder(0, 3, 0, 0)));
        infoStatus = new JLabel();
        infoStatus.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createEtchedBorder(),
                BorderFactory.createEmptyBorder(0, 3, 0, 0)));

        statusBar.setLayout(new GridBagLayout());

        processStatus.setPreferredSize(new Dimension(200, 21));
        processStatus.setMinimumSize(new Dimension(200, 21));

        infoStatus.setPreferredSize(new Dimension(100, 21));
        infoStatus.setMinimumSize(new Dimension(100, 21));
        statusBar.add(processStatus,
                      new GridBagConstraints(0, 0, 1, 0, 2.0, 0.0,
                                             GridBagConstraints.CENTER,
                                             GridBagConstraints.HORIZONTAL,
                                             new Insets(0, 0, 0, 3), 0, 0));
        statusBar.add(infoStatus,
                      new GridBagConstraints(1, 0, 1, 0, 1.0, 0.0,
                                             GridBagConstraints.CENTER,
                                             GridBagConstraints.HORIZONTAL,
                                             new Insets(0, 0, 0, 0), 0, 0));
        getContentPane().add(statusBar, BorderLayout.SOUTH);
    }

    /**
     * Creates a new menubar to be shown in this window.
     * @return the newly created menubar
     */
    private JMenuBar setupMenu() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu(translator.getString("Menu.File"));

        //Adds mostly the same actions, but without icons
        menu.add(new Command(translator.getString("Menu.Print")) {
            public void doit() {
                startPrinterJob();
            }
        });
        // inputHandler must be set to allow reloading
        if (foUserAgent.getInputHandler() != null) {
            menu.add(new Command(translator.getString("Menu.Reload")) {
                public void doit() {
                    reload();
                }
            });
        }
        menu.addSeparator();
        menu.add(new Command(translator.getString("Menu.Exit")) {
            public void doit() {
                dispose();
            }
        });
        menuBar.add(menu);
        menu = new JMenu(translator.getString("Menu.View"));
        menu.add(new Command(translator.getString("Menu.First.page")) {
            public void doit() {
                goToFirstPage();
            }
        });
        menu.add(new Command(translator.getString("Menu.Prev.page")) {
            public void doit() {
                goToPreviousPage();
            }
        });
        menu.add(new Command(translator.getString("Menu.Next.page")) {
            public void doit() {
                goToNextPage();
            }
        });
        menu.add(new Command(translator.getString("Menu.Last.page")) {
            public void doit() {
                goToLastPage();
            }
        });
        menu.add(new Command(translator.getString("Menu.Go.to.Page") + " ...") {
            public void doit() {
                showGoToPageDialog();
            }
        });
        menu.addSeparator();
        JMenu subMenu = new JMenu(translator.getString("Menu.Zoom"));
        subMenu.add(new Command("25%") {
            public void doit() {
                setScale(25.0);
            }
        });
        subMenu.add(new Command("50%") {
            public void doit() {
                setScale(50.0);
            }
        });
        subMenu.add(new Command("75%") {
            public void doit() {
                setScale(75.0);
            }
        });
        subMenu.add(new Command("100%") {
            public void doit() {
                setScale(100.0);
            }
        });
        subMenu.add(new Command("150%") {
            public void doit() {
                setScale(150.0);
            }
        });
        subMenu.add(new Command("200%") {
            public void doit() {
                setScale(200.0);
            }
        });
        subMenu.add(new Command("400%") {
            public void doit() {
                setScale(400.0);
            }
        });
        menu.add(subMenu);
        menu.addSeparator();
        menu.add(new Command(translator.getString("Menu.Default.zoom")) {
            public void doit() {
                setScale(100.0);
            }
        });
        menuBar.add(menu);
        menu = new JMenu(translator.getString("Menu.Help"));
        menu.add(new Command(translator.getString("Menu.About")) {
            public void doit() {
                startHelpAbout();
            }
        });
        menuBar.add(menu);
        return menuBar;
    }

    /** Shows the About box */
    private void startHelpAbout() {
        PreviewDialogAboutBox dlg = new PreviewDialogAboutBox(this, translator);
        //Centers the box
        Dimension dlgSize = dlg.getPreferredSize();
        Dimension frmSize = getSize();
        Point loc = getLocation();
        dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x,
                        (frmSize.height - dlgSize.height) / 2 + loc.y);
        dlg.setVisible(true);
    }

    /**
     * Changes the current visible page
     * @param number the page number to go to
     */
      private void goToPage(int number) {
        currentPage = number;
        showPage();
        setInfo();
    }

    /**
     * Shows the previous page.
     */
    private void goToPreviousPage() {
        if (currentPage <= 0) {
            return;
        }
        currentPage--;
        goToPage(currentPage);
    }

    /**
     * Shows the next page.
     */
    private void goToNextPage() {
        if (currentPage >= renderer.getNumberOfPages() - 1) {
            return;
        }
        currentPage++;
        goToPage(currentPage);
    }

    /**
     * Shows the last page.
     */
    private void goToLastPage() {
        if (currentPage == renderer.getNumberOfPages() - 1) {
            return;
        }
        currentPage = renderer.getNumberOfPages() - 1;
        goToPage(currentPage);
    }

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

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

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

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

            if (fop == null) {
                fop = new Fop(Constants.RENDER_AWT, foUserAgent);
            }

            pageLabel.setIcon(null);
            int savedCurrentPage = currentPage;
            currentPage = 0;
            renderer.clearViewportList();

            try {
                setStatus(translator.getString("Status.Build.FO.tree"));
                foUserAgent.getInputHandler().render(fop);
                goToPage(savedCurrentPage);
                setStatus(translator.getString("Status.Show"));
            } catch (FOPException e) {
                reportException(e);
            }
        }
    }

    /**
     * Shows "go to page" dialog and then goes to the selected page
     */
    private void showGoToPageDialog() {
        GoToPageDialog d = new GoToPageDialog(this,
            translator.getString("Menu.Go.to.Page"), translator);
        d.setLocation((int)getLocation().getX() + 50,
                      (int)getLocation().getY() + 50);
        d.setVisible(true);
        currentPage = d.getPageNumber();
        if (currentPage < 1 || currentPage > renderer.getNumberOfPages()) {
            return;
        }
        currentPage--;
        goToPage(currentPage);
    }

    /** Shows the first page. */
    private void goToFirstPage() {
        if (currentPage == 0) {
            return;
        }
        currentPage = 0;
        goToPage(currentPage);
    }

    /** Prints the document */
    private void startPrinterJob() {
        PrinterJob pj = PrinterJob.getPrinterJob();
        pj.setPageable(renderer);
        if (pj.printDialog()) {
            try {
                pj.print();
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    }

    /** Scales page image */
    private void setScale(double scaleFactor) {
        if (scaleFactor == 25.0) {
            scale.setSelectedIndex(0);
        } else if (scaleFactor == 50.0) {
            scale.setSelectedIndex(1);
        } else if (scaleFactor == 75.0) {
            scale.setSelectedIndex(2);
        } else if (scaleFactor == 100.0) {
            scale.setSelectedIndex(3);
        } else if (scaleFactor == 150.0) {
            scale.setSelectedIndex(4);
        } else if (scaleFactor == 200.0) {
            scale.setSelectedIndex(5);
        } else if (scaleFactor == 400.0) {
            scale.setSelectedIndex(6);
        }
        renderer.setScaleFactor(scaleFactor / 100d);
        reload();
    }

    private void scaleActionPerformed(ActionEvent e) {
        String item = (String)scale.getSelectedItem();
        setScale(Double.parseDouble(item.substring(0, item.indexOf('%'))));
    }

    /**
     * Sets message to be shown in the status bar in a thread safe way.
     * @param message the message
     */
    public void setStatus(String message) {
        SwingUtilities.invokeLater(new ShowStatus(message));
    }

    /** This class is used to show status in a thread safe way. */
    private class ShowStatus implements Runnable {

        /** The message to display */
        private String message;

        /**
         * Constructs ShowStatus thread
         * @param message message to display
         */
        public ShowStatus(String message) {
            this.message = message;
        }

        public void run() {
            processStatus.setText(message.toString());
        }
    }

    /**
     * Updates the message to be shown in the info bar in a thread safe way.
     */
    public void setInfo() {
        SwingUtilities.invokeLater(new ShowInfo());
    }

    /** This class is used to show info in a thread safe way. */
    private class ShowInfo implements Runnable {

        public void run() {

            String message = translator.getString("Status.Page") + " "
                    + (currentPage + 1) + " "
                    + translator.getString("Status.of") + " "
                    + renderer.getCurrentPageNumber();

            infoStatus.setText(message);
        }
    }

    /** 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() {

            setStatus(translator.getString("Status.Build.FO.tree"));

            BufferedImage pageImage = null;
            try {
                pageImage = renderer.getPageImage(currentPage);
            } catch (FOPException e) {
                reportException(e);
            }
            pageLabel.setIcon(new ImageIcon(pageImage));

            setStatus(translator.getString("Status.Show"));
        }
    }

    /**
     * Opens standard Swing error dialog box and reports given exception details.
     * @param e the Exception
     */
    public void reportException(Exception e) {
        String msg = translator.getString("Exception.Occured");
        setStatus(msg);
        JOptionPane.showMessageDialog(
            getContentPane(),
            "<html><b>" + msg + ":</b><br>"
                + e.getClass().getName() + "<br>"
                + e.getMessage() + "</html>",
            translator.getString("Exception.Error"),
            JOptionPane.ERROR_MESSAGE
        );
    }
}