show file properties on selection
[jSite2.git] / src / net / pterodactylus / jsite / gui / FileManager.java
1 /*
2  * jSite2 - FileManager.java -
3  * Copyright © 2008 David Roden
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 package net.pterodactylus.jsite.gui;
21
22 import java.awt.BorderLayout;
23 import java.awt.Color;
24 import java.awt.Component;
25 import java.awt.Dimension;
26 import java.awt.FlowLayout;
27 import java.awt.Font;
28 import java.awt.GridBagConstraints;
29 import java.awt.GridBagLayout;
30 import java.awt.Insets;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33 import java.io.File;
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38
39 import javax.swing.BorderFactory;
40 import javax.swing.JButton;
41 import javax.swing.JDialog;
42 import javax.swing.JLabel;
43 import javax.swing.JOptionPane;
44 import javax.swing.JPanel;
45 import javax.swing.JScrollPane;
46 import javax.swing.JTextField;
47 import javax.swing.JTree;
48 import javax.swing.event.TreeSelectionEvent;
49 import javax.swing.event.TreeSelectionListener;
50 import javax.swing.tree.DefaultTreeCellRenderer;
51 import javax.swing.tree.DefaultTreeModel;
52 import javax.swing.tree.TreeNode;
53 import javax.swing.tree.TreePath;
54
55 import net.pterodactylus.jsite.i18n.I18n;
56 import net.pterodactylus.jsite.i18n.I18nable;
57 import net.pterodactylus.jsite.i18n.gui.I18nAction;
58 import net.pterodactylus.jsite.i18n.gui.I18nLabel;
59 import net.pterodactylus.jsite.project.Project;
60 import net.pterodactylus.util.logging.Logging;
61 import net.pterodactylus.util.swing.SortableTreeNode;
62 import net.pterodactylus.util.swing.SwingUtils;
63
64 /**
65  * Manages physical and virtual files in a project.
66  *
67  * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
68  */
69 public class FileManager extends JDialog implements I18nable, ActionListener, TreeSelectionListener {
70
71         /** Logger. */
72         private static final Logger logger = Logging.getLogger(FileManager.class.getName());
73
74         /** The Swing interface. */
75         private final SwingInterface swingInterface;
76
77         /** The project whose files to manage. */
78         private final Project project;
79
80         /** The root of the file tree. */
81         private final SortableTreeNode fileTreeRoot;
82
83         /** The tree model for the project files. */
84         private final DefaultTreeModel fileTreeModel;
85
86         /** Files that are hidden as per {@link File#isHidden()}. */
87         private final List<String> hiddenFiles = new ArrayList<String>();
88
89         /** The tree cell renderer. */
90         private final FileCellRenderer fileCellRenderer;
91
92         /** The “rescan” action. */
93         private I18nAction rescanAction;
94
95         /** The “close” action. */
96         private I18nAction closeAction;
97
98         /** The “project files” label. */
99         private I18nLabel projectFilesLabel;
100
101         /** The tree that shows the files. */
102         private JTree fileTree;
103
104         /** The scroll pane that holds the file tree. */
105         private JScrollPane fileScrollPane;
106
107         /** The “file properties” label. */
108         private I18nLabel filePropertiesLabel;
109
110         /** The “file path” label. */
111         private I18nLabel filePathLabel;
112
113         /** The “file path” textfield. */
114         private JTextField filePathTextField;
115
116         /** The “file name” label. */
117         private I18nLabel fileNameLabel;
118
119         /** The “file name” textfield. */
120         private JTextField fileNameTextField;
121
122         /**
123          * Creates a new file manager.
124          *
125          * @param swingInterface
126          *            The Swing interface
127          * @param project
128          *            The project whose files to manage
129          */
130         public FileManager(SwingInterface swingInterface, Project project) {
131                 super(swingInterface.getMainWindow(), I18n.get("fileManager.title", project.getName()), true);
132                 logger.log(Level.FINEST, "project: " + project);
133                 this.swingInterface = swingInterface;
134                 this.project = project;
135                 fileTreeRoot = new SortableTreeNode(project.getName());
136                 fileTreeModel = new DefaultTreeModel(fileTreeRoot);
137                 fileCellRenderer = new FileCellRenderer();
138                 initActions();
139                 initComponents();
140                 pack();
141                 SwingUtils.center(this);
142         }
143
144         //
145         // ACTIONS
146         //
147
148         /**
149          * @see java.awt.Component#setVisible(boolean)
150          */
151         @Override
152         public void setVisible(boolean visible) {
153                 if (visible) {
154                         initiateFileScan();
155                 }
156                 super.setVisible(visible);
157         }
158
159         //
160         // PRIVATE METHODS
161         //
162
163         /**
164          * Initializes all actions.
165          */
166         private void initActions() {
167                 closeAction = new I18nAction("fileManager.button.close") {
168
169                         /**
170                          * {@inheritDoc}
171                          */
172                         public void actionPerformed(ActionEvent e) {
173                                 setVisible(false);
174                         }
175                 };
176                 rescanAction = new I18nAction("fileManager.button.rescan") {
177
178                         /**
179                          * {@inheritDoc}
180                          */
181                         @SuppressWarnings("synthetic-access")
182                         public void actionPerformed(ActionEvent actionEvent) {
183                                 initiateFileScan();
184                         }
185                 };
186         }
187
188         /**
189          * Initializes all components.
190          */
191         private void initComponents() {
192                 JPanel contentPanel = new JPanel(new BorderLayout(12, 12));
193                 contentPanel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
194
195                 contentPanel.add(createFileManagerPanel(), BorderLayout.CENTER);
196                 contentPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
197
198                 setContentPane(contentPanel);
199         }
200
201         /**
202          * Creates the main panel with the file tree and the file properties.
203          *
204          * @return The mail panel
205          */
206         private Component createFileManagerPanel() {
207                 JPanel fileManagerPanel = new JPanel(new BorderLayout(12, 12));
208
209                 /* file tree panel */
210                 JPanel fileTreePanel = new JPanel(new BorderLayout(12, 12));
211                 fileManagerPanel.add(fileTreePanel, BorderLayout.LINE_START);
212
213                 fileTree = new JTree(fileTreeModel);
214                 fileTree.setShowsRootHandles(false);
215                 fileTree.addTreeSelectionListener(this);
216                 fileTree.setCellRenderer(fileCellRenderer);
217                 fileTreePanel.add(fileScrollPane = new JScrollPane(fileTree), BorderLayout.CENTER);
218                 fileScrollPane.setPreferredSize(new Dimension(250, 400));
219
220                 projectFilesLabel = new I18nLabel("fileManager.label.projectFiles", fileTree);
221                 JPanel projectFilesLabelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
222                 fileTreePanel.add(projectFilesLabelPanel, BorderLayout.NORTH);
223                 projectFilesLabelPanel.add(projectFilesLabel);
224
225                 /* the right panel */
226                 JPanel rightPanel = new JPanel(new BorderLayout(12, 12));
227                 fileManagerPanel.add(rightPanel, BorderLayout.CENTER);
228
229                 /* properties panel */
230                 JPanel propertiesPanel = new JPanel(new GridBagLayout());
231                 rightPanel.add(propertiesPanel, BorderLayout.CENTER);
232                 propertiesPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(12, 12, 12, 12)));
233
234                 filePropertiesLabel = new I18nLabel("fileManager.label.fileProperties");
235                 filePropertiesLabel.setFont(filePropertiesLabel.getFont().deriveFont(Font.BOLD));
236                 propertiesPanel.add(filePropertiesLabel, new GridBagConstraints(0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
237
238                 filePathLabel = new I18nLabel("fileManager.label.filePath");
239                 filePathTextField = new JTextField();
240                 filePathTextField.setEditable(false);
241                 propertiesPanel.add(filePathLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(12, 24, 0, 0), 0, 0));
242                 propertiesPanel.add(filePathTextField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(12, 12, 0, 0), 0, 0));
243
244                 fileNameLabel = new I18nLabel("fileManager.label.fileName");
245                 fileNameTextField = new JTextField();
246                 fileNameTextField.setEditable(false);
247                 propertiesPanel.add(fileNameLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(12, 24, 0, 0), 0, 0));
248                 propertiesPanel.add(fileNameTextField, new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(12, 12, 0, 0), 0, 0));
249
250                 /* glue panel. */
251                 propertiesPanel.add(new JPanel(), new GridBagConstraints(0, 3, 2, 1, 1.0, 1.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
252
253                 /* action button panel */
254                 JPanel actionButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 12, 12));
255                 rightPanel.add(actionButtonPanel, BorderLayout.PAGE_END);
256                 actionButtonPanel.setBorder(BorderFactory.createEtchedBorder());
257
258                 JButton rescanButton = new JButton(rescanAction);
259                 actionButtonPanel.add(rescanButton);
260
261                 return fileManagerPanel;
262         }
263
264         /**
265          * Creates the button panel.
266          *
267          * @return The button panel
268          */
269         private Component createButtonPanel() {
270                 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING, 12, 12));
271
272                 buttonPanel.setBorder(BorderFactory.createEmptyBorder(-12, -12, -12, -12));
273                 JButton closeButton = new JButton(closeAction);
274                 buttonPanel.add(closeButton);
275
276                 getRootPane().setDefaultButton(closeButton);
277                 return buttonPanel;
278         }
279
280         /**
281          * Initiates a file scan.
282          */
283         private void initiateFileScan() {
284                 swingInterface.getThreadPool().execute(new Runnable() {
285
286                         /**
287                          * @see java.lang.Runnable#run()
288                          */
289                         @SuppressWarnings("synthetic-access")
290                         public void run() {
291                                 fileTree.setEnabled(false);
292                                 rescanAction.setEnabled(false);
293                                 String basePath = project.getBasePath();
294                                 File basePathDirectory = new File(basePath);
295                                 fileTreeRoot.removeAll();
296                                 hiddenFiles.clear();
297                                 if (!basePathDirectory.exists() || !basePathDirectory.isDirectory()) {
298                                         /* TODO - i18n */
299                                         JOptionPane.showMessageDialog(FileManager.this, I18n.get(""), I18n.get(""), JOptionPane.ERROR_MESSAGE);
300                                 } else {
301                                         scanDirectory(fileTreeRoot, basePathDirectory, "", hiddenFiles);
302                                 }
303                                 fileTreeModel.reload();
304                                 // fileScrollPane.revalidate();
305                                 rescanAction.setEnabled(true);
306                                 fileTree.setEnabled(true);
307                         }
308
309                         private void scanDirectory(SortableTreeNode rootNode, File directory, String currentDirectory, List<String> hiddenFiles) {
310                                 for (File file : directory.listFiles()) {
311                                         String fileName = file.getName();
312                                         SortableTreeNode fileNode = new SortableTreeNode(fileName);
313                                         rootNode.add(fileNode);
314                                         if (file.isFile() && file.isHidden()) {
315                                                 hiddenFiles.add((currentDirectory + File.separator + fileName).substring(1));
316                                         }
317                                         if (file.isDirectory()) {
318                                                 scanDirectory(fileNode, file, currentDirectory + File.separator + fileName, hiddenFiles);
319                                         }
320                                 }
321                                 rootNode.sort();
322                         }
323
324                 });
325         }
326
327         /**
328          * Returns the complete path for the given node.
329          *
330          * @param treeNode
331          *            The node
332          * @return The complete path for the node, or the empty string (“”) for the
333          *         root node
334          */
335         private String getPathForNode(TreeNode treeNode) {
336                 TreeNode[] pathToNode = fileTreeModel.getPathToRoot(treeNode);
337                 StringBuilder completePathBuilder = new StringBuilder();
338                 boolean first = true;
339                 for (TreeNode nodePathNode : pathToNode) {
340                         if (first) {
341                                 first = false;
342                                 continue;
343                         }
344                         if (!(nodePathNode instanceof SortableTreeNode)) {
345                                 logger.log(Level.WARNING, "nodePathNode is not a SortableTreeNode!");
346                                 continue;
347                         }
348                         completePathBuilder.append(File.separatorChar).append(((SortableTreeNode) nodePathNode).getUserObject());
349                 }
350                 String completePath = (completePathBuilder.length() == 0) ? "" : completePathBuilder.substring(1);
351                 return completePath;
352         }
353
354         //
355         // INTERFACE I18nable
356         //
357
358         /**
359          * {@inheritDoc}
360          */
361         public void updateI18n() {
362                 setTitle(I18n.get("fileManager.title", project.getName()));
363                 projectFilesLabel.updateI18n();
364                 filePropertiesLabel.updateI18n();
365                 filePathLabel.updateI18n();
366         }
367
368         //
369         // INTERFACE TreeSelectionListener
370         //
371
372         /**
373          * {@inheritDoc}
374          */
375         public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
376                 TreePath[] selectedPaths = fileTree.getSelectionPaths();
377                 if ((selectedPaths != null) && (selectedPaths.length == 1)) {
378                         Object lastPathComponent = selectedPaths[0].getLastPathComponent();
379                         if (!(lastPathComponent instanceof SortableTreeNode)) {
380                                 logger.log(Level.WARNING, "lastPathComponent is not a SortableTreeNode!");
381                                 return;
382                         }
383                         SortableTreeNode node = (SortableTreeNode) lastPathComponent;
384                         String completePath = getPathForNode(node);
385                         int lastSeparator = completePath.lastIndexOf(File.separatorChar);
386                         String filePath = "";
387                         String fileName;
388                         if (lastSeparator == -1) {
389                                 fileName = completePath;
390                         } else {
391                                 filePath = completePath.substring(0, lastSeparator);
392                                 fileName = completePath.substring(lastSeparator + 1);
393                         }
394                         filePathTextField.setText(filePath);
395                         fileNameTextField.setText(fileName);
396                         return;
397                 }
398                 filePathTextField.setText("");
399                 fileNameTextField.setText("");
400         }
401
402         //
403         // INTERFACE ActionListener
404         //
405
406         /**
407          * {@inheritDoc}
408          */
409         public void actionPerformed(ActionEvent actionEvent) {
410                 /* TODO */
411         }
412
413         /**
414          * Tree cell renderer that takes care of certain display properties for
415          * project-specific stuff.
416          *
417          * @author David ‘Bombe’ Roden &lt;bombe@freenetproject.org&gt;
418          */
419         private class FileCellRenderer extends DefaultTreeCellRenderer {
420
421                 /**
422                  * @see javax.swing.tree.TreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree,
423                  *      java.lang.Object, boolean, boolean, boolean, int, boolean)
424                  */
425                 @Override
426                 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
427                         Component superCellRenderer = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
428                         if (!(superCellRenderer instanceof JLabel)) {
429                                 logger.log(Level.WARNING, "superCellRenderer is not a JLabel!");
430                                 return superCellRenderer;
431                         }
432                         if (!(value instanceof SortableTreeNode)) {
433                                 logger.log(Level.WARNING, "value is not a SortableTreeNode!");
434                                 return superCellRenderer;
435                         }
436                         SortableTreeNode node = (SortableTreeNode) value;
437                         TreeNode[] pathToRoot = fileTreeModel.getPathToRoot(node);
438                         if (pathToRoot.length > 1) {
439                                 String completePath = getPathForNode(node);
440                                 if (project.getDefaultFile().equals(completePath)) {
441                                         superCellRenderer.setFont(superCellRenderer.getFont().deriveFont(Font.BOLD));
442                                 } else {
443                                         if (hiddenFiles.contains(completePath)) {
444                                                 /* fade hidden files’ font */
445                                                 Color foreground = superCellRenderer.getForeground();
446                                                 Color background = selected ? getBackgroundSelectionColor() : getBackgroundNonSelectionColor();
447                                                 Color averageColor = new Color((foreground.getRed() + background.getRed()) / 2, (foreground.getGreen() + background.getGreen()) / 2, (foreground.getBlue() + background.getBlue()) / 2);
448                                                 superCellRenderer.setForeground(averageColor);
449                                         } else {
450                                                 superCellRenderer.setFont(superCellRenderer.getFont().deriveFont(Font.PLAIN));
451                                         }
452                                 }
453                         } else {
454                                 superCellRenderer.setFont(superCellRenderer.getFont().deriveFont(Font.BOLD));
455                         }
456                         return superCellRenderer;
457                 }
458
459         }
460
461 }