]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/load/JpegLoader.java
Version 13, August 2011
[GpsPrune.git] / tim / prune / load / JpegLoader.java
1 package tim.prune.load;
2
3 import java.io.File;
4 import java.util.TreeSet;
5
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;
11
12 import tim.prune.App;
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;
26
27 /**
28  * Class to manage the loading of Jpegs and dealing with the GPS data from them
29  */
30 public class JpegLoader implements Runnable, Cancellable
31 {
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;
44
45
46         /**
47          * Constructor
48          * @param inApp Application object to inform of photo load
49          * @param inParentFrame parent frame to reference for dialogs
50          */
51         public JpegLoader(App inApp, JFrame inParentFrame)
52         {
53                 _app = inApp;
54                 _parentFrame = inParentFrame;
55                 _fileFilter = new JpegFileFilter();
56         }
57
58
59         /**
60          * Open the GUI to select options and start the load
61          * @param inRectangle track rectangle
62          */
63         public void openDialog(LatLonRectangle inRectangle)
64         {
65                 // Create file chooser if necessary
66                 if (_fileChooser == null)
67                 {
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));}
89                 }
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)
95                 {
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();
101                 }
102         }
103
104         /** Cancel */
105         public void cancel() {
106                 _cancelled = true;
107         }
108
109
110         /**
111          * Run method for performing tasks in separate thread
112          */
113         public void run()
114         {
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);
123                 _cancelled = false;
124
125                 // Process the files recursively and build lists of photos
126                 processFileList(files, true, _subdirCheckbox.isSelected());
127                 _progressDialog.close();
128                 if (_cancelled) {return;}
129
130                 if (_fileCounts[0] == 0)
131                 {
132                         // No files found at all
133                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nofilesfound");
134                 }
135                 else if (_fileCounts[1] == 0)
136                 {
137                         // No jpegs found
138                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nojpegsfound");
139                 }
140                 else if (!_noExifCheckbox.isSelected() && _fileCounts[2] == 0)
141                 {
142                         // Need coordinates but no gps information found
143                         _app.showErrorMessage("error.jpegload.dialogtitle", "error.jpegload.nogpsfound");
144                 }
145                 else
146                 {
147                         // Found some photos to load - pass information back to app
148                         _app.informPhotosLoaded(_photos);
149                 }
150         }
151
152
153         /**
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
158          */
159         private void processFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
160         {
161                 if (inFiles == null) return;
162                 // Loop over elements in array
163                 for (int i=0; i<inFiles.length && !_cancelled; i++)
164                 {
165                         File file = inFiles[i];
166                         if (file.exists() && file.canRead())
167                         {
168                                 // Check whether it's a file or a directory
169                                 if (file.isFile())
170                                 {
171                                         processFile(file);
172                                 }
173                                 else if (file.isDirectory() && (inFirstDir || inDescend))
174                                 {
175                                         // Always process first directory,
176                                         // only process subdirectories if checkbox selected
177                                         File[] files = file.listFiles();
178                                         processFileList(files, false, inDescend);
179                                 }
180                         }
181                         // if file doesn't exist or isn't readable - ignore
182                 }
183         }
184
185
186         /**
187          * Process the given file, by attempting to extract its tags
188          * @param inFile file object to read
189          */
190         private void processFile(File inFile)
191         {
192                 // Update progress bar
193                 _fileCounts[0]++; // file found
194                 _progressDialog.showProgress(_fileCounts[0], -1);
195
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)
199
200                 if (inFile.exists() && inFile.canRead()) {
201                         _fileCounts[1]++; // jpeg found
202                 }
203                 Photo photo = createPhoto(inFile);
204                 if (photo.getDataPoint() != null) {
205                         _fileCounts[2]++; // photo has coordinates
206                 }
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())))
211                 {
212                         _photos.add(photo);
213                 }
214         }
215
216         /**
217          * Create a Photo object for the given file, including reading exif information
218          * @param inFile file object
219          * @return Photo object
220          */
221         public static Photo createPhoto(File inFile)
222         {
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)
229                 {
230                         if (jpegData.isGpsValid())
231                         {
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);
239                         }
240                         // Use exif timestamp if gps timestamp not available
241                         if (timestamp == null && jpegData.getOriginalTimestamp() != null) {
242                                 timestamp = createTimestamp(jpegData.getOriginalTimestamp());
243                         }
244                         if (timestamp == null && jpegData.getDigitizedTimestamp() != null) {
245                                 timestamp = createTimestamp(jpegData.getDigitizedTimestamp());
246                         }
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());
252                 }
253                 // Use file timestamp if exif timestamp isn't available
254                 if (timestamp == null) {
255                         timestamp = new Timestamp(inFile.lastModified());
256                 }
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);
261                 }
262                 return photo;
263         }
264
265
266         /**
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
272          */
273         private int countFileList(File[] inFiles, boolean inFirstDir, boolean inDescend)
274         {
275                 int fileCount = 0;
276                 if (inFiles != null)
277                 {
278                         // Loop over elements in array
279                         for (int i=0; i<inFiles.length; i++)
280                         {
281                                 File file = inFiles[i];
282                                 if (file.exists() && file.canRead())
283                                 {
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());
288                                         }
289                                         // Check whether it's a file or a directory
290                                         if (file.isFile())
291                                         {
292                                                 fileCount++;
293                                         }
294                                         else if (file.isDirectory() && (inFirstDir || inDescend))
295                                         {
296                                                 fileCount += countFileList(file.listFiles(), false, inDescend);
297                                         }
298                                 }
299                         }
300                 }
301                 return fileCount;
302         }
303
304
305         /**
306          * Create a DataPoint object from the given jpeg data
307          * @param inData Jpeg data including coordinates
308          * @return DataPoint object for Track
309          */
310         private static DataPoint createDataPoint(JpegData inData)
311         {
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);
322                 }
323                 return new DataPoint(latitude, longitude, altitude);
324         }
325
326
327         /**
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
332          */
333         private static double getCoordinateDoubleValue(double[] inValues, boolean isPositive)
334         {
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;
342                 return value;
343         }
344
345
346         /**
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
351          */
352         private static Timestamp createTimestamp(int[] inDate, int[] inTime)
353         {
354                 if (inDate == null || inTime == null || inDate.length != 3 || inTime.length != 3) {
355                         return null;
356                 }
357                 return new Timestamp(inDate[0], inDate[1], inDate[2],
358                         inTime[0], inTime[1], inTime[2]);
359         }
360
361
362         /**
363          * Use the given String value to create a timestamp
364          * @param inStamp timestamp from exif
365          * @return Timestamp object corresponding to input
366          */
367         private static Timestamp createTimestamp(String inStamp)
368         {
369                 Timestamp stamp = null;
370                 try
371                 {
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)));
378                 }
379                 catch (NumberFormatException nfe) {}
380                 return stamp;
381         }
382 }