package org.simantics.utils.ui.widgets; import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Text; public abstract class FileOrDirectorySelectionWidget extends Composite{ Text fileText; String filename[]; private List listeners = new ArrayList(); public FileOrDirectorySelectionWidget(Composite parent, String name,int style) { super(parent, style); this.setLayout(new GridLayout(1,false)); GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.TOP).applyTo(this); Group fileGroup = new Group(this, SWT.NONE); GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.TOP).applyTo(fileGroup); fileGroup.setText(name); fileGroup.setLayout(new GridLayout(2, false)); fileText = new Text(fileGroup, SWT.SINGLE|SWT.BORDER); GridData data = new GridData(); data.grabExcessHorizontalSpace = true; data.horizontalAlignment = SWT.FILL; fileText.setLayoutData(data); Button browseButton = new Button(fileGroup, SWT.PUSH); browseButton.setText("Browse"); data = new GridData(); browseButton.setLayoutData(data); browseButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String[] name = openDialog(); if (name != null) { setFilename(name); } } }); fileText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { String file = fileText.getText(); setFilename(file.split(",")); } }); } protected abstract String[] openDialog(); protected abstract boolean isValid(File file); protected void setFilename(String[] filename) { String text = ""; for (String s : filename) { text += s + ","; } if (text.length() > 2) text = text.substring(0, text.length() - 1); if (!text.equals(fileText.getText())) fileText.setText(text); boolean accept = true; for (String s : filename){ File file = new File(s); if (!isValid(file)) { accept = false; break; } } if (accept) this.filename = filename; else this.filename = null; for (FileSelectionListener l : listeners) { l.fileSelected(this, this.filename); } } public String[] getFilename() { return filename; } public void addListener(FileSelectionListener listener) { this.listeners.add(listener); } public void removeListener(FileSelectionListener listener) { this.listeners.remove(listener); } }