Search in sources :

Example 6 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class Main method handleMouseClicked.

private static void handleMouseClicked(MouseEvent event) {
    tree.setContextMenu(null);
    TreeItem<GuiLocation> selectedItem = tree.getSelectionModel().getSelectedItem();
    if (selectedItem == null || selectedItem.getValue() == null) {
        return;
    }
    if (selectedItem.getValue().getType() == TYPE.ROOT) {
        final ContextMenu contextMenu = new ContextMenu();
        if (userService.getLocations().size() < MAX_INSTALLATIONS) {
            contextMenu.getItems().add(createMenuWithAction(null, "Add new location", Type.ADD_LOCATION, selectedItem.getValue()));
        }
        contextMenu.getItems().add(createMenuWithAction(null, "Locally synced directory", Type.ADD_PRIVATE_DIR, null));
        contextMenu.getItems().add(createMenuWithAction(null, "Install and update all", Type.INSTALL_AND_UPDATE_ALL_LOCATIONS, selectedItem.getValue()));
        contextMenu.getItems().add(createMenuWithAction(null, "Update all", Type.UPDATE_ALL_LOCATIONS, selectedItem.getValue()));
        contextMenu.getItems().add(createMenuWithAction(null, "Refresh view", Type.REFRESH_VIEW, selectedItem.getValue()));
        contextMenu.getItems().add(createMenuWithAction(null, "Reset all views", Type.RESET_ALL_VIEWS, selectedItem.getValue()));
        tree.setContextMenu(contextMenu);
        return;
    }
    if (selectedItem.getValue().getType() == TYPE.INSTALLATION_ROOT) {
        GuiLocation selectedInstallation = selectedItem.getValue();
        if (userService.isInstallationExisting(selectedInstallation.getId())) {
            if (event.getButton() == MouseButton.SECONDARY || event.isControlDown()) {
                final ContextMenu contextMenu = new ContextMenu();
                contextMenu.getItems().add(createMenuWithAction(null, "Update and install all", Type.INSTALLUPDATE_ALL, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Update all", Type.UPDATE_ALL, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Housekeep", Type.HOUSEKEEP, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Set as primary", Type.SET_AS_PRIMARY, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Reset view", Type.RESET_VIEW, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Open folder", Type.OPEN_LOCATION, selectedInstallation));
                contextMenu.getItems().add(createMenuWithAction(null, "Remove location", Type.REMOVE_LOCATION, selectedInstallation));
                tree.setContextMenu(contextMenu);
            } else if (event.getClickCount() == 2) {
                String key = resolveInstallationExpandedKey(selectedInstallation.getId());
                if (localDbService.hasLocalDBSetting(key)) {
                    localDbService.addLocalBooleanDBSetting(key, !localDbService.getBooleanLocalDBSetting(key));
                } else {
                    localDbService.addLocalBooleanDBSetting(key, Boolean.FALSE);
                }
            }
        } else {
            final ContextMenu contextMenu = new ContextMenu();
            contextMenu.getItems().add(createMenuWithAction(null, "Remove location", Type.REMOVE_LOCATION, selectedInstallation));
            tree.setContextMenu(contextMenu);
        }
        return;
    }
    if (selectedItem.getValue().getType() == TYPE.LEAF) {
        if (event.getClickCount() == 2) {
            GuiLocation selectedInstallation = selectedItem.getValue();
            String key = resolveLeafInInstallationExpandedKey(selectedInstallation);
            if (localDbService.hasLocalDBSetting(key)) {
                localDbService.addLocalBooleanDBSetting(key, !localDbService.getBooleanLocalDBSetting(key));
            } else {
                localDbService.addLocalBooleanDBSetting(key, Boolean.FALSE);
            }
        } else if (event.getButton() == MouseButton.SECONDARY || event.isControlDown()) {
            ContextMenu contextMenu = getContextMenu();
            contextMenu.getItems().add(createMenuWithAction(null, "Open folder", Type.OPEN_LEAF_LOCATION, selectedItem.getValue()));
        }
        return;
    }
    if (selectedItem.getValue().getType() == TYPE.INSTALLATION) {
        if (event.getClickCount() == 2) {
            tree.getSelectionModel().clearSelection();
            GuiUtils.showDialog("searchMain.fxml", "Search assemblydb", selectedItem.getValue().getArtifact());
            return;
        } else {
            try {
                if (event.getButton() == MouseButton.SECONDARY || event.isControlDown()) {
                    if (tree.getContextMenu() == null) {
                        tree.setContextMenu(new ContextMenu());
                    }
                    ContextMenu contextMenu = tree.getContextMenu();
                    contextMenu.getItems().clear();
                    GuiLocation selectedInstallation = selectedItem.getValue();
                    List<ActionAndIdHolder> actions = new ArrayList<>();
                    Artifact clickedEntry = selectedInstallation.getArtifact();
                    boolean installed = artifactsService.isInstalled(userService.getLocation(selectedInstallation.getId()).toLocationAndInstallation(), clickedEntry);
                    if (!installed) {
                        actions.add(new ActionAndIdHolder(clickedEntry, Type.INSTALL, selectedInstallation));
                    } else if (artifactsService.needsUpdate(userService.getLocation(selectedInstallation.getId()).toLocationAndInstallation(), clickedEntry)) {
                        actions.add(new ActionAndIdHolder(clickedEntry, Type.UPDATE, selectedInstallation));
                    }
                    boolean containsInstall = actions.stream().filter(item -> item.getType() == Type.INSTALL).findFirst().isPresent();
                    boolean containsUpdate = actions.stream().filter(item -> item.getType() == Type.UPDATE).findFirst().isPresent();
                    if (Support.isRemoteArtifact(clickedEntry) || (Support.isLocalArtifact(clickedEntry) && artifactsService.isPrivateDirAvailable())) {
                        if (containsInstall) {
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Install", Type.INSTALL, selectedInstallation));
                        } else if (containsUpdate) {
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Update", Type.INSTALL, selectedInstallation));
                        }
                    }
                    contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Info", Type.INFO, selectedInstallation));
                    if (installed) {
                        contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Open folder", Type.OPEN, selectedInstallation));
                    }
                    if (Support.isRemoteArtifact(clickedEntry) && artifactsService.isPrivateDirAvailable()) {
                        if (!installed) {
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Hide", Type.HIDE, selectedInstallation));
                        } else {
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Uninstall", Type.UNINSTALL, selectedInstallation));
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Hide & uninstall", Type.HIDE, selectedInstallation));
                        }
                    }
                    if (Support.isRemoteArtifact(clickedEntry) && userService.isPremium()) {
                        contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Search", Type.SEARCH, selectedInstallation));
                    }
                    if (clickedEntry.isMarkedForUpdate()) {
                        if (!clickedEntry.isUpdating()) {
                            contextMenu.getItems().add(createMenuWithAction(clickedEntry, "Cancel", Type.CANCEL_UPDATE, selectedInstallation));
                        }
                    }
                    if (installed && Support.isRemoteArtifact(clickedEntry)) {
                        String baseLocation = Support.appendPathIfMissing(userService.getLocation(selectedInstallation.getId()).toLocationAndInstallation().getLocation()) + clickedEntry.getAbsoluteInstallationPath();
                        File releaseNoteFile = new File(Support.appendPathIfMissing(baseLocation + "/releaselog.json"));
                        ReturningTask<Void> showExtraMenuTask = () -> {
                            if (releaseNoteFile.exists()) {
                                Platform.runLater(() -> {
                                    contextMenu.getItems().add(createMenuWithAction(clickedEntry, "View new entries", Type.SHOW_RELEASES, selectedInstallation, baseLocation));
                                });
                            }
                            return null;
                        };
                        ExecutorUtil.executeAsyncWithRetry(showExtraMenuTask);
                    }
                } else {
                    tree.getSelectionModel().clearSelection();
                }
            } catch (Exception e) {
                LOGGER.error("Exception in mouseclick", e);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) GuiLocation(se.light.assembly64.model.GuiLocation) ContextMenu(javafx.scene.control.ContextMenu) Artifact(se.light.assembly64.model.Artifact) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 7 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class Main method viewPrimary.

public void viewPrimary() {
    primaryStage = new Stage();
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

        public void handle(WindowEvent we) {
            System.exit(1);
        }
    });
    if (!userService.isPremium()) {
        userService.deleteExcludesFromLocalDbQuiet();
    }
    // Setting the saved windowsize
    if (localDbService.hasLocalDBSetting("screenHeight")) {
        primaryStage.setHeight(Double.valueOf(localDbService.getLocalDBSetting("screenHeight")));
    }
    if (localDbService.hasLocalDBSetting("screenWidth")) {
        primaryStage.setWidth(Double.valueOf(localDbService.getLocalDBSetting("screenWidth")));
    }
    GuiUtils.attachIconToStage(primaryStage);
    LOGGER.info("Assembly64 v." + version + " is starting up...");
    try {
        if (userService.isPremium()) {
            primaryStage.setTitle("Assembly64 - Hero edition");
        } else {
            primaryStage.setTitle("Assembly64 - Free edition");
        }
        // menuBar = new MenuBar();
        Menu menuFile = new Menu("Assembly64");
        Menu menuLogs = new Menu("Logs");
        Menu menuMisc = new Menu("Misc");
        // A64
        MenuItem openFile = new MenuItem("Open D64/D71/D81/TAP/G64/T64/BIN/CRT/SID");
        menuFile.getItems().add(openFile);
        MenuItem settingsItem = new MenuItem("Preferences");
        menuFile.getItems().add(settingsItem);
        MenuItem exitItem = new MenuItem("Exit");
        menuFile.getItems().add(exitItem);
        // logsmenu
        MenuItem viewLogItem = new MenuItem("Systemlog");
        menuLogs.getItems().add(viewLogItem);
        MenuItem changelog = new MenuItem("Changelog");
        menuLogs.getItems().add(changelog);
        MenuItem instructions = new MenuItem("Instructions");
        menuMisc.getItems().add(instructions);
        // misc
        MenuItem backers = new MenuItem("Backers");
        menuMisc.getItems().add(backers);
        MenuItem donations = new MenuItem("Donations");
        menuMisc.getItems().add(donations);
        MenuItem feedbackItem = new MenuItem("Feedback & Feature requests");
        menuMisc.getItems().add(feedbackItem);
        MenuItem aboutItem = new MenuItem("About");
        menuMisc.getItems().add(aboutItem);
        menuBar = new MenuBar();
        menuBar.getMenus().addAll(menuFile, menuLogs, menuMisc);
        feedbackItem.setOnAction((item) -> {
            GuiUtils.showDialogBare("feedback.fxml", "Submit feedback");
        });
        exitItem.setOnAction((item) -> {
            System.exit(1);
        });
        openFile.setOnAction((item) -> {
            Analytics.sendEvent("application_click", "open_file");
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("Open Resource File");
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All", "*.*"), new FileChooser.ExtensionFilter("PRG", "*.d64"), new FileChooser.ExtensionFilter("D64", "*.d64"), new FileChooser.ExtensionFilter("D71", "*.d71"), new FileChooser.ExtensionFilter("T64", "*.t64"), new FileChooser.ExtensionFilter("TAP", "*.d71"), new FileChooser.ExtensionFilter("G64", "*.g64"), new FileChooser.ExtensionFilter("G64", "*.tap"), new FileChooser.ExtensionFilter("D71", "*.d71"), new FileChooser.ExtensionFilter("D81", "*.d81"), new FileChooser.ExtensionFilter("BIN", "*.bin"), new FileChooser.ExtensionFilter("CRT", "*.crt"));
            launchViceOrImageView(fileChooser.showOpenDialog(primaryStage));
        });
        settingsItem.setOnAction((item) -> {
            try {
                GuiUtils.showDialogBare("mainSettings.fxml", "Settings", new Object[] {});
            } catch (Exception e) {
                LOGGER.error("Unable to view settings", e);
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view settings").showAndWait();
            }
        });
        viewLogItem.setOnAction((item) -> {
            try {
                Analytics.sendEvent("application_click", "view_logs");
                GuiUtils.showDialogBare("viewFileFromDisk.fxml", "View log", new File(LogConfig.getLogFileAsString()), "Systemlog");
            } catch (Exception e) {
                LOGGER.error("Unable to view logs", e);
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view logs").showAndWait();
            }
        });
        donations.setOnAction((i) -> {
            String linebreak = System.getProperty("line.separator");
            String donStr = userService.getDonations().stream().map(item -> item.dateFormatted() + linebreak + item.getName()).collect(Collectors.joining(linebreak + linebreak));
            GuiUtils.showDialogBare("viewFileFromDisk.fxml", "Donations by heroes", donStr, "Donationshistory");
        });
        backers.setOnAction((item) -> {
            try {
                String[] bck = userService.getBackers();
                int start = ThreadLocalRandom.current().nextInt(0, bck.length - 1);
                StringBuffer names = new StringBuffer();
                for (int i = 0; i < bck.length - 1; i++) {
                    int pos = (start + i) % (bck.length - 1);
                    names.append(bck[pos] + "\n");
                }
                Analytics.sendEvent("application_click", "view_backers");
                GuiUtils.showDialogBare("viewFileFromDisk.fxml", "Backing heroes of Assembly64", names.toString(), "List of backers");
            } catch (Exception e) {
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view backers").showAndWait();
                LOGGER.error("Unable to view logs", e);
            }
        });
        instructions.setOnAction((item) -> {
            try {
                Analytics.sendEvent("application_click", "view_instructions");
                GuiUtils.showDialogBare("viewFileFromDisk.fxml", "This is the way", getClass().getResourceAsStream("instructions.txt"), "Instructions");
            } catch (Exception e) {
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view instructions").showAndWait();
                LOGGER.error("Unable to view instructions", e);
            }
        });
        changelog.setOnAction((item) -> {
            Analytics.sendEvent("application_click", "view_changelog");
            try {
                GuiUtils.showDialogBare("viewFileFromDisk.fxml", "Haxxing haxxing haxxing", getClass().getResourceAsStream("changelog.txt"), "Changelog");
            } catch (Exception e) {
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view changelog").showAndWait();
                LOGGER.error("Unable to view logs", e);
            }
        });
        aboutItem.setOnAction((item) -> {
            try {
                Analytics.sendEvent("application_click", "view_about");
                showAboutDia();
            } catch (Exception e) {
                LOGGER.error("Unable to view about", e);
                GenericMessageDialogController.withErrorProps("Oops", "Unable to view about").showAndWait();
            }
        });
        topContainer.getChildren().addAll(menuBar);
        topContainer.setStyle("-fx-background: #222222;");
        Scene scene = new Scene(topContainer, 300, maxHeight);
        scene.getStylesheets().add(getClass().getResource("css-psidplayer.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setResizable(true);
        GlobalRepoService.getInstance().put("primarystage", primaryStage);
        if (!localDbService.getBooleanLocalDBSetting(Support.SIDIFYASDEFAULT) || userService.isFreemium()) {
            primaryStage.show();
        } else {
            ReturningTask<Void> task = () -> {
                Platform.runLater(() -> {
                    primaryStage.hide();
                    executeIfPremium((Runnable) -> {
                        GuiUtils.showDialog("sidifyMain.fxml", false, "Sidify Heroium", NullWindowOwner.of(), new Object[] { Boolean.TRUE });
                    }, "open_sidify_default");
                });
                return null;
            };
            ExecutorUtil.executeAsyncWithRetry(task);
        }
        scene.heightProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {
                tree.setMinHeight(topContainer.getHeight() - menuBar.getHeight());
                setMagnifierAndSidify();
            }
        });
        scene.widthProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {
                tree.setMinWidth(treeAndComponents.getWidth());
                setMagnifierAndSidify();
            }
        });
        // bootstrapping
        GlobalRepoService.getInstance().put("rootscene", scene);
        for (WorkLocation location : userService.getExistingLocations()) {
            artifactsService.assertCorrectTargetFolderNames(location.asFile());
        }
        setupTree();
        sidifyView.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            Analytics.sendEvent("application_click", "open_sidify");
            executeIfPremium((Runnable) -> {
                // Platform.runLater(() -> primaryStage.hide());
                GuiUtils.showDialog("sidifyMain.fxml", false, "Sidify Heroium", NullWindowOwner.of(), new Object[] { Boolean.FALSE });
            }, "open_sidify");
        });
        downloadLatestDbView.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            executeIfPremium((Runnable) -> {
                if (userService.getPrimaryInstallation().exists()) {
                    InstallationService.getInstance().downloadLatestFromDatabase();
                } else {
                    GenericMessageDialogController.withErrorProps("Ooops..", "No valid downloadlocation is present").showAndWait();
                }
            }, "download_latest");
        });
        userService.locationsAssert();
        if (!localDbService.hasLocalDBSetting(Support.LAST_VERSION)) {
            localDbService.addLocalDBSetting(Support.LAST_VERSION, "0.00");
        }
        if (localDbService.getBooleanLocalDBSetting(Support.SHOWDIA_ON_STARTUP) || !version.equals(localDbService.getLocalDBSetting(Support.LAST_VERSION))) {
            ReturningTask<Void> task = () -> {
                Thread.sleep(300);
                Platform.runLater(() -> showAboutDia());
                return null;
            };
            ExecutorUtil.executeAsyncWithRetry(task);
        }
        ReturningTask<Void> deleteTmpTask = () -> {
            LocalStorageUtil.deleteOldFiles(PathService.getInstance().getTmpFolderAsString(), Support.ONE_WEEK_IN_MILLIS);
            LocalStorageUtil.deleteOldFiles(PathService.getInstance().getDownloadTmpFolderAsString(), Support.ONE_MONTH_IN_MILLIS);
            return null;
        };
        ExecutorUtil.executeAsyncWithRetry(deleteTmpTask);
        // migrate db to .db
        for (WorkLocation location : userService.getLocations()) {
            PathService.getInstance().renameDbFolder(location);
        }
        if (userService.getExistingLocations().size() == 0 && localDbService.hasLocalDBSetting(WORKDIR)) {
            addLocation(new File(localDbService.getLocalDBSetting(WORKDIR)));
            localDbService.deleteLocalDBSetting(WORKDIR);
        }
        if (userService.isPremium() && !localDbService.getBooleanLocalDBSetting(Support.SIDIFYASDEFAULT)) {
            ExecutorUtil.executeAsync(() -> {
                Platform.runLater(() -> {
                    examineContent();
                });
            });
        }
        refreshTree();
    } catch (Exception e) {
        LOGGER.error("Unable to delete cached items", e);
        GenericMessageDialogController.withErrorProps("OOoops", "Unable to startup properly").showAndWait();
    }
}
Also used : EventHandler(javafx.event.EventHandler) StageStyle(javafx.stage.StageStyle) RandomAccessFile(java.io.RandomAccessFile) Scheduler(se.light.assembly64.Scheduler) TYPE(se.light.assembly64.model.GuiLocation.TYPE) LoggerFactory(org.slf4j.LoggerFactory) PathService(se.light.assembly64.service.PathService) VBox(javafx.scene.layout.VBox) StringUtils(org.apache.commons.lang3.StringUtils) FileLock(java.nio.channels.FileLock) Application(javafx.application.Application) ArtifactType(se.light.assembly64.model.ArtifactType) LogConfig(se.light.assembly64.LogConfig) ContextMenu(javafx.scene.control.ContextMenu) Type(se.light.assembly64.Support.Type) WindowEvent(javafx.stage.WindowEvent) WorkLocation(se.light.assembly64.model.WorkLocation) Pane(javafx.scene.layout.Pane) Rectangle2D(javafx.geometry.Rectangle2D) MenuItem(javafx.scene.control.MenuItem) ButtonType(se.light.assembly64.fx.GenericMessageDialogController.ButtonType) Set(java.util.Set) Screen(javafx.stage.Screen) Artifact(se.light.assembly64.model.Artifact) LocalStorageUtil(se.light.assembly64.util.LocalStorageUtil) Collectors(java.util.stream.Collectors) TreeView(javafx.scene.control.TreeView) UserService(se.light.assembly64.service.UserService) Platform(javafx.application.Platform) Duration(javafx.util.Duration) List(java.util.List) PlatformInfoService(se.light.assembly64.service.PlatformInfoService) Optional(java.util.Optional) InstallationService(se.light.assembly64.service.InstallationService) Autoupgrade(se.light.assembly64.Autoupgrade) ReturningTask(se.light.assembly64.model.ReturningTask) Scene(javafx.scene.Scene) MouseButton(javafx.scene.input.MouseButton) TreeItem(javafx.scene.control.TreeItem) GuiLocation(se.light.assembly64.model.GuiLocation) MouseEvent(javafx.scene.input.MouseEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GlobalRepoService(se.light.assembly64.service.GlobalRepoService) GenericMessageDialogController.heroesOnlyFeatureDialog(se.light.assembly64.fx.GenericMessageDialogController.heroesOnlyFeatureDialog) ArrayList(java.util.ArrayList) LatestInstalledItemInfo(se.light.assembly64.model.LatestInstalledItemInfo) ViceService(se.light.assembly64.service.ViceService) UpgradeOptions(se.light.assembly64.Support.UpgradeOptions) FadeTransition(javafx.animation.FadeTransition) GuiUtils(se.light.assembly64.util.GuiUtils) Support(se.light.assembly64.Support) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Support.resolveInstallationExpandedKey(se.light.assembly64.Support.resolveInstallationExpandedKey) DirectoryChooser(javafx.stage.DirectoryChooser) Color(javafx.scene.paint.Color) Analytics(se.light.assembly64.Analytics) Logger(org.slf4j.Logger) MenuBar(javafx.scene.control.MenuBar) ExecutorUtil(se.light.assembly64.util.ExecutorUtil) FileUtils(org.apache.commons.io.FileUtils) ArtifactsService(se.light.assembly64.service.ArtifactsService) File(java.io.File) Menu(javafx.scene.control.Menu) Consumer(java.util.function.Consumer) FileChooser(javafx.stage.FileChooser) ActionEvent(javafx.event.ActionEvent) SelectionMode(javafx.scene.control.SelectionMode) Stage(javafx.stage.Stage) PlatformInfo(se.light.assembly64.model.PlatformInfo) ImageView(javafx.scene.image.ImageView) LocalDBService(se.light.assembly64.service.LocalDBService) ObservableValue(javafx.beans.value.ObservableValue) ChangeListener(javafx.beans.value.ChangeListener) Support.resolveLeafInInstallationExpandedKey(se.light.assembly64.Support.resolveLeafInInstallationExpandedKey) Image(javafx.scene.image.Image) FileChannel(java.nio.channels.FileChannel) Collections(java.util.Collections) LocationAndInstallationStatus(se.light.assembly64.model.LocationAndInstallationStatus) WorkLocation(se.light.assembly64.model.WorkLocation) MenuBar(javafx.scene.control.MenuBar) MenuItem(javafx.scene.control.MenuItem) Scene(javafx.scene.Scene) WindowEvent(javafx.stage.WindowEvent) FileChooser(javafx.stage.FileChooser) Stage(javafx.stage.Stage) ContextMenu(javafx.scene.control.ContextMenu) Menu(javafx.scene.control.Menu) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 8 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class Main method start.

@Override
public void start(Stage splashStage) {
    GlobalRepoService.getInstance().put("main", this);
    try {
        PlatformInfo platformInfo = platformInfoService.getPlatformInfo(platformInfoService.getPlaformPrefix());
        if (platformInfo.isNewerAvailable(version)) {
            try {
                UpgradeController upgradeDialog = GuiUtils.noShowDialog("upgrade.fxml", true, true, "New version available", splashStage, platformInfo);
                upgradeDialog.getStage().showAndWait();
                UpgradeOptions upgradeChoice = upgradeDialog.getUpgradeChoice();
                if (upgradeChoice == UpgradeOptions.DOWNLOAD) {
                    this.getHostServices().showDocument("http://hackerswithstyle.ddns.net/assembly/download.html");
                    ReturningTask<Void> exitWithDelay = () -> {
                        try {
                            Thread.sleep(500);
                            System.exit(1);
                        } catch (Exception e) {
                        }
                        return null;
                    };
                    ExecutorUtil.executeAsyncWithRetry(exitWithDelay);
                } else if (upgradeChoice == UpgradeOptions.UPGRADE) {
                    Autoupgrade.getInstance().doUpgrade();
                    return;
                }
            } catch (Exception e) {
                LOGGER.info("Unable to startup", e);
            }
        }
    } catch (Exception e) {
        OfflineController offlineController = (OfflineController) GuiUtils.showDialogBare("assemblyOffline.fxml", "Ooops :-/", new Object[] {});
        if (offlineController.openSidify()) {
            GuiUtils.showDialog("sidifyMain.fxml", true, "Sidify Heroium", new Object[] { Boolean.FALSE });
            return;
        } else {
            System.exit(1);
        }
    }
    GuiUtils.showDialog("authLogin.fxml", "Login to Assembly", new Object[] {});
    List<String> inputParams = getParameters().getRaw();
    if (platformInfoService.isWin() && inputParams.size() == 1) {
        File f = new File(inputParams.get(0));
        if (f.exists()) {
            launchViceOrImageView(f);
            System.exit(1);
        }
    }
    final Rectangle2D bounds = Screen.getPrimary().getBounds();
    maxHeight = bounds.getHeight() - 150;
    if (maxHeight > 700) {
        maxHeight = 700;
    }
    try {
        // Utils.getInstance().assertFolders();
        if (isAppActive()) {
            GenericMessageDialogController.withErrorProps("Another instance of", "Assembly64 is already active!").withExitAfterOk().showAndWait();
        }
        if (localDbService.getLocalDB().containsKey("uid")) {
            Analytics.sendEvent("application", "startup_existing_user_" + platformInfoService.getPlaformPrefix());
        } else {
            Analytics.sendEvent("application", "startup_new_user_" + platformInfoService.getPlaformPrefix());
        }
        ImageView splash = new ImageView(new Image(getClass().getResourceAsStream("image-assemblysplash.png")));
        splashLayout = new VBox();
        splashLayout.getChildren().addAll(splash);
        Scene splashScene = new Scene(splashLayout, Color.TRANSPARENT);
        splashStage.setScene(splashScene);
        splashStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - SPLASH_WIDTH / 2);
        splashStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - SPLASH_HEIGHT / 2);
        splashStage.initStyle(StageStyle.TRANSPARENT);
        splashStage.setAlwaysOnTop(true);
        splashStage.show();
        ExecutorUtil.executeAsyncWithRetry(() -> {
            try {
                artifactsService.updateChecksumInPrivateFolder();
            } catch (Exception e) {
                LOGGER.error("Unable to update checksum", e);
            }
            return null;
        }, 5);
        ExecutorUtil.executeAsyncWithRetry(() -> {
            try {
                artifactsService.getArtifactsDb();
                refreshedArtifacts.set(true);
            } catch (Exception e) {
                LOGGER.error("Unable to get artifacts", e);
                Thread.sleep(1000);
                throw e;
            }
            return null;
        }, 5);
        ReturningTask<Void> continueTask = () -> {
            int retries = 0;
            while (retries < 5) {
                Thread.sleep(2000);
                if (refreshedArtifacts.get() == Boolean.TRUE) {
                    LOGGER.info("Got artifacts from server, ok to start");
                    break;
                }
                retries++;
            }
            if (refreshedArtifacts.get() == Boolean.FALSE) {
                Platform.runLater(() -> {
                    splashStage.close();
                });
                Platform.runLater(() -> {
                    GuiUtils.showDialog("assemblyOffline.fxml", "Ooops :-/", new Object[] {});
                    try {
                        Thread.sleep(10000);
                    } catch (Exception e) {
                    // TODO Auto-generated catch block
                    }
                });
            } else {
                FadeTransition fadeSplash2 = new FadeTransition(Duration.seconds(0.7), splashLayout);
                fadeSplash2.setFromValue(1.0);
                fadeSplash2.setToValue(0.0);
                fadeSplash2.setOnFinished(actionEvent -> {
                    splashStage.hide();
                    viewPrimary();
                });
                fadeSplash2.play();
            // }
            }
            return null;
        };
        ExecutorUtil.executeAsyncWithRetry(continueTask);
    } catch (Exception e) {
        GenericMessageDialogController.withErrorProps("Error", "Error when starting Assembly").withExitAfterOk().showAndWait();
    }
}
Also used : EventHandler(javafx.event.EventHandler) StageStyle(javafx.stage.StageStyle) RandomAccessFile(java.io.RandomAccessFile) Scheduler(se.light.assembly64.Scheduler) TYPE(se.light.assembly64.model.GuiLocation.TYPE) LoggerFactory(org.slf4j.LoggerFactory) PathService(se.light.assembly64.service.PathService) VBox(javafx.scene.layout.VBox) StringUtils(org.apache.commons.lang3.StringUtils) FileLock(java.nio.channels.FileLock) Application(javafx.application.Application) ArtifactType(se.light.assembly64.model.ArtifactType) LogConfig(se.light.assembly64.LogConfig) ContextMenu(javafx.scene.control.ContextMenu) Type(se.light.assembly64.Support.Type) WindowEvent(javafx.stage.WindowEvent) WorkLocation(se.light.assembly64.model.WorkLocation) Pane(javafx.scene.layout.Pane) Rectangle2D(javafx.geometry.Rectangle2D) MenuItem(javafx.scene.control.MenuItem) ButtonType(se.light.assembly64.fx.GenericMessageDialogController.ButtonType) Set(java.util.Set) Screen(javafx.stage.Screen) Artifact(se.light.assembly64.model.Artifact) LocalStorageUtil(se.light.assembly64.util.LocalStorageUtil) Collectors(java.util.stream.Collectors) TreeView(javafx.scene.control.TreeView) UserService(se.light.assembly64.service.UserService) Platform(javafx.application.Platform) Duration(javafx.util.Duration) List(java.util.List) PlatformInfoService(se.light.assembly64.service.PlatformInfoService) Optional(java.util.Optional) InstallationService(se.light.assembly64.service.InstallationService) Autoupgrade(se.light.assembly64.Autoupgrade) ReturningTask(se.light.assembly64.model.ReturningTask) Scene(javafx.scene.Scene) MouseButton(javafx.scene.input.MouseButton) TreeItem(javafx.scene.control.TreeItem) GuiLocation(se.light.assembly64.model.GuiLocation) MouseEvent(javafx.scene.input.MouseEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GlobalRepoService(se.light.assembly64.service.GlobalRepoService) GenericMessageDialogController.heroesOnlyFeatureDialog(se.light.assembly64.fx.GenericMessageDialogController.heroesOnlyFeatureDialog) ArrayList(java.util.ArrayList) LatestInstalledItemInfo(se.light.assembly64.model.LatestInstalledItemInfo) ViceService(se.light.assembly64.service.ViceService) UpgradeOptions(se.light.assembly64.Support.UpgradeOptions) FadeTransition(javafx.animation.FadeTransition) GuiUtils(se.light.assembly64.util.GuiUtils) Support(se.light.assembly64.Support) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Support.resolveInstallationExpandedKey(se.light.assembly64.Support.resolveInstallationExpandedKey) DirectoryChooser(javafx.stage.DirectoryChooser) Color(javafx.scene.paint.Color) Analytics(se.light.assembly64.Analytics) Logger(org.slf4j.Logger) MenuBar(javafx.scene.control.MenuBar) ExecutorUtil(se.light.assembly64.util.ExecutorUtil) FileUtils(org.apache.commons.io.FileUtils) ArtifactsService(se.light.assembly64.service.ArtifactsService) File(java.io.File) Menu(javafx.scene.control.Menu) Consumer(java.util.function.Consumer) FileChooser(javafx.stage.FileChooser) ActionEvent(javafx.event.ActionEvent) SelectionMode(javafx.scene.control.SelectionMode) Stage(javafx.stage.Stage) PlatformInfo(se.light.assembly64.model.PlatformInfo) ImageView(javafx.scene.image.ImageView) LocalDBService(se.light.assembly64.service.LocalDBService) ObservableValue(javafx.beans.value.ObservableValue) ChangeListener(javafx.beans.value.ChangeListener) Support.resolveLeafInInstallationExpandedKey(se.light.assembly64.Support.resolveLeafInInstallationExpandedKey) Image(javafx.scene.image.Image) FileChannel(java.nio.channels.FileChannel) Collections(java.util.Collections) LocationAndInstallationStatus(se.light.assembly64.model.LocationAndInstallationStatus) FadeTransition(javafx.animation.FadeTransition) Rectangle2D(javafx.geometry.Rectangle2D) Image(javafx.scene.image.Image) Scene(javafx.scene.Scene) PlatformInfo(se.light.assembly64.model.PlatformInfo) UpgradeOptions(se.light.assembly64.Support.UpgradeOptions) ImageView(javafx.scene.image.ImageView) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) VBox(javafx.scene.layout.VBox)

Example 9 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class SearchController method downloadFiles.

private void downloadFiles(List<SearchResultItem> selectedItems, String downloadPath) {
    if (selectedItems.size() > MAX_DOWNLOADSPAN) {
        GenericMessageDialogController.withErrorProps("Ooops...", "Please narrow downloadspan").showAndWait();
        return;
    }
    CancelableTask cancelTask = CancelableTask.of();
    ProgressDBController controller = GuiUtils.showDialogOwnerNoWait("progressBarDbUpdate.fxml", "Progress", true, getStage(), new Object[] { selectedItems.size(), cancelTask, downloadPath, "Files were installed to " + downloadPath });
    ReturningTask<Void> task = () -> {
        int failureCtr = 0;
        for (SearchResultItem item : selectedItems) {
            if (cancelTask.isCancelled()) {
                break;
            }
            controller.setProgressLabel("Installing " + item.getName());
            controller.increaseProgress();
            boolean res = downloadEntryAndSubItems(item, downloadPath);
            if (!res) {
                failureCtr++;
            }
        }
        if (failureCtr == 0) {
            controller.progressDone();
        } else {
            controller.progressDone(failureCtr + " of " + selectedItems.size() + " could not be installed to " + downloadPath);
        }
        return null;
    };
    ExecutorUtil.executeAsyncWithRetry(task, 3);
}
Also used : SearchResultItem(se.light.assembly64.model.SearchResultItem) CancelableTask(se.light.assembly64.model.CancelableTask)

Example 10 with ReturningTask

use of se.light.assembly64.model.ReturningTask in project assembly64fx by freabemania.

the class InstallationService method housekeep.

public void housekeep(File base) {
    GenericMessageDialogController.withInfoProps("Scan was started", "Scanning " + base.getAbsolutePath()).show();
    ReturningTask<Void> task = () -> {
        final AtomicInteger emptyDirs = new AtomicInteger();
        final AtomicInteger emptyFiles = new AtomicInteger();
        for (Artifact entry : artifactsService.getArtifactsDb()) {
            if (artifactsService.isInstalled(base, entry)) {
                boolean emptyDirFound = true;
                while (emptyDirFound) {
                    emptyDirFound = false;
                    for (File f : FileUtils.listFilesAndDirs(LocalStorageUtil.getSubdirOrFile(base, entry), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) {
                        if (!f.isDirectory()) {
                            if (f.length() == 0) {
                                emptyFiles.incrementAndGet();
                                FileUtils.deleteQuietly(f);
                                emptyDirFound = true;
                            }
                        } else {
                            if (f.list().length == 0 || f.getName().toUpperCase().equals("__MACOSX")) {
                                emptyDirs.incrementAndGet();
                                FileUtils.deleteQuietly(f);
                                emptyDirFound = true;
                            }
                        }
                    }
                }
            }
        }
        GenericMessageDialogController.withInfoProps("Housekeeping finished", "Removed " + emptyFiles.get() + " empty files and " + emptyDirs.get() + " dirs", true).showAndWait();
        return null;
    };
    ExecutorUtil.executeAsyncWithRetry(task, 3);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) File(java.io.File) Support.isRemoteArtifact(se.light.assembly64.Support.isRemoteArtifact) Artifact(se.light.assembly64.model.Artifact)

Aggregations

File (java.io.File)7 Image (javafx.scene.image.Image)5 ReturningTask (se.light.assembly64.model.ReturningTask)5 ArrayList (java.util.ArrayList)4 Artifact (se.light.assembly64.model.Artifact)4 RandomAccessFile (java.io.RandomAccessFile)3 List (java.util.List)3 Set (java.util.Set)3 FadeTransition (javafx.animation.FadeTransition)3 ActionEvent (javafx.event.ActionEvent)3 EventHandler (javafx.event.EventHandler)3 ContextMenu (javafx.scene.control.ContextMenu)3 MouseEvent (javafx.scene.input.MouseEvent)3 ContentEntry (se.light.assembly64.model.ContentEntry)3 GuiLocation (se.light.assembly64.model.GuiLocation)3 PlatformInfoService (se.light.assembly64.service.PlatformInfoService)3 FileChannel (java.nio.channels.FileChannel)2 FileLock (java.nio.channels.FileLock)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2