src/Pure/PIDE/document.scala
author wenzelm
Sat Sep 17 21:28:52 2011 +0200 (2011-09-17 ago)
changeset 44957 098dd95349e7
parent 44676 7de87f1ae965
child 44959 9476c856c4b9
permissions -rw-r--r--
more elaborate Node_Renderer, which paints node_name.theory only;
     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] = (Node.Name, 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     object Name
    43     {
    44       val empty = Name("", "", "")
    45     }
    46     sealed case class Name(node: String, dir: String, theory: String)
    47     {
    48       override def hashCode: Int = node.hashCode
    49       override def equals(that: Any): Boolean =
    50         that match {
    51           case other: Name => node == other.node
    52           case _ => false
    53         }
    54       override def toString: String = theory
    55     }
    56 
    57     sealed abstract class Edit[A, B]
    58     {
    59       def foreach(f: A => Unit)
    60       {
    61         this match {
    62           case Edits(es) => es.foreach(f)
    63           case _ =>
    64         }
    65       }
    66     }
    67     case class Clear[A, B]() extends Edit[A, B]
    68     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
    69     case class Header[A, B](header: Node_Header) extends Edit[A, B]
    70     case class Perspective[A, B](perspective: B) extends Edit[A, B]
    71 
    72     def norm_header(f: String => String, g: String => String, header: Node_Header): Node_Header =
    73       header match {
    74         case Exn.Res(h) => Exn.capture { h.norm_deps(f, g) }
    75         case exn => exn
    76       }
    77 
    78     val empty: Node =
    79       Node(Exn.Exn(ERROR("Bad theory header")), Command.Perspective.empty, Map(), Linear_Set())
    80 
    81     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    82       : Iterator[(Command, Text.Offset)] =
    83     {
    84       var i = offset
    85       for (command <- commands) yield {
    86         val start = i
    87         i += command.length
    88         (command, start)
    89       }
    90     }
    91   }
    92 
    93   private val block_size = 1024
    94 
    95   sealed case class Node(
    96     val header: Node_Header,
    97     val perspective: Command.Perspective,
    98     val blobs: Map[String, Blob],
    99     val commands: Linear_Set[Command])
   100   {
   101     def clear: Node = Node.empty.copy(header = header)
   102 
   103 
   104     /* commands */
   105 
   106     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   107     {
   108       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   109       var next_block = 0
   110       var last_stop = 0
   111       for ((command, start) <- Node.command_starts(commands.iterator)) {
   112         last_stop = start + command.length
   113         while (last_stop + 1 > next_block) {
   114           blocks += (command -> start)
   115           next_block += block_size
   116         }
   117       }
   118       (blocks.toArray, Text.Range(0, last_stop))
   119     }
   120 
   121     def full_range: Text.Range = full_index._2
   122 
   123     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   124     {
   125       if (!commands.isEmpty && full_range.contains(i)) {
   126         val (cmd0, start0) = full_index._1(i / block_size)
   127         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   128           case (cmd, start) => start + cmd.length <= i }
   129       }
   130       else Iterator.empty
   131     }
   132 
   133     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   134       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   135 
   136     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   137     {
   138       val range = command_range(i)
   139       if (range.hasNext) Some(range.next) else None
   140     }
   141 
   142     def proper_command_at(i: Text.Offset): Option[Command] =
   143       command_at(i) match {
   144         case Some((command, _)) =>
   145           commands.reverse_iterator(command).find(cmd => !cmd.is_ignored)
   146         case None => None
   147       }
   148 
   149     def command_start(cmd: Command): Option[Text.Offset] =
   150       command_starts.find(_._1 == cmd).map(_._2)
   151 
   152     def command_starts: Iterator[(Command, Text.Offset)] =
   153       Node.command_starts(commands.iterator)
   154   }
   155 
   156 
   157 
   158   /** versioning **/
   159 
   160   /* particular document versions */
   161 
   162   object Version
   163   {
   164     val init: Version = Version(no_id, Map().withDefaultValue(Node.empty))
   165   }
   166 
   167   type Nodes = Map[Node.Name, Node]
   168   sealed case class Version(val id: Version_ID, val nodes: Nodes)
   169 
   170 
   171   /* changes of plain text, eventually resulting in document edits */
   172 
   173   object Change
   174   {
   175     val init: Change = Change(Some(Future.value(Version.init)), Nil, Future.value(Version.init))
   176   }
   177 
   178   sealed case class Change(
   179     val previous: Option[Future[Version]],
   180     val edits: List[Edit_Text],
   181     val version: Future[Version])
   182   {
   183     def is_finished: Boolean =
   184       (previous match { case None => true case Some(future) => future.is_finished }) &&
   185       version.is_finished
   186 
   187     def truncate: Change = copy(previous = None, edits = Nil)
   188   }
   189 
   190 
   191   /* history navigation */
   192 
   193   object History
   194   {
   195     val init: History = History(List(Change.init))
   196   }
   197 
   198   // FIXME pruning, purging of state
   199   sealed case class History(val undo_list: List[Change])
   200   {
   201     require(!undo_list.isEmpty)
   202 
   203     def tip: Change = undo_list.head
   204     def +(change: Change): History = copy(undo_list = change :: undo_list)
   205   }
   206 
   207 
   208 
   209   /** global state -- document structure, execution process, editing history **/
   210 
   211   abstract class Snapshot
   212   {
   213     val state: State
   214     val version: Version
   215     val node: Node
   216     val is_outdated: Boolean
   217     def command_state(command: Command): Command.State
   218     def convert(i: Text.Offset): Text.Offset
   219     def convert(range: Text.Range): Text.Range
   220     def revert(i: Text.Offset): Text.Offset
   221     def revert(range: Text.Range): Text.Range
   222     def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   223       : Stream[Text.Info[Option[A]]]
   224   }
   225 
   226   type Assign =
   227    (List[(Document.Command_ID, Option[Document.Exec_ID])],  // exec state assignment
   228     List[(String, Option[Document.Command_ID])])  // last exec
   229 
   230   val no_assign: Assign = (Nil, Nil)
   231 
   232   object State
   233   {
   234     class Fail(state: State) extends Exception
   235 
   236     val init: State =
   237       State().define_version(Version.init, Assignment.init).assign(Version.init.id, no_assign)._2
   238 
   239     object Assignment
   240     {
   241       val init: Assignment = Assignment(Map.empty, Map.empty, false)
   242     }
   243 
   244     case class Assignment(
   245       val command_execs: Map[Command_ID, Exec_ID],
   246       val last_execs: Map[String, Option[Command_ID]],
   247       val is_finished: Boolean)
   248     {
   249       def check_finished: Assignment = { require(is_finished); this }
   250       def unfinished: Assignment = copy(is_finished = false)
   251 
   252       def assign(add_command_execs: List[(Command_ID, Option[Exec_ID])],
   253         add_last_execs: List[(String, Option[Command_ID])]): Assignment =
   254       {
   255         require(!is_finished)
   256         val command_execs1 =
   257           (command_execs /: add_command_execs) {
   258             case (res, (command_id, None)) => res - command_id
   259             case (res, (command_id, Some(exec_id))) => res + (command_id -> exec_id)
   260           }
   261         Assignment(command_execs1, last_execs ++ add_last_execs, true)
   262       }
   263     }
   264   }
   265 
   266   sealed case class State(
   267     val versions: Map[Version_ID, Version] = Map(),
   268     val commands: Map[Command_ID, Command.State] = Map(),  // static markup from define_command
   269     val execs: Map[Exec_ID, Command.State] = Map(),  // dynamic markup from execution
   270     val assignments: Map[Version_ID, State.Assignment] = Map(),
   271     val history: History = History.init)
   272   {
   273     private def fail[A]: A = throw new State.Fail(this)
   274 
   275     def define_version(version: Version, assignment: State.Assignment): State =
   276     {
   277       val id = version.id
   278       copy(versions = versions + (id -> version),
   279         assignments = assignments + (id -> assignment.unfinished))
   280     }
   281 
   282     def define_command(command: Command): State =
   283     {
   284       val id = command.id
   285       copy(commands = commands + (id -> command.empty_state))
   286     }
   287 
   288     def defined_command(id: Command_ID): Boolean = commands.isDefinedAt(id)
   289 
   290     def find_command(version: Version, id: ID): Option[(Node, Command)] =
   291       commands.get(id) orElse execs.get(id) match {
   292         case None => None
   293         case Some(st) =>
   294           val command = st.command
   295           version.nodes.get(command.node_name).map((_, command))
   296       }
   297 
   298     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   299     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)  // FIXME rename
   300     def the_exec(id: Exec_ID): Command.State = execs.getOrElse(id, fail)
   301     def the_assignment(version: Version): State.Assignment =
   302       assignments.getOrElse(version.id, fail)
   303 
   304     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   305       execs.get(id) match {
   306         case Some(st) =>
   307           val new_st = st.accumulate(message)
   308           (new_st, copy(execs = execs + (id -> new_st)))
   309         case None =>
   310           commands.get(id) match {
   311             case Some(st) =>
   312               val new_st = st.accumulate(message)
   313               (new_st, copy(commands = commands + (id -> new_st)))
   314             case None => fail
   315           }
   316       }
   317 
   318     def assign(id: Version_ID, arg: Assign): (List[Command], State) =
   319     {
   320       val version = the_version(id)
   321       val (command_execs, last_execs) = arg
   322 
   323       val (changed_commands, new_execs) =
   324         ((Nil: List[Command], execs) /: command_execs) {
   325           case ((commands1, execs1), (cmd_id, exec)) =>
   326             val st = the_command(cmd_id)
   327             val commands2 = st.command :: commands1
   328             val execs2 =
   329               exec match {
   330                 case None => execs1
   331                 case Some(exec_id) => execs1 + (exec_id -> st)
   332               }
   333             (commands2, execs2)
   334         }
   335       val new_assignment = the_assignment(version).assign(command_execs, last_execs)
   336       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   337 
   338       (changed_commands, new_state)
   339     }
   340 
   341     def is_assigned(version: Version): Boolean =
   342       assignments.get(version.id) match {
   343         case Some(assgn) => assgn.is_finished
   344         case None => false
   345       }
   346 
   347     def is_stable(change: Change): Boolean =
   348       change.is_finished && is_assigned(change.version.get_finished)
   349 
   350     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   351     def tip_stable: Boolean = is_stable(history.tip)
   352     def tip_version: Version = history.tip.version.get_finished
   353 
   354     def last_exec_offset(name: Node.Name): Text.Offset =
   355     {
   356       val version = tip_version
   357       the_assignment(version).last_execs.get(name.node) match {
   358         case Some(Some(id)) =>
   359           val node = version.nodes(name)
   360           val cmd = the_command(id).command
   361           node.command_start(cmd) match {
   362             case None => 0
   363             case Some(start) => start + cmd.length
   364           }
   365         case _ => 0
   366       }
   367     }
   368 
   369     def continue_history(
   370         previous: Future[Version],
   371         edits: List[Edit_Text],
   372         version: Future[Version]): (Change, State) =
   373     {
   374       val change = Change(Some(previous), edits, version)
   375       (change, copy(history = history + change))
   376     }
   377 
   378     def prune_history(retain: Int = 0): (List[Version], State) =
   379     {
   380       val undo_list = history.undo_list
   381       val n = undo_list.iterator.zipWithIndex.find(p => is_stable(p._1)).get._2 + 1
   382       val (retained, dropped) = undo_list.splitAt(n max retain)
   383 
   384       retained.splitAt(retained.length - 1) match {
   385         case (prefix, List(last)) =>
   386           val dropped_versions = dropped.map(change => change.version.get_finished)
   387           val state1 = copy(history = History(prefix ::: List(last.truncate)))
   388           (dropped_versions, state1)
   389         case _ => fail
   390       }
   391     }
   392 
   393     def removed_versions(removed: List[Version_ID]): State =
   394     {
   395       val versions1 = versions -- removed
   396       val assignments1 = assignments -- removed
   397       var commands1 = Map.empty[Command_ID, Command.State]
   398       var execs1 = Map.empty[Exec_ID, Command.State]
   399       for {
   400         (version_id, version) <- versions1.iterator
   401         val command_execs = assignments1(version_id).command_execs
   402         (_, node) <- version.nodes.iterator
   403         command <- node.commands.iterator
   404       } {
   405         val id = command.id
   406         if (!commands1.isDefinedAt(id) && commands.isDefinedAt(id))
   407           commands1 += (id -> commands(id))
   408         if (command_execs.isDefinedAt(id)) {
   409           val exec_id = command_execs(id)
   410           if (!execs1.isDefinedAt(exec_id) && execs.isDefinedAt(exec_id))
   411             execs1 += (exec_id -> execs(exec_id))
   412         }
   413       }
   414       copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
   415     }
   416 
   417     def command_state(version: Version, command: Command): Command.State =
   418     {
   419       require(is_assigned(version))
   420       try {
   421         the_exec(the_assignment(version).check_finished.command_execs
   422           .getOrElse(command.id, fail))
   423       }
   424       catch { case _: State.Fail => command.empty_state }
   425     }
   426 
   427 
   428     // persistent user-view
   429     def snapshot(name: Node.Name, pending_edits: List[Text.Edit]): Snapshot =
   430     {
   431       val stable = recent_stable
   432       val latest = history.tip
   433 
   434       // FIXME proper treatment of removed nodes
   435       val edits =
   436         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   437             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   438       lazy val reverse_edits = edits.reverse
   439 
   440       new Snapshot
   441       {
   442         val state = State.this
   443         val version = stable.version.get_finished
   444         val node = version.nodes(name)
   445         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   446         def command_state(command: Command): Command.State = state.command_state(version, command)
   447 
   448         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   449         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   450         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   451         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   452 
   453         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   454           : Stream[Text.Info[Option[A]]] =
   455         {
   456           val former_range = revert(range)
   457           for {
   458             (command, command_start) <- node.command_range(former_range).toStream
   459             Text.Info(r0, x) <- command_state(command).markup.
   460               select((former_range - command_start).restrict(command.range)) {
   461                 case Text.Info(r0, info)
   462                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   463                   result(Text.Info(convert(r0 + command_start), info))
   464               }
   465           } yield Text.Info(convert(r0 + command_start), x)
   466         }
   467       }
   468     }
   469   }
   470 }
   471