src/Pure/PIDE/document.scala
author wenzelm
Fri Aug 26 22:14:12 2011 +0200 (2011-08-26 ago)
changeset 44484 470f2ee5950e
parent 44479 9a04e7502e22
child 44543 ba8f24f7156e
permissions -rw-r--r--
tuned Session.edit_node: update_perspective based on last_exec_offset;
     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 version: Version
   195     val node: Node
   196     val is_outdated: Boolean
   197     def lookup_command(id: Command_ID): Option[Command]
   198     def 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 lookup_command(id: Command_ID): Option[Command] = commands.get(id).map(_.command)
   273 
   274     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   275     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   276     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   277     def the_assignment(version: Version): State.Assignment =
   278       assignments.getOrElse(version.id, fail)
   279 
   280     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   281       execs.get(id) match {
   282         case Some(st) =>
   283           val new_st = st.accumulate(message)
   284           (new_st, copy(execs = execs + (id -> new_st)))
   285         case None =>
   286           commands.get(id) match {
   287             case Some(st) =>
   288               val new_st = st.accumulate(message)
   289               (new_st, copy(commands = commands + (id -> new_st)))
   290             case None => fail
   291           }
   292       }
   293 
   294     def assign(id: Version_ID, arg: Assign): (List[Command], State) =
   295     {
   296       val version = the_version(id)
   297       val (command_execs, last_execs) = arg
   298 
   299       val (commands, new_execs) =
   300         ((Nil: List[Command], execs) /: command_execs) {
   301           case ((commands1, execs1), (cmd_id, Some(exec_id))) =>
   302             val st = the_command(cmd_id)
   303             (st.command :: commands1, execs1 + (exec_id -> st))
   304           case (res, (_, None)) => res
   305         }
   306       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   307       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   308 
   309       (commands, new_state)
   310     }
   311 
   312     def is_assigned(version: Version): Boolean =
   313       assignments.get(version.id) match {
   314         case Some(assgn) => assgn.is_finished
   315         case None => false
   316       }
   317 
   318     def is_stable(change: Change): Boolean =
   319       change.is_finished && is_assigned(change.version.get_finished)
   320 
   321     def recent_stable: Option[Change] = history.undo_list.find(is_stable)
   322     def tip_stable: Boolean = is_stable(history.tip)
   323     def tip_version: Version = history.tip.version.get_finished
   324 
   325     def last_exec_offset(name: String): Text.Offset =
   326     {
   327       val version = tip_version
   328       the_assignment(version).last_execs.get(name) match {
   329         case Some(Some(id)) =>
   330           val node = version.nodes(name)
   331           val cmd = the_command(id).command
   332           node.command_start(cmd) match {
   333             case None => 0
   334             case Some(start) => start + cmd.length
   335           }
   336         case _ => 0
   337       }
   338     }
   339 
   340     def continue_history(
   341         previous: Future[Version],
   342         edits: List[Edit_Text],
   343         version: Future[Version]): (Change, State) =
   344     {
   345       val change = Change(previous, edits, version)
   346       (change, copy(history = history + change))
   347     }
   348 
   349 
   350     // persistent user-view
   351     def snapshot(name: String, pending_edits: List[Text.Edit]): Snapshot =
   352     {
   353       val stable = recent_stable.get
   354       val latest = history.tip
   355 
   356       // FIXME proper treatment of removed nodes
   357       val edits =
   358         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   359             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   360       lazy val reverse_edits = edits.reverse
   361 
   362       new Snapshot
   363       {
   364         val version = stable.version.get_finished
   365         val node = version.nodes(name)
   366         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   367 
   368         def lookup_command(id: Command_ID): Option[Command] = State.this.lookup_command(id)
   369 
   370         def state(command: Command): Command.State =
   371           try {
   372             the_exec(the_assignment(version).check_finished.command_execs
   373               .getOrElse(command.id, fail))
   374           }
   375           catch { case _: State.Fail => command.empty_state }
   376 
   377         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   378         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   379         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   380         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   381 
   382         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   383           : Stream[Text.Info[Option[A]]] =
   384         {
   385           val former_range = revert(range)
   386           for {
   387             (command, command_start) <- node.command_range(former_range).toStream
   388             Text.Info(r0, x) <- state(command).markup.
   389               select((former_range - command_start).restrict(command.range)) {
   390                 case Text.Info(r0, info)
   391                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   392                   result(Text.Info(convert(r0 + command_start), info))
   393               }
   394           } yield Text.Info(convert(r0 + command_start), x)
   395         }
   396       }
   397     }
   398   }
   399 }
   400