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