src/Pure/PIDE/session.scala
author wenzelm
Thu Apr 24 23:13:17 2014 +0200 (2014-04-24)
changeset 56710 8f102c18eab7
parent 56709 e83356e94380
child 56711 ef3d00153e3b
permissions -rw-r--r--
more uniform warning/error handling, potentially with propagation to send_wait caller;
wenzelm@56210
     1
/*  Title:      Pure/PIDE/session.scala
wenzelm@36676
     2
    Author:     Makarius
wenzelm@38221
     3
    Options:    :folding=explicit:collapseFolds=1:
wenzelm@36676
     4
wenzelm@56210
     5
PIDE editor session, potentially with running prover process.
wenzelm@36676
     6
*/
wenzelm@34777
     7
wenzelm@34871
     8
package isabelle
wenzelm@34777
     9
wenzelm@44733
    10
wenzelm@44733
    11
import java.util.{Timer, TimerTask}
wenzelm@34777
    12
wenzelm@44733
    13
import scala.collection.mutable
wenzelm@46771
    14
import scala.collection.immutable.Queue
wenzelm@34777
    15
wenzelm@34815
    16
wenzelm@34791
    17
object Session
wenzelm@34791
    18
{
wenzelm@56315
    19
  /* change */
wenzelm@56315
    20
wenzelm@56315
    21
  sealed case class Change(
wenzelm@56315
    22
    previous: Document.Version,
wenzelm@56315
    23
    doc_blobs: Document.Blobs,
wenzelm@56315
    24
    syntax_changed: Boolean,
wenzelm@56316
    25
    deps_changed: Boolean,
wenzelm@56315
    26
    doc_edits: List[Document.Edit_Command],
wenzelm@56315
    27
    version: Document.Version)
wenzelm@56315
    28
wenzelm@56315
    29
wenzelm@34813
    30
  /* events */
wenzelm@34813
    31
wenzelm@43716
    32
  //{{{
wenzelm@50697
    33
  case class Statistics(props: Properties.T)
wenzelm@50117
    34
  case class Global_Options(options: Options)
wenzelm@44805
    35
  case object Caret_Focus
wenzelm@54521
    36
  case class Raw_Edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52531
    37
  case class Dialog_Result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@47027
    38
  case class Commands_Changed(
wenzelm@47027
    39
    assignment: Boolean, nodes: Set[Document.Node.Name], commands: Set[Command])
wenzelm@39630
    40
wenzelm@39630
    41
  sealed abstract class Phase
wenzelm@39630
    42
  case object Inactive extends Phase
wenzelm@39701
    43
  case object Startup extends Phase  // transient
wenzelm@39701
    44
  case object Failed extends Phase
wenzelm@39630
    45
  case object Ready extends Phase
wenzelm@39701
    46
  case object Shutdown extends Phase  // transient
wenzelm@43716
    47
  //}}}
wenzelm@52111
    48
wenzelm@52111
    49
wenzelm@52111
    50
  /* protocol handlers */
wenzelm@52111
    51
wenzelm@52111
    52
  abstract class Protocol_Handler
wenzelm@52111
    53
  {
wenzelm@52111
    54
    def stop(prover: Prover): Unit = {}
wenzelm@56385
    55
    val functions: Map[String, (Prover, Prover.Protocol_Output) => Boolean]
wenzelm@52111
    56
  }
wenzelm@52111
    57
wenzelm@52111
    58
  class Protocol_Handlers(
wenzelm@52111
    59
    handlers: Map[String, Session.Protocol_Handler] = Map.empty,
wenzelm@56385
    60
    functions: Map[String, Prover.Protocol_Output => Boolean] = Map.empty)
wenzelm@52111
    61
  {
wenzelm@53054
    62
    def get(name: String): Option[Protocol_Handler] = handlers.get(name)
wenzelm@53054
    63
wenzelm@52111
    64
    def add(prover: Prover, name: String): Protocol_Handlers =
wenzelm@52111
    65
    {
wenzelm@52111
    66
      val (handlers1, functions1) =
wenzelm@52111
    67
        handlers.get(name) match {
wenzelm@52111
    68
          case Some(old_handler) =>
wenzelm@52111
    69
            System.err.println("Redefining protocol handler: " + name)
wenzelm@52111
    70
            old_handler.stop(prover)
wenzelm@52111
    71
            (handlers - name, functions -- old_handler.functions.keys)
wenzelm@52111
    72
          case None => (handlers, functions)
wenzelm@52111
    73
        }
wenzelm@52111
    74
wenzelm@52111
    75
      val (handlers2, functions2) =
wenzelm@52111
    76
        try {
wenzelm@52111
    77
          val new_handler = Class.forName(name).newInstance.asInstanceOf[Protocol_Handler]
wenzelm@52111
    78
          val new_functions =
wenzelm@52111
    79
            for ((a, f) <- new_handler.functions.toList) yield
wenzelm@56385
    80
              (a, (msg: Prover.Protocol_Output) => f(prover, msg))
wenzelm@52111
    81
wenzelm@52111
    82
          val dups = for ((a, _) <- new_functions if functions1.isDefinedAt(a)) yield a
wenzelm@52111
    83
          if (!dups.isEmpty) error("Duplicate protocol functions: " + commas_quote(dups))
wenzelm@52111
    84
wenzelm@52111
    85
          (handlers1 + (name -> new_handler), functions1 ++ new_functions)
wenzelm@52111
    86
        }
wenzelm@52111
    87
        catch {
wenzelm@52111
    88
          case exn: Throwable =>
wenzelm@56671
    89
            System.err.println(Exn.error_message(
wenzelm@56671
    90
              "Failed to initialize protocol handler: " + quote(name) + "\n" + Exn.message(exn)))
wenzelm@52111
    91
            (handlers1, functions1)
wenzelm@52111
    92
        }
wenzelm@52111
    93
wenzelm@52111
    94
      new Protocol_Handlers(handlers2, functions2)
wenzelm@52111
    95
    }
wenzelm@52111
    96
wenzelm@56385
    97
    def invoke(msg: Prover.Protocol_Output): Boolean =
wenzelm@54442
    98
      msg.properties match {
wenzelm@52111
    99
        case Markup.Function(a) if functions.isDefinedAt(a) =>
wenzelm@54442
   100
          try { functions(a)(msg) }
wenzelm@52111
   101
          catch {
wenzelm@52111
   102
            case exn: Throwable =>
wenzelm@56671
   103
              System.err.println(Exn.error_message(
wenzelm@56671
   104
                "Failed invocation of protocol function: " + quote(a) + "\n" + Exn.message(exn)))
wenzelm@52111
   105
            false
wenzelm@52111
   106
          }
wenzelm@52111
   107
        case _ => false
wenzelm@52111
   108
      }
wenzelm@52113
   109
wenzelm@52113
   110
    def stop(prover: Prover): Protocol_Handlers =
wenzelm@52113
   111
    {
wenzelm@52113
   112
      for ((_, handler) <- handlers) handler.stop(prover)
wenzelm@52113
   113
      new Protocol_Handlers()
wenzelm@52113
   114
    }
wenzelm@52111
   115
  }
wenzelm@34791
   116
}
wenzelm@34791
   117
wenzelm@34777
   118
wenzelm@56208
   119
class Session(val resources: Resources)
wenzelm@34777
   120
{
wenzelm@47653
   121
  /* global flags */
wenzelm@47653
   122
wenzelm@47653
   123
  @volatile var timing: Boolean = false
wenzelm@47653
   124
  @volatile var verbose: Boolean = false
wenzelm@47653
   125
wenzelm@47653
   126
wenzelm@49288
   127
  /* tuning parameters */
wenzelm@49288
   128
wenzelm@49288
   129
  def output_delay: Time = Time.seconds(0.1)  // prover output (markup, common messages)
wenzelm@52800
   130
  def message_delay: Time = Time.seconds(0.1)  // prover input/output messages
wenzelm@49293
   131
  def prune_delay: Time = Time.seconds(60.0)  // prune history -- delete old versions
wenzelm@49293
   132
  def prune_size: Int = 0  // size of retained history
wenzelm@49293
   133
  def syslog_limit: Int = 100
wenzelm@49524
   134
  def reparse_limit: Int = 0
wenzelm@37849
   135
wenzelm@37849
   136
wenzelm@34809
   137
  /* pervasive event buses */
wenzelm@34809
   138
wenzelm@50433
   139
  val statistics = new Event_Bus[Session.Statistics]
wenzelm@50117
   140
  val global_options = new Event_Bus[Session.Global_Options]
wenzelm@44805
   141
  val caret_focus = new Event_Bus[Session.Caret_Focus.type]
wenzelm@49196
   142
  val raw_edits = new Event_Bus[Session.Raw_Edits]
wenzelm@43716
   143
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@43716
   144
  val phase_changed = new Event_Bus[Session.Phase]
wenzelm@56385
   145
  val syslog_messages = new Event_Bus[Prover.Output]
wenzelm@56385
   146
  val raw_output_messages = new Event_Bus[Prover.Output]
wenzelm@56385
   147
  val all_messages = new Event_Bus[Prover.Message]  // potential bottle-neck
lars@55316
   148
  val trace_events = new Event_Bus[Simplifier_Trace.Event.type]
wenzelm@34809
   149
wenzelm@34809
   150
wenzelm@56706
   151
wenzelm@56706
   152
  /** buffered changes: to be dispatched to clients **/
wenzelm@38841
   153
wenzelm@56706
   154
  private case class Received_Change(assignment: Boolean, commands: List[Command])
wenzelm@56706
   155
wenzelm@56706
   156
  private val change_buffer: Consumer_Thread[Received_Change] =
wenzelm@38841
   157
  {
wenzelm@56705
   158
    object changed
wenzelm@56705
   159
    {
wenzelm@56705
   160
      private var assignment: Boolean = false
wenzelm@56705
   161
      private var nodes: Set[Document.Node.Name] = Set.empty
wenzelm@56705
   162
      private var commands: Set[Command] = Set.empty
wenzelm@56705
   163
wenzelm@56705
   164
      def flush(): Unit = synchronized {
wenzelm@56705
   165
        if (assignment || !nodes.isEmpty || !commands.isEmpty)
wenzelm@56705
   166
          commands_changed.event(Session.Commands_Changed(assignment, nodes, commands))
wenzelm@56705
   167
        assignment = false
wenzelm@56705
   168
        nodes = Set.empty
wenzelm@56705
   169
        commands = Set.empty
wenzelm@56705
   170
      }
wenzelm@56705
   171
wenzelm@56706
   172
      def invoke(change: Received_Change): Unit = synchronized {
wenzelm@56706
   173
        assignment |= change.assignment
wenzelm@56706
   174
        for (command <- change.commands) {
wenzelm@56706
   175
          nodes += command.node_name
wenzelm@56706
   176
          commands += command
wenzelm@56705
   177
        }
wenzelm@56705
   178
      }
wenzelm@56705
   179
    }
wenzelm@56705
   180
wenzelm@56706
   181
    val timer = new Timer("change_buffer", true)
wenzelm@56705
   182
    timer.schedule(new TimerTask { def run = changed.flush() }, output_delay.ms, output_delay.ms)
wenzelm@56705
   183
wenzelm@56706
   184
    Consumer_Thread.fork[Received_Change]("change_buffer", daemon = true)(
wenzelm@56706
   185
      consume = { case change => changed.invoke(change); true },
wenzelm@56705
   186
      finish = () => { timer.cancel(); changed.flush() }
wenzelm@56705
   187
    )
wenzelm@38841
   188
  }
wenzelm@38841
   189
wenzelm@38841
   190
wenzelm@56705
   191
wenzelm@45635
   192
  /** pipelined change parsing **/
wenzelm@45635
   193
wenzelm@45635
   194
  private case class Text_Edits(
wenzelm@45635
   195
    previous: Future[Document.Version],
wenzelm@54521
   196
    doc_blobs: Document.Blobs,
wenzelm@45635
   197
    text_edits: List[Document.Edit_Text],
wenzelm@45635
   198
    version_result: Promise[Document.Version])
wenzelm@45635
   199
wenzelm@56704
   200
  private val change_parser = Consumer_Thread.fork[Text_Edits]("change_parser", daemon = true)
wenzelm@45635
   201
  {
wenzelm@56704
   202
    case Text_Edits(previous, doc_blobs, text_edits, version_result) =>
wenzelm@56704
   203
      val prev = previous.get_finished
wenzelm@56704
   204
      val change =
wenzelm@56704
   205
        Timing.timeit("parse_change", timing) {
wenzelm@56704
   206
          resources.parse_change(reparse_limit, prev, doc_blobs, text_edits)
wenzelm@56704
   207
        }
wenzelm@56704
   208
      version_result.fulfill(change.version)
wenzelm@56706
   209
      manager.send(change)
wenzelm@56704
   210
      true
wenzelm@45635
   211
  }
wenzelm@45635
   212
wenzelm@38841
   213
wenzelm@47653
   214
wenzelm@56706
   215
  /** main protocol manager **/
wenzelm@34809
   216
wenzelm@43651
   217
  /* global state */
wenzelm@43644
   218
wenzelm@56690
   219
  private val syslog = Synchronized(Queue.empty[XML.Elem])
wenzelm@56687
   220
  def current_syslog(): String = cat_lines(syslog.value.iterator.map(XML.content))
wenzelm@39626
   221
wenzelm@39630
   222
  @volatile private var _phase: Session.Phase = Session.Inactive
wenzelm@39633
   223
  private def phase_=(new_phase: Session.Phase)
wenzelm@39630
   224
  {
wenzelm@39630
   225
    _phase = new_phase
wenzelm@39701
   226
    phase_changed.event(new_phase)
wenzelm@39630
   227
  }
wenzelm@43716
   228
  def phase = _phase
wenzelm@43553
   229
  def is_ready: Boolean = phase == Session.Ready
wenzelm@39630
   230
wenzelm@56690
   231
  private val global_state = Synchronized(Document.State.init)
wenzelm@56687
   232
  def current_state(): Document.State = global_state.value
wenzelm@46944
   233
wenzelm@56393
   234
  def recent_syntax(): Prover.Syntax =
wenzelm@46944
   235
  {
wenzelm@46944
   236
    val version = current_state().recent_finished.version.get_finished
wenzelm@56394
   237
    version.syntax getOrElse resources.base_syntax
wenzelm@46944
   238
  }
wenzelm@34816
   239
wenzelm@44960
   240
  def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
wenzelm@44960
   241
      pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
wenzelm@56687
   242
    global_state.value.snapshot(name, pending_edits)
wenzelm@43716
   243
wenzelm@43651
   244
wenzelm@53054
   245
  /* protocol handlers */
wenzelm@53054
   246
wenzelm@53054
   247
  @volatile private var _protocol_handlers = new Session.Protocol_Handlers()
wenzelm@53054
   248
wenzelm@53054
   249
  def protocol_handler(name: String): Option[Session.Protocol_Handler] =
wenzelm@53054
   250
    _protocol_handlers.get(name)
wenzelm@53054
   251
wenzelm@53054
   252
wenzelm@43651
   253
  /* theory files */
wenzelm@43651
   254
wenzelm@48707
   255
  def header_edit(name: Document.Node.Name, header: Document.Node.Header): Document.Edit_Text =
wenzelm@44442
   256
  {
wenzelm@48707
   257
    val header1 =
wenzelm@56208
   258
      if (resources.loaded_theories(name.theory))
wenzelm@54559
   259
        header.error("Cannot update finished theory " + quote(name.theory))
wenzelm@48707
   260
      else header
wenzelm@48707
   261
    (name, Document.Node.Deps(header1))
wenzelm@44442
   262
  }
wenzelm@44442
   263
wenzelm@43651
   264
wenzelm@56706
   265
  /* internal messages */
wenzelm@43651
   266
wenzelm@56387
   267
  private case class Start(name: String, args: List[String])
wenzelm@56709
   268
  private case object Stop
wenzelm@52931
   269
  private case class Cancel_Exec(exec_id: Document_ID.Exec)
wenzelm@53054
   270
  private case class Protocol_Command(name: String, args: List[String])
wenzelm@56385
   271
  private case class Messages(msgs: List[Prover.Message])
wenzelm@52084
   272
  private case class Update_Options(options: Options)
wenzelm@41534
   273
wenzelm@56706
   274
wenzelm@56706
   275
  /* buffered prover messages */
wenzelm@56706
   276
wenzelm@56706
   277
  private object receiver
wenzelm@38639
   278
  {
wenzelm@56706
   279
    private var buffer = new mutable.ListBuffer[Prover.Message]
wenzelm@56706
   280
wenzelm@56706
   281
    private def flush(): Unit = synchronized {
wenzelm@56706
   282
      if (!buffer.isEmpty) {
wenzelm@56706
   283
        val msgs = buffer.toList
wenzelm@56706
   284
        manager.send(Messages(msgs))
wenzelm@56706
   285
        buffer = new mutable.ListBuffer[Prover.Message]
wenzelm@56706
   286
      }
wenzelm@56706
   287
    }
wenzelm@34809
   288
wenzelm@56706
   289
    def invoke(msg: Prover.Message): Unit = synchronized {
wenzelm@56706
   290
      msg match {
wenzelm@56706
   291
        case _: Prover.Input =>
wenzelm@56706
   292
          buffer += msg
wenzelm@56706
   293
        case output: Prover.Protocol_Output if output.properties == Markup.Flush =>
wenzelm@56706
   294
          flush()
wenzelm@56706
   295
        case output: Prover.Output =>
wenzelm@56706
   296
          buffer += msg
wenzelm@56706
   297
          if (output.is_syslog)
wenzelm@56706
   298
            syslog.change(queue =>
wenzelm@56706
   299
              {
wenzelm@56706
   300
                val queue1 = queue.enqueue(output.message)
wenzelm@56706
   301
                if (queue1.length > syslog_limit) queue1.dequeue._2 else queue1
wenzelm@56706
   302
              })
wenzelm@56706
   303
      }
wenzelm@56706
   304
    }
wenzelm@56706
   305
wenzelm@56706
   306
    private val timer = new Timer("receiver", true)
wenzelm@56706
   307
    timer.schedule(new TimerTask { def run = flush }, message_delay.ms, message_delay.ms)
wenzelm@56706
   308
wenzelm@56709
   309
    def shutdown() { timer.cancel(); flush() }
wenzelm@56706
   310
  }
wenzelm@49470
   311
wenzelm@34809
   312
wenzelm@56706
   313
  /* postponed changes */
wenzelm@44733
   314
wenzelm@56706
   315
  private object postponed_changes
wenzelm@56706
   316
  {
wenzelm@56706
   317
    private var postponed: List[Session.Change] = Nil
wenzelm@56706
   318
wenzelm@56706
   319
    def store(change: Session.Change): Unit = synchronized { postponed ::= change }
wenzelm@56705
   320
wenzelm@56706
   321
    def flush(): Unit = synchronized {
wenzelm@56706
   322
      val state = global_state.value
wenzelm@56706
   323
      val (assigned, unassigned) = postponed.partition(change => state.is_assigned(change.previous))
wenzelm@56706
   324
      postponed = unassigned
wenzelm@56706
   325
      assigned.reverseIterator.foreach(change => manager.send(change))
wenzelm@56706
   326
    }
wenzelm@56706
   327
  }
wenzelm@44733
   328
wenzelm@56706
   329
wenzelm@56706
   330
  /* manager thread */
wenzelm@44733
   331
wenzelm@56706
   332
  private val manager: Consumer_Thread[Any] =
wenzelm@56706
   333
  {
wenzelm@56706
   334
    var prune_next = Time.now() + prune_delay
wenzelm@44733
   335
wenzelm@56387
   336
    var prover: Option[Prover] = None
wenzelm@44733
   337
wenzelm@44733
   338
wenzelm@52649
   339
    /* raw edits */
wenzelm@52649
   340
wenzelm@54521
   341
    def handle_raw_edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52649
   342
    //{{{
wenzelm@52649
   343
    {
wenzelm@52649
   344
      prover.get.discontinue_execution()
wenzelm@52649
   345
wenzelm@56687
   346
      val previous = global_state.value.history.tip.version
wenzelm@52649
   347
      val version = Future.promise[Document.Version]
wenzelm@56687
   348
      val change = global_state.change_result(_.continue_history(previous, edits, version))
wenzelm@52649
   349
wenzelm@54521
   350
      raw_edits.event(Session.Raw_Edits(doc_blobs, edits))
wenzelm@56704
   351
      change_parser.send(Text_Edits(previous, doc_blobs, edits, version))
wenzelm@52649
   352
    }
wenzelm@52649
   353
    //}}}
wenzelm@52649
   354
wenzelm@52649
   355
wenzelm@43716
   356
    /* resulting changes */
wenzelm@34809
   357
wenzelm@56315
   358
    def handle_change(change: Session.Change)
wenzelm@38221
   359
    //{{{
wenzelm@34809
   360
    {
wenzelm@44383
   361
      def id_command(command: Command)
wenzelm@43720
   362
      {
wenzelm@54519
   363
        for {
wenzelm@54519
   364
          digest <- command.blobs_digests
wenzelm@56687
   365
          if !global_state.value.defined_blob(digest)
wenzelm@54519
   366
        } {
wenzelm@56315
   367
          change.doc_blobs.get(digest) match {
wenzelm@54519
   368
            case Some(blob) =>
wenzelm@56687
   369
              global_state.change(_.define_blob(digest))
wenzelm@56335
   370
              prover.get.define_blob(digest, blob.bytes)
wenzelm@55783
   371
            case None =>
wenzelm@55783
   372
              System.err.println("Missing blob for SHA1 digest " + digest)
wenzelm@54519
   373
          }
wenzelm@54519
   374
        }
wenzelm@54519
   375
wenzelm@56687
   376
        if (!global_state.value.defined_command(command.id)) {
wenzelm@56687
   377
          global_state.change(_.define_command(command))
wenzelm@44644
   378
          prover.get.define_command(command)
wenzelm@43720
   379
        }
wenzelm@43720
   380
      }
wenzelm@56315
   381
      change.doc_edits foreach {
wenzelm@44383
   382
        case (_, edit) =>
wenzelm@44383
   383
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   384
      }
wenzelm@43722
   385
wenzelm@56687
   386
      val assignment = global_state.value.the_assignment(change.previous).check_finished
wenzelm@56687
   387
      global_state.change(_.define_version(change.version, assignment))
wenzelm@56315
   388
      prover.get.update(change.previous.id, change.version.id, change.doc_edits)
wenzelm@56316
   389
      resources.commit(change)
wenzelm@34809
   390
    }
wenzelm@38221
   391
    //}}}
wenzelm@34809
   392
wenzelm@34809
   393
wenzelm@46772
   394
    /* prover output */
wenzelm@34809
   395
wenzelm@56385
   396
    def handle_output(output: Prover.Output)
wenzelm@38221
   397
    //{{{
wenzelm@34809
   398
    {
wenzelm@51662
   399
      def bad_output()
wenzelm@43716
   400
      {
wenzelm@43716
   401
        if (verbose)
wenzelm@46772
   402
          System.err.println("Ignoring prover output: " + output.message.toString)
wenzelm@43716
   403
      }
wenzelm@43716
   404
wenzelm@52531
   405
      def accumulate(state_id: Document_ID.Generic, message: XML.Elem)
wenzelm@51662
   406
      {
wenzelm@51662
   407
        try {
wenzelm@56687
   408
          val st = global_state.change_result(_.accumulate(state_id, message))
wenzelm@56706
   409
          change_buffer.send(Received_Change(false, List(st.command)))
wenzelm@51662
   410
        }
wenzelm@51662
   411
        catch {
wenzelm@51662
   412
          case _: Document.State.Fail => bad_output()
wenzelm@51662
   413
        }
wenzelm@51662
   414
      }
wenzelm@51662
   415
wenzelm@54442
   416
      output match {
wenzelm@56385
   417
        case msg: Prover.Protocol_Output =>
wenzelm@54442
   418
          val handled = _protocol_handlers.invoke(msg)
wenzelm@54442
   419
          if (!handled) {
wenzelm@54442
   420
            msg.properties match {
wenzelm@54442
   421
              case Markup.Protocol_Handler(name) =>
wenzelm@54442
   422
                _protocol_handlers = _protocol_handlers.add(prover.get, name)
wenzelm@54442
   423
wenzelm@54442
   424
              case Protocol.Command_Timing(state_id, timing) =>
wenzelm@54442
   425
                val message = XML.elem(Markup.STATUS, List(XML.Elem(Markup.Timing(timing), Nil)))
wenzelm@54442
   426
                accumulate(state_id, prover.get.xml_cache.elem(message))
wenzelm@46122
   427
wenzelm@54442
   428
              case Markup.Assign_Update =>
wenzelm@54442
   429
                msg.text match {
wenzelm@54442
   430
                  case Protocol.Assign_Update(id, update) =>
wenzelm@54442
   431
                    try {
wenzelm@56687
   432
                      val cmds = global_state.change_result(_.assign(id, update))
wenzelm@56706
   433
                      change_buffer.send(Received_Change(true, cmds))
wenzelm@54442
   434
                    }
wenzelm@54442
   435
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@56706
   436
                    postponed_changes.flush()
wenzelm@54442
   437
                  case _ => bad_output()
wenzelm@54442
   438
                }
wenzelm@54442
   439
                // FIXME separate timeout event/message!?
wenzelm@56691
   440
                if (prover.isDefined && Time.now() > prune_next) {
wenzelm@56687
   441
                  val old_versions = global_state.change_result(_.prune_history(prune_size))
wenzelm@54442
   442
                  if (!old_versions.isEmpty) prover.get.remove_versions(old_versions)
wenzelm@56691
   443
                  prune_next = Time.now() + prune_delay
wenzelm@54442
   444
                }
wenzelm@46122
   445
wenzelm@54442
   446
              case Markup.Removed_Versions =>
wenzelm@54442
   447
                msg.text match {
wenzelm@54442
   448
                  case Protocol.Removed(removed) =>
wenzelm@54442
   449
                    try {
wenzelm@56687
   450
                      global_state.change(_.removed_versions(removed))
wenzelm@54442
   451
                    }
wenzelm@54442
   452
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@54442
   453
                  case _ => bad_output()
wenzelm@54442
   454
                }
wenzelm@54442
   455
wenzelm@54442
   456
              case Markup.ML_Statistics(props) =>
wenzelm@54442
   457
                statistics.event(Session.Statistics(props))
wenzelm@54442
   458
wenzelm@54442
   459
              case Markup.Task_Statistics(props) =>
wenzelm@54442
   460
                // FIXME
wenzelm@52111
   461
wenzelm@54442
   462
              case _ => bad_output()
wenzelm@54442
   463
            }
wenzelm@54442
   464
          }
wenzelm@54442
   465
        case _ =>
wenzelm@54442
   466
          output.properties match {
wenzelm@54442
   467
            case Position.Id(state_id) =>
wenzelm@54442
   468
              accumulate(state_id, output.message)
wenzelm@56210
   469
wenzelm@54442
   470
            case _ if output.is_init =>
wenzelm@54442
   471
              phase = Session.Ready
wenzelm@56210
   472
wenzelm@54442
   473
            case Markup.Return_Code(rc) if output.is_exit =>
wenzelm@54442
   474
              if (rc == 0) phase = Session.Inactive
wenzelm@54442
   475
              else phase = Session.Failed
wenzelm@56210
   476
wenzelm@54442
   477
            case _ => raw_output_messages.event(output)
wenzelm@44661
   478
          }
wenzelm@52111
   479
        }
wenzelm@34809
   480
    }
wenzelm@38221
   481
    //}}}
wenzelm@34809
   482
wenzelm@34820
   483
wenzelm@56706
   484
    /* main thread */
wenzelm@56706
   485
wenzelm@56710
   486
    Consumer_Thread.fork[Any]("Session.manager", daemon = true)
wenzelm@56709
   487
    {
wenzelm@56709
   488
      case arg: Any =>
wenzelm@56709
   489
        //{{{
wenzelm@56709
   490
        arg match {
wenzelm@56709
   491
          case Start(name, args) if prover.isEmpty =>
wenzelm@56709
   492
            if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@56709
   493
              phase = Session.Startup
wenzelm@56709
   494
              prover = Some(resources.start_prover(receiver.invoke _, name, args))
wenzelm@56709
   495
            }
wenzelm@56706
   496
wenzelm@56709
   497
          case Stop =>
wenzelm@56709
   498
            if (phase == Session.Ready) {
wenzelm@56709
   499
              _protocol_handlers = _protocol_handlers.stop(prover.get)
wenzelm@56709
   500
              global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@56709
   501
              phase = Session.Shutdown
wenzelm@56709
   502
              prover.get.terminate
wenzelm@56709
   503
              prover = None
wenzelm@56709
   504
              phase = Session.Inactive
wenzelm@56709
   505
            }
wenzelm@56706
   506
wenzelm@56709
   507
          case Update_Options(options) =>
wenzelm@56709
   508
            if (prover.isDefined && is_ready) {
wenzelm@56709
   509
              prover.get.options(options)
wenzelm@56709
   510
              handle_raw_edits(Document.Blobs.empty, Nil)
wenzelm@56709
   511
            }
wenzelm@56709
   512
            global_options.event(Session.Global_Options(options))
wenzelm@34809
   513
wenzelm@56709
   514
          case Cancel_Exec(exec_id) if prover.isDefined =>
wenzelm@56709
   515
            prover.get.cancel_exec(exec_id)
wenzelm@56706
   516
wenzelm@56709
   517
          case Session.Raw_Edits(doc_blobs, edits) if prover.isDefined =>
wenzelm@56709
   518
            handle_raw_edits(doc_blobs, edits)
wenzelm@56709
   519
wenzelm@56709
   520
          case Session.Dialog_Result(id, serial, result) if prover.isDefined =>
wenzelm@56709
   521
            prover.get.dialog_result(serial, result)
wenzelm@56709
   522
            handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
wenzelm@56706
   523
wenzelm@56709
   524
          case Protocol_Command(name, args) if prover.isDefined =>
wenzelm@56709
   525
            prover.get.protocol_command(name, args:_*)
wenzelm@56706
   526
wenzelm@56709
   527
          case Messages(msgs) =>
wenzelm@56709
   528
            msgs foreach {
wenzelm@56709
   529
              case input: Prover.Input =>
wenzelm@56709
   530
                all_messages.event(input)
wenzelm@56706
   531
wenzelm@56709
   532
              case output: Prover.Output =>
wenzelm@56709
   533
                if (output.is_stdout || output.is_stderr) raw_output_messages.event(output)
wenzelm@56709
   534
                else handle_output(output)
wenzelm@56709
   535
                if (output.is_syslog) syslog_messages.event(output)
wenzelm@56709
   536
                all_messages.event(output)
wenzelm@56709
   537
            }
wenzelm@56709
   538
wenzelm@56709
   539
          case change: Session.Change if prover.isDefined =>
wenzelm@56709
   540
            if (global_state.value.is_assigned(change.previous))
wenzelm@56709
   541
              handle_change(change)
wenzelm@56709
   542
            else postponed_changes.store(change)
wenzelm@56706
   543
        }
wenzelm@56709
   544
        true
wenzelm@56709
   545
        //}}}
wenzelm@56709
   546
    }
wenzelm@34777
   547
  }
wenzelm@34777
   548
wenzelm@34809
   549
wenzelm@43716
   550
  /* actions */
wenzelm@34809
   551
wenzelm@56387
   552
  def start(name: String, args: List[String])
wenzelm@56706
   553
  { manager.send(Start(name, args)) }
wenzelm@45076
   554
wenzelm@50117
   555
  def stop()
wenzelm@50117
   556
  {
wenzelm@56709
   557
    manager.send_wait(Stop)
wenzelm@56709
   558
    receiver.shutdown()
wenzelm@56704
   559
    change_parser.shutdown()
wenzelm@56706
   560
    change_buffer.shutdown()
wenzelm@56706
   561
    manager.shutdown()
wenzelm@50117
   562
  }
wenzelm@38841
   563
wenzelm@53054
   564
  def protocol_command(name: String, args: String*)
wenzelm@56706
   565
  { manager.send(Protocol_Command(name, args.toList)) }
wenzelm@53054
   566
wenzelm@56706
   567
  def cancel_exec(exec_id: Document_ID.Exec)
wenzelm@56706
   568
  { manager.send(Cancel_Exec(exec_id)) }
wenzelm@52931
   569
wenzelm@54521
   570
  def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@56706
   571
  { if (!edits.isEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
wenzelm@50498
   572
wenzelm@52084
   573
  def update_options(options: Options)
wenzelm@56706
   574
  { manager.send_wait(Update_Options(options)) }
wenzelm@52084
   575
wenzelm@52531
   576
  def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@56706
   577
  { manager.send(Session.Dialog_Result(id, serial, result)) }
wenzelm@34777
   578
}