src/Pure/System/session.scala
author wenzelm
Sat Aug 14 21:25:20 2010 +0200 (2010-08-14)
changeset 38413 224efb14f258
parent 38374 7eb0f6991e25
child 38414 49f1f657adc2
permissions -rw-r--r--
Keyword.status: always suppress position;
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@36676
     5
Isabelle session, potentially with running prover.
wenzelm@36676
     6
*/
wenzelm@34777
     7
wenzelm@34871
     8
package isabelle
wenzelm@34777
     9
wenzelm@34777
    10
wenzelm@34820
    11
import scala.actors.TIMEOUT
wenzelm@38226
    12
import scala.actors.Actor
wenzelm@34777
    13
import scala.actors.Actor._
wenzelm@34777
    14
wenzelm@34815
    15
wenzelm@34791
    16
object Session
wenzelm@34791
    17
{
wenzelm@34813
    18
  /* events */
wenzelm@34813
    19
wenzelm@34791
    20
  case object Global_Settings
wenzelm@37849
    21
  case object Perspective
wenzelm@38360
    22
  case class Commands_Changed(set: Set[Command])
wenzelm@34791
    23
}
wenzelm@34791
    24
wenzelm@34777
    25
wenzelm@34851
    26
class Session(system: Isabelle_System)
wenzelm@34777
    27
{
wenzelm@37849
    28
  /* real time parameters */  // FIXME properties or settings (!?)
wenzelm@37849
    29
wenzelm@37849
    30
  // user input (e.g. text edits, cursor movement)
wenzelm@37849
    31
  val input_delay = 300
wenzelm@37849
    32
wenzelm@37849
    33
  // prover output (markup, common messages)
wenzelm@37849
    34
  val output_delay = 100
wenzelm@37849
    35
wenzelm@37849
    36
  // GUI layout updates
wenzelm@37849
    37
  val update_delay = 500
wenzelm@37849
    38
wenzelm@37849
    39
wenzelm@34809
    40
  /* pervasive event buses */
wenzelm@34809
    41
wenzelm@34809
    42
  val global_settings = new Event_Bus[Session.Global_Settings.type]
wenzelm@34809
    43
  val raw_results = new Event_Bus[Isabelle_Process.Result]
wenzelm@37065
    44
  val raw_output = new Event_Bus[Isabelle_Process.Result]
wenzelm@38360
    45
  val commands_changed = new Event_Bus[Session.Commands_Changed]
wenzelm@37849
    46
  val perspective = new Event_Bus[Session.Perspective.type]
wenzelm@34809
    47
wenzelm@34809
    48
wenzelm@34778
    49
  /* unique ids */
wenzelm@34778
    50
wenzelm@38363
    51
  private var id_count: Document.ID = 0
wenzelm@38363
    52
  def create_id(): Document.ID = synchronized {
wenzelm@38355
    53
    require(id_count > java.lang.Long.MIN_VALUE)
wenzelm@38355
    54
    id_count -= 1
wenzelm@38355
    55
    id_count
wenzelm@38355
    56
  }
wenzelm@34778
    57
wenzelm@34778
    58
wenzelm@34826
    59
wenzelm@34826
    60
  /** main actor **/
wenzelm@34809
    61
wenzelm@34851
    62
  @volatile private var syntax = new Outer_Syntax(system.symbols)
wenzelm@34819
    63
  def current_syntax: Outer_Syntax = syntax
wenzelm@34809
    64
wenzelm@38370
    65
  @volatile private var global_state = Document.State.init
wenzelm@38370
    66
  private def change_state(f: Document.State => Document.State) { global_state = f(global_state) }
wenzelm@38370
    67
  def current_state(): Document.State = global_state
wenzelm@34816
    68
wenzelm@38221
    69
  private case class Started(timeout: Int, args: List[String])
wenzelm@34777
    70
  private case object Stop
wenzelm@34777
    71
wenzelm@37129
    72
  private lazy val session_actor = actor {
wenzelm@34809
    73
wenzelm@34809
    74
    var prover: Isabelle_Process with Isar_Document = null
wenzelm@34809
    75
wenzelm@34809
    76
wenzelm@34809
    77
    /* document changes */
wenzelm@34809
    78
wenzelm@38227
    79
    def handle_change(change: Document.Change)
wenzelm@38221
    80
    //{{{
wenzelm@34809
    81
    {
wenzelm@38366
    82
      require(change.is_finished)
wenzelm@34809
    83
wenzelm@38370
    84
      val old_doc = change.prev.join
wenzelm@38150
    85
      val (node_edits, doc) = change.result.join
wenzelm@38366
    86
wenzelm@38370
    87
      var former_assignment = current_state().the_assignment(old_doc).join
wenzelm@38370
    88
      for {
wenzelm@38370
    89
        (name, Some(cmd_edits)) <- node_edits
wenzelm@38370
    90
        (prev, None) <- cmd_edits
wenzelm@38370
    91
        removed <- old_doc.nodes(name).commands.get_after(prev)
wenzelm@38370
    92
      } former_assignment -= removed
wenzelm@38370
    93
wenzelm@38150
    94
      val id_edits =
wenzelm@38150
    95
        node_edits map {
wenzelm@38150
    96
          case (name, None) => (name, None)
wenzelm@38150
    97
          case (name, Some(cmd_edits)) =>
wenzelm@38370
    98
            val ids =
wenzelm@38150
    99
              cmd_edits map {
wenzelm@38150
   100
                case (c1, c2) =>
wenzelm@38150
   101
                  val id1 = c1.map(_.id)
wenzelm@38150
   102
                  val id2 =
wenzelm@38150
   103
                    c2 match {
wenzelm@38150
   104
                      case None => None
wenzelm@38150
   105
                      case Some(command) =>
wenzelm@38370
   106
                        if (current_state().lookup_command(command.id).isEmpty) {
wenzelm@38370
   107
                          change_state(_.define_command(command))
wenzelm@38150
   108
                          prover.define_command(command.id, system.symbols.encode(command.source))
wenzelm@38150
   109
                        }
wenzelm@38150
   110
                        Some(command.id)
wenzelm@38150
   111
                    }
wenzelm@38150
   112
                  (id1, id2)
wenzelm@38150
   113
              }
wenzelm@38370
   114
            (name -> Some(ids))
wenzelm@38150
   115
        }
wenzelm@38370
   116
      change_state(_.define_document(doc, former_assignment))
wenzelm@38370
   117
      prover.edit_document(old_doc.id, doc.id, id_edits)
wenzelm@34809
   118
    }
wenzelm@38221
   119
    //}}}
wenzelm@34809
   120
wenzelm@34809
   121
wenzelm@34809
   122
    /* prover results */
wenzelm@34809
   123
wenzelm@34836
   124
    def bad_result(result: Isabelle_Process.Result)
wenzelm@34836
   125
    {
wenzelm@37041
   126
      System.err.println("Ignoring prover result: " + result.message.toString)
wenzelm@34836
   127
    }
wenzelm@34836
   128
wenzelm@34809
   129
    def handle_result(result: Isabelle_Process.Result)
wenzelm@38221
   130
    //{{{
wenzelm@34809
   131
    {
wenzelm@34809
   132
      raw_results.event(result)
wenzelm@34799
   133
wenzelm@38370
   134
      Position.get_id(result.properties) match {
wenzelm@38370
   135
        case Some(target_id) =>
wenzelm@38370
   136
          try {
wenzelm@38370
   137
            val (st, state) = global_state.accumulate(target_id, result.message)
wenzelm@38370
   138
            global_state = state
wenzelm@38370
   139
            indicate_command_change(st.command)  // FIXME forward Command.State (!?)
wenzelm@38370
   140
          }
wenzelm@38370
   141
          catch {
wenzelm@38373
   142
            case _: Document.State.Fail =>
wenzelm@38370
   143
              if (result.is_status) {
wenzelm@38370
   144
                result.body match {
wenzelm@38370
   145
                  case List(Isar_Document.Assign(edits)) =>
wenzelm@38370
   146
                    try { change_state(_.assign(target_id, edits)) }
wenzelm@38373
   147
                    catch { case _: Document.State.Fail => bad_result(result) }
wenzelm@38370
   148
                  case _ => bad_result(result)
wenzelm@38370
   149
                }
wenzelm@38370
   150
              }
wenzelm@38370
   151
              else bad_result(result)
wenzelm@38370
   152
          }
wenzelm@38370
   153
        case None =>
wenzelm@38370
   154
          if (result.is_status) {
wenzelm@38370
   155
            result.body match {
wenzelm@38370
   156
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   157
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@38370
   158
              case _ => if (!result.is_ready) bad_result(result)
wenzelm@38370
   159
            }
wenzelm@38370
   160
          }
wenzelm@38370
   161
          else if (result.kind == Markup.EXIT) prover = null
wenzelm@38370
   162
          else if (result.is_raw) raw_output.event(result)
wenzelm@38370
   163
          else if (!result.is_system) bad_result(result)  // FIXME syslog for system messages (!?)
wenzelm@34809
   164
        }
wenzelm@34809
   165
    }
wenzelm@38221
   166
    //}}}
wenzelm@34809
   167
wenzelm@34820
   168
wenzelm@34820
   169
    /* prover startup */
wenzelm@34820
   170
wenzelm@34820
   171
    def startup_error(): String =
wenzelm@34820
   172
    {
wenzelm@34820
   173
      val buf = new StringBuilder
wenzelm@34820
   174
      while (
wenzelm@34820
   175
        receiveWithin(0) {
wenzelm@34820
   176
          case result: Isabelle_Process.Result =>
wenzelm@34820
   177
            if (result.is_raw) {
wenzelm@34820
   178
              for (text <- XML.content(result.message))
wenzelm@34820
   179
                buf.append(text)
wenzelm@34820
   180
            }
wenzelm@34820
   181
            true
wenzelm@34820
   182
          case TIMEOUT => false
wenzelm@34820
   183
        }) {}
wenzelm@34820
   184
      buf.toString
wenzelm@34820
   185
    }
wenzelm@34820
   186
wenzelm@34820
   187
    def prover_startup(timeout: Int): Option[String] =
wenzelm@34820
   188
    {
wenzelm@34820
   189
      receiveWithin(timeout) {
wenzelm@34820
   190
        case result: Isabelle_Process.Result
wenzelm@37689
   191
          if result.kind == Markup.INIT =>
wenzelm@34820
   192
          while (receive {
wenzelm@34820
   193
            case result: Isabelle_Process.Result =>
wenzelm@34820
   194
              handle_result(result); !result.is_ready
wenzelm@34820
   195
            }) {}
wenzelm@34820
   196
          None
wenzelm@34820
   197
wenzelm@34820
   198
        case result: Isabelle_Process.Result
wenzelm@37689
   199
          if result.kind == Markup.EXIT =>
wenzelm@34820
   200
          Some(startup_error())
wenzelm@34820
   201
wenzelm@34820
   202
        case TIMEOUT =>  // FIXME clarify
wenzelm@34820
   203
          prover.kill; Some(startup_error())
wenzelm@34820
   204
      }
wenzelm@34820
   205
    }
wenzelm@34809
   206
wenzelm@34809
   207
wenzelm@34809
   208
    /* main loop */
wenzelm@34809
   209
wenzelm@34820
   210
    val xml_cache = new XML.Cache(131071)
wenzelm@34820
   211
wenzelm@34777
   212
    loop {
wenzelm@34777
   213
      react {
wenzelm@38221
   214
        case Started(timeout, args) =>
wenzelm@34777
   215
          if (prover == null) {
wenzelm@34851
   216
            prover = new Isabelle_Process(system, self, args:_*) with Isar_Document
wenzelm@34820
   217
            val origin = sender
wenzelm@34820
   218
            val opt_err = prover_startup(timeout)
wenzelm@34820
   219
            if (opt_err.isDefined) prover = null
wenzelm@34820
   220
            origin ! opt_err
wenzelm@34820
   221
          }
wenzelm@34820
   222
          else reply(None)
wenzelm@34820
   223
wenzelm@34820
   224
        case Stop =>  // FIXME clarify; synchronous
wenzelm@34820
   225
          if (prover != null) {
wenzelm@34820
   226
            prover.kill
wenzelm@34820
   227
            prover = null
wenzelm@34777
   228
          }
wenzelm@34777
   229
wenzelm@38227
   230
        case change: Document.Change if prover != null =>
wenzelm@34777
   231
          handle_change(change)
wenzelm@34777
   232
wenzelm@34777
   233
        case result: Isabelle_Process.Result =>
wenzelm@34795
   234
          handle_result(result.cache(xml_cache))
wenzelm@34777
   235
wenzelm@36782
   236
        case TIMEOUT =>  // FIXME clarify!
wenzelm@36782
   237
wenzelm@34820
   238
        case bad if prover != null =>
wenzelm@34777
   239
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   240
      }
wenzelm@34777
   241
    }
wenzelm@34777
   242
  }
wenzelm@34777
   243
wenzelm@34809
   244
wenzelm@37129
   245
wenzelm@38226
   246
  /** buffered command changes (delay_first discipline) **/
wenzelm@37129
   247
wenzelm@38221
   248
  private lazy val command_change_buffer = actor
wenzelm@38221
   249
  //{{{
wenzelm@38221
   250
  {
wenzelm@37129
   251
    import scala.compat.Platform.currentTime
wenzelm@37129
   252
wenzelm@37129
   253
    var changed: Set[Command] = Set()
wenzelm@37129
   254
    var flush_time: Option[Long] = None
wenzelm@37129
   255
wenzelm@37129
   256
    def flush_timeout: Long =
wenzelm@37129
   257
      flush_time match {
wenzelm@37129
   258
        case None => 5000L
wenzelm@37129
   259
        case Some(time) => (time - currentTime) max 0
wenzelm@37129
   260
      }
wenzelm@37129
   261
wenzelm@37129
   262
    def flush()
wenzelm@37129
   263
    {
wenzelm@38360
   264
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@37129
   265
      changed = Set()
wenzelm@37129
   266
      flush_time = None
wenzelm@37129
   267
    }
wenzelm@37129
   268
wenzelm@37129
   269
    def invoke()
wenzelm@37129
   270
    {
wenzelm@37129
   271
      val now = currentTime
wenzelm@37129
   272
      flush_time match {
wenzelm@37849
   273
        case None => flush_time = Some(now + output_delay)
wenzelm@37129
   274
        case Some(time) => if (now >= time) flush()
wenzelm@37129
   275
      }
wenzelm@37129
   276
    }
wenzelm@37129
   277
wenzelm@37129
   278
    loop {
wenzelm@37129
   279
      reactWithin(flush_timeout) {
wenzelm@37129
   280
        case command: Command => changed += command; invoke()
wenzelm@37129
   281
        case TIMEOUT => flush()
wenzelm@37129
   282
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@37129
   283
      }
wenzelm@37129
   284
    }
wenzelm@37129
   285
  }
wenzelm@38221
   286
  //}}}
wenzelm@37129
   287
wenzelm@37129
   288
  def indicate_command_change(command: Command)
wenzelm@37129
   289
  {
wenzelm@37129
   290
    command_change_buffer ! command
wenzelm@37129
   291
  }
wenzelm@37129
   292
wenzelm@37129
   293
wenzelm@38226
   294
wenzelm@38226
   295
  /** editor history **/
wenzelm@38226
   296
wenzelm@38226
   297
  private case class Edit_Document(edits: List[Document.Node_Text_Edit])
wenzelm@38226
   298
wenzelm@38226
   299
  private val editor_history = new Actor
wenzelm@38226
   300
  {
wenzelm@38366
   301
    @volatile private var history = List(Document.Change.init)
wenzelm@38365
   302
wenzelm@38365
   303
    def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   304
    {
wenzelm@38370
   305
      val state_snapshot = current_state()
wenzelm@38366
   306
      val history_snapshot = history
wenzelm@38366
   307
wenzelm@38370
   308
      val found_stable = history_snapshot.find(change =>
wenzelm@38370
   309
        change.is_finished && state_snapshot.is_assigned(change.document.join))
wenzelm@38370
   310
      require(found_stable.isDefined)
wenzelm@38370
   311
      val stable = found_stable.get
wenzelm@38366
   312
      val latest = history_snapshot.head
wenzelm@38365
   313
wenzelm@38365
   314
      val edits =
wenzelm@38366
   315
        (pending_edits /: history_snapshot.takeWhile(_ != stable))((edits, change) =>
wenzelm@38365
   316
            (for ((a, eds) <- change.edits if a == name) yield eds).flatten ::: edits)
wenzelm@38365
   317
      lazy val reverse_edits = edits.reverse
wenzelm@38365
   318
wenzelm@38365
   319
      new Document.Snapshot {
wenzelm@38366
   320
        val document = stable.document.join
wenzelm@38365
   321
        val node = document.nodes(name)
wenzelm@38366
   322
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38365
   323
        def convert(offset: Int): Int = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38365
   324
        def revert(offset: Int): Int = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@38370
   325
        def lookup_command(id: Document.Command_ID): Option[Command] =
wenzelm@38370
   326
          state_snapshot.lookup_command(id)
wenzelm@38370
   327
        def state(command: Command): Command.State =
wenzelm@38370
   328
          state_snapshot.command_state(document, command)
wenzelm@38365
   329
      }
wenzelm@38365
   330
    }
wenzelm@38226
   331
wenzelm@38226
   332
    def act
wenzelm@38226
   333
    {
wenzelm@38226
   334
      loop {
wenzelm@38226
   335
        react {
wenzelm@38226
   336
          case Edit_Document(edits) =>
wenzelm@38366
   337
            val history_snapshot = history
wenzelm@38366
   338
            require(!history_snapshot.isEmpty)
wenzelm@38366
   339
wenzelm@38366
   340
            val prev = history_snapshot.head.document
wenzelm@38226
   341
            val result: isabelle.Future[(List[Document.Edit[Command]], Document)] =
wenzelm@38226
   342
              isabelle.Future.fork {
wenzelm@38366
   343
                val old_doc = prev.join
wenzelm@38370
   344
                val former_assignment = current_state().the_assignment(old_doc).join  // FIXME async!?
wenzelm@38374
   345
                Thy_Syntax.text_edits(Session.this, old_doc, edits)
wenzelm@38226
   346
              }
wenzelm@38366
   347
            val new_change = new Document.Change(prev, edits, result)
wenzelm@38366
   348
            history ::= new_change
wenzelm@38366
   349
            new_change.document.map(_ => session_actor ! new_change)
wenzelm@38260
   350
            reply(())
wenzelm@38226
   351
wenzelm@38226
   352
          case bad => System.err.println("editor_model: ignoring bad message " + bad)
wenzelm@38226
   353
        }
wenzelm@38226
   354
      }
wenzelm@38226
   355
    }
wenzelm@38226
   356
  }
wenzelm@38226
   357
  editor_history.start
wenzelm@38226
   358
wenzelm@38226
   359
wenzelm@38226
   360
wenzelm@38226
   361
  /** main methods **/
wenzelm@34809
   362
wenzelm@38221
   363
  def started(timeout: Int, args: List[String]): Option[String] =
wenzelm@38221
   364
    (session_actor !? Started(timeout, args)).asInstanceOf[Option[String]]
wenzelm@34820
   365
wenzelm@34777
   366
  def stop() { session_actor ! Stop }
wenzelm@38221
   367
wenzelm@38359
   368
  def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   369
    editor_history.snapshot(name, pending_edits)
wenzelm@38260
   370
wenzelm@38260
   371
  def edit_document(edits: List[Document.Node_Text_Edit]) { editor_history !? Edit_Document(edits) }
wenzelm@34777
   372
}