src/Pure/System/session.scala
author wenzelm
Fri Aug 13 18:21:19 2010 +0200 (2010-08-13)
changeset 38370 8b15d0f98962
parent 38366 fea82d1add74
child 38373 e8197eea3cd0
permissions -rw-r--r--
explicit Document.State value, instead of individual state variables in Session, Command, Document;
Session.snapshot: pure value based on Document.State;
Document.edit_texts: no treatment of state assignment here;
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@38370
   142
            case _: Document.Failed_State =>
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@38370
   147
                    catch { case _: Document.Failed_State => 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
              // keyword declarations   // FIXME always global!?
wenzelm@38370
   157
              case List(Keyword.Command_Decl(name, kind)) => syntax += (name, kind)
wenzelm@38370
   158
              case List(Keyword.Keyword_Decl(name)) => syntax += name
wenzelm@38370
   159
              case _ => if (!result.is_ready) bad_result(result)
wenzelm@38370
   160
            }
wenzelm@38370
   161
          }
wenzelm@38370
   162
          else if (result.kind == Markup.EXIT) prover = null
wenzelm@38370
   163
          else if (result.is_raw) raw_output.event(result)
wenzelm@38370
   164
          else if (!result.is_system) bad_result(result)  // FIXME syslog for system messages (!?)
wenzelm@34809
   165
        }
wenzelm@34809
   166
    }
wenzelm@38221
   167
    //}}}
wenzelm@34809
   168
wenzelm@34820
   169
wenzelm@34820
   170
    /* prover startup */
wenzelm@34820
   171
wenzelm@34820
   172
    def startup_error(): String =
wenzelm@34820
   173
    {
wenzelm@34820
   174
      val buf = new StringBuilder
wenzelm@34820
   175
      while (
wenzelm@34820
   176
        receiveWithin(0) {
wenzelm@34820
   177
          case result: Isabelle_Process.Result =>
wenzelm@34820
   178
            if (result.is_raw) {
wenzelm@34820
   179
              for (text <- XML.content(result.message))
wenzelm@34820
   180
                buf.append(text)
wenzelm@34820
   181
            }
wenzelm@34820
   182
            true
wenzelm@34820
   183
          case TIMEOUT => false
wenzelm@34820
   184
        }) {}
wenzelm@34820
   185
      buf.toString
wenzelm@34820
   186
    }
wenzelm@34820
   187
wenzelm@34820
   188
    def prover_startup(timeout: Int): Option[String] =
wenzelm@34820
   189
    {
wenzelm@34820
   190
      receiveWithin(timeout) {
wenzelm@34820
   191
        case result: Isabelle_Process.Result
wenzelm@37689
   192
          if result.kind == Markup.INIT =>
wenzelm@34820
   193
          while (receive {
wenzelm@34820
   194
            case result: Isabelle_Process.Result =>
wenzelm@34820
   195
              handle_result(result); !result.is_ready
wenzelm@34820
   196
            }) {}
wenzelm@34820
   197
          None
wenzelm@34820
   198
wenzelm@34820
   199
        case result: Isabelle_Process.Result
wenzelm@37689
   200
          if result.kind == Markup.EXIT =>
wenzelm@34820
   201
          Some(startup_error())
wenzelm@34820
   202
wenzelm@34820
   203
        case TIMEOUT =>  // FIXME clarify
wenzelm@34820
   204
          prover.kill; Some(startup_error())
wenzelm@34820
   205
      }
wenzelm@34820
   206
    }
wenzelm@34809
   207
wenzelm@34809
   208
wenzelm@34809
   209
    /* main loop */
wenzelm@34809
   210
wenzelm@34820
   211
    val xml_cache = new XML.Cache(131071)
wenzelm@34820
   212
wenzelm@34777
   213
    loop {
wenzelm@34777
   214
      react {
wenzelm@38221
   215
        case Started(timeout, args) =>
wenzelm@34777
   216
          if (prover == null) {
wenzelm@34851
   217
            prover = new Isabelle_Process(system, self, args:_*) with Isar_Document
wenzelm@34820
   218
            val origin = sender
wenzelm@34820
   219
            val opt_err = prover_startup(timeout)
wenzelm@34820
   220
            if (opt_err.isDefined) prover = null
wenzelm@34820
   221
            origin ! opt_err
wenzelm@34820
   222
          }
wenzelm@34820
   223
          else reply(None)
wenzelm@34820
   224
wenzelm@34820
   225
        case Stop =>  // FIXME clarify; synchronous
wenzelm@34820
   226
          if (prover != null) {
wenzelm@34820
   227
            prover.kill
wenzelm@34820
   228
            prover = null
wenzelm@34777
   229
          }
wenzelm@34777
   230
wenzelm@38227
   231
        case change: Document.Change if prover != null =>
wenzelm@34777
   232
          handle_change(change)
wenzelm@34777
   233
wenzelm@34777
   234
        case result: Isabelle_Process.Result =>
wenzelm@34795
   235
          handle_result(result.cache(xml_cache))
wenzelm@34777
   236
wenzelm@36782
   237
        case TIMEOUT =>  // FIXME clarify!
wenzelm@36782
   238
wenzelm@34820
   239
        case bad if prover != null =>
wenzelm@34777
   240
          System.err.println("session_actor: ignoring bad message " + bad)
wenzelm@34777
   241
      }
wenzelm@34777
   242
    }
wenzelm@34777
   243
  }
wenzelm@34777
   244
wenzelm@34809
   245
wenzelm@37129
   246
wenzelm@38226
   247
  /** buffered command changes (delay_first discipline) **/
wenzelm@37129
   248
wenzelm@38221
   249
  private lazy val command_change_buffer = actor
wenzelm@38221
   250
  //{{{
wenzelm@38221
   251
  {
wenzelm@37129
   252
    import scala.compat.Platform.currentTime
wenzelm@37129
   253
wenzelm@37129
   254
    var changed: Set[Command] = Set()
wenzelm@37129
   255
    var flush_time: Option[Long] = None
wenzelm@37129
   256
wenzelm@37129
   257
    def flush_timeout: Long =
wenzelm@37129
   258
      flush_time match {
wenzelm@37129
   259
        case None => 5000L
wenzelm@37129
   260
        case Some(time) => (time - currentTime) max 0
wenzelm@37129
   261
      }
wenzelm@37129
   262
wenzelm@37129
   263
    def flush()
wenzelm@37129
   264
    {
wenzelm@38360
   265
      if (!changed.isEmpty) commands_changed.event(Session.Commands_Changed(changed))
wenzelm@37129
   266
      changed = Set()
wenzelm@37129
   267
      flush_time = None
wenzelm@37129
   268
    }
wenzelm@37129
   269
wenzelm@37129
   270
    def invoke()
wenzelm@37129
   271
    {
wenzelm@37129
   272
      val now = currentTime
wenzelm@37129
   273
      flush_time match {
wenzelm@37849
   274
        case None => flush_time = Some(now + output_delay)
wenzelm@37129
   275
        case Some(time) => if (now >= time) flush()
wenzelm@37129
   276
      }
wenzelm@37129
   277
    }
wenzelm@37129
   278
wenzelm@37129
   279
    loop {
wenzelm@37129
   280
      reactWithin(flush_timeout) {
wenzelm@37129
   281
        case command: Command => changed += command; invoke()
wenzelm@37129
   282
        case TIMEOUT => flush()
wenzelm@37129
   283
        case bad => System.err.println("command_change_buffer: ignoring bad message " + bad)
wenzelm@37129
   284
      }
wenzelm@37129
   285
    }
wenzelm@37129
   286
  }
wenzelm@38221
   287
  //}}}
wenzelm@37129
   288
wenzelm@37129
   289
  def indicate_command_change(command: Command)
wenzelm@37129
   290
  {
wenzelm@37129
   291
    command_change_buffer ! command
wenzelm@37129
   292
  }
wenzelm@37129
   293
wenzelm@37129
   294
wenzelm@38226
   295
wenzelm@38226
   296
  /** editor history **/
wenzelm@38226
   297
wenzelm@38226
   298
  private case class Edit_Document(edits: List[Document.Node_Text_Edit])
wenzelm@38226
   299
wenzelm@38226
   300
  private val editor_history = new Actor
wenzelm@38226
   301
  {
wenzelm@38366
   302
    @volatile private var history = List(Document.Change.init)
wenzelm@38365
   303
wenzelm@38365
   304
    def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   305
    {
wenzelm@38370
   306
      val state_snapshot = current_state()
wenzelm@38366
   307
      val history_snapshot = history
wenzelm@38366
   308
wenzelm@38370
   309
      val found_stable = history_snapshot.find(change =>
wenzelm@38370
   310
        change.is_finished && state_snapshot.is_assigned(change.document.join))
wenzelm@38370
   311
      require(found_stable.isDefined)
wenzelm@38370
   312
      val stable = found_stable.get
wenzelm@38366
   313
      val latest = history_snapshot.head
wenzelm@38365
   314
wenzelm@38365
   315
      val edits =
wenzelm@38366
   316
        (pending_edits /: history_snapshot.takeWhile(_ != stable))((edits, change) =>
wenzelm@38365
   317
            (for ((a, eds) <- change.edits if a == name) yield eds).flatten ::: edits)
wenzelm@38365
   318
      lazy val reverse_edits = edits.reverse
wenzelm@38365
   319
wenzelm@38365
   320
      new Document.Snapshot {
wenzelm@38366
   321
        val document = stable.document.join
wenzelm@38365
   322
        val node = document.nodes(name)
wenzelm@38366
   323
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38365
   324
        def convert(offset: Int): Int = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38365
   325
        def revert(offset: Int): Int = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@38370
   326
        def lookup_command(id: Document.Command_ID): Option[Command] =
wenzelm@38370
   327
          state_snapshot.lookup_command(id)
wenzelm@38370
   328
        def state(command: Command): Command.State =
wenzelm@38370
   329
          state_snapshot.command_state(document, command)
wenzelm@38365
   330
      }
wenzelm@38365
   331
    }
wenzelm@38226
   332
wenzelm@38226
   333
    def act
wenzelm@38226
   334
    {
wenzelm@38226
   335
      loop {
wenzelm@38226
   336
        react {
wenzelm@38226
   337
          case Edit_Document(edits) =>
wenzelm@38366
   338
            val history_snapshot = history
wenzelm@38366
   339
            require(!history_snapshot.isEmpty)
wenzelm@38366
   340
wenzelm@38366
   341
            val prev = history_snapshot.head.document
wenzelm@38226
   342
            val result: isabelle.Future[(List[Document.Edit[Command]], Document)] =
wenzelm@38226
   343
              isabelle.Future.fork {
wenzelm@38366
   344
                val old_doc = prev.join
wenzelm@38370
   345
                val former_assignment = current_state().the_assignment(old_doc).join  // FIXME async!?
wenzelm@38364
   346
                Document.text_edits(Session.this, old_doc, edits)
wenzelm@38226
   347
              }
wenzelm@38366
   348
            val new_change = new Document.Change(prev, edits, result)
wenzelm@38366
   349
            history ::= new_change
wenzelm@38366
   350
            new_change.document.map(_ => session_actor ! new_change)
wenzelm@38260
   351
            reply(())
wenzelm@38226
   352
wenzelm@38226
   353
          case bad => System.err.println("editor_model: ignoring bad message " + bad)
wenzelm@38226
   354
        }
wenzelm@38226
   355
      }
wenzelm@38226
   356
    }
wenzelm@38226
   357
  }
wenzelm@38226
   358
  editor_history.start
wenzelm@38226
   359
wenzelm@38226
   360
wenzelm@38226
   361
wenzelm@38226
   362
  /** main methods **/
wenzelm@34809
   363
wenzelm@38221
   364
  def started(timeout: Int, args: List[String]): Option[String] =
wenzelm@38221
   365
    (session_actor !? Started(timeout, args)).asInstanceOf[Option[String]]
wenzelm@34820
   366
wenzelm@34777
   367
  def stop() { session_actor ! Stop }
wenzelm@38221
   368
wenzelm@38359
   369
  def snapshot(name: String, pending_edits: List[Text_Edit]): Document.Snapshot =
wenzelm@38365
   370
    editor_history.snapshot(name, pending_edits)
wenzelm@38260
   371
wenzelm@38260
   372
  def edit_document(edits: List[Document.Node_Text_Edit]) { editor_history !? Edit_Document(edits) }
wenzelm@34777
   373
}