From ee4f2dcc3b2ceb11f3dfb1893b06ec15243a2011 Mon Sep 17 00:00:00 2001 From: LeshaInc Date: Thu, 30 Jan 2025 20:29:55 +0000 Subject: [PATCH] Add scalafmt --- .gitlab-ci.yml | 7 + .scalafmt.conf | 35 ++ project/assembly.sbt | 1 - project/build.properties | 2 +- project/buildinfo.sbt | 1 - project/plugins.sbt | 3 + .../scala/ocelot/desktop/ColorScheme.scala | 2 +- .../scala/ocelot/desktop/OcelotDesktop.scala | 93 ++-- src/main/scala/ocelot/desktop/Settings.scala | 23 +- .../scala/ocelot/desktop/audio/Audio.scala | 8 +- .../ocelot/desktop/audio/BeepGenerator.scala | 4 +- .../ocelot/desktop/audio/OggDecoder.scala | 3 +- .../desktop/audio/OpenAlException.scala | 4 +- .../ocelot/desktop/audio/SoundBuffer.scala | 4 +- .../ocelot/desktop/audio/SoundBuffers.scala | 5 +- .../ocelot/desktop/audio/SoundSource.scala | 14 +- .../scala/ocelot/desktop/color/IntColor.scala | 4 +- .../ocelot/desktop/color/RGBAColor.scala | 2 +- .../ocelot/desktop/color/RGBAColorNorm.scala | 2 +- .../scala/ocelot/desktop/entity/Camera.scala | 2 +- .../ocelot/desktop/entity/OpenFMRadio.scala | 47 ++- .../entity/traits/OcelotInterface.scala | 5 +- .../ocelot/desktop/geometry/Basis3D.scala | 18 +- .../desktop/geometry/ProjectionMatrix3D.scala | 6 +- .../ocelot/desktop/geometry/Quaternion.scala | 4 +- .../ocelot/desktop/geometry/Rect2D.scala | 3 +- .../ocelot/desktop/geometry/Size2D.scala | 4 +- .../ocelot/desktop/geometry/Transform2D.scala | 16 +- .../ocelot/desktop/geometry/Transform3D.scala | 7 +- .../ocelot/desktop/geometry/Vector3D.scala | 2 +- .../ocelot/desktop/graphics/Graphics.scala | 37 +- .../desktop/graphics/GraphicsState.scala | 2 +- .../ocelot/desktop/graphics/IconSource.scala | 40 +- .../desktop/graphics/ScreenViewport.scala | 1 + .../desktop/graphics/ShaderProgram.scala | 9 +- .../ocelot/desktop/graphics/Texture.scala | 16 +- .../ocelot/desktop/graphics/Viewport3D.scala | 12 +- .../graphics/buffer/VertexBuffer.scala | 2 +- .../ocelot/desktop/graphics/mesh/Mesh2D.scala | 5 +- .../ocelot/desktop/graphics/mesh/Mesh3D.scala | 4 +- .../desktop/graphics/mesh/MeshBuilder3D.scala | 129 +++--- .../graphics/mesh/MeshInstance2D.scala | 4 +- .../graphics/mesh/MeshInstance3D.scala | 6 +- .../desktop/graphics/mesh/MeshVertex2D.scala | 2 +- .../desktop/graphics/mesh/PrimitiveType.scala | 2 +- .../graphics/render/InstanceRenderer.scala | 17 +- .../desktop/graphics/scene/Camera3D.scala | 4 +- .../graphics/scene/DirectionalLight3D.scala | 3 +- .../desktop/graphics/scene/SceneMesh3D.scala | 3 +- .../ocelot/desktop/inventory/Inventory.scala | 63 +-- .../scala/ocelot/desktop/inventory/Item.scala | 47 +-- .../desktop/inventory/ItemFactory.scala | 28 +- .../desktop/inventory/ItemRecoverer.scala | 5 +- .../ocelot/desktop/inventory/Items.scala | 24 +- .../inventory/PersistedInventory.scala | 12 +- .../desktop/inventory/SyncedInventory.scala | 39 +- .../inventory/item/ComponentBusItem.scala | 5 +- .../desktop/inventory/item/DataCardItem.scala | 4 +- .../item/DiskDriveMountableItem.scala | 5 +- .../desktop/inventory/item/EepromItem.scala | 12 +- .../desktop/inventory/item/FloppyItem.scala | 2 +- .../inventory/item/GraphicsCardItem.scala | 3 +- .../inventory/item/MagicalMemoryItem.scala | 2 +- .../inventory/item/OcelotCardItem.scala | 8 +- .../inventory/item/RedstoneCardItem.scala | 4 +- .../item/SelfDestructingCardItem.scala | 5 +- .../desktop/inventory/item/ServerItem.scala | 24 +- .../inventory/item/SoundCardItem.scala | 6 +- .../item/WirelessNetworkCardItem.scala | 4 +- .../desktop/inventory/traits/CardItem.scala | 4 +- .../inventory/traits/ComponentItem.scala | 7 +- .../inventory/traits/CpuLikeItem.scala | 4 +- .../desktop/inventory/traits/DiskItem.scala | 20 +- .../inventory/traits/PersistableItem.scala | 4 +- .../inventory/traits/RackMountableItem.scala | 7 +- .../desktop/node/ComputerAwareNode.scala | 2 +- src/main/scala/ocelot/desktop/node/Node.scala | 21 +- .../scala/ocelot/desktop/node/NodePort.scala | 2 +- .../ocelot/desktop/node/NodeRegistry.scala | 9 +- .../scala/ocelot/desktop/node/NodeType.scala | 2 +- .../ocelot/desktop/node/NodeTypeGroup.scala | 2 +- .../ocelot/desktop/node/NodeTypeWidget.scala | 4 +- .../desktop/node/OcelotLogParticleNode.scala | 4 +- .../node/PositionalSoundSourcesNode.scala | 5 +- .../desktop/node/nodes/ColorfulLampNode.scala | 6 +- .../desktop/node/nodes/ComputerNode.scala | 21 +- .../desktop/node/nodes/DiskDriveNode.scala | 2 +- .../node/nodes/HologramProjectorNode.scala | 5 +- .../node/nodes/IronNoteBlockNode.scala | 2 +- .../node/nodes/MicrocontrollerNode.scala | 27 +- .../desktop/node/nodes/NoteBlockNode.scala | 2 +- .../node/nodes/NoteBlockNodeBase.scala | 7 +- .../desktop/node/nodes/OcelotBlockNode.scala | 2 +- .../desktop/node/nodes/OpenFMRadioNode.scala | 10 +- .../ocelot/desktop/node/nodes/RackNode.scala | 26 +- .../ocelot/desktop/node/nodes/RaidNode.scala | 26 +- .../ocelot/desktop/node/nodes/RelayNode.scala | 8 +- .../desktop/node/nodes/ScreenNode.scala | 51 ++- .../desktop/node/nodes/TapeDriveNode.scala | 11 +- .../scala/ocelot/desktop/ui/UiHandler.scala | 34 +- .../ocelot/desktop/ui/event/DragEvent.scala | 4 +- .../ocelot/desktop/ui/event/HoverEvent.scala | 4 +- .../ocelot/desktop/ui/event/MouseEvent.scala | 3 - .../event/handlers/DiskActivityHandler.scala | 3 +- .../ui/event/handlers/MouseHandler.scala | 39 +- .../desktop/ui/layout/LinearLayout.scala | 8 +- .../desktop/ui/swing/SplashScreen.scala | 7 +- .../ocelot/desktop/ui/widget/Button.scala | 13 +- .../widget/ChangeSimulationSpeedDialog.scala | 148 ++++--- .../ocelot/desktop/ui/widget/Checkbox.scala | 5 +- .../ui/widget/CloseConfirmationDialog.scala | 59 ++- .../desktop/ui/widget/ComponentUsageBar.scala | 34 +- .../ocelot/desktop/ui/widget/Filler.scala | 1 + .../ocelot/desktop/ui/widget/Histogram.scala | 6 +- .../scala/ocelot/desktop/ui/widget/Icon.scala | 6 +- .../ocelot/desktop/ui/widget/IconButton.scala | 68 ++- .../desktop/ui/widget/InputDialog.scala | 15 +- .../ocelot/desktop/ui/widget/LogWidget.scala | 16 +- .../ocelot/desktop/ui/widget/MenuBar.scala | 65 +-- .../desktop/ui/widget/MenuBarButton.scala | 18 +- .../desktop/ui/widget/Oscilloscope.scala | 109 ++--- .../scala/ocelot/desktop/ui/widget/Plot.scala | 18 +- .../ui/widget/ScreenAspectRatioDialog.scala | 15 +- .../ocelot/desktop/ui/widget/ScrollView.scala | 3 +- .../ocelot/desktop/ui/widget/Slider.scala | 6 +- .../scala/ocelot/desktop/ui/widget/Text.scala | 10 +- .../ocelot/desktop/ui/widget/TextInput.scala | 25 +- .../desktop/ui/widget/TunnelDialog.scala | 10 +- .../desktop/ui/widget/Viewport3DWidget.scala | 30 +- .../desktop/ui/widget/WorkspaceView.scala | 80 ++-- .../ui/widget/card/Redstone1Window.scala | 23 +- .../ui/widget/card/Redstone2Window.scala | 67 +-- .../ui/widget/card/SoundCardWindow.scala | 145 ++++--- .../ui/widget/contextmenu/ContextMenu.scala | 1 + .../widget/contextmenu/ContextMenuEntry.scala | 43 +- .../widget/contextmenu/ContextMenuIcon.scala | 6 +- .../contextmenu/ContextMenuIconSize.scala | 2 +- .../contextmenu/ContextMenuSubmenu.scala | 20 +- .../ui/widget/contextmenu/ContextMenus.scala | 6 +- .../desktop/ui/widget/help/AboutDialog.scala | 77 ++-- .../ui/widget/help/UpdateCheckerDialog.scala | 76 ++-- .../notification/NotificationDialog.scala | 17 +- .../modal/notification/NotificationType.scala | 2 +- .../ui/widget/settings/SettingsDialog.scala | 56 +-- .../ui/widget/settings/SettingsTab.scala | 3 +- .../ui/widget/settings/SoundSettingsTab.scala | 10 +- .../widget/settings/SystemSettingsTab.scala | 128 +++--- .../ui/widget/settings/UISettingsTab.scala | 199 +++++---- .../widget/slot/ComponentBusSlotWidget.scala | 4 +- .../widget/slot/ComputerCpuSlotWidget.scala | 5 +- .../desktop/ui/widget/slot/ItemChooser.scala | 11 +- .../widget/slot/RackMountableSlotWidget.scala | 4 +- .../desktop/ui/widget/slot/SlotWidget.scala | 10 +- .../ui/widget/statusbar/StatusBar.scala | 31 +- .../desktop/ui/widget/tooltip/Tooltip.scala | 6 +- .../ui/widget/tooltip/TooltipPool.scala | 2 +- .../ui/widget/traits/HoverAnimation.scala | 8 +- .../ui/widget/verticalmenu/VerticalMenu.scala | 2 +- .../verticalmenu/VerticalMenuButton.scala | 31 +- .../ui/widget/window/BasicWindow.scala | 3 +- .../ui/widget/window/NodeSelector.scala | 35 +- .../ui/widget/window/PanelWindow.scala | 11 +- .../desktop/ui/widget/window/TitleBar.scala | 11 +- .../desktop/ui/widget/window/Window.scala | 14 +- .../desktop/util/AudibleComputerAware.scala | 3 +- .../ocelot/desktop/util/CommandLine.scala | 10 +- .../ocelot/desktop/util/ComputerAware.scala | 27 +- .../ocelot/desktop/util/ComputerType.scala | 2 +- .../util/DefaultSlotItemsFillable.scala | 1 - .../ocelot/desktop/util/DiskDriveAware.scala | 41 +- .../scala/ocelot/desktop/util/DrawUtils.scala | 6 +- .../scala/ocelot/desktop/util/FileUtils.scala | 13 +- src/main/scala/ocelot/desktop/util/Font.scala | 13 +- .../scala/ocelot/desktop/util/Logging.scala | 2 +- .../util/OcelotInterfaceLogStorage.scala | 6 +- .../ocelot/desktop/util/OcelotOnlineAPI.scala | 9 +- .../ocelot/desktop/util/Persistable.scala | 4 +- .../scala/ocelot/desktop/util/Profiler.scala | 2 +- .../ocelot/desktop/util/ReflectionUtils.scala | 10 +- .../ocelot/desktop/util/SettingsData.scala | 4 +- .../ocelot/desktop/util/Spritesheet.scala | 2 +- .../scala/ocelot/desktop/util/TaskQueue.scala | 7 +- .../ocelot/desktop/util/Transaction.scala | 4 +- .../ocelot/desktop/util/WebcamCapture.scala | 18 +- .../ocelot/desktop/windows/CameraWindow.scala | 64 +-- .../desktop/windows/ComputerWindow.scala | 397 +++++++++--------- .../windows/HologramProjectorWindow.scala | 73 ++-- .../windows/OcelotInterfaceWindow.scala | 2 +- .../desktop/windows/OpenFMRadioWindow.scala | 25 +- .../ocelot/desktop/windows/RackWindow.scala | 51 ++- .../ocelot/desktop/windows/RaidWindow.scala | 16 +- .../ocelot/desktop/windows/RelayWindow.scala | 4 +- .../ocelot/desktop/windows/ScreenWindow.scala | 35 +- .../desktop/windows/TapeDriveWindow.scala | 25 +- 194 files changed, 2153 insertions(+), 1888 deletions(-) create mode 100644 .scalafmt.conf delete mode 100644 project/assembly.sbt delete mode 100644 project/buildinfo.sbt create mode 100644 project/plugins.sbt diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9f23c58..c1c281a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -29,6 +29,13 @@ test: script: - sbt test +scalafmt: + stage: test + before_script: + - sbt -v sbtVersion + script: + - sbt scalafmtCheckAll + build: stage: build before_script: diff --git a/.scalafmt.conf b/.scalafmt.conf new file mode 100644 index 0000000..361c523 --- /dev/null +++ b/.scalafmt.conf @@ -0,0 +1,35 @@ +version = 3.8.6 +runner.dialect = scala213 +preset = default +maxColumn = 120 +indent.defnSite = 2 + +align = { + preset = none + openParenDefnSite = true +} + +newlines = { + source = keep + topLevelStatementBlankLines = [ + { blanks { before = 1, after = 1, beforeAll = -1, afterAll = -1 } } + ] +} + +binPack = { + preset = Oneline + literalsExclude = [] +} + +rewrite = { + rules = [SortModifiers, Imports] + sortModifiers.preset = styleGuide + imports.sort = scalastyle + trailingCommas.style = multiple + insertBraces.minLines = 3 +} + +docstrings = { + oneline = fold + wrap = keep +} \ No newline at end of file diff --git a/project/assembly.sbt b/project/assembly.sbt deleted file mode 100644 index f55a62c..0000000 --- a/project/assembly.sbt +++ /dev/null @@ -1 +0,0 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.1") diff --git a/project/build.properties b/project/build.properties index d0ac2d5..18ce00b 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1,2 +1,2 @@ # suppress inspection "UnusedProperty" for whole file -sbt.version = 1.8.3 +sbt.version = 1.10.7 diff --git a/project/buildinfo.sbt b/project/buildinfo.sbt deleted file mode 100644 index 71982a8..0000000 --- a/project/buildinfo.sbt +++ /dev/null @@ -1 +0,0 @@ -addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0") diff --git a/project/plugins.sbt b/project/plugins.sbt new file mode 100644 index 0000000..67d14ee --- /dev/null +++ b/project/plugins.sbt @@ -0,0 +1,3 @@ +addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.13.1") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1") +addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.4") \ No newline at end of file diff --git a/src/main/scala/ocelot/desktop/ColorScheme.scala b/src/main/scala/ocelot/desktop/ColorScheme.scala index 75cd406..800b4a7 100644 --- a/src/main/scala/ocelot/desktop/ColorScheme.scala +++ b/src/main/scala/ocelot/desktop/ColorScheme.scala @@ -28,7 +28,7 @@ class ColorScheme extends Logging { val bytes = java.lang.Long.parseLong(value.substring(1), 16) val color = if (value.length == 9) { val rgb = bytes >> 8 - IntColor(rgb.toInt).toRGBANorm.withAlpha((bytes & 0xFF).toFloat / 255f) + IntColor(rgb.toInt).toRGBANorm.withAlpha((bytes & 0xff).toFloat / 255f) } else IntColor(bytes.toInt).toRGBANorm entries.addOne((key, color)) } diff --git a/src/main/scala/ocelot/desktop/OcelotDesktop.scala b/src/main/scala/ocelot/desktop/OcelotDesktop.scala index 0bb9a6f..dd6c482 100644 --- a/src/main/scala/ocelot/desktop/OcelotDesktop.scala +++ b/src/main/scala/ocelot/desktop/OcelotDesktop.scala @@ -30,11 +30,8 @@ import scala.io.Source import scala.jdk.CollectionConverters._ import scala.util.{Failure, Success, Try, Using} -object OcelotDesktop - // This configures Log4j appenders & loggers, it should come before Logging in inheritance hierarchy - extends LoggingConfiguration - with Logging -{ +// LoggingConfiguration configures Log4j appenders & loggers, it should come before Logging in inheritance hierarchy +object OcelotDesktop extends LoggingConfiguration with Logging { System.setProperty("awt.useSystemAAFontSettings", "on") System.setProperty("swing.aatext", "true") System.setProperty("LWJGL_WM_CLASS", "Ocelot Desktop") @@ -70,11 +67,10 @@ object OcelotDesktop splashScreen.setStatus("Loading configuration...", 0.10f) val customConfigPath = args.get(CommandLine.ConfigPath).flatten - val desktopConfigPath: Path = + val desktopConfigPath: Path = { if (customConfigPath.isDefined) { Paths.get(customConfigPath.get) - } - else { + } else { // TODO: migration for old locations of ocelot.conf, can be safely removed later // TODO: uncomment this line and delete everything below it when you're ready! // OcelotPaths.desktopConfig @@ -83,23 +79,24 @@ object OcelotDesktop try { if (!Files.exists(newConfigPath)) { - val oldConfigPath = + val oldConfigPath = { if (SystemUtils.IS_OS_WINDOWS) Paths.get(OcelotPaths.windowsAppDataDirectoryName, "Ocelot", "ocelot.conf") else Paths.get(OcelotPaths.linuxHomeDirectoryName, ".config", "ocelot", "ocelot.conf") + } if (Files.exists(oldConfigPath)) Files.move(oldConfigPath, newConfigPath) } - } - catch { + } catch { case _: Throwable => } // TODO: end of upper todo <3 newConfigPath } + } Settings.load(desktopConfigPath) @@ -157,24 +154,28 @@ object OcelotDesktop } } - val updateThread = new Thread(() => try { - val currentThread = Thread.currentThread() + val updateThread = new Thread( + () => + try { + val currentThread = Thread.currentThread() - while (!currentThread.isInterrupted) { - Profiler.measure("tick") { - withTickLockAcquired { - workspace.update() - updateThreadTasks.run() + while (!currentThread.isInterrupted) { + Profiler.measure("tick") { + withTickLockAcquired { + workspace.update() + updateThreadTasks.run() - tpsCounter.tick() + tpsCounter.tick() + } + } + + ticker.waitNext() } - } - - ticker.waitNext() - } - } catch { - case _: InterruptedException => // ignore - }, "update-thread") + } catch { + case _: InterruptedException => // ignore + }, + "update-thread", + ) updateThread.start() splashScreen.dispose() @@ -184,7 +185,8 @@ object OcelotDesktop logger.info("Cleaning up") updateThread.interrupt() - try updateThread.join() catch { + try updateThread.join() + catch { case _: InterruptedException => } @@ -234,7 +236,9 @@ object OcelotDesktop root.workspaceView.load(frontendNBT) if (frontendNBT.hasKey("players")) { players.clear() - players.addAll(frontendNBT.getTagList("players", NBT.TAG_STRING).map((player: NBTTagString) => User(player.getString))) + players.addAll( + frontendNBT.getTagList("players", NBT.TAG_STRING).map((player: NBTTagString) => User(player.getString)) + ) } } @@ -288,12 +292,13 @@ object OcelotDesktop val oldPath = workspace.path if (oldPath != outputPath) { - val (oldFiles, newFiles) = + val (oldFiles, newFiles) = { Using.resources(Files.list(oldPath), Files.list(outputPath)) { (oldDirStream, newDirStream) => val oldFiles = oldDirStream.iterator.asScala.toArray val newFiles = newDirStream.iterator.asScala.toArray (oldFiles, newFiles) } + } val toRemove = newFiles.intersect(oldFiles) @@ -311,8 +316,7 @@ object OcelotDesktop if (Files.isDirectory(path)) { FileUtils.copyDirectory(oldFile, newFile) - } - else { + } else { FileUtils.copyFile(oldFile, newFile) } } @@ -355,11 +359,12 @@ object OcelotDesktop def saveAs(): Unit = showSaveDialog() - def showOpenDialog(): Unit = + def showOpenDialog(): Unit = { showFileChooserDialog(JFileChooser.OPEN_DIALOG, JFileChooser.DIRECTORIES_ONLY) { case Some(dir) => load(dir) case None => Success(()) } + } def load(dir: File): Try[Unit] = { val path = Paths.get(dir.getCanonicalPath, "workspace.nbt") @@ -410,7 +415,7 @@ object OcelotDesktop val result = f(selectedFile) result match { - case f@Failure(_) => showFailureMessage(f) + case f @ Failure(_) => showFailureMessage(f) case Success(_) => } }) @@ -424,13 +429,13 @@ object OcelotDesktop new NotificationDialog( s"Something went wrong!\n($exception)\nCheck the log file for a full stacktrace.", - NotificationType.Error + NotificationType.Error, ).addCloseButton().show() } def showAddPlayerDialog(): Unit = new InputDialog( "Add new player", - text => OcelotDesktop.selectPlayer(text) + text => OcelotDesktop.selectPlayer(text), ).show() def player: User = if (players.nonEmpty) players.head else User("myself") @@ -464,12 +469,15 @@ object OcelotDesktop } private def prepareSavePath(path: Path)(continuation: => Unit): Unit = { - val nonEmpty = try Using.resource(Files.list(path))(_.iterator.asScala.nonEmpty) catch { - case _: FileNotFoundException | _: NoSuchFileException => - logger.info(s"Save path $path does not exist: creating a new directory") - Files.createDirectory(path) + val nonEmpty = { + try Using.resource(Files.list(path))(_.iterator.asScala.nonEmpty) + catch { + case _: FileNotFoundException | _: NoSuchFileException => + logger.info(s"Save path $path does not exist: creating a new directory") + Files.createDirectory(path) - false + false + } } if (nonEmpty) { @@ -478,7 +486,7 @@ object OcelotDesktop |Files in the save directory will be included in the workspace. |They may be overwritten, causing loss of data. |Proceed with saving anyway?""".stripMargin, - NotificationType.Warning + NotificationType.Warning, ) { addButton("Cancel") { close() @@ -491,7 +499,7 @@ object OcelotDesktop } else continuation } - private def showSaveDialog(continuation: => Unit): Unit = + private def showSaveDialog(continuation: => Unit): Unit = { showFileChooserDialog(JFileChooser.SAVE_DIALOG, JFileChooser.DIRECTORIES_ONLY) { dir => Try { if (dir.nonEmpty) { @@ -512,6 +520,7 @@ object OcelotDesktop } } } + } private def showCloseConfirmationDialog(prompt: Option[String])(continuation: => Unit): Unit = { if (UiHandler.root.modalDialogPool.children.exists(_.isInstanceOf[CloseConfirmationDialog])) { diff --git a/src/main/scala/ocelot/desktop/Settings.scala b/src/main/scala/ocelot/desktop/Settings.scala index 3250770..a2e6b95 100644 --- a/src/main/scala/ocelot/desktop/Settings.scala +++ b/src/main/scala/ocelot/desktop/Settings.scala @@ -81,19 +81,23 @@ object Settings extends Logging { if (config.hasPath(path)) config.getDouble(path) else default - def withValuePreserveOrigin(path: String, value: Any): Config = - config.withValue(path, + def withValuePreserveOrigin(path: String, value: Any): Config = { + config.withValue( + path, if (config.hasPath(path)) ConfigValueFactory.fromAnyRef(value).withOrigin(config.getValue(path).origin()) - else ConfigValueFactory.fromAnyRef(value) + else ConfigValueFactory.fromAnyRef(value), ) + } - def withValuePreserveOrigin(path: String, value: Option[Any]): Config = - config.withValue(path, + def withValuePreserveOrigin(path: String, value: Option[Any]): Config = { + config.withValue( + path, if (config.hasPath(path)) ConfigValueFactory.fromAnyRef(value.orNull).withOrigin(config.getValue(path).origin()) - else ConfigValueFactory.fromAnyRef(value.orNull) + else ConfigValueFactory.fromAnyRef(value.orNull), ) + } def withValue(path: String, value: Int2D): Config = { config.withValue(path, ConfigValueFactory.fromIterable(util.Arrays.asList(value.x, value.y))) @@ -107,6 +111,7 @@ object Settings extends Logging { var isSet: Boolean = false def this() = this(0, 0) + def this(list: util.List[Integer]) = { this() if (list.size() == 2) { @@ -143,12 +148,10 @@ object Settings extends Logging { logger.info(s"Loaded Ocelot Desktop configuration from: $path") return - } - catch { + } catch { case _: Throwable => logger.info(s"Failed to parse $path, using default Ocelot Desktop configuration.") - } - finally { + } finally { if (stream != null) stream.close() } diff --git a/src/main/scala/ocelot/desktop/audio/Audio.scala b/src/main/scala/ocelot/desktop/audio/Audio.scala index 434b2e3..680f9d3 100644 --- a/src/main/scala/ocelot/desktop/audio/Audio.scala +++ b/src/main/scala/ocelot/desktop/audio/Audio.scala @@ -15,9 +15,7 @@ object Audio extends Logging { private val sources = new mutable.HashMap[SoundSource, Int] private var _disabled = true - /** - * Should be called _before_ initializing any sound-related resources - */ + /** Should be called _before_ initializing any sound-related resources */ def init(): Unit = { try { AL.create() @@ -39,7 +37,7 @@ object Audio extends Logging { def newStream( soundCategory: SoundCategory.Value, pitch: Float = 1f, - volume: Float = 1f + volume: Float = 1f, ): (SoundStream, SoundSource) = { var source: SoundSource = null @@ -188,7 +186,7 @@ object Audio extends Logging { AL10W.alSourcef( sourceId, AL10.AL_GAIN, - source.volume * SoundCategory.getSettingsValue(source.soundCategory) * Settings.get.volumeMaster + source.volume * SoundCategory.getSettingsValue(source.soundCategory) * Settings.get.volumeMaster, ) } diff --git a/src/main/scala/ocelot/desktop/audio/BeepGenerator.scala b/src/main/scala/ocelot/desktop/audio/BeepGenerator.scala index 24b87a2..df7f0b4 100644 --- a/src/main/scala/ocelot/desktop/audio/BeepGenerator.scala +++ b/src/main/scala/ocelot/desktop/audio/BeepGenerator.scala @@ -19,8 +19,8 @@ object BeepGenerator { val value = (math.signum(math.sin(angle)) * 8192).toShort offset += step if (offset > 1) offset -= 1 - data.put((value & 0xFF).toByte) - data.put(((value >> 8) & 0xFF).toByte) + data.put((value & 0xff).toByte) + data.put(((value >> 8) & 0xff).toByte) } if (data.hasRemaining) { for (_ <- 0 until pauseSampleCount) { diff --git a/src/main/scala/ocelot/desktop/audio/OggDecoder.scala b/src/main/scala/ocelot/desktop/audio/OggDecoder.scala index aebac9b..af37f10 100644 --- a/src/main/scala/ocelot/desktop/audio/OggDecoder.scala +++ b/src/main/scala/ocelot/desktop/audio/OggDecoder.scala @@ -8,7 +8,8 @@ import java.nio.ByteBuffer object OggDecoder { def decode(input: InputStream): SoundSamples = { - val stream = new VorbisStream(new BasicStream(input).getLogicalStreams.iterator().next().asInstanceOf[LogicalOggStream]) + val stream = + new VorbisStream(new BasicStream(input).getLogicalStreams.iterator().next().asInstanceOf[LogicalOggStream]) val rate = stream.getIdentificationHeader.getSampleRate val channels = stream.getIdentificationHeader.getChannels diff --git a/src/main/scala/ocelot/desktop/audio/OpenAlException.scala b/src/main/scala/ocelot/desktop/audio/OpenAlException.scala index d301d1d..430bfef 100644 --- a/src/main/scala/ocelot/desktop/audio/OpenAlException.scala +++ b/src/main/scala/ocelot/desktop/audio/OpenAlException.scala @@ -3,12 +3,10 @@ package ocelot.desktop.audio import scala.util.control import scala.util.control.Exception.Catch -case class OpenAlException(func: String, errName: String, code: Int) - extends Exception(s"OpenAL error: $func: $errName") +case class OpenAlException(func: String, errName: String, code: Int) extends Exception(s"OpenAL error: $func: $errName") object OpenAlException { def defaulting[T](default: => T): Catch[T] = control.Exception.failAsValue(classOf[OpenAlException])(default) def ignoring: Catch[Unit] = defaulting(()) } - diff --git a/src/main/scala/ocelot/desktop/audio/SoundBuffer.scala b/src/main/scala/ocelot/desktop/audio/SoundBuffer.scala index d11dd7f..bb36cde 100644 --- a/src/main/scala/ocelot/desktop/audio/SoundBuffer.scala +++ b/src/main/scala/ocelot/desktop/audio/SoundBuffer.scala @@ -47,8 +47,8 @@ class SoundBuffer(val file: String) extends Resource with Logging { val channels = AL10W.alGetBufferi(bufferId, AL10.AL_CHANNELS) val bits = AL10W.alGetBufferi(bufferId, AL10.AL_BITS) - sizeBytes * 8 / channels / bits - } + sizeBytes * 8 / channels / bits + } case None => 0 } diff --git a/src/main/scala/ocelot/desktop/audio/SoundBuffers.scala b/src/main/scala/ocelot/desktop/audio/SoundBuffers.scala index 0523cfc..cfeee21 100644 --- a/src/main/scala/ocelot/desktop/audio/SoundBuffers.scala +++ b/src/main/scala/ocelot/desktop/audio/SoundBuffers.scala @@ -6,6 +6,7 @@ import scala.collection.mutable.ArrayBuffer object SoundBuffers extends Resource { lazy val MachineComputerRunning: SoundBuffer = load("/ocelot/desktop/sounds/machine/computer_running.ogg") + lazy val MachineFloppyAccess: Array[SoundBuffer] = Array( load("/ocelot/desktop/sounds/machine/floppy_access1.ogg"), load("/ocelot/desktop/sounds/machine/floppy_access2.ogg"), @@ -14,8 +15,10 @@ object SoundBuffers extends Resource { load("/ocelot/desktop/sounds/machine/floppy_access5.ogg"), load("/ocelot/desktop/sounds/machine/floppy_access6.ogg"), ) + lazy val MachineFloppyEject: SoundBuffer = load("/ocelot/desktop/sounds/machine/floppy_eject.ogg") lazy val MachineFloppyInsert: SoundBuffer = load("/ocelot/desktop/sounds/machine/floppy_insert.ogg") + lazy val MachineHDDAccess: Array[SoundBuffer] = Array( load("/ocelot/desktop/sounds/machine/hdd_access1.ogg"), load("/ocelot/desktop/sounds/machine/hdd_access2.ogg"), @@ -43,7 +46,7 @@ object SoundBuffers extends Resource { lazy val NoteBlock: Map[String, SoundBuffer] = List( "banjo", "basedrum", "bass", "bell", "bit", "chime", "cow_bell", "didgeridoo", "flute", "guitar", - "harp", "hat", "iron_xylophone", "pling", "snare", "xylophone" + "harp", "hat", "iron_xylophone", "pling", "snare", "xylophone", ).map(name => { (name, load(s"/ocelot/desktop/sounds/minecraft/note_block/$name.ogg")) }).toMap diff --git a/src/main/scala/ocelot/desktop/audio/SoundSource.scala b/src/main/scala/ocelot/desktop/audio/SoundSource.scala index fd9cfa2..9568f44 100644 --- a/src/main/scala/ocelot/desktop/audio/SoundSource.scala +++ b/src/main/scala/ocelot/desktop/audio/SoundSource.scala @@ -11,7 +11,7 @@ class SoundSource( val looping: Boolean, val pitch: Float, var volume: Float, - var position: Vector3D = Vector3D(0, 0, 0) + var position: Vector3D = Vector3D(0, 0, 0), ) { def duration: Option[Duration] = kind match { case SoundSource.KindSoundBuffer(buffer) => @@ -124,8 +124,12 @@ object SoundSource { SoundSource.fromBuffer(SoundBuffers.MinecraftClickRelease, SoundCategory.Interface) } - lazy val MinecraftExplosion: SoundSource = SoundSource.fromBuffer(SoundBuffers.MinecraftExplosion, SoundCategory.Environment) + lazy val MinecraftExplosion: SoundSource = + SoundSource.fromBuffer(SoundBuffers.MinecraftExplosion, SoundCategory.Environment) - lazy val MachineFloppyInsert: SoundSource = SoundSource.fromBuffer(SoundBuffers.MachineFloppyInsert, SoundCategory.Environment) - lazy val MachineFloppyEject: SoundSource = SoundSource.fromBuffer(SoundBuffers.MachineFloppyEject, SoundCategory.Environment) -} \ No newline at end of file + lazy val MachineFloppyInsert: SoundSource = + SoundSource.fromBuffer(SoundBuffers.MachineFloppyInsert, SoundCategory.Environment) + + lazy val MachineFloppyEject: SoundSource = + SoundSource.fromBuffer(SoundBuffers.MachineFloppyEject, SoundCategory.Environment) +} diff --git a/src/main/scala/ocelot/desktop/color/IntColor.scala b/src/main/scala/ocelot/desktop/color/IntColor.scala index afed1f4..ecd819b 100644 --- a/src/main/scala/ocelot/desktop/color/IntColor.scala +++ b/src/main/scala/ocelot/desktop/color/IntColor.scala @@ -6,8 +6,8 @@ case class IntColor(color: Int) extends Color { override def toRGBA: RGBAColor = { RGBAColor( (color >> 16).toShort, - ((color >> 8) & 0xFF).toShort, - (color & 0xFF).toShort, + ((color >> 8) & 0xff).toShort, + (color & 0xff).toShort, ) } diff --git a/src/main/scala/ocelot/desktop/color/RGBAColor.scala b/src/main/scala/ocelot/desktop/color/RGBAColor.scala index 1bc8c11..f95ef1c 100644 --- a/src/main/scala/ocelot/desktop/color/RGBAColor.scala +++ b/src/main/scala/ocelot/desktop/color/RGBAColor.scala @@ -14,7 +14,7 @@ case class RGBAColor(r: Short, g: Short, b: Short, a: Short = 255) extends Color r.toFloat / 255f, g.toFloat / 255f, b.toFloat / 255f, - a.toFloat / 255f + a.toFloat / 255f, ) override def toHSVA: HSVAColor = toRGBANorm.toHSVA diff --git a/src/main/scala/ocelot/desktop/color/RGBAColorNorm.scala b/src/main/scala/ocelot/desktop/color/RGBAColorNorm.scala index 339534a..51c563f 100644 --- a/src/main/scala/ocelot/desktop/color/RGBAColorNorm.scala +++ b/src/main/scala/ocelot/desktop/color/RGBAColorNorm.scala @@ -18,7 +18,7 @@ case class RGBAColorNorm(r: Float, g: Float, b: Float, a: Float = 1f) extends Co def mapA(f: Float => Float): RGBAColorNorm = copy(a = f(a)) - final private def componentToLinear(x: Float): Float = { + private final def componentToLinear(x: Float): Float = { if (x <= 0.0404482362771082) x / 12.92f else diff --git a/src/main/scala/ocelot/desktop/entity/Camera.scala b/src/main/scala/ocelot/desktop/entity/Camera.scala index a1895ba..2a1ab16 100644 --- a/src/main/scala/ocelot/desktop/entity/Camera.scala +++ b/src/main/scala/ocelot/desktop/entity/Camera.scala @@ -43,7 +43,7 @@ class Camera extends Entity with GenericCamera with DeviceInfo { DeviceAttribute.Class -> DeviceClass.Multimedia, DeviceAttribute.Description -> "Dungeon Scanner 2.5D", DeviceAttribute.Vendor -> Constants.DeviceInfo.DefaultVendor, - DeviceAttribute.Product -> webcamCapture.map(_.name).getOrElse("Blind Pirate") + DeviceAttribute.Product -> webcamCapture.map(_.name).getOrElse("Blind Pirate"), ) override def load(nbt: NBTTagCompound, workspace: Workspace): Unit = { diff --git a/src/main/scala/ocelot/desktop/entity/OpenFMRadio.scala b/src/main/scala/ocelot/desktop/entity/OpenFMRadio.scala index e924882..cd93ba6 100644 --- a/src/main/scala/ocelot/desktop/entity/OpenFMRadio.scala +++ b/src/main/scala/ocelot/desktop/entity/OpenFMRadio.scala @@ -19,11 +19,12 @@ import javax.sound.sampled.AudioFormat.Encoding import javax.sound.sampled.{AudioFormat, AudioSystem} class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { - override val node: Component = + override val node: Component = { Network - .newNode(this, Visibility.Network) - .withComponent("openfm_radio", Visibility.Network) - .create() + .newNode(this, Visibility.Network) + .withComponent("openfm_radio", Visibility.Network) + .create() + } // --------------------------- URL --------------------------- @@ -44,14 +45,18 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { private def playSynchronously(): Unit = { try { // Trying to parse URL and sending request to host - val connection = + val connection = { new URI(url.get) - .toURL - .openConnection - .asInstanceOf[HttpURLConnection] + .toURL + .openConnection + .asInstanceOf[HttpURLConnection] + } connection.setRequestMethod("GET") - connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36") + connection.setRequestProperty( + "User-Agent", + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36", + ) connection.setRequestProperty("Content-Language", "en-US") connection.setDoInput(true) connection.setDoOutput(true) @@ -65,21 +70,22 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { 2, 4, 44100, - false + false, ), // Obtaining audio input stream from HTTP connection - AudioSystem.getAudioInputStream(new BufferedInputStream(connection.getInputStream)) + AudioSystem.getAudioInputStream(new BufferedInputStream(connection.getInputStream)), ) // Keeping input stream format parameters here to offload the reading loop val inputStreamFormat = inputStream.getFormat val inputStreamSampleRate = inputStreamFormat.getSampleRate.toInt - val inputStreamSoundSampleFormat = + val inputStreamSoundSampleFormat = { if (inputStreamFormat.getChannels > 1) Format.Stereo16 else Format.Mono16 + } // Creating Ocelot output sound stream val (outputStream, outputSource) = Audio.newStream(SoundCategory.Records, volume = volume) @@ -99,7 +105,7 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { .flip .asInstanceOf[ByteBuffer], inputStreamSampleRate, - inputStreamSoundSampleFormat + inputStreamSoundSampleFormat, )) } @@ -107,8 +113,7 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { } logger.info("OpenFM input audio stream has reached EOF, closing thread") - } - catch { + } catch { case _: InterruptedException => case e: Exception => logger.error("OpenFM playback exception", e) } @@ -168,6 +173,7 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { private var _volume: Float = 1 def volume: Float = _volume + def volume_=(value: Float): Unit = { _volume = value @@ -211,7 +217,7 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { // --------------------------- Screen color/text --------------------------- private val defaultScreenText = "OpenFM" - private val defaultScreenColor = IntColor(0x0AFF0A) + private val defaultScreenColor = IntColor(0x0aff0a) var screenColor: IntColor = defaultScreenColor private var _screenText: String = defaultScreenText @@ -272,23 +278,26 @@ class OpenFMRadio extends Entity with Environment with DeviceInfo with Logging { if (nbt.hasKey("url")) url = Option(nbt.getString("url")) - screenColor = + screenColor = { if (nbt.hasKey("screenColor")) IntColor(nbt.getInteger("screenColor")) else defaultScreenColor + } - screenText = + screenText = { if (nbt.hasKey("screenText")) nbt.getString("screenText") else defaultScreenText + } - volume = + volume = { if (nbt.hasKey("volume")) nbt.getDouble("volume").toFloat else 1 + } isListenRedstone = nbt.hasKey("isListenRedstone") && nbt.getBoolean("isListenRedstone") diff --git a/src/main/scala/ocelot/desktop/entity/traits/OcelotInterface.scala b/src/main/scala/ocelot/desktop/entity/traits/OcelotInterface.scala index 3aa4193..a7455e6 100644 --- a/src/main/scala/ocelot/desktop/entity/traits/OcelotInterface.scala +++ b/src/main/scala/ocelot/desktop/entity/traits/OcelotInterface.scala @@ -2,7 +2,7 @@ package ocelot.desktop.entity.traits import ocelot.desktop.entity.traits.OcelotInterface.LogEvent import totoro.ocelot.brain.entity.machine.{Arguments, Callback, Context} -import totoro.ocelot.brain.entity.traits.{Entity, Environment, result} +import totoro.ocelot.brain.entity.traits.{result, Entity, Environment} import totoro.ocelot.brain.event.{EventBus, NodeEvent} import java.time.Instant @@ -21,7 +21,8 @@ trait OcelotInterface extends Entity with Environment { result() } - @Callback(direct = true, doc = """function(): integer -- Returns the current Unix timestamp (UTC, in milliseconds).""") + @Callback(direct = true, + doc = """function(): integer -- Returns the current Unix timestamp (UTC, in milliseconds).""") def getTimestamp(context: Context, args: Arguments): Array[AnyRef] = { result(Instant.now().toEpochMilli) } diff --git a/src/main/scala/ocelot/desktop/geometry/Basis3D.scala b/src/main/scala/ocelot/desktop/geometry/Basis3D.scala index 94c9ef5..833f4b2 100644 --- a/src/main/scala/ocelot/desktop/geometry/Basis3D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Basis3D.scala @@ -27,25 +27,25 @@ case class Basis3D(x: Vector3D, y: Vector3D, z: Vector3D) { def *(rhs: Vector3D): Vector3D = Vector3D( x.x * rhs.x + y.x * rhs.y + z.x * rhs.z, x.y * rhs.x + y.y * rhs.y + z.y * rhs.z, - x.z * rhs.x + y.z * rhs.y + z.z * rhs.z + x.z * rhs.x + y.z * rhs.y + z.z * rhs.z, ) def *(rhs: Basis3D): Basis3D = Basis3D( Vector3D( x.x * rhs.x.x + y.x * rhs.x.y + z.x * rhs.x.z, x.y * rhs.x.x + y.y * rhs.x.y + z.y * rhs.x.z, - x.z * rhs.x.x + y.z * rhs.x.y + z.z * rhs.x.z + x.z * rhs.x.x + y.z * rhs.x.y + z.z * rhs.x.z, ), Vector3D( x.x * rhs.y.x + y.x * rhs.y.y + z.x * rhs.y.z, x.y * rhs.y.x + y.y * rhs.y.y + z.y * rhs.y.z, - x.z * rhs.y.x + y.z * rhs.y.y + z.z * rhs.y.z + x.z * rhs.y.x + y.z * rhs.y.y + z.z * rhs.y.z, ), Vector3D( x.x * rhs.z.x + y.x * rhs.z.y + z.x * rhs.z.z, x.y * rhs.z.x + y.y * rhs.z.y + z.y * rhs.z.z, - x.z * rhs.z.x + y.z * rhs.z.y + z.z * rhs.z.z - ) + x.z * rhs.z.x + y.z * rhs.z.y + z.z * rhs.z.z, + ), ) def det: Float = x.x * (y.y * z.z - z.y * y.z) - @@ -59,18 +59,18 @@ case class Basis3D(x: Vector3D, y: Vector3D, z: Vector3D) { Vector3D( (y.y * z.z - z.y * y.z) * s, (x.z * z.y - x.y * z.z) * s, - (x.y * y.z - x.z * y.y) * s + (x.y * y.z - x.z * y.y) * s, ), Vector3D( (y.z * z.x - y.x * z.z) * s, (x.x * z.z - x.z * z.x) * s, - (y.x * x.z - x.x * y.z) * s + (y.x * x.z - x.x * y.z) * s, ), Vector3D( (y.x * z.y - z.x * y.y) * s, (z.x * x.y - x.x * z.y) * s, - (x.x * y.y - y.x * x.y) * s - ) + (x.x * y.y - y.x * x.y) * s, + ), ) } diff --git a/src/main/scala/ocelot/desktop/geometry/ProjectionMatrix3D.scala b/src/main/scala/ocelot/desktop/geometry/ProjectionMatrix3D.scala index c8da411..1fdb4ab 100644 --- a/src/main/scala/ocelot/desktop/geometry/ProjectionMatrix3D.scala +++ b/src/main/scala/ocelot/desktop/geometry/ProjectionMatrix3D.scala @@ -3,11 +3,12 @@ package ocelot.desktop.geometry object ProjectionMatrix3D { def perspective(aspect: Float, fovY: Float, zNear: Float, zFar: Float): ProjectionMatrix3D = { val f = (1.0 / math.tan(math.toRadians(fovY) / 2.0)).toFloat + // format: off ProjectionMatrix3D( f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (zFar + zNear) / (zNear - zFar), (2 * zFar * zNear) / (zNear - zFar), - 0, 0, -1, 0 + 0, 0, -1, 0, ) } } @@ -15,7 +16,6 @@ object ProjectionMatrix3D { case class ProjectionMatrix3D(m11: Float, m12: Float, m13: Float, m14: Float, m21: Float, m22: Float, m23: Float, m24: Float, m31: Float, m32: Float, m33: Float, m34: Float, - m41: Float, m42: Float, m43: Float, m44: Float) -{ + m41: Float, m42: Float, m43: Float, m44: Float) { def array: Array[Float] = Array(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) } diff --git a/src/main/scala/ocelot/desktop/geometry/Quaternion.scala b/src/main/scala/ocelot/desktop/geometry/Quaternion.scala index 9da525a..f4bc3ae 100644 --- a/src/main/scala/ocelot/desktop/geometry/Quaternion.scala +++ b/src/main/scala/ocelot/desktop/geometry/Quaternion.scala @@ -55,7 +55,7 @@ case class Quaternion(x: Float, y: Float, z: Float, w: Float) { y * rhs.z - z * rhs.y + x * rhs.w + w * rhs.x, z * rhs.x - x * rhs.z + y * rhs.w + w * rhs.y, x * rhs.y - y * rhs.x + z * rhs.w + w * rhs.z, - w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z + w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z, ) def conj: Quaternion = Quaternion(-x, -y, -z, w) @@ -72,7 +72,7 @@ case class Quaternion(x: Float, y: Float, z: Float, w: Float) { def basis: Basis3D = Basis3D( Vector3D(1 - 2 * y * y - 2 * z * z, 2 * x * y + 2 * z * w, 2 * x * z - 2 * y * w), Vector3D(2 * x * y - 2 * z * w, 1 - 2 * x * x - 2 * z * z, 2 * y * z + 2 * x * w), - Vector3D(2 * x * z + 2 * y * w, 2 * y * z - 2 * x * w, 1 - 2 * x * x - 2 * y * y) + Vector3D(2 * x * z + 2 * y * w, 2 * y * z - 2 * x * w, 1 - 2 * x * x - 2 * y * y), ) def dot(that: Quaternion): Float = x * that.x + y * that.y + z * that.z + w * that.w diff --git a/src/main/scala/ocelot/desktop/geometry/Rect2D.scala b/src/main/scala/ocelot/desktop/geometry/Rect2D.scala index fe5477c..8f4a8f6 100644 --- a/src/main/scala/ocelot/desktop/geometry/Rect2D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Rect2D.scala @@ -86,7 +86,8 @@ case class Rect2D(x: Float, y: Float, w: Float, h: Float) { Vector2D(x + w / 2f, y), Vector2D(x + w, y + h / 2f), Vector2D(x + w / 2f, y + h), - Vector2D(x, y + h / 2f)) + Vector2D(x, y + h / 2f), + ) def distanceTo(that: Rect2D): Float = { ((center - that.center).abs - (extent + that.extent)).max(Vector2D(0, 0)).length diff --git a/src/main/scala/ocelot/desktop/geometry/Size2D.scala b/src/main/scala/ocelot/desktop/geometry/Size2D.scala index 9a4fbcb..9f2698f 100644 --- a/src/main/scala/ocelot/desktop/geometry/Size2D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Size2D.scala @@ -32,7 +32,7 @@ case class Size2D(width: Float, height: Float) { def clamped(min: Size2D, max: Size2D): Size2D = { Size2D( math.min(max.width, math.max(min.width, width)), - math.min(max.height, math.max(min.height, height)) + math.min(max.height, math.max(min.height, height)), ) } @@ -51,4 +51,4 @@ case class Size2D(width: Float, height: Float) { def /(mul: Float): Size2D = Size2D(width / mul, height / mul) override def toString: String = f"Size2D [ $width%8.2f x $height%8.2f ]" -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/geometry/Transform2D.scala b/src/main/scala/ocelot/desktop/geometry/Transform2D.scala index 52fbe9f..2bfb98d 100644 --- a/src/main/scala/ocelot/desktop/geometry/Transform2D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Transform2D.scala @@ -5,19 +5,19 @@ import java.nio.ByteBuffer object Transform2D { def identity: Transform2D = Transform2D( 1, 0, 0, - 0, 1, 0 + 0, 1, 0, ) def scale(x: Float, y: Float): Transform2D = Transform2D( x, 0, 0, - 0, y, 0 + 0, y, 0, ) def scale(a: Float): Transform2D = Transform2D.scale(a, a) def translate(x: Float, y: Float): Transform2D = Transform2D( 1, 0, x, - 0, 1, y + 0, 1, y, ) def viewport(width: Float, height: Float): Transform2D = @@ -26,6 +26,7 @@ object Transform2D { def rotate(angle: Float): Transform2D = { val (s, c) = (math.sin(angle).asInstanceOf[Float], math.cos(angle).asInstanceOf[Float]) + // format: off Transform2D( c, -s, 0, s, c, 0 @@ -36,13 +37,13 @@ object Transform2D { case class Transform2D(m11: Float, m12: Float, m13: Float, m21: Float, m22: Float, m23: Float) { def array: Array[Float] = Array(m11, m12, m13, m21, m22, m23) - // :| + // format: off def >>(that: Transform2D): Transform2D = Transform2D( m11 * that.m11 + m12 * that.m21, m11 * that.m12 + m12 * that.m22, m11 * that.m13 + m12 * that.m23 + m13, m21 * that.m11 + m22 * that.m21, m21 * that.m12 + m22 * that.m22, m21 * that.m13 + m22 * that.m23 + m23, ) - // (●__●) + // format: off def <<(that: Transform2D): Transform2D = Transform2D( m11 * that.m11 + m21 * that.m12, m12 * that.m11 + m22 * that.m12, m13 * that.m11 + m23 * that.m12 + that.m13, m11 * that.m21 + m21 * that.m22, m12 * that.m21 + m22 * that.m22, m13 * that.m21 + m23 * that.m22 + that.m23 @@ -50,13 +51,14 @@ case class Transform2D(m11: Float, m12: Float, m13: Float, m21: Float, m22: Floa def *(that: Vector2D): Vector2D = Vector2D( m11 * that.x + m12 * that.y + m13, - m21 * that.x + m22 * that.y + m23 + m21 * that.x + m22 * that.y + m23, ) - override def toString: String = + override def toString: String = { f"""Transform2D [$m11%6.3f $m12%6.3f $m13%6.3f] | [$m21%6.3f $m22%6.3f $m23%6.3f] """.stripMargin + } // (╯°□°)╯︵ ┻━┻ def put(buffer: ByteBuffer): Unit = { diff --git a/src/main/scala/ocelot/desktop/geometry/Transform3D.scala b/src/main/scala/ocelot/desktop/geometry/Transform3D.scala index 5ebdb2d..8fdc256 100644 --- a/src/main/scala/ocelot/desktop/geometry/Transform3D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Transform3D.scala @@ -26,6 +26,7 @@ object Transform3D { } case class Transform3D(basis: Basis3D, origin: Vector3D) { + // format: off def array: Array[Float] = Array( basis.x.x, basis.y.x, basis.z.x, origin.x, basis.x.y, basis.y.y, basis.z.y, origin.y, @@ -44,8 +45,8 @@ case class Transform3D(basis: Basis3D, origin: Vector3D) { override def toString: String = s"Transform3D [${basis.x}, ${basis.y}, ${basis.z}, $origin]" def put(buffer: ByteBuffer): Unit = { - buffer.putFloat(basis.x.x); buffer.putFloat(basis.y.x); buffer.putFloat(basis.z.x); buffer.putFloat(origin.x); - buffer.putFloat(basis.x.y); buffer.putFloat(basis.y.y); buffer.putFloat(basis.z.y); buffer.putFloat(origin.y); - buffer.putFloat(basis.x.z); buffer.putFloat(basis.y.z); buffer.putFloat(basis.z.z); buffer.putFloat(origin.z); + buffer.putFloat(basis.x.x); buffer.putFloat(basis.y.x); buffer.putFloat(basis.z.x); buffer.putFloat(origin.x) + buffer.putFloat(basis.x.y); buffer.putFloat(basis.y.y); buffer.putFloat(basis.z.y); buffer.putFloat(origin.y) + buffer.putFloat(basis.x.z); buffer.putFloat(basis.y.z); buffer.putFloat(basis.z.z); buffer.putFloat(origin.z) } } diff --git a/src/main/scala/ocelot/desktop/geometry/Vector3D.scala b/src/main/scala/ocelot/desktop/geometry/Vector3D.scala index 2f9846c..22cd0cf 100644 --- a/src/main/scala/ocelot/desktop/geometry/Vector3D.scala +++ b/src/main/scala/ocelot/desktop/geometry/Vector3D.scala @@ -41,7 +41,7 @@ case class Vector3D(x: Float, y: Float, z: Float) { def cross(that: Vector3D): Vector3D = Vector3D( y * that.z - z * that.y, z * that.x - x * that.z, - x * that.y - y * that.x + x * that.y - y * that.x, ) def angle(that: Vector3D): Float = { diff --git a/src/main/scala/ocelot/desktop/graphics/Graphics.scala b/src/main/scala/ocelot/desktop/graphics/Graphics.scala index 7ae4d5a..8e76669 100644 --- a/src/main/scala/ocelot/desktop/graphics/Graphics.scala +++ b/src/main/scala/ocelot/desktop/graphics/Graphics.scala @@ -17,7 +17,8 @@ import scala.collection.mutable import scala.util.control.Breaks._ //noinspection ScalaWeakerAccess,ScalaUnusedSymbol -class Graphics(private var width: Int, private var height: Int, private var scalingFactor: Float) extends Logging with Resource { +class Graphics(private var width: Int, private var height: Int, private var scalingFactor: Float) + extends Logging with Resource { private var time = 0f private var projection = Transform2D.viewport(width, height) @@ -33,12 +34,15 @@ class Graphics(private var width: Int, private var height: Int, private var scal private val stack = mutable.Stack[GraphicsState](GraphicsState()) private var spriteRect = Spritesheet.sprites("Empty") - private val emptySpriteTrans = Transform2D.translate(spriteRect.x, spriteRect.y) >> Transform2D.scale(spriteRect.w, spriteRect.h) + + private val emptySpriteTrans = + Transform2D.translate(spriteRect.x, spriteRect.y) >> Transform2D.scale(spriteRect.w, spriteRect.h) private val offscreenTexture = new Texture(width, height, GL21.GL_SRGB8_ALPHA8, GL11.GL_UNSIGNED_BYTE, GL11.GL_RGBA) private val offscreenFramebuffer = ARBFramebufferObject.glGenFramebuffers() GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, offscreenFramebuffer) + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, offscreenTexture.texture, 0) @@ -152,7 +156,7 @@ class Graphics(private var width: Int, private var height: Int, private var scal viewport: ScreenViewport, bounds: Rect2D, filteringMode: MinFilteringMode = MinFilteringMode.Nearest, - alpha: Float = 1.0f + alpha: Float = 1.0f, ): Unit = { flush() foreground = RGBAColorNorm(1, 1, 1, alpha) @@ -255,16 +259,17 @@ class Graphics(private var width: Int, private var height: Int, private var scal val uvTransform = Transform2D.translate( rect.x, - rect.y + rect.y, ) >> Transform2D.scale( rect.w - 0.25f / _font.AtlasWidth, - rect.h - 0.25f / _font.AtlasHeight + rect.h - 0.25f / _font.AtlasHeight, ) - val transform = + val transform = { stack.head.transform >> Transform2D.translate(x.round, y.round) >> Transform2D.scale(_font.charWidth(c), fontSize) + } val foreground = stack.head.foreground.toRGBANorm.mapA(_ * alphaMultiplier) val background = stack.head.background.toRGBANorm.mapA(_ * alphaMultiplier) @@ -333,8 +338,7 @@ class Graphics(private var width: Int, private var height: Int, private var scal def sprite(name: String, x: Float, y: Float, width: Float, height: Float, color: Color = Color.White, - animation: Option[Animation] = None): Unit = - { + animation: Option[Animation] = None): Unit = { sprite = name foreground = color _rect(x, y, width, height, fixUV = true, animation) @@ -385,14 +389,15 @@ class Graphics(private var width: Int, private var height: Int, private var scal val uvTransform = Transform2D.translate(spriteRect.x, spriteRect.y) >> (if (fixUV) - Transform2D.scale(spriteRect.w - 0.25f / 1024, spriteRect.h - 0.25f / 1024) - else - Transform2D.scale(spriteRect.w, spriteRect.h)) + Transform2D.scale(spriteRect.w - 0.25f / 1024, spriteRect.h - 0.25f / 1024) + else + Transform2D.scale(spriteRect.w, spriteRect.h)) - val transform = + val transform = { stack.head.transform >> Transform2D.translate(x, y) >> Transform2D.scale(width, height) + } val color = stack.head.foreground.toRGBANorm.mapA(_ * alphaMultiplier) @@ -426,9 +431,9 @@ class Graphics(private var width: Int, private var height: Int, private var scal for (y <- 0 until height) { for (x <- 0 until width) { val i = (x + (height - y - 1) * width) * 4 - val r = buffer.get(i) & 0xFF - val g = buffer.get(i + 1) & 0xFF - val b = buffer.get(i + 2) & 0xFF + val r = buffer.get(i) & 0xff + val g = buffer.get(i + 1) & 0xff + val b = buffer.get(i + 2) & 0xff val rgb = (r << 16) | (g << 8) | b image.setRGB(x, y, rgb) } @@ -456,7 +461,7 @@ class Graphics(private var width: Int, private var height: Int, private var scal Math.round(x * scalingFactor), Math.round(height - h * scalingFactor - y * scalingFactor), Math.round(w * scalingFactor), - Math.round(h * scalingFactor) + Math.round(h * scalingFactor), ) case _ => GL11.glDisable(GL11.GL_SCISSOR_TEST) diff --git a/src/main/scala/ocelot/desktop/graphics/GraphicsState.scala b/src/main/scala/ocelot/desktop/graphics/GraphicsState.scala index 16235cd..7ea78ed 100644 --- a/src/main/scala/ocelot/desktop/graphics/GraphicsState.scala +++ b/src/main/scala/ocelot/desktop/graphics/GraphicsState.scala @@ -10,5 +10,5 @@ case class GraphicsState( var alphaMultiplier: Float = 1f, var sprite: String = "Empty", var scissor: Option[(Float, Float, Float, Float)] = None, - var transform: Transform2D = Transform2D.identity + var transform: Transform2D = Transform2D.identity, ) diff --git a/src/main/scala/ocelot/desktop/graphics/IconSource.scala b/src/main/scala/ocelot/desktop/graphics/IconSource.scala index 06a178a..ecb83c1 100644 --- a/src/main/scala/ocelot/desktop/graphics/IconSource.scala +++ b/src/main/scala/ocelot/desktop/graphics/IconSource.scala @@ -94,7 +94,7 @@ object IconSource { val DiskDriveMountable: IconSource = IconSource("items/DiskDriveMountable") - //noinspection ScalaWeakerAccess + // noinspection ScalaWeakerAccess object Animations { val Apu: Animation = Animation((0, 3f), (1, 3f), (2, 3f), (3, 3f), (4, 3f), (5, 3f), (4, 3f), (3, 3f), (2, 3f), (1, 3f), (0, 3f)) @@ -115,6 +115,7 @@ object IconSource { } case class Animation(frames: Array[(Int, Float)], frameSize: Option[Size2D]) + object Animation { def apply(frames: (Int, Float)*) = new Animation(frames.toArray, None) def apply(size: Size2D, frames: (Int, Float)*) = new Animation(frames.toArray, Some(size)) @@ -127,23 +128,26 @@ object IconSource { IconSource(s"icons/Notification$notificationType") } - val Loading: IconSource = IconSource("Loading", animation = Some(Animation( - Size2D(48, 32), - (0, 0.7f), - (1, 0.7f), - (2, 0.7f), - (3, 0.7f), - (4, 0.7f), - (5, 0.7f), - (6, 0.7f), - (7, 0.7f), - (8, 0.7f), - (9, 0.7f), - (10, 0.7f), - (11, 0.7f), - (12, 0.7f), - (13, 0.7f), - ))) + val Loading: IconSource = IconSource( + "Loading", + animation = Some(Animation( + Size2D(48, 32), + (0, 0.7f), + (1, 0.7f), + (2, 0.7f), + (3, 0.7f), + (4, 0.7f), + (5, 0.7f), + (6, 0.7f), + (7, 0.7f), + (8, 0.7f), + (9, 0.7f), + (10, 0.7f), + (11, 0.7f), + (12, 0.7f), + (13, 0.7f), + )), + ) val SettingsSystem: IconSource = IconSource("icons/SettingsSystem") val SettingsSound: IconSource = IconSource("icons/SettingsSound") diff --git a/src/main/scala/ocelot/desktop/graphics/ScreenViewport.scala b/src/main/scala/ocelot/desktop/graphics/ScreenViewport.scala index 8f71679..54bb181 100644 --- a/src/main/scala/ocelot/desktop/graphics/ScreenViewport.scala +++ b/src/main/scala/ocelot/desktop/graphics/ScreenViewport.scala @@ -21,6 +21,7 @@ class ScreenViewport(graphics: Graphics, private var _width: Int, private var _h private val _font = graphics.normalFont private val spriteRect = Spritesheet.sprites("Empty") + private val emptySpriteTrans = Transform2D.translate(spriteRect.x, spriteRect.y) >> Transform2D.scale(spriteRect.w, spriteRect.h) diff --git a/src/main/scala/ocelot/desktop/graphics/ShaderProgram.scala b/src/main/scala/ocelot/desktop/graphics/ShaderProgram.scala index c4d1256..985c372 100644 --- a/src/main/scala/ocelot/desktop/graphics/ShaderProgram.scala +++ b/src/main/scala/ocelot/desktop/graphics/ShaderProgram.scala @@ -12,10 +12,15 @@ class ShaderProgram(name: String) extends Logging with Resource { private val fragmentShader: Int = createShader( Source.fromResource(s"ocelot/desktop/shader/$name.frag", getClass.getClassLoader), - GL20.GL_FRAGMENT_SHADER, "fragment") + GL20.GL_FRAGMENT_SHADER, + "fragment", + ) + private val vertexShader: Int = createShader( Source.fromResource(s"ocelot/desktop/shader/$name.vert", getClass.getClassLoader), - GL20.GL_VERTEX_SHADER, "vertex") + GL20.GL_VERTEX_SHADER, + "vertex", + ) val shaderProgram: Int = GL20.glCreateProgram() diff --git a/src/main/scala/ocelot/desktop/graphics/Texture.scala b/src/main/scala/ocelot/desktop/graphics/Texture.scala index 7898ad0..52d8db6 100644 --- a/src/main/scala/ocelot/desktop/graphics/Texture.scala +++ b/src/main/scala/ocelot/desktop/graphics/Texture.scala @@ -28,23 +28,25 @@ class Texture() extends Logging with Resource { for (y <- 0 until image.getHeight) { for (x <- 0 until image.getWidth) { val pixel = pixels(y * image.getWidth + x) - buf.put(((pixel >> 16) & 0xFF).toByte) - buf.put(((pixel >> 8) & 0xFF).toByte) - buf.put((pixel & 0xFF).toByte) - buf.put(((pixel >> 24) & 0xFF).toByte) + buf.put(((pixel >> 16) & 0xff).toByte) + buf.put(((pixel >> 8) & 0xff).toByte) + buf.put((pixel & 0xff).toByte) + buf.put(((pixel >> 24) & 0xff).toByte) } } buf.flip() bind() - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL21.GL_SRGB8_ALPHA8, image.getWidth, image.getHeight, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buf) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL21.GL_SRGB8_ALPHA8, image.getWidth, image.getHeight, 0, GL11.GL_RGBA, + GL11.GL_UNSIGNED_BYTE, buf) } def this(width: Int, height: Int, format: Int, dataType: Int, internalFormat: Int) = { this() bind() - GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, format, width, height, 0, internalFormat, dataType, null.asInstanceOf[ByteBuffer]) + GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, format, width, height, 0, internalFormat, dataType, + null.asInstanceOf[ByteBuffer]) } def this(width: Int, height: Int, format: Int, dataType: Int) = { @@ -88,7 +90,7 @@ class Texture() extends Logging with Resource { } object Texture { - class MinFilteringMode private(private[Texture] val glValue: Int, val needsMipmap: Boolean) + class MinFilteringMode private (private[Texture] val glValue: Int, val needsMipmap: Boolean) object MinFilteringMode { val Nearest = new MinFilteringMode(GL11.GL_NEAREST, false) diff --git a/src/main/scala/ocelot/desktop/graphics/Viewport3D.scala b/src/main/scala/ocelot/desktop/graphics/Viewport3D.scala index dc819a6..b54fc1e 100644 --- a/src/main/scala/ocelot/desktop/graphics/Viewport3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/Viewport3D.scala @@ -14,8 +14,13 @@ class Viewport3D(width: Int, height: Int) extends Resource with Logging { private val framebuffer = ARBFramebufferObject.glGenFramebuffers() GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, framebuffer) - GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, textureColor.texture, 0) - GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, textureDepth.texture, 0) + + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL11.GL_TEXTURE_2D, textureColor.texture, + 0) + + GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, textureDepth.texture, + 0) + GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0) private type Instancer = InstanceRenderer[MeshVertex3D, MeshInstance3D] @@ -84,7 +89,8 @@ class Viewport3D(width: Int, height: Int) extends Resource with Logging { private def setupLight(scene: Scene3D): Unit = { shaderProgram.set("uLightDir", scene.lightSource.basis.up) shaderProgram.set("uLightColor", scene.lightSource.color.toRGBANorm.toLinear.rgbVector * scene.lightSource.energy) - shaderProgram.set("uAmbientLightColor", scene.ambientLightColor.toRGBANorm.toLinear.rgbVector * scene.ambientLightEnergy) + shaderProgram.set("uAmbientLightColor", + scene.ambientLightColor.toRGBANorm.toLinear.rgbVector * scene.ambientLightEnergy) } private def collectOpaque(scene: Scene3D): Unit = { diff --git a/src/main/scala/ocelot/desktop/graphics/buffer/VertexBuffer.scala b/src/main/scala/ocelot/desktop/graphics/buffer/VertexBuffer.scala index b1c17da..9099415 100644 --- a/src/main/scala/ocelot/desktop/graphics/buffer/VertexBuffer.scala +++ b/src/main/scala/ocelot/desktop/graphics/buffer/VertexBuffer.scala @@ -21,4 +21,4 @@ class VertexBuffer[V <: Vertex] extends Buffer[V] { ty = head.vertexType super.extractMeta(head) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/Mesh2D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/Mesh2D.scala index 2780ad4..4a7e678 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/Mesh2D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/Mesh2D.scala @@ -6,8 +6,9 @@ import ocelot.desktop.graphics.buffer.Index object Mesh2D { val quad: Mesh2D = new Mesh2D( Array(Vector2D(0f, 0f), Vector2D(1f, 0f), Vector2D(1f, 1f), - Vector2D(1f, 1f), Vector2D(0f, 1f), Vector2D(0f, 0f)).map(v => MeshVertex2D(v, v)), + Vector2D(1f, 1f), Vector2D(0f, 1f), Vector2D(0f, 0f)).map(v => MeshVertex2D(v, v)) ) } -class Mesh2D(override val vertices: Seq[MeshVertex2D], override val indices: Option[Seq[Index]] = None) extends Mesh[MeshVertex2D] +class Mesh2D(override val vertices: Seq[MeshVertex2D], override val indices: Option[Seq[Index]] = None) + extends Mesh[MeshVertex2D] diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/Mesh3D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/Mesh3D.scala index 1ab5bc6..a4014e2 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/Mesh3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/Mesh3D.scala @@ -50,8 +50,8 @@ object Mesh3D { } class Mesh3D(override val vertices: Seq[MeshVertex3D], override val indices: Option[Seq[Index]] = None, - override val primitiveType: PrimitiveType = PrimitiveTriangles) extends Mesh[MeshVertex3D] -{ + override val primitiveType: PrimitiveType = PrimitiveTriangles) + extends Mesh[MeshVertex3D] { val boundingBox: Box3D = { Box3D.fromVertices(vertices.iterator.map(_.pos)) } diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/MeshBuilder3D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/MeshBuilder3D.scala index 6af6b7d..955680e 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/MeshBuilder3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/MeshBuilder3D.scala @@ -43,8 +43,7 @@ class MeshBuilder3D { def triangle(a: Vector3D, aUV: Vector2D, b: Vector3D, bUV: Vector2D, - c: Vector3D, cUV: Vector2D): Unit = - { + c: Vector3D, cUV: Vector2D): Unit = { val normal = (b - a).cross(c - a).normalize val aIdx = vertex(a, normal, aUV) val bIdx = vertex(b, normal, bUV) @@ -56,8 +55,7 @@ class MeshBuilder3D { b: Vector3D, bUV: Vector2D, c: Vector3D, cUV: Vector2D, d: Vector3D, dUV: Vector2D, - color: Color): Unit = - { + color: Color): Unit = { val normal = (b - a).cross(c - a).normalize val aIdx = vertex(a, normal, aUV, color) val bIdx = vertex(b, normal, bUV, color) @@ -74,15 +72,19 @@ class MeshBuilder3D { spriteRect.x + cutRect.x * spriteUVScale * spriteRect.w, spriteRect.y + cutRect.y * spriteUVScale * spriteRect.w, cutRect.w * spriteUVScale * spriteRect.w, - cutRect.h * spriteUVScale * spriteRect.h + cutRect.h * spriteUVScale * spriteRect.h, ) quad( - a, Vector2D(rect.x + rect.w, rect.y), - b, Vector2D(rect.x, rect.y), - c, Vector2D(rect.x, rect.y + rect.h), - d, Vector2D(rect.x + rect.w, rect.y + rect.h), - color + a, + Vector2D(rect.x + rect.w, rect.y), + b, + Vector2D(rect.x, rect.y), + c, + Vector2D(rect.x, rect.y + rect.h), + d, + Vector2D(rect.x + rect.w, rect.y + rect.h), + color, ) } @@ -93,55 +95,72 @@ class MeshBuilder3D { back: Option[(String, Rect2D)] = Some(("Empty", Rect2D.Unit)), top: Option[(String, Rect2D)] = Some(("Empty", Rect2D.Unit)), bottom: Option[(String, Rect2D)] = Some(("Empty", Rect2D.Unit)), - color: Color = Color.White): Unit = - { - left.foreach(sprite => quad( - Vector3D(min.x, max.y, max.z), - Vector3D(min.x, max.y, min.z), - Vector3D(min.x, min.y, min.z), - Vector3D(min.x, min.y, max.z), - sprite, color, - )) + color: Color = Color.White): Unit = { + left.foreach(sprite => { + quad( + Vector3D(min.x, max.y, max.z), + Vector3D(min.x, max.y, min.z), + Vector3D(min.x, min.y, min.z), + Vector3D(min.x, min.y, max.z), + sprite, + color, + ) + }) - right.foreach(sprite => quad( - Vector3D(max.x, max.y, min.z), - Vector3D(max.x, max.y, max.z), - Vector3D(max.x, min.y, max.z), - Vector3D(max.x, min.y, min.z), - sprite, color, - )) + right.foreach(sprite => { + quad( + Vector3D(max.x, max.y, min.z), + Vector3D(max.x, max.y, max.z), + Vector3D(max.x, min.y, max.z), + Vector3D(max.x, min.y, min.z), + sprite, + color, + ) + }) - front.foreach(sprite => quad( - Vector3D(min.x, max.y, min.z), - Vector3D(max.x, max.y, min.z), - Vector3D(max.x, min.y, min.z), - Vector3D(min.x, min.y, min.z), - sprite, color, - )) + front.foreach(sprite => { + quad( + Vector3D(min.x, max.y, min.z), + Vector3D(max.x, max.y, min.z), + Vector3D(max.x, min.y, min.z), + Vector3D(min.x, min.y, min.z), + sprite, + color, + ) + }) - back.foreach(sprite => quad( - Vector3D(max.x, max.y, max.z), - Vector3D(min.x, max.y, max.z), - Vector3D(min.x, min.y, max.z), - Vector3D(max.x, min.y, max.z), - sprite, color, - )) + back.foreach(sprite => { + quad( + Vector3D(max.x, max.y, max.z), + Vector3D(min.x, max.y, max.z), + Vector3D(min.x, min.y, max.z), + Vector3D(max.x, min.y, max.z), + sprite, + color, + ) + }) - top.foreach(sprite => quad( - Vector3D(max.x, max.y, min.z), - Vector3D(min.x, max.y, min.z), - Vector3D(min.x, max.y, max.z), - Vector3D(max.x, max.y, max.z), - sprite, color, - )) + top.foreach(sprite => { + quad( + Vector3D(max.x, max.y, min.z), + Vector3D(min.x, max.y, min.z), + Vector3D(min.x, max.y, max.z), + Vector3D(max.x, max.y, max.z), + sprite, + color, + ) + }) - bottom.foreach(sprite => quad( - Vector3D(max.x, min.y, max.z), - Vector3D(min.x, min.y, max.z), - Vector3D(min.x, min.y, min.z), - Vector3D(max.x, min.y, min.z), - sprite, color, - )) + bottom.foreach(sprite => { + quad( + Vector3D(max.x, min.y, max.z), + Vector3D(min.x, min.y, max.z), + Vector3D(min.x, min.y, min.z), + Vector3D(max.x, min.y, min.z), + sprite, + color, + ) + }) } def line(a: Vector3D, b: Vector3D, aColor: Color = Color.White, bColor: Color = Color.White): Unit = { @@ -154,4 +173,4 @@ class MeshBuilder3D { new Mesh3D(vertices.toSeq, indices = Some(indices.toSeq), primitiveType = primitiveType.getOrElse(PrimitiveTriangles)) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance2D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance2D.scala index 7b1c199..ae66ed9 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance2D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance2D.scala @@ -22,8 +22,8 @@ object MeshInstance2D extends VertexType { } case class MeshInstance2D(color: Color, textColor: Color, transform: Transform2D, uvTransform: Transform2D, - textUvTransform: Transform2D) extends Vertex -{ + textUvTransform: Transform2D) + extends Vertex { override def stride: Int = MeshInstance2D.stride override def vertexType: VertexType = MeshInstance2D diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance3D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance3D.scala index 7e84547..45db4d3 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/MeshInstance3D.scala @@ -17,13 +17,13 @@ object MeshInstance3D extends VertexType { Attribute("inUVTransform0", 3, GL11.GL_FLOAT, normalized = false, stride, 64), Attribute("inUVTransform1", 3, GL11.GL_FLOAT, normalized = false, stride, 76), Attribute("inLightingFactor", 1, GL11.GL_FLOAT, normalized = false, stride, 88), - Attribute("inTextureFactor", 1, GL11.GL_FLOAT, normalized = false, stride, 92) + Attribute("inTextureFactor", 1, GL11.GL_FLOAT, normalized = false, stride, 92), ) } case class MeshInstance3D(color: Color, transform: Transform3D, uvTransform: Transform2D, - lightingFactor: Float, textureFactor: Float) extends Vertex -{ + lightingFactor: Float, textureFactor: Float) + extends Vertex { override def vertexType: VertexType = MeshInstance3D override def stride: Int = MeshInstance3D.stride diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/MeshVertex2D.scala b/src/main/scala/ocelot/desktop/graphics/mesh/MeshVertex2D.scala index afb3118..95e7fea 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/MeshVertex2D.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/MeshVertex2D.scala @@ -10,7 +10,7 @@ object MeshVertex2D extends VertexType { override val attributes: Seq[Attribute] = Array( Attribute("inPos", 2, GL11.GL_FLOAT, normalized = false, stride, 0), - Attribute("inUV", 2, GL11.GL_FLOAT, normalized = false, stride, 8) + Attribute("inUV", 2, GL11.GL_FLOAT, normalized = false, stride, 8), ) } diff --git a/src/main/scala/ocelot/desktop/graphics/mesh/PrimitiveType.scala b/src/main/scala/ocelot/desktop/graphics/mesh/PrimitiveType.scala index a71553c..93c9f56 100644 --- a/src/main/scala/ocelot/desktop/graphics/mesh/PrimitiveType.scala +++ b/src/main/scala/ocelot/desktop/graphics/mesh/PrimitiveType.scala @@ -12,4 +12,4 @@ object PrimitiveTriangles extends PrimitiveType { object PrimitiveLines extends PrimitiveType { override def toGL: Int = GL11.GL_LINES -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/graphics/render/InstanceRenderer.scala b/src/main/scala/ocelot/desktop/graphics/render/InstanceRenderer.scala index ad423d6..1a06bbd 100644 --- a/src/main/scala/ocelot/desktop/graphics/render/InstanceRenderer.scala +++ b/src/main/scala/ocelot/desktop/graphics/render/InstanceRenderer.scala @@ -10,7 +10,8 @@ import org.lwjgl.opengl._ import java.nio.ByteBuffer import scala.collection.mutable.ArrayBuffer -class InstanceRenderer[V <: Vertex, I <: Vertex](mesh: Mesh[V], instanceType: VertexType, shader: ShaderProgram) extends Resource with Logging { +class InstanceRenderer[V <: Vertex, I <: Vertex](mesh: Mesh[V], instanceType: VertexType, shader: ShaderProgram) + extends Resource with Logging { private val InitialCapacity: Int = 1 private val vertexBuffer = new VertexBuffer[V](mesh.vertices) @@ -46,18 +47,20 @@ class InstanceRenderer[V <: Vertex, I <: Vertex](mesh: Mesh[V], instanceType: Ve ( method.invoke(null, "glDrawArraysInstancedARB"), - method.invoke(null, "glDrawElementsInstancedARB") + method.invoke(null, "glDrawElementsInstancedARB"), ) } private lazy val nglDrawElementsInstancedARB = { - val method = classOf[ARBDrawInstanced].getDeclaredMethod("nglDrawElementsInstancedARB", Integer.TYPE, Integer.TYPE, Integer.TYPE, java.lang.Long.TYPE, Integer.TYPE, java.lang.Long.TYPE) + val method = classOf[ARBDrawInstanced].getDeclaredMethod("nglDrawElementsInstancedARB", Integer.TYPE, Integer.TYPE, + Integer.TYPE, java.lang.Long.TYPE, Integer.TYPE, java.lang.Long.TYPE) method.setAccessible(true) method } private lazy val nglDrawArraysInstancedARB = { - val method = classOf[ARBDrawInstanced].getDeclaredMethod("nglDrawArraysInstancedARB", Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, java.lang.Long.TYPE) + val method = classOf[ARBDrawInstanced].getDeclaredMethod("nglDrawArraysInstancedARB", Integer.TYPE, Integer.TYPE, + Integer.TYPE, Integer.TYPE, java.lang.Long.TYPE) method.setAccessible(true) method } @@ -70,10 +73,12 @@ class InstanceRenderer[V <: Vertex, I <: Vertex](mesh: Mesh[V], instanceType: Ve indexBuffer match { case Some(ib) => - nglDrawElementsInstancedARB.invoke(null, mesh.primitiveType.toGL, ib.capacity, GL11.GL_UNSIGNED_INT, 0L, instances.length, glDrawElementsInstancedARBptr) + nglDrawElementsInstancedARB.invoke(null, mesh.primitiveType.toGL, ib.capacity, GL11.GL_UNSIGNED_INT, 0L, + instances.length, glDrawElementsInstancedARBptr) case None => - nglDrawArraysInstancedARB.invoke(null, mesh.primitiveType.toGL, 0, vertexBuffer.capacity, instances.length, glDrawArraysInstancedARBptr) + nglDrawArraysInstancedARB.invoke(null, mesh.primitiveType.toGL, 0, vertexBuffer.capacity, instances.length, + glDrawArraysInstancedARBptr) } instances.clear() diff --git a/src/main/scala/ocelot/desktop/graphics/scene/Camera3D.scala b/src/main/scala/ocelot/desktop/graphics/scene/Camera3D.scala index fd071d6..ac375dc 100644 --- a/src/main/scala/ocelot/desktop/graphics/scene/Camera3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/scene/Camera3D.scala @@ -4,8 +4,8 @@ import ocelot.desktop.geometry.{ProjectionMatrix3D, Vector3D} class Camera3D(var zNear: Float = 0.1f, var zFar: Float = 100.0f, - var fovY: Float = 80.0f) extends SceneNode3D -{ + var fovY: Float = 80.0f) + extends SceneNode3D { def distanceTo(point: Vector3D): Float = { (origin - point).length } diff --git a/src/main/scala/ocelot/desktop/graphics/scene/DirectionalLight3D.scala b/src/main/scala/ocelot/desktop/graphics/scene/DirectionalLight3D.scala index f30a058..e64cae1 100644 --- a/src/main/scala/ocelot/desktop/graphics/scene/DirectionalLight3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/scene/DirectionalLight3D.scala @@ -3,4 +3,5 @@ package ocelot.desktop.graphics.scene import ocelot.desktop.color.Color class DirectionalLight3D(var color: Color = Color.White, - var energy: Float = 1) extends SceneNode3D + var energy: Float = 1) + extends SceneNode3D diff --git a/src/main/scala/ocelot/desktop/graphics/scene/SceneMesh3D.scala b/src/main/scala/ocelot/desktop/graphics/scene/SceneMesh3D.scala index 4c579a8..d17c043 100644 --- a/src/main/scala/ocelot/desktop/graphics/scene/SceneMesh3D.scala +++ b/src/main/scala/ocelot/desktop/graphics/scene/SceneMesh3D.scala @@ -10,4 +10,5 @@ class SceneMesh3D(var mesh: Mesh3D, var lightingFactor: Float = 1, var textureFactor: Float = 1, var isOpaque: Boolean = true, - var priority: Int = 0) extends SceneNode3D \ No newline at end of file + var priority: Int = 0) + extends SceneNode3D diff --git a/src/main/scala/ocelot/desktop/inventory/Inventory.scala b/src/main/scala/ocelot/desktop/inventory/Inventory.scala index 16ec4e3..bd9e1dc 100644 --- a/src/main/scala/ocelot/desktop/inventory/Inventory.scala +++ b/src/main/scala/ocelot/desktop/inventory/Inventory.scala @@ -6,16 +6,12 @@ import totoro.ocelot.brain.event.NodeEvent import scala.collection.mutable -/** - * Provides an inventory — a collection of [[Item]]s indexed by slots. - */ +/** Provides an inventory — a collection of [[Item]]s indexed by slots. */ trait Inventory extends EventAware { // parallels totoro.ocelot.brain.entity.traits.Inventory // this is intentional - /** - * The type of items stored in this inventory. - */ + /** The type of items stored in this inventory. */ type I <: Item private type WeakHashSet[A] = mutable.WeakHashMap[A, Unit] @@ -24,15 +20,13 @@ trait Inventory extends EventAware { private val itemSlots = mutable.HashMap.empty[I, Int] private val observers = mutable.HashMap.empty[Int, WeakHashSet[SlotObserver]] - /** - * Called after a new item is added to the inventory. + /** Called after a new item is added to the inventory. * * @param slot the slot the item was added to */ def onItemAdded(slot: Slot): Unit - /** - * Called after an item is removed from the inventory. + /** Called after an item is removed from the inventory. * * When the item is replaced by another one, the event are sequenced in the following order: * @@ -47,9 +41,7 @@ trait Inventory extends EventAware { */ def onItemRemoved(slot: Slot, removedItem: I, replacedBy: Option[I]): Unit - /** - * An iterator over all slots occupied in this inventory. - */ + /** An iterator over all slots occupied in this inventory. */ def inventoryIterator: Iterator[Slot] = slotItems.keysIterator.map(Slot(_)) def clearInventory(): Unit = { @@ -86,46 +78,35 @@ trait Inventory extends EventAware { } } - /** - * A proxy to access a slot of the inventory. - */ - final class Slot private[Inventory](val index: Int) { + /** A proxy to access a slot of the inventory. */ + final class Slot private[Inventory] (val index: Int) { require(index >= 0) def isEmpty: Boolean = get.isEmpty def nonEmpty: Boolean = !isEmpty - /** - * Inserts the `item` into this slot (replacing the previous item if any). - */ + /** Inserts the `item` into this slot (replacing the previous item if any). */ def put(item: inventory.I): Unit = { setSlot(index, Some(item)) } - /** - * Allows inserting/removing the item in this slot. - */ + /** Allows inserting/removing the item in this slot. */ def set(item: Option[inventory.I]): Unit = { setSlot(index, item) } - /** - * Removes the item contained in this slot if there is one. - */ + /** Removes the item contained in this slot if there is one. */ def remove(): Unit = { setSlot(index, None) } - /** - * The [[Item]] contained in this slot. - */ + /** The [[Item]] contained in this slot. */ def get: Option[inventory.I] = slotItems.get(index) val inventory: Inventory.this.type = Inventory.this - /** - * Registers an observer to receive item added/removed events. + /** Registers an observer to receive item added/removed events. * * @note The inventory keeps a '''weak''' reference to the `observer`. */ @@ -167,9 +148,8 @@ trait Inventory extends EventAware { } final object Slot { - /** - * Creates a proxy to an inventory slot. - */ + + /** Creates a proxy to an inventory slot. */ def apply(index: Int) = new Slot(index) } @@ -178,7 +158,7 @@ trait Inventory extends EventAware { (slotItems.get(index), item) match { case (Some(oldItem), Some(newItem)) if oldItem == newItem => - // no-op + // no-op case (Some(oldItem), Some(newItem)) => // replace old with new @@ -198,7 +178,7 @@ trait Inventory extends EventAware { onItemAddedImpl(slot) case (None, None) => - // no-op + // no-op } } @@ -225,15 +205,14 @@ trait Inventory extends EventAware { object Inventory { trait SlotObserver { - /** - * Called after an item was inserted into this slot. + + /** Called after an item was inserted into this slot. * * @note [[Inventory.onItemAdded]] is called before this method. */ def onItemAdded(): Unit - /** - * Called after an item was removed from this slot. + /** Called after an item was removed from this slot. * * In particular, the slot no longer contains the removed item. * @@ -241,9 +220,7 @@ object Inventory { */ def onItemRemoved(removedItem: Item, replacedBy: Option[Item]): Unit - /** - * Called when an item contained in this slot sends a notification via [[Item.notifySlot]]. - */ + /** Called when an item contained in this slot sends a notification via [[Item.notifySlot]]. */ def onItemNotification(notification: Item.Notification): Unit } } diff --git a/src/main/scala/ocelot/desktop/inventory/Item.scala b/src/main/scala/ocelot/desktop/inventory/Item.scala index 89a70da..22d9481 100644 --- a/src/main/scala/ocelot/desktop/inventory/Item.scala +++ b/src/main/scala/ocelot/desktop/inventory/Item.scala @@ -11,15 +11,11 @@ import ocelot.desktop.util.Disposable import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier -/** - * Something that can be stored in an [[Inventory]]. - */ +/** Something that can be stored in an [[Inventory]]. */ trait Item extends EventAware with Updatable with Disposable { private var _slot: Option[Inventory#Slot] = None - /** - * The slot this item is stored in. - */ + /** The slot this item is stored in. */ def slot: Option[Inventory#Slot] = _slot private[inventory] def slot_=(slot: Option[Inventory#Slot]): Unit = { @@ -32,9 +28,7 @@ trait Item extends EventAware with Updatable with Disposable { } } - /** - * Remove the item from its slot, apply `f`, and put it back into the slot. - */ + /** Remove the item from its slot, apply `f`, and put it back into the slot. */ def reinserting(f: => Unit): Unit = { val prevSlot = slot slot.foreach(_.remove()) @@ -42,8 +36,7 @@ trait Item extends EventAware with Updatable with Disposable { prevSlot.foreach(slot => slot.put(this.asInstanceOf[slot.inventory.I])) } - /** - * Sends a `notification` to observers of the `slot`. + /** Sends a `notification` to observers of the `slot`. * * (Which means, if the item is not put into any slot, nobody will receive the message.) */ @@ -55,18 +48,13 @@ trait Item extends EventAware with Updatable with Disposable { protected def onRemoved(): Unit = {} - /** - * The name of the item (as shown in the tooltip). - */ + /** The name of the item (as shown in the tooltip). */ def name: String = factory.name - /** - * The icon used to draw the item in a slot. - */ + /** The icon used to draw the item in a slot. */ def icon: IconSource = factory.icon - /** - * The tier of the item (if it has one). + /** The tier of the item (if it has one). * * This affects the color of the item name in the tooltip. */ @@ -74,8 +62,7 @@ trait Item extends EventAware with Updatable with Disposable { protected def tooltipNameColor: Color = ColorScheme(s"Tier${tier.getOrElse(Tier.One).id}") - /** - * Override this in subclasses to customize the contents of the tooltip. + /** Override this in subclasses to customize the contents of the tooltip. * * @example {{{ * override protected def fillTooltipBody(body: Widget): Unit = { @@ -91,31 +78,27 @@ trait Item extends EventAware with Updatable with Disposable { tooltip.addLine(name, tooltipNameColor) } - /** - * Override this in subclasses to add new entries to the context menu. + /** Override this in subclasses to add new entries to the context menu. * * It usually makes sense to call `super.fillRmbMenu` ''after'' you've added your own entries. */ def fillRmbMenu(menu: ContextMenu): Unit = {} - /** - * The factory that can be used to build an independent instance of this [[Item]] + /** The factory that can be used to build an independent instance of this [[Item]] * in a way equivalent to this one (e.g. the same tier, label, EEPROM code). * * Keep this rather cheap. */ def factory: ItemFactory - /** - * Override this in subclasses to implement some specific item behavior - * during UI update - */ + /** Override this in subclasses to implement some specific item behavior + * during UI update + */ override def update(): Unit = {} } object Item { - /** - * A notification that can be sent with [[Item.notifySlot]]. - */ + + /** A notification that can be sent with [[Item.notifySlot]]. */ trait Notification } diff --git a/src/main/scala/ocelot/desktop/inventory/ItemFactory.scala b/src/main/scala/ocelot/desktop/inventory/ItemFactory.scala index 9dd9b3d..fb369d4 100644 --- a/src/main/scala/ocelot/desktop/inventory/ItemFactory.scala +++ b/src/main/scala/ocelot/desktop/inventory/ItemFactory.scala @@ -3,8 +3,7 @@ package ocelot.desktop.inventory import ocelot.desktop.graphics.IconSource import totoro.ocelot.brain.util.Tier.Tier -/** - * Provides information about a class of [[Item]]s and allows to build an item instance. +/** Provides information about a class of [[Item]]s and allows to build an item instance. * * Used by [[ocelot.desktop.ui.widget.slot.SlotWidget SlotWidgets]] * (and [[ocelot.desktop.ui.widget.slot.ItemChooser]]) to tell if you can insert an item into the slot @@ -12,20 +11,17 @@ import totoro.ocelot.brain.util.Tier.Tier * In particular, make sure the [[tier]] and [[itemClass]] provided by the factory are accurate. */ trait ItemFactory { - /** - * The concrete type of the [[Item]] built by the factory. - */ + + /** The concrete type of the [[Item]] built by the factory. */ type I <: Item - /** - * The runtime class of the [[Item]] built by the factory. + /** The runtime class of the [[Item]] built by the factory. * * @note It's expected that `build().getClass == itemClass`. */ def itemClass: Class[I] - /** - * A name that represents what will be built by the factory. + /** A name that represents what will be built by the factory. * * Usually [[name]] and [[Item.name]] are the same (in fact, the latter defaults to this unless overridden). * @@ -33,27 +29,21 @@ trait ItemFactory { */ def name: String - /** - * The tier of an item this factory will construct in its [[build]] method. + /** The tier of an item this factory will construct in its [[build]] method. * * @note It's expected that `build().tier == tier`. */ def tier: Option[Tier] - /** - * The icon of an item this factory will construct in its [[build]] method. + /** The icon of an item this factory will construct in its [[build]] method. * * Used by the [[ocelot.desktop.ui.widget.slot.ItemChooser ItemChooser]] in its entries. */ def icon: IconSource - /** - * Constructs a new item instance. - */ + /** Constructs a new item instance. */ def build(): I - /** - * Returns a list of recoverers provided by the factory, - */ + /** Returns a list of recoverers provided by the factory, */ def recoverers: Iterable[ItemRecoverer[_, _]] } diff --git a/src/main/scala/ocelot/desktop/inventory/ItemRecoverer.scala b/src/main/scala/ocelot/desktop/inventory/ItemRecoverer.scala index 7a41969..0fe24cc 100644 --- a/src/main/scala/ocelot/desktop/inventory/ItemRecoverer.scala +++ b/src/main/scala/ocelot/desktop/inventory/ItemRecoverer.scala @@ -1,9 +1,8 @@ package ocelot.desktop.inventory -import scala.reflect.{ClassTag, classTag} +import scala.reflect.{classTag, ClassTag} -/** - * Allows recovering an [[Item]] from [[S]] (typically an [[totoro.ocelot.brain.entity.traits.Entity Entity]]). +/** Allows recovering an [[Item]] from [[S]] (typically an [[totoro.ocelot.brain.entity.traits.Entity Entity]]). * * This is used for migration from old saves before the inventory system was introduced to Ocelot Desktop. */ diff --git a/src/main/scala/ocelot/desktop/inventory/Items.scala b/src/main/scala/ocelot/desktop/inventory/Items.scala index 09d85b2..ed09fbd 100644 --- a/src/main/scala/ocelot/desktop/inventory/Items.scala +++ b/src/main/scala/ocelot/desktop/inventory/Items.scala @@ -20,9 +20,7 @@ object Items extends Logging { // this is just to force load the class during initialization def init(): Unit = {} - /** - * Registers a recoverer for [[ItemRecoverer.sourceClass]]. - */ + /** Registers a recoverer for [[ItemRecoverer.sourceClass]]. */ def registerRecoverer(recoverer: ItemRecoverer[_, _]): Unit = { if (!_recoverers.contains(recoverer.sourceClass)) { _recoverers(recoverer.sourceClass) = recoverer @@ -72,8 +70,7 @@ object Items extends Logging { def groups: Iterable[ItemGroup] = _groups - /** - * Attempts to recover an [[Item]] from `source`. + /** Attempts to recover an [[Item]] from `source`. * * Checks superclasses and traits while looking for a recoverer. */ @@ -111,7 +108,7 @@ object Items extends Logging { case ExtendedTier.Creative => new MagicalMemoryItem.Factory() case tier => new MemoryItem.Factory(tier) } - .map(factory => (factory.name, factory)) + .map(factory => (factory.name, factory)), ) registerTiered("HDD", Tier.One to Tier.Three)(new HddItem.Factory(managed = true, _)) @@ -121,7 +118,7 @@ object Items extends Logging { FloppyItem.Factory.Empty.icon, Loot.Floppies.iterator .map(new FloppyItem.Factory.Loot(_)) - .map(factory => (factory.name, factory)) ++ Some(("Empty", FloppyItem.Factory.Empty)) + .map(factory => (factory.name, factory)) ++ Some(("Empty", FloppyItem.Factory.Empty)), ) registerArbitrary( @@ -129,26 +126,31 @@ object Items extends Logging { EepromItem.Factory.Empty.icon, Loot.Eeproms.iterator .map(new EepromItem.Factory.Loot(_)) - .map(factory => (factory.name, factory)) ++ Some(("Empty", EepromItem.Factory.Empty)) + .map(factory => (factory.name, factory)) ++ Some(("Empty", EepromItem.Factory.Empty)), ) registerTiered("Graphics Card", Tier.One to Tier.Three)(new GraphicsCardItem.Factory(_)) registerSingleton(NetworkCardItem.Factory) + registerTiered("Wireless Net. Card", Tier.One to Tier.Two) { case Tier.One => WirelessNetworkCardItem.Tier1.Factory case Tier.Two => WirelessNetworkCardItem.Tier2.Factory } + registerSingleton(LinkedCardItem.Factory) registerSingleton(InternetCardItem.Factory) + registerTiered("Redstone Card", Tier.One to Tier.Two) { case Tier.One => RedstoneCardItem.Tier1.Factory case Tier.Two => RedstoneCardItem.Tier2.Factory } + registerTiered("Data Card", Tier.One to Tier.Three) { - case Tier.One => DataCardItem.Tier1.Factory - case Tier.Two => DataCardItem.Tier2.Factory + case Tier.One => DataCardItem.Tier1.Factory + case Tier.Two => DataCardItem.Tier2.Factory case Tier.Three => DataCardItem.Tier3.Factory } + registerSingleton(SoundCardItem.Factory) registerSingleton(SelfDestructingCardItem.Factory) registerSingleton(OcelotCardItem.Factory) @@ -162,6 +164,6 @@ object Items extends Logging { new TapeItem.Factory(Tape.Kind.Iron).icon, Tape.Kind.values.iterator .map(new TapeItem.Factory(_)) - .map(factory => (f"${factory.name}%s (${Tape.lengthMinutes(factory.kind)}%.0f min)", factory)) + .map(factory => (f"${factory.name}%s (${Tape.lengthMinutes(factory.kind)}%.0f min)", factory)), ) } diff --git a/src/main/scala/ocelot/desktop/inventory/PersistedInventory.scala b/src/main/scala/ocelot/desktop/inventory/PersistedInventory.scala index 7418fbf..6d456b9 100644 --- a/src/main/scala/ocelot/desktop/inventory/PersistedInventory.scala +++ b/src/main/scala/ocelot/desktop/inventory/PersistedInventory.scala @@ -11,8 +11,7 @@ import totoro.ocelot.brain.nbt.{NBT, NBTTagCompound} import scala.collection.mutable -/** - * Provides persistence for an [[Inventory]]. +/** Provides persistence for an [[Inventory]]. * * [[ComponentItem]]s are treated specially: their [[ComponentItem.component component]] is persisted * along with the item when saving. When loading the item, it first loads the component and uses it to instantiate @@ -45,7 +44,7 @@ trait PersistedInventory extends Inventory with Logging with Persistable { case ItemLoadException(message) => logger.error( s"Could not restore an item in the slot $slotIndex of " + - s"the inventory $this (class ${this.getClass.getName}): $message", + s"the inventory $this (class ${this.getClass.getName}): $message" ) onSlotLoadFailed(slotIndex) } @@ -60,7 +59,8 @@ trait PersistedInventory extends Inventory with Logging with Persistable { super.save(nbt) nbt.setNewTagList( - InventoryTag, inventoryIterator.map { slot => + InventoryTag, + inventoryIterator.map { slot => val item = slot.get.get val slotNbt = new NBTTagCompound @@ -77,7 +77,7 @@ trait PersistedInventory extends Inventory with Logging with Persistable { } slotNbt - } + }, ) } @@ -97,7 +97,7 @@ trait PersistedInventory extends Inventory with Logging with Persistable { constructor.newInstance(entity).asInstanceOf[I] } - //noinspection ScalaWeakerAccess + // noinspection ScalaWeakerAccess @throws[ItemLoadException]("if the item could not be loaded") protected def loadPlainItem(itemClass: Class[_]): I = { itemClass.getConstructor().newInstance().asInstanceOf[I] diff --git a/src/main/scala/ocelot/desktop/inventory/SyncedInventory.scala b/src/main/scala/ocelot/desktop/inventory/SyncedInventory.scala index a891855..3d92d95 100644 --- a/src/main/scala/ocelot/desktop/inventory/SyncedInventory.scala +++ b/src/main/scala/ocelot/desktop/inventory/SyncedInventory.scala @@ -16,8 +16,7 @@ import totoro.ocelot.brain.network.Network import scala.annotation.tailrec -/** - * A [[PersistedInventory]] backed by a [[BrainInventory brain Inventory]]. +/** A [[PersistedInventory]] backed by a [[BrainInventory brain Inventory]]. * * Synchronizes the contents of the two inventories, propagating changes from one to the other. * @@ -36,11 +35,10 @@ trait SyncedInventory extends PersistedInventory with EventAware with Logging { @volatile private var syncFuel: Int = _ + refuel() - /** - * The backing [[BrainInventory brain Inventory]]. - */ + /** The backing [[BrainInventory brain Inventory]]. */ def brainInventory: BrainInventory override def load(nbt: NBTTagCompound): Unit = { @@ -210,7 +208,6 @@ trait SyncedInventory extends PersistedInventory with EventAware with Logging { case SyncDirection.Reconcile => checkSlotStatus(slotIndex) match { case SlotStatus.Synchronized => // no-op - // let's just grab whatever we have case SlotStatus.DesktopNonEmpty => doSync(slotIndex, SyncDirection.DesktopToBrain) case SlotStatus.BrainNonEmpty => doSync(slotIndex, SyncDirection.BrainToDesktop) @@ -249,7 +246,7 @@ trait SyncedInventory extends PersistedInventory with EventAware with Logging { ) } - private def checkSlotStatus(slotIndex: Int): SlotStatus = + private def checkSlotStatus(slotIndex: Int): SlotStatus = { (Slot(slotIndex).get, brainInventory.inventory(slotIndex).get) match { case (Some(item), Some(entity)) if item.component eq entity => SlotStatus.Synchronized case (Some(_), Some(_)) => SlotStatus.Conflict @@ -257,6 +254,7 @@ trait SyncedInventory extends PersistedInventory with EventAware with Logging { case (None, Some(_)) => SlotStatus.BrainNonEmpty case (None, None) => SlotStatus.Synchronized } + } } object SyncedInventory { @@ -267,42 +265,29 @@ object SyncedInventory { object SyncDirection extends Enumeration { type SyncDirection = Value - /** - * Apply a change from the [[SyncedInventory]] to [[SyncedInventory.brainInventory]]. - */ + /** Apply a change from the [[SyncedInventory]] to [[SyncedInventory.brainInventory]]. */ val DesktopToBrain: SyncDirection = Value - /** - * Apply a change from the [[SyncedInventory.brainInventory]] to [[SyncedInventory]]. - */ + /** Apply a change from the [[SyncedInventory.brainInventory]] to [[SyncedInventory]]. */ val BrainToDesktop: SyncDirection = Value - /** - * Try to reconcile conflicts between [[SyncedInventory]] and its [[SyncedInventory.brainInventory]]. - */ + /** Try to reconcile conflicts between [[SyncedInventory]] and its [[SyncedInventory.brainInventory]]. */ val Reconcile: SyncDirection = Value } object SlotStatus extends Enumeration { type SlotStatus = Value - /** - * The slots are in sync (both are empty or they contain the same entity). - */ + /** The slots are in sync (both are empty or they contain the same entity). */ val Synchronized: SlotStatus = Value - /** - * [[SyncedInventory]]'s slot is non-empty; [[SyncedInventory.brainInventory]]'s is empty. - */ + /** [[SyncedInventory]]'s slot is non-empty; [[SyncedInventory.brainInventory]]'s is empty. */ val DesktopNonEmpty: SlotStatus = Value - /** - * [[SyncedInventory]]'s slot is empty; [[SyncedInventory.brainInventory]]'s isn't. - */ + /** [[SyncedInventory]]'s slot is empty; [[SyncedInventory.brainInventory]]'s isn't. */ val BrainNonEmpty: SlotStatus = Value - /** - * The [[SyncedInventory]] and the [[SyncedInventory.brainInventory]] are both non-empty + /** The [[SyncedInventory]] and the [[SyncedInventory.brainInventory]] are both non-empty * and contain different items. */ val Conflict: SlotStatus = Value diff --git a/src/main/scala/ocelot/desktop/inventory/item/ComponentBusItem.scala b/src/main/scala/ocelot/desktop/inventory/item/ComponentBusItem.scala index c479186..a014e3c 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/ComponentBusItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/ComponentBusItem.scala @@ -8,10 +8,7 @@ import totoro.ocelot.brain.entity.ComponentBus import totoro.ocelot.brain.entity.traits.{Entity, Environment} import totoro.ocelot.brain.util.Tier.Tier -class ComponentBusItem(val componentBus: ComponentBus) - extends Item - with ComponentItem -{ +class ComponentBusItem(val componentBus: ComponentBus) extends Item with ComponentItem { override def component: Entity with Environment = componentBus override def showAddress: Boolean = false override def factory: ItemFactory = new ComponentBusItem.Factory(componentBus.tier) diff --git a/src/main/scala/ocelot/desktop/inventory/item/DataCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/DataCardItem.scala index cee2a47..485996d 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/DataCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/DataCardItem.scala @@ -13,7 +13,9 @@ import totoro.ocelot.brain.util.Tier.Tier abstract class DataCardItem extends Item with ComponentItem with PersistableItem with CardItem { override def fillTooltip(tooltip: ItemTooltip): Unit = { super.fillTooltip(tooltip) - tooltip.addLine(s"Soft limit (${Settings.get.dataCardTimeout} sec slowdown): ${Settings.get.dataCardSoftLimit} bytes") + tooltip.addLine( + s"Soft limit (${Settings.get.dataCardTimeout} sec slowdown): ${Settings.get.dataCardSoftLimit} bytes" + ) tooltip.addLine(s"Hard limit (fail): ${Settings.get.dataCardHardLimit} bytes") } } diff --git a/src/main/scala/ocelot/desktop/inventory/item/DiskDriveMountableItem.scala b/src/main/scala/ocelot/desktop/inventory/item/DiskDriveMountableItem.scala index 571c13e..a3a84f6 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/DiskDriveMountableItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/DiskDriveMountableItem.scala @@ -9,10 +9,7 @@ import totoro.ocelot.brain.entity.traits.Floppy import totoro.ocelot.brain.entity.{DiskDriveMountable, FloppyDiskDrive} import totoro.ocelot.brain.util.Tier.Tier -class DiskDriveMountableItem(val diskDriveMountable: DiskDriveMountable) - extends RackMountableItem - with DiskDriveAware -{ +class DiskDriveMountableItem(val diskDriveMountable: DiskDriveMountable) extends RackMountableItem with DiskDriveAware { override def floppyDiskDrive: FloppyDiskDrive = diskDriveMountable override def component: DiskDriveMountable = diskDriveMountable diff --git a/src/main/scala/ocelot/desktop/inventory/item/EepromItem.scala b/src/main/scala/ocelot/desktop/inventory/item/EepromItem.scala index 2e24ffc..99a7b94 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/EepromItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/EepromItem.scala @@ -32,8 +32,11 @@ class EepromItem(val eeprom: EEPROM) extends Item with ComponentItem with Persis } if (source.isEmpty && eeprom != null) { - if (eeprom.codeBytes != null) - tooltip.addLine(s"Code: ${eeprom.codeBytes.map(_.length).getOrElse(0)} bytes / ${Settings.get.eepromSize} bytes") + if (eeprom.codeBytes != null) { + tooltip.addLine( + s"Code: ${eeprom.codeBytes.map(_.length).getOrElse(0)} bytes / ${Settings.get.eepromSize} bytes" + ) + } if (eeprom.volatileData != null) tooltip.addLine(s"Data: ${eeprom.volatileData.length} bytes / ${Settings.get.eepromDataSize} bytes") if (eeprom.readonly) @@ -59,13 +62,14 @@ class EepromItem(val eeprom: EEPROM) extends Item with ComponentItem with Persis onConfirmed = { text => eeprom.codeURL = Some(new URL(text)) }, - inputValidator = text => + inputValidator = text => { try { new URL(text) true } catch { case _: MalformedURLException => false - }, + } + }, ).show() }) diff --git a/src/main/scala/ocelot/desktop/inventory/item/FloppyItem.scala b/src/main/scala/ocelot/desktop/inventory/item/FloppyItem.scala index 4ca145f..8129efe 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/FloppyItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/FloppyItem.scala @@ -7,7 +7,7 @@ import ocelot.desktop.ui.widget.tooltip.ItemTooltip import totoro.ocelot.brain.entity.fs.ReadWriteLabel import totoro.ocelot.brain.entity.traits.{Disk, Entity, Floppy} import totoro.ocelot.brain.entity.{FloppyManaged, FloppyUnmanaged} -import totoro.ocelot.brain.loot.Loot.{LootFloppy, FloppyFactory => LootFloppyFactory} +import totoro.ocelot.brain.loot.Loot.{FloppyFactory => LootFloppyFactory, LootFloppy} import totoro.ocelot.brain.util.DyeColor import totoro.ocelot.brain.util.Tier.Tier diff --git a/src/main/scala/ocelot/desktop/inventory/item/GraphicsCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/GraphicsCardItem.scala index 075b0f6..f1e21a6 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/GraphicsCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/GraphicsCardItem.scala @@ -7,7 +7,8 @@ import totoro.ocelot.brain.entity.GraphicsCard import totoro.ocelot.brain.entity.traits.{Entity, GenericGPU} import totoro.ocelot.brain.util.Tier.Tier -class GraphicsCardItem(val gpu: GraphicsCard) extends Item with ComponentItem with PersistableItem with CardItem with GpuLikeItem { +class GraphicsCardItem(val gpu: GraphicsCard) + extends Item with ComponentItem with PersistableItem with CardItem with GpuLikeItem { override def component: Entity with GenericGPU = gpu override def factory: GraphicsCardItem.Factory = new GraphicsCardItem.Factory(gpu.tier) diff --git a/src/main/scala/ocelot/desktop/inventory/item/MagicalMemoryItem.scala b/src/main/scala/ocelot/desktop/inventory/item/MagicalMemoryItem.scala index c93394e..9cfaeab 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/MagicalMemoryItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/MagicalMemoryItem.scala @@ -30,4 +30,4 @@ object MagicalMemoryItem { override def recoverers: Iterable[ItemRecoverer[_, _]] = Some(ItemRecoverer(new MagicalMemoryItem(_))) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/inventory/item/OcelotCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/OcelotCardItem.scala index aba60f2..4cd357e 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/OcelotCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/OcelotCardItem.scala @@ -14,12 +14,7 @@ import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier class OcelotCardItem(val ocelotCard: OcelotCard) - extends Item - with ComponentItem - with OcelotInterfaceLogStorage - with PersistableItem - with CardItem - with Logging { + extends Item with ComponentItem with OcelotInterfaceLogStorage with PersistableItem with CardItem with Logging { override def component: OcelotCard = ocelotCard @@ -40,6 +35,7 @@ class OcelotCardItem(val ocelotCard: OcelotCard) override def factory: ItemFactory = OcelotCardItem.Factory private val OcelotSays = Array("meow", ":3", "♥", "meooow", "~(=^–^)", "/ᐠ。ꞈ。ᐟ\\", "=^._.^=", "=’①。①’=") + override def fillTooltip(tooltip: ItemTooltip): Unit = { super.fillTooltip(tooltip) tooltip.addLine(OcelotSays(((System.currentTimeMillis() / 5000) % OcelotSays.length).toInt)) diff --git a/src/main/scala/ocelot/desktop/inventory/item/RedstoneCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/RedstoneCardItem.scala index ac144ee..374cbfb 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/RedstoneCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/RedstoneCardItem.scala @@ -13,9 +13,7 @@ import totoro.ocelot.brain.nbt.NBTTagCompound import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier -abstract class RedstoneCardItem extends Item with ComponentItem with PersistableItem with CardItem { - -} +abstract class RedstoneCardItem extends Item with ComponentItem with PersistableItem with CardItem {} object RedstoneCardItem { abstract class Factory extends ItemFactory { diff --git a/src/main/scala/ocelot/desktop/inventory/item/SelfDestructingCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/SelfDestructingCardItem.scala index a7524d8..23fbc29 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/SelfDestructingCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/SelfDestructingCardItem.scala @@ -10,10 +10,7 @@ import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier class SelfDestructingCardItem(val card: SelfDestructingCard) - extends Item - with ComponentItem - with PersistableItem - with CardItem { + extends Item with ComponentItem with PersistableItem with CardItem { override def component: Entity with Environment = card diff --git a/src/main/scala/ocelot/desktop/inventory/item/ServerItem.scala b/src/main/scala/ocelot/desktop/inventory/item/ServerItem.scala index f52e5a4..5f6f4dd 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/ServerItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/ServerItem.scala @@ -11,10 +11,7 @@ import totoro.ocelot.brain.entity.traits.Inventory import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier -class ServerItem(val server: Server) - extends RackMountableItem - with AudibleComputerAware -{ +class ServerItem(val server: Server) extends RackMountableItem with AudibleComputerAware { override def component: Server = server override def factory: ItemFactory = new ServerItem.Factory(server.tier) @@ -44,24 +41,26 @@ class ServerItem(val server: Server) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) case Tier.Two => - cardSlots = addSlotWidgets(new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Two), new CardSlotWidget(_, Tier.Two)) + cardSlots = addSlotWidgets(new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Two), + new CardSlotWidget(_, Tier.Two)) cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.Three)) - componentBusSlots = addSlotWidgets(new ComponentBusSlotWidget(_, Tier.Three), new ComponentBusSlotWidget(_, Tier.Three)) - memorySlots = addSlotWidgets(new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three)) + componentBusSlots = + addSlotWidgets(new ComponentBusSlotWidget(_, Tier.Three), new ComponentBusSlotWidget(_, Tier.Three)) + memorySlots = addSlotWidgets(new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three), + new MemorySlotWidget(_, Tier.Three)) diskSlots = addSlotWidgets(new HddSlotWidget(_, Tier.Three), new HddSlotWidget(_, Tier.Three)) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) case _ => - cardSlots = + cardSlots = { if (server.tier == Tier.Three) { addSlotWidgets( new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Two), - new CardSlotWidget(_, Tier.Two) + new CardSlotWidget(_, Tier.Two), ) - } - else { + } else { addSlotWidgets( new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Three), @@ -69,6 +68,7 @@ class ServerItem(val server: Server) new CardSlotWidget(_, Tier.Three), ) } + } cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.Three)) @@ -82,7 +82,7 @@ class ServerItem(val server: Server) new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three), - new MemorySlotWidget(_, Tier.Three) + new MemorySlotWidget(_, Tier.Three), ) diskSlots = addSlotWidgets( diff --git a/src/main/scala/ocelot/desktop/inventory/item/SoundCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/SoundCardItem.scala index 4e43eca..bad4fb4 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/SoundCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/SoundCardItem.scala @@ -12,11 +12,7 @@ import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier class SoundCardItem(val soundCard: SoundCard) - extends Item - with ComponentItem - with PersistableItem - with CardItem - with Windowed[SoundCardWindow] { + extends Item with ComponentItem with PersistableItem with CardItem with Windowed[SoundCardWindow] { override def createWindow(): SoundCardWindow = new SoundCardWindow(soundCard) diff --git a/src/main/scala/ocelot/desktop/inventory/item/WirelessNetworkCardItem.scala b/src/main/scala/ocelot/desktop/inventory/item/WirelessNetworkCardItem.scala index ae9e3b1..414c46a 100644 --- a/src/main/scala/ocelot/desktop/inventory/item/WirelessNetworkCardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/item/WirelessNetworkCardItem.scala @@ -6,9 +6,7 @@ import totoro.ocelot.brain.entity.WirelessNetworkCard import totoro.ocelot.brain.util.Tier import totoro.ocelot.brain.util.Tier.Tier -abstract class WirelessNetworkCardItem(override val card: WirelessNetworkCard) - extends NetworkCardItem(card) { -} +abstract class WirelessNetworkCardItem(override val card: WirelessNetworkCard) extends NetworkCardItem(card) {} object WirelessNetworkCardItem { abstract class Factory extends ItemFactory { diff --git a/src/main/scala/ocelot/desktop/inventory/traits/CardItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/CardItem.scala index d91bdb6..f1db1a0 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/CardItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/CardItem.scala @@ -2,7 +2,5 @@ package ocelot.desktop.inventory.traits import ocelot.desktop.inventory.Item -/** - * A marker trait implemented by [[Item]]s that can be put into card slots. - */ +/** A marker trait implemented by [[Item]]s that can be put into card slots. */ trait CardItem extends ComponentItem diff --git a/src/main/scala/ocelot/desktop/inventory/traits/ComponentItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/ComponentItem.scala index de067a7..87fa07d 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/ComponentItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/ComponentItem.scala @@ -8,14 +8,13 @@ import ocelot.desktop.ui.widget.contextmenu.{ContextMenu, ContextMenuEntry} import ocelot.desktop.ui.widget.tooltip.ItemTooltip import totoro.ocelot.brain.entity.traits.{Entity, Environment, WorkspaceAware} -/** - * Implemented by [[Item]]s that wrap a component. +/** Implemented by [[Item]]s that wrap a component. * * @note Subclasses must provide a unary constructor that accepts the [[component]]. */ trait ComponentItem extends Item with PersistableItem { - /** - * The component wrapped by this item. + + /** The component wrapped by this item. * * @note The value must already be available during the initialization. */ diff --git a/src/main/scala/ocelot/desktop/inventory/traits/CpuLikeItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/CpuLikeItem.scala index 7655601..044b0fb 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/CpuLikeItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/CpuLikeItem.scala @@ -8,9 +8,7 @@ import ocelot.desktop.ui.widget.tooltip.ItemTooltip import totoro.ocelot.brain.entity.machine.MachineAPI import totoro.ocelot.brain.entity.traits.{Entity, GenericCPU} -/** - * An [[Item]] that acts as a CPU and can therefore be inserted into a CPU slot. - */ +/** An [[Item]] that acts as a CPU and can therefore be inserted into a CPU slot. */ trait CpuLikeItem extends ComponentItem { override def component: Entity with GenericCPU diff --git a/src/main/scala/ocelot/desktop/inventory/traits/DiskItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/DiskItem.scala index c25a31a..71af1d8 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/DiskItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/DiskItem.scala @@ -13,9 +13,7 @@ import totoro.ocelot.brain.util.DyeColor import javax.swing.JFileChooser import scala.util.Try -/** - * A utility mixin for HDDs and floppies. - */ +/** A utility mixin for HDDs and floppies. */ trait DiskItem extends ComponentItem with Windowed[DiskEditWindow] { override def component: Entity with Disk @@ -51,11 +49,12 @@ trait DiskItem extends ComponentItem with Windowed[DiskEditWindow] { // Real path component match { case diskManaged: DiskManaged => - DiskItem.addRealPathContextMenuEntries(menu, diskManaged, realPathSetter => { - reinserting { - realPathSetter() - } - }) + DiskItem.addRealPathContextMenuEntries(menu, diskManaged, + realPathSetter => { + reinserting { + realPathSetter() + } + }) case _ => } @@ -94,10 +93,11 @@ trait DiskItem extends ComponentItem with Windowed[DiskEditWindow] { } object DiskItem { - def addRealPathContextMenuEntries(menu: ContextMenu, diskRealPathAware: DiskRealPathAware, realPathSetter: (() => Unit) => Unit): Unit = { + def addRealPathContextMenuEntries(menu: ContextMenu, diskRealPathAware: DiskRealPathAware, + realPathSetter: (() => Unit) => Unit): Unit = { menu.addEntry(ContextMenuEntry( if (diskRealPathAware.customRealPath.isDefined) "Change directory" else "Set directory", - IconSource.Folder + IconSource.Folder, ) { OcelotDesktop.showFileChooserDialog(JFileChooser.OPEN_DIALOG, JFileChooser.DIRECTORIES_ONLY) { dir => Try { diff --git a/src/main/scala/ocelot/desktop/inventory/traits/PersistableItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/PersistableItem.scala index a35c85b..2aabcc7 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/PersistableItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/PersistableItem.scala @@ -3,7 +3,5 @@ package ocelot.desktop.inventory.traits import ocelot.desktop.inventory.Item import ocelot.desktop.util.Persistable -/** - * Provides serialization and deserialization for an [[Item]]. - */ +/** Provides serialization and deserialization for an [[Item]]. */ trait PersistableItem extends Item with Persistable diff --git a/src/main/scala/ocelot/desktop/inventory/traits/RackMountableItem.scala b/src/main/scala/ocelot/desktop/inventory/traits/RackMountableItem.scala index b57bb32..f5d3ed3 100644 --- a/src/main/scala/ocelot/desktop/inventory/traits/RackMountableItem.scala +++ b/src/main/scala/ocelot/desktop/inventory/traits/RackMountableItem.scala @@ -6,10 +6,7 @@ import ocelot.desktop.ui.widget.contextmenu.ContextMenu import totoro.ocelot.brain.entity.result import totoro.ocelot.brain.entity.traits.{Entity, RackMountable} -trait RackMountableItem - extends Item - with ComponentItem -{ +trait RackMountableItem extends Item with ComponentItem { override def component: Entity with RackMountable def isInRack: Boolean = slot.exists(_.inventory.isInstanceOf[RackNode]) @@ -19,4 +16,4 @@ trait RackMountableItem super.fillRmbMenu(menu) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/ComputerAwareNode.scala b/src/main/scala/ocelot/desktop/node/ComputerAwareNode.scala index e1bda45..671a10c 100644 --- a/src/main/scala/ocelot/desktop/node/ComputerAwareNode.scala +++ b/src/main/scala/ocelot/desktop/node/ComputerAwareNode.scala @@ -21,7 +21,7 @@ import java.util.Calendar import scala.collection.mutable.ArrayBuffer abstract class ComputerAwareNode(entity: Entity with Environment with WorkspaceAware) - extends EntityNode(entity) + extends EntityNode(entity) with SyncedInventory with DiskActivityHandler with OcelotLogParticleNode diff --git a/src/main/scala/ocelot/desktop/node/Node.scala b/src/main/scala/ocelot/desktop/node/Node.scala index 8b7beec..7a83cf7 100644 --- a/src/main/scala/ocelot/desktop/node/Node.scala +++ b/src/main/scala/ocelot/desktop/node/Node.scala @@ -220,17 +220,18 @@ abstract class Node extends Widget with MouseHandler with HoverHandler with Pers private def move(pos: Vector2D): Unit = { val oldPos = position - val desiredPos = - if (KeyEvents.isControlDown) + val desiredPos = { + if (KeyEvents.isControlDown) { (pos - workspaceView.cameraOffset).snap(Size) + // snap the position to the grid relative to the origin - workspaceView.cameraOffset - // restore the camera offset - grabPoint.snap(Size) + // accounts for multi-block screens - Vector2D( - ((Size - width) % Size) / 2, - ((Size - height) % Size) / 2, - ) // if a node is not full-size, moves it to the center of the grid cell - else + workspaceView.cameraOffset - // restore the camera offset + grabPoint.snap(Size) + // accounts for multi-block screens + Vector2D( + ((Size - width) % Size) / 2, + ((Size - height) % Size) / 2, + ) // if a node is not full-size, moves it to the center of the grid cell + } else pos - grabPoint + } position = desiredPos workspaceView.resolveCollision(this) @@ -260,7 +261,7 @@ abstract class Node extends Widget with MouseHandler with HoverHandler with Pers g.sprite( iconSource.path, - position. x + HighlightThickness, + position.x + HighlightThickness, position.y + HighlightThickness, size.width - HighlightThickness * 2, size.height - HighlightThickness * 2, diff --git a/src/main/scala/ocelot/desktop/node/NodePort.scala b/src/main/scala/ocelot/desktop/node/NodePort.scala index 91ded08..c65e8cc 100644 --- a/src/main/scala/ocelot/desktop/node/NodePort.scala +++ b/src/main/scala/ocelot/desktop/node/NodePort.scala @@ -27,4 +27,4 @@ object NodePort { def fromByte(byte: Byte): NodePort = { if (byte == -1) NodePort(None) else NodePort(Some(Direction(byte))) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/NodeRegistry.scala b/src/main/scala/ocelot/desktop/node/NodeRegistry.scala index 750d8e1..d2058c6 100644 --- a/src/main/scala/ocelot/desktop/node/NodeRegistry.scala +++ b/src/main/scala/ocelot/desktop/node/NodeRegistry.scala @@ -3,7 +3,10 @@ package ocelot.desktop.node import ocelot.desktop.entity.{Camera, OcelotBlock, OpenFMRadio} import ocelot.desktop.graphics.IconSource import ocelot.desktop.node.nodes._ -import totoro.ocelot.brain.entity.{Cable, Case, ColorfulLamp, FloppyDiskDrive, HologramProjector, IronNoteBlock, Microcontroller, NoteBlock, Rack, Raid, Relay, Screen, TapeDrive} +import totoro.ocelot.brain.entity.{ + Cable, Case, ColorfulLamp, FloppyDiskDrive, HologramProjector, IronNoteBlock, Microcontroller, NoteBlock, Rack, Raid, + Relay, Screen, TapeDrive, +} import totoro.ocelot.brain.util.Tier import scala.collection.mutable @@ -17,11 +20,11 @@ object NodeRegistry { group = new NodeTypeGroup(name) groups += group } - + private def addType(nodeType: NodeType): Unit = { group.types += nodeType } - + // ------------------------------ Original nodes ------------------------------ nextGroup("Original") diff --git a/src/main/scala/ocelot/desktop/node/NodeType.scala b/src/main/scala/ocelot/desktop/node/NodeType.scala index 1136b61..8399cc2 100644 --- a/src/main/scala/ocelot/desktop/node/NodeType.scala +++ b/src/main/scala/ocelot/desktop/node/NodeType.scala @@ -4,7 +4,7 @@ import ocelot.desktop.graphics.IconSource import totoro.ocelot.brain.util.Tier.Tier class NodeType(val name: String, val icon: IconSource, val tier: Option[Tier], factory: => Node) - extends Ordered[NodeType] { + extends Ordered[NodeType] { def make(): Node = factory override def compare(that: NodeType): Int = this.name.compare(that.name) diff --git a/src/main/scala/ocelot/desktop/node/NodeTypeGroup.scala b/src/main/scala/ocelot/desktop/node/NodeTypeGroup.scala index c186b4e..5f57dca 100644 --- a/src/main/scala/ocelot/desktop/node/NodeTypeGroup.scala +++ b/src/main/scala/ocelot/desktop/node/NodeTypeGroup.scala @@ -4,4 +4,4 @@ import scala.collection.mutable class NodeTypeGroup(val name: String) { val types: mutable.ArrayBuffer[NodeType] = mutable.ArrayBuffer[NodeType]() -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/NodeTypeWidget.scala b/src/main/scala/ocelot/desktop/node/NodeTypeWidget.scala index 8f84145..641a675 100644 --- a/src/main/scala/ocelot/desktop/node/NodeTypeWidget.scala +++ b/src/main/scala/ocelot/desktop/node/NodeTypeWidget.scala @@ -30,10 +30,10 @@ class NodeTypeWidget(val nodeType: NodeType) extends Widget with MouseHandler wi private val labelTooltip = new LabelTooltip(nodeType.name) def onHoverEnter(): Unit = - root.get.tooltipPool.addTooltip(labelTooltip) + root.get.tooltipPool.addTooltip(labelTooltip) def onHoverLeave(): Unit = - root.get.tooltipPool.closeTooltip(labelTooltip) + root.get.tooltipPool.closeTooltip(labelTooltip) override def draw(g: Graphics): Unit = { val size = Spritesheet.spriteSize(nodeType.icon) * 4 diff --git a/src/main/scala/ocelot/desktop/node/OcelotLogParticleNode.scala b/src/main/scala/ocelot/desktop/node/OcelotLogParticleNode.scala index 2f0b259..e490219 100644 --- a/src/main/scala/ocelot/desktop/node/OcelotLogParticleNode.scala +++ b/src/main/scala/ocelot/desktop/node/OcelotLogParticleNode.scala @@ -15,7 +15,7 @@ import scala.util.Random trait OcelotLogParticleNode extends Node { private case class LogParticle( var time: Float = -LogParticleGrow, - angle: Float = Random.between(0f, 2 * math.Pi.toFloat * LogParticleMaxAngle) + angle: Float = Random.between(0f, 2 * math.Pi.toFloat * LogParticleMaxAngle), ) // access should be synchronized because log particles are added in the update thread @@ -76,5 +76,3 @@ object OcelotLogParticleNode { private val LogParticleMoveSpeed: Float = 1f private val LogParticleMoveDistance: Float = 20f } - - diff --git a/src/main/scala/ocelot/desktop/node/PositionalSoundSourcesNode.scala b/src/main/scala/ocelot/desktop/node/PositionalSoundSourcesNode.scala index 5314f8b..054c2eb 100644 --- a/src/main/scala/ocelot/desktop/node/PositionalSoundSourcesNode.scala +++ b/src/main/scala/ocelot/desktop/node/PositionalSoundSourcesNode.scala @@ -29,10 +29,9 @@ trait PositionalSoundSourcesNode extends Node { soundPosition = Vector3D( (nodeCenterX - rootWidthHalf) / rootWidthHalf * limit, (nodeCenterY - rootHeightHalf) / rootHeightHalf * limit, - 0 + 0, ) - } - else { + } else { soundPosition = Vector3D.Zero } diff --git a/src/main/scala/ocelot/desktop/node/nodes/ColorfulLampNode.scala b/src/main/scala/ocelot/desktop/node/nodes/ColorfulLampNode.scala index 776f63c..272dfd3 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/ColorfulLampNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/ColorfulLampNode.scala @@ -16,9 +16,9 @@ class ColorfulLampNode(val lamp: ColorfulLamp) extends EntityNode(lamp) with Lab super.draw(g) lastColor = RGBAColor( - (((lamp.color >>> 10) & 0x1F) << 3).toShort, - (((lamp.color >>> 5) & 0x1F) << 3).toShort, - (((lamp.color >>> 0) & 0x1F) << 3).toShort + (((lamp.color >>> 10) & 0x1f) << 3).toShort, + (((lamp.color >>> 5) & 0x1f) << 3).toShort, + (((lamp.color >>> 0) & 0x1f) << 3).toShort, ) g.rect(position.x + 2, position.y + 2, size.width - 4, size.height - 4, lastColor) diff --git a/src/main/scala/ocelot/desktop/node/nodes/ComputerNode.scala b/src/main/scala/ocelot/desktop/node/nodes/ComputerNode.scala index 597a303..a536982 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/ComputerNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/ComputerNode.scala @@ -15,10 +15,7 @@ import totoro.ocelot.brain.entity.traits.Inventory import totoro.ocelot.brain.util.Tier class ComputerNode(val computerCase: Case) - extends ComputerAwareNode(computerCase) - with AudibleComputerAware - with WindowedNode[ComputerWindow] -{ + extends ComputerAwareNode(computerCase) with AudibleComputerAware with WindowedNode[ComputerWindow] { override val iconSource: IconSource = IconSource.Nodes.Computer.Default override def iconColor: Color = TierColor.get(computerCase.tier) @@ -80,31 +77,31 @@ class ComputerNode(val computerCase: Case) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) case _ => - cardSlots = + cardSlots = { if (computerCase.tier == Tier.Three) { addSlotWidgets( new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Two), - new CardSlotWidget(_, Tier.Two) + new CardSlotWidget(_, Tier.Two), ) - } - else { + } else { addSlotWidgets( new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Three), new CardSlotWidget(_, Tier.Three), ) } + } memorySlots = addSlotWidgets(new MemorySlotWidget(_, Tier.Three), new MemorySlotWidget(_, Tier.Three)) - diskSlots = + diskSlots = { if (computerCase.tier == Tier.Three) { addSlotWidgets(new HddSlotWidget(_, Tier.Three), new HddSlotWidget(_, Tier.Two)) - } - else { + } else { addSlotWidgets(new HddSlotWidget(_, Tier.Three), new HddSlotWidget(_, Tier.Three)) } + } floppySlot = Some(addSlotWidget(new FloppySlotWidget(_))) cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.Three)) @@ -117,4 +114,4 @@ class ComputerNode(val computerCase: Case) override protected def onShiftClick(event: ClickEvent): Unit = toggleIsTurnedOn() override protected def hoveredShiftStatusBarText: String = if (computer.machine.isRunning) "Turn off" else "Turn on" -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/DiskDriveNode.scala b/src/main/scala/ocelot/desktop/node/nodes/DiskDriveNode.scala index f854b26..e848510 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/DiskDriveNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/DiskDriveNode.scala @@ -13,7 +13,7 @@ import ocelot.desktop.windows.DiskDriveWindow import totoro.ocelot.brain.entity.FloppyDiskDrive class DiskDriveNode(entity: FloppyDiskDrive) - extends EntityNode(entity) + extends EntityNode(entity) with SyncedInventory with LabeledEntityNode with DiskDriveAware diff --git a/src/main/scala/ocelot/desktop/node/nodes/HologramProjectorNode.scala b/src/main/scala/ocelot/desktop/node/nodes/HologramProjectorNode.scala index ab1f0c4..6b78e1d 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/HologramProjectorNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/HologramProjectorNode.scala @@ -6,12 +6,9 @@ import ocelot.desktop.windows.HologramProjectorWindow import totoro.ocelot.brain.entity.HologramProjector class HologramProjectorNode(val hologramProjector: HologramProjector) - extends EntityNode(hologramProjector) - with LabeledEntityNode - with WindowedNode[HologramProjectorWindow] { + extends EntityNode(hologramProjector) with LabeledEntityNode with WindowedNode[HologramProjectorWindow] { override def iconSource: IconSource = IconSource.Nodes.HologramProjector(hologramProjector.tier) override def createWindow(): HologramProjectorWindow = new HologramProjectorWindow(this) } - diff --git a/src/main/scala/ocelot/desktop/node/nodes/IronNoteBlockNode.scala b/src/main/scala/ocelot/desktop/node/nodes/IronNoteBlockNode.scala index 06e04ce..f1d6a43 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/IronNoteBlockNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/IronNoteBlockNode.scala @@ -18,7 +18,7 @@ class IronNoteBlockNode(val ironNoteBlock: IronNoteBlock) extends NoteBlockNodeB EventBus.send(NoteBlockTriggerEvent( ironNoteBlock.node.address, Instruments(Random.nextInt(Instruments.length))._1, - Random.nextInt(NumberOfPitches) + Random.nextInt(NumberOfPitches), )) } case _ => diff --git a/src/main/scala/ocelot/desktop/node/nodes/MicrocontrollerNode.scala b/src/main/scala/ocelot/desktop/node/nodes/MicrocontrollerNode.scala index 420741f..ff80185 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/MicrocontrollerNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/MicrocontrollerNode.scala @@ -16,11 +16,10 @@ import totoro.ocelot.brain.network import totoro.ocelot.brain.util.{Direction, Tier} class MicrocontrollerNode(val microcontroller: Microcontroller) - extends ComputerAwareNode(microcontroller) + extends ComputerAwareNode(microcontroller) with ComputerAware with DefaultSlotItemsFillable - with WindowedNode[ComputerWindow] -{ + with WindowedNode[ComputerWindow] { override val iconSource: IconSource = IconSource.Nodes.Microcontroller.Default override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = { @@ -49,7 +48,7 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) NodePort(Some(Direction.Top)), NodePort(Some(Direction.Back)), NodePort(Some(Direction.Right)), - NodePort(Some(Direction.Left)) + NodePort(Some(Direction.Left)), ) override def getNodeByPort(port: NodePort): network.Node = @@ -71,14 +70,14 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) case Tier.One => cardSlots = addSlotWidgets( new CardSlotWidget(_, Tier.One), - new CardSlotWidget(_, Tier.One) + new CardSlotWidget(_, Tier.One), ) cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.One)) memorySlots = addSlotWidgets( new MemorySlotWidget(_, Tier.One), - new MemorySlotWidget(_, Tier.One) + new MemorySlotWidget(_, Tier.One), ) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) @@ -86,14 +85,14 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) case Tier.Two => cardSlots = addSlotWidgets( new CardSlotWidget(_, Tier.Two), - new CardSlotWidget(_, Tier.One) + new CardSlotWidget(_, Tier.One), ) cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.One)) memorySlots = addSlotWidgets( new MemorySlotWidget(_, Tier.One), - new MemorySlotWidget(_, Tier.One) + new MemorySlotWidget(_, Tier.One), ) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) @@ -102,14 +101,14 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) case _ => cardSlots = addSlotWidgets( new CardSlotWidget(_, Tier.Three), - new CardSlotWidget(_, Tier.Three) + new CardSlotWidget(_, Tier.Three), ) cpuSlot = addSlotWidget(new ComputerCpuSlotWidget(_, this, Tier.Three)) memorySlots = addSlotWidgets( new MemorySlotWidget(_, Tier.Three), - new MemorySlotWidget(_, Tier.Three) + new MemorySlotWidget(_, Tier.Three), ) eepromSlot = addSlotWidget(new EepromSlotWidget(_)) @@ -120,17 +119,19 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) // ---------------------------- DefaultSlotItemsFillable ---------------------------- override def fillSlotsWithDefaultItems(): Unit = { - cardSlots(0).item = + cardSlots(0).item = { if (microcontroller.tier == Tier.Two) WirelessNetworkCardItem.Tier2.Factory.build() else WirelessNetworkCardItem.Tier1.Factory.build() + } - cardSlots(1).item = + cardSlots(1).item = { if (microcontroller.tier == Tier.Two) RedstoneCardItem.Tier2.Factory.build() else RedstoneCardItem.Tier1.Factory.build() + } cpuSlot.item = new CpuItem.Factory(Tier.One).build() @@ -145,4 +146,4 @@ class MicrocontrollerNode(val microcontroller: Microcontroller) override protected def onShiftClick(event: ClickEvent): Unit = toggleIsTurnedOn() override protected def hoveredShiftStatusBarText: String = if (computer.machine.isRunning) "Turn off" else "Turn on" -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNode.scala b/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNode.scala index d16520b..62291fd 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNode.scala @@ -60,4 +60,4 @@ object NoteBlockNode { ("pling", "Electric Piano (Glowstone)"), ("harp", "Harp"), ) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNodeBase.scala b/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNodeBase.scala index 4129d59..ea4f2ff 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNodeBase.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/NoteBlockNodeBase.scala @@ -19,7 +19,7 @@ abstract class NoteBlockNodeBase(entity: Entity with Environment) extends Entity SoundBuffers.NoteBlock(event.instrument), SoundCategory.Records, pitch = math.pow(2f, (event.pitch - 12).toFloat / 12f).toFloat, - volume = event.volume.toFloat.min(1f).max(0f) + volume = event.volume.toFloat.min(1f).max(0f), ).play() addParticle(event.pitch) @@ -36,7 +36,8 @@ abstract class NoteBlockNodeBase(entity: Entity with Environment) extends Entity override def drawParticles(g: Graphics): Unit = synchronized { for ((time, pitch) <- particles.reverseIterator) { val col = ColorScheme("Note" + pitch.min(24).max(0)).withAlpha(1 - (2 * time - 1).min(1).max(0)) - g.sprite("particles/Note", position + Vector2D(pitch / 24f * 40f + 5, height / 2 - 10 - 100 * time), Size2D(14, 20), col) + g.sprite("particles/Note", position + Vector2D(pitch / 24f * 40f + 5, height / 2 - 10 - 100 * time), + Size2D(14, 20), col) } particles.mapInPlace { case (t, p) => (t + 1.2f * UiHandler.dt, p) } particles.filterInPlace(_._1 <= 1f) @@ -48,4 +49,4 @@ abstract class NoteBlockNodeBase(entity: Entity with Environment) extends Entity if (isHovered || isMoving) root.get.statusBar.addMouseEntry("icons/LMB", "Play sample") } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/OcelotBlockNode.scala b/src/main/scala/ocelot/desktop/node/nodes/OcelotBlockNode.scala index 8ac98dd..d0a2c5a 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/OcelotBlockNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/OcelotBlockNode.scala @@ -14,7 +14,7 @@ import ocelot.desktop.util.OcelotInterfaceLogStorage import ocelot.desktop.windows.OcelotInterfaceWindow class OcelotBlockNode(val ocelot: OcelotBlock) - extends EntityNode(ocelot) + extends EntityNode(ocelot) with LabeledEntityNode with OcelotLogParticleNode with OcelotInterfaceLogStorage diff --git a/src/main/scala/ocelot/desktop/node/nodes/OpenFMRadioNode.scala b/src/main/scala/ocelot/desktop/node/nodes/OpenFMRadioNode.scala index 69fbb75..7cacfcc 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/OpenFMRadioNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/OpenFMRadioNode.scala @@ -7,7 +7,8 @@ import ocelot.desktop.graphics.{Graphics, IconSource} import ocelot.desktop.node.{EntityNode, LabeledEntityNode, WindowedNode} import ocelot.desktop.windows.OpenFMRadioWindow -class OpenFMRadioNode(val openFMRadio: OpenFMRadio) extends EntityNode(openFMRadio) with LabeledEntityNode with WindowedNode[OpenFMRadioWindow] { +class OpenFMRadioNode(val openFMRadio: OpenFMRadio) + extends EntityNode(openFMRadio) with LabeledEntityNode with WindowedNode[OpenFMRadioWindow] { override def iconSource: IconSource = IconSource.Nodes.OpenFMRadio private var lastTick = OcelotDesktop.ticker.tick @@ -32,8 +33,7 @@ class OpenFMRadioNode(val openFMRadio: OpenFMRadio) extends EntityNode(openFMRad text = rest + first animationIndex += 1 - } - else { + } else { animationIndex = 0 } @@ -62,7 +62,7 @@ class OpenFMRadioNode(val openFMRadio: OpenFMRadio) extends EntityNode(openFMRad g.text( (position.x + size.width / 2) / scale - textWidth / 2, (position.y + 18) / scale, - text + text, ) g.restore() @@ -76,4 +76,4 @@ class OpenFMRadioNode(val openFMRadio: OpenFMRadio) extends EntityNode(openFMRad } override def createWindow(): OpenFMRadioWindow = new OpenFMRadioWindow(this) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/RackNode.scala b/src/main/scala/ocelot/desktop/node/nodes/RackNode.scala index d46d02f..b2853f4 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/RackNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/RackNode.scala @@ -17,10 +17,7 @@ import totoro.ocelot.brain.event.NetworkActivityEvent import totoro.ocelot.brain.network import totoro.ocelot.brain.util.Direction -class RackNode(val rack: Rack) - extends ComputerAwareNode(rack) - with WindowedNode[RackWindow] -{ +class RackNode(val rack: Rack) extends ComputerAwareNode(rack) with WindowedNode[RackWindow] { override val iconSource: IconSource = IconSource.Nodes.Rack.Empty override def exposeAddress = false @@ -29,20 +26,21 @@ class RackNode(val rack: Rack) NodePort(Some(Direction.Top)), NodePort(Some(Direction.Back)), NodePort(Some(Direction.Right)), - NodePort(Some(Direction.Left)) + NodePort(Some(Direction.Left)), ) override def getNodeByPort(port: NodePort): network.Node = rack.sidedNode(port.direction.get) - override def shouldReceiveEventsFor(address: String): Boolean = + override def shouldReceiveEventsFor(address: String): Boolean = { super.shouldReceiveEventsFor(address) || rack.inventory.entities.exists { case mountable: RackMountable if mountable.node.address == address => true case mountable: RackMountable with ComponentInventory => mountable.inventory.entities.exists { - case environment: Environment => environment.node.address == address - } + case environment: Environment => environment.node.address == address + } case _ => false } + } override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = { RackNode.addContextMenuEntriesOfMountable(menu, getMountableByClick(event)) @@ -91,9 +89,9 @@ class RackNode(val rack: Rack) x, y, NoHighlightSize, - NoHighlightSize + NoHighlightSize, ), - driveIconSource + driveIconSource, ) case _ => @@ -131,12 +129,12 @@ class RackNode(val rack: Rack) val localPosition = Vector2D( event.mousePos.x - position.x - horizontalMargin, - event.mousePos.y - position.y - verticalMargin + event.mousePos.y - position.y - verticalMargin, ) val m = Size2D( this.width - horizontalMargin * 2, - this.height - verticalMargin * 2 + this.height - verticalMargin * 2, ) // Checking if click was inside mountables area @@ -207,7 +205,7 @@ object RackNode { "Change floppy" else "Set floppy", - IconSource.Save + IconSource.Save, ) { diskDriveMountableItem.window.open() }) @@ -217,4 +215,4 @@ object RackNode { case _ => } } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/node/nodes/RaidNode.scala b/src/main/scala/ocelot/desktop/node/nodes/RaidNode.scala index ff6f23c..7261f81 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/RaidNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/RaidNode.scala @@ -18,14 +18,13 @@ import totoro.ocelot.brain.util.Tier import scala.util.Random -class RaidNode(val raid: Raid) extends - EntityNode(raid) - with SyncedInventory - with LabeledEntityNode - with DiskActivityHandler - with DefaultSlotItemsFillable - with WindowedNode[RaidWindow] -{ +class RaidNode(val raid: Raid) + extends EntityNode(raid) + with SyncedInventory + with LabeledEntityNode + with DiskActivityHandler + with DefaultSlotItemsFillable + with WindowedNode[RaidWindow] { var diskSlots: Array[HddSlotWidget] = Array.tabulate(3)(index => new HddSlotWidget(Slot(index), Tier.Three)) override val iconSource: IconSource = IconSource.Nodes.Raid.Default @@ -45,7 +44,9 @@ class RaidNode(val raid: Raid) extends } // Disk activity overlay - if (raid.shouldVisualizeDiskActivity && Random.nextDouble() > 0.1 && i == raid.lastDiskAccess % raid.getSizeInventory) { + if ( + raid.shouldVisualizeDiskActivity && Random.nextDouble() > 0.1 && i == raid.lastDiskAccess % raid.getSizeInventory + ) { DrawUtils.drawFilesystemActivity(g, x, y, driveIconSource) } } @@ -56,9 +57,10 @@ class RaidNode(val raid: Raid) extends super.shouldReceiveEventsFor(address) || raid.filesystem.exists(_.node.address == address) override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = { - DiskItem.addRealPathContextMenuEntries(menu, raid, realPathSetter => { - realPathSetter() - }) + DiskItem.addRealPathContextMenuEntries(menu, raid, + realPathSetter => { + realPathSetter() + }) // TODO: Implement DiskDriveWindow later, because at this moment every // TODO: instance of 'Windowed' trait can have only 1 persistable window diff --git a/src/main/scala/ocelot/desktop/node/nodes/RelayNode.scala b/src/main/scala/ocelot/desktop/node/nodes/RelayNode.scala index 4cf2eae..12685db 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/RelayNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/RelayNode.scala @@ -9,10 +9,7 @@ import totoro.ocelot.brain.network import totoro.ocelot.brain.util.Direction class RelayNode(val relay: Relay) - extends EntityNode(relay) - with SyncedInventory - with LabeledNode - with WindowedNode[RelayWindow] { + extends EntityNode(relay) with SyncedInventory with LabeledNode with WindowedNode[RelayWindow] { override val iconSource: IconSource = IconSource.Nodes.Relay @@ -22,7 +19,8 @@ class RelayNode(val relay: Relay) NodePort(Some(Direction.East)), NodePort(Some(Direction.West)), NodePort(Some(Direction.Up)), - NodePort(Some(Direction.Down))) + NodePort(Some(Direction.Down)), + ) override def getNodeByPort(port: NodePort): network.Node = relay.sidedNode(port.direction.get) diff --git a/src/main/scala/ocelot/desktop/node/nodes/ScreenNode.scala b/src/main/scala/ocelot/desktop/node/nodes/ScreenNode.scala index ada9360..6554801 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/ScreenNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/ScreenNode.scala @@ -19,18 +19,14 @@ import totoro.ocelot.brain.nbt.NBTTagCompound import totoro.ocelot.brain.util.PackedColor class ScreenNode(val screen: Screen) - extends EntityNode(screen) - with LabeledEntityNode - with WindowedNode[ScreenWindow] - with TickUpdatable { + extends EntityNode(screen) with LabeledEntityNode with WindowedNode[ScreenWindow] with TickUpdatable { // NOTE: whenever you access screen's TextBuffer methods, make sure to synchronize on `screen`: // computers may update the screen data concurrently via direct methods! // conversely, if a property is only modified via indirect methods, no additional synchronization is necessary. - override def minimumSize: Size2D = Size2D( Size * screen.aspectRatio._1, - Size * screen.aspectRatio._2 + Size * screen.aspectRatio._2, ) override def maximumSize: Size2D = minimumSize @@ -170,7 +166,7 @@ class ScreenNode(val screen: Screen) startY: Float, scaleX: Float, scaleY: Float, - filteringMode: MinFilteringMode + filteringMode: MinFilteringMode, ): Unit = { g.save() g.scale(scaleX, scaleY) @@ -196,7 +192,7 @@ class ScreenNode(val screen: Screen) y, width, height, - iconColor + iconColor, ) } @@ -233,7 +229,7 @@ class ScreenNode(val screen: Screen) position.x + HighlightThickness, position.y + y * Size, NoHighlightSize, - Size + Size, ) } @@ -261,14 +257,15 @@ class ScreenNode(val screen: Screen) ) // Middle - for (x <- 1 until aspectRatioWidth - 1) + for (x <- 1 until aspectRatioWidth - 1) { drawScreenPart( IconSource.Nodes.Screen.RowMiddle, position.x + x * Size, position.y + HighlightThickness, Size, - NoHighlightSize + NoHighlightSize, ) + } // Right drawScreenPart( @@ -276,7 +273,7 @@ class ScreenNode(val screen: Screen) position.x + (aspectRatioWidth - 1) * Size, position.y + HighlightThickness, Size - HighlightThickness, - NoHighlightSize + NoHighlightSize, ) } // n x n @@ -286,7 +283,7 @@ class ScreenNode(val screen: Screen) height: Float, leftIcon: IconSource, middleIcon: IconSource, - rightIcon: IconSource + rightIcon: IconSource, ): Unit = { // Left drawScreenPart( @@ -294,18 +291,19 @@ class ScreenNode(val screen: Screen) position.x + HighlightThickness, y, Size, - height + height, ) // Middle - for (x <- 1 until aspectRatioWidth - 1) + for (x <- 1 until aspectRatioWidth - 1) { drawScreenPart( middleIcon, position.x + x * Size, y, Size, - height + height, ) + } // Right drawScreenPart( @@ -313,7 +311,7 @@ class ScreenNode(val screen: Screen) position.x + (aspectRatioWidth - 1) * Size - HighlightThickness, y, Size, - height + height, ) } @@ -323,18 +321,19 @@ class ScreenNode(val screen: Screen) Size - HighlightThickness, IconSource.Nodes.Screen.TopLeft, IconSource.Nodes.Screen.TopMiddle, - IconSource.Nodes.Screen.TopRight + IconSource.Nodes.Screen.TopRight, ) // Middle - for (y <- 1 until aspectRatioHeight - 1) + for (y <- 1 until aspectRatioHeight - 1) { drawLine( position.y + (y * Size), Size, IconSource.Nodes.Screen.MiddleLeft, IconSource.Nodes.Screen.Middle, - IconSource.Nodes.Screen.MiddleRight + IconSource.Nodes.Screen.MiddleRight, ) + } // Bottom drawLine( @@ -342,7 +341,7 @@ class ScreenNode(val screen: Screen) Size - HighlightThickness, IconSource.Nodes.Screen.BottomLeft, IconSource.Nodes.Screen.BottomMiddle, - IconSource.Nodes.Screen.BottomRight + IconSource.Nodes.Screen.BottomRight, ) } } @@ -365,18 +364,18 @@ class ScreenNode(val screen: Screen) virtualScreenBounds.y, virtualScreenBounds.w, virtualScreenBounds.h, - Color.Black + Color.Black, ) // Calculating pixel data bounds, so that they fit perfectly into the virtual screen val pixelDataSize = Size2D( screenWidth * FontWidth, - screenHeight * FontHeight + screenHeight * FontHeight, ) val scale = Math.min( virtualScreenBounds.w / pixelDataSize.width, - virtualScreenBounds.h / pixelDataSize.height + virtualScreenBounds.h / pixelDataSize.height, ) // Drawing pixel data @@ -386,7 +385,7 @@ class ScreenNode(val screen: Screen) virtualScreenBounds.y + virtualScreenBounds.h / 2 - (pixelDataSize.height * scale) / 2, scale, scale, - MinFilteringMode.NearestMipmapNearest + MinFilteringMode.NearestMipmapNearest, ) } // Drawing simple overlay otherwise @@ -396,7 +395,7 @@ class ScreenNode(val screen: Screen) position.x + HighlightThickness, position.y + HighlightThickness, NoHighlightSize, - NoHighlightSize + NoHighlightSize, ) } } diff --git a/src/main/scala/ocelot/desktop/node/nodes/TapeDriveNode.scala b/src/main/scala/ocelot/desktop/node/nodes/TapeDriveNode.scala index 36b8207..114abe8 100644 --- a/src/main/scala/ocelot/desktop/node/nodes/TapeDriveNode.scala +++ b/src/main/scala/ocelot/desktop/node/nodes/TapeDriveNode.scala @@ -12,19 +12,18 @@ import totoro.ocelot.brain.entity.{TapeDrive, TapeDriveState} import totoro.ocelot.brain.event.{TapeDriveAudioEvent, TapeDriveStopEvent} class TapeDriveNode(val tapeDrive: TapeDrive) - extends EntityNode(tapeDrive) + extends EntityNode(tapeDrive) with SyncedInventory with LabeledEntityNode with PositionalSoundSourcesNode - with WindowedNode[TapeDriveWindow] -{ + with WindowedNode[TapeDriveWindow] { override def iconSource: IconSource = IconSource.Nodes.TapeDrive private lazy val soundTapeRewind: SoundSource = SoundSource.fromBuffer( SoundBuffers.MachineTapeRewind, SoundCategory.Records, - looping = true + looping = true, ) private lazy val streams: (SoundStream, SoundSource) = Audio.newStream(SoundCategory.Records) @@ -53,7 +52,8 @@ class TapeDriveNode(val tapeDrive: TapeDrive) override def update(): Unit = { super.update() - val isRewinding = tapeDrive.state.state == TapeDriveState.State.Rewinding || tapeDrive.state.state == TapeDriveState.State.Forwarding + val isRewinding = + tapeDrive.state.state == TapeDriveState.State.Rewinding || tapeDrive.state.state == TapeDriveState.State.Forwarding if (!isRewinding && soundTapeRewind.isPlaying) { soundTapeRewind.stop() @@ -78,7 +78,6 @@ class TapeDriveNode(val tapeDrive: TapeDrive) override def brainInventory: TapeDrive = tapeDrive - // -------------------------------- Windowed -------------------------------- override protected def createWindow(): TapeDriveWindow = new TapeDriveWindow(this) diff --git a/src/main/scala/ocelot/desktop/ui/UiHandler.scala b/src/main/scala/ocelot/desktop/ui/UiHandler.scala index 52e4345..fea5aed 100644 --- a/src/main/scala/ocelot/desktop/ui/UiHandler.scala +++ b/src/main/scala/ocelot/desktop/ui/UiHandler.scala @@ -76,12 +76,14 @@ object UiHandler extends Logging { private val _clipboard = Toolkit.getDefaultToolkit.getSystemClipboard - def clipboard: String = try { - _clipboard.getData(DataFlavor.stringFlavor).toString - } catch { - case _: UnsupportedFlavorException => - logger.debug("Trying to paste non-Unicode content from clipboard! Replaced with empty string.") - "" + def clipboard: String = { + try { + _clipboard.getData(DataFlavor.stringFlavor).toString + } catch { + case _: UnsupportedFlavorException => + logger.debug("Trying to paste non-Unicode content from clipboard! Replaced with empty string.") + "" + } } def clipboard_=(value: String): Unit = { @@ -155,11 +157,12 @@ object UiHandler extends Logging { private def windowGeometry: Rect2D = new Rect2D(Display.getX, Display.getY, Display.getWidth, Display.getHeight) - private def sanitizeWindowSize(size: Size2D): Size2D = + private def sanitizeWindowSize(size: Size2D): Size2D = { Size2D( if (size.width < 10) 800 else size.width, if (size.height < 10) 600 else size.height, ) + } private def sanitizeWindowGeometry(currentGeometry: Rect2D): Rect2D = { val Rect2D(x, y, w, h) = currentGeometry @@ -243,21 +246,22 @@ object UiHandler extends Logging { val arch = System.getProperty("os.arch") val is64bit = arch.startsWith("amd64") - val libs = - if (SystemUtils.IS_OS_WINDOWS) + val libs = { + if (SystemUtils.IS_OS_WINDOWS) { if (is64bit) Array("jinput-dx8_64.dll", "jinput-raw_64.dll", "jinput-wintab.dll", "lwjgl64.dll", "OpenAL64.dll") else Array("jinput-dx8.dll", "jinput-raw.dll", "jinput-wintab.dll", "lwjgl.dll", "OpenAL32.dll") - else if (SystemUtils.IS_OS_MAC_OSX) + } else if (SystemUtils.IS_OS_MAC_OSX) Array("liblwjgl.dylib") - else if (SystemUtils.IS_OS_LINUX) + else if (SystemUtils.IS_OS_LINUX) { if (is64bit) Array("libjinput-linux64.so", "liblwjgl64.so", "libopenal64.so") else Array("libjinput-linux.so", "liblwjgl.so", "libopenal.so") - else + } else throw new Exception("Unsupported OS") + } logger.debug(s"Unpacking native libraries to: $librariesPath") @@ -329,13 +333,14 @@ object UiHandler extends Logging { UiThreadTasks.add(updateWindowTitle) } - private def updateWindowTitle(): Unit = + private def updateWindowTitle(): Unit = { Display.setTitle( if (_windowTitleSuffix.isEmpty) windowTitleBase else s"$windowTitleBase - ${_windowTitleSuffix.get}" ) + } private var exitRequested = false @@ -441,7 +446,7 @@ object UiHandler extends Logging { ScrollEvents.events.foreach(dispatchEvent(scrollTarget)) - for (event <- MouseEvents.events) + for (event <- MouseEvents.events) { if (event.state == MouseEvent.State.Press) { dispatchEvent(mouseTarget)(event) @@ -452,6 +457,7 @@ object UiHandler extends Logging { } else { dispatchEvent(hierarchy.reverseIterator)(event) } + } hierarchy.reverseIterator.foreach { case handler: HoverHandler if !mouseTarget.contains(handler) => handler.setHovered(false) diff --git a/src/main/scala/ocelot/desktop/ui/event/DragEvent.scala b/src/main/scala/ocelot/desktop/ui/event/DragEvent.scala index 1a65968..b52c1d7 100644 --- a/src/main/scala/ocelot/desktop/ui/event/DragEvent.scala +++ b/src/main/scala/ocelot/desktop/ui/event/DragEvent.scala @@ -3,14 +3,12 @@ package ocelot.desktop.ui.event import ocelot.desktop.geometry.Vector2D object DragEvent { - object State extends Enumeration { val Start, Drag, Stop = Value } def apply(state: DragEvent.State.Value, button: MouseEvent.Button.Value, mousePos: Vector2D, - start: Vector2D, delta: Vector2D): DragEvent = - { + start: Vector2D, delta: Vector2D): DragEvent = { val ev = DragEvent(state, button, mousePos) ev._start = start ev._delta = delta diff --git a/src/main/scala/ocelot/desktop/ui/event/HoverEvent.scala b/src/main/scala/ocelot/desktop/ui/event/HoverEvent.scala index 59e5832..c3abbc2 100644 --- a/src/main/scala/ocelot/desktop/ui/event/HoverEvent.scala +++ b/src/main/scala/ocelot/desktop/ui/event/HoverEvent.scala @@ -1,11 +1,9 @@ package ocelot.desktop.ui.event object HoverEvent { - object State extends Enumeration { val Enter, Leave = Value } - } -case class HoverEvent(state: HoverEvent.State.Value) extends Event \ No newline at end of file +case class HoverEvent(state: HoverEvent.State.Value) extends Event diff --git a/src/main/scala/ocelot/desktop/ui/event/MouseEvent.scala b/src/main/scala/ocelot/desktop/ui/event/MouseEvent.scala index 5db3d10..ec6486b 100644 --- a/src/main/scala/ocelot/desktop/ui/event/MouseEvent.scala +++ b/src/main/scala/ocelot/desktop/ui/event/MouseEvent.scala @@ -1,8 +1,6 @@ package ocelot.desktop.ui.event - object MouseEvent { - object State extends Enumeration { val Press, Release = Value } @@ -12,7 +10,6 @@ object MouseEvent { val Right: Button.Value = Value(1) val Middle: Button.Value = Value(2) } - } case class MouseEvent(state: MouseEvent.State.Value, button: MouseEvent.Button.Value) extends Event diff --git a/src/main/scala/ocelot/desktop/ui/event/handlers/DiskActivityHandler.scala b/src/main/scala/ocelot/desktop/ui/event/handlers/DiskActivityHandler.scala index 1e62011..b5b1dc8 100644 --- a/src/main/scala/ocelot/desktop/ui/event/handlers/DiskActivityHandler.scala +++ b/src/main/scala/ocelot/desktop/ui/event/handlers/DiskActivityHandler.scala @@ -10,13 +10,14 @@ import scala.util.Random trait DiskActivityHandler extends EventAware { eventHandlers += { case BrainEvent(event: FileSystemActivityEvent) if !Audio.isDisabled => - val sound = + val sound = { if (event.activityType == Floppy) SoundBuffers.MachineFloppyAccess .map(buffer => SoundSource.fromBuffer(buffer, SoundCategory.Environment)) else SoundBuffers.MachineHDDAccess .map(buffer => SoundSource.fromBuffer(buffer, SoundCategory.Environment)) + } sound(Random.between(0, sound.length)).play() } diff --git a/src/main/scala/ocelot/desktop/ui/event/handlers/MouseHandler.scala b/src/main/scala/ocelot/desktop/ui/event/handlers/MouseHandler.scala index 2784f4e..d904971 100644 --- a/src/main/scala/ocelot/desktop/ui/event/handlers/MouseHandler.scala +++ b/src/main/scala/ocelot/desktop/ui/event/handlers/MouseHandler.scala @@ -19,8 +19,7 @@ trait MouseHandler extends Widget { protected def receiveDragEvents: Boolean = false - /** - * If `true`, a [[ClickEvent]] will be registered even if the mouse button is released + /** If `true`, a [[ClickEvent]] will be registered even if the mouse button is released * outside the tolerance threshold, as long as it stays within the widget's bounds. */ protected def allowClickReleaseOutsideThreshold: Boolean = !receiveDragEvents @@ -35,14 +34,14 @@ trait MouseHandler extends Widget { val dragStopped = receiveDragEvents && dragButtons.remove(button) val clicked = ( receiveClickEvents - && !dragStopped - && startPositions.get(button).exists(p => { - if (allowClickReleaseOutsideThreshold) { - clippedBounds.contains(mousePos) - } else { - (p - mousePos).lengthSquared < Tolerance * Tolerance - } - }) + && !dragStopped + && startPositions.get(button).exists(p => { + if (allowClickReleaseOutsideThreshold) { + clippedBounds.contains(mousePos) + } else { + (p - mousePos).lengthSquared < Tolerance * Tolerance + } + }) ) if (dragStopped) { @@ -73,16 +72,18 @@ trait MouseHandler extends Widget { } } - dragButtons.foreach( - button => { - handleEvent( - DragEvent( - DragEvent.State.Drag, button, mousePos, startPositions(button), - mousePos - prevPositions(button) - ) + dragButtons.foreach(button => { + handleEvent( + DragEvent( + DragEvent.State.Drag, + button, + mousePos, + startPositions(button), + mousePos - prevPositions(button), ) - prevPositions(button) = mousePos - } + ) + prevPositions(button) = mousePos + } ) } } diff --git a/src/main/scala/ocelot/desktop/ui/layout/LinearLayout.scala b/src/main/scala/ocelot/desktop/ui/layout/LinearLayout.scala index 9a4d469..2d8197a 100644 --- a/src/main/scala/ocelot/desktop/ui/layout/LinearLayout.scala +++ b/src/main/scala/ocelot/desktop/ui/layout/LinearLayout.scala @@ -8,8 +8,8 @@ class LinearLayout(widget: Widget, orientation: Orientation.Value = Orientation.Horizontal, justifyContent: JustifyContent.Value = JustifyContent.Start, alignItems: AlignItems.Value = AlignItems.Stretch, - gap: Float = 0f) extends Layout(widget) -{ + gap: Float = 0f) + extends Layout(widget) { override def recalculateBounds(): Unit = { super.recalculateBounds() @@ -140,7 +140,7 @@ class LinearLayout(widget: Widget, (orientation, alignItems) match { case (Orientation.Vertical, AlignItems.Start) - | (Orientation.Vertical, AlignItems.Stretch) => + | (Orientation.Vertical, AlignItems.Stretch) => child.rawSetPosition(child.position.setX(widget.position.x)) case (Orientation.Vertical, AlignItems.End) => child.rawSetPosition(child.position.setX(widget.position.x + widget.size.width - child.size.width)) @@ -148,7 +148,7 @@ class LinearLayout(widget: Widget, child.rawSetPosition(child.position.setX(widget.position.x + widget.size.width / 2 - child.size.width / 2)) case (Orientation.Horizontal, AlignItems.Start) - | (Orientation.Horizontal, AlignItems.Stretch) => + | (Orientation.Horizontal, AlignItems.Stretch) => child.rawSetPosition(child.position.setY(widget.position.y)) case (Orientation.Horizontal, AlignItems.End) => child.rawSetPosition(child.position.setY(widget.position.y + widget.size.height - child.size.height)) diff --git a/src/main/scala/ocelot/desktop/ui/swing/SplashScreen.scala b/src/main/scala/ocelot/desktop/ui/swing/SplashScreen.scala index 65f0a77..58757b2 100644 --- a/src/main/scala/ocelot/desktop/ui/swing/SplashScreen.scala +++ b/src/main/scala/ocelot/desktop/ui/swing/SplashScreen.scala @@ -35,7 +35,8 @@ class SplashScreen extends JDialog { panel.setBackground(new Color(0, 0, 0, 0)) panel.setLayout(null) - private def addLabel(rectangle: Rectangle, text: String, horizontalAlignment: Int = SwingConstants.LEFT, verticalAlignment: Int = SwingConstants.TOP): JLabel = { + private def addLabel(rectangle: Rectangle, text: String, horizontalAlignment: Int = SwingConstants.LEFT, + verticalAlignment: Int = SwingConstants.TOP): JLabel = { val label = new JLabel(text) label.setForeground(Color.white) label.setBounds(rectangle) @@ -57,7 +58,7 @@ class SplashScreen extends JDialog { new Rectangle(0, 0, imageWidth, imageHeight), s"Version: ${BuildInfo.version} (${BuildInfo.commit.take(7)})", SwingConstants.LEFT, - SwingConstants.BOTTOM + SwingConstants.BOTTOM, ) setLabelMargin(applicationVersion, new Insets(0, 20, 20, 0)) @@ -70,7 +71,7 @@ class SplashScreen extends JDialog { new Rectangle(0, 0, imageWidth, imageHeight), s"© 2018 - ${Year.now.getValue} Ocelot Dev Team", SwingConstants.RIGHT, - SwingConstants.BOTTOM + SwingConstants.BOTTOM, ) setLabelMargin(copyright, new Insets(0, 0, 20, 20)) diff --git a/src/main/scala/ocelot/desktop/ui/widget/Button.scala b/src/main/scala/ocelot/desktop/ui/widget/Button.scala index f50de57..7e983ac 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Button.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Button.scala @@ -11,11 +11,7 @@ import ocelot.desktop.ui.widget.tooltip.Tooltip import ocelot.desktop.ui.widget.traits.HoverAnimation import ocelot.desktop.util.DrawUtils -class Button(tooltip: Option[Tooltip] = None) - extends Widget - with MouseHandler - with HoverHandler - with HoverAnimation { +class Button(tooltip: Option[Tooltip] = None) extends Widget with MouseHandler with HoverHandler with HoverAnimation { def this(tooltip: Tooltip) = this(Some(tooltip)) @@ -53,11 +49,12 @@ class Button(tooltip: Option[Tooltip] = None) val (background, border, foreground) = if (enabled) ( hoverAnimation.color, colorScheme("ButtonBorder"), - colorScheme("ButtonForeground") - ) else ( + colorScheme("ButtonForeground"), + ) + else ( colorScheme("ButtonBackgroundDisabled"), colorScheme("ButtonBorderDisabled"), - colorScheme("ButtonForegroundDisabled") + colorScheme("ButtonForegroundDisabled"), ) g.rect(bounds, background) diff --git a/src/main/scala/ocelot/desktop/ui/widget/ChangeSimulationSpeedDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/ChangeSimulationSpeedDialog.scala index 53454a9..bc4d1ad 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/ChangeSimulationSpeedDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/ChangeSimulationSpeedDialog.scala @@ -21,88 +21,100 @@ class ChangeSimulationSpeedDialog extends ModalDialog { close() } - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= new PaddingBox(new Label("Change simulation speed"), Padding2D(bottom = 16)) + children :+= new PaddingBox(new Label("Change simulation speed"), Padding2D(bottom = 16)) - private var inputTPS: TextInput = _ - private var inputMSPT: TextInput = _ - private def formatMSPT(interval: Duration): String = (interval.toMicros / 1000f).toString - private def formatTPS(interval: Duration): String = (1_000_000f / interval.toMicros).toString + private var inputTPS: TextInput = _ + private var inputMSPT: TextInput = _ + private def formatMSPT(interval: Duration): String = (interval.toMicros / 1000f).toString + private def formatTPS(interval: Duration): String = (1_000_000f / interval.toMicros).toString - inputMSPT = new TextInput(formatMSPT(OcelotDesktop.ticker.tickInterval)) { - focus() + inputMSPT = new TextInput(formatMSPT(OcelotDesktop.ticker.tickInterval)) { + focus() - private def parseInput(text: String): Option[Duration] = try { - validateIntervalUs((text.toFloat * 1000).toLong) - } catch { - case _: NumberFormatException => None + private def parseInput(text: String): Option[Duration] = { + try { + validateIntervalUs((text.toFloat * 1000).toLong) + } catch { + case _: NumberFormatException => None + } + } + + override def onInput(text: String): Unit = { + tickInterval = parseInput(text).map { interval => + inputTPS.setInput(formatTPS(interval)) + interval + } + } + + override def validator(text: String): Boolean = parseInput(text).isDefined + + override def onConfirm(): Unit = confirm() } - override def onInput(text: String): Unit = { - tickInterval = parseInput(text).map { interval => - inputTPS.setInput(formatTPS(interval)) - interval + inputTPS = new TextInput(formatTPS(OcelotDesktop.ticker.tickInterval)) { + private def parseInput(text: String): Option[Duration] = { + try { + validateIntervalUs((1_000_000 / text.toFloat).toLong) + } catch { + case _: NumberFormatException => None + } + } + + override def onInput(text: String): Unit = { + tickInterval = parseInput(text).map { interval => + inputMSPT.setInput(formatMSPT(interval)) + interval + } + } + + override def validator(text: String): Boolean = parseInput(text).isDefined + + override def onConfirm(): Unit = confirm() + } + + children :+= new Label("Milliseconds per tick:") + children :+= new PaddingBox(inputMSPT, Padding2D(bottom = 8)) + children :+= new Label("Ticks per second:") + children :+= new PaddingBox(inputTPS, Padding2D(bottom = 8)) + + children :+= new Widget { + children :+= new Filler + + children :+= new PaddingBox( + new Button { + override def text: String = "Cancel" + override protected def clickSoundSource: ClickSoundSource = SoundSource.InterfaceClickLow + override def onClick(): Unit = close() + }, + Padding2D(right = 8), + ) + + children :+= new Button { + override def text: String = "Apply" + override def onClick(): Unit = confirm() + override def enabled: Boolean = tickInterval.nonEmpty } } - - override def validator(text: String): Boolean = parseInput(text).isDefined - - override def onConfirm(): Unit = confirm() - } - - inputTPS = new TextInput(formatTPS(OcelotDesktop.ticker.tickInterval)) { - private def parseInput(text: String): Option[Duration] = try { - validateIntervalUs((1_000_000 / text.toFloat).toLong) - } catch { - case _: NumberFormatException => None - } - - override def onInput(text: String): Unit = { - tickInterval = parseInput(text).map { interval => - inputMSPT.setInput(formatMSPT(interval)) - interval - } - } - - override def validator(text: String): Boolean = parseInput(text).isDefined - - override def onConfirm(): Unit = confirm() - } - - children :+= new Label("Milliseconds per tick:") - children :+= new PaddingBox(inputMSPT, Padding2D(bottom = 8)) - children :+= new Label("Ticks per second:") - children :+= new PaddingBox(inputTPS, Padding2D(bottom = 8)) - - children :+= new Widget { - children :+= new Filler - - children :+= new PaddingBox(new Button { - override def text: String = "Cancel" - override protected def clickSoundSource: ClickSoundSource = SoundSource.InterfaceClickLow - override def onClick(): Unit = close() - }, Padding2D(right = 8)) - - children :+= new Button { - override def text: String = "Apply" - override def onClick(): Unit = confirm() - override def enabled: Boolean = tickInterval.nonEmpty - } - } - }, Padding2D.equal(16)) + }, + Padding2D.equal(16), + ) } object ChangeSimulationSpeedDialog { private val MaxUpdateInterval = 1.minute private val MinUpdateInterval = 1.micro - private def validateIntervalUs(us: Long): Option[Duration] = try { - val interval = us.micros + private def validateIntervalUs(us: Long): Option[Duration] = { + try { + val interval = us.micros - Option.when(interval >= MinUpdateInterval && interval <= MaxUpdateInterval)(interval) - } catch { - case _: IllegalArgumentException => None + Option.when(interval >= MinUpdateInterval && interval <= MaxUpdateInterval)(interval) + } catch { + case _: IllegalArgumentException => None + } } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/Checkbox.scala b/src/main/scala/ocelot/desktop/ui/widget/Checkbox.scala index 98ffd2e..c0e9dad 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Checkbox.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Checkbox.scala @@ -10,9 +10,7 @@ import ocelot.desktop.ui.widget.traits.HoverAnimation import ocelot.desktop.util.DrawUtils class Checkbox(val label: String, val initialValue: Boolean = false, val isSmall: Boolean = false) - extends Widget - with MouseHandler - with HoverAnimation { + extends Widget with MouseHandler with HoverAnimation { override protected val hoverAnimationColorDefault: Color = ColorScheme("CheckboxBackground") override protected val hoverAnimationColorActive: Color = ColorScheme("CheckboxBackgroundActive") @@ -20,6 +18,7 @@ class Checkbox(val label: String, val initialValue: Boolean = false, val isSmall private var _checked: Boolean = initialValue def checked: Boolean = _checked + def checked_=(value: Boolean): Unit = { if (_checked != value) { _checked = value diff --git a/src/main/scala/ocelot/desktop/ui/widget/CloseConfirmationDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/CloseConfirmationDialog.scala index b9f20ea..2759ca4 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/CloseConfirmationDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/CloseConfirmationDialog.scala @@ -9,33 +9,48 @@ import ocelot.desktop.util.Orientation class CloseConfirmationDialog extends ModalDialog { protected def prompt: String = "Save workspace before exiting?" - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= new PaddingBox(new Label { - override def text: String = prompt - }, Padding2D(bottom = 16)) + children :+= new PaddingBox( + new Label { + override def text: String = prompt + }, + Padding2D(bottom = 16), + ) - children :+= new Widget { - children :+= new PaddingBox(new Button { - override def text: String = "Cancel" - override protected def clickSoundSource: ClickSoundSource = SoundSource.InterfaceClickLow - override def onClick(): Unit = close() - }, Padding2D(left = 8)) + children :+= new Widget { + children :+= new PaddingBox( + new Button { + override def text: String = "Cancel" + override protected def clickSoundSource: ClickSoundSource = SoundSource.InterfaceClickLow + override def onClick(): Unit = close() + }, + Padding2D(left = 8), + ) - children :+= new Filler + children :+= new Filler - children :+= new PaddingBox(new Button { - override def text: String = "No" - override def onClick(): Unit = onNoSaveSelected() - }, Padding2D(right = 8)) + children :+= new PaddingBox( + new Button { + override def text: String = "No" + override def onClick(): Unit = onNoSaveSelected() + }, + Padding2D(right = 8), + ) - children :+= new PaddingBox(new Button { - override def text: String = "Yes" - override def onClick(): Unit = onSaveSelected() - }, Padding2D(right = 8)) - } - }, Padding2D.equal(16)) + children :+= new PaddingBox( + new Button { + override def text: String = "Yes" + override def onClick(): Unit = onSaveSelected() + }, + Padding2D(right = 8), + ) + } + }, + Padding2D.equal(16), + ) def onSaveSelected(): Unit = {} diff --git a/src/main/scala/ocelot/desktop/ui/widget/ComponentUsageBar.scala b/src/main/scala/ocelot/desktop/ui/widget/ComponentUsageBar.scala index e5dbee1..9afbae2 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/ComponentUsageBar.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/ComponentUsageBar.scala @@ -41,17 +41,21 @@ class ComponentUsageBar extends Widget with TickUpdatable { // Vertical lines for (i <- 0 until cellCount) { g.rect( - x + i * cellWidth, position.y, - cellThickness, gridHeight, - ColorScheme("HistogramGrid") + x + i * cellWidth, + position.y, + cellThickness, + gridHeight, + ColorScheme("HistogramGrid"), ) } // Closing vertical line g.rect( - x + gridWidth, position.y, - cellThickness, gridHeight + cellThickness, - ColorScheme("HistogramGrid") + x + gridWidth, + position.y, + cellThickness, + gridHeight + cellThickness, + ColorScheme("HistogramGrid"), ) val fillWidth = Math.min( @@ -59,7 +63,7 @@ class ComponentUsageBar extends Widget with TickUpdatable { cellWidth * currentValue - cellThickness else gridWidth * (currentValue.toFloat / maxValue), - gridWidth + gridWidth, ) // Value fill @@ -70,9 +74,11 @@ class ComponentUsageBar extends Widget with TickUpdatable { } g.rect( - x + cellThickness, position.y + cellThickness, - fillWidth, cellHeight - cellThickness, - fillColor + x + cellThickness, + position.y + cellThickness, + fillWidth, + cellHeight - cellThickness, + fillColor, ) // Value line @@ -83,9 +89,11 @@ class ComponentUsageBar extends Widget with TickUpdatable { } g.rect( - x + fillWidth + cellThickness, position.y, - cellThickness, cellHeight + cellThickness, - edgeColor + x + fillWidth + cellThickness, + position.y, + cellThickness, + cellHeight + cellThickness, + edgeColor, ) } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/Filler.scala b/src/main/scala/ocelot/desktop/ui/widget/Filler.scala index e109896..0a5dbe3 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Filler.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Filler.scala @@ -1,4 +1,5 @@ package ocelot.desktop.ui.widget + import ocelot.desktop.geometry.Size2D class Filler extends Widget { diff --git a/src/main/scala/ocelot/desktop/ui/widget/Histogram.scala b/src/main/scala/ocelot/desktop/ui/widget/Histogram.scala index 0126b67..be259a4 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Histogram.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Histogram.scala @@ -68,7 +68,7 @@ class Histogram extends Widget { position.y, cellThickness, if (lesserThenPreLast) gridHeight else gridHeight + cellThickness, - ColorScheme("HistogramGrid") + ColorScheme("HistogramGrid"), ) // History @@ -87,7 +87,7 @@ class Histogram extends Widget { position.y + gridHeight + cellThickness - historyValueHeight, historyValueWidth, historyValueHeight, - ColorScheme("HistogramFill") + ColorScheme("HistogramFill"), ) } @@ -97,7 +97,7 @@ class Histogram extends Widget { position.y + gridHeight + cellThickness - historyValueHeight, historyValueWidth, cellThickness, - ColorScheme("HistogramEdge") + ColorScheme("HistogramEdge"), ) x += cellSize diff --git a/src/main/scala/ocelot/desktop/ui/widget/Icon.scala b/src/main/scala/ocelot/desktop/ui/widget/Icon.scala index cf7f3eb..f796545 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Icon.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Icon.scala @@ -15,11 +15,13 @@ class Icon(icon: IconSource, size: Size2D = null, private val color: Color = Col } def iconColor: Color = color - def iconSize: Size2D = + + def iconSize: Size2D = { if (size != null) size else if (icon.animation.isDefined && icon.animation.get.frameSize.isDefined) icon.animation.get.frameSize.get else Spritesheet.spriteSize(icon.path) + } override def minimumSize: Size2D = iconSize override def maximumSize: Size2D = minimumSize @@ -27,4 +29,4 @@ class Icon(icon: IconSource, size: Size2D = null, private val color: Color = Col override def draw(g: Graphics): Unit = { g.sprite(icon.path, bounds.x, bounds.y, bounds.w, bounds.h, iconColor, icon.animation) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/IconButton.scala b/src/main/scala/ocelot/desktop/ui/widget/IconButton.scala index 783d84a..77150d3 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/IconButton.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/IconButton.scala @@ -25,10 +25,7 @@ class IconButton( tooltip: Option[String] = None, darkenActiveColorFactor: Float = 0f, val model: IconButton.Model = IconButton.DefaultModel(false), -) extends Widget - with MouseHandler - with HoverHandler - with HoverAnimation { +) extends Widget with MouseHandler with HoverHandler with HoverAnimation { override protected def receiveClickEvents: Boolean = true @@ -47,26 +44,24 @@ class IconButton( clickSoundSource.press.play() case MouseEvent(MouseEvent.State.Release, MouseEvent.Button.Left) => mode match { - case Mode.Regular if model.pressed => - handleRelease() - clickSoundSource.release.play() + case Mode.Regular if model.pressed => + handleRelease() + clickSoundSource.release.play() - case _ => // the other modes are triggered on click. - } + case _ => // the other modes are triggered on click. + } case ClickEvent(MouseEvent.Button.Left, _) => mode match { - case Mode.Regular => // regular buttons are handled above. + case Mode.Regular => // regular buttons are handled above. + case Mode.Switch if model.pressed => + handleRelease() + clickSoundSource.release.play() - case Mode.Switch if model.pressed => - handleRelease() - clickSoundSource.release.play() - - case Mode.Radio if model.pressed => // the radio button is already pressed; ignore. - - case Mode.Radio | Mode.Switch => - handlePress() - clickSoundSource.release.play() - } + case Mode.Radio if model.pressed => // the radio button is already pressed; ignore. + case Mode.Radio | Mode.Switch => + handlePress() + clickSoundSource.release.play() + } } def onPressed(): Unit = {} @@ -183,24 +178,22 @@ object IconButton { sealed trait Mode object Mode { - /** - * Your regular, run-of-the-mill button you love. + + /** Your regular, run-of-the-mill button you love. * * When the LMB is depressed, [[IconButton.onPressed]] is called. * After it's released, [[IconButton.onReleased]] is called. */ case object Regular extends Mode - /** - * A toggleable button, or a switch. + /** A toggleable button, or a switch. * * Clicking the LMB while the button is pressed releases it, and [[IconButton.onReleased]] is called. * Clicking the LMB while the button is released depresses it, and [[IconButton.onPressed]] is called. */ case object Switch extends Mode - /** - * A radio button is like a switch except clicking on it while it's depressed doesn't do anything. + /** A radio button is like a switch except clicking on it while it's depressed doesn't do anything. * * [[IconButton.onReleased]] is never called (unless you do it yourself). * @@ -209,21 +202,18 @@ object IconButton { case object Radio extends Mode } - /** - * This is the visible button state. + /** This is the visible button state. * * When [[IconButton.update]] notices a state change, it runs its animations. * * Note that callbacks are run after running the setter regardless of whether it does anything. */ trait Model { - /** - * Whether to display the pressed button state. - */ + + /** Whether to display the pressed button state. */ def pressed: Boolean - /** - * This setter is used by [[IconButton]] to respond to user interaction. + /** This setter is used by [[IconButton]] to respond to user interaction. * * You may want to override this method to do nothing * if you're proxying another model and updating it in callbacks. @@ -231,14 +221,10 @@ object IconButton { def pressed_=(newValue: Boolean): Unit } - /** - * This is the default model that simply reads from a variable and writes to it. - */ + /** This is the default model that simply reads from a variable and writes to it. */ case class DefaultModel(override var pressed: Boolean) extends Model - /** - * This is a model that ignores user input (presumably you handle it in callbacks). - */ + /** This is a model that ignores user input (presumably you handle it in callbacks). */ class ReadOnlyModel(f: () => Boolean) extends Model { override def pressed: Boolean = f() @@ -246,8 +232,8 @@ object IconButton { } object ReadOnlyModel { - /** - * A utility method to create a new instance of [[ReadOnlyModel]]. + + /** A utility method to create a new instance of [[ReadOnlyModel]]. * * The value returned by [[ReadOnlyModel.pressed]] is obtained * by evaluating the provided expression '''every time'''. diff --git a/src/main/scala/ocelot/desktop/ui/widget/InputDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/InputDialog.scala index 51f12c4..0d3edc9 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/InputDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/InputDialog.scala @@ -10,7 +10,7 @@ class InputDialog( title: String, onConfirmed: String => Unit, initialText: String = "", - inputValidator: String => Boolean = _ => true + inputValidator: String => Boolean = _ => true, ) extends ModalDialog { private val input = new TextInput(initialText) { focus() @@ -30,9 +30,12 @@ class InputDialog( new Widget { override val layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 8) - children :+= new PaddingBox(new Label { - override def text: String = title - }, Padding2D(bottom = 8)) + children :+= new PaddingBox( + new Label { + override def text: String = title + }, + Padding2D(bottom = 8), + ) children :+= input @@ -51,10 +54,10 @@ class InputDialog( confirm() } }, - Padding2D(left = 8) + Padding2D(left = 8), ) } }, - Padding2D.equal(16) + Padding2D.equal(16), ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/LogWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/LogWidget.scala index b4f8b31..49c579e 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/LogWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/LogWidget.scala @@ -103,12 +103,12 @@ abstract class LogWidget extends Widget { BorderThickness * 2, Text.CharHeight * (lines.length max 1) + EntryPadding * 2 + - BorderThickness * 2 + BorderThickness * 2, ) def size: Size2D = Size2D( minimumSize.width max (messageList.size.width - 2 * EntryMargin), - minimumSize.height + minimumSize.height, ) override def maxY: Float = y + minimumSize.height @@ -135,7 +135,7 @@ abstract class LogWidget extends Widget { g, absoluteBounds.x + BorderThickness + EntryPadding, absoluteBounds.y + BorderThickness + EntryPadding, - lines + lines, ) } } @@ -167,7 +167,6 @@ abstract class LogWidget extends Widget { override def minimumSize: Size2D = Size2D( MessageListWidget.minimumSize.width + 2 * BorderThickness, - MessageListWidget.dummyEntry.maxY + EntryMargin + BorderThickness * 2, // outer border (top + bottom) @@ -199,14 +198,11 @@ object LogWidget { sealed trait LogEntry object LogEntry { - /** - * A message received from a log source. - */ + + /** A message received from a log source. */ case class Rx(message: String) extends LogEntry - /** - * A message sent to a log source. - */ + /** A message sent to a log source. */ case class Tx(message: String) extends LogEntry } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/MenuBar.scala b/src/main/scala/ocelot/desktop/ui/widget/MenuBar.scala index 793369a..9aabde2 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/MenuBar.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/MenuBar.scala @@ -19,42 +19,51 @@ class MenuBar extends Widget { private def addEntry(w: Widget): Unit = entries.children :+= w - addEntry(new MenuBarSubmenu("File", menu => { - menu.addEntry(ContextMenuEntry("New", IconSource.Plus) { OcelotDesktop.newWorkspace() }) - menu.addEntry(ContextMenuEntry("Open", IconSource.Folder) { OcelotDesktop.showOpenDialog() }) - menu.addEntry(ContextMenuEntry("Save", IconSource.Save) { OcelotDesktop.save() }) - menu.addEntry(ContextMenuEntry("Save as", IconSource.SaveAs) { OcelotDesktop.saveAs() }) + addEntry(new MenuBarSubmenu( + "File", + menu => { + menu.addEntry(ContextMenuEntry("New", IconSource.Plus) { OcelotDesktop.newWorkspace() }) + menu.addEntry(ContextMenuEntry("Open", IconSource.Folder) { OcelotDesktop.showOpenDialog() }) + menu.addEntry(ContextMenuEntry("Save", IconSource.Save) { OcelotDesktop.save() }) + menu.addEntry(ContextMenuEntry("Save as", IconSource.SaveAs) { OcelotDesktop.saveAs() }) - menu.addSeparator() + menu.addSeparator() - menu.addEntry(ContextMenuEntry("Exit", IconSource.Cross, SoundSource.InterfaceClickLow) { OcelotDesktop.exit() }) - })) + menu.addEntry(ContextMenuEntry("Exit", IconSource.Cross, SoundSource.InterfaceClickLow) { OcelotDesktop.exit() }) + }, + )) - addEntry(new MenuBarSubmenu("Player", menu => { - menu.addEntry(ContextMenuEntry("Create new", IconSource.Plus) { OcelotDesktop.showAddPlayerDialog() }) - menu.addSeparator() - OcelotDesktop.players.foreach(player => { - menu.addEntry(new ContextMenuSubmenu( - s"${if (player == OcelotDesktop.players.head) "● " else " "}${player.nickname}", - onClick = () => OcelotDesktop.selectPlayer(player.nickname) - ) { - addEntry(ContextMenuEntry("Remove", IconSource.Delete, SoundSource.InterfaceClickLow) { - OcelotDesktop.removePlayer(player.nickname) + addEntry(new MenuBarSubmenu( + "Player", + menu => { + menu.addEntry(ContextMenuEntry("Create new", IconSource.Plus) { OcelotDesktop.showAddPlayerDialog() }) + menu.addSeparator() + OcelotDesktop.players.foreach(player => { + menu.addEntry(new ContextMenuSubmenu( + s"${if (player == OcelotDesktop.players.head) "● " else " "}${player.nickname}", + onClick = () => OcelotDesktop.selectPlayer(player.nickname), + ) { + addEntry(ContextMenuEntry("Remove", IconSource.Delete, SoundSource.InterfaceClickLow) { + OcelotDesktop.removePlayer(player.nickname) + }) }) }) - }) - })) + }, + )) addEntry(new MenuBarButton("Settings", () => new SettingsDialog().show())) - addEntry(new MenuBarSubmenu("Help", menu => { - menu.addEntry(ContextMenuEntry("Check for Updates", IconSource.Help) { - new UpdateCheckerDialog().show() - }) - menu.addSeparator() - menu.addEntry(ContextMenuEntry("Manual", IconSource.Book) {}.setEnabled(false)) - menu.addEntry(ContextMenuEntry("About", IconSource.Ocelot) { new AboutDialog().show() }) - })) + addEntry(new MenuBarSubmenu( + "Help", + menu => { + menu.addEntry(ContextMenuEntry("Check for Updates", IconSource.Help) { + new UpdateCheckerDialog().show() + }) + menu.addSeparator() + menu.addEntry(ContextMenuEntry("Manual", IconSource.Book) {}.setEnabled(false)) + menu.addEntry(ContextMenuEntry("About", IconSource.Ocelot) { new AboutDialog().show() }) + }, + )) addEntry(new Widget { override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1) diff --git a/src/main/scala/ocelot/desktop/ui/widget/MenuBarButton.scala b/src/main/scala/ocelot/desktop/ui/widget/MenuBarButton.scala index 11e0d89..25235d4 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/MenuBarButton.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/MenuBarButton.scala @@ -9,18 +9,18 @@ import ocelot.desktop.ui.event.handlers.{HoverHandler, MouseHandler} import ocelot.desktop.ui.event.{ClickEvent, HoverEvent, MouseEvent} import ocelot.desktop.util.animation.ColorAnimation -class MenuBarButton(label: String, handler: () => Unit = () => {}) - extends Widget - with MouseHandler - with HoverHandler { +class MenuBarButton(label: String, handler: () => Unit = () => {}) extends Widget with MouseHandler with HoverHandler { val colorAnimation: ColorAnimation = new ColorAnimation(ColorScheme("TitleBarBackground"), 0.6f) - children :+= new PaddingBox(new Label { - override def text: String = label - override def color: Color = ColorScheme("TitleBarButtonForeground") - override def maximumSize: Size2D = minimumSize - }, Padding2D(left = 8, right = 8, top = 1, bottom = 1)) + children :+= new PaddingBox( + new Label { + override def text: String = label + override def color: Color = ColorScheme("TitleBarButtonForeground") + override def maximumSize: Size2D = minimumSize + }, + Padding2D(left = 8, right = 8, top = 1, bottom = 1), + ) override protected def receiveClickEvents: Boolean = true diff --git a/src/main/scala/ocelot/desktop/ui/widget/Oscilloscope.scala b/src/main/scala/ocelot/desktop/ui/widget/Oscilloscope.scala index cf0baf3..65afa84 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Oscilloscope.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Oscilloscope.scala @@ -30,71 +30,86 @@ class Oscilloscope(isTiny: Boolean = false) extends Widget { setFFTSize(8192) - private val spectrumPlot = () => new Plot { - private lazy val ticksLarge = List(50f, 100f, 200f, 300f, 500f, 1000f, 2000f, 3000f, 5000f, 10000f, 20000f) - private lazy val ticksSmall = List(50f, 200f, 500f, 2000f, 5000f, 20000f) - private lazy val xAxes = List(ticksLarge, ticksSmall).map(ticks => Plot.Axis(0, 22000, ticks, - tickLabels = !isTiny, - tickFormatter = x => if (x >= 1000) f"${x / 1000}%.0fk" else f"$x%.0f", - hoverFormatter = x => if (x >= 1000) f"${x / 1000}%.2fk" else f"$x%.1f", - logOffset = Some(120), - unit = "Hz")) + private val spectrumPlot = () => { + new Plot { + private lazy val ticksLarge = List(50f, 100f, 200f, 300f, 500f, 1000f, 2000f, 3000f, 5000f, 10000f, 20000f) + private lazy val ticksSmall = List(50f, 200f, 500f, 2000f, 5000f, 20000f) + private lazy val xAxes = List(ticksLarge, ticksSmall).map(ticks => { + Plot.Axis( + 0, + 22000, + ticks, + tickLabels = !isTiny, + tickFormatter = x => if (x >= 1000) f"${x / 1000}%.0fk" else f"$x%.0f", + hoverFormatter = x => if (x >= 1000) f"${x / 1000}%.2fk" else f"$x%.1f", + logOffset = Some(120), + unit = "Hz", + ) + }) - override def xAxis: Plot.Axis = if (width >= 600) xAxes.head else xAxes.last + override def xAxis: Plot.Axis = if (width >= 600) xAxes.head else xAxes.last - override lazy val yAxis: Plot.Axis = Plot.Axis(-150, 10, - ticks = List(0f, -20f, -40f, -60f, -80f, -100f, -120f, -140f), - tickLabels = !isTiny, - tickFormatter = y => f"$y%+.0f", - hoverFormatter = y => f"$y%+.1f", - flip = true, - unit = "dB") + override lazy val yAxis: Plot.Axis = Plot.Axis( + -150, + 10, + ticks = List(0f, -20f, -40f, -60f, -80f, -100f, -120f, -140f), + tickLabels = !isTiny, + tickFormatter = y => f"$y%+.0f", + hoverFormatter = y => f"$y%+.1f", + flip = true, + unit = "dB", + ) - override def points: (Array[Float], Array[Float]) = (spectrumPointsX, spectrumPointsY) + override def points: (Array[Float], Array[Float]) = (spectrumPointsX, spectrumPointsY) - override def fill: Boolean = true + override def fill: Boolean = true - override def setupContextMenu(menu: ContextMenu): Unit = { - addFFTSizeEntry(menu) - addSmoothingEntry(menu) + override def setupContextMenu(menu: ContextMenu): Unit = { + addFFTSizeEntry(menu) + addSmoothingEntry(menu) - super.setupContextMenu(menu) + super.setupContextMenu(menu) + } + + override def onPanelLeftClick(): Unit = updateMode(i => if (i == 0) 2 else 0) } - - override def onPanelLeftClick(): Unit = updateMode(i => if (i == 0) 2 else 0) } - private val wavePlot = () => new Plot { - override lazy val xAxis: Plot.Axis = Plot.Axis(0, wavePeriods, - ticks = List(0.5f, 1f, 1.5f, 2f, 2.5f, 3f, 3.5f), - tickLabels = !isTiny, - tickFormatter = x => f"${2 * x}%.0fπ", - hoverFormatter = x => f"${2 * x}%.1fπ") + private val wavePlot = () => { + new Plot { + override lazy val xAxis: Plot.Axis = Plot.Axis(0, wavePeriods, + ticks = List(0.5f, 1f, 1.5f, 2f, 2.5f, 3f, 3.5f), + tickLabels = !isTiny, + tickFormatter = x => f"${2 * x}%.0fπ", + hoverFormatter = x => f"${2 * x}%.1fπ") - override lazy val yAxis: Plot.Axis = Plot.Axis(-1.1f, 1.1f, - ticks = List(-1f, -0.5f, 0f, 0.5f, 1f), - tickLabels = !isTiny, - tickFormatter = y => f"$y%+.1f", - hoverFormatter = y => f"$y%+.2f", - flip = true) + override lazy val yAxis: Plot.Axis = Plot.Axis(-1.1f, 1.1f, + ticks = List(-1f, -0.5f, 0f, 0.5f, 1f), + tickLabels = !isTiny, + tickFormatter = y => f"$y%+.1f", + hoverFormatter = y => f"$y%+.2f", + flip = true) - override def points: (Array[Float], Array[Float]) = (wavePointsX, wavePointsY) + override def points: (Array[Float], Array[Float]) = (wavePointsX, wavePointsY) - override def setupContextMenu(menu: ContextMenu): Unit = { - addFFTSizeEntry(menu) - super.setupContextMenu(menu) + override def setupContextMenu(menu: ContextMenu): Unit = { + addFFTSizeEntry(menu) + super.setupContextMenu(menu) + } + + override def onPanelLeftClick(): Unit = updateMode(i => if (i == 1) 2 else 1) } - - override def onPanelLeftClick(): Unit = updateMode(i => if (i == 1) 2 else 1) } private val modes: List[() => Widget] = List( () => spectrumPlot(), () => wavePlot(), - () => new Widget { - children :+= spectrumPlot() - children :+= wavePlot() - } + () => { + new Widget { + children :+= spectrumPlot() + children :+= wavePlot() + } + }, ) private var modeIdx = 2 diff --git a/src/main/scala/ocelot/desktop/ui/widget/Plot.scala b/src/main/scala/ocelot/desktop/ui/widget/Plot.scala index c9eb711..e59aeaf 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Plot.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Plot.scala @@ -76,11 +76,14 @@ abstract class Plot extends Widget { } } - children :+= new PaddingBox(panel, Padding2D( - left = 4, - right = if (yAxis.ticks.isEmpty || !xAxis.tickLabels) 4 else yAxis.tickWidth * 7 + 6, - top = 4, - bottom = if (xAxis.ticks.isEmpty || !xAxis.tickLabels) 4 else 14) + children :+= new PaddingBox( + panel, + Padding2D( + left = 4, + right = if (yAxis.ticks.isEmpty || !xAxis.tickLabels) 4 else yAxis.tickWidth * 7 + 6, + top = 4, + bottom = if (xAxis.ticks.isEmpty || !xAxis.tickLabels) 4 else 14, + ), ) override def draw(g: Graphics): Unit = { @@ -209,8 +212,7 @@ object Plot { tickFormatter: Float => String = _.toString, tickLabels: Boolean = true, hoverFormatter: Float => String = _.toString, - unit: String = "") - { + unit: String = "") { lazy val tickWidth: Int = if (ticks.isEmpty || !tickLabels) 0 else ticks.map(tickFormatter(_).length).max def mapPos(pos: Float, size: Float): Float = { @@ -245,4 +247,4 @@ object Plot { } } } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/ScreenAspectRatioDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/ScreenAspectRatioDialog.scala index 39f81bf..09e9fc2 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/ScreenAspectRatioDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/ScreenAspectRatioDialog.scala @@ -21,7 +21,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { private def confirm(): Unit = { screenNode.screen.aspectRatio = ( typedWidth.get.toDouble, - typedHeight.get.toDouble + typedHeight.get.toDouble, ) close() @@ -38,8 +38,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { if (intValue >= 1 && intValue <= maxValue) result = Some(intValue) - } - catch { + } catch { case _: NumberFormatException => } @@ -52,7 +51,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { if (canConfirm) confirm() }, - Padding2D(bottom = 8) + Padding2D(bottom = 8), ) } @@ -61,7 +60,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { addInput( 8, () => typedWidth, - value => typedWidth = value + value => typedWidth = value, ) children :+= new Label("Height:") @@ -69,7 +68,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { addInput( 6, () => typedHeight, - value => typedHeight = value + value => typedHeight = value, ) children :+= new Widget { @@ -81,7 +80,7 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { override protected def clickSoundSource: ClickSoundSource = SoundSource.InterfaceClickLow override def onClick(): Unit = close() }, - Padding2D(right = 8) + Padding2D(right = 8), ) val confirmButton: Button = new Button { @@ -93,6 +92,6 @@ class ScreenAspectRatioDialog(screenNode: ScreenNode) extends ModalDialog { children :+= confirmButton } }, - Padding2D.equal(16) + Padding2D.equal(16), ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/ScrollView.scala b/src/main/scala/ocelot/desktop/ui/widget/ScrollView.scala index 5ee3405..9b03fd9 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/ScrollView.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/ScrollView.scala @@ -49,10 +49,11 @@ class ScrollView(val inner: Widget) extends Widget with Logging with HoverHandle val pos = UiHandler.mousePosition mouseOldPos = pos - dragging = + dragging = { if (vThumbBounds.contains(pos)) 1 else if (hThumbBounds.contains(pos)) 2 else 0 + } if (dragging == 1) { scrollToEnd = false diff --git a/src/main/scala/ocelot/desktop/ui/widget/Slider.scala b/src/main/scala/ocelot/desktop/ui/widget/Slider.scala index 68ed070..8e30473 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Slider.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Slider.scala @@ -12,9 +12,7 @@ import ocelot.desktop.ui.widget.traits.HoverAnimation import ocelot.desktop.util.DrawUtils class Slider(var value: Float, val text: String, val snapPoints: Int = 0) - extends Widget - with MouseHandler - with HoverAnimation { + extends Widget with MouseHandler with HoverAnimation { override protected val hoverAnimationColorDefault: Color = ColorScheme("SliderBackground") override protected val hoverAnimationColorActive: Color = ColorScheme("SliderBackgroundActive") @@ -99,7 +97,7 @@ class Slider(var value: Float, val text: String, val snapPoints: Int = 0) handleWidth, height, 2, - ColorScheme("SliderBorder") + ColorScheme("SliderBorder"), ) g.background = Color.Transparent diff --git a/src/main/scala/ocelot/desktop/ui/widget/Text.scala b/src/main/scala/ocelot/desktop/ui/widget/Text.scala index 8bdc475..ac0ac51 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Text.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Text.scala @@ -4,7 +4,7 @@ import ocelot.desktop.ColorScheme import ocelot.desktop.color.Color import ocelot.desktop.geometry.Size2D import ocelot.desktop.graphics.Graphics -import ocelot.desktop.ui.widget.Text.{CharHeight, getWidth, wrap} +import ocelot.desktop.ui.widget.Text.{getWidth, wrap, CharHeight} import ocelot.desktop.util.DrawUtils import totoro.ocelot.brain.util.FontUtils @@ -73,9 +73,11 @@ object Text { def wrap(text: String, wrapWidth: Option[Int]): ArrayBuffer[String] = { val lines = text.linesIterator - .flatMap(line => wrapWidth match { - case Some(wrapWidth) if getWidth(line) > wrapWidth => wrapLine(line, wrapWidth) - case _ => Some(line) + .flatMap(line => { + wrapWidth match { + case Some(wrapWidth) if getWidth(line) > wrapWidth => wrapLine(line, wrapWidth) + case _ => Some(line) + } }) .to(ArrayBuffer) diff --git a/src/main/scala/ocelot/desktop/ui/widget/TextInput.scala b/src/main/scala/ocelot/desktop/ui/widget/TextInput.scala index 52d2b90..7153bd0 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/TextInput.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/TextInput.scala @@ -67,31 +67,31 @@ class TextInput(val initialText: String = "") extends Widget with MouseHandler w focus() events += new CursorMoveTo(pos.x) - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_LEFT, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_LEFT, _) if isFocused => events += new CursorMoveLeft event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_RIGHT, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_RIGHT, _) if isFocused => events += new CursorMoveRight event.consume() - case event@KeyEvent(KeyEvent.State.Press, Keyboard.KEY_HOME, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press, Keyboard.KEY_HOME, _) if isFocused => events += new CursorMoveStart event.consume() - case event@KeyEvent(KeyEvent.State.Press, Keyboard.KEY_END, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press, Keyboard.KEY_END, _) if isFocused => events += new CursorMoveEnd event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_BACK, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_BACK, _) if isFocused => events += new EraseCharBack event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_DELETE, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_DELETE, _) if isFocused => events += new EraseCharFront event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_INSERT, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_INSERT, _) if isFocused => // TODO: insert the whole clipboard string at once instead of going char-by-char. for (char <- UiHandler.clipboard.toCharArray) { events += new WriteChar(char) @@ -99,8 +99,9 @@ class TextInput(val initialText: String = "") extends Widget with MouseHandler w event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_V, _) if isFocused - && KeyEvents.isControlDown => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, Keyboard.KEY_V, _) + if isFocused + && KeyEvents.isControlDown => // TODO: insert the whole clipboard string at once instead of going char-by-char. for (char <- UiHandler.clipboard.toCharArray) { @@ -109,11 +110,11 @@ class TextInput(val initialText: String = "") extends Widget with MouseHandler w event.consume() - case event@KeyEvent(KeyEvent.State.Press, Keyboard.KEY_RETURN, _) if isFocused => + case event @ KeyEvent(KeyEvent.State.Press, Keyboard.KEY_RETURN, _) if isFocused => onConfirm() event.consume() - case event@KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, _, char) if isFocused && !char.isControl => + case event @ KeyEvent(KeyEvent.State.Press | KeyEvent.State.Repeat, _, char) if isFocused && !char.isControl => events += new WriteChar(char) event.consume() } @@ -230,7 +231,7 @@ class TextInput(val initialText: String = "") extends Widget with MouseHandler w private def charWidth(g: Graphics, c: Char): Int = g.font.charWidth(c) - //noinspection SameParameterValue + // noinspection SameParameterValue private def charsWidth(g: Graphics, chars: Array[Char], first: Int, last: Int): Int = { var width = 0 for (index <- first to last) { diff --git a/src/main/scala/ocelot/desktop/ui/widget/TunnelDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/TunnelDialog.scala index afb1bae..e044fc4 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/TunnelDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/TunnelDialog.scala @@ -13,9 +13,8 @@ import java.util.UUID class TunnelDialog( onConfirmed: String => Unit, initialText: String = "", - inputValidator: String => Boolean = _ => true + inputValidator: String => Boolean = _ => true, ) extends ModalDialog { - private val input = new TextInput(initialText) { focus() override def minimumSize: Size2D = Size2D(350, 24) @@ -46,7 +45,8 @@ class TunnelDialog( tooltip = Some("Generate random channel name"), ) { override def onPressed(): Unit = input.text = UUID.randomUUID().toString - }, new Padding2D(left = 8, right = 8) + }, + new Padding2D(left = 8, right = 8), ) children :+= new IconButton( "icons/ButtonClipboard", @@ -76,10 +76,10 @@ class TunnelDialog( confirm() } }, - Padding2D(left = 8) + Padding2D(left = 8), ) } }, - Padding2D.equal(16) + Padding2D.equal(16), ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/Viewport3DWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/Viewport3DWidget.scala index 18b2c0e..58030b1 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/Viewport3DWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/Viewport3DWidget.scala @@ -62,20 +62,23 @@ abstract class Viewport3DWidget extends Widget with MouseHandler with HoverHandl override def maximumSize: Size2D = Size2D(viewportWidth + 4, viewportHeight + 4) - children :+= new PaddingBox(new Widget { - override def minimumSize: Size2D = Size2D(viewportWidth, viewportHeight) + children :+= new PaddingBox( + new Widget { + override def minimumSize: Size2D = Size2D(viewportWidth, viewportHeight) - override def maximumSize: Size2D = Size2D(viewportWidth, viewportHeight) + override def maximumSize: Size2D = Size2D(viewportWidth, viewportHeight) - override def draw(g: Graphics): Unit = { - DrawUtils.panel(g, bounds.x - 2, bounds.y - 2, bounds.w + 4, bounds.h + 4) + override def draw(g: Graphics): Unit = { + DrawUtils.panel(g, bounds.x - 2, bounds.y - 2, bounds.w + 4, bounds.h + 4) - if (!viewportDisposed) { - viewport.draw(scene) - g.blitViewport3D(viewport, bounds) + if (!viewportDisposed) { + viewport.draw(scene) + g.blitViewport3D(viewport, bounds) + } } - } - }, Padding2D.equal(2)) + }, + Padding2D.equal(2), + ) children :+= { val toolbar: Widget = new Widget { @@ -89,7 +92,8 @@ abstract class Viewport3DWidget extends Widget with MouseHandler with HoverHandl protected def setupToolbar(toolbar: Widget): Unit = { toolbar.children :+= new IconButton( - "icons/Home", "icons/Home", + "icons/Home", + "icons/Home", pressedColor = Color.White.withAlpha(0.5f), releasedColor = Color.White.withAlpha(0.2f), darkenActiveColorFactor = 0.5f, @@ -111,13 +115,13 @@ abstract class Viewport3DWidget extends Widget with MouseHandler with HoverHandl cameraFinalDistance = (if (offset > 0) cameraFinalDistance / ScrollSpeed else cameraFinalDistance * ScrollSpeed) .clamp(MinDistance, MaxDistance) - case event@DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left, _) if KeyEvents.isShiftDown => + case event @ DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left, _) if KeyEvents.isShiftDown => val basis = cameraFinalTransform.basis val movement = (basis.left * event.delta.x + basis.up * event.delta.y) * cameraFinalDistance * PanSpeed cameraCurrentTarget += movement cameraFinalTarget += movement - case event@DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left, _) => + case event @ DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left, _) => val basis = cameraFinalTransform.basis val xRotation = Quaternion.axisAngle(Vector3D.Up, -event.delta.x * RotateSpeed) val yRotation = Quaternion.axisAngle(basis.left, event.delta.y * RotateSpeed) diff --git a/src/main/scala/ocelot/desktop/ui/widget/WorkspaceView.scala b/src/main/scala/ocelot/desktop/ui/widget/WorkspaceView.scala index 2596aa4..2d7c4b1 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/WorkspaceView.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/WorkspaceView.scala @@ -31,6 +31,7 @@ import scala.jdk.CollectionConverters._ class WorkspaceView extends Widget with Persistable with MouseHandler with HoverHandler with Logging { @volatile var nodes: immutable.Seq[Node] = immutable.ArraySeq[Node]() + var windowPool = new WindowPool var nodeSelector = new NodeSelector var profilerWindow = new ProfilerWindow @@ -44,6 +45,7 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover override protected val layout: Layout = new CopyLayout(this) children +:= windowPool + children +:= new NoLayoutBox { override def hierarchy: ArraySeq[Widget] = ArraySeq.from(nodes) } @@ -81,7 +83,9 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover throw NodeLoadException(s"could not find an entity $address") } val constructor = findUnaryConstructor(clazz, entity.getClass).getOrElse { - throw NodeLoadException(s"the entity node cannot be instantiated with an argument of class ${entity.getClass.getName}") + throw NodeLoadException( + s"the entity node cannot be instantiated with an argument of class ${entity.getClass.getName}" + ) } constructor.newInstance(entity).asInstanceOf[EntityNode] @@ -107,11 +111,12 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover try { val clazz = Class.forName(clazzName) - val node = + val node = { if (classOf[EntityNode].isAssignableFrom(clazz)) loadEntityNode(clazz, nbt) else loadPlainNode(clazz) + } node.workspaceView = this node.root = _root @@ -134,25 +139,28 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover }) } - private def findNodeByAddress(nodes: Iterable[Node], address: String): Option[EntityNode] = + private def findNodeByAddress(nodes: Iterable[Node], address: String): Option[EntityNode] = { nodes .collect { case node: EntityNode => node } .find(_.entity match { - case sided: SidedEnvironment => Direction.values.exists(dir => sided.canConnect(dir) && sided.sidedNode(dir).address == address) + case sided: SidedEnvironment => + Direction.values.exists(dir => sided.canConnect(dir) && sided.sidedNode(dir).address == address) case env => env.node.address == address }) + } override def save(nbt: NBTTagCompound): Unit = { val cameraOffsetTag = new NBTTagCompound cameraOffset.save(cameraOffsetTag) nbt.setTag("cameraOffset", cameraOffsetTag) - nbt.setTagList("nodes", nodes.toList.map(node => { - val nbt = new NBTTagCompound - nbt.setString("class", node.getClass.getName) - node.save(nbt) - nbt: NBTBase - }).asJava) + nbt.setTagList("nodes", + nodes.toList.map(node => { + val nbt = new NBTTagCompound + nbt.setString("class", node.getClass.getName) + node.save(nbt) + nbt: NBTBase + }).asJava) val pairs = new mutable.HashSet[(Byte, String, Byte, String)] @@ -168,21 +176,25 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover } } - nbt.setTagList("connections", pairs.toList.map { case (byteA, addrA, byteB, addrB) => - val nbt = new NBTTagCompound - nbt.setByte("ap", byteA) - nbt.setString("a", addrA) - nbt.setByte("bp", byteB) - nbt.setString("b", addrB) - nbt: NBTBase - }.asJava) + nbt.setTagList( + "connections", + pairs.toList.map { case (byteA, addrA, byteB, addrB) => + val nbt = new NBTTagCompound + nbt.setByte("ap", byteA) + nbt.setString("a", addrA) + nbt.setByte("bp", byteB) + nbt.setString("b", addrB) + nbt: NBTBase + }.asJava, + ) } - private def getNode(environment: Environment, direction: Option[Direction.Value]) = + private def getNode(environment: Environment, direction: Option[Direction.Value]) = { environment match { case sided: SidedEnvironment => sided.sidedNode(direction.get) case env => env.node } + } def newWorkspace(): Unit = { reset() @@ -220,7 +232,7 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover node.fillSlotsWithDefaultItems() node }, - Vector2D(Size, Size) + Vector2D(Size, Size), ) addNode( @@ -229,7 +241,7 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover node.attachKeyboard() node }, - Vector2D(204, 136) + Vector2D(204, 136), ) nodes.head.connect(NodePort(), nodes(1), NodePort()) @@ -240,7 +252,7 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover override protected def receiveDragEvents: Boolean = true eventHandlers += { - case ev@DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left | MouseEvent.Button.Middle, _) => + case ev @ DragEvent(DragEvent.State.Drag, MouseEvent.Button.Left | MouseEvent.Button.Middle, _) => moveCameraOffset(ev.delta) case ClickEvent(MouseEvent.Button.Left | MouseEvent.Button.Right, pos) => @@ -342,11 +354,12 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover ((aSide, aCenter, aLen), (bSide, bCenter, bLen)) } - if (checkCollision) + if (checkCollision) { iter = iter.filter { case ((aSide, aCenter, aLen), (bSide, bCenter, bLen)) => checkConnectorCollision(aSide, aCenter, aLen) && - checkConnectorCollision(bSide, bCenter, bLen) + checkConnectorCollision(bSide, bCenter, bLen) } + } var paths = iter.map { case ((aSide, aCenter, aLen), (bSide, bCenter, bLen)) => val aEnd = aSide + (aSide - aCenter).normalizeAxisAligned * aLen @@ -354,10 +367,11 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover Array(aSide, aEnd, bEnd, bSide) }.filter(DrawUtils.isValidPolyline) - if (forceParallel) + if (forceParallel) { paths = paths.filter { case Array(aStart, aEnd, bEnd, bStart) => (aEnd - aStart).dot(bEnd - bStart) != 0f } + } paths } @@ -388,7 +402,8 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover } } - private def drawConnection(g: Graphics, aNode: Node, aPort: NodePort, bNode: Node, bPort: NodePort, color: Color): Unit = { + private def drawConnection(g: Graphics, aNode: Node, aPort: NodePort, bNode: Node, bPort: NodePort, color: Color) + : Unit = { val (aRect, bRect) = (aNode.bounds, bNode.bounds) if (aRect.collides(bRect)) return if (aRect.x < bRect.x) { @@ -443,11 +458,12 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover private def newConnectionTarget: Option[(Node, NodePort)] = { val (node, _, endpoint) = newConnection.get - val validTargets = + val validTargets = { nodes.iterator .filter(_ != node) .filter(_.bounds.inflate(20).contains(endpoint)) .filter(_.ports.nonEmpty) + } if (validTargets.nonEmpty) { val target = validTargets.minBy(n => (n.bounds.center - endpoint).lengthSquared) @@ -542,7 +558,8 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover nodeA.connections.foreach { case (portA, nodeB, portB) => if (!drawn.contains((nodeA, portA, nodeB, portB)) && !drawn.contains((nodeB, portB, nodeA, portA))) { val color = ColorScheme("Connection").toHSVA - val tint = (nodeA.getNodeByPort(portA).address + ":" + nodeB.getNodeByPort(portB).address).hashCode % 1000 / 1000f + val tint = + (nodeA.getNodeByPort(portA).address + ":" + nodeB.getNodeByPort(portB).address).hashCode % 1000 / 1000f val tinted = color.copy(v = color.v + tint * 0.1f) drawn += ((nodeA, portA, nodeB, portB)) drawConnection(g, nodeA, portA, nodeB, portB, color = tinted) @@ -571,8 +588,11 @@ class WorkspaceView extends Widget with Persistable with MouseHandler with Hover if (!nodeSelector.isClosed) { g.sprite( IconSource.Nodes.NewNode, - newNodePos.x + cameraOffset.x, newNodePos.y + cameraOffset.y, - 64, 64, color + newNodePos.x + cameraOffset.x, + newNodePos.y + cameraOffset.y, + 64, + 64, + color, ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/card/Redstone1Window.scala b/src/main/scala/ocelot/desktop/ui/widget/card/Redstone1Window.scala index 43c5f35..b8bc13b 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/card/Redstone1Window.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/card/Redstone1Window.scala @@ -25,17 +25,24 @@ class Redstone1Window(card: Redstone.Tier1) extends PanelWindow { override protected def titleMaxLength: Int = 26 - private def redstoneBlock(side: Direction.Value, name: String) = new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, Orientation.Horizontal, alignItems = AlignItems.Center) + private def redstoneBlock(side: Direction.Value, name: String) = new PaddingBox( + new Widget { + override protected val layout: Layout = + new LinearLayout(this, Orientation.Horizontal, alignItems = AlignItems.Center) - children :+= new PaddingBox(new Label { - override def text: String = name + children :+= new PaddingBox( + new Label { + override def text: String = name - override def maximumSize: Size2D = minimumSize - }, Padding2D(right = 8)) + override def maximumSize: Size2D = minimumSize + }, + Padding2D(right = 8), + ) - children :+= redstoneKnob(side) - }, Padding2D.equal(4)) + children :+= redstoneKnob(side) + }, + Padding2D.equal(4), + ) setInner(new Widget { children :+= new Widget { diff --git a/src/main/scala/ocelot/desktop/ui/widget/card/Redstone2Window.scala b/src/main/scala/ocelot/desktop/ui/widget/card/Redstone2Window.scala index dd2c42e..35ebd4e 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/card/Redstone2Window.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/card/Redstone2Window.scala @@ -25,40 +25,43 @@ class Redstone2Window(card: Redstone.Tier2) extends PanelWindow { override protected def titleMaxLength: Int = 36 - private def bundledBlock(side: Direction.Value, name: String) = new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, - orientation = Orientation.Vertical, alignItems = AlignItems.Center) + private def bundledBlock(side: Direction.Value, name: String) = new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, + orientation = Orientation.Vertical, alignItems = AlignItems.Center) - children :+= new Label { - override def text: String = name + children :+= new Label { + override def text: String = name - override def maximumSize: Size2D = minimumSize - } - children :+= new Widget { - children :+= bundledKnob(side, 0) - children :+= bundledKnob(side, 1) - children :+= bundledKnob(side, 2) - children :+= bundledKnob(side, 3) - } - children :+= new Widget { - children :+= bundledKnob(side, 4) - children :+= bundledKnob(side, 5) - children :+= bundledKnob(side, 6) - children :+= bundledKnob(side, 7) - } - children :+= new Widget { - children :+= bundledKnob(side, 8) - children :+= bundledKnob(side, 9) - children :+= bundledKnob(side, 10) - children :+= bundledKnob(side, 11) - } - children :+= new Widget { - children :+= bundledKnob(side, 12) - children :+= bundledKnob(side, 13) - children :+= bundledKnob(side, 14) - children :+= bundledKnob(side, 15) - } - }, Padding2D.equal(4)) + override def maximumSize: Size2D = minimumSize + } + children :+= new Widget { + children :+= bundledKnob(side, 0) + children :+= bundledKnob(side, 1) + children :+= bundledKnob(side, 2) + children :+= bundledKnob(side, 3) + } + children :+= new Widget { + children :+= bundledKnob(side, 4) + children :+= bundledKnob(side, 5) + children :+= bundledKnob(side, 6) + children :+= bundledKnob(side, 7) + } + children :+= new Widget { + children :+= bundledKnob(side, 8) + children :+= bundledKnob(side, 9) + children :+= bundledKnob(side, 10) + children :+= bundledKnob(side, 11) + } + children :+= new Widget { + children :+= bundledKnob(side, 12) + children :+= bundledKnob(side, 13) + children :+= bundledKnob(side, 14) + children :+= bundledKnob(side, 15) + } + }, + Padding2D.equal(4), + ) setInner(new Widget { children :+= new Widget { diff --git a/src/main/scala/ocelot/desktop/ui/widget/card/SoundCardWindow.scala b/src/main/scala/ocelot/desktop/ui/widget/card/SoundCardWindow.scala index 0728f34..956b2cf 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/card/SoundCardWindow.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/card/SoundCardWindow.scala @@ -23,6 +23,7 @@ class SoundCardWindow(card: SoundCard) extends PanelWindow { private var passedTime = 0 private val masterOscilloscope = new Oscilloscope + private val channelOscilloscopes = Array.fill(numChannels) { new Oscilloscope(isTiny = true) } @@ -43,19 +44,22 @@ class SoundCardWindow(card: SoundCard) extends PanelWindow { override protected def titleMaxLength: Int = 80 - setInner(new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + setInner( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= new PaddingBox(masterOscilloscope, Padding2D(left = 4, right = 4)) + children :+= new PaddingBox(masterOscilloscope, Padding2D(left = 4, right = 4)) - for (i <- 0 until numChannels / 2) { - children :+= new Widget { - children :+= channelWidgets(2 * i) - children :+= patchbays(i) - children :+= channelWidgets(2 * i + 1) + for (i <- 0 until numChannels / 2) { + children :+= new Widget { + children :+= channelWidgets(2 * i) + children :+= patchbays(i) + children :+= channelWidgets(2 * i + 1) + } } - } - }, padding = Padding2D(left = 4, right = 4, bottom = 8)) + }, + padding = Padding2D(left = 4, right = 4, bottom = 8), + ) private def numChannels: Int = process.channels.length @@ -332,75 +336,78 @@ object SoundCardWindow { lastEvent = System.nanoTime() } - children :+= new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= oscilloscope + children :+= oscilloscope - children :+= new Widget { - override def minimumSize: Size2D = Size2D(300, 50) + children :+= new Widget { + override def minimumSize: Size2D = Size2D(300, 50) - override def draw(g: Graphics): Unit = { - for (((icon, clazz), i) <- waves.zipWithIndex) { - val active = clazz.isInstance(channel.generator) - val color = if (active) ColorScheme("SoundCardWaveActive") else ColorScheme("SoundCardWaveOff") - g.sprite(icon, position.x + 24 * i + 2, position.y + 4, color) - } - - var text = "" - g.setSmallFont() - g.foreground = ColorScheme("Label") - - val note = freqToNote(channel.frequency) - text = if (note.isDefined) { - f"Freq: ${channel.frequency}%.1f (${note.get})" - } else { - f"Freq: ${channel.frequency}%.1f" - } - g.text(position.x + 1, position.y + 22, text, shrink = 1) - - text = f"Vol: ${channel.volume}%.2f (${magToDb(channel.volume)}%.1fdB)" - g.text(position.x + 1, position.y + 32, text, shrink = 1) - - text = f"Pos: ${channel.offset}%.4f" - g.text(position.x + 1, position.y + 42, text, shrink = 1) - - if (channel.envelope.isEmpty) { - text = if (channel.isOpen) "Open" else "Closed" - g.text(position.x + width / 2, position.y + 22, text, shrink = 1) - - text = "No envelope" - g.text(position.x + width / 2 + 1, position.y + 32, text, shrink = 1) - } - - for (env <- channel.envelope) { - drawEnvelope(g, env, Rect2D(position.x + width / 2 + 2, position.y + 2, width / 2 - 4, 16), - (System.nanoTime() - lastEvent) / 1e6f) + override def draw(g: Graphics): Unit = { + for (((icon, clazz), i) <- waves.zipWithIndex) { + val active = clazz.isInstance(channel.generator) + val color = if (active) ColorScheme("SoundCardWaveActive") else ColorScheme("SoundCardWaveOff") + g.sprite(icon, position.x + 24 * i + 2, position.y + 4, color) + } + var text = "" + g.setSmallFont() g.foreground = ColorScheme("Label") - text = f"A: ${env.attack / 1000f}%.3f" - g.text(position.x + width / 2 + 1, position.y + 22, text, shrink = 1) + val note = freqToNote(channel.frequency) + text = if (note.isDefined) { + f"Freq: ${channel.frequency}%.1f (${note.get})" + } else { + f"Freq: ${channel.frequency}%.1f" + } + g.text(position.x + 1, position.y + 22, text, shrink = 1) - text = f"D: ${env.decay / 1000f}%.3f" - g.text(position.x + width / 2 + 70, position.y + 22, text, shrink = 1) + text = f"Vol: ${channel.volume}%.2f (${magToDb(channel.volume)}%.1fdB)" + g.text(position.x + 1, position.y + 32, text, shrink = 1) - text = f"S: ${env.sustain}%.3f" - g.text(position.x + width / 2 + 1, position.y + 32, text, shrink = 1) + text = f"Pos: ${channel.offset}%.4f" + g.text(position.x + 1, position.y + 42, text, shrink = 1) - text = f"R: ${env.release / 1000f}%.3f" - g.text(position.x + width / 2 + 70, position.y + 32, text, shrink = 1) + if (channel.envelope.isEmpty) { + text = if (channel.isOpen) "Open" else "Closed" + g.text(position.x + width / 2, position.y + 22, text, shrink = 1) + + text = "No envelope" + g.text(position.x + width / 2 + 1, position.y + 32, text, shrink = 1) + } + + for (env <- channel.envelope) { + drawEnvelope(g, env, Rect2D(position.x + width / 2 + 2, position.y + 2, width / 2 - 4, 16), + (System.nanoTime() - lastEvent) / 1e6f) + + g.foreground = ColorScheme("Label") + + text = f"A: ${env.attack / 1000f}%.3f" + g.text(position.x + width / 2 + 1, position.y + 22, text, shrink = 1) + + text = f"D: ${env.decay / 1000f}%.3f" + g.text(position.x + width / 2 + 70, position.y + 22, text, shrink = 1) + + text = f"S: ${env.sustain}%.3f" + g.text(position.x + width / 2 + 1, position.y + 32, text, shrink = 1) + + text = f"R: ${env.release / 1000f}%.3f" + g.text(position.x + width / 2 + 70, position.y + 32, text, shrink = 1) + } + + for (fm <- channel.frequencyMod) { + text = f"FM depth: ${fm.depth}%.1f" + g.text(position.x + width / 2 + 1, position.y + 42, text, shrink = 1) + } + + g.setNormalFont() } - - for (fm <- channel.frequencyMod) { - text = f"FM depth: ${fm.depth}%.1f" - g.text(position.x + width / 2 + 1, position.y + 42, text, shrink = 1) - } - - g.setNormalFont() } - } - }, Padding2D.equal(4)) + }, + Padding2D.equal(4), + ) } private class Patchbay(leftIdx: Int, rightIdx: Int, isFirst: Boolean, isLast: Boolean) extends Widget { @@ -492,4 +499,4 @@ object SoundCardWindow { } private case class Connector(column: Int, colorIdx: Int, from: Float, to: Float) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenu.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenu.scala index 3dd2efb..0157248 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenu.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenu.scala @@ -17,6 +17,7 @@ class ContextMenu extends Widget { protected var _contextMenus: ContextMenus = _ protected val alpha = new ValueAnimation(0f, 8f) + protected val inner: Widget = new Widget { override protected val layout = new LinearLayout(this, orientation = Orientation.Vertical) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuEntry.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuEntry.scala index 30d889c..459c324 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuEntry.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuEntry.scala @@ -17,10 +17,8 @@ class ContextMenuEntry( icon: Option[ContextMenuIcon] = None, onClick: () => Unit = () => {}, sound: ClickSoundSource = SoundSource.InterfaceClick, - soundDisabled: ClickSoundSource = SoundSource.InterfaceClickLow -) extends Widget - with MouseHandler - with HoverHandler { + soundDisabled: ClickSoundSource = SoundSource.InterfaceClickLow, +) extends Widget with MouseHandler with HoverHandler { private[contextmenu] val alpha = new ValueAnimation(0f, 10f) private[contextmenu] val textAlpha = new ValueAnimation(0f, 5f) @@ -50,7 +48,7 @@ class ContextMenuEntry( case _ => Size2D(32, 32) } }, - Padding2D(left = 8f, right = 8f) + Padding2D(left = 8f, right = 8f), ) case _ => } @@ -60,9 +58,10 @@ class ContextMenuEntry( override def text: String = label override def color: Color = ColorScheme("ContextMenuText") }, - Padding2D(top = 5f, bottom = 5f) + Padding2D(top = 5f, bottom = 5f), ) - }, Padding2D(left = padLeft, right = 16f, top = 2f, bottom = 2f) + }, + Padding2D(left = padLeft, right = 16f, top = 2f, bottom = 2f), ) override def receiveMouseEvents: Boolean = !isGhost @@ -137,42 +136,46 @@ class ContextMenuEntry( object ContextMenuEntry { def apply( label: String, - icon: Option[ContextMenuIcon] = None - )(onClick: => Unit): ContextMenuEntry = + icon: Option[ContextMenuIcon] = None, + )(onClick: => Unit): ContextMenuEntry = { new ContextMenuEntry( label, onClick = onClick _, - icon = icon + icon = icon, ) + } def apply( - label: String - )(onClick: => Unit): ContextMenuEntry = + label: String + )(onClick: => Unit): ContextMenuEntry = { new ContextMenuEntry( label, onClick = onClick _, - icon = None + icon = None, ) + } def apply( label: String, - icon: IconSource - )(onClick: => Unit): ContextMenuEntry = + icon: IconSource, + )(onClick: => Unit): ContextMenuEntry = { new ContextMenuEntry( label, Some(ContextMenuIcon(icon)), onClick = onClick _, ) + } def apply( - label: String, - icon: IconSource, - sound: ClickSoundSource - )(onClick: => Unit): ContextMenuEntry = + label: String, + icon: IconSource, + sound: ClickSoundSource, + )(onClick: => Unit): ContextMenuEntry = { new ContextMenuEntry( label, Some(ContextMenuIcon(icon)), sound = sound, - onClick = onClick _ + onClick = onClick _, ) + } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIcon.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIcon.scala index f91e876..a8a962e 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIcon.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIcon.scala @@ -4,7 +4,7 @@ import ocelot.desktop.color.Color import ocelot.desktop.graphics.IconSource case class ContextMenuIcon( - source: IconSource, - size: ContextMenuIconSize.Value = ContextMenuIconSize.Normal, - color: Option[Color] = None + source: IconSource, + size: ContextMenuIconSize.Value = ContextMenuIconSize.Normal, + color: Option[Color] = None, ) diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIconSize.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIconSize.scala index 68bcf1f..7168d81 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIconSize.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuIconSize.scala @@ -2,4 +2,4 @@ package ocelot.desktop.ui.widget.contextmenu object ContextMenuIconSize extends Enumeration { val Normal, Big = Value -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuSubmenu.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuSubmenu.scala index 2625b62..9f1e842 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuSubmenu.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenuSubmenu.scala @@ -11,18 +11,20 @@ class ContextMenuSubmenu( label: String, icon: Option[ContextMenuIcon] = None, onClick: () => Unit = () => {}, -) -extends ContextMenuEntry( - label + " ", - icon, - onClick -) { +) extends ContextMenuEntry( + label + " ", + icon, + onClick, + ) { private val parentEntry = this + private val submenu = new ContextMenu { override def update(): Unit = { super.update() - if (!isClosing && !bounds.inflate(4).contains(UiHandler.mousePosition) - && !parentEntry.isHovered) close() + if ( + !isClosing && !bounds.inflate(4).contains(UiHandler.mousePosition) + && !parentEntry.isHovered + ) close() } } @@ -59,4 +61,4 @@ extends ContextMenuEntry( contextMenus.open(submenu, position + Vector2D(width, -4), position.x, position.y + height + 4, isSubmenu = true) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenus.scala b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenus.scala index 214723d..88ead9d 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenus.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/contextmenu/ContextMenus.scala @@ -33,8 +33,7 @@ class ContextMenus extends Widget { def open(menu: ContextMenu, openPos: Vector2D = UiHandler.mousePosition, - isSubmenu: Boolean = false): Unit = - { + isSubmenu: Boolean = false): Unit = { open(menu, openPos, openPos.x, openPos.y, isSubmenu) } @@ -42,8 +41,7 @@ class ContextMenus extends Widget { openPos: Vector2D, xFlipPos: Float, yFlipPos: Float, - isSubmenu: Boolean): Unit = - { + isSubmenu: Boolean): Unit = { if (children.contains(menu)) return if (menu.entries.isEmpty) return if (!isSubmenu) for (child <- menus) close(child) diff --git a/src/main/scala/ocelot/desktop/ui/widget/help/AboutDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/help/AboutDialog.scala index efde0c4..3b4d364 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/help/AboutDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/help/AboutDialog.scala @@ -31,49 +31,50 @@ class AboutDialog extends ModalDialog { } children :+= logo - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 8) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 8) - children :++= Seq( - new PaddingBox(AboutLabel("OCELOT DESKTOP"), Padding2D(top = 32)), - new PaddingBox(AboutLabel(" OpenComputers Emulator", isSmall = true), Padding2D(bottom = 16)), + children :++= Seq( + new PaddingBox(AboutLabel("OCELOT DESKTOP"), Padding2D(top = 32)), + new PaddingBox(AboutLabel(" OpenComputers Emulator", isSmall = true), Padding2D(bottom = 16)), + AboutLabel(s"Version: ${BuildInfo.version}"), + new PaddingBox(AboutLabel(s" (${BuildInfo.commit.take(7)})", isSmall = true), Padding2D(bottom = 16)), + AboutLabel(s"MIT License (c) ${Year.now.getValue} Ocelot Dev Team"), + AboutLabel(" OpenComputers (C) 2013-2015, MIT, Florian \"Sangar\" Nücke", isSmall = true), + AboutLabel(" MineOS (C) 2022, Dungeon MIT License, ECS", isSmall = true), + AboutLabel(" Advanced Loader (C) 2018, MIT, Luca_S", isSmall = true), + AboutLabel(" Unifont (C) 2007, SIL OFL 1.1, Roman Czyborra", isSmall = true), + AboutLabel(" Unscii (Public Domain) by viznut", isSmall = true), + AboutLabel(" wcwidth (C) 2005-2020, MIT, Rich Felker, et al.", isSmall = true), + AboutLabel(" JNLua (C) 2008-2012, MIT, Andre Naef", isSmall = true), + AboutLabel(" LuaJ (C) 2007, MIT, Luaj.org", isSmall = true), + AboutLabel(" Typesafe Config (C) 2011-2012, Apache License 2.0, Typesafe Inc.", isSmall = true), + AboutLabel(" LWJGL2 (C) 2002-2007, BSD, Lightweight Java Game Library Project", isSmall = true), + ) - AboutLabel(s"Version: ${BuildInfo.version}"), - new PaddingBox(AboutLabel(s" (${BuildInfo.commit.take(7)})", isSmall = true), Padding2D(bottom = 16)), + children :+= new Filler - AboutLabel(s"MIT License (c) ${Year.now.getValue} Ocelot Dev Team"), - AboutLabel(" OpenComputers (C) 2013-2015, MIT, Florian \"Sangar\" Nücke", isSmall = true), - AboutLabel(" MineOS (C) 2022, Dungeon MIT License, ECS", isSmall = true), - AboutLabel(" Advanced Loader (C) 2018, MIT, Luca_S", isSmall = true), - AboutLabel(" Unifont (C) 2007, SIL OFL 1.1, Roman Czyborra", isSmall = true), - AboutLabel(" Unscii (Public Domain) by viznut", isSmall = true), - AboutLabel(" wcwidth (C) 2005-2020, MIT, Rich Felker, et al.", isSmall = true), - AboutLabel(" JNLua (C) 2008-2012, MIT, Andre Naef", isSmall = true), - AboutLabel(" LuaJ (C) 2007, MIT, Luaj.org", isSmall = true), - AboutLabel(" Typesafe Config (C) 2011-2012, Apache License 2.0, Typesafe Inc.", isSmall = true), - AboutLabel(" LWJGL2 (C) 2002-2007, BSD, Lightweight Java Game Library Project", isSmall = true), - ) + children :+= new Widget { + children :+= new Filler { + override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1) + } - children :+= new Filler + if (Desktop.isDesktopSupported) { + children :+= new PaddingBox(new AboutButton("Website", WebsiteURL), Padding2D(right = 8)) + children :+= new PaddingBox(new AboutButton("IRC", IrcURL), Padding2D(right = 8)) + children :+= new PaddingBox(new AboutButton("Discord", DiscordURL), Padding2D(right = 20)) + } - children :+= new Widget { - children :+= new Filler { - override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1) + children :+= new Button { + override def text: String = "Ok" + override def onClick(): Unit = close() + override protected def colorScheme: ColorScheme = customButtonColorScheme + } } - - if (Desktop.isDesktopSupported) { - children :+= new PaddingBox(new AboutButton("Website", WebsiteURL), Padding2D(right = 8)) - children :+= new PaddingBox(new AboutButton("IRC", IrcURL), Padding2D(right = 8)) - children :+= new PaddingBox(new AboutButton("Discord", DiscordURL), Padding2D(right = 20)) - } - - children :+= new Button { - override def text: String = "Ok" - override def onClick(): Unit = close() - override protected def colorScheme: ColorScheme = customButtonColorScheme - } - } - }, Padding2D.equal(18)) + }, + Padding2D.equal(18), + ) override def draw(g: Graphics): Unit = { g.rect(bounds.x, bounds.y, logo.bounds.w, bounds.h, ColorScheme("Accent")) @@ -81,7 +82,7 @@ class AboutDialog extends ModalDialog { } } - protected override def drawInner(g: Graphics): Unit = { + override protected def drawInner(g: Graphics): Unit = { DrawUtils.shadow(g, bounds.x - 8, bounds.y - 8, bounds.w + 16, bounds.h + 20, 0.5f) g.rect(bounds, ColorScheme("ContextMenuBackground")) DrawUtils.ring(g, bounds.x, bounds.y, bounds.w, bounds.h, 1, ColorScheme("ContextMenuBorder")) diff --git a/src/main/scala/ocelot/desktop/ui/widget/help/UpdateCheckerDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/help/UpdateCheckerDialog.scala index 99f9169..2dd31b8 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/help/UpdateCheckerDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/help/UpdateCheckerDialog.scala @@ -24,25 +24,30 @@ class UpdateCheckerDialog extends ModalDialog with Logging { override protected val layout: Layout = new LinearLayout(this, orientation = Vertical) } - children :+= new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Vertical, gap = 16) + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Vertical, gap = 16) - children :+= container + children :+= container - children :+= new Widget { - children :+= new Filler { - override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1) + children :+= new Widget { + children :+= new Filler { + override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 1) + } + children :+= new Button { + override def text: String = "Ok" + override def onClick(): Unit = close() + } } - children :+= new Button { - override def text: String = "Ok" - override def onClick(): Unit = close() - } - } - }, Padding2D.equal(16)) + }, + Padding2D.equal(16), + ) // loading screen container.children :+= new Label("Checking development news...") - container.children :+= new PaddingBox(new Icon(IconSource.Loading, color = ColorScheme("Label")), Padding2D(16, 0, 0, 90)) + + container.children :+= new PaddingBox(new Icon(IconSource.Loading, color = ColorScheme("Label")), + Padding2D(16, 0, 0, 90)) // check the API OcelotOnlineAPI.checkRemoteVersion { @@ -54,15 +59,20 @@ class UpdateCheckerDialog extends ModalDialog with Logging { if (newReleaseVersion == BuildInfo.version) { container.children :+= new PaddingBox(new Label("Up to date!", small = true), Padding2D(6)) } else { - container.children :+= new PaddingBox(new Label("New release version is available:", small = true), Padding2D(6)) + container.children :+= new PaddingBox(new Label("New release version is available:", small = true), + Padding2D(6)) if (Desktop.isDesktopSupported) { - container.children :+= new PaddingBox(new Button { - override def text: String = "Download" + container.children :+= new PaddingBox( + new Button { + override def text: String = "Download" - override def onClick(): Unit = Desktop.getDesktop.browse(new URI("https://ocelot.fomalhaut.me/desktop")) - }, Padding2D(6)) + override def onClick(): Unit = Desktop.getDesktop.browse(new URI("https://ocelot.fomalhaut.me/desktop")) + }, + Padding2D(6), + ) } else { - container.children :+= new PaddingBox(new Label("https://ocelot.fomalhaut.me/desktop", small = true), Padding2D(6)) + container.children :+= new PaddingBox(new Label("https://ocelot.fomalhaut.me/desktop", small = true), + Padding2D(6)) } } } else { @@ -80,16 +90,24 @@ class UpdateCheckerDialog extends ModalDialog with Logging { container.children :+= new PaddingBox(new Label("Up to date!", small = true), Padding2D(6)) } else { container.children :+= new PaddingBox( - new Label(s"New dev build from ${version.devDate.get.withZoneSameInstant(ZoneId.systemDefault()).format(dateFormat)}:", small = true) - , Padding2D(4)) + new Label( + s"New dev build from ${version.devDate.get.withZoneSameInstant(ZoneId.systemDefault()).format(dateFormat)}:", + small = true, + ), + Padding2D(4), + ) if (Desktop.isDesktopSupported) { - container.children :+= new PaddingBox(new Button { - override def text: String = "Download" + container.children :+= new PaddingBox( + new Button { + override def text: String = "Download" - override def onClick(): Unit = Desktop.getDesktop.browse(new URI("https://ocelot.fomalhaut.me/desktop")) - }, Padding2D(6)) + override def onClick(): Unit = Desktop.getDesktop.browse(new URI("https://ocelot.fomalhaut.me/desktop")) + }, + Padding2D(6), + ) } else { - container.children :+= new PaddingBox(new Label("https://ocelot.fomalhaut.me/desktop", small = true), Padding2D(6)) + container.children :+= new PaddingBox(new Label("https://ocelot.fomalhaut.me/desktop", small = true), + Padding2D(6)) } } } else { @@ -101,8 +119,10 @@ class UpdateCheckerDialog extends ModalDialog with Logging { val message = "Ocelot website is unavailable...\n" + s"($exception)\n" + "Check the log file for a full stacktrace." - setContainerChildren(ArraySeq.unsafeWrapArray(message.split('\n').map(line => new Label { - override def text: String = line + setContainerChildren(ArraySeq.unsafeWrapArray(message.split('\n').map(line => { + new Label { + override def text: String = line + } }))) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationDialog.scala index e08d60e..5736d83 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationDialog.scala @@ -10,7 +10,8 @@ import ocelot.desktop.ui.widget.modal.ModalDialog import ocelot.desktop.ui.widget.modal.notification.NotificationType.NotificationType import ocelot.desktop.util.{DrawUtils, Orientation} -class NotificationDialog(message: String, notificationType: NotificationType = NotificationType.Warning) extends ModalDialog { +class NotificationDialog(message: String, notificationType: NotificationType = NotificationType.Warning) + extends ModalDialog { private val buttonsLayout: Widget = new Widget { override val layout: LinearLayout = new LinearLayout(this, gap = 15) @@ -31,7 +32,7 @@ class NotificationDialog(message: String, notificationType: NotificationType = N // Icon children :+= new PaddingBox( new Icon(IconSource.Notification(notificationType), Size2D(22, 22)), - Padding2D.equal(10) + Padding2D.equal(10), ) children :+= new Filler @@ -48,10 +49,12 @@ class NotificationDialog(message: String, notificationType: NotificationType = N override val layout: LinearLayout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 5) - children :++= message.split('\n').map(line => new Label { - override def text: String = line + children :++= message.split('\n').map(line => { + new Label { + override def text: String = line - override def color: Color = ColorScheme("ContextMenuText") + override def color: Color = ColorScheme("ContextMenuText") + } }) } @@ -62,10 +65,10 @@ class NotificationDialog(message: String, notificationType: NotificationType = N children :+= buttonsLayout } }, - Padding2D.equal(15) + Padding2D.equal(15), ) - protected override def drawInner(g: Graphics): Unit = { + override protected def drawInner(g: Graphics): Unit = { DrawUtils.shadow(g, bounds.x - 8, bounds.y - 8, bounds.w + 16, bounds.h + 20, 0.5f) g.rect(bounds, ColorScheme("ContextMenuBackground")) DrawUtils.ring(g, bounds.x, bounds.y, bounds.w, bounds.h, 1, ColorScheme("ContextMenuBorder")) diff --git a/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationType.scala b/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationType.scala index 025ed42..2490803 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationType.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/modal/notification/NotificationType.scala @@ -4,4 +4,4 @@ object NotificationType extends Enumeration { type NotificationType = Value val Error, Warning, Info = Value -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsDialog.scala b/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsDialog.scala index 8445df6..7d71513 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsDialog.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsDialog.scala @@ -12,10 +12,11 @@ import ocelot.desktop.util.{Orientation, SettingsData} class SettingsDialog extends ModalDialog { private val settingsBackup = new SettingsData(Settings.get) + private val tabs = Seq( new UISettingsTab, new SoundSettingsTab, - new SystemSettingsTab + new SystemSettingsTab, ) private def resetSettings(): Unit = { @@ -44,35 +45,42 @@ class SettingsDialog extends ModalDialog { } } - children :+= new PaddingBox(new Button { - override def text: String = "Ok" + children :+= new PaddingBox( + new Button { + override def text: String = "Ok" - override def onClick(): Unit = close() - }, Padding2D(left = 8)) + override def onClick(): Unit = close() + }, + Padding2D(left = 8), + ) } } - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) - children :+= new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= tabs.foldLeft(new VerticalMenu())((menu, tab) => - menu.addEntry(new VerticalMenuButton(tab.icon, tab.label, self => { - container.children = tab +: container.children.tail - menu.entries.foreach(_.selected = false) - self.selected = true - })) - ) - children.head.asInstanceOf[VerticalMenu].entries.head.selected = true - } + children :+= tabs.foldLeft(new VerticalMenu())((menu, tab) => { + menu.addEntry(new VerticalMenuButton(tab.icon, tab.label, + self => { + container.children = tab +: container.children.tail + menu.entries.foreach(_.selected = false) + self.selected = true + })) + }) + children.head.asInstanceOf[VerticalMenu].entries.head.selected = true + } - children :+= new PaddingBox(container, Padding2D(left = 8)) + children :+= new PaddingBox(container, Padding2D(left = 8)) - override def draw(g: Graphics): Unit = { - g.rect(bounds.x + children.head.bounds.w - 2f, bounds.y, 2f, bounds.h, ColorScheme("VerticalMenuBorder")) - super.draw(g) - } - }, Padding2D.equal(16)) + override def draw(g: Graphics): Unit = { + g.rect(bounds.x + children.head.bounds.w - 2f, bounds.y, 2f, bounds.h, ColorScheme("VerticalMenuBorder")) + super.draw(g) + } + }, + Padding2D.equal(16), + ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsTab.scala b/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsTab.scala index e509e29..ab80c6e 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsTab.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/settings/SettingsTab.scala @@ -11,8 +11,7 @@ trait SettingsTab extends Widget { val icon: IconSource val label: String - /** - * Callback that will be called by the parent Settings dialog when settings were changed + /** Callback that will be called by the parent Settings dialog when settings were changed * from outside the tab (for example user pressed "Cancel" and they were reset). * Apply necessary immediate actions here. * (Like adjusting volume for sound resources in case of Sound settings.) diff --git a/src/main/scala/ocelot/desktop/ui/widget/settings/SoundSettingsTab.scala b/src/main/scala/ocelot/desktop/ui/widget/settings/SoundSettingsTab.scala index 3422b26..798fc4e 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/settings/SoundSettingsTab.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/settings/SoundSettingsTab.scala @@ -27,31 +27,31 @@ class SoundSettingsTab extends SettingsTab { addSlider( "Master volume", Settings.get.volumeMaster, - Settings.get.volumeMaster = _ + Settings.get.volumeMaster = _, ) addSlider( "Music blocks volume", Settings.get.volumeRecords, - Settings.get.volumeRecords = _ + Settings.get.volumeRecords = _, ) addSlider( "Environment volume", Settings.get.volumeEnvironment, - Settings.get.volumeEnvironment = _ + Settings.get.volumeEnvironment = _, ) addSlider( "Beep volume", Settings.get.volumeBeep, - Settings.get.volumeBeep = _ + Settings.get.volumeBeep = _, ) addSlider( "Interface volume", Settings.get.volumeInterface, - Settings.get.volumeInterface = _ + Settings.get.volumeInterface = _, ) children :+= new Checkbox("Use positional sound", Settings.get.soundPositional) { diff --git a/src/main/scala/ocelot/desktop/ui/widget/settings/SystemSettingsTab.scala b/src/main/scala/ocelot/desktop/ui/widget/settings/SystemSettingsTab.scala index 0b0f073..ae7941a 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/settings/SystemSettingsTab.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/settings/SystemSettingsTab.scala @@ -36,32 +36,36 @@ class SystemSettingsTab extends SettingsTab with Logging { } } - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) - children :+= new PaddingBox(textInput, Padding2D(right = 8)) + children :+= new PaddingBox(textInput, Padding2D(right = 8)) - children :+= new IconButton( - "icons/Folder", - "icons/Folder", - releasedColor = ColorScheme("ButtonForeground"), - pressedColor = ColorScheme("ButtonForegroundPressed"), - drawBackground = true, - padding = 3.5f, - tooltip = Some("Search for OpenComputers configuration file"), - ) { - override def onPressed(): Unit = { - OcelotDesktop.showFileChooserDialog(JFileChooser.OPEN_DIALOG, JFileChooser.FILES_ONLY) { - case Some(dir) => - setConfigPath(dir.getCanonicalPath) - Success(()) - case None => Success(()) + children :+= new IconButton( + "icons/Folder", + "icons/Folder", + releasedColor = ColorScheme("ButtonForeground"), + pressedColor = ColorScheme("ButtonForegroundPressed"), + drawBackground = true, + padding = 3.5f, + tooltip = Some("Search for OpenComputers configuration file"), + ) { + override def onPressed(): Unit = { + OcelotDesktop.showFileChooserDialog(JFileChooser.OPEN_DIALOG, JFileChooser.FILES_ONLY) { + case Some(dir) => + setConfigPath(dir.getCanonicalPath) + Success(()) + case None => Success(()) + } } } - } - }, Padding2D(bottom = 4)) + }, + Padding2D(bottom = 4), + ) - children :+= new PaddingBox(new Label("Generate new OpenComputers configuration file in:"), Padding2D(top = 8, bottom = 8)) + children :+= new PaddingBox(new Label("Generate new OpenComputers configuration file in:"), + Padding2D(top = 8, bottom = 8)) children :+= new Widget { children :+= new Button(new LabelTooltip(new File(OcelotPaths.openComputersConfigName).getCanonicalPath)) { @@ -70,47 +74,60 @@ class SystemSettingsTab extends SettingsTab with Logging { unpackConfig(new File(OcelotPaths.openComputersConfigName)) } } - children :+= new PaddingBox(new Button(new LabelTooltip(OcelotPaths.openComputersConfig.toString)) { - override def text: String = "Config Directory" - override def onClick(): Unit = { - unpackConfig(OcelotPaths.openComputersConfig.toFile) - } - }, Padding2D(left = 8)) - children :+= new PaddingBox(new Button(new LabelTooltip("...")) { - override def text: String = "Custom Path" - override def onClick(): Unit = { - OcelotDesktop.showFileChooserDialog(JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY) { - case Some(file) => - unpackConfig(file) - Success(()) - case None => Success(()) + children :+= new PaddingBox( + new Button(new LabelTooltip(OcelotPaths.openComputersConfig.toString)) { + override def text: String = "Config Directory" + override def onClick(): Unit = { + unpackConfig(OcelotPaths.openComputersConfig.toFile) } - } - }, Padding2D(left = 8)) + }, + Padding2D(left = 8), + ) + children :+= new PaddingBox( + new Button(new LabelTooltip("...")) { + override def text: String = "Custom Path" + override def onClick(): Unit = { + OcelotDesktop.showFileChooserDialog(JFileChooser.SAVE_DIALOG, JFileChooser.FILES_ONLY) { + case Some(file) => + unpackConfig(file) + Success(()) + case None => Success(()) + } + } + }, + Padding2D(left = 8), + ) } - children :+= new PaddingBox(new Checkbox("Workspace autosave", Settings.get.autosave) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Workspace autosave", Settings.get.autosave) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.autosave = value - applySettings() - } - }, Padding2D(top = 16)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.autosave = value + applySettings() + } + }, + Padding2D(top = 16), + ) - children :+= new PaddingBox(new Widget { - children :+= new PaddingBox(new Label("Workspace autosave period (seconds):"), Padding2D(top = 4, right = 8)) + children :+= new PaddingBox( + new Widget { + children :+= new PaddingBox(new Label("Workspace autosave period (seconds):"), Padding2D(top = 4, right = 8)) - children :+= new TextInput(Settings.get.autosavePeriod.toString) { - override def onInput(text: String): Unit = { - try { - Settings.get.autosavePeriod = text.toInt - } catch { - case _: NumberFormatException => logger.warn(s"Trying to set a non-number value ($text) to the `autosavePeriod` setting!"); + children :+= new TextInput(Settings.get.autosavePeriod.toString) { + override def onInput(text: String): Unit = { + try { + Settings.get.autosavePeriod = text.toInt + } catch { + case _: NumberFormatException => + logger.warn(s"Trying to set a non-number value ($text) to the `autosavePeriod` setting!"); + } } } - } - }, Padding2D(bottom = 8)) + }, + Padding2D(bottom = 8), + ) private def unpackConfig(file: File): Unit = { if (file.exists()) { @@ -134,7 +151,7 @@ class SystemSettingsTab extends SettingsTab with Logging { case Failure(exception) => new NotificationDialog( s"Something went wrong!\n($exception)\nCheck the log file for a full stacktrace.", - NotificationType.Error + NotificationType.Error, ).addCloseButton().show() } } @@ -152,6 +169,7 @@ class SystemSettingsTab extends SettingsTab with Logging { override def text = "Restart Ocelot to apply new configuration" } + children :+= new PaddingBox(restartWarning, Padding2D(top = 4, bottom = 8)) private class InvisibleLabel extends Label { diff --git a/src/main/scala/ocelot/desktop/ui/widget/settings/UISettingsTab.scala b/src/main/scala/ocelot/desktop/ui/widget/settings/UISettingsTab.scala index a4bf67c..e406c4f 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/settings/UISettingsTab.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/settings/UISettingsTab.scala @@ -22,117 +22,142 @@ class UISettingsTab extends SettingsTab { } } - children :+= new PaddingBox(new Checkbox("Pin newly opened windows", - initialValue = Settings.get.pinNewWindows) - { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Pin newly opened windows", + initialValue = Settings.get.pinNewWindows) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.pinNewWindows = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.pinNewWindows = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Fullscreen mode", - initialValue = Settings.get.windowFullscreen) - { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Fullscreen mode", + initialValue = Settings.get.windowFullscreen) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.windowFullscreen = value - applySettings() - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.windowFullscreen = value + applySettings() + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Save workspace on exit", - initialValue = Settings.get.saveOnExit) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Save workspace on exit", + initialValue = Settings.get.saveOnExit) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.saveOnExit = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.saveOnExit = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Re-open last workspace on startup", - initialValue = Settings.get.openLastWorkspace) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Re-open last workspace on startup", + initialValue = Settings.get.openLastWorkspace) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.openLastWorkspace = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.openLastWorkspace = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Show previews on screen blocks", - initialValue = Settings.get.renderScreenDataOnNodes) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Show previews on screen blocks", + initialValue = Settings.get.renderScreenDataOnNodes) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.renderScreenDataOnNodes = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.renderScreenDataOnNodes = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Enable mipmaps for screen windows", - initialValue = Settings.get.screenWindowMipmap) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Enable mipmaps for screen windows", + initialValue = Settings.get.screenWindowMipmap) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.screenWindowMipmap = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.screenWindowMipmap = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Checkbox("Enable festive decorations", - initialValue = Settings.get.enableFestiveDecorations) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Checkbox("Enable festive decorations", + initialValue = Settings.get.enableFestiveDecorations) { + override def minimumSize: Size2D = Size2D(512, 24) - override def onValueChanged(value: Boolean): Unit = { - Settings.get.enableFestiveDecorations = value - } - }, Padding2D(bottom = 8)) + override def onValueChanged(value: Boolean): Unit = { + Settings.get.enableFestiveDecorations = value + } + }, + Padding2D(bottom = 8), + ) - children :+= new PaddingBox(new Slider((Settings.get.scaleFactor - 1) / 2, "Interface scale", 5) { - override def minimumSize: Size2D = Size2D(512, 24) + children :+= new PaddingBox( + new Slider((Settings.get.scaleFactor - 1) / 2, "Interface scale", 5) { + override def minimumSize: Size2D = Size2D(512, 24) - // Interpolates [0; 1] as [1; 3] rounded to nearest 0.5 - private def convertToScale(slider: Float): Float = (slider * 4 + 2).round.max(2).min(6) / 2.0f + // Interpolates [0; 1] as [1; 3] rounded to nearest 0.5 + private def convertToScale(slider: Float): Float = (slider * 4 + 2).round.max(2).min(6) / 2.0f - override def formatText: String = f"$text: ${convertToScale(value)}%.1fx" + override def formatText: String = f"$text: ${convertToScale(value)}%.1fx" - override def onValueFinal(value: Float): Unit = { - Settings.get.scaleFactor = convertToScale(value) - applySettings() - } - }, Padding2D(bottom = 8)) + override def onValueFinal(value: Float): Unit = { + Settings.get.scaleFactor = convertToScale(value) + applySettings() + } + }, + Padding2D(bottom = 8), + ) children :+= new PaddingBox(new Label("Tooltip delays:"), Padding2D(bottom = 8)) - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this) - children :+= new Slider(Settings.get.tooltipDelayItem / 2.0f, "Items") { - override def minimumSize: Size2D = Size2D(247, 24) + children :+= new Slider(Settings.get.tooltipDelayItem / 2.0f, "Items") { + override def minimumSize: Size2D = Size2D(247, 24) - private def convert(value: Float): Float = roundAt(2)(value * 2.0f).toFloat - override def formatText: String = f"$text: ${convert(value)}%.2f s" + private def convert(value: Float): Float = roundAt(2)(value * 2.0f).toFloat + override def formatText: String = f"$text: ${convert(value)}%.2f s" - override def onValueFinal(value: Float): Unit = { - // we are treating 0 as 0.001 to keep the legacy behaviour - Settings.get.tooltipDelayItem = convert(value) max 0.001f min 2.0f + override def onValueFinal(value: Float): Unit = { + // we are treating 0 as 0.001 to keep the legacy behaviour + Settings.get.tooltipDelayItem = convert(value) max 0.001f min 2.0f + } } - } - children :+= new Widget { - override def maximumSize: Size2D = Size2D(16, 8) - } - - children :+= new Slider(Settings.get.tooltipDelayUI / 2.0f, "UI Elements") { - override def minimumSize: Size2D = Size2D(247, 24) - - private def convert(value: Float): Float = roundAt(2)(value * 2.0f).toFloat - override def formatText: String = f"$text: ${convert(value)}%.2f s" - - override def onValueFinal(value: Float): Unit = { - // we are treating 0 as 0.001 to keep the legacy behaviour - Settings.get.tooltipDelayUI = convert(value) max 0.001f min 2.0f + children :+= new Widget { + override def maximumSize: Size2D = Size2D(16, 8) } - } - }, Padding2D(bottom = 16)) + + children :+= new Slider(Settings.get.tooltipDelayUI / 2.0f, "UI Elements") { + override def minimumSize: Size2D = Size2D(247, 24) + + private def convert(value: Float): Float = roundAt(2)(value * 2.0f).toFloat + override def formatText: String = f"$text: ${convert(value)}%.2f s" + + override def onValueFinal(value: Float): Unit = { + // we are treating 0 as 0.001 to keep the legacy behaviour + Settings.get.tooltipDelayUI = convert(value) max 0.001f min 2.0f + } + } + }, + Padding2D(bottom = 16), + ) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/slot/ComponentBusSlotWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/slot/ComponentBusSlotWidget.scala index 573c25b..b65a127 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/slot/ComponentBusSlotWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/slot/ComponentBusSlotWidget.scala @@ -5,9 +5,7 @@ import ocelot.desktop.inventory.Inventory import ocelot.desktop.inventory.item.ComponentBusItem import totoro.ocelot.brain.util.Tier.Tier -class ComponentBusSlotWidget(slot: Inventory#Slot, _tier: Tier) - extends SlotWidget[ComponentBusItem](slot) -{ +class ComponentBusSlotWidget(slot: Inventory#Slot, _tier: Tier) extends SlotWidget[ComponentBusItem](slot) { override def ghostIcon: Option[IconSource] = Some(IconSource.ComponentBusIcon) override def slotTier: Option[Tier] = Some(_tier) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/slot/ComputerCpuSlotWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/slot/ComputerCpuSlotWidget.scala index 1a316ee..5114852 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/slot/ComputerCpuSlotWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/slot/ComputerCpuSlotWidget.scala @@ -6,9 +6,8 @@ import ocelot.desktop.util.ComputerAware import totoro.ocelot.brain.util.Tier.Tier class ComputerCpuSlotWidget(slot: Inventory#Slot, computer: ComputerAware, _tier: Tier) - extends CpuSlotWidget(slot, _tier) { - - protected override def onItemNotification(notification: Item.Notification): Unit = { + extends CpuSlotWidget(slot, _tier) { + override protected def onItemNotification(notification: Item.Notification): Unit = { super.onItemNotification(notification) notification match { diff --git a/src/main/scala/ocelot/desktop/ui/widget/slot/ItemChooser.scala b/src/main/scala/ocelot/desktop/ui/widget/slot/ItemChooser.scala index f5795b5..33f5df0 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/slot/ItemChooser.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/slot/ItemChooser.scala @@ -13,7 +13,7 @@ class ItemChooser[I <: Item](slot: SlotWidget[I]) extends ContextMenu { private def makeMenuEntry(factory: ItemFactory, label: String): ContextMenuEntry = { ContextMenuEntry( label, - Some(ContextMenuIcon(factory.icon, ContextMenuIconSize.Big, Some(Color.White))) + Some(ContextMenuIcon(factory.icon, ContextMenuIconSize.Big, Some(Color.White))), ) { slot.item = factory.build().asInstanceOf[I] } @@ -22,7 +22,7 @@ class ItemChooser[I <: Item](slot: SlotWidget[I]) extends ContextMenu { private def addSubmenu[T: HasLabel]( name: String, factories: Seq[(T, ItemFactory)], - icon: Option[ContextMenuIcon] = None + icon: Option[ContextMenuIcon] = None, ): Unit = { val tierLabel = implicitly[HasLabel[T]].label _ @@ -32,7 +32,9 @@ class ItemChooser[I <: Item](slot: SlotWidget[I]) extends ContextMenu { addEntry( new ContextMenuSubmenu( name, - Some(icon.getOrElse(ContextMenuIcon(acceptedFactories.last._2.icon, ContextMenuIconSize.Big, Some(Color.White)))) + Some( + icon.getOrElse(ContextMenuIcon(acceptedFactories.last._2.icon, ContextMenuIconSize.Big, Some(Color.White))) + ), ) { for ((tier, factory) <- acceptedFactories) { addEntry(makeMenuEntry(factory, tierLabel(tier))) @@ -53,7 +55,8 @@ class ItemChooser[I <: Item](slot: SlotWidget[I]) extends ContextMenu { case ExtendedTieredItemGroup(name, factories) => addSubmenu(name, factories) - case ArbitraryItemGroup(name, icon, factories) => addSubmenu(name, factories, Some(ContextMenuIcon(icon, ContextMenuIconSize.Big, Some(Color.White)))) + case ArbitraryItemGroup(name, icon, factories) => + addSubmenu(name, factories, Some(ContextMenuIcon(icon, ContextMenuIconSize.Big, Some(Color.White)))) } } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/slot/RackMountableSlotWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/slot/RackMountableSlotWidget.scala index 493dc67..9cb4b8d 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/slot/RackMountableSlotWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/slot/RackMountableSlotWidget.scala @@ -5,9 +5,7 @@ import ocelot.desktop.inventory.Inventory import ocelot.desktop.inventory.item.ServerItem import ocelot.desktop.inventory.traits.RackMountableItem -class RackMountableSlotWidget(slot: Inventory#Slot) - extends SlotWidget[RackMountableItem](slot) -{ +class RackMountableSlotWidget(slot: Inventory#Slot) extends SlotWidget[RackMountableItem](slot) { override def ghostIcon: Option[IconSource] = Some(IconSource.ServerIcon) override def onItemRemoved(removedItem: RackMountableItem, replacedBy: Option[RackMountableItem]): Unit = { diff --git a/src/main/scala/ocelot/desktop/ui/widget/slot/SlotWidget.scala b/src/main/scala/ocelot/desktop/ui/widget/slot/SlotWidget.scala index ade53b4..482fb16 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/slot/SlotWidget.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/slot/SlotWidget.scala @@ -20,9 +20,7 @@ import scala.math.Ordering.Implicits.infixOrderingOps import scala.reflect.ClassTag class SlotWidget[I <: Item](private val slot: Inventory#Slot)(implicit slotItemTag: ClassTag[I]) - extends Widget - with MouseHandler - with HoverHandler { + extends Widget with MouseHandler with HoverHandler { slotWidget => @@ -96,8 +94,8 @@ class SlotWidget[I <: Item](private val slot: Inventory#Slot)(implicit slotItemT protected def onItemNotification(notification: Item.Notification): Unit = {} - final override def minimumSize: Size2D = Size2D(36, 36) - final override def maximumSize: Size2D = minimumSize + override final def minimumSize: Size2D = Size2D(36, 36) + override final def maximumSize: Size2D = minimumSize override protected def receiveClickEvents: Boolean = true @@ -231,7 +229,7 @@ class SlotWidget[I <: Item](private val slot: Inventory#Slot)(implicit slotItemT } } - final override def draw(g: Graphics): Unit = { + override final def draw(g: Graphics): Unit = { g.sprite("EmptySlot", bounds) val iconBounds = bounds.inflate(-2) diff --git a/src/main/scala/ocelot/desktop/ui/widget/statusbar/StatusBar.scala b/src/main/scala/ocelot/desktop/ui/widget/statusbar/StatusBar.scala index d56c9b7..e1f13ca 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/statusbar/StatusBar.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/statusbar/StatusBar.scala @@ -31,11 +31,14 @@ class StatusBar extends Widget { case KeyEvent(KeyEvent.State.Press, Keyboard.KEY_F2, _) => showFPS = !showFPS if (showFPS) { - children :+= new PaddingBox(new Label { - override def maximumSize: Size2D = minimumSize - override def color: Color = ColorScheme("StatusBarFPS") - override def text: String = f"FPS: ${UiHandler.fps}%02.1f" - }, Padding2D(left = 8, right = 8)) + children :+= new PaddingBox( + new Label { + override def maximumSize: Size2D = minimumSize + override def color: Color = ColorScheme("StatusBarFPS") + override def text: String = f"FPS: ${UiHandler.fps}%02.1f" + }, + Padding2D(left = 8, right = 8), + ) } else { children = children.take(2) } @@ -44,8 +47,7 @@ class StatusBar extends Widget { children :+= new ScrollView(new Widget { children :+= keyMouseEntries children :+= keyEntries - }) - { + }) { override def minimumSize: Size2D = inner.minimumSize.copy(width = 5f) override def maximumSize: Size2D = inner.minimumSize.copy(width = Float.PositiveInfinity) override def hThumbVisible: Boolean = false @@ -127,16 +129,25 @@ class StatusBar extends Widget { } HoverBox - }, Padding2D(left = 8) + }, + Padding2D(left = 8), ) def addMouseEntry(icon: String, text: String): Unit = { - if (!keyMouseEntries.children.filter(_.isInstanceOf[MouseEntry]).map(_.asInstanceOf[MouseEntry]).exists(_.icon == icon)) + if ( + !keyMouseEntries.children.filter(_.isInstanceOf[MouseEntry]).map(_.asInstanceOf[MouseEntry]).exists( + _.icon == icon + ) + ) keyMouseEntries.children :+= new MouseEntry(icon, text) } def addKeyMouseEntry(icon: String, key: String, text: String): Unit = { - if (!keyMouseEntries.children.filter(_.isInstanceOf[KeyMouseEntry]).map(_.asInstanceOf[KeyMouseEntry]).exists(v => v.icon == icon && v.key == key)) + if ( + !keyMouseEntries.children.filter(_.isInstanceOf[KeyMouseEntry]).map(_.asInstanceOf[KeyMouseEntry]).exists(v => + v.icon == icon && v.key == key + ) + ) keyMouseEntries.children :+= new KeyMouseEntry(icon, key, text) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/tooltip/Tooltip.scala b/src/main/scala/ocelot/desktop/ui/widget/tooltip/Tooltip.scala index 0f456af..c3c0519 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/tooltip/Tooltip.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/tooltip/Tooltip.scala @@ -21,9 +21,7 @@ abstract class Tooltip extends Widget { children :+= new PaddingBox(body, bodyPadding) - /** - * Time before the tooltip will become visible (in seconds) - */ + /** Time before the tooltip will become visible (in seconds) */ val DelayTime = 0.001f eventHandlers += { @@ -67,4 +65,4 @@ abstract class Tooltip extends Widget { g.rect(position.x + 5, position.y + 5, size.width, size.height, RGBAColor(20, 20, 20, 100)) drawChildren(g) } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/tooltip/TooltipPool.scala b/src/main/scala/ocelot/desktop/ui/widget/tooltip/TooltipPool.scala index cf089e0..f4e4392 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/tooltip/TooltipPool.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/tooltip/TooltipPool.scala @@ -82,7 +82,7 @@ class TooltipPool extends Widget { } tooltip.tooltip.position = tooltip.tooltip.position + (UiHandler.mousePosition + offset - tooltip.tooltip.position) * - (if (tooltip.tooltip.isClosing) Math.pow(Easing.easeInQuad(tooltip.tooltip.getAlpha), 6) else 1.0) + (if (tooltip.tooltip.isClosing) Math.pow(Easing.easeInQuad(tooltip.tooltip.getAlpha), 6) else 1.0) }) if (dueToClean) { diff --git a/src/main/scala/ocelot/desktop/ui/widget/traits/HoverAnimation.scala b/src/main/scala/ocelot/desktop/ui/widget/traits/HoverAnimation.scala index e419554..449c2af 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/traits/HoverAnimation.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/traits/HoverAnimation.scala @@ -8,9 +8,7 @@ import ocelot.desktop.ui.event.handlers.HoverHandler import ocelot.desktop.ui.widget.{Updatable, Widget} import ocelot.desktop.util.animation.ColorAnimation -/** - * Helper trait that manages color animations for UI widgets that should be highlighted on mouse hover. - */ +/** Helper trait that manages color animations for UI widgets that should be highlighted on mouse hover. */ //noinspection ScalaWeakerAccess @@ -19,7 +17,9 @@ trait HoverAnimation extends Widget with EventAware with HoverHandler with Updat protected val hoverAnimationSpeedLeave: Float = AnimationSpeedHoverLeave protected val hoverAnimationColorDefault: Color = ColorScheme("ButtonBackground") protected val hoverAnimationColorActive: Color = ColorScheme("ButtonBackgroundActive") - protected lazy val hoverAnimation: ColorAnimation = new ColorAnimation(hoverAnimationColorDefault, hoverAnimationSpeedEnter) + + protected lazy val hoverAnimation: ColorAnimation = + new ColorAnimation(hoverAnimationColorDefault, hoverAnimationSpeedEnter) eventHandlers += { case HoverEvent(HoverEvent.State.Enter) => diff --git a/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenu.scala b/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenu.scala index 497c11a..d458ad0 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenu.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenu.scala @@ -11,7 +11,7 @@ class VerticalMenu extends Widget { override def receiveMouseEvents: Boolean = true override def maximumSize: Size2D = minimumSize - + private val container: Widget = new Widget { override val layout = new LinearLayout(this, orientation = Orientation.Vertical) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenuButton.scala b/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenuButton.scala index d38f217..c332135 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenuButton.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/verticalmenu/VerticalMenuButton.scala @@ -13,28 +13,29 @@ import ocelot.desktop.util.Orientation import ocelot.desktop.util.animation.ColorAnimation class VerticalMenuButton(icon: IconSource, label: String, handler: VerticalMenuButton => Unit = _ => {}) - extends Widget - with MouseHandler - with HoverHandler { + extends Widget with MouseHandler with HoverHandler { val colorAnimation: ColorAnimation = new ColorAnimation(ColorScheme("VerticalMenuBackground"), 0.6f) var selected = false - children :+= new PaddingBox(new Widget { - override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) + children :+= new PaddingBox( + new Widget { + override val layout = new LinearLayout(this, orientation = Orientation.Horizontal) - children :+= new PaddingBox( - new Icon(icon, color = ColorScheme("VerticalMenuEntryIcon")), - Padding2D(right = 8) - ) + children :+= new PaddingBox( + new Icon(icon, color = ColorScheme("VerticalMenuEntryIcon")), + Padding2D(right = 8), + ) - children :+= new Label { - override def text: String = label - override def color: Color = ColorScheme("VerticalMenuEntryForeground") - override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 16) - } - }, Padding2D(left = 8, right = 24, top = 8, bottom = 8)) + children :+= new Label { + override def text: String = label + override def color: Color = ColorScheme("VerticalMenuEntryForeground") + override def maximumSize: Size2D = Size2D(Float.PositiveInfinity, 16) + } + }, + Padding2D(left = 8, right = 24, top = 8, bottom = 8), + ) override protected def receiveClickEvents: Boolean = true diff --git a/src/main/scala/ocelot/desktop/ui/widget/window/BasicWindow.scala b/src/main/scala/ocelot/desktop/ui/widget/window/BasicWindow.scala index 9bca484..6ac77bf 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/window/BasicWindow.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/window/BasicWindow.scala @@ -48,8 +48,7 @@ trait BasicWindow extends Window { if (alpha.value < 0.001) { state = Window.State.Closed - } - else if (alpha.value > 0.999) { + } else if (alpha.value > 0.999) { state = Window.State.Open } } diff --git a/src/main/scala/ocelot/desktop/ui/widget/window/NodeSelector.scala b/src/main/scala/ocelot/desktop/ui/widget/window/NodeSelector.scala index e67879a..12f87c0 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/window/NodeSelector.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/window/NodeSelector.scala @@ -47,24 +47,25 @@ class NodeSelector extends Window with Logging { private var rowCount = 0 private def addNodeWidget(widget: Widget): Unit = { - val row = + val row = { if (rows.lastOption.exists(row => row.isInstanceOf[Row] && row.children.length < nodesPerRow)) { rows.last - } - else { + } else { val row = new Row(rows.length) rows :+= row rowCount += 1 row } + } row.children :+= widget } private def addNodeGroupTitle(group: NodeTypeGroup): Unit = { rows :+= new Widget { - override protected val layout = new LinearLayout(this, Orientation.Vertical, JustifyContent.Center, AlignItems.Center) + override protected val layout = + new LinearLayout(this, Orientation.Vertical, JustifyContent.Center, AlignItems.Center) children :+= new Label { override def text: String = group.name @@ -83,19 +84,21 @@ class NodeSelector extends Window with Logging { addNodeGroupTitle(group) // Nodes from group - group.types.foreach(nodeType => addNodeWidget(new NodeTypeWidget(nodeType) { - override def onClick(): Unit = { - val node = nodeType.make() + group.types.foreach(nodeType => { + addNodeWidget(new NodeTypeWidget(nodeType) { + override def onClick(): Unit = { + val node = nodeType.make() - node match { - case fillable: DefaultSlotItemsFillable => fillable.fillSlotsWithDefaultItems() - case _ => + node match { + case fillable: DefaultSlotItemsFillable => fillable.fillSlotsWithDefaultItems() + case _ => + } + + workspaceView.addNode(node) + close() } - - workspaceView.addNode(node) - close() - } - })) + }) + }) }) } @@ -191,4 +194,4 @@ class NodeSelector extends Window with Logging { } initNodeTypes() -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/ui/widget/window/PanelWindow.scala b/src/main/scala/ocelot/desktop/ui/widget/window/PanelWindow.scala index 296d714..1148190 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/window/PanelWindow.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/window/PanelWindow.scala @@ -17,10 +17,13 @@ trait PanelWindow extends BasicWindow { def setInner(inner: Widget, padding: Padding2D = Padding2D(bottom = 13, left = 12, right = 12)): Unit = { children = ArraySeq.empty - children :+= new PaddingBox(new TitleBar(PanelWindow.this) { - override def title: String = PanelWindow.this.title - override def titleMaxLength: Int = PanelWindow.this.titleMaxLength - }, Padding2D(top = 8, left = 12, right = 12, bottom = 2)) + children :+= new PaddingBox( + new TitleBar(PanelWindow.this) { + override def title: String = PanelWindow.this.title + override def titleMaxLength: Int = PanelWindow.this.titleMaxLength + }, + Padding2D(top = 8, left = 12, right = 12, bottom = 2), + ) children :+= new PaddingBox(inner, padding) } diff --git a/src/main/scala/ocelot/desktop/ui/widget/window/TitleBar.scala b/src/main/scala/ocelot/desktop/ui/widget/window/TitleBar.scala index 0ba7ad6..b1710c1 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/window/TitleBar.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/window/TitleBar.scala @@ -16,20 +16,22 @@ class TitleBar(val window: Window) extends Widget { orientation = Orientation.Horizontal, alignItems = AlignItems.Center) children :+= new Label { - override def text: String = + override def text: String = { if (title.length > titleMaxLength) title.take(titleMaxLength - 1) + "…" else title + } override def isSmall: Boolean = true } children :+= new IconButton( - "icons/Pin", "icons/Unpin", + "icons/Pin", + "icons/Unpin", mode = IconButton.Mode.Switch, darkenActiveColorFactor = 0.5f, - model = IconButton.ReadOnlyModel(isPinned) + model = IconButton.ReadOnlyModel(isPinned), ) { override def onPressed(): Unit = onPinRequested() @@ -37,7 +39,8 @@ class TitleBar(val window: Window) extends Widget { } children :+= new IconButton( - "icons/Close", "icons/Close", + "icons/Close", + "icons/Close", darkenActiveColorFactor = 0.5f, ) { override def onPressed(): Unit = onCloseRequested() diff --git a/src/main/scala/ocelot/desktop/ui/widget/window/Window.scala b/src/main/scala/ocelot/desktop/ui/widget/window/Window.scala index 54e9592..f14f5f1 100644 --- a/src/main/scala/ocelot/desktop/ui/widget/window/Window.scala +++ b/src/main/scala/ocelot/desktop/ui/widget/window/Window.scala @@ -33,7 +33,7 @@ trait Window extends Widget with Persistable with MouseHandler { case MouseEvent(MouseEvent.State.Press, _) => focus() - case ev@DragEvent(DragEvent.State.Start, MouseEvent.Button.Left, mousePos) => + case ev @ DragEvent(DragEvent.State.Start, MouseEvent.Button.Left, mousePos) => if (dragRegions.exists(_.contains(ev.start))) { grabPoint = Some(mousePos - position) } @@ -174,8 +174,7 @@ trait Window extends Widget with Persistable with MouseHandler { } } - /** - * Disposes of the window immediately. This will make it dramatically pop out of existence, + /** Disposes of the window immediately. This will make it dramatically pop out of existence, * without playing the closing animation. * * Unless you know what you're doing, use `closeAndDispose`. @@ -187,13 +186,14 @@ trait Window extends Widget with Persistable with MouseHandler { windowPool.removeWindow(this) } - def closeAndDispose(): Unit = + def closeAndDispose(): Unit = { if (UiHandler.terminating && !isDisposed) { dispose() } else { disposeOnClose = true close() } + } private def canCloseOnEsc: Boolean = isFocused && !root.get.modalDialogPool.isVisible @@ -218,17 +218,19 @@ trait Window extends Widget with Persistable with MouseHandler { _isFocused = nbt.getBoolean("focused") - _isPinned = + _isPinned = { if (nbt.hasKey("pinned")) nbt.getBoolean("pinned") else Settings.get.pinNewWindows + } - position = + position = { if (nbt.hasKey("position")) new Vector2D(nbt.getCompoundTag("position")) else new Vector2D(nbt) + } if (nbt.hasKey("size")) size = new Size2D(nbt.getCompoundTag("size")) diff --git a/src/main/scala/ocelot/desktop/util/AudibleComputerAware.scala b/src/main/scala/ocelot/desktop/util/AudibleComputerAware.scala index 41b02d5..fe601a9 100644 --- a/src/main/scala/ocelot/desktop/util/AudibleComputerAware.scala +++ b/src/main/scala/ocelot/desktop/util/AudibleComputerAware.scala @@ -12,8 +12,7 @@ trait AudibleComputerAware extends ComputerAware { def updateRunningSound(): Unit = { if (!computer.machine.isRunning && soundComputerRunning.isPlaying) { soundComputerRunning.stop() - } - else if (computer.machine.isRunning && !soundComputerRunning.isPlaying && !Audio.isDisabled) { + } else if (computer.machine.isRunning && !soundComputerRunning.isPlaying && !Audio.isDisabled) { soundComputerRunning.play() } } diff --git a/src/main/scala/ocelot/desktop/util/CommandLine.scala b/src/main/scala/ocelot/desktop/util/CommandLine.scala index bed8a6e..83aa162 100644 --- a/src/main/scala/ocelot/desktop/util/CommandLine.scala +++ b/src/main/scala/ocelot/desktop/util/CommandLine.scala @@ -9,7 +9,9 @@ object CommandLine { val WorkspacePath: Argument = Argument("-w", "--workspace", "Open provided workspace on start", takesValue = true) val availableArguments: ArrayBuffer[Argument] = ArrayBuffer( - Help, ConfigPath, WorkspacePath + Help, + ConfigPath, + WorkspacePath, ) def parse(args: Array[String]): mutable.HashMap[Argument, Option[String]] = { @@ -26,11 +28,13 @@ object CommandLine { arguments } - def doc: String = """ + def doc: String = { + """ |Usage: java -jar ocelot.jar [options] |where options include: |""".stripMargin + availableArguments.foldLeft("") { - (acc: String, arg: Argument) => s"$acc\n ${arg.shortForm}, ${arg.longForm}: ${arg.doc}" + (acc: String, arg: Argument) => s"$acc\n ${arg.shortForm}, ${arg.longForm}: ${arg.doc}" + } } case class Argument(shortForm: String, longForm: String, doc: String, takesValue: Boolean = false) diff --git a/src/main/scala/ocelot/desktop/util/ComputerAware.scala b/src/main/scala/ocelot/desktop/util/ComputerAware.scala index 7a44612..95a496a 100644 --- a/src/main/scala/ocelot/desktop/util/ComputerAware.scala +++ b/src/main/scala/ocelot/desktop/util/ComputerAware.scala @@ -17,12 +17,7 @@ import totoro.ocelot.brain.util.Tier.Tier import scala.math.Ordering.Implicits.infixOrderingOps import scala.reflect.ClassTag -trait ComputerAware - extends Logging - with SyncedInventory - with DefaultSlotItemsFillable - with Windowed[ComputerWindow] -{ +trait ComputerAware extends Logging with SyncedInventory with DefaultSlotItemsFillable with Windowed[ComputerWindow] { override type I = Item with ComponentItem def computer: Computer with TieredPersistable @@ -40,8 +35,7 @@ trait ComputerAware def toggleIsTurnedOn(): Unit = { if (computer.machine.isRunning) { turnOff() - } - else { + } else { turnOn() } } @@ -56,8 +50,7 @@ trait ComputerAware turnOff() turnOn() }) - } - else { + } else { menu.addEntry(ContextMenuEntry("Turn on", IconSource.Power) { turnOn() }) @@ -94,12 +87,12 @@ trait ComputerAware protected def slots: IterableOnce[SlotWidget[I]] = ( // slots may be null during initialization Option(eepromSlot).iterator ++ - Option(cpuSlot).iterator ++ - componentBusSlots.iterator ++ - memorySlots.iterator ++ - cardSlots.iterator ++ - diskSlots.iterator ++ - floppySlot.iterator + Option(cpuSlot).iterator ++ + componentBusSlots.iterator ++ + memorySlots.iterator ++ + cardSlots.iterator ++ + diskSlots.iterator ++ + floppySlot.iterator ).map(_.asInstanceOf[SlotWidget[I]]) private def addSlot(): Slot = { @@ -128,7 +121,7 @@ trait ComputerAware widget } - protected def addSlotWidgets[T <: SlotWidget[_] : ClassTag](factories: (Slot => T)*): Array[T] = { + protected def addSlotWidgets[T <: SlotWidget[_]: ClassTag](factories: (Slot => T)*): Array[T] = { val array = Array.newBuilder[T] for (factory <- factories) diff --git a/src/main/scala/ocelot/desktop/util/ComputerType.scala b/src/main/scala/ocelot/desktop/util/ComputerType.scala index 3c080ff..675a364 100644 --- a/src/main/scala/ocelot/desktop/util/ComputerType.scala +++ b/src/main/scala/ocelot/desktop/util/ComputerType.scala @@ -4,4 +4,4 @@ object ComputerType extends Enumeration { type ComputerType = Value val Computer, Server, Microcontroller = Value -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/util/DefaultSlotItemsFillable.scala b/src/main/scala/ocelot/desktop/util/DefaultSlotItemsFillable.scala index 753a5c9..d2d323e 100644 --- a/src/main/scala/ocelot/desktop/util/DefaultSlotItemsFillable.scala +++ b/src/main/scala/ocelot/desktop/util/DefaultSlotItemsFillable.scala @@ -2,7 +2,6 @@ package ocelot.desktop.util import ocelot.desktop.inventory.Inventory - trait DefaultSlotItemsFillable extends Inventory { def fillSlotsWithDefaultItems(): Unit } diff --git a/src/main/scala/ocelot/desktop/util/DiskDriveAware.scala b/src/main/scala/ocelot/desktop/util/DiskDriveAware.scala index 52a7a09..cea3914 100644 --- a/src/main/scala/ocelot/desktop/util/DiskDriveAware.scala +++ b/src/main/scala/ocelot/desktop/util/DiskDriveAware.scala @@ -17,12 +17,7 @@ import totoro.ocelot.brain.entity.traits.Inventory import totoro.ocelot.brain.loot.Loot import totoro.ocelot.brain.util.DyeColor -trait DiskDriveAware - extends Logging - with SyncedInventory - with DefaultSlotItemsFillable - with Windowed[DiskDriveWindow] -{ +trait DiskDriveAware extends Logging with SyncedInventory with DefaultSlotItemsFillable with Windowed[DiskDriveWindow] { override type I = FloppyItem def floppyDiskDrive: FloppyDiskDrive @@ -34,14 +29,14 @@ trait DiskDriveAware def drawActivityAndFloppy( g: Graphics, bounds: Rect2D, - iconSource: DiskActivityIconSource with FloppyDriveIconSource + iconSource: DiskActivityIconSource with FloppyDriveIconSource, ): Unit = { DrawUtils.drawFilesystemActivity( g, bounds.x, bounds.y, floppyDiskDrive, - iconSource + iconSource, ) for (item <- floppySlotWidget.item) { @@ -51,7 +46,7 @@ trait DiskDriveAware bounds.y, bounds.w, bounds.h, - IntColor(ColorValues(item.color.value)) + IntColor(ColorValues(item.color.value)), ) } } @@ -104,20 +99,20 @@ object DiskDriveAware { val ColorValues: Map[DyeColor, Int] = Map( DyeColor.Black -> 0x444444, // 0x1E1B1B - DyeColor.Red -> 0xB3312C, + DyeColor.Red -> 0xb3312c, DyeColor.Green -> 0x339911, // 0x3B511A - DyeColor.Brown -> 0x51301A, - DyeColor.Blue -> 0x6666FF, // 0x253192 - DyeColor.Purple -> 0x7B2FBE, - DyeColor.Cyan -> 0x66FFFF, // 0x287697 - DyeColor.Silver -> 0xABABAB, + DyeColor.Brown -> 0x51301a, + DyeColor.Blue -> 0x6666ff, // 0x253192 + DyeColor.Purple -> 0x7b2fbe, + DyeColor.Cyan -> 0x66ffff, // 0x287697 + DyeColor.Silver -> 0xababab, DyeColor.Gray -> 0x666666, // 0x434343 - DyeColor.Pink -> 0xD88198, - DyeColor.Lime -> 0x66FF66, // 0x41CD34 - DyeColor.Yellow -> 0xFFFF66, // 0xDECF2A - DyeColor.LightBlue -> 0xAAAAFF, // 0x6689D3 - DyeColor.Magenta -> 0xC354CD, - DyeColor.Orange -> 0xEB8844, - DyeColor.White -> 0xF0F0F0 + DyeColor.Pink -> 0xd88198, + DyeColor.Lime -> 0x66ff66, // 0x41CD34 + DyeColor.Yellow -> 0xffff66, // 0xDECF2A + DyeColor.LightBlue -> 0xaaaaff, // 0x6689D3 + DyeColor.Magenta -> 0xc354cd, + DyeColor.Orange -> 0xeb8844, + DyeColor.White -> 0xf0f0f0, ) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/util/DrawUtils.scala b/src/main/scala/ocelot/desktop/util/DrawUtils.scala index 079c6a6..50fb29a 100644 --- a/src/main/scala/ocelot/desktop/util/DrawUtils.scala +++ b/src/main/scala/ocelot/desktop/util/DrawUtils.scala @@ -229,7 +229,7 @@ object DrawUtils { g: Graphics, x: Float, y: Float, - iconSource: DiskActivityIconSource + iconSource: DiskActivityIconSource, ): Unit = { g.sprite(iconSource.DiskActivity, x, y, NoHighlightSize, NoHighlightSize) } @@ -239,7 +239,7 @@ object DrawUtils { x: Float, y: Float, diskActivityAware: DiskActivityAware, - iconSource: DiskActivityIconSource + iconSource: DiskActivityIconSource, ): Unit = { if (diskActivityAware.shouldVisualizeDiskActivity) { drawFilesystemActivity( @@ -256,7 +256,7 @@ object DrawUtils { x: Float, y: Float, networkActivityAware: NetworkActivityAware, - iconSource: NetworkActivityIconSource + iconSource: NetworkActivityIconSource, ): Unit = { if (networkActivityAware.shouldVisualizeNetworkActivity) g.sprite(iconSource.NetworkActivity, x, y, NoHighlightSize, NoHighlightSize) diff --git a/src/main/scala/ocelot/desktop/util/FileUtils.scala b/src/main/scala/ocelot/desktop/util/FileUtils.scala index 27bb142..a4f15b2 100644 --- a/src/main/scala/ocelot/desktop/util/FileUtils.scala +++ b/src/main/scala/ocelot/desktop/util/FileUtils.scala @@ -30,12 +30,13 @@ object FileUtils extends Logging { def unpackResource(resource: String, target: File): Try[File] = Try { val configResource = classOf[Settings].getResource(resource) - Using.resources(Channels.newChannel(configResource.openStream()), new FileOutputStream(target).getChannel) { (in, out) => - out.transferFrom(in, 0, Long.MaxValue) - target.setReadable(true, false) - target.setWritable(true, false) - target.setExecutable(false, false) - target + Using.resources(Channels.newChannel(configResource.openStream()), new FileOutputStream(target).getChannel) { + (in, out) => + out.transferFrom(in, 0, Long.MaxValue) + target.setReadable(true, false) + target.setWritable(true, false) + target.setExecutable(false, false) + target } } } diff --git a/src/main/scala/ocelot/desktop/util/Font.scala b/src/main/scala/ocelot/desktop/util/Font.scala index 8cd465a..596f01f 100644 --- a/src/main/scala/ocelot/desktop/util/Font.scala +++ b/src/main/scala/ocelot/desktop/util/Font.scala @@ -59,7 +59,7 @@ class Font(val name: String, val fontSize: Int) extends Resource with Logging { ox.asInstanceOf[Float] / AtlasWidth.asInstanceOf[Float], oy.asInstanceOf[Float] / AtlasHeight.asInstanceOf[Float], width.asInstanceOf[Float] / AtlasWidth.asInstanceOf[Float], - fontSize.asInstanceOf[Float] / AtlasHeight.asInstanceOf[Float] + fontSize.asInstanceOf[Float] / AtlasHeight.asInstanceOf[Float], ) var x = 0 @@ -69,10 +69,11 @@ class Font(val name: String, val fontSize: Int) extends Resource with Logging { for (i <- 3 to 0 by -1) { val bit = (Character.digit(char, 16) >> i) & 1 - atlas.setRGB(ox + x, oy + y, bit match { - case 0 => 0x00000000 - case 1 => 0xFFFFFFFF - }) + atlas.setRGB(ox + x, oy + y, + bit match { + case 0 => 0x00000000 + case 1 => 0xffffffff + }) x += 1 @@ -128,4 +129,4 @@ class Font(val name: String, val fontSize: Int) extends Resource with Logging { super.freeResource() texture.freeResource() } -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/util/Logging.scala b/src/main/scala/ocelot/desktop/util/Logging.scala index cc76d53..34b7a65 100644 --- a/src/main/scala/ocelot/desktop/util/Logging.scala +++ b/src/main/scala/ocelot/desktop/util/Logging.scala @@ -1,6 +1,6 @@ package ocelot.desktop.util -import org.apache.logging.log4j.{LogManager, Logger} +import org.apache.logging.log4j.{Logger, LogManager} trait Logging { protected val logger: Logger = LogManager.getLogger(this.getClass) diff --git a/src/main/scala/ocelot/desktop/util/OcelotInterfaceLogStorage.scala b/src/main/scala/ocelot/desktop/util/OcelotInterfaceLogStorage.scala index 41f7aab..8d8405b 100644 --- a/src/main/scala/ocelot/desktop/util/OcelotInterfaceLogStorage.scala +++ b/src/main/scala/ocelot/desktop/util/OcelotInterfaceLogStorage.scala @@ -12,11 +12,7 @@ import totoro.ocelot.brain.nbt.{NBT, NBTBase, NBTTagCompound, NBTTagString} import scala.collection.mutable import scala.jdk.CollectionConverters.BufferHasAsJava -trait OcelotInterfaceLogStorage - extends EventAware - with Persistable - with Windowed[OcelotInterfaceWindow] - with Logging { +trait OcelotInterfaceLogStorage extends EventAware with Persistable with Windowed[OcelotInterfaceWindow] with Logging { def ocelotInterface: OcelotInterface diff --git a/src/main/scala/ocelot/desktop/util/OcelotOnlineAPI.scala b/src/main/scala/ocelot/desktop/util/OcelotOnlineAPI.scala index b72d866..51dfb03 100644 --- a/src/main/scala/ocelot/desktop/util/OcelotOnlineAPI.scala +++ b/src/main/scala/ocelot/desktop/util/OcelotOnlineAPI.scala @@ -24,8 +24,10 @@ object OcelotOnlineAPI { val releaseVersion = RegexReleaseVersion.findFirstMatchIn(response).map(_.group(1)) val releaseDate = RegexReleaseDate.findFirstMatchIn(response).map(_.group(1)) val version = Version( - devId, devDate.map(it => ZonedDateTime.parse(it)), - releaseVersion, releaseDate.map(it => ZonedDateTime.parse(it)) + devId, + devDate.map(it => ZonedDateTime.parse(it)), + releaseVersion, + releaseDate.map(it => ZonedDateTime.parse(it)), ) source.close() @@ -45,5 +47,6 @@ object OcelotOnlineAPI { } } - case class Version(devId: Option[String], devDate: Option[ZonedDateTime], releaseVersion: Option[String], releaseDate: Option[ZonedDateTime]) + case class Version(devId: Option[String], devDate: Option[ZonedDateTime], releaseVersion: Option[String], + releaseDate: Option[ZonedDateTime]) } diff --git a/src/main/scala/ocelot/desktop/util/Persistable.scala b/src/main/scala/ocelot/desktop/util/Persistable.scala index c765e6a..8c38a66 100644 --- a/src/main/scala/ocelot/desktop/util/Persistable.scala +++ b/src/main/scala/ocelot/desktop/util/Persistable.scala @@ -4,9 +4,7 @@ import totoro.ocelot.brain.nbt.NBTTagCompound import totoro.ocelot.brain.util.{Persistable => BrainPersistable} import totoro.ocelot.brain.workspace.Workspace -/** - * Akin to [[BrainPersistable the brain's Persistable]] except it doesn't care about workspaces. - */ +/** Akin to [[BrainPersistable the brain's Persistable]] except it doesn't care about workspaces. */ trait Persistable extends BrainPersistable { def load(nbt: NBTTagCompound): Unit = {} diff --git a/src/main/scala/ocelot/desktop/util/Profiler.scala b/src/main/scala/ocelot/desktop/util/Profiler.scala index 52e719e..cdab42c 100644 --- a/src/main/scala/ocelot/desktop/util/Profiler.scala +++ b/src/main/scala/ocelot/desktop/util/Profiler.scala @@ -29,7 +29,7 @@ object Profiler { def report(): Array[String] = { var res = Array[String]() val width = timeEntries.map(_._1.length).max - for ((name, entry) <- timeEntries.iterator.toArray.sortBy(_._1).reverse) { + for ((name, entry) <- timeEntries.iterator.toArray.sortBy(_._1).reverse) { val (p5, p50, p95) = entry.percentiles() res +:= s"${name.padTo(width, ' ')} │ 5% ${formatTime(p5)} │ 50% ${formatTime(p50)} │ 95% ${formatTime(p95)} │ last ${formatTime(entry.lastSample)}" } diff --git a/src/main/scala/ocelot/desktop/util/ReflectionUtils.scala b/src/main/scala/ocelot/desktop/util/ReflectionUtils.scala index bb89169..fd01e24 100644 --- a/src/main/scala/ocelot/desktop/util/ReflectionUtils.scala +++ b/src/main/scala/ocelot/desktop/util/ReflectionUtils.scala @@ -4,8 +4,8 @@ import java.lang.reflect.Constructor import scala.collection.mutable.ArrayBuffer object ReflectionUtils { - /** - * Returns the linearization order of a class. + + /** Returns the linearization order of a class. * * Roughly speaking, it's the order method calls are resolved in. * @@ -27,16 +27,14 @@ object ReflectionUtils { merged.reverseIterator } - /** - * Finds a (most specific) unary constructor of `constructedClass` that accepts `argumentClass` (or its subtype). - */ + /** Finds a (most specific) unary constructor of `constructedClass` that accepts `argumentClass` (or its subtype). */ def findUnaryConstructor[A](constructedClass: Class[A], argumentClass: Class[_]): Option[Constructor[A]] = { try { // happy case: just grab the constructor directly return Some(constructedClass.getConstructor(argumentClass)) } catch { case _: NoSuchMethodException => - // uh-oh, we'll have to try harder... + // uh-oh, we'll have to try harder... } val constructors = constructedClass.getConstructors diff --git a/src/main/scala/ocelot/desktop/util/SettingsData.scala b/src/main/scala/ocelot/desktop/util/SettingsData.scala index cf025c3..a277660 100644 --- a/src/main/scala/ocelot/desktop/util/SettingsData.scala +++ b/src/main/scala/ocelot/desktop/util/SettingsData.scala @@ -9,7 +9,6 @@ class SettingsData { // implementation notes: // this class relies on reflection to implement updateWith // it's assumed all fields that should be copied are declared as **public var** - def this(data: SettingsData) { this() updateWith(data) @@ -60,7 +59,7 @@ class SettingsData { } object SettingsData { - private val Fields = + private val Fields = { universe.typeOf[SettingsData] .decls .filter(_.isTerm) @@ -69,4 +68,5 @@ object SettingsData { // the var itself is private: check setter and getter .filter(v => v.setter.isPublic && v.getter.isPublic) .toList + } } diff --git a/src/main/scala/ocelot/desktop/util/Spritesheet.scala b/src/main/scala/ocelot/desktop/util/Spritesheet.scala index 9c425b3..3e4cf81 100644 --- a/src/main/scala/ocelot/desktop/util/Spritesheet.scala +++ b/src/main/scala/ocelot/desktop/util/Spritesheet.scala @@ -46,7 +46,7 @@ object Spritesheet extends Resource with Logging { split(1).toFloat / resolution.width, split(2).toFloat / resolution.height, split(3).toFloat / resolution.width, - split(4).toFloat / resolution.height + split(4).toFloat / resolution.height, )) } diff --git a/src/main/scala/ocelot/desktop/util/TaskQueue.scala b/src/main/scala/ocelot/desktop/util/TaskQueue.scala index a64ef6d..0eb1bb6 100644 --- a/src/main/scala/ocelot/desktop/util/TaskQueue.scala +++ b/src/main/scala/ocelot/desktop/util/TaskQueue.scala @@ -2,10 +2,9 @@ package ocelot.desktop.util import java.util.concurrent.LinkedBlockingQueue -/** - * A thread-safe queue of tasks that should be run in owner thread. - * Works the same way as Platform.runLater() from JavaFX. - */ +/** A thread-safe queue of tasks that should be run in owner thread. + * Works the same way as Platform.runLater() from JavaFX. + */ class TaskQueue { private val queue = new LinkedBlockingQueue[() => Unit]() diff --git a/src/main/scala/ocelot/desktop/util/Transaction.scala b/src/main/scala/ocelot/desktop/util/Transaction.scala index e2160ee..d1afe97 100644 --- a/src/main/scala/ocelot/desktop/util/Transaction.scala +++ b/src/main/scala/ocelot/desktop/util/Transaction.scala @@ -2,7 +2,7 @@ package ocelot.desktop.util import scala.collection.mutable.ArrayBuffer -class Transaction protected() { +class Transaction protected () { private val cleanupCallbacks = ArrayBuffer.empty[() => Unit] def onFailure(f: => Unit): Unit = { @@ -26,7 +26,7 @@ class Transaction protected() { object Transaction { private[Transaction] case class AbortedException(tx: AbortableTransaction) extends RuntimeException - class AbortableTransaction protected[Transaction]() extends Transaction { + class AbortableTransaction protected[Transaction] () extends Transaction { def abort(): Nothing = { throw Transaction.AbortedException(this) } diff --git a/src/main/scala/ocelot/desktop/util/WebcamCapture.scala b/src/main/scala/ocelot/desktop/util/WebcamCapture.scala index d5558ed..fddba96 100644 --- a/src/main/scala/ocelot/desktop/util/WebcamCapture.scala +++ b/src/main/scala/ocelot/desktop/util/WebcamCapture.scala @@ -60,20 +60,17 @@ class WebcamCapture(private val webcam: Webcam) extends Thread(s"WebcamCaptureTh synchronized { wait() } - } - - else { + } else { webcam.open() val image = Option(webcam.getImage) synchronized { - frame = image + frame = image } Thread.sleep(WebcamCapture.FrameTimeout.toMillis) } - } - catch { + } catch { case _: InterruptedException => interrupt() } } @@ -95,10 +92,11 @@ class WebcamCapture(private val webcam: Webcam) extends Thread(s"WebcamCaptureTh val frameX = clampedX * (frame.get.getWidth - 1).toFloat val frameY = clampedY * (frame.get.getHeight - 1).toFloat val color = new Color(frame.get.getRGB(frameX.toInt, frameY.toInt)) - val normalizedDistance = - 0.2126f * WebcamCapture.toLinear(color.getRed ) + - 0.7152f * WebcamCapture.toLinear(color.getGreen) + - 0.0722f * WebcamCapture.toLinear(color.getBlue ) + val normalizedDistance = { + 0.2126f * WebcamCapture.toLinear(color.getRed) + + 0.7152f * WebcamCapture.toLinear(color.getGreen) + + 0.0722f * WebcamCapture.toLinear(color.getBlue) + } WebcamCapture.MaxDistance * (1f - normalizedDistance) } diff --git a/src/main/scala/ocelot/desktop/windows/CameraWindow.scala b/src/main/scala/ocelot/desktop/windows/CameraWindow.scala index 4a2be2d..9ab9764 100644 --- a/src/main/scala/ocelot/desktop/windows/CameraWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/CameraWindow.scala @@ -21,36 +21,48 @@ class CameraWindow(cameraNode: CameraNode) extends PanelWindow { setInner(new Widget { override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= new PaddingBox(new Button { - override def minimumSize: Size2D = super.minimumSize.copy(width = 256) - override def maximumSize: Size2D = super.maximumSize.copy(width = 512) - override def text: String = camera.webcamCapture.map(_.name).getOrElse("") + children :+= new PaddingBox( + new Button { + override def minimumSize: Size2D = super.minimumSize.copy(width = 256) + override def maximumSize: Size2D = super.maximumSize.copy(width = 512) + override def text: String = camera.webcamCapture.map(_.name).getOrElse("") - override def onClick(): Unit = { - val menu = new ContextMenu - for (webcam <- Webcam.getWebcams().asScala) { - menu.addEntry(ContextMenuEntry(webcam.getName) { - cameraNode.camera.webcamCapture = WebcamCapture.getInstance(webcam) - }) + override def onClick(): Unit = { + val menu = new ContextMenu + for (webcam <- Webcam.getWebcams().asScala) { + menu.addEntry(ContextMenuEntry(webcam.getName) { + cameraNode.camera.webcamCapture = WebcamCapture.getInstance(webcam) + }) + } + + root.get.contextMenus.open(menu, Vector2D(position.x, position.y + size.height)) } + }, + Padding2D.equal(8), + ) - root.get.contextMenus.open(menu, Vector2D(position.x, position.y + size.height)) - } - }, Padding2D.equal(8)) + children :+= new PaddingBox( + new Checkbox("Flip image horizontally", + initialValue = camera.flipHorizontally) { + override def onValueChanged(newValue: Boolean): Unit = camera.flipHorizontally = newValue + }, + Padding2D.equal(8), + ) - children :+= new PaddingBox(new Checkbox("Flip image horizontally", - initialValue = camera.flipHorizontally) { - override def onValueChanged(newValue: Boolean): Unit = camera.flipHorizontally = newValue - }, Padding2D.equal(8)) + children :+= new PaddingBox( + new Checkbox("Flip image vertically", + initialValue = camera.flipVertically) { + override def onValueChanged(newValue: Boolean): Unit = camera.flipVertically = newValue + }, + Padding2D.equal(8), + ) - children :+= new PaddingBox(new Checkbox("Flip image vertically", - initialValue = camera.flipVertically) { - override def onValueChanged(newValue: Boolean): Unit = camera.flipVertically = newValue - }, Padding2D.equal(8)) - - children :+= new PaddingBox(new Checkbox("Unlimit call budget", - initialValue = camera.directCalls) { - override def onValueChanged(newValue: Boolean): Unit = camera.directCalls = newValue - }, Padding2D.equal(8)) + children :+= new PaddingBox( + new Checkbox("Unlimit call budget", + initialValue = camera.directCalls) { + override def onValueChanged(newValue: Boolean): Unit = camera.directCalls = newValue + }, + Padding2D.equal(8), + ) }) } diff --git a/src/main/scala/ocelot/desktop/windows/ComputerWindow.scala b/src/main/scala/ocelot/desktop/windows/ComputerWindow.scala index eae66ef..baacfb6 100644 --- a/src/main/scala/ocelot/desktop/windows/ComputerWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/ComputerWindow.scala @@ -48,91 +48,104 @@ class ComputerWindow(computerAware: ComputerAware) extends BasicWindow { override def minimumSize: Size2D = Size2D.Zero - children :+= new PaddingBox(new Widget { - children :+= new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - class PerTickHistogram extends Histogram with TickUpdatable { - override def minimumSize: Size2D = Size2D(windowWidth(), 70) - override def maximumSize: Size2D = minimumSize + class PerTickHistogram extends Histogram with TickUpdatable { + override def minimumSize: Size2D = Size2D(windowWidth(), 70) + override def maximumSize: Size2D = minimumSize - def historySize: Int = 200 + def historySize: Int = 200 - def appendHistoryValue(value: Float): Unit = { - if (history.length > historySize) { - history.remove(0) + def appendHistoryValue(value: Float): Unit = { + if (history.length > historySize) { + history.remove(0) + } + + history.append(value) + } + + def reset(): Unit = { + value = "N/A" + history.clear() + } + + override def tickUpdate(): Unit = { + super.tickUpdate() + if (!computerAware.computer.machine.isRunning) reset() + } } - history.append(value) - } + children :+= new ComponentUsageBar { + override def minimumSize: Size2D = Size2D(windowWidth(), 34) + override def maximumSize: Size2D = minimumSize + override def tickUpdate(): Unit = { + super.tickUpdate() + maxValue = computerAware.computer.machine.maxComponents + currentValue = computerAware.computer.machine.componentCount + } + } - def reset(): Unit = { - value = "N/A" - history.clear() - } + children :+= new PerTickHistogram { + title = "Memory usage" - override def tickUpdate(): Unit = { - super.tickUpdate() - if (!computerAware.computer.machine.isRunning) reset() - } + override def tickUpdate(): Unit = { + super.tickUpdate() + val (free, total) = computerAware.computer.machine.latestMemoryUsage + val used = total - free + + val ratio = if (total == 0) 0 else used.toFloat / total.toFloat + + value = f"${used.toFloat / 1024f / 1024f}%.1fM" + appendHistoryValue(ratio) + } + } + + children :+= new PaddingBox( + new PerTickHistogram { + title = "CPU usage" + + override def tickUpdate(): Unit = { + super.tickUpdate() + val (start, _end) = computerAware.computer.machine.latestExecutionInfo + val end = if (start < _end) _end else System.nanoTime() + val cpuUsage = if (start == 0) 0 + else ((end - start).toFloat / 1000000000f * OcelotDesktop.tpsCounter.fps).min(1f) + value = f"${cpuUsage * 100}%.0f%%" + appendHistoryValue(cpuUsage) + } + }, + Padding2D(top = 8), + ) + + children :+= new PaddingBox( + new PerTickHistogram { + title = "Call budget usage" + + override def tickUpdate(): Unit = { + super.tickUpdate() + val (budget, maxBudget) = computerAware.computer.machine.latestCallBudget + value = f"${maxBudget - budget}%.1f" + appendHistoryValue((1.0 - budget / maxBudget).toFloat) + } + }, + Padding2D(top = 8), + ) + }, + Padding2D.equal(7), + ) + + override def draw(g: Graphics): Unit = { + DrawUtils.panel(g, position.x, position.y, width, height) + + super.draw(g) } - - children :+= new ComponentUsageBar { - override def minimumSize: Size2D = Size2D(windowWidth(), 34) - override def maximumSize: Size2D = minimumSize - override def tickUpdate(): Unit = { - super.tickUpdate() - maxValue = computerAware.computer.machine.maxComponents - currentValue = computerAware.computer.machine.componentCount - } - } - - children :+= new PerTickHistogram { - title = "Memory usage" - - override def tickUpdate(): Unit = { - super.tickUpdate() - val (free, total) = computerAware.computer.machine.latestMemoryUsage - val used = total - free - - val ratio = if (total == 0) 0 else used.toFloat / total.toFloat - - value = f"${used.toFloat / 1024f / 1024f}%.1fM" - appendHistoryValue(ratio) - } - } - - children :+= new PaddingBox(new PerTickHistogram { - title = "CPU usage" - - override def tickUpdate(): Unit = { - super.tickUpdate() - val (start, _end) = computerAware.computer.machine.latestExecutionInfo - val end = if (start < _end) _end else System.nanoTime() - val cpuUsage = if (start == 0) 0 else ((end - start).toFloat / 1000000000f * OcelotDesktop.tpsCounter.fps).min(1f) - value = f"${cpuUsage * 100}%.0f%%" - appendHistoryValue(cpuUsage) - } - }, Padding2D(top = 8)) - - children :+= new PaddingBox(new PerTickHistogram { - title = "Call budget usage" - - override def tickUpdate(): Unit = { - super.tickUpdate() - val (budget, maxBudget) = computerAware.computer.machine.latestCallBudget - value = f"${maxBudget - budget}%.1f" - appendHistoryValue((1.0 - budget / maxBudget).toFloat) - } - }, Padding2D(top = 8)) - }, Padding2D.equal(7)) - - override def draw(g: Graphics): Unit = { - DrawUtils.panel(g, position.x, position.y, width, height) - - super.draw(g) - } - }, Padding2D(10, 12, 0, 12)) + }, + Padding2D(10, 12, 0, 12), + ) override def draw(g: Graphics): Unit = { if (height < 1) @@ -144,137 +157,145 @@ class ComputerWindow(computerAware: ComputerAware) extends BasicWindow { } } - children :+= new PaddingBox(new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - children :+= new PaddingBox( - new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) - // Title bar - children :+= new PaddingBox(new TitleBar(ComputerWindow.this) { - override def title: String = { - val name = computerAware.computerType match { - case ComputerType.Server => "Server" - case ComputerType.Microcontroller => "Microcontroller" - case _ => "Computer" - } - - s"$name ${computerAware.computer.machine.node.address}" - } - - override def titleMaxLength: Int = computerAware.computerType match { - case ComputerType.Server => 35 - case ComputerType.Microcontroller => 24 - case _ => 27 - } - }, Padding2D(bottom = 8)) - - children :+= new Widget { - // Drawer button - children :+= new PaddingBox(drawerButton, Padding2D(top = if (isServerMachineType) 134 else 120)) - - // EEPROM & power button + // Title bar children :+= new PaddingBox( - new Widget { - // Microcontrollers have different EEPROM location - if (computerAware.computerType != ComputerType.Microcontroller) - children :+= new PaddingBox(computerAware.eepromSlot, Padding2D(right = 10)) - - // Power button - children :+= new IconButton( - "buttons/PowerOff", - "buttons/PowerOn", - mode = IconButton.Mode.Switch, - sizeMultiplier = 2, - model = IconButton.ReadOnlyModel(computerAware.computer.machine.isRunning), - ) with HoverHighlight { - override def enabled: Boolean = !isServerMachineType || computerAware.asInstanceOf[ServerItem].isInRack - - override def draw(g: Graphics): Unit = { - if (enabled) { - super.draw(g) - } + new TitleBar(ComputerWindow.this) { + override def title: String = { + val name = computerAware.computerType match { + case ComputerType.Server => "Server" + case ComputerType.Microcontroller => "Microcontroller" + case _ => "Computer" } - override def onPressed(): Unit = computerAware.turnOn() + s"$name ${computerAware.computer.machine.node.address}" + } - override def onReleased(): Unit = computerAware.turnOff() - - protected override def clickSoundSource: ClickSoundSource = SoundSource.MinecraftClick + override def titleMaxLength: Int = computerAware.computerType match { + case ComputerType.Server => 35 + case ComputerType.Microcontroller => 24 + case _ => 27 } }, - Padding2D( - top = if (isServerMachineType) 58 else 44, - left = 22, - right = if (isServerMachineType) 10 else 0 - ) + Padding2D(bottom = 8), ) - // Motherboard - children :+= { - // Slots order - val rows = computerAware.computerType match { - case ComputerType.Server => Array( - (8, computerAware.cardSlots), - (12, Array(computerAware.cpuSlot) ++ computerAware.componentBusSlots), - (12, computerAware.memorySlots), - (12, computerAware.diskSlots) - ) - case ComputerType.Microcontroller => Array( - (19, computerAware.cardSlots), - (8, Array(computerAware.cpuSlot) ++ computerAware.memorySlots), - (8, Array(computerAware.eepromSlot)) - ) - case _ => Array( - (19, computerAware.cardSlots), - (8, Array(computerAware.cpuSlot) ++ computerAware.memorySlots), - (8, computerAware.diskSlots ++ computerAware.floppySlot.toArray) - ) - } + children :+= new Widget { + // Drawer button + children :+= new PaddingBox(drawerButton, Padding2D(top = if (isServerMachineType) 134 else 120)) - // Slot widgets - new Widget { - for ((padding, row) <- rows) { - children :+= new PaddingBox( - new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical) + // EEPROM & power button + children :+= new PaddingBox( + new Widget { + // Microcontrollers have different EEPROM location + if (computerAware.computerType != ComputerType.Microcontroller) + children :+= new PaddingBox(computerAware.eepromSlot, Padding2D(right = 10)) - for (slot <- row) - children :+= slot - }, - Padding2D( - left = padding.toFloat, - top = if (isServerMachineType) 4 else 8 + // Power button + children :+= new IconButton( + "buttons/PowerOff", + "buttons/PowerOn", + mode = IconButton.Mode.Switch, + sizeMultiplier = 2, + model = IconButton.ReadOnlyModel(computerAware.computer.machine.isRunning), + ) with HoverHighlight { + override def enabled: Boolean = + !isServerMachineType || computerAware.asInstanceOf[ServerItem].isInRack + + override def draw(g: Graphics): Unit = { + if (enabled) { + super.draw(g) + } + } + + override def onPressed(): Unit = computerAware.turnOn() + + override def onReleased(): Unit = computerAware.turnOff() + + override protected def clickSoundSource: ClickSoundSource = SoundSource.MinecraftClick + } + }, + Padding2D( + top = if (isServerMachineType) 58 else 44, + left = 22, + right = if (isServerMachineType) 10 else 0, + ), + ) + + // Motherboard + children :+= { + // Slots order + val rows = computerAware.computerType match { + case ComputerType.Server => Array( + (8, computerAware.cardSlots), + (12, Array(computerAware.cpuSlot) ++ computerAware.componentBusSlots), + (12, computerAware.memorySlots), + (12, computerAware.diskSlots), + ) + case ComputerType.Microcontroller => Array( + (19, computerAware.cardSlots), + (8, Array(computerAware.cpuSlot) ++ computerAware.memorySlots), + (8, Array(computerAware.eepromSlot)), + ) + case _ => Array( + (19, computerAware.cardSlots), + (8, Array(computerAware.cpuSlot) ++ computerAware.memorySlots), + (8, computerAware.diskSlots ++ computerAware.floppySlot.toArray), ) - ) } - override def minimumSize: Size2D = computerAware.computerType match { - case ComputerType.Server => Size2D(200, 156) - case _ => Size2D(158, 140) - } + // Slot widgets + new Widget { + for ((padding, row) <- rows) { + children :+= new PaddingBox( + new Widget { + override protected val layout: Layout = + new LinearLayout(this, orientation = Orientation.Vertical) - override def draw(g: Graphics): Unit = { - // Background image - g.sprite( - s"window/${if (isServerMachineType) "rack" else "case"}/Motherboard", - position.x, - position.y, - width, - height - ) + for (slot <- row) + children :+= slot + }, + Padding2D( + left = padding.toFloat, + top = if (isServerMachineType) 4 else 8, + ), + ) + } - drawChildren(g) + override def minimumSize: Size2D = computerAware.computerType match { + case ComputerType.Server => Size2D(200, 156) + case _ => Size2D(158, 140) + } + + override def draw(g: Graphics): Unit = { + // Background image + g.sprite( + s"window/${if (isServerMachineType) "rack" else "case"}/Motherboard", + position.x, + position.y, + width, + height, + ) + + drawChildren(g) + } } } } - } - }, - Padding2D(8, 12, 0, 12) - ) - children :+= bottomDrawer - }, Padding2D(bottom = 10)) + }, + Padding2D(8, 12, 0, 12), + ) + children :+= bottomDrawer + }, + Padding2D(bottom = 10), + ) children } diff --git a/src/main/scala/ocelot/desktop/windows/HologramProjectorWindow.scala b/src/main/scala/ocelot/desktop/windows/HologramProjectorWindow.scala index 662b4ca..9699996 100644 --- a/src/main/scala/ocelot/desktop/windows/HologramProjectorWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/HologramProjectorWindow.scala @@ -24,14 +24,19 @@ object HologramProjectorWindow { val spriteSide = "blocks/HologramProjectorSide" builder.cuboid( - Vector3D(4, 0, 4), Vector3D(12, 3, 12), - left = None, right = None, front = None, back = None, + Vector3D(4, 0, 4), + Vector3D(12, 3, 12), + left = None, + right = None, + front = None, + back = None, top = Some((spriteTop, Rect2D(4, 4, 8, 8))), bottom = Some((spriteBottom, Rect2D(4, 4, 8, 8))), ) builder.cuboid( - Vector3D(0, 0, 0), Vector3D(2, 7, 16), + Vector3D(0, 0, 0), + Vector3D(2, 7, 16), top = Some((spriteTop, Rect2D(0, 0, 2, 16))), bottom = Some((spriteBottom, Rect2D(0, 0, 2, 16))), front = Some((spriteSide, Rect2D(2, 9, -2, 7))), @@ -41,7 +46,8 @@ object HologramProjectorWindow { ) builder.cuboid( - Vector3D(14, 0, 0), Vector3D(16, 7, 16), + Vector3D(14, 0, 0), + Vector3D(16, 7, 16), top = Some((spriteTop, Rect2D(14, 0, 2, 16))), bottom = Some((spriteBottom, Rect2D(14, 0, 2, 16))), front = Some((spriteSide, Rect2D(0, 9, 2, 7))), @@ -51,8 +57,10 @@ object HologramProjectorWindow { ) builder.cuboid( - Vector3D(2, 0, 0), Vector3D(14, 7, 2), - left = None, right = None, + Vector3D(2, 0, 0), + Vector3D(14, 7, 2), + left = None, + right = None, top = Some((spriteTop, Rect2D(2, 0, 12, 2))), bottom = Some((spriteBottom, Rect2D(2, 2, 12, -2))), front = Some((spriteSide, Rect2D(2, 9, 12, 7))), @@ -60,8 +68,10 @@ object HologramProjectorWindow { ) builder.cuboid( - Vector3D(2, 0, 14), Vector3D(14, 7, 16), - left = None, right = None, + Vector3D(2, 0, 14), + Vector3D(14, 7, 16), + left = None, + right = None, top = Some((spriteTop, Rect2D(2, 14, 12, 2))), bottom = Some((spriteBottom, Rect2D(2, 16, 12, -2))), front = Some((spriteSide, Rect2D(2, 9, 12, 7))), @@ -69,32 +79,44 @@ object HologramProjectorWindow { ) builder.cuboid( - Vector3D(2, 0, 2), Vector3D(4, 5, 14), - front = None, back = None, left = None, + Vector3D(2, 0, 2), + Vector3D(4, 5, 14), + front = None, + back = None, + left = None, top = Some((spriteTop, Rect2D(2, 2, 2, 12))), bottom = Some((spriteBottom, Rect2D(2, 2, 2, 12))), right = Some((spriteSide, Rect2D(2, 16, 12, -5))), ) builder.cuboid( - Vector3D(12, 0, 2), Vector3D(14, 5, 14), - front = None, back = None, right = None, + Vector3D(12, 0, 2), + Vector3D(14, 5, 14), + front = None, + back = None, + right = None, top = Some((spriteTop, Rect2D(12, 2, 2, 12))), bottom = Some((spriteBottom, Rect2D(12, 2, 2, 12))), left = Some((spriteSide, Rect2D(2, 16, 12, -5))), ) builder.cuboid( - Vector3D(4, 0, 2), Vector3D(12, 5, 4), - left = None, right = None, front = None, + Vector3D(4, 0, 2), + Vector3D(12, 5, 4), + left = None, + right = None, + front = None, top = Some((spriteTop, Rect2D(4, 2, 8, 2))), bottom = Some((spriteBottom, Rect2D(4, 2, 8, 2))), back = Some((spriteSide, Rect2D(4, 16, 8, -5))), ) builder.cuboid( - Vector3D(4, 0, 12), Vector3D(12, 5, 14), - left = None, right = None, back = None, + Vector3D(4, 0, 12), + Vector3D(12, 5, 14), + left = None, + right = None, + back = None, top = Some((spriteTop, Rect2D(4, 12, 8, 2))), bottom = Some((spriteBottom, Rect2D(4, 12, 8, 2))), front = Some((spriteSide, Rect2D(4, 16, 8, -5))), @@ -116,7 +138,8 @@ class HologramProjectorWindow(val hologramProjectorNode: HologramProjectorNode) super.setupToolbar(toolbar) toolbar.children :+= new IconButton( - "icons/GridOff", "icons/Grid", + "icons/GridOff", + "icons/Grid", pressedColor = Color.White.withAlpha(0.5f), releasedColor = Color.White.withAlpha(0.2f), mode = IconButton.Mode.Switch, @@ -149,22 +172,24 @@ class HologramProjectorWindow(val hologramProjectorNode: HologramProjectorNode) mesh.foreach(mesh => { val workspace = hologram.workspace - val subTick = (System.nanoTime() - workspace.getLastTickNanoTime).toFloat / 1e9f / OcelotDesktop.tpsCounter.dt.max(1e-9f) + val subTick = + (System.nanoTime() - workspace.getLastTickNanoTime).toFloat / 1e9f / OcelotDesktop.tpsCounter.dt.max(1e-9f) val time = workspace.getIngameTime + subTick.clamp(0, 1) var transform = Transform3D.translate(0.5f, 0.5f, 0.5f) * Transform3D.rotate( - Vector3D(hologram.rotationX, hologram.rotationY, hologram.rotationZ), hologram.rotationAngle.toRadians + Vector3D(hologram.rotationX, hologram.rotationY, hologram.rotationZ), + hologram.rotationAngle.toRadians, ) * Transform3D.rotate( Vector3D(hologram.rotationSpeedX, hologram.rotationSpeedY, hologram.rotationSpeedZ), - (hologram.rotationSpeed * (time % (360 * 20 - 1)) / 20f).toRadians + (hologram.rotationSpeed * (time % (360 * 20 - 1)) / 20f).toRadians, ) * Transform3D.scale(1.001f) * Transform3D.translate( (hologram.translationX * hologram.width / 16f - 1.5f) * hologram.scale, hologram.translationY * hologram.height / 16f * hologram.scale, - (hologram.translationZ * hologram.width / 16f - 1.5f) * hologram.scale + (hologram.translationZ * hologram.width / 16f - 1.5f) * hologram.scale, ) val hologramFlickerFrequency = Settings.get.hologramFlickerFrequency @@ -174,12 +199,12 @@ class HologramProjectorWindow(val hologramProjectorNode: HologramProjectorNode) transform *= Transform3D.scale(Vector3D( 1 + random.nextGaussian() * 0.01, 1 + random.nextGaussian() * 0.001, - 1 + random.nextGaussian() * 0.01 + 1 + random.nextGaussian() * 0.01, )) transform *= Transform3D.translate(Vector3D( random.nextGaussian() * 0.01, random.nextGaussian() * 0.01, - random.nextGaussian() * 0.01 + random.nextGaussian() * 0.01, )) } @@ -244,7 +269,7 @@ class HologramProjectorWindow(val hologramProjectorNode: HologramProjectorNode) top = face.filter(_ => isEmpty(x, y + 1, z)), bottom = face.filter(_ => isEmpty(x, y - 1, z)), front = face.filter(_ => isEmpty(x, y, z - 1)), - back = face.filter(_ => isEmpty(x, y, z + 1)) + back = face.filter(_ => isEmpty(x, y, z + 1)), ) } } diff --git a/src/main/scala/ocelot/desktop/windows/OcelotInterfaceWindow.scala b/src/main/scala/ocelot/desktop/windows/OcelotInterfaceWindow.scala index 483ad49..39aa839 100644 --- a/src/main/scala/ocelot/desktop/windows/OcelotInterfaceWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/OcelotInterfaceWindow.scala @@ -42,7 +42,7 @@ class OcelotInterfaceWindow(storage: OcelotInterfaceLogStorage) extends PanelWin override def maximumSize: Size2D = minimumSize }, - Padding2D(right = 12) + Padding2D(right = 12), ) children :+= new TextInput(storage.messageLimit.toString) { diff --git a/src/main/scala/ocelot/desktop/windows/OpenFMRadioWindow.scala b/src/main/scala/ocelot/desktop/windows/OpenFMRadioWindow.scala index 2c0b3a0..0567389 100644 --- a/src/main/scala/ocelot/desktop/windows/OpenFMRadioWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/OpenFMRadioWindow.scala @@ -39,7 +39,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { radio.volDown() } }, - Padding2D(0, 0, 0, x) + Padding2D(0, 0, 0, x), ) } @@ -52,7 +52,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { override def text: String = (radio.volume * 10).floor.toInt.toString override def color: Color = Color.White }, - Padding2D(2, 0, 0, 20) + Padding2D(2, 0, 0, 20), ) addVolumeUpOrDownButton(isUp = true, 8) @@ -66,7 +66,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { sizeMultiplier = scale, model = new IconButton.Model { override var pressed: Boolean = radio.isListenRedstone }, ), - Padding2D(0, 0, 0, 128) + Padding2D(0, 0, 0, 128), ) // Close button @@ -74,14 +74,14 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { new IconButton( "buttons/OpenFMRadioCloseOff", "buttons/OpenFMRadioCloseOn", - sizeMultiplier = scale + sizeMultiplier = scale, ) { override def onPressed(): Unit = close() }, - Padding2D(0, 0, 0, 10) + Padding2D(0, 0, 0, 10), ) }, - Padding2D(8, 0, 0, 188) + Padding2D(8, 0, 0, 188), ) // Url text input @@ -95,7 +95,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { radio.url = Option(text) } }, - Padding2D(5, 0, 0, 32) + Padding2D(5, 0, 0, 32), ) // Start/stop button @@ -110,7 +110,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { override def onPressed(): Unit = radio.play() override def onReleased(): Unit = radio.stop() }, - Padding2D(13, 0, 0, 208) + Padding2D(13, 0, 0, 208), ) // Color / text titles @@ -131,7 +131,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { override def color: Color = Color.White } }, - Padding2D(10, 0, 0, 30) + Padding2D(10, 0, 0, 30), ) // Color / text text inputs @@ -154,8 +154,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { try { Integer.parseInt(text, 16) true - } - catch { + } catch { case _: Throwable => false } } @@ -172,7 +171,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { } } }, - Padding2D(1, 0, 0, 30) + Padding2D(1, 0, 0, 30), ) // OpenFM logo @@ -181,7 +180,7 @@ class OpenFMRadioWindow(radioNode: OpenFMRadioNode) extends BasicWindow { override def text: String = "OpenFM" override def color: Color = Color.White }, - Padding2D(22, 0, 0, 210) + Padding2D(22, 0, 0, 210), ) override def draw(g: Graphics): Unit = { diff --git a/src/main/scala/ocelot/desktop/windows/RackWindow.scala b/src/main/scala/ocelot/desktop/windows/RackWindow.scala index 21d8bd7..80f7caa 100644 --- a/src/main/scala/ocelot/desktop/windows/RackWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/RackWindow.scala @@ -33,7 +33,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { case _ => "Left" }) - private def shouldConnectionBeVisible(slotWidget: RackMountableSlotWidget, connectableIndex: Int) = + private def shouldConnectionBeVisible(slotWidget: RackMountableSlotWidget, connectableIndex: Int) = { connectableIndex == 0 || ( slotWidget.item match { @@ -44,10 +44,12 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { case _ => false } ) - + } + override protected def title: String = "Rack" - private val mountableSlotWidgets: Array[RackMountableSlotWidget] = new Array[RackMountableSlotWidget](rackNode.rack.getSizeInventory) + private val mountableSlotWidgets: Array[RackMountableSlotWidget] = + new Array[RackMountableSlotWidget](rackNode.rack.getSizeInventory) setInner( new PaddingBox( @@ -68,7 +70,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { children :+= widget } }, - Padding2D(top = 8) + Padding2D(top = 8), ) // Lines & connections @@ -84,7 +86,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { position.x + 12, position.y + 172, 102, - 4 + 4, ) } @@ -94,7 +96,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { position.x + linesMarginLeft, position.y, size.width, - size.height + size.height, ) super.draw(g) @@ -103,7 +105,8 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { // Connection rows children :+= new PaddingBox( new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 10) + override protected val layout: Layout = + new LinearLayout(this, orientation = Orientation.Vertical, gap = 10) for (i <- mountableSlotWidgets.indices) { val mountableIndex = i @@ -136,7 +139,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { position.x, y, 2, - connectionHeight + connectionHeight, ) // Line @@ -152,7 +155,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { case Direction.Right => nodeButtonsGap * 4 + nodeButtonsWidth * 3 case _ => nodeButtonsGap * 5 + nodeButtonsWidth * 4 }, - connectionHeight + connectionHeight, ) } } @@ -170,18 +173,20 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { def addSideButtons(direction: Direction): Unit = { children :+= new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = linesGap) + override protected val layout: Layout = + new LinearLayout(this, orientation = Orientation.Vertical, gap = linesGap) for (i <- 0 until 4) { val connectableIndex = i val isNetwork = connectableIndex > 0 children :+= new Button { - override def enabled: Boolean = shouldConnectionBeVisible(mountableSlotWidget, connectableIndex) + override def enabled: Boolean = + shouldConnectionBeVisible(mountableSlotWidget, connectableIndex) override def minimumSize: Size2D = Size2D( nodeButtonsWidth, - if (isNetwork) lineNetworkHeight else lineSideHeight + if (isNetwork) lineNetworkHeight else lineSideHeight, ) override def maximumSize: Size2D = minimumSize @@ -197,7 +202,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { None // Connecting normally else - Some(direction) + Some(direction), ) } @@ -205,7 +210,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { if (enabled) { g.sprite( directionToSpriteName("window/rack/Node", direction), - bounds + bounds, ) } } @@ -220,12 +225,12 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { addSideButtons(Direction.Right) addSideButtons(Direction.Left) }, - Padding2D(left = 14) + Padding2D(left = 14), ) } } }, - Padding2D(10) + Padding2D(10), ) } @@ -239,7 +244,7 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { new Label { override def text: String = data }, - Padding2D(left = 20, bottom = 6) + Padding2D(left = 20, bottom = 6), ) } @@ -279,20 +284,20 @@ class RackWindow(rackNode: RackNode) extends PanelWindow { g.text(x, y, text) } - protected override def clickSoundSource: ClickSoundSource = SoundSource.MinecraftClick + override protected def clickSoundSource: ClickSoundSource = SoundSource.MinecraftClick }, - Padding2D(left = -15, top = 45) + Padding2D(left = -15, top = 45), ) }, - Padding2D(top = 3) + Padding2D(top = 3), ) }, Padding2D( top = 8, right = 8, bottom = 8, - left = 8 - ) + left = 8, + ), ) ) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/windows/RaidWindow.scala b/src/main/scala/ocelot/desktop/windows/RaidWindow.scala index 08556bb..02544a5 100644 --- a/src/main/scala/ocelot/desktop/windows/RaidWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/RaidWindow.scala @@ -26,7 +26,7 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { this, orientation = Orientation.Vertical, gap = 10, - alignItems = AlignItems.Start + alignItems = AlignItems.Start, ) // HDD slots & background border @@ -42,7 +42,7 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { position.x, position.y, size.width, - size.height + size.height, ) super.draw(g) @@ -54,7 +54,7 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { override protected val layout: Layout = new LinearLayout( this, orientation = Orientation.Horizontal, - gap = 4 + gap = 4, ) var hddSlotWidget: HddSlotWidget = _ @@ -65,10 +65,10 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { children :+= hddSlotWidget } }, - Padding2D(left = 8, top = 8) + Padding2D(left = 8, top = 8), ) }, - Padding2D(left = 94, top = 10) + Padding2D(left = 94, top = 10), ) // Text under HDDs @@ -77,7 +77,7 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { override protected val layout: Layout = new LinearLayout( this, orientation = Orientation.Vertical, - gap = 2 + gap = 2, ) def addLabel(data: String): Unit = { @@ -90,8 +90,8 @@ class RaidWindow(raidNode: RaidNode) extends PanelWindow { addLabel("Adding a disk wipes it.") addLabel("Removing a disk wipes the raid.") }, - Padding2D(left = 5) + Padding2D(left = 5), ) } ) -} \ No newline at end of file +} diff --git a/src/main/scala/ocelot/desktop/windows/RelayWindow.scala b/src/main/scala/ocelot/desktop/windows/RelayWindow.scala index f295ec9..53bf2fb 100644 --- a/src/main/scala/ocelot/desktop/windows/RelayWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/RelayWindow.scala @@ -119,8 +119,8 @@ class RelayWindow(val node: RelayNode) extends PanelWindow { override def isItemAccepted(factory: ItemFactory): Boolean = { super.isItemAccepted(factory) && - Array(classOf[WirelessNetworkCardItem], classOf[LinkedCardItem]) - .exists(_.isAssignableFrom(factory.itemClass)) + Array(classOf[WirelessNetworkCardItem], classOf[LinkedCardItem]) + .exists(_.isAssignableFrom(factory.itemClass)) } } } diff --git a/src/main/scala/ocelot/desktop/windows/ScreenWindow.scala b/src/main/scala/ocelot/desktop/windows/ScreenWindow.scala index 7af5321..d61a25c 100644 --- a/src/main/scala/ocelot/desktop/windows/ScreenWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/ScreenWindow.scala @@ -47,7 +47,7 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { override def minimumSize: Size2D = Size2D( screenWidth * FontWidth * scaleX + BorderHorizontal, - screenHeight * scaleY * FontHeight + BorderVertical + screenHeight * scaleY * FontHeight + BorderVertical, ) override def receiveScrollEvents: Boolean = true @@ -83,7 +83,9 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { event.consume() } - if (pinButtonBounds.contains(UiHandler.mousePosition) || closeButtonBounds.contains(UiHandler.mousePosition)) { + if ( + pinButtonBounds.contains(UiHandler.mousePosition) || closeButtonBounds.contains(UiHandler.mousePosition) + ) { SoundSource.InterfaceClick.press.play() } @@ -112,7 +114,7 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { screen.mouseScroll(lastMousePos.x, lastMousePos.y, event.offset, OcelotDesktop.player) event.consume() - case event@DragEvent(DragEvent.State.Start, MouseEvent.Button.Left, _) => + case event @ DragEvent(DragEvent.State.Start, MouseEvent.Button.Left, _) => if (scaleDragRegion.contains(event.start)) { scaleDragPoint = Some(event.start) startingWidth = screenWidth * FontWidth * scaleX @@ -140,8 +142,7 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { val highScale = (FontWidth * midScale * uiScale).ceil / FontWidth / uiScale newScale = if (midScale - lowScale > highScale - midScale) highScale else lowScale - } - else { + } else { val newHeight = startingWidth * (screenHeight * FontHeight / screenWidth / FontWidth) - sy val maxHeight = screenHeight * FontHeight var midScale = (newHeight / maxHeight).max(0f) @@ -178,7 +179,7 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { override def fitToCenter(): Unit = { scale = math.min( ((UiHandler.root.width * 0.9f) / (screenWidth * FontWidth + BorderHorizontal)).min(1f).max(0f), - ((UiHandler.root.height * 0.9f) / (screenHeight * FontHeight + BorderVertical)).min(1f).max(0f) + ((UiHandler.root.height * 0.9f) / (screenHeight * FontHeight + BorderVertical)).min(1f).max(0f), ) super.fitToCenter() @@ -197,12 +198,12 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { if (screen.getPrecisionMode) { Vector2D( (p.x - BorderLeft - position.x) / FontWidth / scaleX, - (p.y - BorderTop - position.y) / FontHeight / scaleY + (p.y - BorderTop - position.y) / FontHeight / scaleY, ) } else { Vector2D( math.floor((p.x - BorderLeft - position.x) / FontWidth / scaleX), - math.floor((p.y - BorderTop - position.y) / FontHeight / scaleY) + math.floor((p.y - BorderTop - position.y) / FontHeight / scaleY), ) } } @@ -236,19 +237,26 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { lastMousePos = currentMousePos - if (isFocused && screen.tier > Tier.One) + if (isFocused && screen.tier > Tier.One) { for (button <- MouseEvents.pressedButtons) { screen.mouseDrag(lastMousePos.x, lastMousePos.y, button.id, OcelotDesktop.player) } + } } private def pinButtonBounds: Rect2D = Rect2D( position.x + screenWidth * FontWidth * scaleX - 13, - position.y + 3, 14, 14) + position.y + 3, + 14, + 14, + ) private def closeButtonBounds: Rect2D = Rect2D( position.x + screenWidth * FontWidth * scaleX + 2, - position.y + 3, 15, 14) + position.y + 3, + 15, + 14, + ) override def draw(g: Graphics): Unit = { beginDraw(g) @@ -273,11 +281,10 @@ class ScreenWindow(screenNode: ScreenNode) extends BasicWindow with Logging { MinFilteringMode.LinearMipmapLinear } else { MinFilteringMode.Nearest - } + }, ) - } - else { + } else { g.rect(startX, startY, windowWidth, windowHeight, ColorScheme("ScreenOff")) } diff --git a/src/main/scala/ocelot/desktop/windows/TapeDriveWindow.scala b/src/main/scala/ocelot/desktop/windows/TapeDriveWindow.scala index bf4d610..9be7ff1 100644 --- a/src/main/scala/ocelot/desktop/windows/TapeDriveWindow.scala +++ b/src/main/scala/ocelot/desktop/windows/TapeDriveWindow.scala @@ -27,7 +27,8 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { setInner(new PaddingBox( new Widget { - override protected val layout: Layout = new LinearLayout(this, orientation = Orientation.Vertical, gap = 16, alignItems = AlignItems.Center) + override protected val layout: Layout = + new LinearLayout(this, orientation = Orientation.Vertical, gap = 16, alignItems = AlignItems.Center) // Screen children :+= new Widget { @@ -38,7 +39,7 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { // Screen background g.sprite( "window/tape/Screen", - bounds + bounds, ) // A barely noticeable overlay showing the playback progress @@ -53,7 +54,7 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { position.y + offset, (width - offset * 2) * playedPart, height - offset * 2, - playbackOverlayColor + playbackOverlayColor, ) } @@ -68,8 +69,7 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { if (text.isEmpty) text = "Unnamed tape" - } - else { + } else { g.foreground = Color.Red text = "No tape" } @@ -97,7 +97,7 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { TapeInsert.play() } - override def onItemRemoved(removedItem: TapeItem, replacedBy: Option[TapeItem]): Unit = { + override def onItemRemoved(removedItem: TapeItem, replacedBy: Option[TapeItem]): Unit = { super.onItemRemoved(removedItem, replacedBy) if (!Audio.isDisabled) @@ -112,8 +112,8 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { def addButton( sprite: String, pressedState: TapeDriveState.State, - isToggle: Boolean = true - ): Unit = { + isToggle: Boolean = true, + ): Unit = { children :+= new IconButton( s"window/tape/$sprite", s"window/tape/${sprite}Pressed", @@ -123,15 +123,16 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { IconButton.Mode.Switch else IconButton.Mode.Regular, - model = + model = { if (isToggle) ReadOnlyModel(tapeDriveNode.tapeDrive.state.state == pressedState) else - DefaultModel(false), + DefaultModel(false) + }, ) with HoverHighlight { override def onPressed(): Unit = tapeDriveNode.tapeDrive.state.switchState(pressedState) - protected override def clickSoundSource: ClickSoundSource = TapeButtonSound + override protected def clickSoundSource: ClickSoundSource = TapeButtonSound } } @@ -141,7 +142,7 @@ class TapeDriveWindow(val tapeDriveNode: TapeDriveNode) extends PanelWindow { addButton("Forward", TapeDriveState.State.Forwarding) } }, - Padding2D(top = 10, left = 18) + Padding2D(top = 10, left = 18), )) }