]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/save/ExifSaver.java
Version 4, January 2008
[GpsPrune.git] / tim / prune / save / ExifSaver.java
1 package tim.prune.save;
2
3 import java.awt.BorderLayout;
4 import java.awt.Dimension;
5 import java.awt.FlowLayout;
6 import java.awt.Frame;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.io.File;
10
11 import javax.swing.BoxLayout;
12 import javax.swing.JButton;
13 import javax.swing.JCheckBox;
14 import javax.swing.JDialog;
15 import javax.swing.JLabel;
16 import javax.swing.JOptionPane;
17 import javax.swing.JPanel;
18 import javax.swing.JProgressBar;
19 import javax.swing.JScrollPane;
20 import javax.swing.JTable;
21
22 import tim.prune.ExternalTools;
23 import tim.prune.I18nManager;
24 import tim.prune.data.Altitude;
25 import tim.prune.data.Coordinate;
26 import tim.prune.data.DataPoint;
27 import tim.prune.data.Photo;
28 import tim.prune.data.PhotoList;
29 import tim.prune.data.PhotoStatus;
30
31 /**
32  * Class to call Exiftool to save coordinate information in jpg files
33  */
34 public class ExifSaver implements Runnable
35 {
36         private Frame _parentFrame = null;
37         private JDialog _dialog = null;
38         private JCheckBox _overwriteCheckbox = null;
39         private JProgressBar _progressBar = null;
40         private PhotoTableModel _photoTableModel = null;
41
42
43         // To preserve timestamps of file use parameter -P
44         // To overwrite file (careful!) use parameter -overwrite_original_in_place
45
46         // To read all GPS tags,   use -GPS:All
47         // To delete all GPS tags, use -GPS:All=
48
49         // To set Altitude, use -GPSAltitude= and -GPSAltitudeRef=
50         // To set Latitude, use -GPSLatitude= and -GPSLatitudeRef=
51
52         // To delete all tags with overwrite: exiftool -P -overwrite_original_in_place -GPS:All= <filename>
53
54         // To set altitude with overwrite: exiftool -P -overwrite_original_in_place -GPSAltitude=1234 -GPSAltitudeRef='Above Sea Level' <filename>
55         // (setting altitude ref to 0 doesn't work)
56         // To set latitude with overwrite: exiftool -P -overwrite_original_in_place -GPSLatitude='12 34 56.78' -GPSLatitudeRef=N <filename>
57         // (latitude as space-separated deg min sec, reference as either N or S)
58         // Same for longitude, reference E or W
59
60
61         /**
62          * Constructor
63          * @param inParentFrame parent frame
64          */
65         public ExifSaver(Frame inParentFrame)
66         {
67                 _parentFrame = inParentFrame;
68         }
69
70
71         /**
72          * Save exif information to all photos in the list
73          * whose coordinate information has changed since loading
74          * @param inPhotoList list of photos to save
75          * @return true if saved
76          */
77         public boolean saveExifInformation(PhotoList inPhotoList)
78         {
79                 // Check if external exif tool can be called
80                 boolean exifToolInstalled = ExternalTools.isExiftoolInstalled();
81                 if (!exifToolInstalled)
82                 {
83                         // show warning
84                         int answer = JOptionPane.showConfirmDialog(_dialog, I18nManager.getText("dialog.saveexif.noexiftool"),
85                                 I18nManager.getText("dialog.saveexif.title"),
86                                 JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
87                         if (answer == JOptionPane.NO_OPTION || answer == JOptionPane.CLOSED_OPTION)
88                         {
89                                 return false;
90                         }
91                 }
92                 // Make model and add all photos to it
93                 _photoTableModel = new PhotoTableModel(inPhotoList.getNumPhotos());
94                 for (int i=0; i<inPhotoList.getNumPhotos(); i++)
95                 {
96                         Photo photo = inPhotoList.getPhoto(i);
97                         PhotoTableEntry entry = new PhotoTableEntry(photo);
98                         _photoTableModel.addPhotoInfo(entry);
99                 }
100                 // Check if there are any modified photos to save
101                 if (_photoTableModel.getNumSaveablePhotos() < 1)
102                 {
103                         JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("dialog.saveexif.nothingtosave"),
104                                 I18nManager.getText("dialog.saveexif.title"), JOptionPane.WARNING_MESSAGE);
105                         return false;
106                 }
107                 // Construct dialog
108                 _dialog = new JDialog(_parentFrame, I18nManager.getText("dialog.saveexif.title"), true);
109                 _dialog.setLocationRelativeTo(_parentFrame);
110                 _dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
111                 _dialog.getContentPane().add(makeDialogComponents());
112                 _dialog.pack();
113                 // set progress bar and show dialog
114                 _progressBar.setVisible(false);
115                 _dialog.show();
116                 return true;
117         }
118
119
120         /**
121          * Put together the dialog components for adding to the gui
122          * @return panel containing all gui components
123          */
124         private JPanel makeDialogComponents()
125         {
126                 JPanel panel = new JPanel();
127                 panel.setLayout(new BorderLayout());
128                 panel.add(new JLabel(I18nManager.getText("dialog.saveexif.intro")), BorderLayout.NORTH);
129                 // centre panel with most controls
130                 JPanel centrePanel = new JPanel();
131                 centrePanel.setLayout(new BorderLayout());
132                 // table panel with table and checkbox
133                 JPanel tablePanel = new JPanel();
134                 tablePanel.setLayout(new BorderLayout());
135                 JTable photoTable = new JTable(_photoTableModel);
136                 JScrollPane scrollPane = new JScrollPane(photoTable);
137                 scrollPane.setPreferredSize(new Dimension(300, 160));
138                 tablePanel.add(scrollPane, BorderLayout.CENTER);
139                 _overwriteCheckbox = new JCheckBox(I18nManager.getText("dialog.saveexif.overwrite"));
140                 _overwriteCheckbox.setSelected(false);
141                 tablePanel.add(_overwriteCheckbox, BorderLayout.SOUTH);
142                 centrePanel.add(tablePanel, BorderLayout.CENTER);
143                 // progress bar below main controls
144                 _progressBar = new JProgressBar(0, 100);
145                 centrePanel.add(_progressBar, BorderLayout.SOUTH);
146                 panel.add(centrePanel, BorderLayout.CENTER);
147                 // Right-hand panel with select all, none buttons
148                 JPanel rightPanel = new JPanel();
149                 rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
150                 JButton selectAllButton = new JButton(I18nManager.getText("button.selectall"));
151                 selectAllButton.addActionListener(new ActionListener() {
152                         public void actionPerformed(ActionEvent e)
153                         {
154                                 selectPhotos(true);
155                         }
156                 });
157                 rightPanel.add(selectAllButton);
158                 JButton selectNoneButton = new JButton(I18nManager.getText("button.selectnone"));
159                 selectNoneButton.addActionListener(new ActionListener() {
160                         public void actionPerformed(ActionEvent e)
161                         {
162                                 selectPhotos(false);
163                         }
164                 });
165                 rightPanel.add(selectNoneButton);
166                 panel.add(rightPanel, BorderLayout.EAST);
167                 // Lower panel with ok and cancel buttons
168                 JPanel buttonPanel = new JPanel();
169                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
170                 JButton okButton = new JButton(I18nManager.getText("button.ok"));
171                 okButton.addActionListener(new ActionListener() {
172                         public void actionPerformed(ActionEvent e)
173                         {
174                                 // start new thread to do save
175                                 new Thread(ExifSaver.this).start();
176                         }
177                 });
178                 buttonPanel.add(okButton);
179                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
180                 cancelButton.addActionListener(new ActionListener() {
181                         public void actionPerformed(ActionEvent e)
182                         {
183                                 _dialog.dispose();
184                         }
185                 });
186                 buttonPanel.add(cancelButton);
187                 panel.add(buttonPanel, BorderLayout.SOUTH);
188                 return panel;
189         }
190
191
192         /**
193          * Select all or select none
194          * @param inSelected true to select all photos, false to deselect all
195          */
196         private void selectPhotos(boolean inSelected)
197         {
198                 int numPhotos = _photoTableModel.getRowCount();
199                 for (int i=0; i<numPhotos; i++)
200                 {
201                         _photoTableModel.getPhotoTableEntry(i).setSaveFlag(inSelected);
202                 }
203                 _photoTableModel.fireTableDataChanged();
204         }
205
206
207         /**
208          * Run method for saving in separate thread
209          */
210         public void run()
211         {
212                 PhotoTableEntry entry = null;
213                 Photo photo = null;
214                 int numPhotos = _photoTableModel.getRowCount();
215                 _progressBar.setMaximum(numPhotos);
216                 _progressBar.setValue(0);
217                 _progressBar.setVisible(true);
218                 boolean overwriteFlag = _overwriteCheckbox.isSelected();
219                 int numSaved = 0;
220                 // Loop over all photos in list
221                 for (int i=0; i<numPhotos; i++)
222                 {
223                         entry = _photoTableModel.getPhotoTableEntry(i);
224                         if (entry != null && entry.getSaveFlag())
225                         {
226                                 // Only look at photos which are selected and whose status has changed since load
227                                 photo = entry.getPhoto();
228                                 if (photo != null && photo.getOriginalStatus() != photo.getCurrentStatus())
229                                 {
230                                         // Increment counter if save successful
231                                         if (savePhoto(photo, overwriteFlag))
232                                         {
233                                                 numSaved++;
234                                         }
235                                 }
236                         }
237                         // update progress bar
238                         _progressBar.setValue(i + 1);
239                 }
240                 _progressBar.setVisible(false);
241                 // Show confirmation dialog
242                 JOptionPane.showMessageDialog(_dialog, I18nManager.getText("dialog.saveexif.ok1") + " "
243                         + numSaved + " " + I18nManager.getText("dialog.saveexif.ok2"),
244                         I18nManager.getText("dialog.saveexif.title"), JOptionPane.INFORMATION_MESSAGE);
245                 // close dialog, all finished
246                 _dialog.dispose();
247         }
248
249
250         /**
251          * Save the details for the given photo
252          * @param inPhoto Photo object
253          * @param inOverwriteFlag true to overwrite file, false otherwise
254          * @return true if details saved ok
255          */
256         private boolean savePhoto(Photo inPhoto, boolean inOverwriteFlag)
257         {
258                 // Check whether photo file still exists
259                 if (!inPhoto.getFile().exists())
260                 {
261                         // photo file doesn't exist any more
262                         JOptionPane.showMessageDialog(_parentFrame,
263                                 I18nManager.getText("error.saveexif.filenotfound") + " : " + inPhoto.getFile().getAbsolutePath(),
264                                 I18nManager.getText("dialog.saveexif.title"), JOptionPane.ERROR_MESSAGE);
265                         return false;
266                 }
267                 // Warn if file read-only and selected to overwrite
268                 if (inOverwriteFlag && !inPhoto.getFile().canWrite())
269                 {
270                         // eek, can't overwrite file
271                         int answer = JOptionPane.showConfirmDialog(_parentFrame,
272                                 I18nManager.getText("error.saveexif.cannotoverwrite1") + " " + inPhoto.getFile().getAbsolutePath()
273                                         + " " + I18nManager.getText("error.saveexif.cannotoverwrite2"),
274                                 I18nManager.getText("dialog.saveexif.title"),
275                                 JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
276                         if (answer == JOptionPane.YES_OPTION)
277                         {
278                                 // don't overwrite this image but write to copy
279                                 inOverwriteFlag = false;
280                         }
281                         else
282                         {
283                                 // don't do anything with this file
284                                 return false;
285                         }
286                 }
287                 String[] command = null;
288                 if (inPhoto.getCurrentStatus() == PhotoStatus.NOT_CONNECTED)
289                 {
290                         // Photo is no longer connected, so delete gps tags
291                         command = getDeleteGpsExifTagsCommand(inPhoto.getFile(), inOverwriteFlag);
292                 }
293                 else
294                 {
295                         // Photo is now connected, so write new gps tags
296                         command = getWriteGpsExifTagsCommand(inPhoto.getFile(), inPhoto.getDataPoint(), inOverwriteFlag);
297                 }
298                 // Execute exif command
299                 try
300                 {
301                         Runtime.getRuntime().exec(command);
302                 }
303                 catch (Exception e)
304                 {
305                         // show error message
306                         JOptionPane.showMessageDialog(_parentFrame, "Exception: '" + e.getClass().getName() + "' : "
307                                 + e.getMessage(), I18nManager.getText("dialog.saveexif.title"), JOptionPane.ERROR_MESSAGE);
308                         return false;
309                 }
310                 return true;
311         }
312
313
314         /**
315          * Create the command to delete the gps exif tags from the specified file
316          * @param inFile file from which to delete tags
317          * @param inOverwrite true to overwrite file, false to create copy
318          * @return external command to delete gps tags
319          */
320         private static String[] getDeleteGpsExifTagsCommand(File inFile, boolean inOverwrite)
321         {
322                 // Make a string array to construct the command and its parameters
323                 String[] result = new String[inOverwrite?5:4];
324                 result[0] = "exiftool";
325                 result[1] = "-P";
326                 if (inOverwrite) {result[2] = " -overwrite_original_in_place";}
327                 // remove all gps tags
328                 int paramOffset = inOverwrite?3:2;
329                 result[paramOffset] = "-GPS:All=";
330                 result[paramOffset + 1] = inFile.getAbsolutePath();
331                 return result;
332         }
333
334
335         /**
336          * Create the comand to write the gps exif tags to the specified file
337          * @param inFile file to which to write the tags
338          * @param inPoint DataPoint object containing coordinate information
339          * @param inOverwrite true to overwrite file, false to create copy
340          * @return external command to write gps tags
341          */
342         private static String[] getWriteGpsExifTagsCommand(File inFile, DataPoint inPoint, boolean inOverwrite)
343         {
344                 // Make a string array to construct the command and its parameters
345                 String[] result = new String[inOverwrite?10:9];
346                 result[0] = "exiftool";
347                 result[1] = "-P";
348                 if (inOverwrite) {result[2] = "-overwrite_original_in_place";}
349                 int paramOffset = inOverwrite?3:2;
350                 // To set latitude : -GPSLatitude='12 34 56.78' -GPSLatitudeRef='N'
351                 // (latitude as space-separated deg min sec, reference as either N or S)
352                 result[paramOffset] = "-GPSLatitude='" + inPoint.getLatitude().output(Coordinate.FORMAT_DEG_MIN_SEC_WITH_SPACES)
353                  + "'";
354                 result[paramOffset + 1] = "-GPSLatitudeRef=" + inPoint.getLatitude().output(Coordinate.FORMAT_CARDINAL);
355                 // same for longitude with space-separated deg min sec, reference as either E or W
356                 result[paramOffset + 2] = "-GPSLongitude='" + inPoint.getLongitude().output(Coordinate.FORMAT_DEG_MIN_SEC_WITH_SPACES)
357                  + "'";
358                 result[paramOffset + 3] = "-GPSLongitudeRef=" + inPoint.getLongitude().output(Coordinate.FORMAT_CARDINAL);
359                 // add altitude if it has it
360                 result[paramOffset + 4] = "-GPSAltitude="
361                  + (inPoint.hasAltitude()?inPoint.getAltitude().getValue(Altitude.FORMAT_METRES):0);
362                 result[paramOffset + 5] = "-GPSAltitudeRef='Above Sea Level'";
363                 // add the filename to modify
364                 result[paramOffset + 6] = inFile.getAbsolutePath();
365                 return result;
366         }
367 }