1 package tim.prune.load;
4 import java.util.TreeSet;
6 import javax.swing.BoxLayout;
7 import javax.swing.JCheckBox;
8 import javax.swing.JFileChooser;
9 import javax.swing.JFrame;
10 import javax.swing.JPanel;
13 import tim.prune.I18nManager;
14 import tim.prune.config.Config;
15 import tim.prune.data.Altitude;
16 import tim.prune.data.DataPoint;
17 import tim.prune.data.Field;
18 import tim.prune.data.LatLonRectangle;
19 import tim.prune.data.Latitude;
20 import tim.prune.data.Longitude;
21 import tim.prune.data.Photo;
22 import tim.prune.data.Timestamp;
23 import tim.prune.function.Cancellable;
24 import tim.prune.jpeg.ExifGateway;
25 import tim.prune.jpeg.JpegData;
28 * Class to manage the loading of Jpegs and dealing with the GPS data from them
30 public class JpegLoader implements Runnable, Cancellable
32 private App _app = null;
33 private JFrame _parentFrame = null;
34 private JFileChooser _fileChooser = null;
35 private GenericFileFilter _fileFilter = null;
36 private JCheckBox _subdirCheckbox = null;
37 private JCheckBox _noExifCheckbox = null;
38 private JCheckBox _outsideAreaCheckbox = null;
39 private MediaLoadProgressDialog _progressDialog = null;
40 private int[] _fileCounts = null;
41 private boolean _cancelled = false;
42 private LatLonRectangle _trackRectangle = null;
43 private TreeSet<Photo> _photos = null;
48 * @param inApp Application object to inform of photo load
49 * @param inParentFrame parent frame to reference for dialogs
51 public JpegLoader(App inApp, JFrame inParentFrame)
54 _parentFrame = inParentFrame;
55 _fileFilter = new JpegFileFilter();
60 * Open the GUI to select options and start the load
61 * @param inRectangle track rectangle
63 public void openDialog(LatLonRectangle inRectangle)
65 // Create file chooser if necessary
66 if (_fileChooser == null)
68 _fileChooser = new JFileChooser();
69 _fileChooser.setMultiSelectionEnabled(true);
70 _fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
71 _fileChooser.setFileFilter(_fileFilter);
72 _fileChooser.setDialogTitle(I18nManager.getText("menu.file.addphotos"));
73 _subdirCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.subdirectories"));
74 _subdirCheckbox.setSelected(true);
75 _noExifCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.loadjpegswithoutcoords"));
76 _noExifCheckbox.setSelected(true);
77 _outsideAreaCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.loadjpegsoutsidearea"));
78 _outsideAreaCheckbox.setSelected(true);
79 JPanel panel = new JPanel();
80 panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
81 panel.add(_subdirCheckbox);
82 panel.add(_noExifCheckbox);
83 panel.add(_outsideAreaCheckbox);
84 _fileChooser.setAccessory(panel);
85 // start from directory in config if already set by other operations
86 String configDir = Config.getConfigString(Config.KEY_PHOTO_DIR);
87 if (configDir == null) {configDir = Config.getConfigString(Config.KEY_TRACK_DIR);}
88 if (configDir != null) {_fileChooser.setCurrentDirectory(new File(configDir));}
90 // enable/disable track checkbox
91 _trackRectangle = inRectangle;
92 _outsideAreaCheckbox.setEnabled(_trackRectangle != null && !_trackRectangle.isEmpty());
93 // Show file dialog to choose file / directory(ies)
94 if (_fileChooser.showOpenDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
96 // Bring up dialog before starting
97 _progressDialog = new MediaLoadProgressDialog(_parentFrame, this);
98 _progressDialog.show();
99 // start thread for processing
100 new Thread(this).start();
105 public void cancel() {
111 * Run method for performing tasks in separate thread
115 // Initialise arrays, errors, summaries
116 _fileCounts = new int[3]; // files, jpegs, gps
117 _photos = new TreeSet<Photo>(new MediaSorter());
118 File[] files = _fileChooser.getSelectedFiles();
119 // Loop recursively over selected files/directories to count files
120 int numFiles = countFileList(files, true, _subdirCheckbox.isSelected());
121 // Set up the progress bar for this number of files
122 _progressDialog.showProgress(0, numFiles);
125 // Process the files recursively and build lists of photos
126 processFileList(files, true, _subdirCheckbox.isSelected());
127 _progressDialog.close();
128 if (_cancelled) {return;}
130 if (_fileCounts[0] == 0)
132 // No files found at all
133 _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nofilesfound");
135 else if (_fileCounts[1] == 0)
138 _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nojpegsfound");
140 else if (!_noExifCheckbox.isSelected() && _fileCounts[2] == 0)
142 // Need coordinates but no gps information found
143 _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nogpsfound");
147 // Found some photos to load - pass information back to app
148 _app.informPhotosLoaded(_photos);
154 * Process a list of files and/or directories
155 * @param inFiles array of file/directories
156 * @param inFirstDir true if first directory
157 * @param inDescend true to descend to subdirectories
159 private void processFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
161 if (inFiles == null) return;
162 // Loop over elements in array
163 for (int i=0; i<inFiles.length && !_cancelled; i++)
165 File file = inFiles[i];
166 if (file.exists() && file.canRead())
168 // Check whether it's a file or a directory
173 else if (file.isDirectory() && (inFirstDir || inDescend))
175 // Always process first directory,
176 // only process subdirectories if checkbox selected
177 File[] files = file.listFiles();
178 processFileList(files, false, inDescend);
181 // if file doesn't exist or isn't readable - ignore
187 * Process the given file, by attempting to extract its tags
188 * @param inFile file object to read
190 private void processFile(File inFile)
192 // Update progress bar
193 _fileCounts[0]++; // file found
194 _progressDialog.showProgress(_fileCounts[0], -1);
196 // Check whether filename corresponds with accepted filenames
197 if (!_fileFilter.acceptFilename(inFile.getName())) {return;}
198 // If it's a Jpeg, we can use ExifReader to get coords, otherwise we could try exiftool (if it's installed)
200 if (inFile.exists() && inFile.canRead()) {
201 _fileCounts[1]++; // jpeg found
203 Photo photo = createPhoto(inFile);
204 if (photo.getDataPoint() != null) {
205 _fileCounts[2]++; // photo has coordinates
207 // Check the criteria for adding the photo - check whether the photo has coordinates and if so if they're within the rectangle
208 if ( (photo.getDataPoint() != null || _noExifCheckbox.isSelected())
209 && (photo.getDataPoint() == null || !_outsideAreaCheckbox.isEnabled()
210 || _outsideAreaCheckbox.isSelected() || _trackRectangle.containsPoint(photo.getDataPoint())))
217 * Create a Photo object for the given file, including reading exif information
218 * @param inFile file object
219 * @return Photo object
221 public static Photo createPhoto(File inFile)
223 // Create Photo object
224 Photo photo = new Photo(inFile);
225 // Try to get information out of exif
226 JpegData jpegData = ExifGateway.getJpegData(inFile);
227 Timestamp timestamp = null;
228 if (jpegData != null)
230 if (jpegData.isGpsValid())
232 timestamp = createTimestamp(jpegData.getGpsDatestamp(), jpegData.getGpsTimestamp());
233 // Make DataPoint and attach to Photo
234 DataPoint point = createDataPoint(jpegData);
235 point.setPhoto(photo);
236 point.setSegmentStart(true);
237 photo.setDataPoint(point);
238 photo.setOriginalStatus(Photo.Status.TAGGED);
240 // Use exif timestamp if gps timestamp not available
241 if (timestamp == null && jpegData.getOriginalTimestamp() != null) {
242 timestamp = createTimestamp(jpegData.getOriginalTimestamp());
244 if (timestamp == null && jpegData.getDigitizedTimestamp() != null) {
245 timestamp = createTimestamp(jpegData.getDigitizedTimestamp());
247 photo.setExifThumbnail(jpegData.getThumbnailImage());
248 // Also extract orientation tag for setting rotation state of photo
249 photo.setRotation(jpegData.getRequiredRotation());
250 // Set bearing, if any
251 photo.setBearing(jpegData.getBearing());
253 // Use file timestamp if exif timestamp isn't available
254 if (timestamp == null) {
255 timestamp = new Timestamp(inFile.lastModified());
257 // Apply timestamp to photo and its point (if any)
258 photo.setTimestamp(timestamp);
259 if (photo.getDataPoint() != null) {
260 photo.getDataPoint().setFieldValue(Field.TIMESTAMP, timestamp.getText(Timestamp.FORMAT_ISO_8601), false);
267 * Recursively count the selected Files so we can draw a progress bar
268 * @param inFiles file list
269 * @param inFirstDir true if first directory
270 * @param inDescend true to descend to subdirectories
271 * @return count of the files selected
273 private int countFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
278 // Loop over elements in array
279 for (int i=0; i<inFiles.length; i++)
281 File file = inFiles[i];
282 if (file.exists() && file.canRead())
284 // Store first directory in config for later
285 if (i == 0 && inFirstDir) {
286 File workingDir = file.isDirectory()?file:file.getParentFile();
287 Config.setConfigString(Config.KEY_PHOTO_DIR, workingDir.getAbsolutePath());
289 // Check whether it's a file or a directory
294 else if (file.isDirectory() && (inFirstDir || inDescend))
296 fileCount += countFileList(file.listFiles(), false, inDescend);
306 * Create a DataPoint object from the given jpeg data
307 * @param inData Jpeg data including coordinates
308 * @return DataPoint object for Track
310 private static DataPoint createDataPoint(JpegData inData)
312 // Create model objects from jpeg data
313 double latval = getCoordinateDoubleValue(inData.getLatitude(),
314 inData.getLatitudeRef() == 'N' || inData.getLatitudeRef() == 'n');
315 Latitude latitude = new Latitude(latval, Latitude.FORMAT_DEG_MIN_SEC);
316 double lonval = getCoordinateDoubleValue(inData.getLongitude(),
317 inData.getLongitudeRef() == 'E' || inData.getLongitudeRef() == 'e');
318 Longitude longitude = new Longitude(lonval, Longitude.FORMAT_DEG_MIN_SEC);
319 Altitude altitude = null;
320 if (inData.hasAltitude()) {
321 altitude = new Altitude(inData.getAltitude(), Altitude.Format.METRES);
323 return new DataPoint(latitude, longitude, altitude);
328 * Convert an array of 3 doubles (deg-min-sec) into a double coordinate value
329 * @param inValues array of three doubles for deg-min-sec
330 * @param isPositive true for positive hemisphere, for positive double value
331 * @return double value of coordinate, either positive or negative
333 private static double getCoordinateDoubleValue(double[] inValues, boolean isPositive)
335 if (inValues == null || inValues.length != 3) return 0.0;
336 double value = inValues[0] // degrees
337 + inValues[1] / 60.0 // minutes
338 + inValues[2] / 60.0 / 60.0; // seconds
339 // make sure it's the correct sign
340 value = Math.abs(value);
341 if (!isPositive) value = -value;
347 * Use the given int values to create a timestamp
348 * @param inDate ints describing date
349 * @param inTime ints describing time
350 * @return Timestamp object corresponding to inputs
352 private static Timestamp createTimestamp(int[] inDate, int[] inTime)
354 if (inDate == null || inTime == null || inDate.length != 3 || inTime.length != 3) {
357 return new Timestamp(inDate[0], inDate[1], inDate[2],
358 inTime[0], inTime[1], inTime[2]);
363 * Use the given String value to create a timestamp
364 * @param inStamp timestamp from exif
365 * @return Timestamp object corresponding to input
367 private static Timestamp createTimestamp(String inStamp)
369 Timestamp stamp = null;
372 stamp = new Timestamp(Integer.parseInt(inStamp.substring(0, 4)),
373 Integer.parseInt(inStamp.substring(5, 7)),
374 Integer.parseInt(inStamp.substring(8, 10)),
375 Integer.parseInt(inStamp.substring(11, 13)),
376 Integer.parseInt(inStamp.substring(14, 16)),
377 Integer.parseInt(inStamp.substring(17)));
379 catch (NumberFormatException nfe) {}