1 package tim.prune.save;
3 import java.awt.BorderLayout;
5 import java.awt.Component;
6 import java.awt.FlowLayout;
8 import java.awt.FontMetrics;
9 import java.awt.Graphics;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.event.KeyAdapter;
13 import java.awt.event.KeyEvent;
15 import java.io.IOException;
17 import javax.imageio.ImageIO;
18 import javax.swing.BorderFactory;
19 import javax.swing.BoxLayout;
20 import javax.swing.JButton;
21 import javax.swing.JCheckBox;
22 import javax.swing.JDialog;
23 import javax.swing.JFileChooser;
24 import javax.swing.JLabel;
25 import javax.swing.JOptionPane;
26 import javax.swing.JPanel;
29 import tim.prune.GenericFunction;
30 import tim.prune.I18nManager;
31 import tim.prune.config.ColourScheme;
32 import tim.prune.config.Config;
33 import tim.prune.data.DataPoint;
34 import tim.prune.data.DoubleRange;
35 import tim.prune.data.Track;
36 import tim.prune.gui.BaseImageDefinitionPanel;
37 import tim.prune.gui.GuiGridLayout;
38 import tim.prune.gui.WholeNumberField;
39 import tim.prune.gui.map.MapSource;
40 import tim.prune.gui.map.MapSourceLibrary;
41 import tim.prune.gui.map.MapUtils;
42 import tim.prune.load.GenericFileFilter;
43 import tim.prune.threedee.ImageDefinition;
46 * Class to handle the exporting of map images, optionally with track data drawn on top.
47 * This allows images larger than the screen to be generated.
49 public class ImageExporter extends GenericFunction implements BaseImageConsumer
51 private JDialog _dialog = null;
52 private JCheckBox _drawDataCheckbox = null;
53 private JCheckBox _drawTrackPointsCheckbox = null;
54 private WholeNumberField _textScaleField = null;
55 private BaseImageDefinitionPanel _baseImagePanel = null;
56 private JFileChooser _fileChooser = null;
57 private JButton _okButton = null;
61 * @param inApp App object
63 public ImageExporter(App inApp)
68 /** Get the name key */
69 public String getNameKey() {
70 return "function.exportimage";
74 * Begin the function by showing the input dialog
81 _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
82 _dialog.setLocationRelativeTo(_parentFrame);
83 _dialog.getContentPane().add(makeDialogComponents());
85 _textScaleField.setValue(100);
88 // Check if there is a cache to use
89 if (!BaseImageConfigDialog.isImagePossible())
91 _app.showErrorMessage(getNameKey(), "dialog.exportimage.noimagepossible");
95 _baseImagePanel.updateBaseImageDetails();
98 _dialog.setVisible(true);
102 * Make the dialog components to select the export options
103 * @return Component holding gui elements
105 private Component makeDialogComponents()
107 JPanel panel = new JPanel();
108 panel.setLayout(new BorderLayout(4, 4));
109 // Checkbox for drawing track or not
110 _drawDataCheckbox = new JCheckBox(I18nManager.getText("dialog.exportimage.drawtrack"));
111 _drawDataCheckbox.setSelected(true); // draw by default
112 // Also whether to draw track points or not
113 _drawTrackPointsCheckbox = new JCheckBox(I18nManager.getText("dialog.exportimage.drawtrackpoints"));
114 _drawTrackPointsCheckbox.setSelected(true);
115 // Add listener to en/disable trackpoints checkbox
116 _drawDataCheckbox.addActionListener(new ActionListener() {
117 public void actionPerformed(ActionEvent arg0) {
118 _drawTrackPointsCheckbox.setEnabled(_drawDataCheckbox.isSelected());
122 // TODO: Maybe have other controls such as line width, symbol scale factor
123 JPanel controlsPanel = new JPanel();
124 GuiGridLayout grid = new GuiGridLayout(controlsPanel);
125 grid.add(new JLabel(I18nManager.getText("dialog.exportimage.textscalepercent") + ": "));
126 _textScaleField = new WholeNumberField(3);
127 _textScaleField.setText("888");
128 grid.add(_textScaleField);
130 // OK, Cancel buttons
131 JPanel buttonPanel = new JPanel();
132 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
133 _okButton = new JButton(I18nManager.getText("button.ok"));
134 _okButton.addActionListener(new ActionListener() {
135 public void actionPerformed(ActionEvent e)
138 _baseImagePanel.getGrouter().clearMapImage();
142 buttonPanel.add(_okButton);
143 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
144 cancelButton.addActionListener(new ActionListener() {
145 public void actionPerformed(ActionEvent e)
147 _baseImagePanel.getGrouter().clearMapImage();
151 buttonPanel.add(cancelButton);
152 panel.add(buttonPanel, BorderLayout.SOUTH);
154 // Listener to close dialog if escape pressed
155 KeyAdapter closer = new KeyAdapter() {
156 public void keyReleased(KeyEvent e)
158 if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
160 _baseImagePanel.getGrouter().clearMapImage();
164 _drawDataCheckbox.addKeyListener(closer);
166 // Panel for the base image
167 _baseImagePanel = new BaseImageDefinitionPanel(this, _dialog, _app.getTrackInfo().getTrack());
169 // Panel for the checkboxes at the top
170 JPanel checkPanel = new JPanel();
171 checkPanel.setLayout(new BoxLayout(checkPanel, BoxLayout.Y_AXIS));
172 checkPanel.add(_drawDataCheckbox);
173 checkPanel.add(_drawTrackPointsCheckbox);
175 // add these panels to the holder panel
176 JPanel holderPanel = new JPanel();
177 holderPanel.setLayout(new BorderLayout(5, 5));
178 holderPanel.add(checkPanel, BorderLayout.NORTH);
179 holderPanel.add(controlsPanel, BorderLayout.CENTER);
180 holderPanel.add(_baseImagePanel, BorderLayout.SOUTH);
181 holderPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
183 panel.add(holderPanel, BorderLayout.NORTH);
189 * Select the file and export data to it
191 private void doExport()
193 _okButton.setEnabled(false);
194 // OK pressed, so choose output file
195 if (_fileChooser == null)
197 _fileChooser = new JFileChooser();
198 _fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
199 _fileChooser.setFileFilter(new GenericFileFilter("filetype.png", new String[] {"png"}));
200 _fileChooser.setAcceptAllFileFilterUsed(false);
201 // start from directory in config which should be set
202 final String configDir = Config.getConfigString(Config.KEY_TRACK_DIR);
203 if (configDir != null) {_fileChooser.setCurrentDirectory(new File(configDir));}
206 // Allow choose again if an existing file is selected
207 boolean chooseAgain = false;
211 if (_fileChooser.showSaveDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
213 // OK pressed and file chosen
214 File pngFile = _fileChooser.getSelectedFile();
215 if (!pngFile.getName().toLowerCase().endsWith(".png"))
217 pngFile = new File(pngFile.getAbsolutePath() + ".png");
219 // Check if file exists and if necessary prompt for overwrite
220 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
221 if (!pngFile.exists() || JOptionPane.showOptionDialog(_parentFrame,
222 I18nManager.getText("dialog.save.overwrite.text"),
223 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
224 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
225 == JOptionPane.YES_OPTION)
228 if (!exportFile(pngFile))
230 // export failed so need to choose again
236 // overwrite cancelled so need to choose again
240 } while (chooseAgain);
244 * Export the track data to the specified file
245 * @param inPngFile File object to save to
246 * @return true if successful
248 private boolean exportFile(File inPngFile)
250 // Get the image file from the grouter
251 ImageDefinition imageDef = _baseImagePanel.getImageDefinition();
252 MapSource source = MapSourceLibrary.getSource(imageDef.getSourceIndex());
253 MapGrouter grouter = _baseImagePanel.getGrouter();
254 GroutedImage baseImage = grouter.getMapImage(_app.getTrackInfo().getTrack(), source,
256 if (baseImage == null || !baseImage.isValid())
258 _app.showErrorMessage(getNameKey(), "dialog.exportpov.cannotmakebaseimage");
263 if (_drawDataCheckbox.isSelected())
265 // Draw the track on top of this image
268 // Write composite image to file
269 if (!ImageIO.write(baseImage.getImage(), "png", inPngFile)) {
270 _app.showErrorMessage(getNameKey(), "dialog.exportpov.cannotmakebaseimage");
271 return false; // choose again - the image creation worked but the save failed
274 catch (IOException ioe) {
275 System.err.println("Can't write image: " + ioe.getClass().getName());
281 * Draw the track and waypoint data from the current Track onto the given image
282 * @param inImage GroutedImage from map tiles
284 private void drawData(GroutedImage inImage)
286 // Work out x, y limits for drawing
287 DoubleRange xRange = inImage.getXRange();
288 DoubleRange yRange = inImage.getYRange();
289 final int zoomFactor = 1 << _baseImagePanel.getImageDefinition().getZoom();
290 Graphics g = inImage.getImage().getGraphics();
291 // TODO: Set line width, style etc
292 g.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
295 final Track track = _app.getTrackInfo().getTrack();
296 final int numPoints = track.getNumPoints();
297 int prevX = 0, prevY = 0;
298 for (int i=0; i<numPoints; i++)
300 DataPoint point = track.getPoint(i);
301 if (!point.isWaypoint())
303 double x = track.getX(i) - xRange.getMinimum();
304 double y = track.getY(i) - yRange.getMinimum();
305 // use zoom level to calculate pixel coords on image
306 int px = (int) (x * zoomFactor * 256), py = (int) (y * zoomFactor * 256);
307 // System.out.println("Point: x=" + x + ", px=" + px + ", y=" + y + ", py=" + py);
308 if (!point.getSegmentStart()) {
309 // draw from previous point to this one
310 g.drawLine(prevX, prevY, px, py);
312 // Only draw points if requested
313 if (_drawTrackPointsCheckbox.isSelected())
315 g.drawRect(px-2, py-2, 3, 3);
318 prevX = px; prevY = py;
322 final Color textColour = Config.getColourScheme().getColour(ColourScheme.IDX_TEXT);
323 g.setColor(textColour);
325 for (int i=0; i<numPoints; i++)
327 DataPoint point = track.getPoint(i);
328 if (point.isWaypoint())
330 // draw blob for each waypoint
331 double x = track.getX(i) - xRange.getMinimum();
332 double y = track.getY(i) - yRange.getMinimum();
333 // use zoom level to calculate pixel coords on image
334 int px = (int) (x * zoomFactor * 256), py = (int) (y * zoomFactor * 256);
335 g.fillRect(px-3, py-3, 6, 6);
338 // Set text size according to input
339 int fontScalePercent = _textScaleField.getValue();
340 if (fontScalePercent > 10 && fontScalePercent <= 999)
342 Font gFont = g.getFont();
343 g.setFont(gFont.deriveFont((float) (gFont.getSize() * 0.01 * fontScalePercent)));
345 FontMetrics fm = g.getFontMetrics();
346 final int nameHeight = fm.getHeight();
347 final int imageSize = inImage.getImageSize();
349 // Loop over points again, draw photo points
350 final Color photoColour = Config.getColourScheme().getColour(ColourScheme.IDX_SECONDARY);
351 g.setColor(photoColour);
352 for (int i=0; i<numPoints; i++)
354 DataPoint point = track.getPoint(i);
355 if (point.hasMedia())
357 // draw blob for each photo
358 double x = track.getX(i) - xRange.getMinimum();
359 double y = track.getY(i) - yRange.getMinimum();
360 // use zoom level to calculate pixel coords on image
361 int px = (int) (x * zoomFactor * 256), py = (int) (y * zoomFactor * 256);
362 g.fillRect(px-3, py-3, 6, 6);
366 // Loop over points again, now draw names for waypoints
367 g.setColor(textColour);
368 for (int i=0; i<numPoints; i++)
370 DataPoint point = track.getPoint(i);
371 if (point.isWaypoint())
373 double x = track.getX(i) - xRange.getMinimum();
374 double y = track.getY(i) - yRange.getMinimum();
375 int px = (int) (x * zoomFactor * 256), py = (int) (y * zoomFactor * 256);
377 // Figure out where to draw waypoint name so it doesn't obscure track
378 String waypointName = point.getWaypointName();
379 int nameWidth = fm.stringWidth(waypointName);
380 boolean drawnName = false;
381 // Make arrays for coordinates right left up down
382 int[] nameXs = {px + 2, px - nameWidth - 2, px - nameWidth/2, px - nameWidth/2};
383 int[] nameYs = {py + (nameHeight/2), py + (nameHeight/2), py - 2, py + nameHeight + 2};
384 for (int extraSpace = 4; extraSpace < 13 && !drawnName; extraSpace+=2)
386 // Shift arrays for coordinates right left up down
387 nameXs[0] += 2; nameXs[1] -= 2;
388 nameYs[2] -= 2; nameYs[3] += 2;
389 // Check each direction in turn right left up down
390 for (int a=0; a<4; a++)
392 if (nameXs[a] > 0 && (nameXs[a] + nameWidth) < imageSize
393 && nameYs[a] < imageSize && (nameYs[a] - nameHeight) > 0
394 && !MapUtils.overlapsPoints(inImage.getImage(), nameXs[a], nameYs[a],
395 nameWidth, nameHeight, textColour))
397 // Found a rectangle to fit - draw name here and quit
398 g.drawString(waypointName, nameXs[a], nameYs[a]);
407 // Maybe draw note at the bottom, export from GpsPrune? Filename?
408 // Note: Differences from main map: No mapPosition (modifying position and visible points),
409 // no selection, no opacities, maybe different scale/text factors
413 * Base image has changed, need to enable/disable ok button
415 public void baseImageChanged()
417 final boolean useImage = _baseImagePanel.getImageDefinition().getUseImage();
418 final int zoomLevel = _baseImagePanel.getImageDefinition().getZoom();
419 final boolean okEnabled = useImage && _baseImagePanel.getFoundData()
420 && MapGrouter.isZoomLevelOk(_app.getTrackInfo().getTrack(), zoomLevel);
421 _okButton.setEnabled(okEnabled);