src/Pure/GUI/gui_thread.scala
author wenzelm
Mon, 19 Dec 2022 13:28:58 +0100
changeset 76709 fdbdc573a06b
parent 75393 87ebf5a50283
permissions -rw-r--r--
tuned signature;

/*  Title:      Pure/GUI/gui_thread.scala
    Author:     Makarius

Evaluation within the GUI thread (for AWT/Swing).
*/

package isabelle


import javax.swing.SwingUtilities


object GUI_Thread {
  /* context check */

  def check(): Boolean = SwingUtilities.isEventDispatchThread()

  def assert[A](body: => A): A = {
    Predef.assert(check())
    body
  }

  def require[A](body: => A): A = {
    Predef.require(check(), "GUI thread expected")
    body
  }


  /* event dispatch queue */

  def now[A](body: => A): A = {
    if (check()) body
    else {
      lazy val result = assert { Exn.capture(body) }
      SwingUtilities.invokeAndWait(() => result)
      Exn.release(result)
    }
  }

  def later(body: => Unit): Unit = {
    if (check()) body
    else SwingUtilities.invokeLater(() => body)
  }

  def future[A](body: => A): Future[A] = {
    if (check()) Future.value(body)
    else {
      val promise = Future.promise[A]
      later { promise.fulfill_result(Exn.capture(body)) }
      promise
    }
  }
}