Search in sources :

Example 66 with ObservableValue

use of javafx.beans.value.ObservableValue in project Board-Instrumentation-Framework by intel.

the class SteelSimpleGaugeWidget method Create.

@Override
public boolean Create(GridPane pane, DataManager dataMgr) {
    SetParent(pane);
    if (false == SetupGauge()) {
        return false;
    }
    _Gauge.setValue(_InitialValue);
    ConfigureDimentions();
    ConfigureAlignment();
    SetupPeekaboo(dataMgr);
    pane.add(_Gauge, getColumn(), getRow(), getColumnSpan(), getRowSpan());
    dataMgr.AddListener(getMinionID(), getNamespace(), new ChangeListener() {

        @Override
        public void changed(ObservableValue o, Object oldVal, Object newVal) {
            if (IsPaused()) {
                return;
            }
            double newDialValue = 0;
            String strVal = newVal.toString();
            try {
                newDialValue = Double.parseDouble(strVal);
            } catch (Exception ex) {
                LOGGER.severe("Invalid data for Simple Gauge received: " + strVal);
                return;
            }
            _Gauge.setValue(newDialValue);
        }
    });
    return true;
}
Also used : ObservableValue(javafx.beans.value.ObservableValue) ChangeListener(javafx.beans.value.ChangeListener)

Example 67 with ObservableValue

use of javafx.beans.value.ObservableValue in project RichTextFX by FXMisc.

the class ArrowFactory method apply.

@Override
public Node apply(int lineNumber) {
    Polygon triangle = new Polygon(0.0, 0.0, 10.0, 5.0, 0.0, 10.0);
    triangle.setFill(Color.GREEN);
    ObservableValue<Boolean> visible = Val.map(shownLine, sl -> sl == lineNumber);
    triangle.visibleProperty().bind(Val.flatMap(triangle.sceneProperty(), scene -> {
        return scene != null ? visible : Val.constant(false);
    }));
    return triangle;
}
Also used : Color(javafx.scene.paint.Color) Val(org.reactfx.value.Val) Node(javafx.scene.Node) ObservableValue(javafx.beans.value.ObservableValue) Polygon(javafx.scene.shape.Polygon) IntFunction(java.util.function.IntFunction) Polygon(javafx.scene.shape.Polygon)

Example 68 with ObservableValue

use of javafx.beans.value.ObservableValue in project assembly64fx by freabemania.

the class SidifyMainContoller method init.

public void init(Boolean showBackButton) {
    if (!playerWindowActive.compareAndSet(false, true)) {
        setCancelShow(true);
        return;
    }
    imageCache = CachedImageService.getInstance();
    playListService = PlaylistService.getInstance();
    downloadService = DownloadArtifactsService.getInstance();
    pathService = PathService.getInstance();
    sidPlayService = SIDPlayerService.getInstance();
    volume.setMin(-50L);
    volume.setMax(12);
    volume.setValue(sidPlayService.getVolume());
    volume.valueProperty().addListener(new ChangeListener<Number>() {

        public void changed(ObservableValue<? extends Number> ov, Number oldVal, Number newVal) {
            sidPlayService.setVolume(newVal.intValue());
        }
    });
    volume.valueChangingProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observableValue, Boolean wasChanging, Boolean changing) {
            if (!changing) {
                sidPlayService.storeVolume();
            }
        }
    });
    if (isOffline()) {
        enableSearchImage.setVisible(false);
    }
    performSearchImage.setVisible(false);
    searchField.setVisible(false);
    setIconPlaying(false);
    name.setCellValueFactory(new PropertyValueFactory<PlaylistEntry, String>("nameMasked"));
    group.setCellValueFactory(new PropertyValueFactory<PlaylistEntry, String>("groupMasked"));
    year.setCellValueFactory(new PropertyValueFactory<PlaylistEntry, String>("year"));
    downloaded.setCellValueFactory(new PropertyValueFactory<PlaylistEntry, ImageView>("downloaded"));
    status.setCellValueFactory(new PropertyValueFactory<PlaylistEntry, ImageView>("status"));
    progressSlider.setMin(0);
    progressSlider.setMax(SLIDERMAX);
    progressSlider.disableProperty().setValue(Boolean.TRUE);
    progressUpdater = new ProgressUpdater(played, remaining, progressSlider, prevSub, nextSub);
    status.setMaxWidth(40);
    status.setMinWidth(40);
    status.setSortable(false);
    name.setSortable(false);
    group.setSortable(false);
    year.setSortable(false);
    // songLength.setSortable(false);
    downloaded.setSortable(false);
    songlist.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    songlist.setPlaceholder(new Label(""));
    songlist.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    searchPeriod.setItems(FXCollections.observableArrayList(SEARCH_PERIOD.ALL, SEARCH_PERIOD.ONE_DAY, SEARCH_PERIOD.TWO_DAYS, SEARCH_PERIOD.FOUR_DAYS, SEARCH_PERIOD.ONE_WEEK, SEARCH_PERIOD.TWO_WEEKS, SEARCH_PERIOD.THREE_WEEKS, SEARCH_PERIOD.ONE_MONTH, SEARCH_PERIOD.TWO_MONTHS));
    searchPeriod.getSelectionModel().select(0);
    searchPeriod.setVisible(false);
    if (openedMain || !showBackButton) {
        openedMain = true;
        backToAssemblyImage.setVisible(false);
    }
    getStage().getScene().heightProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneHeight) {
            resizeComponentsHeight();
            delayedResize();
        }
    });
    getStage().getScene().widthProperty().addListener(new ChangeListener<Number>() {

        @Override
        public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneHeight, Number newSceneWidth) {
            resizeComponentsWidth();
            delayedResize();
        }
    });
    songlist.setRowFactory(tv -> {
        TableRow<PlaylistEntry> row = new TableRow<>();
        row.setOnDragDetected(event -> {
            if (!row.isEmpty() && isPlaylistMine(activePlaylist)) {
                Integer index = row.getIndex();
                Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
                db.setDragView(row.snapshot(null, null));
                ClipboardContent cc = new ClipboardContent();
                cc.put(SERIALIZED_MIME_TYPE, index);
                db.setContent(cc);
                event.consume();
            }
        });
        row.setOnDragOver(event -> {
            if (!isSearchActive() && isPlaylistMine(activePlaylist)) {
                Dragboard db = event.getDragboard();
                if (db.hasContent(SERIALIZED_MIME_TYPE)) {
                    if (row.getIndex() != ((Integer) db.getContent(SERIALIZED_MIME_TYPE)).intValue()) {
                        event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                        event.consume();
                    }
                }
            }
        });
        row.setOnDragDropped(event -> {
            if (!isSearchActive() && isPlaylistMine(activePlaylist)) {
                Dragboard db = event.getDragboard();
                if (db.hasContent(SERIALIZED_MIME_TYPE)) {
                    int draggedIndex = (Integer) db.getContent(SERIALIZED_MIME_TYPE);
                    PlaylistEntry draggedPerson = songlist.getItems().remove(draggedIndex);
                    int dropIndex;
                    if (row.isEmpty()) {
                        dropIndex = songlist.getItems().size();
                    } else {
                        dropIndex = row.getIndex();
                    }
                    songlist.getItems().add(dropIndex, draggedPerson);
                    event.setDropCompleted(true);
                    clearAndSelect(dropIndex);
                    Analytics.sendEvent("sidify", "dragndrop_song");
                    playListService.moveSongInList(playListService.getPlaylistForSong(draggedPerson), draggedIndex, dropIndex);
                    event.consume();
                    populateLeftList();
                }
            }
        });
        return row;
    });
    getStage().setOnCloseRequest(new EventHandler<WindowEvent>() {

        public void handle(WindowEvent we) {
            if (GlobalRepoService.getInstance().contains("overridebacktoassembly")) {
                closeAndcleanup(true);
            } else {
                closeAndcleanup(!LocalDBService.getInstance().getSidifyAsDefault());
            }
        }
    });
    populateLeftList();
    leftlist.setCellFactory(callback -> new ListCell<PlayerItem>() {

        @Override
        protected void updateItem(PlayerItem t, boolean bln) {
            super.updateItem(t, bln);
            if (t != null) {
                setText(t.getName());
            }
        }
    });
    leftlist.setOnMousePressed(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            disableSearch(true, false);
            PlayerItem clickedItem = leftlist.getSelectionModel().getSelectedItem();
            if (clickedItem.getType() == MENU_TYPE.NONCLICKABLE) {
                leftlist.getSelectionModel().clearSelection();
            } else if (clickedItem.getType() == MENU_TYPE.PLAYLIST || clickedItem.getType() == MENU_TYPE.PUBLICLIST) {
                PlaylistInfo playlist = clickedItem.getPlaylist();
                // activePlaylist = playlist;
                if ((event.getButton() == MouseButton.SECONDARY || event.isControlDown()) && !isOffline()) {
                    final ContextMenu contextMenu = new ContextMenu();
                    if (clickedItem.getType() == MENU_TYPE.PLAYLIST) {
                        MenuItem tmp = new MenuItem("Delete");
                        tmp.setOnAction((ActionEvent event2) -> {
                            playListService.deletePlaylist(playlist);
                            populateLeftList();
                            clearSongList();
                        });
                        MenuItem rename = new MenuItem("Edit");
                        rename.setOnAction((ActionEvent event2) -> {
                            GuiUtils.showDialog("sidifyCreateNewPlaylist.fxml", Boolean.TRUE, "Yada", getStage(), new Object[] { playlist, false });
                            populateLeftList();
                        });
                        contextMenu.getItems().add(tmp);
                        contextMenu.getItems().add(rename);
                        leftlist.setContextMenu(contextMenu);
                    } else {
                        MenuItem tmp = new MenuItem("Unfollow");
                        tmp.setOnAction((ActionEvent event2) -> {
                            playListService.deletePlaylist(playlist);
                            playListService.resetAndGetPublicPlaylists();
                            populateLeftList();
                        });
                        contextMenu.getItems().add(tmp);
                    }
                    MenuItem offline = new MenuItem("Download to offline");
                    offline.setOnAction((ActionEvent event2) -> {
                        Analytics.sendEvent("sidify", "download_playlist");
                        workQueue.offer(playlist);
                    });
                    MenuItem info = new MenuItem("Playlistinfo");
                    info.setOnAction((ActionEvent event2) -> {
                        GuiUtils.showDialog("sidifyViewPublicPlaylistInfo.fxml", Boolean.TRUE, "Playlistinfo", getStage(), new Object[] { playlist });
                    });
                    MenuItem exportLists = new MenuItem("Export playlist");
                    exportLists.setOnAction((ActionEvent event2) -> {
                        GuiUtils.showDialog("sidifyExportPlaylist.fxml", Boolean.TRUE, "Playlistinfo", getStage(), new Object[] { playlist });
                    });
                    contextMenu.getItems().add(offline);
                    contextMenu.getItems().add(info);
                    contextMenu.getItems().add(exportLists);
                    leftlist.setContextMenu(contextMenu);
                } else {
                    refreshCurrentSongList(playlist);
                }
                if (event.getClickCount() == 2) {
                    activePlaylist = playlist;
                    if (activePlaylist != null) {
                        List<PlaylistEntry> songsForPlaylist = playListService.getSongsForPlaylist(activePlaylist);
                        if (songsForPlaylist.size() > 0) {
                            if (randomSongs.get() == false) {
                                clearAndSelect(0);
                                setActiveSongInList(0);
                            } else {
                                randomize();
                                clearAndSelect(getActiveSongInList());
                            }
                            startSwitchSongLoopFromScratch();
                        }
                    }
                    songlist.requestFocus();
                }
                scrollToTop();
                populateLeftList();
            }
        }
    });
    songlist.setOnKeyTyped(event -> {
        if (!isSearchActive()) {
            if (event.getCharacter().length() > 0 && event.getCharacter().charAt(0) == Support.ENTER_KEY) {
                setBackgroundplaylistState();
                setNewSongPlayingState(false);
                startSwitchSongLoopFromScratch();
            }
        }
    });
    songlist.setOnMousePressed(event -> {
        songlist.setContextMenu(null);
        List<PlaylistEntry> selectedItems = songlist.getSelectionModel().getSelectedItems();
        if (selectedItems == null) {
            return;
        }
        if (isSearchActive()) {
            List<List<ContentEntry>> contentEntries = new ArrayList<>();
            for (PlaylistEntry playlistEntry : selectedItems) {
                ContentEntryInfo entryInfo = SearchService.getInstance().getSearchItems(playlistEntry.getId(), playlistEntry.getCategory());
                List<ContentEntry> entries = entryInfo.getContentEntry().stream().filter(item -> item.getName().toLowerCase().endsWith(".sid")).collect(Collectors.toList());
                List<ContentEntry> tmp = new ArrayList<>();
                tmp.addAll(entries);
                contentEntries.add(tmp);
            }
            boolean addable = !contentEntries.stream().filter(item -> item.size() > 1).findFirst().isPresent();
            if (event.getButton() == MouseButton.SECONDARY || event.isControlDown()) {
                if (addable) {
                    final ContextMenu contextMenu = new ContextMenu();
                    Menu addToPlaylist = new Menu("Add to playlist");
                    for (PlaylistInfo plist : playListService.getPlaylistInfo()) {
                        PlaylistMenuItem mItem = new PlaylistMenuItem(plist);
                        mItem.setOnAction((ActionEvent event2) -> {
                            PlaylistMenuItem item = (PlaylistMenuItem) event2.getSource();
                            if (Support.isPlaylistMine(item.getPlaylist())) {
                                playListService.addSongs(item.getPlaylist(), selectedItems, contentEntries);
                                songlist.getSelectionModel().clearSelection();
                            } else {
                                GenericMessageDialogController.withErrorProps("Sidify", "You can not add song to public lists!").showAndWait();
                            }
                        });
                        addToPlaylist.getItems().add(mItem);
                    }
                    MenuItem mItem = new MenuItem("Add to new playlist");
                    mItem.setOnAction((ActionEvent event2) -> {
                        SidifyCreatePlaylistController controller = GuiUtils.showDialog("sidifyCreateNewPlaylist.fxml", Boolean.TRUE, "Create new playlist", getStage(), new Object[] { null, false });
                        PlaylistInfo newPlaylist = controller.getNewlyCreatedPlayList();
                        if (newPlaylist != null) {
                            playListService.addSongs(newPlaylist, selectedItems, contentEntries);
                            songlist.getSelectionModel().clearSelection();
                            populateLeftList();
                        }
                    });
                    addToPlaylist.getItems().add(mItem);
                    contextMenu.getItems().add(addToPlaylist);
                    songlist.setContextMenu(contextMenu);
                } else {
                    // If we have more than one entry and
                    // want to add all
                    final ContextMenu contextMenu = new ContextMenu();
                    long nofSids = contentEntries.stream().collect(Collectors.summarizingInt(item -> item.size())).getSum();
                    Menu addToPlaylist = new Menu("Add all (" + nofSids + ") songs to playlist");
                    for (PlaylistInfo plist : playListService.getPlaylistInfo()) {
                        ContentEntryInfoMenuItem mItem = new ContentEntryInfoMenuItem(plist.getName(), contentEntries);
                        mItem.setOnAction((ActionEvent event2) -> {
                            ContentEntryInfoMenuItem item = (ContentEntryInfoMenuItem) event2.getSource();
                            playListService.addSongs(plist, selectedItems, item.getContentEntries());
                            songlist.getSelectionModel().clearSelection();
                            populateLeftList();
                        });
                        addToPlaylist.getItems().add(mItem);
                    }
                    contextMenu.getItems().add(addToPlaylist);
                    MenuItem mItem = new MenuItem("Add to new playlist");
                    mItem.setOnAction((ActionEvent event2) -> {
                        SidifyCreatePlaylistController controller = GuiUtils.showDialog("sidifyCreateNewPlaylist.fxml", Boolean.TRUE, "Create new playlist", getStage(), new Object[] { null, false });
                        PlaylistInfo newPlaylist = controller.getNewlyCreatedPlayList();
                        ContentEntryInfoMenuItem cmItem = new ContentEntryInfoMenuItem(newPlaylist.getName(), contentEntries);
                        if (newPlaylist != null) {
                            playListService.addSongs(newPlaylist, selectedItems, cmItem.getContentEntries());
                            songlist.getSelectionModel().clearSelection();
                            populateLeftList();
                        }
                    });
                    addToPlaylist.getItems().add(mItem);
                    songlist.setContextMenu(contextMenu);
                }
            } else {
                if (event.getClickCount() == 2) {
                    setBackgroundplaylistState();
                    try {
                        if (contentEntries.size() == 1 && contentEntries.get(0).size() == 1) {
                            setNewSongPlayingState(false);
                            selectedItems.get(0).setFileId(contentEntries.get(0).get(0).getId());
                            startSwitchSongLoopFromScratch();
                        } else {
                            GuiUtils.showDialog("sidifyViewMultipeSongs.fxml", Boolean.TRUE, "Choose", getStage(), new Object[] { Support.flattenAndEnrichEntries(selectedItems, contentEntries) });
                            refreshPlaylistIfNeeded(playListService.getPlaylistForSong(selectedItems.get(0)));
                            populateLeftList();
                        }
                    } catch (Exception e) {
                        LOGGER.error("Unable to play item", e);
                    }
                }
            }
        } else {
            List<List<ContentEntry>> contentEntries = new ArrayList<>();
            for (PlaylistEntry playlistEntry : selectedItems) {
                List<ContentEntry> tmp = new ArrayList<>();
                ContentEntry entry = new ContentEntry();
                entry.setFullPlaylistInfo(playlistEntry);
                entry.setId(playlistEntry.getFileId());
                entry.setName(playlistEntry.getName());
                tmp.add(entry);
                contentEntries.add(tmp);
            }
            setBackgroundplaylistState();
            if ((event.getButton() == MouseButton.SECONDARY || event.isControlDown()) && !isOffline()) {
                final ContextMenu contextMenu = new ContextMenu();
                Menu addToPlaylist = new Menu("Add to playlist");
                for (PlaylistInfo plist : playListService.getPlaylistInfo()) {
                    PlaylistMenuItem mItem = new PlaylistMenuItem(plist);
                    mItem.setOnAction((ActionEvent event2) -> {
                        PlaylistMenuItem item = (PlaylistMenuItem) event2.getSource();
                        if (Support.isPlaylistMine(item.getPlaylist())) {
                            playListService.addSongs(item.getPlaylist(), selectedItems, contentEntries);
                            PlaylistInfo currentPlaylist = playListService.getPlaylistForSong(selectedItems.get(0));
                            refreshPlaylistIfNeeded(currentPlaylist);
                            songlist.getSelectionModel().clearSelection();
                        } else {
                            GenericMessageDialogController.withErrorProps("Sidify", "You can not add song to public lists!").showAndWait();
                        }
                    });
                    addToPlaylist.getItems().add(mItem);
                }
                contextMenu.getItems().add(addToPlaylist);
                MenuItem mItem = new MenuItem("Add to new playlist");
                mItem.setOnAction((ActionEvent event2) -> {
                    SidifyCreatePlaylistController controller = GuiUtils.showDialog("sidifyCreateNewPlaylist.fxml", Boolean.TRUE, "Create new playlist", getStage(), new Object[] { null, false });
                    PlaylistInfo newPlaylist = controller.getNewlyCreatedPlayList();
                    ContentEntryInfoMenuItem cmItem = new ContentEntryInfoMenuItem(newPlaylist.getName(), contentEntries);
                    if (newPlaylist != null) {
                        playListService.addSongs(newPlaylist, selectedItems, cmItem.getContentEntries());
                        songlist.getSelectionModel().clearSelection();
                        populateLeftList();
                    }
                });
                addToPlaylist.getItems().add(mItem);
                if (isPlaylistMine(playListService.getPlaylistForSong(selectedItems.get(0)))) {
                    PlaylistEntryMenuItem deleteItem = new PlaylistEntryMenuItem("Delete", selectedItems);
                    deleteItem.setOnAction((ActionEvent event2) -> {
                        PlaylistEntryMenuItem item = (PlaylistEntryMenuItem) event2.getSource();
                        PlaylistInfo currentPlaylist = playListService.getPlaylistForSong(item.getPlaylistEntry());
                        playListService.deleteSongs(currentPlaylist, item.getPlaylistEntries());
                        songlist.getSelectionModel().clearSelection();
                        populateLeftList();
                        refreshPlaylistIfNeeded(currentPlaylist);
                    });
                    contextMenu.getItems().add(deleteItem);
                }
                songlist.setContextMenu(contextMenu);
            } else if (event.getClickCount() == 2) {
                setNewSongPlayingState(false);
                startSwitchSongLoopFromScratch();
                populateLeftList();
            }
        }
    });
    searchField.setOnKeyReleased((event) -> {
        if (event.getCode() == KeyCode.ENTER) {
            doSearch(searchField.getText());
        }
    });
    try {
        searchPeriod.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends SEARCH_PERIOD> observable, SEARCH_PERIOD oldValue, SEARCH_PERIOD newValue) -> doSearch(searchField.getText()));
    } catch (Exception e) {
        LOGGER.info("Unable to add listener", e);
    }
    disableSearch();
    workQueue = new ArrayBlockingQueue<>(1000);
    Executors.newSingleThreadExecutor().execute(() -> {
        while (true) {
            try {
                Object queueItem = workQueue.take();
                if (queueItem instanceof PoisonPill) {
                    break;
                } else if (queueItem instanceof PlaylistInfo) {
                    downloadPlaylistOffline((PlaylistInfo) queueItem, true);
                } else if (queueItem instanceof String && ((String) queueItem).equals("checklists")) {
                    for (PlaylistInfo pInfo : playListService.getPlaylistInfo()) {
                        if (pInfo.isAvailableOffline()) {
                            downloadPlaylistOffline(pInfo, false);
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    });
    if (!isOffline()) {
        checkOfflineScheduler = Executors.newScheduledThreadPool(1);
        checkOfflineScheduler.scheduleAtFixedRate(() -> {
            workQueue.offer("checklists");
        }, 5, 10, TimeUnit.SECONDS);
    }
}
Also used : EventHandler(javafx.event.EventHandler) Support.isOffline(se.light.assembly64.Support.isOffline) ListCell(javafx.scene.control.ListCell) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) PathService(se.light.assembly64.service.PathService) StringUtils(org.apache.commons.lang3.StringUtils) ContentEntryInfo(se.light.assembly64.model.ContentEntryInfo) CachedImageService(se.light.assembly64.service.CachedImageService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContextMenu(javafx.scene.control.ContextMenu) WindowEvent(javafx.stage.WindowEvent) TableView(javafx.scene.control.TableView) ContentEntry(se.light.assembly64.model.ContentEntry) Pane(javafx.scene.layout.Pane) TextField(javafx.scene.control.TextField) PlaylistEntryMenuItem(se.light.assembly64.model.PlaylistEntryMenuItem) MenuItem(javafx.scene.control.MenuItem) PropertyValueFactory(javafx.scene.control.cell.PropertyValueFactory) SidTune(libsidplay.sidtune.SidTune) SidFileInfo(se.light.assembly64.model.SidFileInfo) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) SearchException(se.light.assembly64.model.SearchException) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Platform(javafx.application.Platform) FXML(javafx.fxml.FXML) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) List(java.util.List) DataFormat(javafx.scene.input.DataFormat) PlaylistMenuItem(se.light.assembly64.model.PlaylistMenuItem) AnchorPane(javafx.scene.layout.AnchorPane) ObservableList(javafx.collections.ObservableList) ClipboardContent(javafx.scene.input.ClipboardContent) ReturningTask(se.light.assembly64.model.ReturningTask) MouseButton(javafx.scene.input.MouseButton) ListView(javafx.scene.control.ListView) PlaylistEntry(se.light.assembly64.model.PlaylistEntry) MouseEvent(javafx.scene.input.MouseEvent) SearchService(se.light.assembly64.service.SearchService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FXCollections(javafx.collections.FXCollections) PoisonPill(se.light.assembly64.model.PoisonPill) PlaylistInfo(se.light.assembly64.model.PlaylistInfo) GlobalRepoService(se.light.assembly64.service.GlobalRepoService) TransferMode(javafx.scene.input.TransferMode) ArrayList(java.util.ArrayList) TableColumn(javafx.scene.control.TableColumn) Support.isSearchActive(se.light.assembly64.Support.isSearchActive) Dragboard(javafx.scene.input.Dragboard) Slider(javafx.scene.control.Slider) GuiUtils(se.light.assembly64.util.GuiUtils) Support(se.light.assembly64.Support) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MetadataService(se.light.assembly64.fx.mdresolve.MetadataService) DownloadArtifactsService(se.light.assembly64.service.DownloadArtifactsService) PlaylistService(se.light.assembly64.service.PlaylistService) BaseGuiController(se.light.assembly64.model.BaseGuiController) Analytics(se.light.assembly64.Analytics) KeyCode(javafx.scene.input.KeyCode) Logger(org.slf4j.Logger) Label(javafx.scene.control.Label) ExecutorUtil(se.light.assembly64.util.ExecutorUtil) TargetAndPath(se.light.assembly64.model.TargetAndPath) TableRow(javafx.scene.control.TableRow) ContentEntryInfoMenuItem(se.light.assembly64.model.ContentEntryInfoMenuItem) Support.resolveFilename(se.light.assembly64.Support.resolveFilename) Support.setSearchActive(se.light.assembly64.Support.setSearchActive) SongNotAvailableException(se.light.assembly64.model.SongNotAvailableException) Support.isPlaylistMine(se.light.assembly64.Support.isPlaylistMine) File(java.io.File) ChoiceBox(javafx.scene.control.ChoiceBox) Menu(javafx.scene.control.Menu) SIDPlayerService(se.light.assembly64.service.SIDPlayerService) TimeUnit(java.util.concurrent.TimeUnit) ActionEvent(javafx.event.ActionEvent) SpecifyFileIdException(se.light.assembly64.model.SpecifyFileIdException) SelectionMode(javafx.scene.control.SelectionMode) Stage(javafx.stage.Stage) ImageView(javafx.scene.image.ImageView) LocalDBService(se.light.assembly64.service.LocalDBService) ObservableValue(javafx.beans.value.ObservableValue) SEARCH_PERIOD(se.light.assembly64.Support.SEARCH_PERIOD) Comparator(java.util.Comparator) ChangeListener(javafx.beans.value.ChangeListener) Collections(java.util.Collections) Image(javafx.scene.image.Image) PlaylistEntryMenuItem(se.light.assembly64.model.PlaylistEntryMenuItem) PoisonPill(se.light.assembly64.model.PoisonPill) ActionEvent(javafx.event.ActionEvent) Label(javafx.scene.control.Label) ArrayList(java.util.ArrayList) ObservableValue(javafx.beans.value.ObservableValue) PlaylistMenuItem(se.light.assembly64.model.PlaylistMenuItem) List(java.util.List) ObservableList(javafx.collections.ObservableList) ArrayList(java.util.ArrayList) ImageView(javafx.scene.image.ImageView) PlaylistInfo(se.light.assembly64.model.PlaylistInfo) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Dragboard(javafx.scene.input.Dragboard) ContentEntryInfo(se.light.assembly64.model.ContentEntryInfo) SEARCH_PERIOD(se.light.assembly64.Support.SEARCH_PERIOD) TableRow(javafx.scene.control.TableRow) ContentEntryInfoMenuItem(se.light.assembly64.model.ContentEntryInfoMenuItem) ClipboardContent(javafx.scene.input.ClipboardContent) ContextMenu(javafx.scene.control.ContextMenu) ContextMenu(javafx.scene.control.ContextMenu) Menu(javafx.scene.control.Menu) MouseEvent(javafx.scene.input.MouseEvent) PlaylistEntryMenuItem(se.light.assembly64.model.PlaylistEntryMenuItem) MenuItem(javafx.scene.control.MenuItem) PlaylistMenuItem(se.light.assembly64.model.PlaylistMenuItem) ContentEntryInfoMenuItem(se.light.assembly64.model.ContentEntryInfoMenuItem) SearchException(se.light.assembly64.model.SearchException) SongNotAvailableException(se.light.assembly64.model.SongNotAvailableException) SpecifyFileIdException(se.light.assembly64.model.SpecifyFileIdException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ContentEntry(se.light.assembly64.model.ContentEntry) WindowEvent(javafx.stage.WindowEvent) PlaylistEntry(se.light.assembly64.model.PlaylistEntry)

Example 69 with ObservableValue

use of javafx.beans.value.ObservableValue 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 70 with ObservableValue

use of javafx.beans.value.ObservableValue in project CodenameOne by codenameone.

the class SEBrowserComponent method init.

private static void init(SEBrowserComponent self, BrowserComponent p) {
    final WeakReference<SEBrowserComponent> weakSelf = new WeakReference<>(self);
    final WeakReference<BrowserComponent> weakP = new WeakReference<>(p);
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            SEBrowserComponent self = weakSelf.get();
            if (self == null) {
                return;
            }
            self.cnt = new InternalJPanel(self.instance, self);
            // <--- Important if container is opaque it will cause
            self.cnt.setOpaque(false);
            // all kinds of flicker due to painting conflicts with CN1 pipeline.
            self.cnt.setLayout(new BorderLayout());
            self.cnt.add(BorderLayout.CENTER, self.panel);
        // cnt.setVisible(false);
        }
    });
    self.web.getEngine().getLoadWorker().messageProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> ov, String t, String t1) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (t1.startsWith("Loading http:") || t1.startsWith("Loading file:") || t1.startsWith("Loading https:")) {
                String url = t1.substring("Loading ".length());
                if (!url.equals(self.currentURL)) {
                    p.fireWebEvent("onStart", new ActionEvent(url));
                }
                self.currentURL = url;
            } else if ("Loading complete".equals(t1)) {
            }
        }
    });
    self.web.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {

        @Override
        public void handle(WebEvent<String> t) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            String msg = t.getData();
            if (msg.startsWith("!cn1_message:")) {
                System.out.println("Receiving message " + msg);
                p.fireWebEvent("onMessage", new ActionEvent(msg.substring("!cn1_message:".length())));
            }
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            System.out.println("Received exception: " + t1.getMessage());
            if (ov.getValue() != null) {
                ov.getValue().printStackTrace();
            }
            if (t != ov.getValue() && t != null) {
                t.printStackTrace();
            }
            if (t1 != ov.getValue() && t1 != t && t1 != null) {
                t.printStackTrace();
            }
        }
    });
    self.web.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {

        @Override
        public void changed(ObservableValue ov, State oldState, State newState) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            try {
                netscape.javascript.JSObject w = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                if (w == null) {
                    System.err.println("Could not get window");
                } else {
                    Bridge b = new Bridge(p);
                    self.putClientProperty("SEBrowserComponent.Bridge.jconsole", b);
                    w.setMember("jconsole", b);
                }
            } catch (Throwable t) {
                Log.e(t);
            }
            if (self == null || p == null) {
                return;
            }
            String url = self.web.getEngine().getLocation();
            if (newState == State.SCHEDULED) {
                p.fireWebEvent("onStart", new ActionEvent(url));
            } else if (newState == State.RUNNING) {
                p.fireWebEvent("onLoadResource", new ActionEvent(url));
            } else if (newState == State.SUCCEEDED) {
                if (!p.isNativeScrollingEnabled()) {
                    self.web.getEngine().executeScript("document.body.style.overflow='hidden'");
                }
                // let's just add a client property to the BrowserComponent to enable firebug
                if (Boolean.TRUE.equals(p.getClientProperty("BrowserComponent.firebug"))) {
                    self.web.getEngine().executeScript("if (!document.getElementById('FirebugLite')){E = document['createElement' + 'NS'] && document.documentElement.namespaceURI;E = E ? document['createElement' + 'NS'](E, 'script') : document['createElement']('script');E['setAttribute']('id', 'FirebugLite');E['setAttribute']('src', 'https://getfirebug.com/' + 'firebug-lite.js' + '#startOpened');E['setAttribute']('FirebugLite', '4');(document['getElementsByTagName']('head')[0] || document['getElementsByTagName']('body')[0]).appendChild(E);E = new Image;E['setAttribute']('src', 'https://getfirebug.com/' + '#startOpened');}");
                }
                netscape.javascript.JSObject window = (netscape.javascript.JSObject) self.web.getEngine().executeScript("window");
                Bridge b = new Bridge(p);
                self.putClientProperty("SEBrowserComponent.Bridge.cn1application", b);
                window.setMember("cn1application", b);
                self.web.getEngine().executeScript("while (window._cn1ready && window._cn1ready.length > 0) {var f = window._cn1ready.shift(); f();}");
                // System.out.println("cn1application is "+self.web.getEngine().executeScript("window.cn1application && window.cn1application.shouldNavigate"));
                self.web.getEngine().executeScript("window.addEventListener('unload', function(e){console.log('unloading...');return 'foobar';});");
                p.fireWebEvent("onLoad", new ActionEvent(url));
            }
            self.currentURL = url;
            self.repaint();
        }
    });
    self.web.getEngine().getLoadWorker().exceptionProperty().addListener(new ChangeListener<Throwable>() {

        @Override
        public void changed(ObservableValue<? extends Throwable> ov, Throwable t, Throwable t1) {
            BrowserComponent p = weakP.get();
            if (p == null) {
                return;
            }
            t1.printStackTrace();
            if (t1 == null) {
                if (t == null) {
                    p.fireWebEvent("onError", new ActionEvent("Unknown error", -1));
                } else {
                    p.fireWebEvent("onError", new ActionEvent(t.getMessage(), -1));
                }
            } else {
                p.fireWebEvent("onError", new ActionEvent(t1.getMessage(), -1));
            }
        }
    });
    // Monitor the location property so that we can send the shouldLoadURL event.
    // This allows us to cancel the loading of a URL if we want to handle it ourself.
    self.web.getEngine().locationProperty().addListener(new ChangeListener<String>() {

        @Override
        public void changed(ObservableValue<? extends String> prop, String before, String after) {
            SEBrowserComponent self = weakSelf.get();
            BrowserComponent p = weakP.get();
            if (self == null || p == null) {
                return;
            }
            if (!p.fireBrowserNavigationCallbacks(self.web.getEngine().getLocation())) {
                self.web.getEngine().getLoadWorker().cancel();
            }
        }
    });
    self.adjustmentListener = new AdjustmentListener() {

        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    SEBrowserComponent self = weakSelf.get();
                    if (self == null) {
                        return;
                    }
                    self.onPositionSizeChange();
                }
            });
        }
    };
}
Also used : ActionEvent(com.codename1.ui.events.ActionEvent) ObservableValue(javafx.beans.value.ObservableValue) BorderLayout(java.awt.BorderLayout) WeakReference(java.lang.ref.WeakReference) WebEvent(javafx.scene.web.WebEvent) AdjustmentEvent(java.awt.event.AdjustmentEvent) State(javafx.concurrent.Worker.State) AdjustmentListener(java.awt.event.AdjustmentListener)

Aggregations

ObservableValue (javafx.beans.value.ObservableValue)85 ChangeListener (javafx.beans.value.ChangeListener)53 FXML (javafx.fxml.FXML)13 Scene (javafx.scene.Scene)13 ImageView (javafx.scene.image.ImageView)13 KeyEvent (javafx.scene.input.KeyEvent)11 ArrayList (java.util.ArrayList)10 Label (javafx.scene.control.Label)10 TableColumn (javafx.scene.control.TableColumn)10 TableView (javafx.scene.control.TableView)10 ActionEvent (javafx.event.ActionEvent)9 MouseEvent (javafx.scene.input.MouseEvent)9 TextField (javafx.scene.control.TextField)8 Color (javafx.scene.paint.Color)8 ObservableList (javafx.collections.ObservableList)7 MenuItem (javafx.scene.control.MenuItem)7 CellDataFeatures (javafx.scene.control.TableColumn.CellDataFeatures)7 List (java.util.List)6 Set (java.util.Set)6 Platform (javafx.application.Platform)6