You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.3 KiB

4 years ago
4 years ago
  1. package nova.monadic_sfx.executors
  2. import akka.dispatch.{
  3. DispatcherPrerequisites,
  4. ExecutorServiceFactory,
  5. ExecutorServiceConfigurator
  6. }
  7. import com.typesafe.config.Config
  8. import java.util.concurrent.{
  9. ExecutorService,
  10. AbstractExecutorService,
  11. ThreadFactory,
  12. TimeUnit
  13. }
  14. import java.util.Collections
  15. import javax.swing.SwingUtilities
  16. import javafx.application.Platform
  17. import monix.execution.Scheduler
  18. import scala.concurrent.ExecutionContext
  19. import java.util.concurrent.Executor
  20. // First we wrap invokeLater/runLater as an ExecutorService
  21. trait GUIExecutorService extends AbstractExecutorService {
  22. def execute(command: Runnable): Unit
  23. def shutdown(): Unit = ()
  24. def shutdownNow() = Collections.emptyList[Runnable]
  25. def isShutdown = false
  26. def isTerminated = false
  27. def awaitTermination(l: Long, timeUnit: TimeUnit) = true
  28. }
  29. object JavaFXExecutorService extends GUIExecutorService {
  30. override def execute(command: Runnable) = Platform.runLater(command)
  31. }
  32. object SwingExecutorService extends GUIExecutorService {
  33. override def execute(command: Runnable) = SwingUtilities.invokeLater(command)
  34. }
  35. class JavaFXEventThreadExecutorServiceConfigurator(
  36. config: Config,
  37. prerequisites: DispatcherPrerequisites
  38. ) extends ExecutorServiceConfigurator(config, prerequisites) {
  39. private val f = new ExecutorServiceFactory {
  40. def createExecutorService: ExecutorService = JavaFXExecutorService
  41. }
  42. def createExecutorServiceFactory(
  43. id: String,
  44. threadFactory: ThreadFactory
  45. ): ExecutorServiceFactory = f
  46. }
  47. // Then we create an ExecutorServiceConfigurator so that Akka can use our SwingExecutorService for the dispatchers
  48. class SwingEventThreadExecutorServiceConfigurator(
  49. config: Config,
  50. prerequisites: DispatcherPrerequisites
  51. ) extends ExecutorServiceConfigurator(config, prerequisites) {
  52. private val f = new ExecutorServiceFactory {
  53. def createExecutorService: ExecutorService = SwingExecutorService
  54. }
  55. def createExecutorServiceFactory(
  56. id: String,
  57. threadFactory: ThreadFactory
  58. ): ExecutorServiceFactory = f
  59. }
  60. object JFXExecutionContexts {
  61. val javaFxExecutionContext: ExecutionContext =
  62. ExecutionContext.fromExecutor(new Executor {
  63. def execute(command: Runnable): Unit = {
  64. Platform.runLater(command)
  65. }
  66. })
  67. val fxScheduler =
  68. Scheduler(javaFxExecutionContext)
  69. }