src/Pure/PIDE/document.scala
author wenzelm
Wed Aug 07 11:44:17 2013 +0200 (2013-08-07)
changeset 52887 98eac7b7eec3
parent 52862 930ce8eacb87
child 52889 ea3338812e67
permissions -rw-r--r--
tuned signature;
wenzelm@36676
     1
/*  Title:      Pure/PIDE/document.scala
wenzelm@36676
     2
    Author:     Makarius
wenzelm@36676
     3
wenzelm@38150
     4
Document as collection of named nodes, each consisting of an editable
wenzelm@38418
     5
list of commands, associated with asynchronous execution process.
wenzelm@36676
     6
*/
wenzelm@34407
     7
wenzelm@34871
     8
package isabelle
wenzelm@34318
     9
wenzelm@34760
    10
wenzelm@38150
    11
import scala.collection.mutable
wenzelm@37073
    12
wenzelm@37073
    13
wenzelm@34823
    14
object Document
wenzelm@34483
    15
{
wenzelm@38424
    16
  /** document structure **/
wenzelm@38424
    17
wenzelm@46723
    18
  /* individual nodes */
wenzelm@38424
    19
wenzelm@44615
    20
  type Edit[A, B] = (Node.Name, Node.Edit[A, B])
wenzelm@44384
    21
  type Edit_Text = Edit[Text.Edit, Text.Perspective]
wenzelm@52849
    22
  type Edit_Command = Edit[Command.Edit, Command.Perspective]
wenzelm@38151
    23
wenzelm@38151
    24
  object Node
wenzelm@38151
    25
  {
wenzelm@52887
    26
    val empty: Node = new Node()
wenzelm@52887
    27
wenzelm@52887
    28
wenzelm@52887
    29
    /* header and name */
wenzelm@52887
    30
wenzelm@48707
    31
    sealed case class Header(
wenzelm@46938
    32
      imports: List[Name],
wenzelm@48706
    33
      keywords: Thy_Header.Keywords,
wenzelm@48707
    34
      errors: List[String] = Nil)
wenzelm@48707
    35
    {
wenzelm@48707
    36
      def error(msg: String): Header = copy(errors = errors ::: List(msg))
wenzelm@48707
    37
    }
wenzelm@48707
    38
wenzelm@51294
    39
    def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
wenzelm@46737
    40
wenzelm@44957
    41
    object Name
wenzelm@44957
    42
    {
wenzelm@44957
    43
      val empty = Name("", "", "")
wenzelm@46723
    44
wenzelm@46723
    45
      object Ordering extends scala.math.Ordering[Name]
wenzelm@46723
    46
      {
wenzelm@46723
    47
        def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
wenzelm@46723
    48
      }
wenzelm@44957
    49
    }
wenzelm@52887
    50
wenzelm@44616
    51
    sealed case class Name(node: String, dir: String, theory: String)
wenzelm@44615
    52
    {
wenzelm@44615
    53
      override def hashCode: Int = node.hashCode
wenzelm@44615
    54
      override def equals(that: Any): Boolean =
wenzelm@44615
    55
        that match {
wenzelm@44615
    56
          case other: Name => node == other.node
wenzelm@44615
    57
          case _ => false
wenzelm@44615
    58
        }
wenzelm@44642
    59
      override def toString: String = theory
wenzelm@44615
    60
    }
wenzelm@44615
    61
wenzelm@52887
    62
wenzelm@52887
    63
    /* overlays -- print functions with arguments */
wenzelm@52887
    64
wenzelm@52887
    65
    type Overlay = (Command, (String, List[String]))
wenzelm@52887
    66
wenzelm@52887
    67
    object Overlays
wenzelm@52887
    68
    {
wenzelm@52887
    69
      val empty = new Overlays(Map.empty)
wenzelm@52887
    70
    }
wenzelm@52887
    71
wenzelm@52887
    72
    final class Overlays private(rep: Map[Command, List[(String, List[String])]])
wenzelm@52887
    73
    {
wenzelm@52887
    74
      def commands: Set[Command] = rep.keySet
wenzelm@52887
    75
      def is_empty: Boolean = rep.isEmpty
wenzelm@52887
    76
wenzelm@52887
    77
      def insert(cmd: Command, over: (String, List[String])): Overlays =
wenzelm@52887
    78
      {
wenzelm@52887
    79
        val overs = rep.getOrElse(cmd, Nil)
wenzelm@52887
    80
        if (overs.contains(over)) this
wenzelm@52887
    81
        else new Overlays(rep + (cmd -> (over :: overs)))
wenzelm@52887
    82
      }
wenzelm@52887
    83
wenzelm@52887
    84
      def remove(cmd: Command, over: (String, List[String])): Overlays =
wenzelm@52887
    85
        rep.get(cmd) match {
wenzelm@52887
    86
          case Some(overs) =>
wenzelm@52887
    87
            if (overs.contains(over)) {
wenzelm@52887
    88
              overs.filterNot(_ == over) match {
wenzelm@52887
    89
                case Nil => new Overlays(rep - cmd)
wenzelm@52887
    90
                case overs1 => new Overlays(rep + (cmd -> overs1))
wenzelm@52887
    91
              }
wenzelm@52887
    92
            }
wenzelm@52887
    93
            else this
wenzelm@52887
    94
          case None => this
wenzelm@52887
    95
        }
wenzelm@52887
    96
wenzelm@52887
    97
      def dest: List[Overlay] =
wenzelm@52887
    98
        (for {
wenzelm@52887
    99
          (cmd, overs) <- rep.iterator
wenzelm@52887
   100
          over <- overs
wenzelm@52887
   101
        } yield (cmd, over)).toList
wenzelm@52887
   102
    }
wenzelm@52887
   103
wenzelm@52887
   104
wenzelm@52887
   105
    /* edits */
wenzelm@52887
   106
wenzelm@44384
   107
    sealed abstract class Edit[A, B]
wenzelm@44156
   108
    {
wenzelm@44383
   109
      def foreach(f: A => Unit)
wenzelm@44383
   110
      {
wenzelm@44156
   111
        this match {
wenzelm@44383
   112
          case Edits(es) => es.foreach(f)
wenzelm@44383
   113
          case _ =>
wenzelm@44156
   114
        }
wenzelm@44383
   115
      }
wenzelm@44156
   116
    }
wenzelm@44384
   117
    case class Clear[A, B]() extends Edit[A, B]
wenzelm@44384
   118
    case class Edits[A, B](edits: List[A]) extends Edit[A, B]
wenzelm@48707
   119
    case class Deps[A, B](header: Header) extends Edit[A, B]
wenzelm@52849
   120
    case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
wenzelm@52808
   121
    type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
wenzelm@52849
   122
    type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
wenzelm@44156
   123
wenzelm@52887
   124
wenzelm@52887
   125
    /* commands */
wenzelm@52887
   126
wenzelm@38426
   127
    def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
wenzelm@38426
   128
      : Iterator[(Command, Text.Offset)] =
wenzelm@38227
   129
    {
wenzelm@38227
   130
      var i = offset
wenzelm@38227
   131
      for (command <- commands) yield {
wenzelm@38227
   132
        val start = i
wenzelm@38227
   133
        i += command.length
wenzelm@38227
   134
        (command, start)
wenzelm@38227
   135
      }
wenzelm@38227
   136
    }
wenzelm@46680
   137
wenzelm@46680
   138
    private val block_size = 1024
wenzelm@38151
   139
  }
wenzelm@38151
   140
wenzelm@46712
   141
  final class Node private(
wenzelm@48707
   142
    val header: Node.Header = Node.bad_header("Bad theory header"),
wenzelm@52849
   143
    val perspective: Node.Perspective_Command =
wenzelm@52887
   144
      Node.Perspective(false, Command.Perspective.empty, Node.Overlays.empty),
wenzelm@46677
   145
    val commands: Linear_Set[Command] = Linear_Set.empty)
wenzelm@38151
   146
  {
wenzelm@46680
   147
    def clear: Node = new Node(header = header)
wenzelm@46680
   148
wenzelm@48707
   149
    def update_header(new_header: Node.Header): Node =
wenzelm@49678
   150
      new Node(new_header, perspective, commands)
wenzelm@46680
   151
wenzelm@52849
   152
    def update_perspective(new_perspective: Node.Perspective_Command): Node =
wenzelm@49678
   153
      new Node(header, new_perspective, commands)
wenzelm@46680
   154
wenzelm@52849
   155
    def same_perspective(other_perspective: Node.Perspective_Command): Boolean =
wenzelm@52849
   156
      perspective.required == other_perspective.required &&
wenzelm@52849
   157
      perspective.visible.same(other_perspective.visible) &&
wenzelm@52849
   158
      perspective.overlays == other_perspective.overlays
wenzelm@52808
   159
wenzelm@46680
   160
    def update_commands(new_commands: Linear_Set[Command]): Node =
wenzelm@49678
   161
      new Node(header, perspective, new_commands)
wenzelm@44443
   162
wenzelm@44443
   163
wenzelm@43697
   164
    /* commands */
wenzelm@43697
   165
wenzelm@38879
   166
    private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
wenzelm@38879
   167
    {
wenzelm@38879
   168
      val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
wenzelm@38879
   169
      var next_block = 0
wenzelm@38879
   170
      var last_stop = 0
wenzelm@38879
   171
      for ((command, start) <- Node.command_starts(commands.iterator)) {
wenzelm@38879
   172
        last_stop = start + command.length
wenzelm@38885
   173
        while (last_stop + 1 > next_block) {
wenzelm@38879
   174
          blocks += (command -> start)
wenzelm@46680
   175
          next_block += Node.block_size
wenzelm@38879
   176
        }
wenzelm@38879
   177
      }
wenzelm@38879
   178
      (blocks.toArray, Text.Range(0, last_stop))
wenzelm@38879
   179
    }
wenzelm@38151
   180
wenzelm@38879
   181
    def full_range: Text.Range = full_index._2
wenzelm@38151
   182
wenzelm@38569
   183
    def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
wenzelm@38879
   184
    {
wenzelm@38879
   185
      if (!commands.isEmpty && full_range.contains(i)) {
wenzelm@46680
   186
        val (cmd0, start0) = full_index._1(i / Node.block_size)
wenzelm@38879
   187
        Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
wenzelm@38879
   188
          case (cmd, start) => start + cmd.length <= i }
wenzelm@38879
   189
      }
wenzelm@38879
   190
      else Iterator.empty
wenzelm@38879
   191
    }
wenzelm@38151
   192
wenzelm@38569
   193
    def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
wenzelm@38569
   194
      command_range(range.start) takeWhile { case (_, start) => start < range.stop }
wenzelm@38151
   195
wenzelm@38426
   196
    def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
wenzelm@38151
   197
    {
wenzelm@38151
   198
      val range = command_range(i)
wenzelm@38151
   199
      if (range.hasNext) Some(range.next) else None
wenzelm@38151
   200
    }
wenzelm@38151
   201
wenzelm@38879
   202
    def command_start(cmd: Command): Option[Text.Offset] =
wenzelm@46677
   203
      Node.command_starts(commands.iterator).find(_._1 == cmd).map(_._2)
wenzelm@38151
   204
  }
wenzelm@38151
   205
wenzelm@38151
   206
wenzelm@46723
   207
  /* development graph */
wenzelm@46723
   208
wenzelm@46723
   209
  object Nodes
wenzelm@46723
   210
  {
wenzelm@46723
   211
    val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
wenzelm@46723
   212
  }
wenzelm@46723
   213
wenzelm@46723
   214
  final class Nodes private(graph: Graph[Node.Name, Node])
wenzelm@46723
   215
  {
wenzelm@46723
   216
    def get_name(s: String): Option[Node.Name] =
wenzelm@46723
   217
      graph.keys.find(name => name.node == s)
wenzelm@46723
   218
wenzelm@46723
   219
    def apply(name: Node.Name): Node =
wenzelm@46723
   220
      graph.default_node(name, Node.empty).get_node(name)
wenzelm@46723
   221
wenzelm@46723
   222
    def + (entry: (Node.Name, Node)): Nodes =
wenzelm@46723
   223
    {
wenzelm@46723
   224
      val (name, node) = entry
wenzelm@48707
   225
      val imports = node.header.imports
wenzelm@46723
   226
      val graph1 =
wenzelm@46739
   227
        (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
wenzelm@46723
   228
      val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
wenzelm@46739
   229
      val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
wenzelm@46723
   230
      new Nodes(graph3.map_node(name, _ => node))
wenzelm@46723
   231
    }
wenzelm@46723
   232
wenzelm@46723
   233
    def entries: Iterator[(Node.Name, Node)] =
wenzelm@46723
   234
      graph.entries.map({ case (name, (node, _)) => (name, node) })
wenzelm@46723
   235
wenzelm@46942
   236
    def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
wenzelm@46723
   237
    def topological_order: List[Node.Name] = graph.topological_order
wenzelm@46723
   238
  }
wenzelm@46723
   239
wenzelm@46723
   240
wenzelm@38424
   241
wenzelm@38424
   242
  /** versioning **/
wenzelm@38424
   243
wenzelm@38424
   244
  /* particular document versions */
wenzelm@34485
   245
wenzelm@38417
   246
  object Version
wenzelm@38417
   247
  {
wenzelm@46681
   248
    val init: Version = new Version()
wenzelm@46681
   249
wenzelm@46941
   250
    def make(syntax: Outer_Syntax, nodes: Nodes): Version =
wenzelm@52530
   251
      new Version(Document_ID.make(), syntax, nodes)
wenzelm@38417
   252
  }
wenzelm@38417
   253
wenzelm@46712
   254
  final class Version private(
wenzelm@52530
   255
    val id: Document_ID.Version = Document_ID.none,
wenzelm@46941
   256
    val syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@46723
   257
    val nodes: Nodes = Nodes.empty)
wenzelm@46941
   258
  {
wenzelm@52530
   259
    def is_init: Boolean = id == Document_ID.none
wenzelm@46941
   260
  }
immler@34660
   261
wenzelm@34859
   262
wenzelm@38424
   263
  /* changes of plain text, eventually resulting in document edits */
wenzelm@38227
   264
wenzelm@38227
   265
  object Change
wenzelm@38227
   266
  {
wenzelm@46678
   267
    val init: Change = new Change()
wenzelm@46678
   268
wenzelm@46678
   269
    def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
wenzelm@46678
   270
      new Change(Some(previous), edits, version)
wenzelm@38227
   271
  }
wenzelm@38227
   272
wenzelm@46712
   273
  final class Change private(
wenzelm@46677
   274
    val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
wenzelm@46677
   275
    val edits: List[Edit_Text] = Nil,
wenzelm@46677
   276
    val version: Future[Version] = Future.value(Version.init))
wenzelm@38227
   277
  {
wenzelm@44672
   278
    def is_finished: Boolean =
wenzelm@44672
   279
      (previous match { case None => true case Some(future) => future.is_finished }) &&
wenzelm@44672
   280
      version.is_finished
wenzelm@44672
   281
wenzelm@46678
   282
    def truncate: Change = new Change(None, Nil, version)
wenzelm@38227
   283
  }
wenzelm@38227
   284
wenzelm@38227
   285
wenzelm@38841
   286
  /* history navigation */
wenzelm@38841
   287
wenzelm@38841
   288
  object History
wenzelm@38841
   289
  {
wenzelm@46679
   290
    val init: History = new History()
wenzelm@38841
   291
  }
wenzelm@38841
   292
wenzelm@46712
   293
  final class History private(
wenzelm@46679
   294
    val undo_list: List[Change] = List(Change.init))  // non-empty list
wenzelm@38841
   295
  {
wenzelm@46679
   296
    def tip: Change = undo_list.head
wenzelm@46679
   297
    def + (change: Change): History = new History(change :: undo_list)
wenzelm@38841
   298
wenzelm@46679
   299
    def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
wenzelm@46679
   300
    {
wenzelm@46679
   301
      val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
wenzelm@46679
   302
      val (retained, dropped) = undo_list.splitAt(n max retain)
wenzelm@46679
   303
wenzelm@46679
   304
      retained.splitAt(retained.length - 1) match {
wenzelm@46679
   305
        case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
wenzelm@46679
   306
        case _ => None
wenzelm@46679
   307
      }
wenzelm@46679
   308
    }
wenzelm@38841
   309
  }
wenzelm@38841
   310
wenzelm@38841
   311
wenzelm@38841
   312
wenzelm@38841
   313
  /** global state -- document structure, execution process, editing history **/
wenzelm@38424
   314
wenzelm@38424
   315
  abstract class Snapshot
wenzelm@38424
   316
  {
wenzelm@44582
   317
    val state: State
wenzelm@38424
   318
    val version: Version
wenzelm@48923
   319
    val node_name: Node.Name
wenzelm@38424
   320
    val node: Node
wenzelm@38424
   321
    val is_outdated: Boolean
wenzelm@38427
   322
    def convert(i: Text.Offset): Text.Offset
wenzelm@39177
   323
    def convert(range: Text.Range): Text.Range
wenzelm@38427
   324
    def revert(i: Text.Offset): Text.Offset
wenzelm@39177
   325
    def revert(range: Text.Range): Text.Range
wenzelm@51494
   326
    def eq_content(other: Snapshot): Boolean
wenzelm@52508
   327
    def cumulate_markup[A](
wenzelm@52508
   328
      range: Text.Range,
wenzelm@52508
   329
      info: A,
wenzelm@52508
   330
      elements: Option[Set[String]],
wenzelm@50500
   331
      result: Command.State => PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]]
wenzelm@52508
   332
    def select_markup[A](
wenzelm@52508
   333
      range: Text.Range,
wenzelm@52508
   334
      elements: Option[Set[String]],
wenzelm@50500
   335
      result: Command.State => PartialFunction[Text.Markup, A]): Stream[Text.Info[A]]
wenzelm@38424
   336
  }
wenzelm@38424
   337
wenzelm@52563
   338
  type Assign_Update =
wenzelm@52563
   339
    List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
wenzelm@44476
   340
wenzelm@38370
   341
  object State
wenzelm@38370
   342
  {
wenzelm@38373
   343
    class Fail(state: State) extends Exception
wenzelm@38373
   344
wenzelm@44479
   345
    object Assignment
wenzelm@44479
   346
    {
wenzelm@46683
   347
      val init: Assignment = new Assignment()
wenzelm@44479
   348
    }
wenzelm@38370
   349
wenzelm@46712
   350
    final class Assignment private(
wenzelm@52530
   351
      val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
wenzelm@46677
   352
      val is_finished: Boolean = false)
wenzelm@38370
   353
    {
wenzelm@44477
   354
      def check_finished: Assignment = { require(is_finished); this }
wenzelm@47388
   355
      def unfinished: Assignment = new Assignment(command_execs, false)
wenzelm@44479
   356
wenzelm@52563
   357
      def assign(update: Assign_Update): Assignment =
wenzelm@38370
   358
      {
wenzelm@38976
   359
        require(!is_finished)
wenzelm@44479
   360
        val command_execs1 =
wenzelm@52563
   361
          (command_execs /: update) {
wenzelm@52563
   362
            case (res, (command_id, exec_ids)) =>
wenzelm@52563
   363
              if (exec_ids.isEmpty) res - command_id
wenzelm@52563
   364
              else res + (command_id -> exec_ids)
wenzelm@44479
   365
          }
wenzelm@47388
   366
        new Assignment(command_execs1, true)
wenzelm@38150
   367
      }
wenzelm@38370
   368
    }
wenzelm@46682
   369
wenzelm@46682
   370
    val init: State =
wenzelm@52563
   371
      State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
wenzelm@38370
   372
  }
wenzelm@38370
   373
wenzelm@46712
   374
  final case class State private(
wenzelm@52530
   375
    val versions: Map[Document_ID.Version, Version] = Map.empty,
wenzelm@52530
   376
    val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
wenzelm@52530
   377
    val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
wenzelm@52530
   378
    val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
wenzelm@38841
   379
    val history: History = History.init)
wenzelm@38370
   380
  {
wenzelm@38373
   381
    private def fail[A]: A = throw new State.Fail(this)
wenzelm@38370
   382
wenzelm@44479
   383
    def define_version(version: Version, assignment: State.Assignment): State =
wenzelm@38370
   384
    {
wenzelm@38417
   385
      val id = version.id
wenzelm@38417
   386
      copy(versions = versions + (id -> version),
wenzelm@44479
   387
        assignments = assignments + (id -> assignment.unfinished))
wenzelm@38370
   388
    }
wenzelm@38370
   389
wenzelm@38373
   390
    def define_command(command: Command): State =
wenzelm@38373
   391
    {
wenzelm@38373
   392
      val id = command.id
wenzelm@49414
   393
      copy(commands = commands + (id -> command.init_state))
wenzelm@38373
   394
    }
wenzelm@38373
   395
wenzelm@52530
   396
    def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
wenzelm@44582
   397
wenzelm@52531
   398
    def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
wenzelm@44582
   399
      commands.get(id) orElse execs.get(id) match {
wenzelm@44582
   400
        case None => None
wenzelm@44582
   401
        case Some(st) =>
wenzelm@44582
   402
          val command = st.command
wenzelm@46681
   403
          val node = version.nodes(command.node_name)
wenzelm@46681
   404
          Some((node, command))
wenzelm@44582
   405
      }
wenzelm@38373
   406
wenzelm@52530
   407
    def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
wenzelm@52564
   408
    def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
wenzelm@52564
   409
    def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
wenzelm@52563
   410
    def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
wenzelm@38370
   411
wenzelm@52531
   412
    def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
wenzelm@38370
   413
      execs.get(id) match {
wenzelm@44446
   414
        case Some(st) =>
wenzelm@49527
   415
          val new_st = st + (id, message)
wenzelm@44446
   416
          (new_st, copy(execs = execs + (id -> new_st)))
wenzelm@38370
   417
        case None =>
wenzelm@38370
   418
          commands.get(id) match {
wenzelm@38370
   419
            case Some(st) =>
wenzelm@49527
   420
              val new_st = st + (id, message)
wenzelm@38370
   421
              (new_st, copy(commands = commands + (id -> new_st)))
wenzelm@38370
   422
            case None => fail
wenzelm@38370
   423
          }
wenzelm@38370
   424
      }
wenzelm@38370
   425
wenzelm@52563
   426
    def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
wenzelm@38370
   427
    {
wenzelm@38417
   428
      val version = the_version(id)
wenzelm@38370
   429
wenzelm@52566
   430
      def upd(exec_id: Document_ID.Exec, st: Command.State)
wenzelm@52566
   431
          : Option[(Document_ID.Exec, Command.State)] =
wenzelm@52566
   432
        if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
wenzelm@52566
   433
wenzelm@44543
   434
      val (changed_commands, new_execs) =
wenzelm@52563
   435
        ((Nil: List[Command], execs) /: update) {
wenzelm@52566
   436
          case ((commands1, execs1), (command_id, exec)) =>
wenzelm@52566
   437
            val st = the_static_state(command_id)
wenzelm@52566
   438
            val command = st.command
wenzelm@52527
   439
            val commands2 = command :: commands1
wenzelm@44543
   440
            val execs2 =
wenzelm@44543
   441
              exec match {
wenzelm@52527
   442
                case Nil => execs1
wenzelm@52527
   443
                case eval_id :: print_ids =>
wenzelm@52566
   444
                  execs1 ++ upd(eval_id, st) ++
wenzelm@52566
   445
                    (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
wenzelm@44543
   446
              }
wenzelm@44543
   447
            (commands2, execs2)
wenzelm@38370
   448
        }
wenzelm@52563
   449
      val new_assignment = the_assignment(version).assign(update)
wenzelm@43722
   450
      val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
wenzelm@44476
   451
wenzelm@44543
   452
      (changed_commands, new_state)
wenzelm@38370
   453
    }
wenzelm@38370
   454
wenzelm@38417
   455
    def is_assigned(version: Version): Boolean =
wenzelm@43722
   456
      assignments.get(version.id) match {
wenzelm@38370
   457
        case Some(assgn) => assgn.is_finished
wenzelm@38370
   458
        case None => false
wenzelm@38370
   459
      }
wenzelm@38370
   460
wenzelm@44436
   461
    def is_stable(change: Change): Boolean =
wenzelm@44436
   462
      change.is_finished && is_assigned(change.version.get_finished)
wenzelm@44436
   463
wenzelm@46944
   464
    def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
wenzelm@44672
   465
    def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
wenzelm@44436
   466
    def tip_stable: Boolean = is_stable(history.tip)
wenzelm@44475
   467
    def tip_version: Version = history.tip.version.get_finished
wenzelm@44436
   468
wenzelm@44446
   469
    def continue_history(
wenzelm@44446
   470
        previous: Future[Version],
wenzelm@40479
   471
        edits: List[Edit_Text],
wenzelm@43722
   472
        version: Future[Version]): (Change, State) =
wenzelm@38841
   473
    {
wenzelm@46678
   474
      val change = Change.make(previous, edits, version)
wenzelm@38841
   475
      (change, copy(history = history + change))
wenzelm@38841
   476
    }
wenzelm@38841
   477
wenzelm@44672
   478
    def prune_history(retain: Int = 0): (List[Version], State) =
wenzelm@44672
   479
    {
wenzelm@46679
   480
      history.prune(is_stable, retain) match {
wenzelm@46679
   481
        case Some((dropped, history1)) =>
wenzelm@44672
   482
          val dropped_versions = dropped.map(change => change.version.get_finished)
wenzelm@46679
   483
          val state1 = copy(history = history1)
wenzelm@44672
   484
          (dropped_versions, state1)
wenzelm@46679
   485
        case None => fail
wenzelm@44672
   486
      }
wenzelm@44672
   487
    }
wenzelm@44672
   488
wenzelm@52530
   489
    def removed_versions(removed: List[Document_ID.Version]): State =
wenzelm@44676
   490
    {
wenzelm@44676
   491
      val versions1 = versions -- removed
wenzelm@44676
   492
      val assignments1 = assignments -- removed
wenzelm@52530
   493
      var commands1 = Map.empty[Document_ID.Command, Command.State]
wenzelm@52530
   494
      var execs1 = Map.empty[Document_ID.Exec, Command.State]
wenzelm@44676
   495
      for {
wenzelm@44676
   496
        (version_id, version) <- versions1.iterator
wenzelm@46997
   497
        command_execs = assignments1(version_id).command_execs
wenzelm@46723
   498
        (_, node) <- version.nodes.entries
wenzelm@44676
   499
        command <- node.commands.iterator
wenzelm@44676
   500
      } {
wenzelm@52568
   501
        if (!commands1.isDefinedAt(command.id))
wenzelm@52568
   502
          commands.get(command.id).foreach(st => commands1 += (command.id -> st))
wenzelm@52568
   503
        for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
wenzelm@52527
   504
          if (!execs1.isDefinedAt(exec_id))
wenzelm@52527
   505
            execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
wenzelm@44676
   506
        }
wenzelm@44676
   507
      }
wenzelm@44676
   508
      copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
wenzelm@44676
   509
    }
wenzelm@44676
   510
wenzelm@44613
   511
    def command_state(version: Version, command: Command): Command.State =
wenzelm@44613
   512
    {
wenzelm@44613
   513
      require(is_assigned(version))
wenzelm@44613
   514
      try {
wenzelm@52527
   515
        the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
wenzelm@52564
   516
          .map(the_dynamic_state(_)) match {
wenzelm@52527
   517
            case eval_state :: print_states => (eval_state /: print_states)(_ ++ _)
wenzelm@52527
   518
            case Nil => fail
wenzelm@52527
   519
          }
wenzelm@44613
   520
      }
wenzelm@47395
   521
      catch {
wenzelm@47395
   522
        case _: State.Fail =>
wenzelm@52564
   523
          try { the_static_state(command.id) }
wenzelm@49414
   524
          catch { case _: State.Fail => command.init_state }
wenzelm@47395
   525
      }
wenzelm@44613
   526
    }
wenzelm@44613
   527
wenzelm@49645
   528
    def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
wenzelm@49645
   529
      node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
wenzelm@38841
   530
wenzelm@38841
   531
    // persistent user-view
wenzelm@49346
   532
    def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
wenzelm@49346
   533
      : Snapshot =
wenzelm@38370
   534
    {
wenzelm@44672
   535
      val stable = recent_stable
wenzelm@44436
   536
      val latest = history.tip
wenzelm@38841
   537
wenzelm@44156
   538
      // FIXME proper treatment of removed nodes
wenzelm@38841
   539
      val edits =
wenzelm@38841
   540
        (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
wenzelm@44156
   541
            (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
wenzelm@38841
   542
      lazy val reverse_edits = edits.reverse
wenzelm@38841
   543
wenzelm@38841
   544
      new Snapshot
wenzelm@38841
   545
      {
wenzelm@44582
   546
        val state = State.this
wenzelm@39698
   547
        val version = stable.version.get_finished
wenzelm@48923
   548
        val node_name = name
wenzelm@38841
   549
        val node = version.nodes(name)
wenzelm@38841
   550
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38841
   551
wenzelm@38841
   552
        def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38841
   553
        def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@43425
   554
        def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
wenzelm@43425
   555
        def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
wenzelm@39177
   556
wenzelm@51494
   557
        def eq_content(other: Snapshot): Boolean =
wenzelm@49346
   558
          !is_outdated && !other.is_outdated &&
wenzelm@49346
   559
            node.commands.size == other.node.commands.size &&
wenzelm@49346
   560
            ((node.commands.iterator zip other.node.commands.iterator) forall {
wenzelm@49346
   561
              case (cmd1, cmd2) =>
wenzelm@51494
   562
                state.command_state(version, cmd1) eq_content
wenzelm@51494
   563
                  other.state.command_state(other.version, cmd2)
wenzelm@49346
   564
            })
wenzelm@49346
   565
wenzelm@46178
   566
        def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
wenzelm@50500
   567
          result: Command.State => PartialFunction[(A, Text.Markup), A]): Stream[Text.Info[A]] =
wenzelm@45459
   568
        {
wenzelm@45467
   569
          val former_range = revert(range)
wenzelm@45459
   570
          for {
wenzelm@45459
   571
            (command, command_start) <- node.command_range(former_range).toStream
wenzelm@50500
   572
            st = state.command_state(version, command)
wenzelm@50500
   573
            res = result(st)
wenzelm@50500
   574
            Text.Info(r0, a) <- st.markup.
wenzelm@46178
   575
              cumulate[A]((former_range - command_start).restrict(command.range), info, elements,
wenzelm@46178
   576
                {
wenzelm@46178
   577
                  case (a, Text.Info(r0, b))
wenzelm@50500
   578
                  if res.isDefinedAt((a, Text.Info(convert(r0 + command_start), b))) =>
wenzelm@50500
   579
                    res((a, Text.Info(convert(r0 + command_start), b)))
wenzelm@46178
   580
                })
wenzelm@45459
   581
          } yield Text.Info(convert(r0 + command_start), a)
wenzelm@45459
   582
        }
wenzelm@45459
   583
wenzelm@46178
   584
        def select_markup[A](range: Text.Range, elements: Option[Set[String]],
wenzelm@50500
   585
          result: Command.State => PartialFunction[Text.Markup, A]): Stream[Text.Info[A]] =
wenzelm@38845
   586
        {
wenzelm@50500
   587
          def result1(st: Command.State) =
wenzelm@50500
   588
          {
wenzelm@50500
   589
            val res = result(st)
wenzelm@45468
   590
            new PartialFunction[(Option[A], Text.Markup), Option[A]] {
wenzelm@50500
   591
              def isDefinedAt(arg: (Option[A], Text.Markup)): Boolean = res.isDefinedAt(arg._2)
wenzelm@50500
   592
              def apply(arg: (Option[A], Text.Markup)): Option[A] = Some(res(arg._2))
wenzelm@45468
   593
            }
wenzelm@50500
   594
          }
wenzelm@46198
   595
          for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
wenzelm@46198
   596
            yield Text.Info(r, x)
wenzelm@38845
   597
        }
wenzelm@38841
   598
      }
wenzelm@38150
   599
    }
wenzelm@34485
   600
  }
wenzelm@34840
   601
}
wenzelm@34840
   602