1 package tim.prune.save;
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.FlowLayout;
6 import java.awt.GridLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
10 import java.io.FileWriter;
11 import java.io.IOException;
12 import java.text.NumberFormat;
13 import java.util.Iterator;
14 import java.util.TreeSet;
16 import javax.swing.BorderFactory;
17 import javax.swing.BoxLayout;
18 import javax.swing.JButton;
19 import javax.swing.JCheckBox;
20 import javax.swing.JDialog;
21 import javax.swing.JFileChooser;
22 import javax.swing.JLabel;
23 import javax.swing.JOptionPane;
24 import javax.swing.JPanel;
25 import javax.swing.JTextField;
26 import javax.swing.SwingConstants;
29 import tim.prune.I18nManager;
30 import tim.prune.UpdateMessageBroker;
31 import tim.prune.config.Config;
32 import tim.prune.data.Track;
33 import tim.prune.function.Export3dFunction;
34 import tim.prune.gui.DialogCloser;
35 import tim.prune.load.GenericFileFilter;
36 import tim.prune.threedee.ThreeDModel;
39 * Class to export a 3d scene of the track to a specified Svg file
41 public class SvgExporter extends Export3dFunction
43 private Track _track = null;
44 private JDialog _dialog = null;
45 private JFileChooser _fileChooser = null;
46 private double _phi = 0.0, _theta = 0.0;
47 private JTextField _phiField = null, _thetaField = null;
48 private JTextField _altitudeFactorField = null;
49 private JCheckBox _gradientsCheckbox = null;
50 private static final double _scaleFactor = 200.0;
55 * @param inApp App object
57 public SvgExporter(App inApp)
60 _track = inApp.getTrackInfo().getTrack();
61 // Set default rotation angles
62 _phi = 30; _theta = 55;
65 /** Get the name key */
66 public String getNameKey() {
67 return "function.exportsvg";
71 * Set the rotation angles using coordinates for the camera
72 * @param inX X coordinate of camera
73 * @param inY Y coordinate of camera
74 * @param inZ Z coordinate of camera
76 public void setCameraCoordinates(double inX, double inY, double inZ)
78 // Calculate phi and theta based on camera x,y,z
79 _phi = Math.toDegrees(Math.atan2(inX, inZ));
80 _theta = Math.toDegrees(Math.atan2(inY, Math.sqrt(inX*inX + inZ*inZ)));
85 * Show the dialog to select options and export file
89 // Make dialog window to select angles, colours etc
92 _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
93 _dialog.setLocationRelativeTo(_parentFrame);
94 _dialog.getContentPane().add(makeDialogComponents());
98 NumberFormat threeDP = NumberFormat.getNumberInstance();
99 threeDP.setMaximumFractionDigits(3);
100 _phiField.setText(threeDP.format(_phi));
101 _thetaField.setText(threeDP.format(_theta));
102 // Set vertical scale
103 _altitudeFactorField.setText("" + _altFactor);
106 _dialog.setVisible(true);
111 * Make the dialog components to select the export options
112 * @return Component holding gui elements
114 private Component makeDialogComponents()
116 JPanel panel = new JPanel();
117 panel.setLayout(new BorderLayout());
118 JLabel introLabel = new JLabel(I18nManager.getText("dialog.exportsvg.text"));
119 introLabel.setBorder(BorderFactory.createEmptyBorder(4, 4, 6, 4));
120 panel.add(introLabel, BorderLayout.NORTH);
121 // OK, Cancel buttons
122 JPanel buttonPanel = new JPanel();
123 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
124 JButton okButton = new JButton(I18nManager.getText("button.ok"));
125 okButton.addActionListener(new ActionListener() {
126 public void actionPerformed(ActionEvent e)
132 buttonPanel.add(okButton);
133 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
134 cancelButton.addActionListener(new ActionListener() {
135 public void actionPerformed(ActionEvent e) {
139 buttonPanel.add(cancelButton);
140 panel.add(buttonPanel, BorderLayout.SOUTH);
143 JPanel centralPanel = new JPanel();
144 centralPanel.setLayout(new GridLayout(0, 2, 10, 4));
147 JLabel phiLabel = new JLabel(I18nManager.getText("dialog.exportsvg.phi"));
148 phiLabel.setHorizontalAlignment(SwingConstants.TRAILING);
149 centralPanel.add(phiLabel);
150 _phiField = new JTextField("" + _phi);
151 _phiField.addKeyListener(new DialogCloser(_dialog));
152 centralPanel.add(_phiField);
153 JLabel thetaLabel = new JLabel(I18nManager.getText("dialog.exportsvg.theta"));
154 thetaLabel.setHorizontalAlignment(SwingConstants.TRAILING);
155 centralPanel.add(thetaLabel);
156 _thetaField = new JTextField("" + _theta);
157 centralPanel.add(_thetaField);
158 // Altitude exaggeration
159 JLabel altFactorLabel = new JLabel(I18nManager.getText("dialog.3d.altitudefactor"));
160 altFactorLabel.setHorizontalAlignment(SwingConstants.TRAILING);
161 centralPanel.add(altFactorLabel);
162 _altitudeFactorField = new JTextField("" + _altFactor);
163 centralPanel.add(_altitudeFactorField);
164 // Checkbox for gradients or not
165 JLabel gradientsLabel = new JLabel(I18nManager.getText("dialog.exportsvg.gradients"));
166 gradientsLabel.setHorizontalAlignment(SwingConstants.TRAILING);
167 centralPanel.add(gradientsLabel);
168 _gradientsCheckbox = new JCheckBox();
169 _gradientsCheckbox.setSelected(true);
170 centralPanel.add(_gradientsCheckbox);
172 // add this grid to the holder panel
173 JPanel holderPanel = new JPanel();
174 holderPanel.setLayout(new BorderLayout(5, 5));
175 JPanel boxPanel = new JPanel();
176 boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.Y_AXIS));
177 boxPanel.add(centralPanel);
178 holderPanel.add(boxPanel, BorderLayout.CENTER);
180 panel.add(holderPanel, BorderLayout.CENTER);
186 * Select the file and export data to it
188 private void doExport()
190 // Copy camera coordinates
191 _phi = checkAngle(_phiField.getText());
192 _theta = checkAngle(_thetaField.getText());
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.svg", new String[] {"svg"}));
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 file = _fileChooser.getSelectedFile();
215 if (!file.getName().toLowerCase().endsWith(".svg")) {
216 file = new File(file.getAbsolutePath() + ".svg");
218 // Check if file exists and if necessary prompt for overwrite
219 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
220 if (!file.exists() || JOptionPane.showOptionDialog(_parentFrame,
221 I18nManager.getText("dialog.save.overwrite.text"),
222 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
223 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
224 == JOptionPane.YES_OPTION)
227 if (exportFile(file))
229 // file saved - store directory in config for later
230 Config.setConfigString(Config.KEY_TRACK_DIR, file.getParentFile().getAbsolutePath());
233 // export failed so need to choose again
238 // overwrite cancelled so need to choose again
242 } while (chooseAgain);
247 * Export the track data to the specified file
248 * @param inFile File object to save to
249 * @return true if successful
251 private boolean exportFile(File inFile)
253 FileWriter writer = null;
254 // find out the line separator for this system
255 String lineSeparator = System.getProperty("line.separator");
258 // create and scale model
259 ThreeDModel model = new ThreeDModel(_track);
262 // try to use given altitude factor
263 _altFactor = Double.parseDouble(_altitudeFactorField.getText());
264 model.setAltitudeFactor(_altFactor);
266 catch (NumberFormatException nfe) {}
269 boolean useGradients = _gradientsCheckbox.isSelected();
271 // Create file and write basics
272 writer = new FileWriter(inFile);
273 writeStartOfFile(writer, useGradients, lineSeparator);
274 writeBasePlane(writer, lineSeparator);
275 // write out cardinal letters NESW
276 writeCardinals(writer, lineSeparator);
279 writeDataPoints(writer, model, useGradients, lineSeparator);
280 writeEndOfFile(writer, lineSeparator);
283 UpdateMessageBroker.informSubscribers(I18nManager.getText("confirm.save.ok1")
284 + " " + _track.getNumPoints() + " " + I18nManager.getText("confirm.save.ok2")
285 + " " + inFile.getAbsolutePath());
288 catch (IOException ioe)
290 JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.save.failed") + " : " + ioe.getMessage(),
291 I18nManager.getText("error.save.dialogtitle"), JOptionPane.ERROR_MESSAGE);
295 // close file ignoring exceptions
299 catch (Exception e) {}
306 * Write the start of the Svg file
307 * @param inWriter Writer to use for writing file
308 * @param inUseGradients true to use gradients, false for flat fills
309 * @param inLineSeparator line separator to use
310 * @throws IOException on file writing error
312 private static void writeStartOfFile(FileWriter inWriter, boolean inUseGradients,
313 String inLineSeparator)
316 inWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
317 inWriter.write(inLineSeparator);
318 inWriter.write("<!-- Svg file produced by GpsPrune - see http://activityworkshop.net/ -->");
319 inWriter.write(inLineSeparator);
320 inWriter.write("<svg width=\"800\" height=\"700\">");
321 inWriter.write(inLineSeparator);
324 final String defs = "<defs>" +
325 "<radialGradient id=\"wayfill\" cx=\"0.5\" cy=\"0.5\" r=\"0.5\" fx=\"0.5\" fy=\"0.5\">" +
326 "<stop offset=\"0%\" stop-color=\"#2323aa\"/>" +
327 "<stop offset=\"100%\" stop-color=\"#000080\"/>" +
328 "</radialGradient>" + inLineSeparator +
329 "<radialGradient id=\"trackfill\" cx=\"0.5\" cy=\"0.5\" r=\"0.5\" fx=\"0.5\" fy=\"0.5\">" +
330 "<stop offset=\"0%\" stop-color=\"#23aa23\"/>" +
331 "<stop offset=\"100%\" stop-color=\"#008000\"/>" +
332 "</radialGradient>" +
334 inWriter.write(defs);
335 inWriter.write(inLineSeparator);
337 inWriter.write("<g inkscape:label=\"Layer 1\" inkscape:groupmode=\"layer\" id=\"layer1\">");
338 inWriter.write(inLineSeparator);
342 * Write the base plane
343 * @param inWriter Writer to use for writing file
344 * @param inLineSeparator line separator to use
345 * @throws IOException on file writing error
347 private void writeBasePlane(FileWriter inWriter, String inLineSeparator)
350 // Use model size and camera angles to draw path for base rectangle (using 3d transform)
351 int[] coords1 = convertCoordinates(-1.0, -1.0, 0);
352 int[] coords2 = convertCoordinates(1.0, -1.0, 0);
353 int[] coords3 = convertCoordinates(1.0, 1.0, 0);
354 int[] coords4 = convertCoordinates(-1.0, 1.0, 0);
355 final String corners = "M " + coords1[0] + "," + coords1[1]
356 + " L " + coords2[0] + "," + coords2[1]
357 + " L " + coords3[0] + "," + coords3[1]
358 + " L " + coords4[0] + "," + coords4[1] + " z";
359 inWriter.write("<path style=\"fill:#446666;stroke:#000000;\" d=\"" + corners + "\" id=\"rect1\" />");
360 inWriter.write(inLineSeparator);
364 * Write the cardinal letters NESW
365 * @param inWriter Writer to use for writing file
366 * @param inLineSeparator line separator to use
367 * @throws IOException on file writing error
369 private void writeCardinals(FileWriter inWriter, String inLineSeparator)
372 // Use model size and camera angles to calculate positions
373 int[] coordsN = convertCoordinates(0, 1.0, 0);
374 writeCardinal(inWriter, coordsN[0], coordsN[1], "cardinal.n", inLineSeparator);
375 int[] coordsE = convertCoordinates(1.0, 0, 0);
376 writeCardinal(inWriter, coordsE[0], coordsE[1], "cardinal.e", inLineSeparator);
377 int[] coordsS = convertCoordinates(0, -1.0, 0);
378 writeCardinal(inWriter, coordsS[0], coordsS[1], "cardinal.s", inLineSeparator);
379 int[] coordsW = convertCoordinates(-1.0, 0, 0);
380 writeCardinal(inWriter, coordsW[0], coordsW[1], "cardinal.w", inLineSeparator);
384 * Write a single cardinal letter
385 * @param inWriter Writer to use for writing file
386 * @param inX x coordinate
387 * @param inY y coordinate
388 * @param inKey key for string to write
389 * @param inLineSeparator line separator to use
390 * @throws IOException on file writing error
392 private static void writeCardinal(FileWriter inWriter, int inX, int inY, String inKey, String inLineSeparator)
395 inWriter.write("<text x=\"" + inX + "\" y=\"" + inY + "\" font-size=\"26\" fill=\"black\" " +
396 "stroke=\"white\" stroke-width=\"0.5\">");
397 inWriter.write(I18nManager.getText(inKey));
398 inWriter.write("</text>");
399 inWriter.write(inLineSeparator);
403 * Convert the given 3d coordinates into 2d coordinates by rotating and mapping
404 * @param inX x coordinate (east)
405 * @param inY y coordinate (north)
406 * @param inZ z coordinate (up)
407 * @return 2d coordinates as integer array
409 private int[] convertCoordinates(double inX, double inY, double inZ)
411 // Rotate by phi degrees around vertical axis
412 final double cosPhi = Math.cos(Math.toRadians(_phi));
413 final double sinPhi = Math.sin(Math.toRadians(_phi));
414 final double x2 = inX * cosPhi + inY * sinPhi;
415 final double y2 = inY * cosPhi - inX * sinPhi;
416 final double z2 = inZ;
417 // Rotate by theta degrees around horizontal axis
418 final double cosTheta = Math.cos(Math.toRadians(_theta));
419 final double sinTheta = Math.sin(Math.toRadians(_theta));
421 double y3 = y2 * sinTheta + z2 * cosTheta;
422 // don't need to calculate z3
423 // Scale results to sensible scale for svg
424 x3 = x3 * _scaleFactor + 400;
425 y3 = -y3 * _scaleFactor + 350;
426 return new int[] {(int) x3, (int) y3};
430 * Finish off the file by closing the tags
431 * @param inWriter Writer to use for writing file
432 * @param inLineSeparator line separator to use
433 * @throws IOException on file writing error
435 private static void writeEndOfFile(FileWriter inWriter, String inLineSeparator)
438 inWriter.write(inLineSeparator);
439 inWriter.write("</g></svg>");
440 inWriter.write(inLineSeparator);
444 * Write out all the data points to the file in the balls-and-sticks style
445 * @param inWriter Writer to use for writing file
446 * @param inModel model object for getting data points
447 * @param inUseGradients true to use gradients, false for flat fills
448 * @param inLineSeparator line separator to use
449 * @throws IOException on file writing error
451 private void writeDataPoints(FileWriter inWriter, ThreeDModel inModel, boolean inUseGradients,
452 String inLineSeparator)
455 final int numPoints = inModel.getNumPoints();
456 TreeSet<SvgFragment> fragments = new TreeSet<SvgFragment>();
457 for (int i=0; i<numPoints; i++)
459 StringBuilder builder = new StringBuilder();
460 int[] coords = convertCoordinates(inModel.getScaledHorizValue(i), inModel.getScaledVertValue(i),
461 inModel.getScaledAltValue(i));
462 // vertical rod (if altitude positive)
463 if (inModel.getScaledAltValue(i) > 0.0)
465 int[] baseCoords = convertCoordinates(inModel.getScaledHorizValue(i), inModel.getScaledVertValue(i), 0);
466 builder.append("<line x1=\"").append(baseCoords[0]).append("\" y1=\"").append(baseCoords[1])
467 .append("\" x2=\"").append(coords[0]).append("\" y2=\"").append(coords[1])
468 .append("\" stroke=\"gray\" stroke-width=\"3\" />");
469 builder.append(inLineSeparator);
471 // ball (different according to type)
472 if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
475 builder.append("<circle cx=\"").append(coords[0]).append("\" cy=\"").append(coords[1])
476 .append("\" r=\"11\" ").append(inUseGradients?"fill=\"url(#wayfill)\"":"fill=\"blue\"")
477 .append(" stroke=\"green\" stroke-width=\"0.2\" />");
481 // normal track point ball
482 builder.append("<circle cx=\"").append(coords[0]).append("\" cy=\"").append(coords[1])
483 .append("\" r=\"7\" ").append(inUseGradients?"fill=\"url(#trackfill)\"":"fill=\"green\"")
484 .append(" stroke=\"blue\" stroke-width=\"0.2\" />");
486 builder.append(inLineSeparator);
488 fragments.add(new SvgFragment(builder.toString(), coords[1]));
491 // Iterate over the sorted set and write to file
492 Iterator<SvgFragment> iterator = fragments.iterator();
493 while (iterator.hasNext()) {
494 inWriter.write(iterator.next().getFragment());
500 * Check the given angle value
501 * @param inString String entered by user
502 * @return validated value
504 private static double checkAngle(String inString)
508 value = Double.parseDouble(inString);
510 catch (Exception e) {} // ignore parse failures