src/Pure/PIDE/session.scala
author wenzelm
Fri Apr 25 12:51:08 2014 +0200 (2014-04-25)
changeset 56715 52125652e82a
parent 56713 3438dfba58fe
child 56719 80eb2192516a
permissions -rw-r--r--
clarified Session.Consumer, with Session.Outlet managed by dispatcher thread;
eliminated old actors;
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@56706
   185
  /** buffered changes: to be dispatched to clients **/
wenzelm@38841
   186
wenzelm@56706
   187
  private case class Received_Change(assignment: Boolean, commands: List[Command])
wenzelm@56706
   188
wenzelm@56706
   189
  private val change_buffer: Consumer_Thread[Received_Change] =
wenzelm@38841
   190
  {
wenzelm@56705
   191
    object changed
wenzelm@56705
   192
    {
wenzelm@56705
   193
      private var assignment: Boolean = false
wenzelm@56705
   194
      private var nodes: Set[Document.Node.Name] = Set.empty
wenzelm@56705
   195
      private var commands: Set[Command] = Set.empty
wenzelm@56705
   196
wenzelm@56705
   197
      def flush(): Unit = synchronized {
wenzelm@56705
   198
        if (assignment || !nodes.isEmpty || !commands.isEmpty)
wenzelm@56715
   199
          commands_changed.post(Session.Commands_Changed(assignment, nodes, commands))
wenzelm@56705
   200
        assignment = false
wenzelm@56705
   201
        nodes = Set.empty
wenzelm@56705
   202
        commands = Set.empty
wenzelm@56705
   203
      }
wenzelm@56705
   204
wenzelm@56706
   205
      def invoke(change: Received_Change): Unit = synchronized {
wenzelm@56706
   206
        assignment |= change.assignment
wenzelm@56706
   207
        for (command <- change.commands) {
wenzelm@56706
   208
          nodes += command.node_name
wenzelm@56706
   209
          commands += command
wenzelm@56705
   210
        }
wenzelm@56705
   211
      }
wenzelm@56705
   212
    }
wenzelm@56705
   213
wenzelm@56706
   214
    val timer = new Timer("change_buffer", true)
wenzelm@56705
   215
    timer.schedule(new TimerTask { def run = changed.flush() }, output_delay.ms, output_delay.ms)
wenzelm@56705
   216
wenzelm@56706
   217
    Consumer_Thread.fork[Received_Change]("change_buffer", daemon = true)(
wenzelm@56706
   218
      consume = { case change => changed.invoke(change); true },
wenzelm@56705
   219
      finish = () => { timer.cancel(); changed.flush() }
wenzelm@56705
   220
    )
wenzelm@38841
   221
  }
wenzelm@38841
   222
wenzelm@38841
   223
wenzelm@56705
   224
wenzelm@45635
   225
  /** pipelined change parsing **/
wenzelm@45635
   226
wenzelm@45635
   227
  private case class Text_Edits(
wenzelm@45635
   228
    previous: Future[Document.Version],
wenzelm@54521
   229
    doc_blobs: Document.Blobs,
wenzelm@45635
   230
    text_edits: List[Document.Edit_Text],
wenzelm@45635
   231
    version_result: Promise[Document.Version])
wenzelm@45635
   232
wenzelm@56704
   233
  private val change_parser = Consumer_Thread.fork[Text_Edits]("change_parser", daemon = true)
wenzelm@45635
   234
  {
wenzelm@56704
   235
    case Text_Edits(previous, doc_blobs, text_edits, version_result) =>
wenzelm@56704
   236
      val prev = previous.get_finished
wenzelm@56704
   237
      val change =
wenzelm@56704
   238
        Timing.timeit("parse_change", timing) {
wenzelm@56704
   239
          resources.parse_change(reparse_limit, prev, doc_blobs, text_edits)
wenzelm@56704
   240
        }
wenzelm@56704
   241
      version_result.fulfill(change.version)
wenzelm@56706
   242
      manager.send(change)
wenzelm@56704
   243
      true
wenzelm@45635
   244
  }
wenzelm@45635
   245
wenzelm@38841
   246
wenzelm@47653
   247
wenzelm@56706
   248
  /** main protocol manager **/
wenzelm@34809
   249
wenzelm@43651
   250
  /* global state */
wenzelm@43644
   251
wenzelm@56690
   252
  private val syslog = Synchronized(Queue.empty[XML.Elem])
wenzelm@56687
   253
  def current_syslog(): String = cat_lines(syslog.value.iterator.map(XML.content))
wenzelm@39626
   254
wenzelm@39630
   255
  @volatile private var _phase: Session.Phase = Session.Inactive
wenzelm@39633
   256
  private def phase_=(new_phase: Session.Phase)
wenzelm@39630
   257
  {
wenzelm@39630
   258
    _phase = new_phase
wenzelm@56715
   259
    phase_changed.post(new_phase)
wenzelm@39630
   260
  }
wenzelm@43716
   261
  def phase = _phase
wenzelm@43553
   262
  def is_ready: Boolean = phase == Session.Ready
wenzelm@39630
   263
wenzelm@56690
   264
  private val global_state = Synchronized(Document.State.init)
wenzelm@56687
   265
  def current_state(): Document.State = global_state.value
wenzelm@46944
   266
wenzelm@56393
   267
  def recent_syntax(): Prover.Syntax =
wenzelm@46944
   268
  {
wenzelm@46944
   269
    val version = current_state().recent_finished.version.get_finished
wenzelm@56394
   270
    version.syntax getOrElse resources.base_syntax
wenzelm@46944
   271
  }
wenzelm@34816
   272
wenzelm@44960
   273
  def snapshot(name: Document.Node.Name = Document.Node.Name.empty,
wenzelm@44960
   274
      pending_edits: List[Text.Edit] = Nil): Document.Snapshot =
wenzelm@56687
   275
    global_state.value.snapshot(name, pending_edits)
wenzelm@43716
   276
wenzelm@43651
   277
wenzelm@53054
   278
  /* protocol handlers */
wenzelm@53054
   279
wenzelm@53054
   280
  @volatile private var _protocol_handlers = new Session.Protocol_Handlers()
wenzelm@53054
   281
wenzelm@53054
   282
  def protocol_handler(name: String): Option[Session.Protocol_Handler] =
wenzelm@53054
   283
    _protocol_handlers.get(name)
wenzelm@53054
   284
wenzelm@53054
   285
wenzelm@43651
   286
  /* theory files */
wenzelm@43651
   287
wenzelm@48707
   288
  def header_edit(name: Document.Node.Name, header: Document.Node.Header): Document.Edit_Text =
wenzelm@44442
   289
  {
wenzelm@48707
   290
    val header1 =
wenzelm@56208
   291
      if (resources.loaded_theories(name.theory))
wenzelm@54559
   292
        header.error("Cannot update finished theory " + quote(name.theory))
wenzelm@48707
   293
      else header
wenzelm@48707
   294
    (name, Document.Node.Deps(header1))
wenzelm@44442
   295
  }
wenzelm@44442
   296
wenzelm@43651
   297
wenzelm@56706
   298
  /* internal messages */
wenzelm@43651
   299
wenzelm@56387
   300
  private case class Start(name: String, args: List[String])
wenzelm@56709
   301
  private case object Stop
wenzelm@52931
   302
  private case class Cancel_Exec(exec_id: Document_ID.Exec)
wenzelm@53054
   303
  private case class Protocol_Command(name: String, args: List[String])
wenzelm@56385
   304
  private case class Messages(msgs: List[Prover.Message])
wenzelm@52084
   305
  private case class Update_Options(options: Options)
wenzelm@41534
   306
wenzelm@56706
   307
wenzelm@56706
   308
  /* buffered prover messages */
wenzelm@56706
   309
wenzelm@56706
   310
  private object receiver
wenzelm@38639
   311
  {
wenzelm@56706
   312
    private var buffer = new mutable.ListBuffer[Prover.Message]
wenzelm@56706
   313
wenzelm@56706
   314
    private def flush(): Unit = synchronized {
wenzelm@56706
   315
      if (!buffer.isEmpty) {
wenzelm@56706
   316
        val msgs = buffer.toList
wenzelm@56706
   317
        manager.send(Messages(msgs))
wenzelm@56706
   318
        buffer = new mutable.ListBuffer[Prover.Message]
wenzelm@56706
   319
      }
wenzelm@56706
   320
    }
wenzelm@34809
   321
wenzelm@56706
   322
    def invoke(msg: Prover.Message): Unit = synchronized {
wenzelm@56706
   323
      msg match {
wenzelm@56706
   324
        case _: Prover.Input =>
wenzelm@56706
   325
          buffer += msg
wenzelm@56706
   326
        case output: Prover.Protocol_Output if output.properties == Markup.Flush =>
wenzelm@56706
   327
          flush()
wenzelm@56706
   328
        case output: Prover.Output =>
wenzelm@56706
   329
          buffer += msg
wenzelm@56706
   330
          if (output.is_syslog)
wenzelm@56706
   331
            syslog.change(queue =>
wenzelm@56706
   332
              {
wenzelm@56706
   333
                val queue1 = queue.enqueue(output.message)
wenzelm@56706
   334
                if (queue1.length > syslog_limit) queue1.dequeue._2 else queue1
wenzelm@56706
   335
              })
wenzelm@56706
   336
      }
wenzelm@56706
   337
    }
wenzelm@56706
   338
wenzelm@56706
   339
    private val timer = new Timer("receiver", true)
wenzelm@56706
   340
    timer.schedule(new TimerTask { def run = flush }, message_delay.ms, message_delay.ms)
wenzelm@56706
   341
wenzelm@56709
   342
    def shutdown() { timer.cancel(); flush() }
wenzelm@56706
   343
  }
wenzelm@49470
   344
wenzelm@34809
   345
wenzelm@56706
   346
  /* postponed changes */
wenzelm@44733
   347
wenzelm@56706
   348
  private object postponed_changes
wenzelm@56706
   349
  {
wenzelm@56706
   350
    private var postponed: List[Session.Change] = Nil
wenzelm@56706
   351
wenzelm@56706
   352
    def store(change: Session.Change): Unit = synchronized { postponed ::= change }
wenzelm@56705
   353
wenzelm@56706
   354
    def flush(): Unit = synchronized {
wenzelm@56706
   355
      val state = global_state.value
wenzelm@56706
   356
      val (assigned, unassigned) = postponed.partition(change => state.is_assigned(change.previous))
wenzelm@56706
   357
      postponed = unassigned
wenzelm@56706
   358
      assigned.reverseIterator.foreach(change => manager.send(change))
wenzelm@56706
   359
    }
wenzelm@56706
   360
  }
wenzelm@44733
   361
wenzelm@56706
   362
wenzelm@56706
   363
  /* manager thread */
wenzelm@44733
   364
wenzelm@56706
   365
  private val manager: Consumer_Thread[Any] =
wenzelm@56706
   366
  {
wenzelm@56706
   367
    var prune_next = Time.now() + prune_delay
wenzelm@44733
   368
wenzelm@56387
   369
    var prover: Option[Prover] = None
wenzelm@44733
   370
wenzelm@44733
   371
wenzelm@52649
   372
    /* raw edits */
wenzelm@52649
   373
wenzelm@54521
   374
    def handle_raw_edits(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@52649
   375
    //{{{
wenzelm@52649
   376
    {
wenzelm@56712
   377
      require(prover.isDefined)
wenzelm@56712
   378
wenzelm@52649
   379
      prover.get.discontinue_execution()
wenzelm@52649
   380
wenzelm@56687
   381
      val previous = global_state.value.history.tip.version
wenzelm@52649
   382
      val version = Future.promise[Document.Version]
wenzelm@56711
   383
      global_state.change(_.continue_history(previous, edits, version))
wenzelm@52649
   384
wenzelm@56715
   385
      raw_edits.post(Session.Raw_Edits(doc_blobs, edits))
wenzelm@56704
   386
      change_parser.send(Text_Edits(previous, doc_blobs, edits, version))
wenzelm@52649
   387
    }
wenzelm@52649
   388
    //}}}
wenzelm@52649
   389
wenzelm@52649
   390
wenzelm@43716
   391
    /* resulting changes */
wenzelm@34809
   392
wenzelm@56315
   393
    def handle_change(change: Session.Change)
wenzelm@38221
   394
    //{{{
wenzelm@34809
   395
    {
wenzelm@56712
   396
      require(prover.isDefined)
wenzelm@56712
   397
wenzelm@44383
   398
      def id_command(command: Command)
wenzelm@43720
   399
      {
wenzelm@54519
   400
        for {
wenzelm@54519
   401
          digest <- command.blobs_digests
wenzelm@56687
   402
          if !global_state.value.defined_blob(digest)
wenzelm@54519
   403
        } {
wenzelm@56315
   404
          change.doc_blobs.get(digest) match {
wenzelm@54519
   405
            case Some(blob) =>
wenzelm@56687
   406
              global_state.change(_.define_blob(digest))
wenzelm@56335
   407
              prover.get.define_blob(digest, blob.bytes)
wenzelm@55783
   408
            case None =>
wenzelm@55783
   409
              System.err.println("Missing blob for SHA1 digest " + digest)
wenzelm@54519
   410
          }
wenzelm@54519
   411
        }
wenzelm@54519
   412
wenzelm@56687
   413
        if (!global_state.value.defined_command(command.id)) {
wenzelm@56687
   414
          global_state.change(_.define_command(command))
wenzelm@44644
   415
          prover.get.define_command(command)
wenzelm@43720
   416
        }
wenzelm@43720
   417
      }
wenzelm@56315
   418
      change.doc_edits foreach {
wenzelm@44383
   419
        case (_, edit) =>
wenzelm@44383
   420
          edit foreach { case (c1, c2) => c1 foreach id_command; c2 foreach id_command }
wenzelm@44383
   421
      }
wenzelm@43722
   422
wenzelm@56687
   423
      val assignment = global_state.value.the_assignment(change.previous).check_finished
wenzelm@56687
   424
      global_state.change(_.define_version(change.version, assignment))
wenzelm@56315
   425
      prover.get.update(change.previous.id, change.version.id, change.doc_edits)
wenzelm@56316
   426
      resources.commit(change)
wenzelm@34809
   427
    }
wenzelm@38221
   428
    //}}}
wenzelm@34809
   429
wenzelm@34809
   430
wenzelm@46772
   431
    /* prover output */
wenzelm@34809
   432
wenzelm@56385
   433
    def handle_output(output: Prover.Output)
wenzelm@38221
   434
    //{{{
wenzelm@34809
   435
    {
wenzelm@51662
   436
      def bad_output()
wenzelm@43716
   437
      {
wenzelm@43716
   438
        if (verbose)
wenzelm@56713
   439
          System.err.println("Ignoring bad prover output: " + output.message.toString)
wenzelm@43716
   440
      }
wenzelm@43716
   441
wenzelm@52531
   442
      def accumulate(state_id: Document_ID.Generic, message: XML.Elem)
wenzelm@51662
   443
      {
wenzelm@51662
   444
        try {
wenzelm@56687
   445
          val st = global_state.change_result(_.accumulate(state_id, message))
wenzelm@56706
   446
          change_buffer.send(Received_Change(false, List(st.command)))
wenzelm@51662
   447
        }
wenzelm@51662
   448
        catch {
wenzelm@51662
   449
          case _: Document.State.Fail => bad_output()
wenzelm@51662
   450
        }
wenzelm@51662
   451
      }
wenzelm@51662
   452
wenzelm@54442
   453
      output match {
wenzelm@56385
   454
        case msg: Prover.Protocol_Output =>
wenzelm@54442
   455
          val handled = _protocol_handlers.invoke(msg)
wenzelm@54442
   456
          if (!handled) {
wenzelm@54442
   457
            msg.properties match {
wenzelm@56712
   458
              case Markup.Protocol_Handler(name) if prover.isDefined =>
wenzelm@54442
   459
                _protocol_handlers = _protocol_handlers.add(prover.get, name)
wenzelm@54442
   460
wenzelm@56712
   461
              case Protocol.Command_Timing(state_id, timing) if prover.isDefined =>
wenzelm@54442
   462
                val message = XML.elem(Markup.STATUS, List(XML.Elem(Markup.Timing(timing), Nil)))
wenzelm@54442
   463
                accumulate(state_id, prover.get.xml_cache.elem(message))
wenzelm@46122
   464
wenzelm@54442
   465
              case Markup.Assign_Update =>
wenzelm@54442
   466
                msg.text match {
wenzelm@54442
   467
                  case Protocol.Assign_Update(id, update) =>
wenzelm@54442
   468
                    try {
wenzelm@56687
   469
                      val cmds = global_state.change_result(_.assign(id, update))
wenzelm@56706
   470
                      change_buffer.send(Received_Change(true, cmds))
wenzelm@54442
   471
                    }
wenzelm@54442
   472
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@56706
   473
                    postponed_changes.flush()
wenzelm@54442
   474
                  case _ => bad_output()
wenzelm@54442
   475
                }
wenzelm@54442
   476
                // FIXME separate timeout event/message!?
wenzelm@56691
   477
                if (prover.isDefined && Time.now() > prune_next) {
wenzelm@56687
   478
                  val old_versions = global_state.change_result(_.prune_history(prune_size))
wenzelm@54442
   479
                  if (!old_versions.isEmpty) prover.get.remove_versions(old_versions)
wenzelm@56691
   480
                  prune_next = Time.now() + prune_delay
wenzelm@54442
   481
                }
wenzelm@46122
   482
wenzelm@54442
   483
              case Markup.Removed_Versions =>
wenzelm@54442
   484
                msg.text match {
wenzelm@54442
   485
                  case Protocol.Removed(removed) =>
wenzelm@54442
   486
                    try {
wenzelm@56687
   487
                      global_state.change(_.removed_versions(removed))
wenzelm@54442
   488
                    }
wenzelm@54442
   489
                    catch { case _: Document.State.Fail => bad_output() }
wenzelm@54442
   490
                  case _ => bad_output()
wenzelm@54442
   491
                }
wenzelm@54442
   492
wenzelm@54442
   493
              case Markup.ML_Statistics(props) =>
wenzelm@56715
   494
                statistics.post(Session.Statistics(props))
wenzelm@54442
   495
wenzelm@54442
   496
              case Markup.Task_Statistics(props) =>
wenzelm@54442
   497
                // FIXME
wenzelm@52111
   498
wenzelm@54442
   499
              case _ => bad_output()
wenzelm@54442
   500
            }
wenzelm@54442
   501
          }
wenzelm@54442
   502
        case _ =>
wenzelm@54442
   503
          output.properties match {
wenzelm@54442
   504
            case Position.Id(state_id) =>
wenzelm@54442
   505
              accumulate(state_id, output.message)
wenzelm@56210
   506
wenzelm@54442
   507
            case _ if output.is_init =>
wenzelm@54442
   508
              phase = Session.Ready
wenzelm@56210
   509
wenzelm@54442
   510
            case Markup.Return_Code(rc) if output.is_exit =>
wenzelm@56713
   511
              prover = None
wenzelm@54442
   512
              if (rc == 0) phase = Session.Inactive
wenzelm@54442
   513
              else phase = Session.Failed
wenzelm@56210
   514
wenzelm@56715
   515
            case _ => raw_output_messages.post(output)
wenzelm@44661
   516
          }
wenzelm@52111
   517
        }
wenzelm@34809
   518
    }
wenzelm@38221
   519
    //}}}
wenzelm@34809
   520
wenzelm@34820
   521
wenzelm@56706
   522
    /* main thread */
wenzelm@56706
   523
wenzelm@56710
   524
    Consumer_Thread.fork[Any]("Session.manager", daemon = true)
wenzelm@56709
   525
    {
wenzelm@56709
   526
      case arg: Any =>
wenzelm@56709
   527
        //{{{
wenzelm@56709
   528
        arg match {
wenzelm@56709
   529
          case Start(name, args) if prover.isEmpty =>
wenzelm@56709
   530
            if (phase == Session.Inactive || phase == Session.Failed) {
wenzelm@56709
   531
              phase = Session.Startup
wenzelm@56709
   532
              prover = Some(resources.start_prover(receiver.invoke _, name, args))
wenzelm@56709
   533
            }
wenzelm@56706
   534
wenzelm@56709
   535
          case Stop =>
wenzelm@56712
   536
            if (prover.isDefined && is_ready) {
wenzelm@56709
   537
              _protocol_handlers = _protocol_handlers.stop(prover.get)
wenzelm@56709
   538
              global_state.change(_ => Document.State.init)  // FIXME event bus!?
wenzelm@56709
   539
              phase = Session.Shutdown
wenzelm@56709
   540
              prover.get.terminate
wenzelm@56709
   541
            }
wenzelm@56706
   542
wenzelm@56709
   543
          case Update_Options(options) =>
wenzelm@56709
   544
            if (prover.isDefined && is_ready) {
wenzelm@56709
   545
              prover.get.options(options)
wenzelm@56709
   546
              handle_raw_edits(Document.Blobs.empty, Nil)
wenzelm@56709
   547
            }
wenzelm@56715
   548
            global_options.post(Session.Global_Options(options))
wenzelm@34809
   549
wenzelm@56709
   550
          case Cancel_Exec(exec_id) if prover.isDefined =>
wenzelm@56709
   551
            prover.get.cancel_exec(exec_id)
wenzelm@56706
   552
wenzelm@56709
   553
          case Session.Raw_Edits(doc_blobs, edits) if prover.isDefined =>
wenzelm@56709
   554
            handle_raw_edits(doc_blobs, edits)
wenzelm@56709
   555
wenzelm@56709
   556
          case Session.Dialog_Result(id, serial, result) if prover.isDefined =>
wenzelm@56709
   557
            prover.get.dialog_result(serial, result)
wenzelm@56709
   558
            handle_output(new Prover.Output(Protocol.Dialog_Result(id, serial, result)))
wenzelm@56706
   559
wenzelm@56709
   560
          case Protocol_Command(name, args) if prover.isDefined =>
wenzelm@56709
   561
            prover.get.protocol_command(name, args:_*)
wenzelm@56706
   562
wenzelm@56709
   563
          case Messages(msgs) =>
wenzelm@56709
   564
            msgs foreach {
wenzelm@56709
   565
              case input: Prover.Input =>
wenzelm@56715
   566
                all_messages.post(input)
wenzelm@56706
   567
wenzelm@56709
   568
              case output: Prover.Output =>
wenzelm@56715
   569
                if (output.is_stdout || output.is_stderr) raw_output_messages.post(output)
wenzelm@56709
   570
                else handle_output(output)
wenzelm@56715
   571
                if (output.is_syslog) syslog_messages.post(output)
wenzelm@56715
   572
                all_messages.post(output)
wenzelm@56709
   573
            }
wenzelm@56709
   574
wenzelm@56709
   575
          case change: Session.Change if prover.isDefined =>
wenzelm@56709
   576
            if (global_state.value.is_assigned(change.previous))
wenzelm@56709
   577
              handle_change(change)
wenzelm@56709
   578
            else postponed_changes.store(change)
wenzelm@56706
   579
        }
wenzelm@56709
   580
        true
wenzelm@56709
   581
        //}}}
wenzelm@56709
   582
    }
wenzelm@34777
   583
  }
wenzelm@34777
   584
wenzelm@34809
   585
wenzelm@43716
   586
  /* actions */
wenzelm@34809
   587
wenzelm@56387
   588
  def start(name: String, args: List[String])
wenzelm@56706
   589
  { manager.send(Start(name, args)) }
wenzelm@45076
   590
wenzelm@50117
   591
  def stop()
wenzelm@50117
   592
  {
wenzelm@56709
   593
    manager.send_wait(Stop)
wenzelm@56709
   594
    receiver.shutdown()
wenzelm@56704
   595
    change_parser.shutdown()
wenzelm@56706
   596
    change_buffer.shutdown()
wenzelm@56706
   597
    manager.shutdown()
wenzelm@56715
   598
    dispatcher.shutdown()
wenzelm@50117
   599
  }
wenzelm@38841
   600
wenzelm@53054
   601
  def protocol_command(name: String, args: String*)
wenzelm@56706
   602
  { manager.send(Protocol_Command(name, args.toList)) }
wenzelm@53054
   603
wenzelm@56706
   604
  def cancel_exec(exec_id: Document_ID.Exec)
wenzelm@56706
   605
  { manager.send(Cancel_Exec(exec_id)) }
wenzelm@52931
   606
wenzelm@54521
   607
  def update(doc_blobs: Document.Blobs, edits: List[Document.Edit_Text])
wenzelm@56706
   608
  { if (!edits.isEmpty) manager.send_wait(Session.Raw_Edits(doc_blobs, edits)) }
wenzelm@50498
   609
wenzelm@52084
   610
  def update_options(options: Options)
wenzelm@56706
   611
  { manager.send_wait(Update_Options(options)) }
wenzelm@52084
   612
wenzelm@52531
   613
  def dialog_result(id: Document_ID.Generic, serial: Long, result: String)
wenzelm@56706
   614
  { manager.send(Session.Dialog_Result(id, serial, result)) }
wenzelm@34777
   615
}