src/Tools/jEdit/src/document_view.scala
author wenzelm
Mon Sep 17 17:56:10 2012 +0200 (2012-09-17)
changeset 49407 215ba6884bdf
parent 49406 38db4832b210
child 49408 3cfc114acd05
permissions -rw-r--r--
tuned signature;
     1 /*  Title:      Tools/jEdit/src/document_view.scala
     2     Author:     Fabian Immler, TU Munich
     3     Author:     Makarius
     4 
     5 Document view connected to jEdit text area.
     6 */
     7 
     8 package isabelle.jedit
     9 
    10 
    11 import isabelle._
    12 
    13 import scala.collection.mutable
    14 import scala.collection.immutable.SortedMap
    15 import scala.actors.Actor._
    16 
    17 import java.lang.System
    18 import java.text.BreakIterator
    19 import java.awt.{Color, Graphics2D, Point}
    20 import java.awt.event.{MouseMotionAdapter, MouseAdapter, MouseEvent,
    21   FocusAdapter, FocusEvent, WindowEvent, WindowAdapter}
    22 import javax.swing.event.{CaretListener, CaretEvent}
    23 
    24 import org.gjt.sp.util.Log
    25 
    26 import org.gjt.sp.jedit.{jEdit, OperatingSystem, Debug}
    27 import org.gjt.sp.jedit.gui.RolloverButton
    28 import org.gjt.sp.jedit.options.GutterOptionPane
    29 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea, TextAreaExtension, TextAreaPainter}
    30 import org.gjt.sp.jedit.syntax.{SyntaxStyle}
    31 
    32 
    33 object Document_View
    34 {
    35   /* document view of text area */
    36 
    37   private val key = new Object
    38 
    39   def apply(text_area: JEditTextArea): Option[Document_View] =
    40   {
    41     Swing_Thread.require()
    42     text_area.getClientProperty(key) match {
    43       case doc_view: Document_View => Some(doc_view)
    44       case _ => None
    45     }
    46   }
    47 
    48   def exit(text_area: JEditTextArea)
    49   {
    50     Swing_Thread.require()
    51     apply(text_area) match {
    52       case None =>
    53       case Some(doc_view) =>
    54         doc_view.deactivate()
    55         text_area.putClientProperty(key, null)
    56     }
    57   }
    58 
    59   def init(model: Document_Model, text_area: JEditTextArea): Document_View =
    60   {
    61     exit(text_area)
    62     val doc_view = new Document_View(model, text_area)
    63     text_area.putClientProperty(key, doc_view)
    64     doc_view.activate()
    65     doc_view
    66   }
    67 }
    68 
    69 
    70 class Document_View(val model: Document_Model, val text_area: JEditTextArea)
    71 {
    72   private val session = model.session
    73 
    74 
    75   /* robust extension body */
    76 
    77   def robust_body[A](default: A)(body: => A): A =
    78   {
    79     try {
    80       Swing_Thread.require()
    81       if (model.buffer == text_area.getBuffer) body
    82       else {
    83         Log.log(Log.ERROR, this, ERROR("Inconsistent document model"))
    84         default
    85       }
    86     }
    87     catch { case t: Throwable => Log.log(Log.ERROR, this, t); default }
    88   }
    89 
    90 
    91   /* visible text range */
    92 
    93   // NB: TextArea.getScreenLineEndOffset of last line is beyond Buffer.getLength
    94   def proper_line_range(start: Text.Offset, end: Text.Offset): Text.Range =
    95     Text.Range(start, end min model.buffer.getLength)
    96 
    97   def visible_range(): Option[Text.Range] =
    98   {
    99     val n = text_area.getVisibleLines
   100     if (n > 0) {
   101       val start = text_area.getScreenLineStartOffset(0)
   102       val raw_end = text_area.getScreenLineEndOffset(n - 1)
   103       Some(proper_line_range(start, if (raw_end >= 0) raw_end else model.buffer.getLength))
   104     }
   105     else None
   106   }
   107 
   108   def invalidate_range(range: Text.Range)
   109   {
   110     text_area.invalidateLineRange(
   111       model.buffer.getLineOfOffset(range.start),
   112       model.buffer.getLineOfOffset(range.stop))
   113   }
   114 
   115 
   116   /* perspective */
   117 
   118   def perspective(): Text.Perspective =
   119   {
   120     Swing_Thread.require()
   121     val buffer_range = model.buffer_range()
   122     Text.Perspective(
   123       for {
   124         i <- 0 until text_area.getVisibleLines
   125         start = text_area.getScreenLineStartOffset(i)
   126         stop = text_area.getScreenLineEndOffset(i)
   127         if start >= 0 && stop >= 0
   128         range <- buffer_range.try_restrict(Text.Range(start, stop))
   129         if !range.is_singularity
   130       }
   131       yield range)
   132   }
   133 
   134   private def update_perspective = new TextAreaExtension
   135   {
   136     override def paintScreenLineRange(gfx: Graphics2D,
   137       first_line: Int, last_line: Int, physical_lines: Array[Int],
   138       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   139     {
   140       model.update_perspective()
   141     }
   142   }
   143 
   144 
   145   /* active areas within the text */
   146 
   147   private class Active_Area[A](
   148     rendering: Isabelle_Rendering => Text.Range => Option[Text.Info[A]])
   149   {
   150     private var the_info: Option[Text.Info[A]] = None
   151 
   152     def info: Option[Text.Info[A]] = the_info
   153 
   154     def update(new_info: Option[Text.Info[A]])
   155     {
   156       val old_info = the_info
   157       if (new_info != old_info) {
   158         for { opt <- List(old_info, new_info); Text.Info(range, _) <- opt }
   159           invalidate_range(range)
   160         the_info = new_info
   161       }
   162     }
   163 
   164     def update_rendering(r: Isabelle_Rendering, range: Text.Range)
   165     { update(rendering(r)(range)) }
   166 
   167     def reset { update(None) }
   168   }
   169 
   170   // owned by Swing thread
   171 
   172   private var control: Boolean = false
   173 
   174   private val highlight_area = new Active_Area[Color]((r: Isabelle_Rendering) => r.highlight _)
   175   def highlight_info(): Option[Text.Info[Color]] = highlight_area.info
   176 
   177   private val hyperlink_area = new Active_Area[Hyperlink]((r: Isabelle_Rendering) => r.hyperlink _)
   178   def hyperlink_info(): Option[Text.Info[Hyperlink]] = hyperlink_area.info
   179 
   180   private val active_areas = List(highlight_area, hyperlink_area)
   181   private def active_reset(): Unit = active_areas.foreach(_.reset)
   182 
   183   private val focus_listener = new FocusAdapter {
   184     override def focusLost(e: FocusEvent) { active_reset() }
   185   }
   186 
   187   private val window_listener = new WindowAdapter {
   188     override def windowIconified(e: WindowEvent) { active_reset() }
   189     override def windowDeactivated(e: WindowEvent) { active_reset() }
   190   }
   191 
   192   private val mouse_listener = new MouseAdapter {
   193     override def mouseClicked(e: MouseEvent) {
   194       hyperlink_area.info match {
   195         case Some(Text.Info(range, link)) => link.follow(text_area.getView)
   196         case None =>
   197       }
   198     }
   199   }
   200 
   201   private val mouse_motion_listener = new MouseMotionAdapter {
   202     override def mouseMoved(e: MouseEvent) {
   203       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   204       if (control && model.buffer.isLoaded) {
   205         JEdit_Lib.buffer_lock(model.buffer) {
   206           val rendering = Isabelle_Rendering(model.snapshot(), Isabelle.options.value)
   207           val mouse_range =
   208             JEdit_Lib.point_range(model.buffer, text_area.xyToOffset(e.getX(), e.getY()))
   209           active_areas.foreach(_.update_rendering(rendering, mouse_range))
   210         }
   211       }
   212       else active_reset()
   213     }
   214   }
   215 
   216 
   217   /* text area painting */
   218 
   219   private val text_area_painter = new Text_Area_Painter(this)
   220 
   221   private val tooltip_painter = new TextAreaExtension
   222   {
   223     override def getToolTipText(x: Int, y: Int): String =
   224     {
   225       robust_body(null: String) {
   226         val rendering = Isabelle_Rendering(model.snapshot(), Isabelle.options.value)
   227         val offset = text_area.xyToOffset(x, y)
   228         val range = Text.Range(offset, offset + 1)
   229         val tip =
   230           if (control) rendering.tooltip(range)
   231           else rendering.tooltip_message(range)
   232         tip.map(Isabelle.tooltip(_)) getOrElse null
   233       }
   234     }
   235   }
   236 
   237   private val gutter_painter = new TextAreaExtension
   238   {
   239     override def paintScreenLineRange(gfx: Graphics2D,
   240       first_line: Int, last_line: Int, physical_lines: Array[Int],
   241       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   242     {
   243       robust_body(()) {
   244         Swing_Thread.assert()
   245 
   246         val gutter = text_area.getGutter
   247         val width = GutterOptionPane.getSelectionAreaWidth
   248         val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   249         val FOLD_MARKER_SIZE = 12
   250 
   251         if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   252           JEdit_Lib.buffer_lock(model.buffer) {
   253             val rendering = Isabelle_Rendering(model.snapshot(), Isabelle.options.value)
   254 
   255             for (i <- 0 until physical_lines.length) {
   256               if (physical_lines(i) != -1) {
   257                 val line_range = proper_line_range(start(i), end(i))
   258 
   259                 // gutter icons
   260                 rendering.gutter_message(line_range) match {
   261                   case Some(icon) =>
   262                     val x0 = (FOLD_MARKER_SIZE + width - border_width - icon.getIconWidth) max 10
   263                     val y0 = y + i * line_height + (((line_height - icon.getIconHeight) / 2) max 0)
   264                     icon.paintIcon(gutter, gfx, x0, y0)
   265                   case None =>
   266                 }
   267               }
   268             }
   269           }
   270         }
   271       }
   272     }
   273   }
   274 
   275 
   276   /* caret handling */
   277 
   278   private val delay_caret_update =
   279     Swing_Thread.delay_last(Time.seconds(Isabelle.options.real("editor_input_delay"))) {
   280       session.caret_focus.event(Session.Caret_Focus)
   281     }
   282 
   283   private val caret_listener = new CaretListener {
   284     override def caretUpdate(e: CaretEvent) { delay_caret_update.invoke() }
   285   }
   286 
   287 
   288   /* text status overview left of scrollbar */
   289 
   290   private object overview extends Text_Overview(this)
   291   {
   292     val delay_repaint =
   293       Swing_Thread.delay_first(
   294         Time.seconds(Isabelle.options.real("editor_update_delay"))) { repaint() }
   295   }
   296 
   297 
   298   /* main actor */
   299 
   300   private val main_actor = actor {
   301     loop {
   302       react {
   303         case _: Session.Raw_Edits =>
   304           Swing_Thread.later {
   305             overview.delay_repaint.postpone(
   306               Time.seconds(Isabelle.options.real("editor_input_delay")))
   307           }
   308 
   309         case changed: Session.Commands_Changed =>
   310           val buffer = model.buffer
   311           Swing_Thread.later {
   312             JEdit_Lib.buffer_lock(buffer) {
   313               if (model.buffer == text_area.getBuffer) {
   314                 val snapshot = model.snapshot()
   315 
   316                 if (changed.assignment ||
   317                     (changed.nodes.contains(model.name) &&
   318                      changed.commands.exists(snapshot.node.commands.contains)))
   319                   Swing_Thread.later { overview.delay_repaint.invoke() }
   320 
   321                 visible_range() match {
   322                   case Some(visible) =>
   323                     if (changed.assignment) invalidate_range(visible)
   324                     else {
   325                       val visible_cmds =
   326                         snapshot.node.command_range(snapshot.revert(visible)).map(_._1)
   327                       if (visible_cmds.exists(changed.commands)) {
   328                         for {
   329                           line <- 0 until text_area.getVisibleLines
   330                           start = text_area.getScreenLineStartOffset(line) if start >= 0
   331                           end = text_area.getScreenLineEndOffset(line) if end >= 0
   332                           range = proper_line_range(start, end)
   333                           line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   334                           if line_cmds.exists(changed.commands)
   335                         } text_area.invalidateScreenLineRange(line, line)
   336                       }
   337                     }
   338                   case None =>
   339                 }
   340               }
   341             }
   342           }
   343 
   344         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   345       }
   346     }
   347   }
   348 
   349 
   350   /* activation */
   351 
   352   private def activate()
   353   {
   354     val painter = text_area.getPainter
   355     painter.addExtension(TextAreaPainter.LOWEST_LAYER, update_perspective)
   356     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, tooltip_painter)
   357     text_area_painter.activate()
   358     text_area.getGutter.addExtension(gutter_painter)
   359     text_area.addFocusListener(focus_listener)
   360     text_area.getView.addWindowListener(window_listener)
   361     painter.addMouseListener(mouse_listener)
   362     painter.addMouseMotionListener(mouse_motion_listener)
   363     text_area.addCaretListener(caret_listener)
   364     text_area.addLeftOfScrollBar(overview)
   365     session.raw_edits += main_actor
   366     session.commands_changed += main_actor
   367   }
   368 
   369   private def deactivate()
   370   {
   371     val painter = text_area.getPainter
   372     session.raw_edits -= main_actor
   373     session.commands_changed -= main_actor
   374     text_area.removeFocusListener(focus_listener)
   375     text_area.getView.removeWindowListener(window_listener)
   376     painter.removeMouseMotionListener(mouse_motion_listener)
   377     painter.removeMouseListener(mouse_listener)
   378     text_area.removeCaretListener(caret_listener); delay_caret_update.revoke()
   379     text_area.removeLeftOfScrollBar(overview); overview.delay_repaint.revoke()
   380     text_area.getGutter.removeExtension(gutter_painter)
   381     text_area_painter.deactivate()
   382     painter.removeExtension(tooltip_painter)
   383     painter.removeExtension(update_perspective)
   384   }
   385 }