Files
SmartCSV.fx/src/main/java/ninja/javafx/smartcsv/fx/SmartCSVController.java

489 lines
17 KiB
Java
Raw Normal View History

2015-11-28 23:06:14 +01:00
/*
The MIT License (MIT)
-----------------------------------------------------------------------------
Copyright (c) 2015 javafx.ninja <info@javafx.ninja>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package ninja.javafx.smartcsv.fx;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
2015-11-28 23:06:14 +01:00
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
2015-12-07 22:41:59 +01:00
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
2015-11-28 23:06:14 +01:00
import javafx.scene.layout.BorderPane;
import javafx.stage.FileChooser;
import ninja.javafx.smartcsv.FileReader;
import ninja.javafx.smartcsv.csv.CSVFileReader;
import ninja.javafx.smartcsv.csv.CSVFileWriter;
import ninja.javafx.smartcsv.fx.about.AboutController;
2015-12-07 22:41:59 +01:00
import ninja.javafx.smartcsv.fx.list.ValidationErrorListCell;
2016-01-11 09:03:22 +01:00
import ninja.javafx.smartcsv.fx.preferences.PreferencesController;
2015-11-28 23:06:14 +01:00
import ninja.javafx.smartcsv.fx.table.ObservableMapValueFactory;
import ninja.javafx.smartcsv.fx.table.ValidationCellFactory;
import ninja.javafx.smartcsv.fx.table.model.CSVModel;
import ninja.javafx.smartcsv.fx.table.model.CSVRow;
2015-12-17 19:56:14 +01:00
import ninja.javafx.smartcsv.fx.table.model.CSVValue;
2016-01-11 09:03:22 +01:00
import ninja.javafx.smartcsv.preferences.PreferencesFileReader;
2016-01-11 11:14:25 +01:00
import ninja.javafx.smartcsv.preferences.PreferencesFileWriter;
2015-12-07 22:41:59 +01:00
import ninja.javafx.smartcsv.validation.ValidationError;
2015-11-28 23:06:14 +01:00
import ninja.javafx.smartcsv.validation.ValidationFileReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
2016-01-11 09:03:22 +01:00
import org.supercsv.prefs.CsvPreference;
2015-11-28 23:06:14 +01:00
import java.io.File;
2016-01-11 09:03:22 +01:00
import java.io.IOException;
2015-11-28 23:06:14 +01:00
import java.net.URL;
import java.util.Optional;
2015-11-28 23:06:14 +01:00
import java.util.ResourceBundle;
import static java.lang.Math.max;
2015-12-30 09:52:00 +01:00
import static javafx.application.Platform.exit;
2015-11-28 23:06:14 +01:00
import static javafx.application.Platform.runLater;
/**
* main controller of the application
*/
@Component
public class SmartCSVController extends FXMLController {
2016-01-11 11:14:25 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// constants
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private static final File PREFERENCES_FILE = new File(System.getProperty("user.home") +
File.separator +
".SmartCSV.fx" +
File.separator + "" +
"preferences.json");
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// injections
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2016-01-11 09:03:22 +01:00
@Autowired
private PreferencesFileReader preferencesLoader;
2016-01-11 11:14:25 +01:00
@Autowired
private PreferencesFileWriter preferencesWriter;
2015-11-28 23:06:14 +01:00
@Autowired
private CSVFileReader csvLoader;
@Autowired
private ValidationFileReader validationLoader;
@Autowired
private CSVFileWriter csvFileWriter;
@Autowired
private AboutController aboutController;
2016-01-11 09:03:22 +01:00
@Autowired
private PreferencesController preferencesController;
2015-11-28 23:06:14 +01:00
@FXML
private BorderPane applicationPane;
@FXML
private Label csvName;
@FXML
private Label configurationName;
@FXML
private Label stateName;
2015-11-28 23:06:14 +01:00
2015-12-07 22:41:59 +01:00
@FXML
private ListView errorList;
@FXML
private AnchorPane tableWrapper;
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// members
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private ValidationCellFactory cellFactory;
2015-11-28 23:06:14 +01:00
private final LoadCSVService loadCSVService = new LoadCSVService();
private final SaveCSVService saveCSVService = new SaveCSVService();
private CSVModel model;
2015-12-07 22:41:59 +01:00
private TableView<CSVRow> tableView;
private File lastDirectory;
private BooleanProperty fileChanged = new SimpleBooleanProperty(true);
private ResourceBundle resourceBundle;
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// init
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void initialize(URL location, ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
saveCSVService.setWriter(csvFileWriter);
cellFactory = new ValidationCellFactory(resourceBundle);
errorList.setCellFactory(param -> new ValidationErrorListCell(resourceBundle));
errorList.getSelectionModel().selectedItemProperty().addListener(observable -> scrollToError());
fileChanged.addListener(observable -> setStateName());
setStateName();
2016-01-11 09:16:40 +01:00
loadCsvPreferences();
2015-11-28 23:06:14 +01:00
}
2016-01-11 09:03:22 +01:00
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// setter
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Value("${fxml.smartcvs.view}")
@Override
public void setFxmlFilePath(String filePath) {
this.fxmlFilePath = filePath;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@FXML
public void openCsv(ActionEvent actionEvent) {
loadFile(csvLoader, "CSV files (*.csv)", "*.csv", "Open CSV", csvName);
2015-11-28 23:06:14 +01:00
}
@FXML
public void openConfig(ActionEvent actionEvent) {
loadFile(validationLoader, "JSON files (*.json)", "*.json", "Open Validation Configuration", configurationName);
2015-11-28 23:06:14 +01:00
}
@FXML
public void saveCsv(ActionEvent actionEvent) {
saveCSVService.restart();
}
@FXML
public void saveAsCsv(ActionEvent actionEvent) {
saveFile(csvFileWriter, "CSV files (*.csv)", "*.csv");
}
@FXML
public void close(ActionEvent actionEvent) {
if (canExit()) {
2015-12-30 09:52:00 +01:00
exit();
}
2015-11-28 23:06:14 +01:00
}
2015-12-02 13:53:20 +01:00
@FXML
public void about(ActionEvent actionEvent) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("About");
alert.setHeaderText("SmartCSV.fx");
alert.getDialogPane().setContent(aboutController.getView());
2015-12-02 13:53:20 +01:00
alert.showAndWait();
}
2015-11-28 23:06:14 +01:00
2016-01-11 09:03:22 +01:00
@FXML
public void preferences(ActionEvent actionEvent) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Preferences");
alert.setHeaderText("Preferences");
alert.getDialogPane().setContent(preferencesController.getView());
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
2016-01-11 11:14:25 +01:00
CsvPreference csvPreference = preferencesController.getCsvPreference();
setCsvPreference(csvPreference);
saveCsvPreferences(csvPreference);
2016-01-11 09:03:22 +01:00
}
}
public boolean canExit() {
boolean canExit = true;
if (model != null && fileChanged.get()) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle(resourceBundle.getString("dialog.exit.title"));
alert.setHeaderText(resourceBundle.getString("dialog.exit.header.text"));
alert.setContentText(resourceBundle.getString("dialog.exit.text"));
Optional<ButtonType> result = alert.showAndWait();
if (result.get() != ButtonType.OK){
canExit = false;
}
}
return canExit;
2015-12-02 13:53:20 +01:00
}
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// private methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2016-01-11 09:16:40 +01:00
private void loadCsvPreferences() {
2016-01-11 09:03:22 +01:00
try {
2016-01-11 11:14:25 +01:00
if (PREFERENCES_FILE.exists()) {
preferencesLoader.read(PREFERENCES_FILE);
}
2016-01-11 09:16:40 +01:00
setCsvPreference(preferencesLoader.getCSVpreference());
2016-01-11 11:14:25 +01:00
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveCsvPreferences(CsvPreference csvPreference) {
try {
createPreferenceFile();
preferencesWriter.saveFile(PREFERENCES_FILE, csvPreference);
} catch (IOException e) {
2016-01-11 09:03:22 +01:00
e.printStackTrace();
}
}
2016-01-11 11:14:25 +01:00
private void createPreferenceFile() throws IOException {
if (!PREFERENCES_FILE.exists()) {
createPreferencesFileFolder();
PREFERENCES_FILE.createNewFile();
}
}
private void createPreferencesFileFolder() {
if (!PREFERENCES_FILE.getParentFile().exists()) {
PREFERENCES_FILE.getParentFile().mkdir();
}
}
2016-01-11 09:03:22 +01:00
private void setCsvPreference(CsvPreference csvPreference) {
csvLoader.setCsvPreference(csvPreference);
csvFileWriter.setCsvPreference(csvPreference);
preferencesController.setCsvPreference(csvPreference);
}
private void loadFile(FileReader fileReader, String filterText, String filter, String title, Label fileLabel) {
2015-11-28 23:06:14 +01:00
final FileChooser fileChooser = new FileChooser();
//Set extension filter
final FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(filterText, filter);
fileChooser.getExtensionFilters().add(extFilter);
fileChooser.setTitle(title);
if (lastDirectory != null) {
fileChooser.setInitialDirectory(lastDirectory);
}
2015-11-28 23:06:14 +01:00
//Show open file dialog
final File file = fileChooser.showOpenDialog(applicationPane.getScene().getWindow());
if (file != null) {
loadCSVService.setFileLabel(fileLabel);
2015-11-28 23:06:14 +01:00
loadCSVService.setFile(file);
loadCSVService.setFileReader(fileReader);
loadCSVService.restart();
}
}
private void saveFile(CSVFileWriter writer, String filterText, String filter) {
if (model != null) {
final FileChooser fileChooser = new FileChooser();
//Set extension filter
final FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(filterText, filter);
fileChooser.getExtensionFilters().add(extFilter);
File initfile = new File(model.getFilepath());
fileChooser.setInitialDirectory(initfile.getParentFile());
fileChooser.setInitialFileName(initfile.getName());
fileChooser.setTitle("Save File");
//Show open file dialog
final File file = fileChooser.showOpenDialog(applicationPane.getScene().getWindow());
if (file != null) {
model.setFilepath(file.getAbsolutePath());
saveCSVService.setWriter(writer);
2015-11-28 23:06:14 +01:00
saveCSVService.restart();
}
}
}
/**
* Creates new table view and add the new content
*/
private void resetContent() {
model = csvLoader.getData();
if (model != null) {
model.setValidator(validationLoader.getValidator());
tableView = new TableView<>();
2015-11-28 23:06:14 +01:00
for (String column : model.getHeader()) {
addColumn(column, tableView);
}
tableView.getItems().setAll(model.getRows());
tableView.setEditable(true);
2015-12-07 22:41:59 +01:00
AnchorPane.setBottomAnchor(tableView, 0.0);
AnchorPane.setTopAnchor(tableView, 0.0);
AnchorPane.setLeftAnchor(tableView, 0.0);
AnchorPane.setRightAnchor(tableView, 0.0);
tableWrapper.getChildren().setAll(tableView);
2015-12-07 22:41:59 +01:00
errorList.setItems(model.getValidationError());
}
2015-11-28 23:06:14 +01:00
}
/**
* Adds a column with the given name to the tableview
* @param header name of the column header
* @param tableView the tableview
*/
private void addColumn(String header, TableView tableView) {
TableColumn column = new TableColumn(header);
column.setCellValueFactory(new ObservableMapValueFactory(header));
column.setCellFactory(cellFactory);
column.setEditable(true);
column.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CSVRow, CSVValue>>() {
@Override
public void handle(TableColumn.CellEditEvent<CSVRow, CSVValue> event) {
event.getTableView().getItems().get(event.getTablePosition().getRow()).
2015-12-18 01:47:38 +01:00
getColumns().get(header).setValue(event.getNewValue());
runLater(() -> {
fileChanged.setValue(true);
model.revalidate();
});
2015-11-28 23:06:14 +01:00
}
});
tableView.getColumns().add(column);
}
2015-12-07 22:41:59 +01:00
private void scrollToError() {
ValidationError entry = (ValidationError)errorList.getSelectionModel().getSelectedItem();
if (entry != null) {
if (entry.getLineNumber() != null) {
tableView.scrollTo(max(0, entry.getLineNumber() - 1));
2015-12-07 22:41:59 +01:00
tableView.getSelectionModel().select(entry.getLineNumber());
} else {
tableView.scrollTo(0);
}
}
}
2015-11-28 23:06:14 +01:00
private void setStateName() {
if (model != null) {
if (fileChanged.get()) {
stateName.setText(resourceBundle.getString("state.changed"));
} else {
stateName.setText(resourceBundle.getString("state.unchanged"));
}
} else {
stateName.setText("");
}
}
2015-11-28 23:06:14 +01:00
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// inner class
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Service class for async load of a csv file
*/
private class LoadCSVService extends Service {
private File file = null;
private FileReader fileReader;
private Label fileLabel;
2015-11-28 23:06:14 +01:00
public void setFile(File value) {
file = value;
}
public void setFileReader(FileReader fileReader) {
this.fileReader = fileReader;
}
public void setFileLabel(Label fileLabel) {
this.fileLabel = fileLabel;
}
2015-11-28 23:06:14 +01:00
@Override
protected Task createTask() {
return new Task() {
@Override
protected Void call() throws Exception {
if (file != null) {
try {
lastDirectory = file.getParentFile();
2015-11-28 23:06:14 +01:00
fileReader.read(file);
runLater(() -> {
fileLabel.setText(file.getName());
resetContent();
fileChanged.setValue(false);
});
2015-12-07 22:41:59 +01:00
} catch (Throwable ex) {
2015-11-28 23:06:14 +01:00
ex.printStackTrace();
}
}
return null;
}
};
}
2015-11-28 23:06:14 +01:00
}
/**
* Service class for async load of a csv file
*/
private class SaveCSVService extends Service {
private CSVFileWriter writer;
public void setWriter(CSVFileWriter writer) {
this.writer = writer;
}
2015-11-28 23:06:14 +01:00
@Override
protected Task createTask() {
return new Task() {
@Override
protected Void call() throws Exception {
try {
writer.saveFile(model);
runLater(() -> {
resetContent();
fileChanged.setValue(false);
});
2015-12-07 22:41:59 +01:00
} catch (Throwable ex) {
2015-11-28 23:06:14 +01:00
ex.printStackTrace();
}
return null;
}
};
}
2015-11-28 23:06:14 +01:00
}
}