use of javafx.application.Platform in project PayFile by mikehearn.
the class ConnectServerController method maybeSettleLastServer.
/**
* Possibly reconnect to the last paid server and ask it to give us back the money. Note that after 24 hours this
* channel will expire anyway, so if the server is gone, it's not the end of the world, we'll still get the money
* back. The returned future completes immediately if nothing needs to be done.
*/
private CompletableFuture<Void> maybeSettleLastServer(HostAndPort newServerName) {
final HostAndPort lastPaidServer = Settings.getLastPaidServer();
// If we didn't have a payment channel, or we did but it's with the same server we're connecting to, ignore.
if (lastPaidServer == null || newServerName.equals(lastPaidServer))
return CompletableFuture.completedFuture(null);
BigInteger amountInLastServer = PayFileClient.getBalanceForServer(lastPaidServer.getHostText(), lastPaidServer.getPort(), Main.bitcoin.wallet());
// If the last server we paid was already settled, ignore.
if (amountInLastServer.compareTo(BigInteger.ZERO) == 0)
return CompletableFuture.completedFuture(null);
// Otherwise we have some money locked up with the last server. Ask for it back.
final CompletableFuture<Void> future = new CompletableFuture<>();
titleLabel.setText(String.format("Contacting %s to request early settlement ...", lastPaidServer));
log.info("Connecting to {}", lastPaidServer);
Main.connect(lastPaidServer, REFUND_CONNECT_TIMEOUT_MSEC).whenCompleteAsync((client, ex) -> {
if (ex == null) {
log.info("Connected. Requesting early settlement.");
titleLabel.setText("Requesting early settlement ...");
client.settlePaymentChannel().whenCompleteAsync((v, settleEx) -> {
if (settleEx == null) {
log.info("Settled. Proceeding ...");
client.disconnect();
future.complete(null);
} else {
crashAlert(settleEx);
}
}, Platform::runLater);
} else {
log.error("Failed to connect", ex);
titleLabel.setText(defaultTitle);
informUserTheyMustWait(lastPaidServer);
}
}, Platform::runLater);
return future;
}
use of javafx.application.Platform in project PayFile by mikehearn.
the class Controller method download.
public void download(ActionEvent event) throws Exception {
File destination = null;
try {
final PayFileClient.File downloadingFile = checkNotNull(selectedFile.get());
if (downloadingFile.getPrice() > getBalance().longValue())
throw new InsufficientMoneyException(BigInteger.valueOf(downloadingFile.getPrice() - getBalance().longValue()));
// Ask the user where to put it.
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle("Select download directory");
File directory = chooser.showDialog(Main.instance.mainWindow);
if (directory == null)
return;
destination = new File(directory, downloadingFile.getFileName());
FileOutputStream fileStream = new FileOutputStream(destination);
final long startTime = System.currentTimeMillis();
cancelBtn.setVisible(true);
progressBarLabel.setText("Downloading " + downloadingFile.getFileName());
// Make the UI update whilst the download is in progress: progress bar and balance label.
ProgressOutputStream stream = new ProgressOutputStream(fileStream, downloadingFile.getSize());
progressBar.progressProperty().bind(stream.progressProperty());
Main.client.setOnPaymentMade((amt) -> Platform.runLater(this::refreshBalanceLabel));
// Swap in the progress bar with an animation.
animateSwap();
// ... and start the download.
Settings.setLastPaidServer(Main.serverAddress);
downloadFuture = Main.client.downloadFile(downloadingFile, stream);
final File fDestination = destination;
// When we're done ...
downloadFuture.handleAsync((ok, exception) -> {
// ... swap widgets back out again
animateSwap();
if (exception != null) {
if (!(exception instanceof CancellationException))
crashAlert(exception);
} else {
// Otherwise inform the user we're finished and let them open the file.
int secondsTaken = (int) (System.currentTimeMillis() - startTime) / 1000;
runAlert((stage, controller) -> controller.withOpenFile(stage, downloadingFile, fDestination, secondsTaken));
}
return null;
}, Platform::runLater);
} catch (InsufficientMoneyException e) {
if (destination != null)
destination.delete();
final String price = Utils.bitcoinValueToFriendlyString(BigInteger.valueOf(selectedFile.get().getPrice()));
final String missing = String.valueOf(e.missing);
informationalAlert("Insufficient funds", "This file costs %s BTC but you can't afford that. You need %s satoshis to complete the transaction.", price, missing);
}
}
use of javafx.application.Platform in project bitsquare by bitsquare.
the class BitsquareApp method start.
@Override
public void start(Stage stage) throws IOException {
BitsquareApp.primaryStage = stage;
String logPath = Paths.get(env.getProperty(AppOptionKeys.APP_DATA_DIR_KEY), "bitsquare").toString();
Log.setup(logPath);
log.info("Log files under: " + logPath);
Version.printVersion();
Utilities.printSysInfo();
Log.setLevel(Level.toLevel(env.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY)));
UserThread.setExecutor(Platform::runLater);
UserThread.setTimerClass(UITimer.class);
shutDownHandler = this::stop;
// setup UncaughtExceptionHandler
Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
// Might come from another thread
if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
log.error(throwable.getMessage());
} else if (throwable instanceof ClassCastException && "sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData".equals(throwable.getMessage())) {
log.warn(throwable.getMessage());
} else {
log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
log.error("throwableMessage= " + throwable.getMessage());
log.error("throwableClass= " + throwable.getClass());
log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
throwable.printStackTrace();
UserThread.execute(() -> showErrorPopup(throwable, false));
}
};
Thread.setDefaultUncaughtExceptionHandler(handler);
Thread.currentThread().setUncaughtExceptionHandler(handler);
try {
Utilities.checkCryptoPolicySetup();
} catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) {
e.printStackTrace();
UserThread.execute(() -> showErrorPopup(e, true));
}
Security.addProvider(new BouncyCastleProvider());
try {
// Guice
bitsquareAppModule = new BitsquareAppModule(env, primaryStage);
injector = Guice.createInjector(bitsquareAppModule);
injector.getInstance(InjectorViewFactory.class).setInjector(injector);
Version.setBtcNetworkId(injector.getInstance(BitsquareEnvironment.class).getBitcoinNetwork().ordinal());
if (Utilities.isLinux())
System.setProperty("prism.lcdtext", "false");
Storage.setDatabaseCorruptionHandler((String fileName) -> {
corruptedDatabaseFiles.add(fileName);
if (mainView != null)
mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
});
// load the main view and create the main scene
CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class);
mainView = (MainView) viewLoader.load(MainView.class);
mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
/* Storage.setDatabaseCorruptionHandler((String fileName) -> {
corruptedDatabaseFiles.add(fileName);
if (mainView != null)
mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
});*/
//740
scene = new Scene(mainView.getRoot(), 1200, 700);
Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13);
Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13);
Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13);
Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13);
scene.getStylesheets().setAll("/io/bitsquare/gui/bitsquare.css", "/io/bitsquare/gui/images.css", "/io/bitsquare/gui/CandleStickChart.css");
// configure the system tray
SystemTray.create(primaryStage, shutDownHandler);
primaryStage.setOnCloseRequest(event -> {
event.consume();
stop();
});
scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
if (new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.W, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
stop();
} else if (new KeyCodeCombination(KeyCode.Q, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.Q, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
stop();
} else if (new KeyCodeCombination(KeyCode.E, KeyCombination.SHORTCUT_DOWN).match(keyEvent) || new KeyCodeCombination(KeyCode.E, KeyCombination.CONTROL_DOWN).match(keyEvent)) {
showEmptyWalletPopup();
} else if (new KeyCodeCombination(KeyCode.M, KeyCombination.ALT_DOWN).match(keyEvent)) {
showSendAlertMessagePopup();
} else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
showFilterPopup();
} else if (new KeyCodeCombination(KeyCode.F, KeyCombination.ALT_DOWN).match(keyEvent)) {
showFPSWindow();
} else if (new KeyCodeCombination(KeyCode.J, KeyCombination.ALT_DOWN).match(keyEvent)) {
WalletService walletService = injector.getInstance(WalletService.class);
if (walletService.getWallet() != null)
new ShowWalletDataWindow(walletService).information("Wallet raw data").show();
else
new Popup<>().warning("The wallet is not initialized yet").show();
} else if (new KeyCodeCombination(KeyCode.G, KeyCombination.ALT_DOWN).match(keyEvent)) {
TradeWalletService tradeWalletService = injector.getInstance(TradeWalletService.class);
WalletService walletService = injector.getInstance(WalletService.class);
if (walletService.getWallet() != null)
new SpendFromDepositTxWindow(tradeWalletService).information("Emergency wallet tool").show();
else
new Popup<>().warning("The wallet is not initialized yet").show();
} else if (DevFlags.DEV_MODE && new KeyCodeCombination(KeyCode.D, KeyCombination.SHORTCUT_DOWN).match(keyEvent)) {
showDebugWindow();
}
});
// configure the primary stage
primaryStage.setTitle(env.getRequiredProperty(APP_NAME_KEY));
primaryStage.setScene(scene);
// 1190
primaryStage.setMinWidth(1000);
primaryStage.setMinHeight(620);
// on windows the title icon is also used as task bar icon in a larger size
// on Linux no title icon is supported but also a large task bar icon is derived from that title icon
String iconPath;
if (Utilities.isOSX())
iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png";
else if (Utilities.isWindows())
iconPath = "/images/task_bar_icon_windows.png";
else
iconPath = "/images/task_bar_icon_linux.png";
primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath)));
// make the UI visible
primaryStage.show();
if (!Utilities.isCorrectOSArchitecture()) {
String osArchitecture = Utilities.getOSArchitecture();
// We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
// Needs at least more testing on different machines...
new Popup<>().warning("You probably have the wrong Bitsquare version for this computer.\n" + "Your computer's architecture is: " + osArchitecture + ".\n" + "The Bitsquare binary you installed is: " + Utilities.getJVMArchitecture() + ".\n" + "Please shut down and re-install the correct version (" + osArchitecture + ").").show();
}
UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN, TimeUnit.MINUTES);
} catch (Throwable throwable) {
showErrorPopup(throwable, false);
}
}
use of javafx.application.Platform in project jvarkit by lindenb.
the class BamStage method createReadGroupPane.
private Tab createReadGroupPane(final SAMFileHeader header) {
final TableView<SAMReadGroupRecord> table = new TableView<>(header == null ? FXCollections.observableArrayList() : FXCollections.observableArrayList(header.getReadGroups()));
table.getColumns().add(makeColumn("ID", G -> G.getId()));
table.getColumns().add(makeColumn("Sample", G -> G.getSample()));
table.getColumns().add(makeColumn("Center", G -> G.getSequencingCenter()));
table.getColumns().add(makeColumn("Platform", G -> G.getPlatform()));
table.getColumns().add(makeColumn("PlatformModel", G -> G.getPlatformModel()));
table.getColumns().add(makeColumn("PlatformUnit", G -> G.getPlatformUnit()));
table.getColumns().add(makeColumn("MedianInsertSize", G -> G.getPredictedMedianInsertSize()));
table.getColumns().add(makeColumn("Desc", G -> G.getDescription()));
table.getColumns().add(makeColumn("PU", G -> G.getPlatformUnit()));
table.getColumns().add(makeColumn("Lib", G -> G.getLibrary()));
table.getColumns().add(makeColumn("Run-Date", G -> G.getRunDate()));
final Tab tab = new Tab("ReadGroups", table);
tab.setClosable(false);
table.setPlaceholder(new Label("No BAM read-greoup."));
return tab;
}
use of javafx.application.Platform in project dwoss by gg-net.
the class FileChooserBuilder method open.
/**
* Opens a file chooser and returns the selected file or empty.
*
* @return the selected file or empty.
*/
// TODO: This is the only time we us a javafx component in all modes. It should be considered, that in the swing mode, the JFileChoser should be used.
public Result<File> open() {
SwingCore.ensurePlatformIsRunning();
return new Result<>(CompletableFuture.supplyAsync(() -> {
FileChooser fileChooser = new FileChooser();
if (title == null)
fileChooser.setTitle("Open File");
else
fileChooser.setTitle(title);
File result = fileChooser.showOpenDialog(null);
if (result == null)
throw new UiWorkflowBreak(NULL_RESULT);
return result;
}, Platform::runLater).thenApplyAsync(r -> r, // the last Apply is for the thread change only
UiCore.getExecutor()));
}
Aggregations