org.fxmisc.easybind.EasyBind Java Examples

The following examples show how to use org.fxmisc.easybind.EasyBind. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DepositView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void activate() {
    tableView.getSelectionModel().selectedItemProperty().addListener(tableViewSelectionListener);
    sortedList.comparatorProperty().bind(tableView.comparatorProperty());

    updateList();

    walletService.addBalanceListener(balanceListener);
    amountTextFieldSubscription = EasyBind.subscribe(amountTextField.textProperty(), t -> {
        addressTextField.setAmountAsCoin(ParsingUtils.parseToCoin(t, formatter));
        updateQRCode();
    });

    if (tableView.getSelectionModel().getSelectedItem() == null && !sortedList.isEmpty())
        tableView.getSelectionModel().select(0);
}
 
Example #2
Source File: PendingTradesViewModel.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
public void onSelectedItemChanged(PendingTradesListItem selectedItem) {
    if (tradeStateSubscription != null) {
        tradeStateSubscription.unsubscribe();
        sellerState.set(SellerState.UNDEFINED);
        buyerState.set(BuyerState.UNDEFINED);
    }

    if (messageStateSubscription != null) {
        messageStateSubscription.unsubscribe();
        messageStateProperty.set(MessageState.UNDEFINED);
    }

    if (selectedItem != null) {
        this.trade = selectedItem.getTrade();
        tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), this::onTradeStateChanged);

        messageStateSubscription = EasyBind.subscribe(trade.getProcessModel().getPaymentStartedMessageStateProperty(), this::onMessageStateChanged);
    }
}
 
Example #3
Source File: MainController.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
public void onBitcoinSetup() {
    model.setWallet(bitcoin.wallet());
    addressControl.addressProperty().bind(model.addressProperty());
    balance.textProperty().bind(EasyBind.map(model.balanceProperty(), coin -> MonetaryFormat.BTC.noCode().format(coin).toString()));
    // Don't let the user click send money when the wallet is empty.
    sendMoneyOutBtn.disableProperty().bind(model.balanceProperty().isEqualTo(Coin.ZERO));

    showBitcoinSyncMessage();
    model.syncProgressProperty().addListener(x -> {
        if (model.syncProgressProperty().get() >= 1.0) {
            readyToGoAnimation();
            if (syncItem != null) {
                syncItem.cancel();
                syncItem = null;
            }
        } else if (syncItem == null) {
            showBitcoinSyncMessage();
        }
    });
}
 
Example #4
Source File: MainController.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
public void onBitcoinSetup() {
    model.setWallet(bitcoin.wallet());
    addressControl.addressProperty().bind(model.addressProperty());
    balance.textProperty().bind(EasyBind.map(model.balanceProperty(), coin -> MonetaryFormat.BTC.noCode().format(coin).toString()));
    // Don't let the user click send money when the wallet is empty.
    sendMoneyOutBtn.disableProperty().bind(model.balanceProperty().isEqualTo(Coin.ZERO));

    showBitcoinSyncMessage();
    model.syncProgressProperty().addListener(x -> {
        if (model.syncProgressProperty().get() >= 1.0) {
            readyToGoAnimation();
            if (syncItem != null) {
                syncItem.cancel();
                syncItem = null;
            }
        } else if (syncItem == null) {
            showBitcoinSyncMessage();
        }
    });
}
 
Example #5
Source File: VoteResultView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void activate() {
    super.activate();

    phasesView.activate();

    daoFacade.addBsqStateListener(this);
    cyclesTableView.getSelectionModel().selectedItemProperty().addListener(selectedVoteResultListItemListener);

    if (daoStateService.isParseBlockChainComplete()) {
        checkForResultPhase(daoStateService.getChainHeight());
        fillCycleList();
    }

    exportButton.setOnAction(event -> {
        JsonElement cyclesJsonArray = getVotingHistoryJson();
        GUIUtil.exportJSON("voteResultsHistory.json", cyclesJsonArray, (Stage) root.getScene().getWindow());
    });
    if (proposalsTableView != null) {
        GUIUtil.setFitToRowsForTableView(proposalsTableView, 25, 28, 6, 6);

        selectedProposalSubscription = EasyBind.subscribe(proposalsTableView.getSelectionModel().selectedItemProperty(),
                this::onSelectProposalResultListItem);
    }
    GUIUtil.setFitToRowsForTableView(cyclesTableView, 25, 28, 6, 6);
}
 
Example #6
Source File: PreferencePane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
private void bindProperties() {
    categories.add(new GeneralPane());
    categories.add(new InferencePane());
    categories.add(new TrainingPane());

    categoryList.getItems().addAll(EasyBind.map(categories, Category::getName));

    categoryList.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
        Category selected = categories.stream().filter(p -> p.getName().equals(newValue)).findFirst().get();
        scroller.setContent((Node) selected);
    });

    ObservableList<ObservableValue<Boolean>> dirties = EasyBind.map(categories, c -> c.dirtyProperty());
    lookupButton(ButtonType.APPLY).disableProperty().bind(EasyBind.combine(dirties, stream -> stream.allMatch(a -> !a)));

    categoryList.getSelectionModel().select(0);

    // Split Pane Divider
    splitPane.sceneProperty().addListener(((observable, oldValue, newValue) -> {
        if (newValue != null) {
            var positions = splitPane.getDividerPositions();
            splitPane.getScene().widthProperty().addListener((obs, oldItem, newItem) -> splitPane.setDividerPositions(positions));
        }
    }));
}
 
Example #7
Source File: TrainingPane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
private void bindProperties() {
    // Update on any directory changes
    dirTFImage.textProperty().addListener((observable, oldValue, newValue) -> updateNumSamples());
    dirTFAnnotation.textProperty().addListener((observable, oldValue, newValue) -> updateNumSamples());
    dirTFData.textProperty().addListener((observable, oldValue, newValue) -> updateLabelMap());
    dirTFBaseModel.textProperty().addListener((observable, oldValue, newValue) -> updateTraining());

    BooleanBinding changes[] = {
            dirTFImage.textProperty().isNotEqualTo(Settings.tfImageDirProperty),
            dirTFAnnotation.textProperty().isNotEqualTo(Settings.tfAnnotationDirProperty),
            dirTFData.textProperty().isNotEqualTo(Settings.tfDataDirProperty),
            new SimpleListProperty(labelMapPane.getItems()).isNotEqualTo(
                    FXCollections.observableList(TFTrainer.getLabelMapItems(dirTFData.getText()))),
            dirTFBaseModel.textProperty().isNotEqualTo(Settings.tfBaseModelDirProperty),
            txtDockerImage.textProperty().isNotEqualTo(Settings.dockerImageProperty),
            txtContainerHostName.textProperty().isNotEqualTo(Settings.containerHostNameProperty),
            txtContainerName.textProperty().isNotEqualTo(Settings.containerNameProperty),
    };
    dirtyProperty.unbind();
    dirtyProperty.bind(EasyBind.combine(
            FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));
}
 
Example #8
Source File: InferencePane.java    From OpenLabeler with Apache License 2.0 6 votes vote down vote up
public InferencePane() {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/preference/InferencePane.fxml"), bundle);
    loader.setRoot(this);
    loader.setController(this);

    try {
        loader.load();
    }
    catch (Exception ex) {
        LOG.log(Level.SEVERE, "Unable to load FXML", ex);
    }

    // Bind Properties
    BooleanBinding changes[] = {
            chkUseInference.selectedProperty().isNotEqualTo(Settings.useInferenceProperty),
            pickerHintStrokeColor.valueProperty().isNotEqualTo(Settings.hintStrokeColorProperty),
            fileTFLabelMap.textProperty().isNotEqualTo(Settings.tfLabelMapFileProperty),
            dirTFSavedModel.textProperty().isNotEqualTo(Settings.tfSavedModelDirProperty),
    };
    dirtyProperty.bind(EasyBind.combine(
            FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));

    load();
}
 
Example #9
Source File: StateMonitorView.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void activate() {
    selectedItemSubscription = EasyBind.subscribe(tableView.getSelectionModel().selectedItemProperty(), this::onSelectItem);

    sortedList.comparatorProperty().bind(tableView.comparatorProperty());
    sortedConflictList.comparatorProperty().bind(conflictTableView.comparatorProperty());

    daoStateService.addDaoStateListener(this);

    resyncButton.visibleProperty().bind(isInConflictWithSeedNode);
    resyncButton.managedProperty().bind(isInConflictWithSeedNode);

    resyncButton.setOnAction(ev -> resyncDaoState());

    if (daoStateService.isParseBlockChainComplete()) {
        onDataUpdate();
    }

    GUIUtil.setFitToRowsForTableView(tableView, 25, 28, 2, 5);
    GUIUtil.setFitToRowsForTableView(conflictTableView, 38, 28, 2, 4);
}
 
Example #10
Source File: ProposalsView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void activate() {
    phasesView.activate();

    selectedProposalSubscription = EasyBind.subscribe(tableView.getSelectionModel().selectedItemProperty(), this::onSelectProposal);

    daoFacade.addBsqStateListener(this);

    sortedList.comparatorProperty().bind(tableView.comparatorProperty());
    tableView.setPrefHeight(100);
    root.getScene().heightProperty().addListener(sceneHeightListener);
    UserThread.execute(() -> {
        if (root.getScene() != null)
            updateTableHeight(root.getScene().getHeight());
    });

    stakeInputTextField.textProperty().addListener(stakeListener);
    voteButton.setOnAction(e -> onVote());

    onUpdateBalances(bsqWalletService.getAvailableConfirmedBalance(),
            bsqWalletService.getAvailableNonBsqBalance(),
            bsqWalletService.getUnverifiedBalance(),
            bsqWalletService.getUnconfirmedChangeBalance(),
            bsqWalletService.getLockedForVotingBalance(),
            bsqWalletService.getLockupBondsBalance(),
            bsqWalletService.getUnlockingBondsBalance());

    if (daoStateService.isParseBlockChainComplete()) {
        addListenersAfterParseBlockChainComplete();

        updateListItems();
        applyMerit();
        updateViews();
    }
}
 
Example #11
Source File: P2pNetworkListItem.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
P2pNetworkListItem(Connection connection, ClockWatcher clockWatcher) {
    this.connection = connection;
    this.clockWatcher = clockWatcher;
    this.statistic = connection.getStatistic();

    sentBytesSubscription = EasyBind.subscribe(statistic.sentBytesProperty(),
            e -> sentBytes.set(FormattingUtils.formatBytes((long) e)));
    receivedBytesSubscription = EasyBind.subscribe(statistic.receivedBytesProperty(),
            e -> receivedBytes.set(FormattingUtils.formatBytes((long) e)));
    onionAddressSubscription = EasyBind.subscribe(connection.getPeersNodeAddressProperty(),
            nodeAddress -> onionAddress.set(nodeAddress != null ? nodeAddress.getFullAddress() : Res.get("settings.net.notKnownYet")));
    roundTripTimeSubscription = EasyBind.subscribe(statistic.roundTripTimeProperty(),
            roundTripTime -> this.roundTripTime.set((int) roundTripTime == 0 ? "-" : roundTripTime + " ms"));

    listener = new ClockWatcher.Listener() {
        @Override
        public void onSecondTick() {
            onLastActivityChanged(statistic.getLastActivityTimestamp());
            updatePeerType();
            updateConnectionType();
        }

        @Override
        public void onMinuteTick() {
        }
    };
    clockWatcher.addListener(listener);
    onLastActivityChanged(statistic.getLastActivityTimestamp());
    updatePeerType();
    updateConnectionType();
}
 
Example #12
Source File: ProposalsView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addListenersAfterParseBlockChainComplete() {
    daoFacade.getActiveOrMyUnconfirmedProposals().addListener(proposalListChangeListener);
    daoFacade.getAllBallots().addListener(ballotListChangeListener);

    bsqWalletService.addBsqBalanceListener(this);

    phaseSubscription = EasyBind.subscribe(daoFacade.phaseProperty(), this::onPhaseChanged);
}
 
Example #13
Source File: PolygonItem.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyDoubleProperty getMinXProperty() {
   if (minXProperty == null) {
      minXProperty = new SimpleDoubleProperty();
      minXProperty.bind(EasyBind.map(boundsInLocalProperty(), Bounds::getMinX));
   }
   return minXProperty;
}
 
Example #14
Source File: MutableOfferView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addSubscriptions() {
    isWaitingForFundsSubscription = EasyBind.subscribe(model.isWaitingForFunds, isWaitingForFunds -> {

        if (isWaitingForFunds) {
            waitingForFundsSpinner.play();
        } else {
            waitingForFundsSpinner.stop();
        }

        waitingForFundsLabel.setVisible(isWaitingForFunds);
        waitingForFundsLabel.setManaged(isWaitingForFunds);
    });

    balanceSubscription = EasyBind.subscribe(model.getDataModel().getBalance(), balanceTextField::setBalance);
}
 
Example #15
Source File: NotificationCenter.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Inject
public NotificationCenter(TradeManager tradeManager,
                          MediationManager mediationManager,
                          RefundManager refundManager,
                          Preferences preferences,
                          Navigation navigation) {
    this.tradeManager = tradeManager;
    this.mediationManager = mediationManager;
    this.refundManager = refundManager;
    this.navigation = navigation;

    EasyBind.subscribe(preferences.getUseAnimationsProperty(), useAnimations -> NotificationCenter.useAnimations = useAnimations);
}
 
Example #16
Source File: TradeStepView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void registerSubscriptions() {
    disputeStateSubscription = EasyBind.subscribe(trade.disputeStateProperty(), newValue -> {
        if (newValue != null) {
            updateDisputeState(newValue);
        }
    });

    mediationResultStateSubscription = EasyBind.subscribe(trade.mediationResultStateProperty(), newValue -> {
        if (newValue != null) {
            updateMediationResultState(true);
        }
    });

    UserThread.execute(() -> model.p2PService.removeP2PServiceListener(bootstrapListener));
}
 
Example #17
Source File: SetupPayoutTxListener.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();
        if (!trade.isPayoutPublished()) {
            BtcWalletService walletService = processModel.getBtcWalletService();
            String id = processModel.getOffer().getId();
            Address address = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.TRADE_PAYOUT).getAddress();

            TransactionConfidence confidence = walletService.getConfidenceForAddress(address);
            if (isInNetwork(confidence)) {
                applyConfidence(confidence);
            } else {
                confidenceListener = new AddressConfidenceListener(address) {
                    @Override
                    public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
                        if (isInNetwork(confidence))
                            applyConfidence(confidence);
                    }
                };
                walletService.addAddressConfidenceListener(confidenceListener);

                tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
                    if (trade.isPayoutPublished()) {
                        swapMultiSigEntry();

                        // hack to remove tradeStateSubscription at callback
                        UserThread.execute(this::unSubscribe);
                    }
                });
            }
        }

        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example #18
Source File: PolygonItem.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyDoubleProperty getMinYProperty() {
   if (minYProperty == null) {
      minYProperty = new SimpleDoubleProperty();
      minYProperty.bind(EasyBind.map(boundsInLocalProperty(), Bounds::getMinY));
   }
   return minYProperty;
}
 
Example #19
Source File: ChatView.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addListenersOnSessionChange(ReadOnlyDoubleProperty widthProperty) {
    if (tableGroupHeadline != null) {
        tableGroupHeadline.prefWidthProperty().bind(widthProperty);
        messageListView.prefWidthProperty().bind(widthProperty);
        this.prefWidthProperty().bind(widthProperty);
        chatMessages.addListener(disputeDirectMessageListListener);
        inputTextAreaTextSubscription = EasyBind.subscribe(inputTextArea.textProperty(), t -> sendButton.setDisable(t.isEmpty()));
    }
}
 
Example #20
Source File: P2PService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Inject
public P2PService(NetworkNode networkNode,
                  PeerManager peerManager,
                  P2PDataStorage p2PDataStorage,
                  RequestDataManager requestDataManager,
                  PeerExchangeManager peerExchangeManager,
                  KeepAliveManager keepAliveManager,
                  Broadcaster broadcaster,
                  SeedNodeRepository seedNodeRepository,
                  Socks5ProxyProvider socks5ProxyProvider,
                  EncryptionService encryptionService,
                  KeyRing keyRing) {
    this.networkNode = networkNode;
    this.peerManager = peerManager;
    this.p2PDataStorage = p2PDataStorage;
    this.requestDataManager = requestDataManager;
    this.peerExchangeManager = peerExchangeManager;
    this.keepAliveManager = keepAliveManager;
    this.broadcaster = broadcaster;
    this.seedNodeRepository = seedNodeRepository;
    this.socks5ProxyProvider = socks5ProxyProvider;
    this.encryptionService = encryptionService;
    this.keyRing = keyRing;

    this.networkNode.addConnectionListener(this);
    this.networkNode.addMessageListener(this);
    this.p2PDataStorage.addHashMapChangedListener(this);
    this.requestDataManager.addListener(this);

    // We need to have both the initial data delivered and the hidden service published
    networkReadyBinding = EasyBind.combine(hiddenServicePublished, preliminaryDataReceived,
            (hiddenServicePublished, preliminaryDataReceived)
                    -> hiddenServicePublished && preliminaryDataReceived);
    networkReadySubscription = networkReadyBinding.subscribe((observable, oldValue, newValue) -> {
        if (newValue)
            onNetworkReady();
    });
}
 
Example #21
Source File: TorNetworkNode.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
public void shutDown(@Nullable Runnable shutDownCompleteHandler) {
    // this one is executed synchronously
    BooleanProperty networkNodeShutDown = networkNodeShutDown();
    // this one is committed as a thread to the executor
    BooleanProperty torNetworkNodeShutDown = torNetworkNodeShutDown();
    BooleanProperty shutDownTimerTriggered = shutDownTimerTriggered();

    // Need to store allShutDown to not get garbage collected
    allShutDown = EasyBind.combine(torNetworkNodeShutDown, networkNodeShutDown, shutDownTimerTriggered, (a, b, c) -> (a && b) || c);
    allShutDown.subscribe((observable, oldValue, newValue) -> {
        if (newValue) {
            shutDownTimeoutTimer.stop();
            long ts = System.currentTimeMillis();
            log.debug("Shutdown executorService");
            try {
                MoreExecutors.shutdownAndAwaitTermination(executorService, 500, TimeUnit.MILLISECONDS);
                log.debug("Shutdown executorService done after " + (System.currentTimeMillis() - ts) + " ms.");
                log.debug("Shutdown completed");
            } catch (Throwable t) {
                log.error("Shutdown executorService failed with exception: " + t.getMessage());
                t.printStackTrace();
            } finally {
                try {
                    if (shutDownCompleteHandler != null)
                        shutDownCompleteHandler.run();
                } catch (Throwable ignore) {
                }
            }
        }
    });
}
 
Example #22
Source File: BisqSetup.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
private void startP2pNetworkAndWallet() {
    ChangeListener<Boolean> walletInitializedListener = (observable, oldValue, newValue) -> {
        // TODO that seems to be called too often if Tor takes longer to start up...
        if (newValue && !p2pNetworkReady.get() && displayTorNetworkSettingsHandler != null)
            displayTorNetworkSettingsHandler.accept(true);
    };

    Timer startupTimeout = UserThread.runAfter(() -> {
        log.warn("startupTimeout called");
        if (walletsManager.areWalletsEncrypted())
            walletInitialized.addListener(walletInitializedListener);
        else if (displayTorNetworkSettingsHandler != null)
            displayTorNetworkSettingsHandler.accept(true);
    }, STARTUP_TIMEOUT_MINUTES, TimeUnit.MINUTES);

    p2pNetworkReady = p2PNetworkSetup.init(this::initWallet, displayTorNetworkSettingsHandler);

    // We only init wallet service here if not using Tor for bitcoinj.
    // When using Tor, wallet init must be deferred until Tor is ready.
    if (!preferences.getUseTorForBitcoinJ() || bisqEnvironment.isBitcoinLocalhostNodeRunning()) {
        initWallet();
    }

    // need to store it to not get garbage collected
    p2pNetworkAndWalletInitialized = EasyBind.combine(walletInitialized, p2pNetworkReady,
            (a, b) -> {
                log.info("walletInitialized={}, p2pNetWorkReady={}", a, b);
                return a && b;
            });
    p2pNetworkAndWalletInitialized.subscribe((observable, oldValue, newValue) -> {
        if (newValue) {
            startupTimeout.stop();
            walletInitialized.removeListener(walletInitializedListener);
            if (displayTorNetworkSettingsHandler != null)
                displayTorNetworkSettingsHandler.accept(false);
            step5();
        }
    });
}
 
Example #23
Source File: BuyerSetupPayoutTxListener.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();
        if (!trade.isPayoutPublished()) {
            BtcWalletService walletService = processModel.getBtcWalletService();
            final String id = processModel.getOffer().getId();
            Address address = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.TRADE_PAYOUT).getAddress();

            final TransactionConfidence confidence = walletService.getConfidenceForAddress(address);
            if (isInNetwork(confidence)) {
                applyConfidence(confidence);
            } else {
                confidenceListener = new AddressConfidenceListener(address) {
                    @Override
                    public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
                        if (isInNetwork(confidence))
                            applyConfidence(confidence);
                    }
                };
                walletService.addAddressConfidenceListener(confidenceListener);

                tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
                    if (trade.isPayoutPublished()) {
                        swapMultiSigEntry();

                        // hack to remove tradeStateSubscription at callback
                        UserThread.execute(this::unSubscribe);
                    }
                });
            }
        }

        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example #24
Source File: GeneralPane.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
public GeneralPane() {
   FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/preference/GeneralPane.fxml"), bundle);
   loader.setRoot(this);
   loader.setController(this);

   try {
      loader.load();
   }
   catch (Exception ex) {
      LOG.log(Level.SEVERE, "Unable to load FXML", ex);
   }

   // Bind Properties
   BooleanBinding changes[] = {
         chkOpenLastMedia.selectedProperty().isNotEqualTo(Settings.openLastMediaProperty),
         chkSaveEveryChange.selectedProperty().isNotEqualTo(Settings.saveEveryChangeProperty),
         textAnnotationsDir.textProperty().isNotEqualTo(Settings.annotationDirProperty),
         pickerObjectStrokeColor.valueProperty().isNotEqualTo(Settings.objectStrokeColorProperty),
         chkAutoSetName.selectedProperty().isNotEqualTo(Settings.autoSetNameProperty),
         chkAnimateOutline.selectedProperty().isNotEqualTo(Settings.animateOutlineProperty),
         new SimpleListProperty(nameTablePane.getItems()).isNotEqualTo(Settings.recentNamesProperty),
   };
   dirtyProperty.bind(EasyBind.combine(
         FXCollections.observableArrayList(changes), stream -> stream.reduce((a, b) -> a | b).orElse(false)));

   load();
}
 
Example #25
Source File: PolygonItem.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyDoubleProperty getMaxYProperty() {
   if (maxYProperty == null) {
      maxYProperty = new SimpleDoubleProperty();
      maxYProperty.bind(EasyBind.map(boundsInLocalProperty(), Bounds::getMaxY));
   }
   return maxYProperty;
}
 
Example #26
Source File: PolygonItem.java    From OpenLabeler with Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyDoubleProperty getMaxXProperty() {
   if (maxXProperty == null) {
      maxXProperty = new SimpleDoubleProperty();
      maxXProperty.bind(EasyBind.map(boundsInLocalProperty(), Bounds::getMaxX));
   }
   return maxXProperty;
}
 
Example #27
Source File: MainViewModel.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void onSetupComplete() {
    // We handle the trade period here as we display a global popup if we reached dispute time
    tradesAndUIReady = EasyBind.combine(isSplashScreenRemoved, tradeManager.pendingTradesInitializedProperty(), (a, b) -> a && b);
    tradesAndUIReady.subscribe((observable, oldValue, newValue) -> {
        if (newValue) {
            tradeManager.applyTradePeriodState();

            tradeManager.getTradableList().forEach(trade -> {
                Date maxTradePeriodDate = trade.getMaxTradePeriodDate();
                String key;
                switch (trade.getTradePeriodState()) {
                    case FIRST_HALF:
                        break;
                    case SECOND_HALF:
                        key = "displayHalfTradePeriodOver" + trade.getId();
                        if (DontShowAgainLookup.showAgain(key)) {
                            DontShowAgainLookup.dontShowAgain(key, true);
                            new Popup().warning(Res.get("popup.warning.tradePeriod.halfReached",
                                    trade.getShortId(),
                                    DisplayUtils.formatDateTime(maxTradePeriodDate)))
                                    .show();
                        }
                        break;
                    case TRADE_PERIOD_OVER:
                        key = "displayTradePeriodOver" + trade.getId();
                        if (DontShowAgainLookup.showAgain(key)) {
                            DontShowAgainLookup.dontShowAgain(key, true);
                            new Popup().warning(Res.get("popup.warning.tradePeriod.ended",
                                    trade.getShortId(),
                                    DisplayUtils.formatDateTime(maxTradePeriodDate)))
                                    .show();
                        }
                        break;
                }
            });
        }
    });

    setupP2PNumPeersWatcher();
    setupBtcNumPeersWatcher();

    marketPricePresentation.setup();
    daoPresentation.setup();
    accountPresentation.setup();

    if (DevEnv.isDevMode()) {
        preferences.setShowOwnOffersInOfferBook(true);
        setupDevDummyPaymentAccounts();
    }

    getShowAppScreen().set(true);
}
 
Example #28
Source File: OfferBookView.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void activate() {
    currencyComboBox.setCellFactory(GUIUtil.getTradeCurrencyCellFactory(Res.get("shared.oneOffer"),
            Res.get("shared.multipleOffers"),
            (model.getDirection() == OfferPayload.Direction.BUY ? model.getSellOfferCounts() : model.getBuyOfferCounts())));

    currencyComboBox.setConverter(new CurrencyStringConverter(currencyComboBox));
    currencyComboBox.getEditor().getStyleClass().add("combo-box-editor-bold");

    currencyComboBox.setAutocompleteItems(model.getTradeCurrencies());
    currencyComboBox.setVisibleRowCount(Math.min(currencyComboBox.getItems().size(), 10));

    currencyComboBox.setOnChangeConfirmed(e -> {
        if (currencyComboBox.getEditor().getText().isEmpty())
            currencyComboBox.getSelectionModel().select(SHOW_ALL);
        model.onSetTradeCurrency(currencyComboBox.getSelectionModel().getSelectedItem());
    });

    if (model.showAllTradeCurrenciesProperty.get())
        currencyComboBox.getSelectionModel().select(SHOW_ALL);
    else
        currencyComboBox.getSelectionModel().select(model.getSelectedTradeCurrency());
    currencyComboBox.getEditor().setText(new CurrencyStringConverter(currencyComboBox).toString(currencyComboBox.getSelectionModel().getSelectedItem()));

    volumeColumn.sortableProperty().bind(model.showAllTradeCurrenciesProperty.not());
    priceColumn.sortableProperty().bind(model.showAllTradeCurrenciesProperty.not());
    model.getOfferList().comparatorProperty().bind(tableView.comparatorProperty());
    model.priceSortTypeProperty.addListener((observable, oldValue, newValue) -> priceColumn.setSortType(newValue));
    priceColumn.setSortType(model.priceSortTypeProperty.get());

    amountColumn.sortTypeProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue == TableColumn.SortType.DESCENDING) {
            amountColumn.setComparator(Comparator.comparing(o -> o.getOffer().getAmount(), Comparator.nullsFirst(Comparator.naturalOrder())));
        } else {
            amountColumn.setComparator(Comparator.comparing(o -> o.getOffer().getMinAmount(), Comparator.nullsFirst(Comparator.naturalOrder())));
        }
    });
    volumeColumn.sortTypeProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue == TableColumn.SortType.DESCENDING) {
            volumeColumn.setComparator(Comparator.comparing(o -> o.getOffer().getVolume(), Comparator.nullsFirst(Comparator.naturalOrder())));
        } else {
            volumeColumn.setComparator(Comparator.comparing(o -> o.getOffer().getMinVolume(), Comparator.nullsFirst(Comparator.naturalOrder())));
        }
    });

    paymentMethodComboBox.setConverter(new PaymentMethodStringConverter(paymentMethodComboBox));
    paymentMethodComboBox.getEditor().getStyleClass().add("combo-box-editor-bold");

    paymentMethodComboBox.setAutocompleteItems(model.getPaymentMethods());
    paymentMethodComboBox.setVisibleRowCount(Math.min(paymentMethodComboBox.getItems().size(), 10));

    paymentMethodComboBox.setOnChangeConfirmed(e -> {
        if (paymentMethodComboBox.getEditor().getText().isEmpty())
            paymentMethodComboBox.getSelectionModel().select(SHOW_ALL);
        model.onSetPaymentMethod(paymentMethodComboBox.getSelectionModel().getSelectedItem());
        updateSigningStateColumn();
    });

    if (model.showAllPaymentMethods)
        paymentMethodComboBox.getSelectionModel().select(SHOW_ALL);
    else
        paymentMethodComboBox.getSelectionModel().select(model.selectedPaymentMethod);
    paymentMethodComboBox.getEditor().setText(new PaymentMethodStringConverter(paymentMethodComboBox).toString(paymentMethodComboBox.getSelectionModel().getSelectedItem()));

    createOfferButton.setOnAction(e -> onCreateOffer());

    MonadicBinding<Void> currencySelectionBinding = EasyBind.combine(
            model.showAllTradeCurrenciesProperty, model.tradeCurrencyCode,
            (showAll, code) -> {
                setDirectionTitles();
                if (showAll) {
                    volumeColumn.setTitleWithHelpText(Res.get("shared.amountMinMax"), Res.get("shared.amountHelp"));
                    priceColumn.setTitle(Res.get("shared.price"));
                    priceColumn.getStyleClass().remove("first-column");

                    if (!tableView.getColumns().contains(marketColumn))
                        tableView.getColumns().add(0, marketColumn);
                } else {
                    volumeColumn.setTitleWithHelpText(Res.get("offerbook.volume", code), Res.get("shared.amountHelp"));
                    priceColumn.setTitle(CurrencyUtil.getPriceWithCurrencyCode(code));
                    priceColumn.getStyleClass().add("first-column");

                    tableView.getColumns().remove(marketColumn);
                }

                updateSigningStateColumn();

                return null;
            });

    currencySelectionSubscriber = currencySelectionBinding.subscribe((observable, oldValue, newValue) -> {
    });

    tableView.setItems(model.getOfferList());

    model.getOfferList().addListener(offerListListener);
    nrOfOffersLabel.setText(Res.get("offerbook.nrOffers", model.getOfferList().size()));

    model.priceFeedService.updateCounterProperty().addListener(priceFeedUpdateCounterListener);
}
 
Example #29
Source File: BuyerSetupDepositTxListener.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void run() {
    try {
        runInterceptHook();

        if (trade.getDepositTx() == null && processModel.getPreparedDepositTx() != null) {
            BtcWalletService walletService = processModel.getBtcWalletService();
            final NetworkParameters params = walletService.getParams();
            Transaction preparedDepositTx = new Transaction(params, processModel.getPreparedDepositTx());
            checkArgument(!preparedDepositTx.getOutputs().isEmpty(), "preparedDepositTx.getOutputs() must not be empty");
            Address depositTxAddress = preparedDepositTx.getOutput(0).getAddressFromP2SH(params);
            final TransactionConfidence confidence = walletService.getConfidenceForAddress(depositTxAddress);
            if (isInNetwork(confidence)) {
                applyConfidence(confidence);
            } else {
                confidenceListener = new AddressConfidenceListener(depositTxAddress) {
                    @Override
                    public void onTransactionConfidenceChanged(TransactionConfidence confidence) {
                        if (isInNetwork(confidence))
                            applyConfidence(confidence);
                    }
                };
                walletService.addAddressConfidenceListener(confidenceListener);

                tradeStateSubscription = EasyBind.subscribe(trade.stateProperty(), newValue -> {
                    if (trade.isDepositPublished()) {
                        swapReservedForTradeEntry();

                        // hack to remove tradeStateSubscription at callback
                        UserThread.execute(this::unSubscribe);
                    }
                });
            }
        }

        // we complete immediately, our object stays alive because the balanceListener is stored in the WalletService
        complete();
    } catch (Throwable t) {
        failed(t);
    }
}
 
Example #30
Source File: NetworkSettingsView.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void activate() {
    bitcoinPeersToggleGroup.selectedToggleProperty().addListener(bitcoinPeersToggleGroupListener);

    if (filterManager.getFilter() != null)
        applyPreventPublicBtcNetwork();

    filterManager.filterProperty().addListener(filterPropertyListener);

    useTorForBtcJCheckBox.setSelected(preferences.getUseTorForBitcoinJ());
    useTorForBtcJCheckBox.setOnAction(event -> {
        boolean selected = useTorForBtcJCheckBox.isSelected();
        if (selected != preferences.getUseTorForBitcoinJ()) {
            new Popup().information(Res.get("settings.net.needRestart"))
                    .actionButtonText(Res.get("shared.applyAndShutDown"))
                    .onAction(() -> {
                        preferences.setUseTorForBitcoinJ(selected);
                        UserThread.runAfter(BisqApp.getShutDownHandler(), 500, TimeUnit.MILLISECONDS);
                    })
                    .closeButtonText(Res.get("shared.cancel"))
                    .onClose(() -> useTorForBtcJCheckBox.setSelected(!selected))
                    .show();
        }
    });

    reSyncSPVChainButton.setOnAction(event -> GUIUtil.reSyncSPVChain(preferences));

    bitcoinPeersSubscription = EasyBind.subscribe(walletsSetup.connectedPeersProperty(),
            connectedPeers -> updateBitcoinPeersTable());

    bitcoinBlocksDownloadedSubscription = EasyBind.subscribe(walletsSetup.blocksDownloadedFromPeerProperty(),
            peer -> updateBitcoinPeersTable());

    bitcoinBlockHeightSubscription = EasyBind.subscribe(walletsSetup.chainHeightProperty(),
            chainHeight -> updateBitcoinPeersTable());

    nodeAddressSubscription = EasyBind.subscribe(p2PService.getNetworkNode().nodeAddressProperty(),
            nodeAddress -> onionAddress.setText(nodeAddress == null ?
                    Res.get("settings.net.notKnownYet") :
                    nodeAddress.getFullAddress()));
    numP2PPeersSubscription = EasyBind.subscribe(p2PService.getNumConnectedPeers(), numPeers -> updateP2PTable());
    totalTrafficTextField.textProperty().bind(EasyBind.combine(Statistic.totalSentBytesProperty(),
            Statistic.totalReceivedBytesProperty(),
            (sent, received) -> Res.get("settings.net.sentReceived",
                    FormattingUtils.formatBytes((long) sent),
                    FormattingUtils.formatBytes((long) received))));

    bitcoinSortedList.comparatorProperty().bind(bitcoinPeersTableView.comparatorProperty());
    bitcoinPeersTableView.setItems(bitcoinSortedList);

    p2pSortedList.comparatorProperty().bind(p2pPeersTableView.comparatorProperty());
    p2pPeersTableView.setItems(p2pSortedList);

    btcNodesInputTextField.setText(preferences.getBitcoinNodes());

    btcNodesInputTextField.focusedProperty().addListener(btcNodesInputTextFieldFocusListener);

    openTorSettingsButton.setOnAction(e -> torNetworkSettingsWindow.show());
}