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