A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.
Java application-securityappsecbug-bountyburp-alternativeburp-suitedasthttp-proxyinfosecintercepting-proxyjavaowaspowasp-zappenetration-testingpentestingsecuritysecurity-toolsvulnerability-scannerweb-application-securityweb-security
package opensuite.ui;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.geom.RoundRectangle2D;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Open Suite's file picker. It is used exactly as a {@link JFileChooser} is:
* set a title, a starting folder, a suggested file or a filter, call
* {@code showOpenDialog} or {@code showSaveDialog}, and read
* {@code getSelectedFile}. What opens is the suite's own window instead of
* the toolkit's: places down the left, the folder's path across the top as
* steps that can be clicked, the files in a table that sorts, and a box that
* narrows the list as it is typed in.
*
* <p>A picker opened with no folder starts where the last one was left, so a
* second file from the same folder is one click away.
*/
public class FileChooser extends JFileChooser {
/** Where the last picker was left, for the next one that names no folder. */
private static volatile File lastFolder;
private final boolean folderGiven;
private File folder;
private boolean showHidden;
private int sortColumn = 0;
private boolean sortAscending = true;
private int result = CANCEL_OPTION;
private JDialog dialog;
private final List<File> rows = new ArrayList<>();
private final Listing listing = new Listing();
private JTable table;
private JPanel crumbs;
private JTextField nameField, narrow;
private JButton approve;
private JComboBox<String> types;
private JLabel empty;
private List<File> places = List.of();
private JList<File> placeList;
public FileChooser() { super(); folderGiven = false; }
public FileChooser(String startIn) { super(startIn); folderGiven = startIn != null && !startIn.isBlank(); }
public FileChooser(File startIn) { super(startIn); folderGiven = startIn != null; }
@Override public void setCurrentDirectory(File dir) {
super.setCurrentDirectory(dir);
if (dialog != null && dir != null) folder = dir;
}
// ------------------------------------------------------------ showing
@Override public int showDialog(Component parent, String approveText) throws HeadlessException {
if (approveText != null) { setApproveButtonText(approveText); setDialogType(CUSTOM_DIALOG); }
boolean save = getDialogType() == SAVE_DIALOG;
boolean foldersOnly = getFileSelectionMode() == DIRECTORIES_ONLY;
// Where to start: the folder that was named, or the suggested file's, or where the last picker was left.
File suggested = getSelectedFile();
File start = null;
if (suggested != null && suggested.getParentFile() != null && suggested.getParentFile().isDirectory()) start = suggested.getParentFile();
if (start == null && folderGiven) start = getCurrentDirectory();
if (start == null) start = lastFolder;
if (start == null || !start.isDirectory()) start = getCurrentDirectory();
if (start != null && start.isFile()) start = start.getParentFile();
if (start == null || !start.isDirectory()) start = new File(System.getProperty("user.home"));
folder = start;
Window owner = parent == null ? null : parent instanceof Window w ? w : SwingUtilities.getWindowAncestor(parent);
String title = getDialogTitle();
if (title == null || title.isBlank()) title = foldersOnly ? "Select folder" : save ? "Save" : "Open";
dialog = new JDialog(owner, title, Dialog.ModalityType.APPLICATION_MODAL);
dialog.setIconImages(AppIcon.images());
dialog.setContentPane(build(save, foldersOnly, suggested));
dialog.setSize(900, 580);
dialog.setMinimumSize(new Dimension(640, 400));
dialog.setLocationRelativeTo(owner);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.getRootPane().registerKeyboardAction(e -> dialog.dispose(),
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
dialog.getRootPane().setDefaultButton(approve);
result = CANCEL_OPTION;
show(folder);
SwingUtilities.invokeLater(() -> (save ? nameField : table).requestFocusInWindow());
dialog.setVisible(true); // returns when the window closes
dialog = null;
if (result == APPROVE_OPTION) lastFolder = folder;
return result;
}
@Override public int showOpenDialog(Component parent) throws HeadlessException {
setDialogType(OPEN_DIALOG);
return showDialog(parent, null);
}
@Override public int showSaveDialog(Component parent) throws HeadlessException {
setDialogType(SAVE_DIALOG);
return showDialog(parent, null);
}
// ------------------------------------------------------------ the window
private JComponent build(boolean save, boolean foldersOnly, File suggested) {
JPanel root = new JPanel(new BorderLayout());
root.setBackground(Theme.BG);
// Top: up, home, new folder, then the path as steps, then the narrowing box.
JButton up = tool(new Mark(Mark.UP), "Up one folder");
JButton home = tool(new Mark(Mark.HOME), "Home folder");
JButton make = tool(new Mark(Mark.NEW), "New folder");
up.addActionListener(e -> { File p = folder.getParentFile(); if (p != null) show(p); });
home.addActionListener(e -> show(new File(System.getProperty("user.home"))));
make.addActionListener(e -> newFolder());
crumbs = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
crumbs.setOpaque(false);
JScrollPane crumbScroll = new JScrollPane(crumbs, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
crumbScroll.setBorder(BorderFactory.createEmptyBorder());
crumbScroll.setOpaque(false);
crumbScroll.getViewport().setOpaque(false);
narrow = Ui.field("", 14);
narrow.putClientProperty("JTextField.placeholderText", "Filter");
narrow.setToolTipText("Show only the names that contain this text");
narrow.getDocument().addDocumentListener(onChange(this::relist));
JPanel tools = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
tools.setOpaque(false);
tools.add(up); tools.add(home); tools.add(make);
JPanel filterSide = new JPanel(new FlowLayout(FlowLayout.RIGHT, 6, 0));
filterSide.setOpaque(false);
JLabel glass = new JLabel(Glyphs.search(14, Theme.MUTED));
filterSide.add(glass); filterSide.add(narrow);
// The suite's own mark, over the places column, so the window is plainly Open Suite's.
String ink = String.format("#%06x", Theme.TEXT.getRGB() & 0xFFFFFF), orange = String.format("#%06x", Theme.ACCENT.getRGB() & 0xFFFFFF);
JLabel brand = new JLabel("<html><span style='color:" + ink + "'>Open</span> <span style='color:" + orange + "'>Suite</span></html>",
AppIcon.icon(22), SwingConstants.LEFT);
brand.setFont(Ui.BOLD.deriveFont(Ui.BOLD.getSize2D() + 3f));
brand.setIconTextGap(7);
brand.setPreferredSize(new Dimension(158, 28));
JPanel lead = new JPanel(new BorderLayout());
lead.setOpaque(false);
lead.add(brand, BorderLayout.WEST);
lead.add(tools, BorderLayout.CENTER);
JPanel top = new JPanel(new BorderLayout(8, 0));
top.setOpaque(false);
top.setBorder(Ui.pad(10, 12, 10, 12));
top.add(lead, BorderLayout.WEST);
top.add(crumbScroll, BorderLayout.CENTER);
top.add(filterSide, BorderLayout.EAST);
// Left: the places most files are in.
places = placesOf();
placeList = new JList<>(places.toArray(new File[0]));
placeList.setFont(Ui.PLAIN);
placeList.setBackground(Theme.SURFACE);
placeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
placeList.setFixedCellHeight(30);
placeList.setCellRenderer(new PlaceRenderer());
placeList.addListSelectionListener(e -> {
File p = placeList.getSelectedValue();
if (!e.getValueIsAdjusting() && p != null && !p.equals(folder)) show(p);
});
JScrollPane placeScroll = Ui.scroll(placeList);
placeScroll.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 1, Theme.BORDER));
placeScroll.setPreferredSize(new Dimension(170, 10));
// Centre: the folder's contents.
table = new JTable(listing);
Ui.styleTable(table);
table.setRowHeight(26);
table.setShowGrid(false);
table.setIntercellSpacing(new Dimension(0, 0));
table.setFillsViewportHeight(true);
table.setSelectionMode(isMultiSelectionEnabled() ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION : ListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().getColumn(0).setCellRenderer(new NameRenderer());
DefaultTableCellRenderer quiet = new DefaultTableCellRenderer();
quiet.setForeground(Theme.MUTED);
quiet.setBorder(Ui.pad(0, 6, 0, 6));
table.getColumnModel().getColumn(1).setCellRenderer(quiet);
table.getColumnModel().getColumn(2).setCellRenderer(quiet);
table.getColumnModel().getColumn(0).setPreferredWidth(430);
table.getColumnModel().getColumn(1).setPreferredWidth(90);
table.getColumnModel().getColumn(2).setPreferredWidth(150);
table.getTableHeader().setReorderingAllowed(false);
table.getTableHeader().addMouseListener(new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
int c = table.columnAtPoint(e.getPoint());
if (c < 0) return;
if (c == sortColumn) sortAscending = !sortAscending; else { sortColumn = c; sortAscending = true; }
relist();
}
});
// Two presses on the same row within the desktop's double-click time
// open it. Counted here from the presses themselves: a click event is
// not sent at all when the pointer moves between press and release,
// which a hand on a fine screen does, so the folder would not open.
table.addMouseListener(new MouseAdapter() {
private long lastPress;
private int lastRow = -1;
@Override public void mousePressed(MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
int row = table.rowAtPoint(e.getPoint());
Object set = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
long within = Math.max(500, set instanceof Integer i ? i : 500);
boolean second = row >= 0 && row == lastRow && e.getWhen() - lastPress <= within;
lastRow = second ? -1 : row;
lastPress = e.getWhen();
if (!second) return;
table.setRowSelectionInterval(row, row);
e.consume();
SwingUtilities.invokeLater(FileChooser.this::openRow);
}
});
table.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "open-row");
table.getActionMap().put("open-row", new AbstractAction() {
@Override public void actionPerformed(java.awt.event.ActionEvent e) { openRow(); }
});
table.addKeyListener(new KeyAdapter() {
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { File p = folder.getParentFile(); if (p != null) show(p); }
}
// Typing a letter goes to the first name that starts with it.
@Override public void keyTyped(KeyEvent e) {
char ch = Character.toLowerCase(e.getKeyChar());
if (!Character.isLetterOrDigit(ch) && ch != '.' && ch != '_') return;
int from = table.getSelectedRow() + 1;
for (int k = 0; k < rows.size(); k++) {
int i = (from + k) % rows.size();
if (rows.get(i).getName().toLowerCase(Locale.ROOT).startsWith(String.valueOf(ch))) {
table.setRowSelectionInterval(i, i);
table.scrollRectToVisible(table.getCellRect(i, 0, true));
return;
}
}
}
});
table.getSelectionModel().addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) return;
int i = table.getSelectedRow();
if (i < 0 || i >= rows.size()) return;
File f = rows.get(i);
// A file's name goes in the box; a folder's does when it is a folder that is being picked.
if (f.isFile() || foldersOnly) nameField.setText(f.getName());
});
JScrollPane tableScroll = Ui.scroll(table);
tableScroll.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Theme.BORDER));
tableScroll.getViewport().setBackground(Theme.CONTENT);
empty = Ui.label("");
empty.setForeground(Theme.MUTED);
empty.setHorizontalAlignment(SwingConstants.CENTER);
JPanel centre = new JPanel(new CardLayout());
centre.add(tableScroll, "files");
JPanel emptyCard = new JPanel(new BorderLayout());
emptyCard.setBackground(Theme.CONTENT);
emptyCard.setBorder(BorderFactory.createMatteBorder(1, 0, 1, 0, Theme.BORDER));
emptyCard.add(empty, BorderLayout.CENTER);
centre.add(emptyCard, "empty");
this.centreCards = centre;
JPanel middle = new JPanel(new BorderLayout());
middle.setOpaque(false);
middle.add(placeScroll, BorderLayout.WEST);
middle.add(centre, BorderLayout.CENTER);
// Anything a caller hangs beside the list keeps its place, on the right.
JComponent extra = getAccessory();
if (extra != null) {
JPanel side = new JPanel(new BorderLayout());
side.setOpaque(false);
side.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 1, 1, 0, Theme.BORDER), Ui.pad(10, 10, 10, 10)));
side.add(extra, BorderLayout.NORTH);
middle.add(side, BorderLayout.EAST);
}
// Bottom: the name, the kinds of file shown, and the two buttons.
nameField = Ui.field(suggested != null ? suggested.getName() : "", 30);
nameField.addActionListener(e -> accept());
JLabel nameLabel = Ui.label(foldersOnly ? "Folder:" : "File name:");
List<FileFilter> filters = new ArrayList<>(Arrays.asList(getChoosableFileFilters()));
FileFilter chosen = getFileFilter();
if (chosen != null && !filters.contains(chosen)) filters.add(chosen);
types = new JComboBox<>();
types.setFont(Ui.PLAIN);
for (FileFilter f : filters) types.addItem(f.getDescription());
if (chosen != null) types.setSelectedIndex(filters.indexOf(chosen));
types.addActionListener(e -> {
int i = types.getSelectedIndex();
if (i >= 0 && i < filters.size()) { setFileFilter(filters.get(i)); relist(); }
});
JCheckBox hidden = Ui.check("Show hidden files", false);
hidden.setOpaque(false);
hidden.addActionListener(e -> { showHidden = hidden.isSelected(); relist(); });
JPanel nameRow = new JPanel(new BorderLayout(8, 0));
nameRow.setOpaque(false);
nameRow.add(nameLabel, BorderLayout.WEST);
nameRow.add(nameField, BorderLayout.CENTER);
if (filters.size() > 1 && !foldersOnly) {
types.setPreferredSize(new Dimension(220, nameField.getPreferredSize().height));
nameRow.add(types, BorderLayout.EAST);
}
String word = getApproveButtonText();
if (word == null || word.isBlank()) word = foldersOnly ? "Select folder" : save ? "Save" : "Open";
approve = primary(word);
approve.addActionListener(e -> accept());
JButton cancel = Ui.button("Cancel");
cancel.addActionListener(e -> dialog.dispose());
Ui.sizedAlike(Math.max(96, approve.getPreferredSize().width + 8), approve, cancel);
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT, 8, 0));
buttons.setOpaque(false);
buttons.add(cancel); buttons.add(approve);
JPanel lastRow = new JPanel(new BorderLayout());
lastRow.setOpaque(false);
lastRow.add(hidden, BorderLayout.WEST);
lastRow.add(buttons, BorderLayout.EAST);
JPanel bottom = new JPanel();
bottom.setOpaque(false);
bottom.setLayout(new BoxLayout(bottom, BoxLayout.Y_AXIS));
bottom.setBorder(Ui.pad(12, 12, 12, 12));
bottom.add(nameRow);
bottom.add(Box.createVerticalStrut(12));
bottom.add(lastRow);
root.add(top, BorderLayout.NORTH);
root.add(middle, BorderLayout.CENTER);
root.add(bottom, BorderLayout.SOUTH);
return root;
}
private JPanel centreCards;
// ------------------------------------------------------------ the folder shown
/** Show a folder: its path as steps, its contents in the list. */
private void show(File dir) {
if (dir == null) return;
if (!dir.isDirectory()) {
JOptionPane.showMessageDialog(dialog, "That folder could not be opened:\n" + dir.getPath(), dialog.getTitle(), JOptionPane.WARNING_MESSAGE);
return;
}
folder = dir.getAbsoluteFile();
if (narrow != null && !narrow.getText().isEmpty()) narrow.setText(""); // lists by itself
steps();
relist();
int at = places.indexOf(folder);
if (at >= 0) placeList.setSelectedIndex(at); else placeList.clearSelection();
}
/** The path across the top, one button a folder; a click goes to that folder. */
private void steps() {
crumbs.removeAll();
List<File> chain = new ArrayList<>();
for (File f = folder; f != null; f = f.getParentFile()) chain.add(0, f);
for (int i = 0; i < chain.size(); i++) {
File f = chain.get(i);
boolean last = i == chain.size() - 1;
String text = f.getName().isEmpty() ? rootName(f) : f.getName();
JButton b = new JButton(text);
b.setFont(last ? Ui.BOLD : Ui.PLAIN);
b.setForeground(last ? Theme.TEXT : Theme.MUTED);
b.setBorder(Ui.pad(4, 6, 4, 6));
b.setContentAreaFilled(false);
b.setFocusPainted(false);
b.setFocusable(false);
b.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b.setToolTipText(f.getPath());
b.addActionListener(e -> show(f));
crumbs.add(b);
if (!last) {
JLabel sep = new JLabel(Glyphs.chevron(10, Theme.MUTED, 0));
crumbs.add(sep);
}
}
crumbs.revalidate();
crumbs.repaint();
// The folder being shown is the end of the path: keep that end in view.
SwingUtilities.invokeLater(() -> crumbs.scrollRectToVisible(new Rectangle(Math.max(0, crumbs.getPreferredSize().width - 1), 0, 1, 1)));
}
/** Read the folder again: folders first, then the files the filter admits, in the chosen order. */
private void relist() {
if (folder == null || table == null) return;
String want = narrow.getText().strip().toLowerCase(Locale.ROOT);
boolean foldersOnly = getFileSelectionMode() == DIRECTORIES_ONLY;
FileFilter filter = getFileFilter();
File[] all = folder.listFiles();
rows.clear();
if (all != null) for (File f : all) {
if (!showHidden && hidden(f)) continue;
boolean dir = f.isDirectory();
if (!dir && foldersOnly) continue;
if (!dir && filter != null && !filter.accept(f)) continue;
if (!want.isEmpty() && !f.getName().toLowerCase(Locale.ROOT).contains(want)) continue;
rows.add(f);
}
Comparator<File> by = switch (sortColumn) {
case 1 -> Comparator.comparingLong(f -> f.isDirectory() ? -1 : f.length());
case 2 -> Comparator.comparingLong(File::lastModified);
default -> Comparator.comparing(f -> f.getName().toLowerCase(Locale.ROOT));
};
if (!sortAscending) by = by.reversed();
Comparator<File> foldersFirst = Comparator.comparing(f -> !f.isDirectory());
rows.sort(foldersFirst.thenComparing(by));
listing.fireTableDataChanged();
table.getTableHeader().repaint();
empty.setText(all == null ? "This folder cannot be read." : !want.isEmpty() ? "Nothing here matches \"" + narrow.getText().strip() + "\"."
: foldersOnly ? "No folders here." : "This folder is empty.");
((CardLayout) centreCards.getLayout()).show(centreCards, rows.isEmpty() ? "empty" : "files");
}
/** A double click or Enter on a row: go into a folder, take a file. */
private void openRow() {
int i = table.getSelectedRow();
if (i < 0 || i >= rows.size()) return;
File f = rows.get(i);
if (f.isDirectory()) show(f); else accept();
}
private void newFolder() {
String name = JOptionPane.showInputDialog(dialog, "Name of the new folder:", "New folder", JOptionPane.PLAIN_MESSAGE);
if (name == null || name.isBlank()) return;
File made = new File(folder, name.strip());
if (!made.mkdir()) {
JOptionPane.showMessageDialog(dialog, "The folder could not be made here.", "New folder", JOptionPane.WARNING_MESSAGE);
return;
}
relist();
int at = rows.indexOf(made);
if (at >= 0) { table.setRowSelectionInterval(at, at); table.scrollRectToVisible(table.getCellRect(at, 0, true)); }
}
// ------------------------------------------------------------ the answer
/** The button, Enter in the name box, or a double click on a file. */
private void accept() {
boolean save = getDialogType() == SAVE_DIALOG;
boolean foldersOnly = getFileSelectionMode() == DIRECTORIES_ONLY;
String typed = nameField.getText().strip();
// Several rows picked, where several may be.
if (isMultiSelectionEnabled() && table.getSelectedRowCount() > 1) {
List<File> picked = new ArrayList<>();
for (int i : table.getSelectedRows()) picked.add(rows.get(i));
setSelectedFiles(picked.toArray(new File[0]));
finish();
return;
}
if (typed.isEmpty()) {
// Nothing named: a folder is being picked and this one is it, or the row under the cursor is opened.
if (foldersOnly) { answer(folder); return; }
int i = table.getSelectedRow();
if (i >= 0 && i < rows.size() && rows.get(i).isDirectory()) show(rows.get(i));
return;
}
// A path may be typed in full, or from the home folder with ~.
if (typed.startsWith("~")) typed = System.getProperty("user.home") + typed.substring(1);
File named = new File(typed);
if (!named.isAbsolute()) named = new File(folder, typed);
if (named.isDirectory() && !foldersOnly) { nameField.setText(""); show(named); return; }
if (foldersOnly && !named.isDirectory()) {
JOptionPane.showMessageDialog(dialog, "There is no folder of that name here.", dialog.getTitle(), JOptionPane.WARNING_MESSAGE);
return;
}
if (!save && !named.exists()) {
JOptionPane.showMessageDialog(dialog, "There is no file of that name here:\n" + named.getPath(), dialog.getTitle(), JOptionPane.WARNING_MESSAGE);
return;
}
if (save && named.getParentFile() != null && !named.getParentFile().isDirectory()) {
JOptionPane.showMessageDialog(dialog, "The folder for that file does not exist:\n" + named.getParent(), dialog.getTitle(), JOptionPane.WARNING_MESSAGE);
return;
}
answer(named);
}
private void answer(File f) {
setSelectedFile(f);
if (isMultiSelectionEnabled()) setSelectedFiles(new File[]{ f });
finish();
}
private void finish() {
result = APPROVE_OPTION;
dialog.dispose();
}
// ------------------------------------------------------------ parts
/** Home and the folders of it that most files are in, then the whole file system. */
private static List<File> placesOf() {
File home = new File(System.getProperty("user.home"));
List<File> out = new ArrayList<>();
out.add(home);
for (String n : new String[]{ "Desktop", "Documents", "Downloads" }) {
File f = new File(home, n);
if (f.isDirectory()) out.add(f);
}
File last = lastFolder;
if (last != null && last.isDirectory() && !out.contains(last)) out.add(last);
// The whole file system: one root, or on Windows each drive.
File[] roots = File.listRoots();
if (roots != null) for (File r : roots) if (!out.contains(r)) out.add(r);
return out;
}
/** What a root is called: "/" where there is one, a drive's letter ("C:") on Windows. */
static String rootName(File root) {
String p = root.getPath();
return p.length() > 1 && (p.endsWith("\\") || p.endsWith("/")) ? p.substring(0, p.length() - 1) : p;
}
/**
* Whether a file is kept out of sight. On Windows that includes what the
* system marks as its own, such as the old-name links in a home folder,
* which are read without being followed since they cannot be opened.
*/
static boolean hidden(File f) {
if (opensuite.core.Os.WINDOWS) {
try {
java.nio.file.attribute.DosFileAttributes a = java.nio.file.Files.readAttributes(f.toPath(),
java.nio.file.attribute.DosFileAttributes.class, java.nio.file.LinkOption.NOFOLLOW_LINKS);
return a.isHidden() || a.isSystem();
} catch (java.io.IOException | RuntimeException e) { /* fall through to the plain answer */ }
}
return f.isHidden();
}
private static String sizeOf(long bytes) {
if (bytes < 1024) return bytes + " B";
String[] units = { "KB", "MB", "GB", "TB" };
double v = bytes;
int u = -1;
do { v /= 1024; u++; } while (v >= 1024 && u < units.length - 1);
return (v >= 100 ? String.format(Locale.ROOT, "%.0f", v) : String.format(Locale.ROOT, "%.1f", v)) + " " + units[u];
}
private static DocumentListener onChange(Runnable r) {
return new DocumentListener() {
@Override public void insertUpdate(DocumentEvent e) { r.run(); }
@Override public void removeUpdate(DocumentEvent e) { r.run(); }
@Override public void changedUpdate(DocumentEvent e) { r.run(); }
};
}
/** A small square button of the top bar. */
private static JButton tool(Icon icon, String tip) {
JButton b = Ui.button("", tip);
b.setIcon(icon);
b.setPreferredSize(new Dimension(32, 28));
b.setFocusable(false);
return b;
}
/** The button that gives the answer, in the suite's own colour. */
private static JButton primary(String text) {
JButton b = new JButton(text) {
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(!isEnabled() ? Theme.SURFACE_3 : getModel().isPressed() || getModel().isRollover() ? Theme.ACCENT_DARK : Theme.ACCENT);
g2.fill(new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 6, 6));
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setFont(getFont());
g2.setColor(Color.WHITE);
FontMetrics fm = g2.getFontMetrics();
g2.drawString(getText(), (getWidth() - fm.stringWidth(getText())) / 2, (getHeight() - fm.getHeight()) / 2 + fm.getAscent());
g2.dispose();
}
};
b.setFont(Ui.BOLD);
b.setContentAreaFilled(false);
b.setBorderPainted(false);
b.setFocusPainted(false);
b.setRolloverEnabled(true);
b.setPreferredSize(new Dimension(Math.max(96, b.getFontMetrics(Ui.BOLD).stringWidth(text) + 36), Ui.button("x").getPreferredSize().height));
return b;
}
private final class Listing extends AbstractTableModel {
private final String[] columns = { "Name", "Size", "Modified" };
private final SimpleDateFormat when = new SimpleDateFormat("d MMM yyyy, HH:mm");
@Override public int getRowCount() { return rows.size(); }
@Override public int getColumnCount() { return columns.length; }
@Override public String getColumnName(int c) {
return columns[c] + (c == sortColumn ? (sortAscending ? " ▴" : " ▾") : "");
}
@Override public Object getValueAt(int r, int c) {
if (r >= rows.size()) return "";
File f = rows.get(r);
return switch (c) {
case 0 -> f;
case 1 -> f.isDirectory() ? "" : sizeOf(f.length());
default -> when.format(new Date(f.lastModified()));
};
}
}
/** A name with a folder or a sheet of paper before it. */
private static final class NameRenderer extends DefaultTableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable t, Object v, boolean sel, boolean focus, int r, int c) {
super.getTableCellRendererComponent(t, v, sel, false, r, c);
File f = (File) v;
setText(f.getName());
setIcon(new Mark(f.isDirectory() ? Mark.FOLDER : Mark.FILE));
setIconTextGap(8);
setBorder(Ui.pad(0, 8, 0, 6));
return this;
}
}
private final class PlaceRenderer extends DefaultListCellRenderer {
@Override public Component getListCellRendererComponent(JList<?> l, Object v, int i, boolean sel, boolean focus) {
super.getListCellRendererComponent(l, v, i, sel, false);
File f = (File) v;
File home = new File(System.getProperty("user.home"));
boolean root = f.getParentFile() == null;
setText(f.equals(home) ? "Home" : root ? (f.getPath().equals("/") ? "File system" : rootName(f)) : f.getName());
setIcon(new Mark(f.equals(home) ? Mark.HOME : root ? Mark.DISK : Mark.FOLDER));
setIconTextGap(8);
setBorder(Ui.pad(0, 12, 0, 8));
setToolTipText(f.getPath());
if (sel) { setBackground(Theme.ACCENT_LIGHT); setForeground(Theme.TEXT); }
else setBackground(Theme.SURFACE);
return this;
}
}
/** The picker's own small drawings: a folder, a sheet of paper, a house, a disk, an arrow up, a folder with a plus. */
private static final class Mark implements Icon {
static final int FOLDER = 0, FILE = 1, HOME = 2, DISK = 3, UP = 4, NEW = 5;
private final int kind;
Mark(int kind) { this.kind = kind; }
@Override public int getIconWidth() { return 16; }
@Override public int getIconHeight() { return 16; }
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2.translate(x, y);
g2.setStroke(new BasicStroke(1.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
switch (kind) {
case FOLDER, NEW -> {
Path2D p = new Path2D.Float();
p.moveTo(1.5, 4); p.lineTo(6, 4); p.lineTo(7.5, 5.8); p.lineTo(14.5, 5.8);
p.lineTo(14.5, 13); p.lineTo(1.5, 13); p.closePath();
if (kind == FOLDER) {
g2.setColor(new Color(Theme.ACCENT.getRed(), Theme.ACCENT.getGreen(), Theme.ACCENT.getBlue(), 200));
g2.fill(p);
} else {
g2.setColor(Theme.ICON);
g2.draw(p);
g2.drawLine(8, 8, 8, 11); g2.drawLine(6, 9, 10, 9);
}
}
case FILE -> {
Path2D p = new Path2D.Float();
p.moveTo(3.5, 1.5); p.lineTo(9.5, 1.5); p.lineTo(12.5, 4.5); p.lineTo(12.5, 14.5); p.lineTo(3.5, 14.5); p.closePath();
g2.setColor(Theme.CONTENT); g2.fill(p);
g2.setColor(Theme.MUTED); g2.draw(p);
g2.drawLine(9, 2, 9, 5); g2.drawLine(9, 5, 12, 5);
}
case HOME -> {
g2.setColor(Theme.ICON);
Path2D p = new Path2D.Float();
p.moveTo(2, 8); p.lineTo(8, 2.5); p.lineTo(14, 8);
g2.draw(p);
Path2D w = new Path2D.Float();
w.moveTo(4, 7.5); w.lineTo(4, 13.5); w.lineTo(12, 13.5); w.lineTo(12, 7.5);
g2.draw(w);
}
case DISK -> {
g2.setColor(Theme.ICON);
g2.draw(new RoundRectangle2D.Float(2, 4, 12, 8, 3, 3));
g2.fillOval(10, 7, 2, 2);
}
default -> {
g2.setColor(Theme.ICON);
g2.drawLine(8, 13, 8, 3); g2.drawLine(4, 7, 8, 3); g2.drawLine(12, 7, 8, 3);
}
}
g2.dispose();
}
}
}