src/Pure/System/session.scala
author wenzelm
Mon Aug 23 16:53:22 2010 +0200 (2010-08-23)
changeset 38639 f642faca303e
parent 38569 9d480f6a2589
child 38722 ba31936497c2
permissions -rw-r--r--
main session actor as independent thread, to avoid starvation via regular worker pool;
tuned;
wenzelm@36676
     1
/*  Title:      Pure/System/session.scala
wenzelm@36676
     2
    Author:     Makarius
wenzelm@38221
     3
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@36676
     4
wenzelm@36676
     5
Isabelle session, potentially with running prover.
wenzelm@36676
     6
*/
wenzelm@34777
     7
wenzelm@34871
     8
package isabelle
wenzelm@34777
     9
wenzelm@34777
    10
wenzelm@34820
    11
import scala.actors.TIMEOUT
wenzelm@38226
    12
import scala.actors.Actor
wenzelm@34777
    13
import scala.actors.Actor._
wenzelm@34777
    14
wenzelm@34815
    15
wenzelm@34791
    16
object Session
wenzelm@34791
    17
{
wenzelm@34813
    18
  /* events */
wenzelm@34813
    19
wenzelm@34791
    20
  case object Global_Settings
wenzelm@37849
    21
  case object Perspective
wenzelm@38360
    22
  case class Commands_Changed(set: Set[Command])
wenzelm@34791
    23
}
wenzelm@34791
    24
wenzelm@34777
    25
wenzelm@34851
    26
class Session(system: Isabelle_System)
wenzelm@34777
    27
{
wenzelm@37849
    28
  /* real time parameters */  // FIXME properties or settings (!?)
wenzelm@37849
    29
wenzelm@37849
    30
  // user input (e.g. text edits, cursor movement)
wenzelm@37849
    31
  val input_delay = 300
wenzelm@37849
    32
wenzelm@37849
    33
  // prover output (markup, common messages)
wenzelm@37849
    34
  val output_delay = 100
wenzelm@37849
    35
wenzelm@37849
    36
  // GUI layout updates
wenzelm@37849
    37
  val update_delay = 500
wenzelm@37849
    38
wenzelm@37849
    39
wenzelm@34809
    40
  /* pervasive event buses */
wenzelm@34809
    41
wenzelm@34809
    42
  val global_settings = new Event_Bus[Session.Global_Settings.type]
wenzelm@38423
    43
  val raw_protocol = new Event_Bus[Isabelle_Process.Result]
wenzelm@37065
    44
  val raw_output = new Event_Bus[Isabelle_Process.Result]
wenzelm@38360
    45
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@37849
    46
  val perspective = new Event_Bus[Session.Perspective.type]
wenzelm@34809
    47
wenzelm@34809
    48
wenzelm@34778
    49
  /* unique ids */
wenzelm@34778
    50
wenzelm@38363
    51
  private var id_count: Document.ID = 0
wenzelm@38419
    52
  def new_id(): Document.ID = synchronized {
wenzelm@38355
    53
    require(id_count > java.lang.Long.MIN_VALUE)
wenzelm@38355
    54
    id_count -= 1
wenzelm@38355
    55
    id_count
wenzelm@38355
    56
  }
wenzelm@34778
    57
wenzelm@34778
    58
wenzelm@34826
    59
wenzelm@34826
    60
  /** main actor **/
wenzelm@34809
    61
wenzelm@34851
    62
  @volatile private var syntax = new Outer_Syntax(system.symbols)
wenzelm@38569
    63
  def current_syntax(): Outer_Syntax = syntax
wenzelm@34809
    64
wenzelm@38370
    65
  @volatile private var global_state = Document.State.init
wenzelm@38370
    66
  private def change_state(f: Document.State => Document.State) { global_state = f(global_state) }
wenzelm@38370
    67
  def current_state(): Document.State = global_state
wenzelm@34816
    68
wenzelm@38221
    69
  private case class Started(timeout: Int, args: List[String])
wenzelm@34777
    70
  private case object Stop
wenzelm@34777
    71
wenzelm@38639
    72
  private val session_actor = Simple_Thread.actor("session_actor", daemon = true)
wenzelm@38639
    73
  {
wenzelm@34809
    74
    var prover: Isabelle_Process with Isar_Document = null
wenzelm@34809
    75
wenzelm@34809
    76
wenzelm@34809
    77
    /* document changes */
wenzelm@34809
    78
wenzelm@38227
    79
    def handle_change(change: Document.Change)
wenzelm@38221
    80
    //{{{
wenzelm@34809
    81
    {
wenzelm@38366
    82
      require(change.is_finished)
wenzelm@34809
    83
wenzelm@38417
    84
      val previous = change.previous.join
wenzelm@38417
    85
      val (node_edits, current) = change.result.join
wenzelm@38366
    86
wenzelm@38417
    87
      var former_assignment = current_state().the_assignment(previous).join
wenzelm@38370
    88
      for {
wenzelm@38370
    89
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
    90
        (prev, None) <- cmd_edits
wenzelm@38417
    91
        removed <- previous.nodes(name).commands.get_after(prev)
wenzelm@38370
    92
      } former_assignment -= removed
wenzelm@38370
    93
wenzelm@38150
    94
      val id_edits =
wenzelm@38150
    95
        node_edits map {
wenzelm@38150
    96
          case (name, None) => (name, None)
wenzelm@38150
    97
          case (name, Some(cmd_edits)) =>
wenzelm@38370
    98
            val ids =
wenzelm@38150
    99
              cmd_edits map {
wenzelm@38150
   100
                case (c1, c2) =>
wenzelm@38150
   101
                  val id1 = c1.map(_.id)
wenzelm@38150
   102
                  val id2 =
wenzelm@38150
   103
                    c2 match {
wenzelm@38150
   104
                      case None => None
wenzelm@38150
   105
                      case Some(command) =>
wenzelm@38370
   106
                        if (current_state().lookup_command(command.id).isEmpty) {
wenzelm@38370
   107
                          change_state(_.define_command(command))
wenzelm@38150
   108
                          prover.define_command(command.id, system.symbols.encode(command.source))
wenzelm@38150
   109
                        }
wenzelm@38150
   110
                        Some(command.id)
wenzelm@38150
   111
                    }
wenzelm@38150
   112
                  (id1, id2)
wenzelm@38150
   113
              }
wenzelm@38370
   114
            (name -> Some(ids))
wenzelm@38150
   115
        }
wenzelm@38417
   116
      change_state(_.define_version(current, former_assignment))
wenzelm@38417
   117
      prover.edit_version(previous.id, current.id, id_edits)
wenzelm@34809
   118
    }
wenzelm@38221
   119
    //}}}
wenzelm@34809
   120
wenzelm@34809
   121
wenzelm@34809
   122
    /* prover results */
wenzelm@34809
   123
wenzelm@34836
   124
    def bad_result(result: Isabelle_Process.Result)
wenzelm@34836
   125
    {
wenzelm@37041
   126
      System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@34836
   127
    }
wenzelm@34836
   128
wenzelm@34809
   129
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   130
    //{{{
wenzelm@34809
   131
    {
wenzelm@38423
   132
      raw_protocol.event(result)
wenzelm@34799
   133
wenzelm@38370
   134
      Position.get_id(result.properties) match {
wenzelm@38414
   135
        case Some(state_id) =>
wenzelm@38370
   136
          try {
wenzelm@38414
   137
            val (st, state) = global_state.accumulate(state_id, result.message)
wenzelm@38370
   138
            global_state = state
wenzelm@38414
   139
            indicate_command_change(st.command)
wenzelm@38370
   140
          }
wenzelm@38414
   141
          catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   142
        case None =>
wenzelm@38370
   143
          if (result.is_status) {
wenzelm@38370
   144
            result.body match {
wenzelm@38417
   145
              case List(Isar_Document.Assign(id, edits)) =>
wenzelm@38417
   146
                try { change_state(_.assign(id, edits)) }
wenzelm@38414
   147
                catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   148
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   149
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@38370
   150
              case _ => if (!result.is_ready) bad_result(result)
wenzelm@38370
   151
            }
wenzelm@38370
   152
          }
wenzelm@38370
   153
          else if (result.kind == Markup.EXIT) prover = null
wenzelm@38370
   154
          else if (result.is_raw) raw_output.event(result)
wenzelm@38370
   155
          else if (!result.is_system) bad_result(result)  // FIXME syslog for system messages (!?)
wenzelm@34809
   156
        }
wenzelm@34809
   157
    }
wenzelm@38221
   158
    //}}}
wenzelm@34809
   159
wenzelm@34820
   160
wenzelm@34820
   161
    /* prover startup */
wenzelm@34820
   162
wenzelm@34820
   163
    def startup_error(): String =
wenzelm@34820
   164
    {
wenzelm@34820
   165
      val buf = new StringBuilder
wenzelm@34820
   166
      while (
wenzelm@34820
   167
        receiveWithin(0) {
wenzelm@34820
   168
          case result: Isabelle_Process.Result =>
wenzelm@34820
   169
            if (result.is_raw) {
wenzelm@34820
   170
              for (text <- XML.content(result.message))
wenzelm@34820
   171
                buf.append(text)
wenzelm@34820
   172
            }
wenzelm@34820
   173
            true
wenzelm@34820
   174
          case TIMEOUT => false
wenzelm@34820
   175
        }) {}
wenzelm@34820
   176
      buf.toString
wenzelm@34820
   177
    }
wenzelm@34820
   178
wenzelm@34820
   179
    def prover_startup(timeout: Int): Option[String] =
wenzelm@34820
   180
    {
wenzelm@34820
   181
      receiveWithin(timeout) {
wenzelm@34820
   182
        case result: Isabelle_Process.Result
wenzelm@37689
   183
          if result.kind == Markup.INIT =>
wenzelm@34820
   184
          while (receive {
wenzelm@34820
   185
            case result: Isabelle_Process.Result =>
wenzelm@34820
   186
              handle_result(result); !result.is_ready
wenzelm@34820
   187
            }) {}
wenzelm@34820
   188
          None
wenzelm@34820
   189
wenzelm@34820
   190
        case result: Isabelle_Process.Result
wenzelm@37689
   191
          if result.kind == Markup.EXIT =>
wenzelm@34820
   192
          Some(startup_error())
wenzelm@34820
   193
wenzelm@34820
   194
        case TIMEOUT =>  // FIXME clarify
wenzelm@34820
   195
          prover.kill; Some(startup_error())
wenzelm@34820
   196
      }
wenzelm@34820
   197
    }
wenzelm@34809
   198
wenzelm@34809
   199
wenzelm@34809
   200
    /* main loop */
wenzelm@34809
   201
wenzelm@38639
   202
    var finished = false
wenzelm@38639
   203
    while (!finished) {
wenzelm@38639
   204
      receive {
wenzelm@38221
   205
        case Started(timeout, args) =>
wenzelm@34777
   206
          if (prover == null) {
wenzelm@34851
   207
            prover = new Isabelle_Process(system, self, args:_*) with Isar_Document
wenzelm@34820
   208
            val origin = sender
wenzelm@34820
   209
            val opt_err = prover_startup(timeout)
wenzelm@34820
   210
            if (opt_err.isDefined) prover = null
wenzelm@34820
   211
            origin ! opt_err
wenzelm@34820
   212
          }
wenzelm@34820
   213
          else reply(None)
wenzelm@34820
   214
wenzelm@38639
   215
        case Stop => // FIXME synchronous!?
wenzelm@34820
   216
          if (prover != null) {
wenzelm@34820
   217
            prover.kill
wenzelm@34820
   218
            prover = null
wenzelm@38639
   219
            finished = true
wenzelm@34777
   220
          }
wenzelm@34777
   221
wenzelm@38227
   222
        case change: Document.Change if prover != null =>
wenzelm@34777
   223
          handle_change(change)
wenzelm@34777
   224
wenzelm@34777
   225
        case result: Isabelle_Process.Result =>
wenzelm@38446
   226
          handle_result(result)
wenzelm@34777
   227
wenzelm@36782
   228
        case TIMEOUT =>  // FIXME clarify!
wenzelm@36782
   229
wenzelm@34820
   230
        case bad if prover != null =>
wenzelm@34777
   231
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   232
      }
wenzelm@34777
   233
    }
wenzelm@34777
   234
  }
wenzelm@34777
   235
wenzelm@34809
   236
wenzelm@37129
   237
wenzelm@38226
   238
  /** buffered command changes (delay_first discipline) **/
wenzelm@37129
   239
wenzelm@38639
   240
  private val command_change_buffer = actor
wenzelm@38221
   241
  //{{{
wenzelm@38221
   242
  {
wenzelm@37129
   243
    import scala.compat.Platform.currentTime
wenzelm@37129
   244
wenzelm@37129
   245
    var changed: Set[Command] = Set()
wenzelm@37129
   246
    var flush_time: Option[Long] = None
wenzelm@37129
   247
wenzelm@37129
   248
    def flush_timeout: Long =
wenzelm@37129
   249
      flush_time match {
wenzelm@37129
   250
        case None => 5000L
wenzelm@37129
   251
        case Some(time) => (time - currentTime) max 0
wenzelm@37129
   252
      }
wenzelm@37129
   253
wenzelm@37129
   254
    def flush()
wenzelm@37129
   255
    {
wenzelm@38360
   256
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@37129
   257
      changed = Set()
wenzelm@37129
   258
      flush_time = None
wenzelm@37129
   259
    }
wenzelm@37129
   260
wenzelm@37129
   261
    def invoke()
wenzelm@37129
   262
    {
wenzelm@37129
   263
      val now = currentTime
wenzelm@37129
   264
      flush_time match {
wenzelm@37849
   265
        case None => flush_time = Some(now + output_delay)
wenzelm@37129
   266
        case Some(time) => if (now >= time) flush()
wenzelm@37129
   267
      }
wenzelm@37129
   268
    }
wenzelm@37129
   269
wenzelm@37129
   270
    loop {
wenzelm@37129
   271
      reactWithin(flush_timeout) {
wenzelm@37129
   272
        case command: Command => changed += command; invoke()
wenzelm@37129
   273
        case TIMEOUT => flush()
wenzelm@37129
   274
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@37129
   275
      }
wenzelm@37129
   276
    }
wenzelm@37129
   277
  }
wenzelm@38221
   278
  //}}}
wenzelm@37129
   279
wenzelm@37129
   280
  def indicate_command_change(command: Command)
wenzelm@37129
   281
  {
wenzelm@37129
   282
    command_change_buffer ! command
wenzelm@37129
   283
  }
wenzelm@37129
   284
wenzelm@37129
   285
wenzelm@38226
   286
wenzelm@38226
   287
  /** editor history **/
wenzelm@38226
   288
wenzelm@38417
   289
  private case class Edit_Version(edits: List[Document.Node_Text_Edit])
wenzelm@38226
   290
wenzelm@38639
   291
  @volatile private var history = Document.History.init
wenzelm@38365
   292
wenzelm@38639
   293
  def snapshot(name: String, pending_edits: List[Text.Edit]): Document.Snapshot =
wenzelm@38639
   294
    history.snapshot(name, pending_edits, current_state())
wenzelm@38226
   295
wenzelm@38639
   296
  private val editor_history = actor
wenzelm@38639
   297
  {
wenzelm@38639
   298
    loop {
wenzelm@38639
   299
      react {
wenzelm@38639
   300
        case Edit_Version(edits) =>
wenzelm@38639
   301
          val prev = history.tip.current
wenzelm@38639
   302
          val result =
wenzelm@38639
   303
            // FIXME potential denial-of-service concerning worker pool (!?!?)
wenzelm@38639
   304
            isabelle.Future.fork {
wenzelm@38639
   305
              val previous = prev.join
wenzelm@38639
   306
              val former_assignment = current_state().the_assignment(previous).join  // FIXME async!?
wenzelm@38639
   307
              Thy_Syntax.text_edits(Session.this, previous, edits)
wenzelm@38639
   308
            }
wenzelm@38639
   309
          val change = new Document.Change(prev, edits, result)
wenzelm@38639
   310
          history += change
wenzelm@38639
   311
          change.current.map(_ => session_actor ! change)
wenzelm@38639
   312
          reply(())
wenzelm@38226
   313
wenzelm@38639
   314
        case bad => System.err.println("editor_model: ignoring bad message " + bad)
wenzelm@38226
   315
      }
wenzelm@38226
   316
    }
wenzelm@38226
   317
  }
wenzelm@38226
   318
wenzelm@38226
   319
wenzelm@38226
   320
wenzelm@38226
   321
  /** main methods **/
wenzelm@34809
   322
wenzelm@38221
   323
  def started(timeout: Int, args: List[String]): Option[String] =
wenzelm@38221
   324
    (session_actor !? Started(timeout, args)).asInstanceOf[Option[String]]
wenzelm@34820
   325
wenzelm@34777
   326
  def stop() { session_actor ! Stop }
wenzelm@38221
   327
wenzelm@38417
   328
  def edit_version(edits: List[Document.Node_Text_Edit]) { editor_history !? Edit_Version(edits) }
wenzelm@34777
   329
}