src/Pure/PIDE/document.scala
author wenzelm
Tue, 30 Aug 2011 16:04:26 +0200
changeset 45469 479c07072992
parent 45468 7daef43592d0
child 45498 274eff0ea12e
permissions -rw-r--r--
tuned signature;
     1 /*  Title:      Pure/PIDE/document.scala
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 
    13 
    14 object Document
    15 {
    16   /* formal identifiers */
    17 
    18   type ID = Long
    19   val ID = Properties.Value.Long
    20 
    21   type Version_ID = ID
    22   type Command_ID = ID
    23   type Exec_ID = ID
    24 
    25   val no_id: ID = 0
    26   val new_id = new Counter
    27 
    28 
    29 
    30   /** document structure **/
    31 
    32   /* named nodes -- development graph */
    33 
    34   type Edit[A, B] = (String, Node.Edit[A, B])
    35   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    36   type Edit_Command = Edit[(Option[Command], Option[Command]), Command.Perspective]
    37 
    38   type Node_Header = Exn.Result[Thy_Header]
    39 
    40   object Node
    41   {
    42     sealed abstract class Edit[A, B]
    43     {
    44       def foreach(f: A => Unit)
    45       {
    46         this match {
    47           case Edits(es) => es.foreach(f)
    48           case _ =>
    49         }
    50       }
    51     }
    52     case class Clear[A, B]() extends Edit[A, B]
    53     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
    54     case class Header[A, B](header: Node_Header) extends Edit[A, B]
    55     case class Perspective[A, B](perspective: B) extends Edit[A, B]
    56 
    57     def norm_header(f: String => String, g: String => String, header: Node_Header): Node_Header =
    58       header match {
    59         case Exn.Res(h) => Exn.capture { h.norm_deps(f, g) }
    60         case exn => exn
    61       }
    62 
    63     val empty: Node =
    64       Node(Exn.Exn(ERROR("Bad theory header")), Command.Perspective.empty, Map(), Linear_Set())
    65 
    66     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    67       : Iterator[(Command, Text.Offset)] =
    68     {
    69       var i = offset
    70       for (command <- commands) yield {
    71         val start = i
    72         i += command.length
    73         (command, start)
    74       }
    75     }
    76   }
    77 
    78   private val block_size = 1024
    79 
    80   sealed case class Node(
    81     val header: Node_Header,
    82     val perspective: Command.Perspective,
    83     val blobs: Map[String, Blob],
    84     val commands: Linear_Set[Command])
    85   {
    86     def clear: Node = Node.empty.copy(header = header)
    87 
    88 
    89     /* commands */
    90 
    91     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
    92     {
    93       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
    94       var next_block = 0
    95       var last_stop = 0
    96       for ((command, start) <- Node.command_starts(commands.iterator)) {
    97         last_stop = start + command.length
    98         while (last_stop + 1 > next_block) {
    99           blocks += (command -> start)
   100           next_block += block_size
   101         }
   102       }
   103       (blocks.toArray, Text.Range(0, last_stop))
   104     }
   105 
   106     def full_range: Text.Range = full_index._2
   107 
   108     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   109     {
   110       if (!commands.isEmpty && full_range.contains(i)) {
   111         val (cmd0, start0) = full_index._1(i / block_size)
   112         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   113           case (cmd, start) => start + cmd.length <= i }
   114       }
   115       else Iterator.empty
   116     }
   117 
   118     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   119       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   120 
   121     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   122     {
   123       val range = command_range(i)
   124       if (range.hasNext) Some(range.next) else None
   125     }
   126 
   127     def proper_command_at(i: Text.Offset): Option[Command] =
   128       command_at(i) match {
   129         case Some((command, _)) =>
   130           commands.reverse_iterator(command).find(cmd => !cmd.is_ignored)
   131         case None => None
   132       }
   133 
   134     def command_start(cmd: Command): Option[Text.Offset] =
   135       command_starts.find(_._1 == cmd).map(_._2)
   136 
   137     def command_starts: Iterator[(Command, Text.Offset)] =
   138       Node.command_starts(commands.iterator)
   139   }
   140 
   141 
   142 
   143   /** versioning **/
   144 
   145   /* particular document versions */
   146 
   147   object Version
   148   {
   149     val init: Version = Version(no_id, Map().withDefaultValue(Node.empty))
   150   }
   151 
   152   type Nodes = Map[String, Node]
   153   sealed case class Version(val id: Version_ID, val nodes: Nodes)
   154 
   155 
   156   /* changes of plain text, eventually resulting in document edits */
   157 
   158   object Change
   159   {
   160     val init: Change = Change(Future.value(Version.init), Nil, Future.value(Version.init))
   161   }
   162 
   163   sealed case class Change(
   164     val previous: Future[Version],
   165     val edits: List[Edit_Text],
   166     val version: Future[Version])
   167   {
   168     def is_finished: Boolean = previous.is_finished && version.is_finished
   169   }
   170 
   171 
   172   /* history navigation */
   173 
   174   object History
   175   {
   176     val init: History = new History(List(Change.init))
   177   }
   178 
   179   // FIXME pruning, purging of state
   180   class History(val undo_list: List[Change])
   181   {
   182     require(!undo_list.isEmpty)
   183 
   184     def tip: Change = undo_list.head
   185     def +(change: Change): History = new History(change :: undo_list)
   186   }
   187 
   188 
   189 
   190   /** global state -- document structure, execution process, editing history **/
   191 
   192   abstract class Snapshot
   193   {
   194     val state: State
   195     val version: Version
   196     val node: Node
   197     val is_outdated: Boolean
   198     def command_state(command: Command): Command.State
   199     def convert(i: Text.Offset): Text.Offset
   200     def convert(range: Text.Range): Text.Range
   201     def revert(i: Text.Offset): Text.Offset
   202     def revert(range: Text.Range): Text.Range
   203     def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   204       : Stream[Text.Info[Option[A]]]
   205   }
   206 
   207   type Assign =
   208    (List[(Document.Command_ID, Option[Document.Exec_ID])],  // exec state assignment
   209     List[(String, Option[Document.Command_ID])])  // last exec
   210 
   211   val no_assign: Assign = (Nil, Nil)
   212 
   213   object State
   214   {
   215     class Fail(state: State) extends Exception
   216 
   217     val init: State =
   218       State().define_version(Version.init, Assignment.init).assign(Version.init.id, no_assign)._2
   219 
   220     object Assignment
   221     {
   222       val init: Assignment = Assignment(Map.empty, Map.empty, false)
   223     }
   224 
   225     case class Assignment(
   226       val command_execs: Map[Command_ID, Exec_ID],
   227       val last_execs: Map[String, Option[Command_ID]],
   228       val is_finished: Boolean)
   229     {
   230       def check_finished: Assignment = { require(is_finished); this }
   231       def unfinished: Assignment = copy(is_finished = false)
   232 
   233       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])],
   234         add_last_execs: List[(String, Option[Command_ID])]): Assignment =
   235       {
   236         require(!is_finished)
   237         val command_execs1 =
   238           (command_execs /: add_command_execs) {
   239             case (res, (command_id, None)) => res - command_id
   240             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   241           }
   242         Assignment(command_execs1, last_execs ++ add_last_execs, true)
   243       }
   244     }
   245   }
   246 
   247   sealed case class State(
   248     val versions: Map[Version_ID, Version] = Map(),
   249     val commands: Map[Command_ID, Command.State] = Map(),  // static markup from define_command
   250     val execs: Map[Exec_ID, Command.State] = Map(),  // dynamic markup from execution
   251     val assignments: Map[Version_ID, State.Assignment] = Map(),
   252     val disposed: Set[ID] = Set(),  // FIXME unused!?
   253     val history: History = History.init)
   254   {
   255     private def fail[A]: A = throw new State.Fail(this)
   256 
   257     def define_version(version: Version, assignment: State.Assignment): State =
   258     {
   259       val id = version.id
   260       if (versions.isDefinedAt(id) || disposed(id)) fail
   261       copy(versions = versions + (id -> version),
   262         assignments = assignments + (id -> assignment.unfinished))
   263     }
   264 
   265     def define_command(command: Command): State =
   266     {
   267       val id = command.id
   268       if (commands.isDefinedAt(id) || disposed(id)) fail
   269       copy(commands = commands + (id -> command.empty_state))
   270     }
   271 
   272     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   273 
   274     def find_command(version: Version, id: ID): Option[(String, Node, Command)] =
   275       commands.get(id) orElse execs.get(id) match {
   276         case None => None
   277         case Some(st) =>
   278           val command = st.command
   279           version.nodes.find({ case (_, node) => node.commands(command) })
   280             .map({ case (name, node) => (name, node, command) })
   281       }
   282 
   283     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   284     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   285     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   286     def the_assignment(version: Version): State.Assignment =
   287       assignments.getOrElse(version.id, fail)
   288 
   289     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   290       execs.get(id) match {
   291         case Some(st) =>
   292           val new_st = st.accumulate(message)
   293           (new_st, copy(execs = execs + (id -> new_st)))
   294         case None =>
   295           commands.get(id) match {
   296             case Some(st) =>
   297               val new_st = st.accumulate(message)
   298               (new_st, copy(commands = commands + (id -> new_st)))
   299             case None => fail
   300           }
   301       }
   302 
   303     def assign(id: Version_ID, arg: Assign): (List[Command], State) =
   304     {
   305       val version = the_version(id)
   306       val (command_execs, last_execs) = arg
   307 
   308       val (changed_commands, new_execs) =
   309         ((Nil: List[Command], execs) /: command_execs) {
   310           case ((commands1, execs1), (cmd_id, exec)) =>
   311             val st = the_command(cmd_id)
   312             val commands2 = st.command :: commands1
   313             val execs2 =
   314               exec match {
   315                 case None => execs1
   316                 case Some(exec_id) => execs1 + (exec_id -> st)
   317               }
   318             (commands2, execs2)
   319         }
   320       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   321       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   322 
   323       (changed_commands, new_state)
   324     }
   325 
   326     def is_assigned(version: Version): Boolean =
   327       assignments.get(version.id) match {
   328         case Some(assgn) => assgn.is_finished
   329         case None => false
   330       }
   331 
   332     def is_stable(change: Change): Boolean =
   333       change.is_finished && is_assigned(change.version.get_finished)
   334 
   335     def recent_stable: Option[Change] = history.undo_list.find(is_stable)
   336     def tip_stable: Boolean = is_stable(history.tip)
   337     def tip_version: Version = history.tip.version.get_finished
   338 
   339     def last_exec_offset(name: String): Text.Offset =
   340     {
   341       val version = tip_version
   342       the_assignment(version).last_execs.get(name) match {
   343         case Some(Some(id)) =>
   344           val node = version.nodes(name)
   345           val cmd = the_command(id).command
   346           node.command_start(cmd) match {
   347             case None => 0
   348             case Some(start) => start + cmd.length
   349           }
   350         case _ => 0
   351       }
   352     }
   353 
   354     def continue_history(
   355         previous: Future[Version],
   356         edits: List[Edit_Text],
   357         version: Future[Version]): (Change, State) =
   358     {
   359       val change = Change(previous, edits, version)
   360       (change, copy(history = history + change))
   361     }
   362 
   363 
   364     // persistent user-view
   365     def snapshot(name: String, pending_edits: List[Text.Edit]): Snapshot =
   366     {
   367       val stable = recent_stable.get
   368       val latest = history.tip
   369 
   370       // FIXME proper treatment of removed nodes
   371       val edits =
   372         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   373             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   374       lazy val reverse_edits = edits.reverse
   375 
   376       new Snapshot
   377       {
   378         val state = State.this
   379         val version = stable.version.get_finished
   380         val node = version.nodes(name)
   381         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   382 
   383         def command_state(command: Command): Command.State =
   384           try {
   385             the_exec(the_assignment(version).check_finished.command_execs
   386               .getOrElse(command.id, fail))
   387           }
   388           catch { case _: State.Fail => command.empty_state }
   389 
   390         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   391         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   392         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   393         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   394 
   395         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   396           : Stream[Text.Info[Option[A]]] =
   397         {
   398           val former_range = revert(range)
   399           for {
   400             (command, command_start) <- node.command_range(former_range).toStream
   401             Text.Info(r0, x) <- command_state(command).markup.
   402               select((former_range - command_start).restrict(command.range)) {
   403                 case Text.Info(r0, info)
   404                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   405                   result(Text.Info(convert(r0 + command_start), info))
   406               }
   407           } yield Text.Info(convert(r0 + command_start), x)
   408         }
   409       }
   410     }
   411   }
   412 }
   413