]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/load/JpegLoader.java
08b29fad02e6b32ec2cfc6bafa663869d76cbefa
[GpsPrune.git] / tim / prune / load / JpegLoader.java
1 package tim.prune.load;
2
3 import java.awt.event.ActionEvent;
4 import java.awt.event.ActionListener;
5 import java.io.File;
6 import java.util.TreeSet;
7
8 import javax.swing.BorderFactory;
9 import javax.swing.BoxLayout;
10 import javax.swing.JButton;
11 import javax.swing.JCheckBox;
12 import javax.swing.JDialog;
13 import javax.swing.JFileChooser;
14 import javax.swing.JFrame;
15 import javax.swing.JLabel;
16 import javax.swing.JPanel;
17 import javax.swing.JProgressBar;
18
19 import tim.prune.App;
20 import tim.prune.I18nManager;
21 import tim.prune.config.Config;
22 import tim.prune.data.Altitude;
23 import tim.prune.data.DataPoint;
24 import tim.prune.data.LatLonRectangle;
25 import tim.prune.data.Latitude;
26 import tim.prune.data.Longitude;
27 import tim.prune.data.Photo;
28 import tim.prune.data.Timestamp;
29 import tim.prune.drew.jpeg.ExifReader;
30 import tim.prune.drew.jpeg.JpegData;
31 import tim.prune.drew.jpeg.JpegException;
32 import tim.prune.drew.jpeg.Rational;
33
34 /**
35  * Class to manage the loading of Jpegs and dealing with the GPS data from them
36  */
37 public class JpegLoader implements Runnable
38 {
39         private App _app = null;
40         private JFrame _parentFrame = null;
41         private JFileChooser _fileChooser = null;
42         private GenericFileFilter _fileFilter = null;
43         private JCheckBox _subdirCheckbox = null;
44         private JCheckBox _noExifCheckbox = null;
45         private JCheckBox _outsideAreaCheckbox = null;
46         private JDialog _progressDialog   = null;
47         private JProgressBar _progressBar = null;
48         private int[] _fileCounts = null;
49         private boolean _cancelled = false;
50         private LatLonRectangle _trackRectangle = null;
51         private TreeSet<Photo> _photos = null;
52
53
54         /**
55          * Constructor
56          * @param inApp Application object to inform of photo load
57          * @param inParentFrame parent frame to reference for dialogs
58          */
59         public JpegLoader(App inApp, JFrame inParentFrame)
60         {
61                 _app = inApp;
62                 _parentFrame = inParentFrame;
63                 String[] fileTypes = {"jpg", "jpe", "jpeg"};
64                 _fileFilter = new GenericFileFilter("filetype.jpeg", fileTypes);
65         }
66
67
68         /**
69          * Open the GUI to select options and start the load
70          * @param inRectangle track rectangle
71          */
72         public void openDialog(LatLonRectangle inRectangle)
73         {
74                 // Create file chooser if necessary
75                 if (_fileChooser == null)
76                 {
77                         _fileChooser = new JFileChooser();
78                         _fileChooser.setMultiSelectionEnabled(true);
79                         _fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
80                         _fileChooser.setFileFilter(_fileFilter);
81                         _fileChooser.setDialogTitle(I18nManager.getText("menu.file.addphotos"));
82                         _subdirCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.subdirectories"));
83                         _subdirCheckbox.setSelected(true);
84                         _noExifCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.loadjpegswithoutcoords"));
85                         _noExifCheckbox.setSelected(true);
86                         _outsideAreaCheckbox = new JCheckBox(I18nManager.getText("dialog.jpegload.loadjpegsoutsidearea"));
87                         _outsideAreaCheckbox.setSelected(true);
88                         JPanel panel = new JPanel();
89                         panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
90                         panel.add(_subdirCheckbox);
91                         panel.add(_noExifCheckbox);
92                         panel.add(_outsideAreaCheckbox);
93                         _fileChooser.setAccessory(panel);
94                         // start from directory in config if already set by other operations
95                         String configDir = Config.getConfigString(Config.KEY_PHOTO_DIR);
96                         if (configDir == null) {configDir = Config.getConfigString(Config.KEY_TRACK_DIR);}
97                         if (configDir != null) {_fileChooser.setCurrentDirectory(new File(configDir));}
98                 }
99                 // enable/disable track checkbox
100                 _trackRectangle = inRectangle;
101                 _outsideAreaCheckbox.setEnabled(_trackRectangle != null && !_trackRectangle.isEmpty());
102                 // Show file dialog to choose file / directory(ies)
103                 if (_fileChooser.showOpenDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
104                 {
105                         // Bring up dialog before starting
106                         if (_progressDialog == null) {
107                                 createProgressDialog();
108                         }
109                         // reset dialog and show it
110                         _progressBar.setValue(0);
111                         _progressBar.setString("");
112                         _progressDialog.setVisible(true);
113                         // start thread for processing
114                         new Thread(this).start();
115                 }
116         }
117
118
119         /**
120          * Create the dialog to show the progress
121          */
122         private void createProgressDialog()
123         {
124                 _progressDialog = new JDialog(_parentFrame, I18nManager.getText("dialog.jpegload.progress.title"));
125                 _progressDialog.setLocationRelativeTo(_parentFrame);
126                 _progressBar = new JProgressBar(0, 100);
127                 _progressBar.setValue(0);
128                 _progressBar.setStringPainted(true);
129                 _progressBar.setString("");
130                 JPanel panel = new JPanel();
131                 panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
132                 panel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
133                 panel.add(new JLabel(I18nManager.getText("dialog.jpegload.progress")));
134                 panel.add(_progressBar);
135                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
136                 cancelButton.addActionListener(new ActionListener() {
137                         public void actionPerformed(ActionEvent e)
138                         {
139                                 _cancelled = true;
140                         }
141                 });
142                 panel.add(cancelButton);
143                 _progressDialog.getContentPane().add(panel);
144                 _progressDialog.pack();
145         }
146
147
148         /**
149          * Run method for performing tasks in separate thread
150          */
151         public void run()
152         {
153                 // Initialise arrays, errors, summaries
154                 _fileCounts = new int[4]; // files, jpegs, exifs, gps
155                 _photos = new TreeSet<Photo>(new PhotoSorter());
156                 File[] files = _fileChooser.getSelectedFiles();
157                 // Loop recursively over selected files/directories to count files
158                 int numFiles = countFileList(files, true, _subdirCheckbox.isSelected());
159                 // Set up the progress bar for this number of files
160                 _progressBar.setMaximum(numFiles);
161                 _progressBar.setValue(0);
162                 _cancelled = false;
163
164                 // Process the files recursively and build lists of photos
165                 processFileList(files, true, _subdirCheckbox.isSelected());
166                 _progressDialog.setVisible(false);
167                 _progressDialog.dispose(); // Sometimes dialog doesn't disappear without this dispose
168                 if (_cancelled) {return;}
169
170                 //System.out.println("Finished - counts are: " + _fileCounts[0] + ", " + _fileCounts[1]
171                 //  + ", " + _fileCounts[2] + ", " + _fileCounts[3]);
172                 if (_fileCounts[0] == 0)
173                 {
174                         // No files found at all
175                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nofilesfound");
176                 }
177                 else if (_fileCounts[1] == 0)
178                 {
179                         // No jpegs found
180                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nojpegsfound");
181                 }
182                 else if (!_noExifCheckbox.isSelected() && _fileCounts[2] == 0)
183                 {
184                         // Need coordinates but no exif found
185                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.noexiffound");
186                 }
187                 else if (!_noExifCheckbox.isSelected() && _fileCounts[3] == 0)
188                 {
189                         // Need coordinates but no gps information found
190                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nogpsfound");
191                 }
192                 else
193                 {
194                         // Found some photos to load - pass information back to app
195                         _app.informPhotosLoaded(_photos);
196                 }
197         }
198
199
200         /**
201          * Process a list of files and/or directories
202          * @param inFiles array of file/directories
203          * @param inFirstDir true if first directory
204          * @param inDescend true to descend to subdirectories
205          */
206         private void processFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
207         {
208                 if (inFiles != null)
209                 {
210                         // Loop over elements in array
211                         for (int i=0; i<inFiles.length && !_cancelled; i++)
212                         {
213                                 File file = inFiles[i];
214                                 if (file.exists() && file.canRead())
215                                 {
216                                         // Check whether it's a file or a directory
217                                         if (file.isFile())
218                                         {
219                                                 processFile(file);
220                                         }
221                                         else if (file.isDirectory() && (inFirstDir || inDescend))
222                                         {
223                                                 // Always process first directory,
224                                                 // only process subdirectories if checkbox selected
225                                                 File[] files = file.listFiles();
226                                                 processFileList(files, false, inDescend);
227                                         }
228                                 }
229                                 // if file doesn't exist or isn't readable - ignore
230                         }
231                 }
232         }
233
234
235         /**
236          * Process the given file, by attempting to extract its tags
237          * @param inFile file object to read
238          */
239         private void processFile(File inFile)
240         {
241                 // Update progress bar
242                 _fileCounts[0]++; // file found
243                 _progressBar.setValue(_fileCounts[0]);
244                 _progressBar.setString("" + _fileCounts[0] + " / " + _progressBar.getMaximum());
245                 _progressBar.repaint();
246
247                 // Check whether filename corresponds with accepted filenames
248                 if (!_fileFilter.acceptFilename(inFile.getName())) {return;}
249                 // If it's a Jpeg, we can use ExifReader to get coords, otherwise we could try exiftool (if it's installed)
250
251                 // Create Photo object
252                 Photo photo = new Photo(inFile);
253                 // Try to get information out of exif
254                 try
255                 {
256                         JpegData jpegData = new ExifReader(inFile).extract();
257                         _fileCounts[1]++; // jpeg found (no exception thrown)
258                         if (jpegData.getExifDataPresent())
259                                 {_fileCounts[2]++;} // exif found
260                         if (jpegData.isValid())
261                         {
262                                 if (jpegData.getGpsDatestamp() != null && jpegData.getGpsTimestamp() != null)
263                                 {
264                                         photo.setTimestamp(createTimestamp(jpegData.getGpsDatestamp(), jpegData.getGpsTimestamp()));
265                                 }
266                                 // Make DataPoint and attach to Photo
267                                 DataPoint point = createDataPoint(jpegData);
268                                 point.setPhoto(photo);
269                                 point.setSegmentStart(true);
270                                 photo.setDataPoint(point);
271                                 photo.setOriginalStatus(Photo.Status.TAGGED);
272                                 _fileCounts[3]++;
273                         }
274                         // Use exif timestamp if gps timestamp not available
275                         if (photo.getTimestamp() == null && jpegData.getOriginalTimestamp() != null)
276                         {
277                                 photo.setTimestamp(createTimestamp(jpegData.getOriginalTimestamp()));
278                         }
279                         photo.setExifThumbnail(jpegData.getThumbnailImage());
280                         // Also extract orientation tag for setting rotation state of photo
281                         photo.setRotation(jpegData.getRequiredRotation());
282                 }
283                 catch (JpegException jpe) { // don't list errors, just count them
284                 }
285                 // Use file timestamp if exif timestamp isn't available
286                 if (photo.getTimestamp() == null) {
287                         photo.setTimestamp(new Timestamp(inFile.lastModified()));
288                 }
289                 // Check the criteria for adding the photo - check whether the photo has coordinates and if so if they're within the rectangle
290                 if ( (photo.getDataPoint() != null || _noExifCheckbox.isSelected())
291                         && (photo.getDataPoint() == null || !_outsideAreaCheckbox.isEnabled()
292                                 || _outsideAreaCheckbox.isSelected() || _trackRectangle.containsPoint(photo.getDataPoint())))
293                 {
294                         _photos.add(photo);
295                 }
296         }
297
298
299         /**
300          * Recursively count the selected Files so we can draw a progress bar
301          * @param inFiles file list
302          * @param inFirstDir true if first directory
303          * @param inDescend true to descend to subdirectories
304          * @return count of the files selected
305          */
306         private int countFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
307         {
308                 int fileCount = 0;
309                 if (inFiles != null)
310                 {
311                         // Loop over elements in array
312                         for (int i=0; i<inFiles.length; i++)
313                         {
314                                 File file = inFiles[i];
315                                 if (file.exists() && file.canRead())
316                                 {
317                                         // Store first directory in config for later
318                                         if (i == 0 && inFirstDir) {
319                                                 File workingDir = file.isDirectory()?file:file.getParentFile();
320                                                 Config.setConfigString(Config.KEY_PHOTO_DIR, workingDir.getAbsolutePath());
321                                         }
322                                         // Check whether it's a file or a directory
323                                         if (file.isFile())
324                                         {
325                                                 fileCount++;
326                                         }
327                                         else if (file.isDirectory() && (inFirstDir || inDescend))
328                                         {
329                                                 fileCount += countFileList(file.listFiles(), false, inDescend);
330                                         }
331                                 }
332                         }
333                 }
334                 return fileCount;
335         }
336
337
338         /**
339          * Create a DataPoint object from the given jpeg data
340          * @param inData Jpeg data including coordinates
341          * @return DataPoint object for Track
342          */
343         private static DataPoint createDataPoint(JpegData inData)
344         {
345                 // Create model objects from jpeg data
346                 double latval = getCoordinateDoubleValue(inData.getLatitude(),
347                         inData.getLatitudeRef() == 'N' || inData.getLatitudeRef() == 'n');
348                 Latitude latitude = new Latitude(latval, Latitude.FORMAT_DEG_MIN_SEC);
349                 double lonval = getCoordinateDoubleValue(inData.getLongitude(),
350                         inData.getLongitudeRef() == 'E' || inData.getLongitudeRef() == 'e');
351                 Longitude longitude = new Longitude(lonval, Longitude.FORMAT_DEG_MIN_SEC);
352                 Altitude altitude = null;
353                 if (inData.getAltitude() != null)
354                 {
355                         altitude = new Altitude(inData.getAltitude().intValue(), Altitude.Format.METRES);
356                 }
357                 return new DataPoint(latitude, longitude, altitude);
358         }
359
360
361         /**
362          * Convert an array of 3 Rational numbers into a double coordinate value
363          * @param inRationals array of three Rational objects
364          * @param isPositive true for positive hemisphere, for positive double value
365          * @return double value of coordinate, either positive or negative
366          */
367         private static double getCoordinateDoubleValue(Rational[] inRationals, boolean isPositive)
368         {
369                 if (inRationals == null || inRationals.length != 3) return 0.0;
370                 double value = inRationals[0].doubleValue()        // degrees
371                         + inRationals[1].doubleValue() / 60.0          // minutes
372                         + inRationals[2].doubleValue() / 60.0 / 60.0;  // seconds
373                 // make sure it's the correct sign
374                 value = Math.abs(value);
375                 if (!isPositive) value = -value;
376                 return value;
377         }
378
379
380         /**
381          * Use the given Rational values to create a timestamp
382          * @param inDate rationals describing date
383          * @param inTime rationals describing time
384          * @return Timestamp object corresponding to inputs
385          */
386         private static Timestamp createTimestamp(Rational[] inDate, Rational[] inTime)
387         {
388                 return new Timestamp(inDate[0].intValue(), inDate[1].intValue(), inDate[2].intValue(),
389                         inTime[0].intValue(), inTime[1].intValue(), inTime[2].intValue());
390         }
391
392
393         /**
394          * Use the given String value to create a timestamp
395          * @param inStamp timestamp from exif
396          * @return Timestamp object corresponding to input
397          */
398         private static Timestamp createTimestamp(String inStamp)
399         {
400                 Timestamp stamp = null;
401                 try
402                 {
403                         stamp = new Timestamp(Integer.parseInt(inStamp.substring(0, 4)),
404                                 Integer.parseInt(inStamp.substring(5, 7)),
405                                 Integer.parseInt(inStamp.substring(8, 10)),
406                                 Integer.parseInt(inStamp.substring(11, 13)),
407                                 Integer.parseInt(inStamp.substring(14, 16)),
408                                 Integer.parseInt(inStamp.substring(17)));
409                 }
410                 catch (NumberFormatException nfe) {}
411                 return stamp;
412         }
413 }