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