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