src/Pure/PIDE/document.scala
author wenzelm
Sat Aug 13 15:59:26 2011 +0200 (2011-08-13)
changeset 44182 ecb51b457064
parent 44163 32e0c150c010
child 44183 1de22a7b2a82
permissions -rw-r--r--
clarified node header -- exclude master_dir;
     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] = (String, Node.Edit[A])
    35   type Edit_Text = Edit[Text.Edit]
    36   type Edit_Command = Edit[(Option[Command], Option[Command])]
    37   type Edit_Command_ID = Edit[(Option[Command_ID], Option[Command_ID])]
    38 
    39   type Node_Header = Exn.Result[Thy_Header]
    40 
    41   object Node
    42   {
    43     sealed abstract class Edit[A]
    44     {
    45       def map[B](f: A => B): Edit[B] =
    46         this match {
    47           case Remove() => Remove()
    48           case Edits(es) => Edits(es.map(f))
    49           case Header(header) => Header(header)
    50         }
    51     }
    52     case class Remove[A]() extends Edit[A]
    53     case class Edits[A](edits: List[A]) extends Edit[A]
    54     case class Header[A](header: Node_Header) extends Edit[A]
    55 
    56     def norm_header[A](f: Path => String, header: Node_Header): Header[A] =
    57       header match {
    58         case Exn.Res(h) => Header[A](Exn.capture { h.norm_deps(name => f(Path.explode(name))) })
    59         case exn => Header[A](exn)
    60       }
    61 
    62     val empty: Node = Node(Exn.Exn(ERROR("Bad theory header")), Map(), Linear_Set())
    63 
    64     def command_starts(commands: Iterator[Command], offset: Text.Offset = 0)
    65       : Iterator[(Command, Text.Offset)] =
    66     {
    67       var i = offset
    68       for (command <- commands) yield {
    69         val start = i
    70         i += command.length
    71         (command, start)
    72       }
    73     }
    74   }
    75 
    76   private val block_size = 1024
    77 
    78   sealed case class Node(
    79     val header: Node_Header,
    80     val blobs: Map[String, Blob],
    81     val commands: Linear_Set[Command])
    82   {
    83     /* commands */
    84 
    85     private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
    86     {
    87       val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
    88       var next_block = 0
    89       var last_stop = 0
    90       for ((command, start) <- Node.command_starts(commands.iterator)) {
    91         last_stop = start + command.length
    92         while (last_stop + 1 > next_block) {
    93           blocks += (command -> start)
    94           next_block += block_size
    95         }
    96       }
    97       (blocks.toArray, Text.Range(0, last_stop))
    98     }
    99 
   100     def full_range: Text.Range = full_index._2
   101 
   102     def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   103     {
   104       if (!commands.isEmpty && full_range.contains(i)) {
   105         val (cmd0, start0) = full_index._1(i / block_size)
   106         Node.command_starts(commands.iterator(cmd0), start0) dropWhile {
   107           case (cmd, start) => start + cmd.length <= i }
   108       }
   109       else Iterator.empty
   110     }
   111 
   112     def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
   113       command_range(range.start) takeWhile { case (_, start) => start < range.stop }
   114 
   115     def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
   116     {
   117       val range = command_range(i)
   118       if (range.hasNext) Some(range.next) else None
   119     }
   120 
   121     def proper_command_at(i: Text.Offset): Option[Command] =
   122       command_at(i) match {
   123         case Some((command, _)) =>
   124           commands.reverse_iterator(command).find(cmd => !cmd.is_ignored)
   125         case None => None
   126       }
   127 
   128     def command_start(cmd: Command): Option[Text.Offset] =
   129       command_starts.find(_._1 == cmd).map(_._2)
   130 
   131     def command_starts: Iterator[(Command, Text.Offset)] =
   132       Node.command_starts(commands.iterator)
   133   }
   134 
   135 
   136 
   137   /** versioning **/
   138 
   139   /* particular document versions */
   140 
   141   object Version
   142   {
   143     val init: Version = Version(no_id, Map().withDefaultValue(Node.empty))
   144   }
   145 
   146   sealed case class Version(val id: Version_ID, val nodes: Map[String, Node])
   147 
   148 
   149   /* changes of plain text, eventually resulting in document edits */
   150 
   151   object Change
   152   {
   153     val init = Change(Future.value(Version.init), Nil, Future.value(Version.init))
   154   }
   155 
   156   sealed case class Change(
   157     val previous: Future[Version],
   158     val edits: List[Edit_Text],
   159     val version: Future[Version])
   160   {
   161     def is_finished: Boolean = previous.is_finished && version.is_finished
   162   }
   163 
   164 
   165   /* history navigation */
   166 
   167   object History
   168   {
   169     val init = new History(List(Change.init))
   170   }
   171 
   172   // FIXME pruning, purging of state
   173   class History(val undo_list: List[Change])
   174   {
   175     require(!undo_list.isEmpty)
   176 
   177     def tip: Change = undo_list.head
   178     def +(change: Change): History = new History(change :: undo_list)
   179   }
   180 
   181 
   182 
   183   /** global state -- document structure, execution process, editing history **/
   184 
   185   abstract class Snapshot
   186   {
   187     val version: Version
   188     val node: Node
   189     val is_outdated: Boolean
   190     def lookup_command(id: Command_ID): Option[Command]
   191     def state(command: Command): Command.State
   192     def convert(i: Text.Offset): Text.Offset
   193     def convert(range: Text.Range): Text.Range
   194     def revert(i: Text.Offset): Text.Offset
   195     def revert(range: Text.Range): Text.Range
   196     def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   197       : Stream[Text.Info[Option[A]]]
   198   }
   199 
   200   object State
   201   {
   202     class Fail(state: State) extends Exception
   203 
   204     val init = State().define_version(Version.init, Map()).assign(Version.init.id, Nil)._2
   205 
   206     case class Assignment(
   207       val assignment: Map[Command, Exec_ID],
   208       val is_finished: Boolean = false)
   209     {
   210       def get_finished: Map[Command, Exec_ID] = { require(is_finished); assignment }
   211       def assign(command_execs: List[(Command, Exec_ID)]): Assignment =
   212       {
   213         require(!is_finished)
   214         Assignment(assignment ++ command_execs, true)
   215       }
   216     }
   217   }
   218 
   219   sealed case class State(
   220     val versions: Map[Version_ID, Version] = Map(),
   221     val commands: Map[Command_ID, Command.State] = Map(),
   222     val execs: Map[Exec_ID, (Command.State, Set[Version])] = Map(),
   223     val assignments: Map[Version_ID, State.Assignment] = Map(),
   224     val disposed: Set[ID] = Set(),  // FIXME unused!?
   225     val history: History = History.init)
   226   {
   227     private def fail[A]: A = throw new State.Fail(this)
   228 
   229     def define_version(version: Version, former_assignment: Map[Command, Exec_ID]): State =
   230     {
   231       val id = version.id
   232       if (versions.isDefinedAt(id) || disposed(id)) fail
   233       copy(versions = versions + (id -> version),
   234         assignments = assignments + (id -> State.Assignment(former_assignment)))
   235     }
   236 
   237     def define_command(command: Command): State =
   238     {
   239       val id = command.id
   240       if (commands.isDefinedAt(id) || disposed(id)) fail
   241       copy(commands = commands + (id -> command.empty_state))
   242     }
   243 
   244     def lookup_command(id: Command_ID): Option[Command] = commands.get(id).map(_.command)
   245 
   246     def the_version(id: Version_ID): Version = versions.getOrElse(id, fail)
   247     def the_command(id: Command_ID): Command.State = commands.getOrElse(id, fail)
   248     def the_exec_state(id: Exec_ID): Command.State = execs.getOrElse(id, fail)._1
   249     def the_assignment(version: Version): State.Assignment =
   250       assignments.getOrElse(version.id, fail)
   251 
   252     def accumulate(id: ID, message: XML.Elem): (Command.State, State) =
   253       execs.get(id) match {
   254         case Some((st, occs)) =>
   255           val new_st = st.accumulate(message)
   256           (new_st, copy(execs = execs + (id -> (new_st, occs))))
   257         case None =>
   258           commands.get(id) match {
   259             case Some(st) =>
   260               val new_st = st.accumulate(message)
   261               (new_st, copy(commands = commands + (id -> new_st)))
   262             case None => fail
   263           }
   264       }
   265 
   266     def assign(id: Version_ID, edits: List[(Command_ID, Exec_ID)]): (List[Command], State) =
   267     {
   268       val version = the_version(id)
   269       val occs = Set(version)  // FIXME unused (!?)
   270 
   271       var new_execs = execs
   272       val assigned_execs =
   273         for ((cmd_id, exec_id) <- edits) yield {
   274           val st = the_command(cmd_id)
   275           if (new_execs.isDefinedAt(exec_id) || disposed(exec_id)) fail
   276           new_execs += (exec_id -> (st, occs))
   277           (st.command, exec_id)
   278         }
   279       val new_assignment = the_assignment(version).assign(assigned_execs)
   280       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   281       (assigned_execs.map(_._1), new_state)
   282     }
   283 
   284     def is_assigned(version: Version): Boolean =
   285       assignments.get(version.id) match {
   286         case Some(assgn) => assgn.is_finished
   287         case None => false
   288       }
   289 
   290     def extend_history(previous: Future[Version],
   291         edits: List[Edit_Text],
   292         version: Future[Version]): (Change, State) =
   293     {
   294       val change = Change(previous, edits, version)
   295       (change, copy(history = history + change))
   296     }
   297 
   298 
   299     // persistent user-view
   300     def snapshot(name: String, pending_edits: List[Text.Edit]): Snapshot =
   301     {
   302       val found_stable = history.undo_list.find(change =>
   303         change.is_finished && is_assigned(change.version.get_finished))
   304       require(found_stable.isDefined)
   305       val stable = found_stable.get
   306       val latest = history.undo_list.head
   307 
   308       // FIXME proper treatment of removed nodes
   309       val edits =
   310         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   311             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   312       lazy val reverse_edits = edits.reverse
   313 
   314       new Snapshot
   315       {
   316         val version = stable.version.get_finished
   317         val node = version.nodes(name)
   318         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   319 
   320         def lookup_command(id: Command_ID): Option[Command] = State.this.lookup_command(id)
   321 
   322         def state(command: Command): Command.State =
   323           try { the_exec_state(the_assignment(version).get_finished.getOrElse(command, fail)) }
   324           catch { case _: State.Fail => command.empty_state }
   325 
   326         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   327         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   328         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   329         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   330 
   331         def select_markup[A](range: Text.Range)(result: Markup_Tree.Select[A])
   332           : Stream[Text.Info[Option[A]]] =
   333         {
   334           val former_range = revert(range)
   335           for {
   336             (command, command_start) <- node.command_range(former_range).toStream
   337             Text.Info(r0, x) <- state(command).markup.
   338               select((former_range - command_start).restrict(command.range)) {
   339                 case Text.Info(r0, info)
   340                 if result.isDefinedAt(Text.Info(convert(r0 + command_start), info)) =>
   341                   result(Text.Info(convert(r0 + command_start), info))
   342               }
   343           } yield Text.Info(convert(r0 + command_start), x)
   344         }
   345       }
   346     }
   347   }
   348 }
   349