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