View Javadoc
1   /**
2    * Copyright 2011, Aiki IT, FotoRenamer
3    * <p/>
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * <p/>
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * <p/>
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package de.aikiit.fotorenamer.gui;
17  
18  import de.aikiit.fotorenamer.exception.InvalidDirectoryException;
19  import de.aikiit.fotorenamer.exception.NoFilesFoundException;
20  import de.aikiit.fotorenamer.image.CreationDateFromExifImageRenamer;
21  import de.aikiit.fotorenamer.util.LocalizationHelper;
22  import org.apache.logging.log4j.LogManager;
23  import org.apache.logging.log4j.Logger;
24  import org.apache.logging.log4j.util.Strings;
25  
26  import javax.swing.*;
27  import java.awt.*;
28  import java.awt.datatransfer.DataFlavor;
29  import java.awt.dnd.DnDConstants;
30  import java.awt.dnd.DropTarget;
31  import java.awt.dnd.DropTargetDropEvent;
32  import java.awt.event.KeyAdapter;
33  import java.awt.event.KeyEvent;
34  import java.io.File;
35  import java.io.IOException;
36  
37  import static de.aikiit.fotorenamer.util.LocalizationHelper.getBundleString;
38  import static de.aikiit.fotorenamer.util.LocalizationHelper.getParameterizedBundleString;
39  
40  /**
41   * This component provides a means to select images that are to be renamed.
42   *
43   * @author hirsch, 13.10.2003
44   * @version 2004-01-08
45   */
46  class ImageDirectorySelector extends JPanel {
47      /**
48       * The logger of this class.
49       **/
50      private static final Logger LOG =
51              LogManager.getLogger(ImageDirectorySelector.class);
52  
53      /**
54       * Contains the selected directory as a text field or any user input.
55       */
56      private JTextField textField = null;
57      /**
58       * The UI's button to start directory selection.
59       */
60      private JButton browseButton = null;
61      /**
62       * An image icon that is displayed as part of the button.
63       */
64      private final ImageIcon imageIcon;
65  
66      /**
67       * Default constructor provides means to create an imageSelect with a given
68       * image icon that is able to only work on directories.
69       *
70       * @param icon This icon is used as a picture in the select
71       *             button.
72       */
73      ImageDirectorySelector(final ImageIcon icon) {
74          super();
75          this.imageIcon = icon;
76          init();
77      }
78  
79      /**
80       * Provides a means to disable this component
81       * (e.g. during run of file renaming).
82       *
83       * @param enable Enable/disable this component.
84       */
85      public final void setEnabled(final boolean enable) {
86          textField.setEnabled(enable);
87          browseButton.setEnabled(enable);
88      }
89  
90      /**
91       * This method is used as a blocking call until the user selects something
92       * in the UI.
93       *
94       * @return Returns whether anything is selected within the current
95       * configuration.
96       */
97      // TODO improve design, let class emit an event in case a directory was selected
98      public final boolean isWaiting() {
99          return Strings.isEmpty(getSelectedDirectory());
100     }
101 
102     /**
103      * Initialize internal UI components.
104      */
105     private void init() {
106         // Set layout.
107         GridBagLayout grid = new GridBagLayout();
108         GridBagConstraints gbc = new GridBagConstraints();
109         gbc.insets = new Insets(0, 2, 0, 2);
110         setLayout(grid);
111 
112         // Add field.
113         gbc.gridx = 0;
114         gbc.gridy = 0;
115         gbc.gridheight = 1;
116         gbc.gridwidth = 2;
117         gbc.anchor = GridBagConstraints.WEST;
118         textField = new JTextField(60);
119         grid.setConstraints(textField, gbc);
120         add(textField);
121 
122         // Add button.
123         gbc.gridx = 2;
124         gbc.gridy = 0;
125         gbc.gridheight = 1;
126         gbc.gridwidth = 1;
127         gbc.anchor = GridBagConstraints.EAST;
128 
129         // show button
130         browseButton = this.imageIcon == null
131                 ? new JButton(
132                 getBundleString(
133                         "fotorenamer.ui.selector.title"))
134                 : new JButton(
135                 getBundleString(
136                         "fotorenamer.ui.selector.title"), this.imageIcon);
137         browseButton.setMnemonic(getBundleString("fotorenamer.ui.selector.title.mnemonic").charAt(0));
138         browseButton.setMargin(new Insets(1, 1, 1, 1));
139         grid.setConstraints(browseButton, gbc);
140         add(browseButton);
141 
142         // Add action listener and take current contents of textfield as start directory
143         browseButton.addActionListener(event -> {
144 
145             String currentPath = getSelectedDirectory();
146             JFileChooser fileDlg = new JFileChooser(com.google.common.base.Strings.isNullOrEmpty(currentPath) ? null : currentPath);
147 
148             fileDlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
149             fileDlg.setDialogTitle(
150                     getBundleString(
151                             "fotorenamer.ui.selector.directory"));
152             fileDlg.setApproveButtonText(getBundleString(
153                     "fotorenamer.ui.selector.select"));
154 
155             if (fileDlg.showOpenDialog(this)
156                     == JFileChooser.APPROVE_OPTION) {
157                 // use getCanonicalPath() to avoid ..-path manipulations and
158                 // try to set the selected file in the UI
159                 try {
160                     textField.setText(
161                             fileDlg.getSelectedFile().getCanonicalPath());
162                 } catch (IOException ioe) {
163                     LOG.error("Error while selecting directory, extracted text is: "
164                             + textField.getText());
165                     LOG.error(ioe.getMessage());
166                 }
167             }
168         });
169 
170         // make textfield drag'n'dropable
171         textField.setDropTarget(new DropTarget() {
172             public synchronized void drop(DropTargetDropEvent evt) {
173                 try {
174                     evt.acceptDrop(DnDConstants.ACTION_COPY);
175                     Object transferData = evt
176                             .getTransferable().getTransferData(
177                                     DataFlavor.javaFileListFlavor);
178 
179                     if (transferData instanceof java.util.List) {
180                         //noinspection unchecked
181                         java.util.List<File> droppedFiles = (java.util.List<File>) transferData;
182                         if (!droppedFiles.isEmpty()) {
183                             for (File droppedFile : droppedFiles) {
184                                 if (droppedFile.isDirectory()) {
185                                     final String path = droppedFile.getAbsolutePath();
186                                     LOG.info("Drag'n'drop done for file: " + path + " with " + droppedFiles.size() + " element(s) received");
187                                     textField.setText(path);
188                                     break;
189                                 }
190                             }
191                         }
192                     }
193 
194                 } catch (Exception ex) {
195                     LOG.info("Drag'd'drop did not work due to " + ex);
196                 }
197             }
198         });
199 
200         // make textfield react on Enter/copied over from MainUIWindow
201         textField.addKeyListener(new KeyAdapter() {
202             @Override
203             public void keyPressed(final KeyEvent e) {
204                 if (e.getKeyCode() == KeyEvent.VK_ENTER) {
205 
206                     SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
207                         @Override
208                         protected Void doInBackground() {
209                             if (isWaiting()) {
210                                 showErrorPopup(getBundleString("fotorenamer.ui.error.nodirectory"), getBundleString("fotorenamer.ui.error.nodirectory.title"));
211                                 return null;
212                             }
213 
214                             // perform renaming
215                             try {
216                                 CreationDateFromExifImageRenamer renamer =
217                                         new CreationDateFromExifImageRenamer(getSelectedDirectory());
218                                 new Thread(renamer).start();
219                             } catch (InvalidDirectoryException uv) {
220                                 LOG.info("Invalid directory selected: " + uv.getMessage());
221                                 showErrorPopup(getParameterizedBundleString("fotorenamer.ui.error.invaliddirectory", uv.getMessage()), getBundleString("fotorenamer.ui.error.invaliddirectory.title"));
222                             } catch (NoFilesFoundException kde) {
223                                 LOG.info("No files found in " + kde.getMessage());
224                                 showErrorPopup(getParameterizedBundleString("fotorenamer.ui.error.nofiles", kde.getMessage()), getBundleString("fotorenamer.ui.error.nofiles.title"));
225                             }
226                             return null;
227                         }
228 
229                         @Override
230                         protected void done() {
231                             // TODO how can I communicate with the surrounding UI to block the user from pressing the buttons
232                             LOG.debug("Finished working, cannot reset UI from the selector itself. Should find a way to lock the startbutton somehow.");
233                         }
234                     };
235                     // Execute the SwingWorker; GUI will not freeze
236                     worker.execute();
237                 }
238             }
239 
240         });
241     }
242 
243     void showErrorPopup(final String message, final String title) {
244         JOptionPane.showMessageDialog(null,
245                 message,
246                 title,
247                 JOptionPane.ERROR_MESSAGE);
248     }
249 
250     /**
251      * Current directory is the representation of this component.
252      *
253      * @return The currently selected directory.
254      */
255     final String getSelectedDirectory() {
256         String currentSelection = LocalizationHelper.removeCrLf(this.textField.getText());
257         if (!com.google.common.base.Strings.isNullOrEmpty(currentSelection)) {
258             currentSelection = currentSelection.replaceAll("~", System.getProperty("user.home"));
259             currentSelection = currentSelection.trim();
260             LOG.debug("User input transformed into " + currentSelection);
261         }
262         return currentSelection;
263     }
264 }