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