Rename network map visualiser to simulator

This commit is contained in:
Ross Nicoll
2016-09-16 10:57:38 +01:00
parent 94eee5acbc
commit 5a8ad0a6dd
25 changed files with 1 additions and 1 deletions

View File

@ -0,0 +1,59 @@
buildscript {
repositories {
mavenCentral()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
apply plugin: 'us.kirchmeier.capsule'
group 'com.r3cev.prototyping'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.5
repositories {
mavenLocal()
mavenCentral()
jcenter()
maven {
url 'http://oss.sonatype.org/content/repositories/snapshots'
}
maven {
url 'https://dl.bintray.com/kotlin/exposed'
}
}
applicationDefaultJvmArgs = ["-javaagent:${rootProject.configurations.quasar.singleFile}"]
mainClassName = 'com.r3cev.corda.netmap.NetworkMapVisualiserKt'
dependencies {
compile project(":core")
compile project(":node")
compile project(":contracts")
compile rootProject
// GraphStream: For visualisation
compile "org.graphstream:gs-core:1.3"
compile "org.graphstream:gs-ui:1.3"
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile group: 'junit', name: 'junit', version: '4.11'
}
task capsule(type: FatCapsule) {
applicationClass 'com.r3cev.corda.netmap.NetworkExplorerKt'
reallyExecutable
capsuleManifest {
minJavaVersion = '1.8.0'
javaAgents = [rootProject.configurations.quasar.singleFile.name]
}
}

View File

@ -0,0 +1,365 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
package com.r3cev.corda.netmap
import com.r3corda.core.messaging.SingleMessageRecipient
import com.r3corda.core.then
import com.r3corda.core.utilities.ProgressTracker
import com.r3corda.testing.node.InMemoryMessagingNetwork
import com.r3corda.testing.node.MockNetwork
import com.r3corda.simulation.IRSSimulation
import com.r3corda.simulation.Simulation
import com.r3corda.node.services.network.NetworkMapService
import javafx.animation.*
import javafx.application.Application
import javafx.application.Platform
import javafx.beans.property.SimpleDoubleProperty
import javafx.beans.value.WritableValue
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.*
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.shape.Line
import javafx.scene.shape.Polygon
import javafx.stage.Stage
import javafx.util.Duration
import rx.Scheduler
import rx.schedulers.Schedulers
import java.nio.file.Files
import java.nio.file.Paths
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.*
import kotlin.concurrent.schedule
import kotlin.concurrent.scheduleAtFixedRate
import kotlin.system.exitProcess
import com.r3cev.corda.netmap.VisualiserViewModel.Style
fun <T : Any> WritableValue<T>.keyValue(endValue: T, interpolator: Interpolator = Interpolator.EASE_OUT) = KeyValue(this, endValue, interpolator)
// TODO: This code is all horribly ugly. Refactor to use TornadoFX to clean it up.
class NetworkMapVisualiser : Application() {
enum class NodeType {
BANK, SERVICE
}
enum class RunPauseButtonLabel {
RUN, PAUSE;
override fun toString(): String {
return name.toLowerCase().capitalize()
}
}
sealed class RunningPausedState {
class Running(val tickTimer: TimerTask): RunningPausedState()
class Paused(): RunningPausedState()
val buttonLabel: RunPauseButtonLabel
get() {
return when (this) {
is RunningPausedState.Running -> RunPauseButtonLabel.PAUSE
is RunningPausedState.Paused -> RunPauseButtonLabel.RUN
}
}
}
private val view = VisualiserView()
private val viewModel = VisualiserViewModel()
val timer = Timer()
val uiThread: Scheduler = Schedulers.from { Platform.runLater(it) }
override fun start(stage: Stage) {
viewModel.view = view
viewModel.presentationMode = "--presentation-mode" in parameters.raw
buildScene(stage)
viewModel.displayStyle = if ("--circle" in parameters.raw) { Style.CIRCLE } else { viewModel.displayStyle }
val simulation = viewModel.simulation
// Update the white-backgrounded label indicating what protocol step it's up to.
simulation.allProtocolSteps.observeOn(uiThread).subscribe { step: Pair<Simulation.SimulatedNode, ProgressTracker.Change> ->
val (node, change) = step
val label = viewModel.nodesToWidgets[node]!!.statusLabel
if (change is ProgressTracker.Change.Position) {
// Fade in the status label if it's our first step.
if (label.text == "") {
with(FadeTransition(Duration(150.0), label)) {
fromValue = 0.0
toValue = 1.0
play()
}
}
label.text = change.newStep.label
if (change.newStep == ProgressTracker.DONE && change.tracker == change.tracker.topLevelTracker) {
runLater(500, -1) {
// Fade out the status label.
with(FadeTransition(Duration(750.0), label)) {
fromValue = 1.0
toValue = 0.0
setOnFinished { label.text = "" }
play()
}
}
}
} else if (change is ProgressTracker.Change.Rendering) {
label.text = change.ofStep.label
}
}
// Fire the message bullets between nodes.
simulation.network.messagingNetwork.sentMessages.observeOn(uiThread).subscribe { msg: InMemoryMessagingNetwork.MessageTransfer ->
val senderNode: MockNetwork.MockNode = simulation.network.addressToNode(msg.sender.myAddress)
val destNode: MockNetwork.MockNode = simulation.network.addressToNode(msg.recipients as SingleMessageRecipient)
if (transferIsInteresting(msg)) {
viewModel.nodesToWidgets[senderNode]!!.pulseAnim.play()
viewModel.fireBulletBetweenNodes(senderNode, destNode, "bank", "bank")
}
}
// Pulse all parties in a trade when the trade completes
simulation.doneSteps.observeOn(uiThread).subscribe { nodes: Collection<Simulation.SimulatedNode> ->
nodes.forEach { viewModel.nodesToWidgets[it]!!.longPulseAnim.play() }
}
stage.setOnCloseRequest { exitProcess(0) }
//stage.isMaximized = true
stage.show()
}
fun runLater(startAfter: Int, delayBetween: Int, body: () -> Unit) {
if (delayBetween != -1) {
timer.scheduleAtFixedRate(startAfter.toLong(), delayBetween.toLong()) {
Platform.runLater {
body()
}
}
} else {
timer.schedule(startAfter.toLong()) {
Platform.runLater {
body()
}
}
}
}
private fun buildScene(stage: Stage) {
view.stage = stage
view.setup(viewModel.runningPausedState, viewModel.displayStyle, viewModel.presentationMode)
bindSidebar()
bindTopbar()
viewModel.createNodes()
// Spacebar advances simulation by one step.
stage.scene.accelerators[KeyCodeCombination(KeyCode.SPACE)] = Runnable { onNextInvoked() }
reloadStylesheet(stage)
stage.focusedProperty().addListener { value, old, new ->
if (new) {
reloadStylesheet(stage)
}
}
}
private fun bindTopbar() {
view.resetButton.setOnAction({reset()})
view.nextButton.setOnAction {
if (!view.simulateInitialisationCheckbox.isSelected && !viewModel.simulation.networkInitialisationFinished.isDone) {
skipNetworkInitialisation()
} else {
onNextInvoked()
}
}
viewModel.simulation.networkInitialisationFinished.then {
view.simulateInitialisationCheckbox.isVisible = false
}
view.runPauseButton.setOnAction {
val oldRunningPausedState = viewModel.runningPausedState
val newRunningPausedState = when (oldRunningPausedState) {
is NetworkMapVisualiser.RunningPausedState.Running -> {
oldRunningPausedState.tickTimer.cancel()
view.nextButton.isDisable = false
view.resetButton.isDisable = false
NetworkMapVisualiser.RunningPausedState.Paused()
}
is NetworkMapVisualiser.RunningPausedState.Paused -> {
val tickTimer = timer.scheduleAtFixedRate(viewModel.stepDuration.toMillis().toLong(), viewModel.stepDuration.toMillis().toLong()) {
Platform.runLater {
onNextInvoked()
}
}
view.nextButton.isDisable = true
view.resetButton.isDisable = true
if (!view.simulateInitialisationCheckbox.isSelected && !viewModel.simulation.networkInitialisationFinished.isDone) {
skipNetworkInitialisation()
}
NetworkMapVisualiser.RunningPausedState.Running(tickTimer)
}
}
view.runPauseButton.text = newRunningPausedState.buttonLabel.toString()
viewModel.runningPausedState = newRunningPausedState
}
view.styleChoice.selectionModel.selectedItemProperty()
.addListener { ov, value, newValue -> viewModel.displayStyle = newValue }
viewModel.simulation.dateChanges.observeOn(uiThread).subscribe { view.dateLabel.text = it.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)) }
}
private fun reloadStylesheet(stage: Stage) {
stage.scene.stylesheets.clear()
// TODO: Improve path resolution to avoid hardcoding a specific user directory.
// Enable hot reload without needing to rebuild.
val mikesCSS = "/Users/mike/Source/R3/r3dlg-prototyping/network-explorer/src/main/resources/com/r3cev/corda/netmap/styles.css"
if (Files.exists(Paths.get(mikesCSS)))
stage.scene.stylesheets.add("file://$mikesCSS")
else
stage.scene.stylesheets.add(NetworkMapVisualiser::class.java.getResource("styles.css").toString())
}
private fun bindSidebar() {
viewModel.simulation.allProtocolSteps.observeOn(uiThread).subscribe { step: Pair<Simulation.SimulatedNode, ProgressTracker.Change> ->
val (node, change) = step
if (change is ProgressTracker.Change.Position) {
val tracker = change.tracker.topLevelTracker
if (change.newStep == ProgressTracker.DONE) {
if (change.tracker == tracker) {
// Protocol done; schedule it for removal in a few seconds. We batch them up to make nicer
// animations.
println("Protocol done for ${node.info.identity.name}")
viewModel.doneTrackers += tracker
} else {
// Subprotocol is done; ignore it.
}
} else if (!viewModel.trackerBoxes.containsKey(tracker)) {
// New protocol started up; add.
val extraLabel = viewModel.simulation.extraNodeLabels[node]
val label = if (extraLabel != null) "${node.storage.myLegalIdentity.name}: $extraLabel" else node.storage.myLegalIdentity.name
val widget = view.buildProgressTrackerWidget(label, tracker.topLevelTracker)
bindProgressTracketWidget(tracker.topLevelTracker, widget)
println("Added: ${tracker}, ${widget}")
viewModel.trackerBoxes[tracker] = widget.vbox
view.sidebar.children += widget.vbox
}
}
}
Timer().scheduleAtFixedRate(0, 500) {
Platform.runLater {
for (tracker in viewModel.doneTrackers) {
val pane = viewModel.trackerBoxes[tracker]!!
// Slide the other tracker widgets up and over this one.
val slideProp = SimpleDoubleProperty(0.0)
slideProp.addListener { obv -> pane.padding = Insets(0.0, 0.0, slideProp.value, 0.0) }
val timeline = Timeline(
KeyFrame(Duration(250.0),
KeyValue(pane.opacityProperty(), 0.0),
KeyValue(slideProp, -pane.height - 50.0) // Subtract the bottom padding gap.
)
)
timeline.setOnFinished {
println("Removed: ${tracker}")
val vbox = viewModel.trackerBoxes.remove(tracker)
view.sidebar.children.remove(vbox)
}
timeline.play()
}
viewModel.doneTrackers.clear()
}
}
}
private fun bindProgressTracketWidget(tracker: ProgressTracker, widget: TrackerWidget) {
val allSteps: List<Pair<Int, ProgressTracker.Step>> = tracker.allSteps
tracker.changes.observeOn(uiThread).subscribe { step: ProgressTracker.Change ->
val stepHeight = widget.cursorBox.height / allSteps.size
if (step is ProgressTracker.Change.Position) {
// Figure out the index of the new step.
val curStep = allSteps.indexOfFirst { it.second == step.newStep }
// Animate the cursor to the right place.
with(TranslateTransition(Duration(350.0), widget.cursor)) {
fromY = widget.cursor.translateY
toY = (curStep * stepHeight) + 22.5
play()
}
} else if (step is ProgressTracker.Change.Structural) {
val new = view.buildProgressTrackerWidget(widget.label.text, tracker)
val prevWidget = viewModel.trackerBoxes[step.tracker] ?: throw AssertionError("No previous widget for tracker: ${step.tracker}")
val i = (prevWidget.parent as VBox).children.indexOf(viewModel.trackerBoxes[step.tracker])
(prevWidget.parent as VBox).children[i] = new.vbox
viewModel.trackerBoxes[step.tracker] = new.vbox
}
}
}
var started = false
private fun startSimulation() {
if (!started) {
viewModel.simulation.start()
started = true
}
}
private fun reset() {
viewModel.simulation.stop()
viewModel.simulation = IRSSimulation(true, false, null)
started = false
start(view.stage)
}
private fun skipNetworkInitialisation() {
startSimulation()
while (!viewModel.simulation.networkInitialisationFinished.isDone) {
iterateSimulation()
}
}
private fun onNextInvoked() {
if (started) {
iterateSimulation()
} else {
startSimulation()
}
}
private fun iterateSimulation() {
// Loop until either we ran out of things to do, or we sent an interesting message.
while (true) {
val transfer: InMemoryMessagingNetwork.MessageTransfer = viewModel.simulation.iterate() ?: break
if (transferIsInteresting(transfer))
break
else
System.err.println("skipping boring $transfer")
}
}
private fun transferIsInteresting(transfer: InMemoryMessagingNetwork.MessageTransfer): Boolean {
// Loopback messages are boring.
if (transfer.sender.myAddress == transfer.recipients) return false
// Network map push acknowledgements are boring.
if (NetworkMapService.PUSH_ACK_PROTOCOL_TOPIC in transfer.message.topicSession.topic) return false
return true
}
}
fun main(args: Array<String>) {
Application.launch(NetworkMapVisualiser::class.java, *args)
}

View File

@ -0,0 +1,18 @@
package com.r3cev.corda.netmap
import javafx.scene.paint.Color
internal
fun colorToRgb(color: Color): String {
val builder = StringBuilder()
builder.append("rgb(")
builder.append(Math.round(color.red * 256))
builder.append(",")
builder.append(Math.round(color.green * 256))
builder.append(",")
builder.append(Math.round(color.blue * 256))
builder.append(")")
return builder.toString()
}

View File

@ -0,0 +1,304 @@
package com.r3cev.corda.netmap
import com.r3corda.core.utilities.ProgressTracker
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.application.Platform
import javafx.collections.FXCollections
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.ZoomEvent
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.shape.Polygon
import javafx.scene.text.Font
import javafx.stage.Stage
import javafx.util.Duration
import com.r3cev.corda.netmap.VisualiserViewModel.Style
data class TrackerWidget(val vbox: VBox, val cursorBox: Pane, val label: Label, val cursor: Polygon)
internal class VisualiserView() {
lateinit var root: Pane
lateinit var stage: Stage
lateinit var splitter: SplitPane
lateinit var sidebar: VBox
lateinit var resetButton: Button
lateinit var nextButton: Button
lateinit var runPauseButton: Button
lateinit var simulateInitialisationCheckbox: CheckBox
lateinit var styleChoice: ChoiceBox<Style>
var dateLabel = Label("")
var scrollPane: ScrollPane? = null
var hideButton = Button("«").apply { styleClass += "hide-sidebar-button" }
// -23.2031,29.8406,33.0469,64.3209
val mapImage = ImageView(Image(NetworkMapVisualiser::class.java.getResourceAsStream("Europe.jpg")))
val backgroundColor: Color = mapImage.image.pixelReader.getColor(0, 0)
val stageWidth = 1024.0
val stageHeight = 768.0
var defaultZoom = 0.7
val bitmapWidth = 1900.0
val bitmapHeight = 1900.0
fun setup(runningPausedState: NetworkMapVisualiser.RunningPausedState,
displayStyle: Style,
presentationMode: Boolean) {
NetworkMapVisualiser::class.java.getResourceAsStream("SourceSansPro-Regular.otf").use {
Font.loadFont(it, 120.0)
}
if(displayStyle == Style.MAP) {
mapImage.onZoom = EventHandler<javafx.scene.input.ZoomEvent> { event ->
event.consume()
mapImage.fitWidth = mapImage.fitWidth * event.zoomFactor
mapImage.fitHeight = mapImage.fitHeight * event.zoomFactor
//repositionNodes()
}
}
scaleMap(displayStyle);
root = Pane(mapImage)
root.background = Background(BackgroundFill(backgroundColor, CornerRadii.EMPTY, Insets.EMPTY))
scrollPane = buildScrollPane(backgroundColor, displayStyle)
val vbox = makeTopBar(runningPausedState, displayStyle, presentationMode)
StackPane.setAlignment(vbox, Pos.TOP_CENTER)
// Now build the sidebar
val defaultSplitterPosition = 0.3
splitter = SplitPane(makeSidebar(), scrollPane)
splitter.styleClass += "splitter"
Platform.runLater {
splitter.dividers[0].position = defaultSplitterPosition
}
VBox.setVgrow(splitter, Priority.ALWAYS)
// And the left hide button.
hideButton = makeHideButton(defaultSplitterPosition)
val screenStack = VBox(vbox, StackPane(splitter, hideButton))
screenStack.styleClass += "root-pane"
stage.scene = Scene(screenStack, backgroundColor)
stage.width = 1024.0
stage.height = 768.0
}
fun buildScrollPane(backgroundColor: Color, displayStyle: Style): ScrollPane {
when (displayStyle) {
Style.MAP -> {
mapImage.fitWidth = bitmapWidth * defaultZoom
mapImage.fitHeight = bitmapHeight * defaultZoom
mapImage.onZoom = EventHandler<ZoomEvent> { event ->
event.consume()
mapImage.fitWidth = mapImage.fitWidth * event.zoomFactor
mapImage.fitHeight = mapImage.fitHeight * event.zoomFactor
}
}
Style.CIRCLE -> {
val scaleRatio = Math.min(stageWidth / bitmapWidth, stageHeight / bitmapHeight)
mapImage.fitWidth = bitmapWidth * scaleRatio
mapImage.fitHeight = bitmapHeight * scaleRatio
}
}
return ScrollPane(Group(root)).apply {
when (displayStyle) {
Style.MAP -> {
hvalue = 0.4
vvalue = 0.7
}
Style.CIRCLE -> {
hvalue = 0.0
vvalue = 0.0
}
}
hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER
vbarPolicy = ScrollPane.ScrollBarPolicy.NEVER
isPannable = true
isFocusTraversable = false
style = "-fx-background-color: " + colorToRgb(backgroundColor)
styleClass += "edge-to-edge"
}
}
fun makeHideButton(defaultSplitterPosition: Double): Button {
var hideButtonToggled = false
hideButton.isFocusTraversable = false
hideButton.setOnAction {
if (!hideButtonToggled) {
hideButton.translateXProperty().unbind()
Timeline(
KeyFrame(Duration.millis(500.0),
splitter.dividers[0].positionProperty().keyValue(0.0),
hideButton.translateXProperty().keyValue(0.0),
hideButton.rotateProperty().keyValue(180.0)
)
).play()
} else {
bindHideButtonPosition()
Timeline(
KeyFrame(Duration.millis(500.0),
splitter.dividers[0].positionProperty().keyValue(defaultSplitterPosition),
hideButton.rotateProperty().keyValue(0.0)
)
).play()
}
hideButtonToggled = !hideButtonToggled
}
bindHideButtonPosition()
StackPane.setAlignment(hideButton, Pos.TOP_LEFT)
return hideButton
}
fun bindHideButtonPosition() {
hideButton.translateXProperty().unbind()
hideButton.translateXProperty().bind(splitter.dividers[0].positionProperty().multiply(splitter.widthProperty()).subtract(hideButton.widthProperty()))
}
fun scaleMap(displayStyle: Style) {
when (displayStyle) {
Style.MAP -> {
mapImage.fitWidth = bitmapWidth * defaultZoom
mapImage.fitHeight = bitmapHeight * defaultZoom
}
Style.CIRCLE -> {
val scaleRatio = Math.min(stageWidth / bitmapWidth, stageHeight / bitmapHeight)
mapImage.fitWidth = bitmapWidth * scaleRatio
mapImage.fitHeight = bitmapHeight * scaleRatio
}
}
}
fun makeSidebar(): Node {
sidebar = VBox()
sidebar.styleClass += "sidebar"
sidebar.isFillWidth = true
val sp = ScrollPane(sidebar)
sp.isFitToWidth = true
sp.isFitToHeight = true
sp.styleClass += "sidebar"
sp.hbarPolicy = ScrollPane.ScrollBarPolicy.NEVER
sp.vbarPolicy = ScrollPane.ScrollBarPolicy.NEVER
sp.minWidth = 0.0
return sp
}
fun makeTopBar(runningPausedState: NetworkMapVisualiser.RunningPausedState,
displayStyle: Style,
presentationMode: Boolean): VBox {
nextButton = Button("Next").apply {
styleClass += "button"
styleClass += "next-button"
}
runPauseButton = Button(runningPausedState.buttonLabel.toString()).apply {
styleClass += "button"
styleClass += "run-button"
}
simulateInitialisationCheckbox = CheckBox("Simulate initialisation")
resetButton = Button("Reset").apply {
styleClass += "button"
styleClass += "reset-button"
}
val displayStyles = FXCollections.observableArrayList<Style>()
Style.values().forEach { displayStyles.add(it) }
styleChoice = ChoiceBox(displayStyles).apply {
styleClass += "choice"
styleClass += "style-choice"
}
styleChoice.value = displayStyle
val dropShadow = Pane().apply { styleClass += "drop-shadow-pane-horizontal"; minHeight = 8.0 }
val logoImage = ImageView(javaClass.getResource("R3 logo.png").toExternalForm())
logoImage.fitHeight = 65.0
logoImage.isPreserveRatio = true
val logoLabel = HBox(logoImage, VBox(
Label("D I S T R I B U T E D L E D G E R G R O U P").apply { styleClass += "dlg-label" },
Label("Network Simulator").apply { styleClass += "logo-label" }
))
logoLabel.spacing = 10.0
HBox.setHgrow(logoLabel, Priority.ALWAYS)
logoLabel.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_PREF_SIZE)
dateLabel = Label("").apply { styleClass += "date-label" }
// Buttons area. In presentation mode there are no controls visible and you must use the keyboard.
val hbox = if (presentationMode) {
HBox(logoLabel, dateLabel).apply { styleClass += "controls-hbox" }
} else {
HBox(logoLabel, dateLabel, simulateInitialisationCheckbox, runPauseButton, nextButton, resetButton, styleChoice).apply { styleClass += "controls-hbox" }
}
hbox.styleClass += "fat-buttons"
hbox.spacing = 20.0
hbox.alignment = Pos.CENTER_RIGHT
hbox.padding = Insets(10.0, 20.0, 10.0, 20.0)
val vbox = VBox(hbox, dropShadow)
vbox.styleClass += "controls-vbox"
vbox.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE)
vbox.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_PREF_SIZE)
return vbox
}
// TODO: Extract this to a real widget.
fun buildProgressTrackerWidget(label: String, tracker: ProgressTracker): TrackerWidget {
val allSteps: List<Pair<Int, ProgressTracker.Step>> = tracker.allSteps
val stepsBox = VBox().apply {
styleClass += "progress-tracker-widget-steps"
}
for ((indent, step) in allSteps) {
val stepLabel = Label(step.label).apply { padding = Insets(0.0, 0.0, 0.0, indent * 15.0) }
stepsBox.children += StackPane(stepLabel)
}
val arrowSize = 7.0
val cursor = Polygon(-arrowSize, -arrowSize, arrowSize, 0.0, -arrowSize, arrowSize).apply {
styleClass += "progress-tracker-cursor"
}
val cursorBox = Pane(cursor).apply {
styleClass += "progress-tracker-cursor-box"
minWidth = 25.0
}
val curStep = allSteps.indexOfFirst { it.second == tracker.currentStep }
Platform.runLater {
val stepHeight = cursorBox.height / allSteps.size
cursor.translateY = (curStep * stepHeight) + 20.0
}
val vbox: VBox?
HBox.setHgrow(stepsBox, Priority.ALWAYS)
val content = HBox(cursorBox, stepsBox)
// Make the title bar
val title = Label(label).apply { styleClass += "sidebar-title-label" }
StackPane.setAlignment(title, Pos.CENTER_LEFT)
vbox = VBox(StackPane(title), content)
vbox.padding = Insets(0.0, 0.0, 25.0, 0.0)
return TrackerWidget(vbox, cursorBox, title, cursor)
}
/**
* Update the current display style. MUST only be called on the UI
* thread.
*/
fun updateDisplayStyle(displayStyle: Style) {
requireNotNull(splitter)
splitter.items.remove(scrollPane!!)
scrollPane = buildScrollPane(backgroundColor, displayStyle)
splitter.items.add(scrollPane!!)
splitter.dividers[0].position = 0.3
mapImage.isVisible = when (displayStyle) {
Style.MAP -> true
Style.CIRCLE -> false
}
// TODO: Can any current bullets be re-routed in flight?
}
}

View File

@ -0,0 +1,222 @@
package com.r3cev.corda.netmap
import com.r3corda.core.utilities.ProgressTracker
import com.r3corda.testing.node.MockNetwork
import com.r3corda.simulation.IRSSimulation
import javafx.animation.*
import javafx.geometry.Pos
import javafx.scene.control.Label
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.scene.shape.Circle
import javafx.scene.shape.Line
import javafx.util.Duration
import java.util.*
class VisualiserViewModel {
enum class Style {
MAP, CIRCLE;
override fun toString(): String {
return name.toLowerCase().capitalize()
}
}
inner class NodeWidget(val node: MockNetwork.MockNode, val innerDot: Circle, val outerDot: Circle, val longPulseDot: Circle,
val pulseAnim: Animation, val longPulseAnim: Animation,
val nameLabel: Label, val statusLabel: Label) {
fun position(index: Int, nodeCoords: (node: MockNetwork.MockNode, index: Int) -> Pair<Double, Double>) {
val (x, y) = nodeCoords(node, index)
innerDot.centerX = x
innerDot.centerY = y
outerDot.centerX = x
outerDot.centerY = y
longPulseDot.centerX = x
longPulseDot.centerY = y
(nameLabel.parent as StackPane).relocate(x - 270.0, y - 10.0)
(statusLabel.parent as StackPane).relocate(x + 20.0, y - 10.0)
}
}
internal lateinit var view: VisualiserView
var presentationMode: Boolean = false
var simulation = IRSSimulation(true, false, null) // Manually pumped.
val trackerBoxes = HashMap<ProgressTracker, Pane>()
val doneTrackers = ArrayList<ProgressTracker>()
val nodesToWidgets = HashMap<MockNetwork.MockNode, NodeWidget>()
var bankCount: Int = 0
var serviceCount: Int = 0
var stepDuration = Duration.millis(500.0)
var runningPausedState: NetworkMapVisualiser.RunningPausedState = NetworkMapVisualiser.RunningPausedState.Paused()
var displayStyle: Style = Style.MAP
set(value) {
field = value
view.updateDisplayStyle(value)
repositionNodes()
view.bindHideButtonPosition()
}
fun repositionNodes() {
for ((index, bank) in simulation.banks.withIndex()) {
nodesToWidgets[bank]!!.position(index, when (displayStyle) {
Style.MAP -> { node, index -> nodeMapCoords(node) }
Style.CIRCLE -> { node, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.BANK, index) }
})
}
for ((index, serviceProvider) in (simulation.serviceProviders + simulation.regulators).withIndex()) {
nodesToWidgets[serviceProvider]!!.position(index, when (displayStyle) {
Style.MAP -> { node, index -> nodeMapCoords(node) }
Style.CIRCLE -> { node, index -> nodeCircleCoords(NetworkMapVisualiser.NodeType.SERVICE, index) }
})
}
}
fun nodeMapCoords(node: MockNetwork.MockNode): Pair<Double, Double> {
// For an image of the whole world, we use:
// return node.place.coordinate.project(mapImage.fitWidth, mapImage.fitHeight, 85.0511, -85.0511, -180.0, 180.0)
// For Europe, our bounds are: (lng,lat)
// bottom left: -23.2031,29.8406
// top right: 33.0469,64.3209
try {
return node.place.coordinate.project(view.mapImage.fitWidth, view.mapImage.fitHeight, 64.3209, 29.8406, -23.2031, 33.0469)
} catch(e: Exception) {
throw Exception("Cannot project ${node.info.identity}", e)
}
}
fun nodeCircleCoords(type: NetworkMapVisualiser.NodeType, index: Int): Pair<Double, Double> {
val stepRad: Double = when(type) {
NetworkMapVisualiser.NodeType.BANK -> 2 * Math.PI / bankCount
NetworkMapVisualiser.NodeType.SERVICE -> (2 * Math.PI / serviceCount)
}
val tangentRad: Double = stepRad * index + when(type) {
NetworkMapVisualiser.NodeType.BANK -> 0.0
NetworkMapVisualiser.NodeType.SERVICE -> Math.PI / 2
}
val radius = when (type) {
NetworkMapVisualiser.NodeType.BANK -> Math.min(view.stageWidth, view.stageHeight) / 3.5
NetworkMapVisualiser.NodeType.SERVICE -> Math.min(view.stageWidth, view.stageHeight) / 8
}
val xOffset = -220
val yOffset = -80
val circleX = view.stageWidth / 2 + xOffset
val circleY = view.stageHeight / 2 + yOffset
val x: Double = radius * Math.cos(tangentRad) + circleX;
val y: Double = radius * Math.sin(tangentRad) + circleY;
return Pair(x, y)
}
fun createNodes() {
bankCount = simulation.banks.size
serviceCount = simulation.serviceProviders.size + simulation.regulators.size
for ((index, bank) in simulation.banks.withIndex()) {
nodesToWidgets[bank] = makeNodeWidget(bank, "bank", bank.configuration.myLegalName, NetworkMapVisualiser.NodeType.BANK, index)
}
for ((index, service) in simulation.serviceProviders.withIndex()) {
nodesToWidgets[service] = makeNodeWidget(service, "network-service", service.configuration.myLegalName, NetworkMapVisualiser.NodeType.SERVICE, index)
}
for ((index, service) in simulation.regulators.withIndex()) {
nodesToWidgets[service] = makeNodeWidget(service, "regulator", service.configuration.myLegalName, NetworkMapVisualiser.NodeType.SERVICE, index + simulation.serviceProviders.size)
}
}
fun makeNodeWidget(forNode: MockNetwork.MockNode, type: String, label: String = "Bank of Bologna",
nodeType: NetworkMapVisualiser.NodeType, index: Int): NodeWidget {
fun emitRadarPulse(initialRadius: Double, targetRadius: Double, duration: Double): Pair<Circle, Animation> {
val pulse = Circle(initialRadius).apply {
styleClass += "node-$type"
styleClass += "node-circle-pulse"
}
val animation = Timeline(
KeyFrame(Duration.seconds(0.0),
pulse.radiusProperty().keyValue(initialRadius),
pulse.opacityProperty().keyValue(1.0)
),
KeyFrame(Duration.seconds(duration),
pulse.radiusProperty().keyValue(targetRadius),
pulse.opacityProperty().keyValue(0.0)
)
)
return Pair(pulse, animation)
}
val innerDot = Circle(10.0).apply {
styleClass += "node-$type"
styleClass += "node-circle-inner"
}
val (outerDot, pulseAnim) = emitRadarPulse(10.0, 50.0, 0.45)
val (longPulseOuterDot, longPulseAnim) = emitRadarPulse(10.0, 100.0, 1.45)
view.root.children += outerDot
view.root.children += longPulseOuterDot
view.root.children += innerDot
val nameLabel = Label(label)
val nameLabelRect = StackPane(nameLabel).apply {
styleClass += "node-label"
alignment = Pos.CENTER_RIGHT
// This magic min width depends on the longest label of all nodes we may have, which we aren't calculating.
// TODO: Dynamically adjust it depending on the longest label to display.
minWidth = 250.0
}
view.root.children += nameLabelRect
val statusLabel = Label("")
val statusLabelRect = StackPane(statusLabel).apply { styleClass += "node-status-label" }
view.root.children += statusLabelRect
val widget = NodeWidget(forNode, innerDot, outerDot, longPulseOuterDot, pulseAnim, longPulseAnim, nameLabel, statusLabel)
when (displayStyle) {
Style.CIRCLE -> widget.position(index, { node, index -> nodeCircleCoords(nodeType, index) } )
Style.MAP -> widget.position(index, { node, index -> nodeMapCoords(node) })
}
return widget
}
fun fireBulletBetweenNodes(senderNode: MockNetwork.MockNode, destNode: MockNetwork.MockNode, startType: String, endType: String) {
val sx = nodesToWidgets[senderNode]!!.innerDot.centerX
val sy = nodesToWidgets[senderNode]!!.innerDot.centerY
val dx = nodesToWidgets[destNode]!!.innerDot.centerX
val dy = nodesToWidgets[destNode]!!.innerDot.centerY
val bullet = Circle(3.0)
bullet.styleClass += "bullet"
bullet.styleClass += "connection-$startType-to-$endType"
with(TranslateTransition(stepDuration, bullet)) {
fromX = sx
fromY = sy
toX = dx
toY = dy
setOnFinished {
// For some reason removing/adding the bullet nodes causes an annoying 1px shift in the map view, so
// to avoid visual distraction we just deliberately leak the bullet node here. Obviously this is a
// memory leak that would break long term usage.
//
// TODO: Find root cause and fix.
//
// root.children.remove(bullet)
bullet.isVisible = false
}
play()
}
val line = Line(sx, sy, dx, dy).apply { styleClass += "message-line" }
// Fade in quick, then fade out slow.
with(FadeTransition(stepDuration.divide(5.0), line)) {
fromValue = 0.0
toValue = 1.0
play()
setOnFinished {
with(FadeTransition(stepDuration.multiply(6.0), line)) { fromValue = 1.0; toValue = 0.0; play() }
}
}
view.root.children.add(1, line)
view.root.children.add(bullet)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<VBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1">
<children>
<HBox alignment="CENTER_RIGHT" prefHeight="0.0" prefWidth="600.0">
<children>
<Button fx:id="nextButton" mnemonicParsing="false" onAction="#onNextClicked" text="Next" />
</children>
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
</padding>
</HBox>
<SplitPane dividerPositions="0.2408026755852843" prefHeight="336.0" prefWidth="600.0" VBox.vgrow="ALWAYS">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
<ScrollPane fx:id="mapView" hbarPolicy="NEVER" pannable="true" prefHeight="200.0" prefWidth="200.0" vbarPolicy="NEVER" />
</items>
</SplitPane>
</children>
</VBox>

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -0,0 +1,43 @@
Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the copyright statement(s).
"Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 469 KiB

View File

@ -0,0 +1,227 @@
/*
* Copyright 2015 Distributed Ledger Group LLC. Distributed as Licensed Company IP to DLG Group Members
* pursuant to the August 7, 2015 Advisory Services Agreement and subject to the Company IP License terms
* set forth therein.
*
* All other rights reserved.
*/
.root-pane {
-fx-font-family: "Source Sans Pro", sans-serif;
-fx-font-size: 12pt;
}
.node-bank {
-base-fill: #9e7bff;
}
.node-regulator {
-base-fill: #fff2d1;
}
.node-network-service {
-base-fill: red;
}
.node-circle-inner {
-fx-fill: -base-fill;
-fx-stroke: derive(-base-fill, -40%);
-fx-stroke-width: 2px;
}
.node-circle-pulse {
-fx-fill: radial-gradient(center 50% 50%, radius 50%, #ffffff00, derive(-base-fill, 50%));
}
.hide-sidebar-button {
-fx-background-color: linear-gradient(to left, #464646, derive(#1c1c1c, 10%));
-fx-min-width: 0;
-fx-text-fill: #ffffffaa;
-fx-alignment: top-right;
-fx-label-padding: 0;
-fx-padding: 0 10 0 10;
-fx-border-color: #00000066;
-fx-border-width: 1 0 1 1;
}
.bullet {
-fx-fill: black;
}
.connection-bank-to-bank {
-fx-fill: white;
}
.message-line {
-fx-stroke: white;
}
.connection-bank-to-regulator {
-fx-stroke: red;
}
.node-label > Label, .node-status-label > Label {
-fx-text-fill: white;
-fx-effect: dropshadow(gaussian, black, 10, 0.1, 0, 0);
}
/* Hack around the Modena theme that makes all scroll panes grey by default */
.scroll-pane > .viewport {
-fx-background-color: transparent;
}
.scroll-pane .scroll-bar {
-fx-background-color: transparent;
}
.flat-button {
-fx-background-color: white;
-fx-padding: 0 0 0 0;
}
.flat-button:hover {
-fx-underline: true;
-fx-cursor: hand;
}
.flat-button:focused {
-fx-font-weight: bold;
}
.fat-buttons Button {
-fx-padding: 10 15 10 15;
-fx-min-width: 100;
-fx-font-weight: bold;
-fx-base: whitesmoke;
}
.fat-buttons ChoiceBox {
-fx-padding: 4 8 4 8;
-fx-min-width: 100;
-fx-font-weight: bold;
-fx-base: whitesmoke;
}
.fat-buttons Button:default {
-fx-base: orange;
-fx-text-fill: white;
-fx-font-family: 'Source Sans Pro', sans-serif;
}
.fat-buttons Button:cancel {
-fx-background-color: white;
-fx-background-insets: 1;
-fx-border-color: lightgray;
-fx-border-radius: 3;
-fx-text-fill: black;
}
.fat-buttons Button:cancel:hover {
-fx-base: white;
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-text-fill: black;
}
/** take out the focus ring */
.no-focus-button:focused {
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-background-insets: 0 0 -1 0, 0, 1, 2;
-fx-background-radius: 3px, 3px, 2px, 1px;
}
.blue-button {
-fx-base: lightblue;
-fx-text-fill: darkslategrey;
}
.blue-button:disabled {
-fx-text-fill: white;
}
.green-button {
-fx-base: #62c462;
-fx-text-fill: darkslategrey;
}
.green-button:disabled {
-fx-text-fill: white;
}
.next-button {
-fx-base: #66b2ff;
-fx-text-fill: white;
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-background-insets: 0 0 -1 0, 0, 1, 2;
-fx-background-radius: 3px, 3px, 2px, 1px;
}
.style-choice:default {
-fx-base: #66b2ff;
-fx-text-fill: white;
-fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color;
-fx-background-insets: 0 0 -1 0, 0, 1, 2;
-fx-background-radius: 3px, 3px, 2px, 1px;
}
.controls-hbox {
-fx-background-color: white;
}
.drop-shadow-pane-horizontal {
/*-fx-background-color: linear-gradient(to top, #888, #fff);*/
-fx-background-color: white;
-fx-border-color: #555;
-fx-border-width: 0 0 1 0;
}
.logo-label {
-fx-font-size: 40;
-fx-text-fill: slategray;
}
.date-label {
-fx-font-size: 30;
}
.splitter {
-fx-padding: 0;
-fx-background-color: #464646;
}
.splitter > .split-pane-divider {
-fx-background-color: linear-gradient(to left, #1c1c1c, transparent);
-fx-border-color: black;
-fx-border-width: 0 1 0 0;
-fx-padding: 0 2 0 2;
}
.progress-tracker-cursor-box {
-fx-padding: 0 15 0 0;
}
.progress-tracker-cursor {
-fx-translate-x: 15.0;
-fx-fill: white;
}
.sidebar {
-fx-background-color: #464646;
}
.sidebar > VBox > StackPane {
-fx-background-color: #666666;
-fx-padding: 5px;
}
.sidebar > VBox > StackPane > Label {
-fx-text-fill: white;
}
.progress-tracker-widget-steps {
-fx-spacing: 5;
-fx-fill-width: true;
}
.progress-tracker-widget-steps > StackPane {
-fx-background-color: #5a5a5a;
-fx-padding: 7px;
-fx-alignment: center-left;
}
.progress-tracker-widget-steps > StackPane > Label {
-fx-text-fill: white;
}