src/Tools/jEdit/src/document_view.scala
author wenzelm
Wed Sep 07 21:38:48 2011 +0200 (2011-09-07)
changeset 44805 48a5c104d434
parent 44776 47e8c8daccae
child 45460 dcd02d1a25d7
permissions -rw-r--r--
clarified terminology;
     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.actors.Actor._
    15 
    16 import java.lang.System
    17 import java.awt.{BorderLayout, Graphics, Color, Dimension, Graphics2D, Point}
    18 import java.awt.event.{MouseAdapter, MouseMotionAdapter, MouseEvent,
    19   FocusAdapter, FocusEvent, WindowEvent, WindowAdapter}
    20 import javax.swing.{JPanel, ToolTipManager, Popup, PopupFactory, SwingUtilities, BorderFactory}
    21 import javax.swing.event.{CaretListener, CaretEvent}
    22 
    23 import org.gjt.sp.util.Log
    24 
    25 import org.gjt.sp.jedit.{jEdit, OperatingSystem, Debug}
    26 import org.gjt.sp.jedit.gui.RolloverButton
    27 import org.gjt.sp.jedit.options.GutterOptionPane
    28 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea, TextAreaExtension, TextAreaPainter,
    29   ScrollListener}
    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   // simplify slightly odd result of TextArea.getScreenLineEndOffset etc.
    94   // NB: jEdit already normalizes \r\n and \r to \n
    95   def proper_line_range(start: Text.Offset, end: Text.Offset): Text.Range =
    96   {
    97     val stop = if (start < end) end - 1 else end min model.buffer.getLength
    98     Text.Range(start, stop)
    99   }
   100 
   101   def visible_range(): Text.Range =
   102   {
   103     val start = text_area.getScreenLineStartOffset(0)
   104     val raw_end = text_area.getScreenLineEndOffset(text_area.getVisibleLines - 1 max 0)
   105     proper_line_range(start, if (raw_end >= 0) raw_end else model.buffer.getLength)
   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         val start = text_area.getScreenLineStartOffset(i)
   126         val stop = text_area.getScreenLineEndOffset(i)
   127         if start >= 0 && stop >= 0
   128         val 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   /* snapshot */
   146 
   147   // owned by Swing thread
   148   @volatile private var was_outdated = false
   149   @volatile private var was_updated = false
   150 
   151   def update_snapshot(): Document.Snapshot =
   152   {
   153     Swing_Thread.require()
   154     val snapshot = model.snapshot()
   155     was_updated = was_outdated && !snapshot.is_outdated
   156     was_outdated = was_outdated || snapshot.is_outdated
   157     snapshot
   158   }
   159 
   160   def flush_snapshot(): (Boolean, Document.Snapshot) =
   161   {
   162     Swing_Thread.require()
   163     val snapshot = update_snapshot()
   164     val updated = was_updated
   165     if (updated) { was_outdated = false; was_updated = false }
   166     (updated, snapshot)
   167   }
   168 
   169 
   170   /* HTML popups */
   171 
   172   private var html_popup: Option[Popup] = None
   173 
   174   private def exit_popup() { html_popup.map(_.hide) }
   175 
   176   private val html_panel =
   177     new HTML_Panel(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   178   html_panel.setBorder(BorderFactory.createLineBorder(Color.black))
   179 
   180   private def html_panel_resize()
   181   {
   182     Swing_Thread.now {
   183       html_panel.resize(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   184     }
   185   }
   186 
   187   private def init_popup(snapshot: Document.Snapshot, x: Int, y: Int)
   188   {
   189     exit_popup()
   190 /* FIXME broken
   191     val offset = text_area.xyToOffset(x, y)
   192     val p = new Point(x, y); SwingUtilities.convertPointToScreen(p, text_area.getPainter)
   193 
   194     // FIXME snapshot.cumulate
   195     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match {
   196       case Text.Info(_, Some(msg)) #:: _ =>
   197         val popup = PopupFactory.getSharedInstance().getPopup(text_area, html_panel, p.x, p.y + 60)
   198         html_panel.render_sync(List(msg))
   199         Thread.sleep(10)  // FIXME !?
   200         popup.show
   201         html_popup = Some(popup)
   202       case _ =>
   203     }
   204 */
   205   }
   206 
   207 
   208   /* subexpression highlighting */
   209 
   210   private def subexp_range(snapshot: Document.Snapshot, x: Int, y: Int)
   211     : Option[(Text.Range, Color)] =
   212   {
   213     val offset = text_area.xyToOffset(x, y)
   214     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.subexp) match {
   215       case Text.Info(_, Some((range, color))) #:: _ => Some((snapshot.convert(range), color))
   216       case _ => None
   217     }
   218   }
   219 
   220   @volatile private var _highlight_range: Option[(Text.Range, Color)] = None
   221   def highlight_range(): Option[(Text.Range, Color)] = _highlight_range
   222 
   223 
   224   /* CONTROL-mouse management */
   225 
   226   private var control: Boolean = false
   227 
   228   private def exit_control()
   229   {
   230     exit_popup()
   231     _highlight_range = None
   232   }
   233 
   234   private val focus_listener = new FocusAdapter {
   235     override def focusLost(e: FocusEvent) {
   236       _highlight_range = None // FIXME exit_control !?
   237     }
   238   }
   239 
   240   private val window_listener = new WindowAdapter {
   241     override def windowIconified(e: WindowEvent) { exit_control() }
   242     override def windowDeactivated(e: WindowEvent) { exit_control() }
   243   }
   244 
   245   private val mouse_motion_listener = new MouseMotionAdapter {
   246     override def mouseMoved(e: MouseEvent) {
   247       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   248       val x = e.getX()
   249       val y = e.getY()
   250 
   251       if (!model.buffer.isLoaded) exit_control()
   252       else
   253         Isabelle.swing_buffer_lock(model.buffer) {
   254           val snapshot = update_snapshot()
   255 
   256           if (control) init_popup(snapshot, x, y)
   257 
   258           _highlight_range map { case (range, _) => invalidate_range(range) }
   259           _highlight_range = if (control) subexp_range(snapshot, x, y) else None
   260           _highlight_range map { case (range, _) => invalidate_range(range) }
   261         }
   262     }
   263   }
   264 
   265 
   266   /* text area painting */
   267 
   268   private val text_area_painter = new Text_Area_Painter(this)
   269 
   270   private val tooltip_painter = new TextAreaExtension
   271   {
   272     override def getToolTipText(x: Int, y: Int): String =
   273     {
   274       robust_body(null: String) {
   275         val snapshot = update_snapshot()
   276         val offset = text_area.xyToOffset(x, y)
   277         if (control) {
   278           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   279           {
   280             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   281             case _ => null
   282           }
   283         }
   284         else {
   285           // FIXME snapshot.cumulate
   286           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   287           {
   288             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   289             case _ => null
   290           }
   291         }
   292       }
   293     }
   294   }
   295 
   296   private val gutter_painter = new TextAreaExtension
   297   {
   298     override def paintScreenLineRange(gfx: Graphics2D,
   299       first_line: Int, last_line: Int, physical_lines: Array[Int],
   300       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   301     {
   302       robust_body(()) {
   303         val gutter = text_area.getGutter
   304         val width = GutterOptionPane.getSelectionAreaWidth
   305         val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   306         val FOLD_MARKER_SIZE = 12
   307 
   308         if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   309           Isabelle.swing_buffer_lock(model.buffer) {
   310             val snapshot = update_snapshot()
   311             for (i <- 0 until physical_lines.length) {
   312               if (physical_lines(i) != -1) {
   313                 val line_range = proper_line_range(start(i), end(i))
   314 
   315                 // gutter icons
   316                 val icons =
   317                   (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   318                     snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   319                   yield icon).toList.sortWith(_ >= _)
   320                 icons match {
   321                   case icon :: _ =>
   322                     val icn = icon.icon
   323                     val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   324                     val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   325                     icn.paintIcon(gutter, gfx, x0, y0)
   326                   case Nil =>
   327                 }
   328               }
   329             }
   330           }
   331         }
   332       }
   333     }
   334   }
   335 
   336 
   337   /* caret range */
   338 
   339   def caret_range(): Text.Range =
   340     Isabelle.buffer_lock(model.buffer) {
   341       def text(i: Text.Offset): Char = model.buffer.getText(i, 1).charAt(0)
   342       val caret = text_area.getCaretPosition
   343       try {
   344         val c = text(caret)
   345         if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(caret + 1)))
   346           Text.Range(caret, caret + 2)
   347         else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(caret - 1)))
   348           Text.Range(caret - 1, caret + 1)
   349         else Text.Range(caret, caret + 1)
   350       }
   351       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(caret, caret + 1) }
   352     }
   353 
   354 
   355   /* caret handling */
   356 
   357   def selected_command(): Option[Command] =
   358   {
   359     Swing_Thread.require()
   360     update_snapshot().node.proper_command_at(text_area.getCaretPosition)
   361   }
   362 
   363   private val caret_listener = new CaretListener {
   364     private val delay = Swing_Thread.delay_last(session.input_delay) {
   365       session.caret_focus.event(Session.Caret_Focus)
   366     }
   367     override def caretUpdate(e: CaretEvent) { delay() }
   368   }
   369 
   370 
   371   /* overview of command status left of scrollbar */
   372 
   373   private val overview = new JPanel(new BorderLayout)
   374   {
   375     private val WIDTH = 10
   376     private val HEIGHT = 2
   377 
   378     setPreferredSize(new Dimension(WIDTH, 0))
   379 
   380     setRequestFocusEnabled(false)
   381 
   382     addMouseListener(new MouseAdapter {
   383       override def mousePressed(event: MouseEvent) {
   384         val line = y_to_line(event.getY)
   385         if (line >= 0 && line < text_area.getLineCount)
   386           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   387       }
   388     })
   389 
   390     override def addNotify() {
   391       super.addNotify()
   392       ToolTipManager.sharedInstance.registerComponent(this)
   393     }
   394 
   395     override def removeNotify() {
   396       ToolTipManager.sharedInstance.unregisterComponent(this)
   397       super.removeNotify
   398     }
   399 
   400     override def paintComponent(gfx: Graphics)
   401     {
   402       super.paintComponent(gfx)
   403       Swing_Thread.assert()
   404 
   405       val buffer = model.buffer
   406       Isabelle.buffer_lock(buffer) {
   407         val snapshot = update_snapshot()
   408 
   409         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   410         {
   411           try {
   412             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   413             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   414             Some((line1, line2))
   415           }
   416           catch { case e: ArrayIndexOutOfBoundsException => None }
   417         }
   418         for {
   419           (command, start) <- snapshot.node.command_starts
   420           if !command.is_ignored
   421           (line1, line2) <- line_range(command, start)
   422           val y = line_to_y(line1)
   423           val height = HEIGHT * (line2 - line1)
   424           color <- Isabelle_Markup.overview_color(snapshot, command)
   425         } {
   426           gfx.setColor(color)
   427           gfx.fillRect(0, y, getWidth - 1, height)
   428         }
   429       }
   430     }
   431 
   432     private def line_to_y(line: Int): Int =
   433       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   434 
   435     private def y_to_line(y: Int): Int =
   436       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   437   }
   438 
   439 
   440   /* main actor */
   441 
   442   private val main_actor = actor {
   443     loop {
   444       react {
   445         case changed: Session.Commands_Changed =>
   446           val buffer = model.buffer
   447           Isabelle.swing_buffer_lock(buffer) {
   448             val (updated, snapshot) = flush_snapshot()
   449             val visible = visible_range()
   450 
   451             if (updated ||
   452                 (changed.nodes.contains(model.name) &&
   453                  changed.commands.exists(snapshot.node.commands.contains)))
   454               overview.repaint()
   455 
   456             if (updated) invalidate_range(visible)
   457             else {
   458               val visible_cmds =
   459                 snapshot.node.command_range(snapshot.revert(visible)).map(_._1)
   460               if (visible_cmds.exists(changed.commands)) {
   461                 for {
   462                   line <- 0 until text_area.getVisibleLines
   463                   val start = text_area.getScreenLineStartOffset(line) if start >= 0
   464                   val end = text_area.getScreenLineEndOffset(line) if end >= 0
   465                   val range = proper_line_range(start, end)
   466                   val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   467                   if line_cmds.exists(changed.commands)
   468                 } text_area.invalidateScreenLineRange(line, line)
   469               }
   470             }
   471           }
   472 
   473         case Session.Global_Settings => html_panel_resize()
   474 
   475         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   476       }
   477     }
   478   }
   479 
   480 
   481   /* activation */
   482 
   483   private def activate()
   484   {
   485     val painter = text_area.getPainter
   486     painter.addExtension(TextAreaPainter.LOWEST_LAYER, update_perspective)
   487     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, tooltip_painter)
   488     text_area_painter.activate()
   489     text_area.getGutter.addExtension(gutter_painter)
   490     text_area.addFocusListener(focus_listener)
   491     text_area.getView.addWindowListener(window_listener)
   492     painter.addMouseMotionListener(mouse_motion_listener)
   493     text_area.addCaretListener(caret_listener)
   494     text_area.addLeftOfScrollBar(overview)
   495     session.commands_changed += main_actor
   496     session.global_settings += main_actor
   497   }
   498 
   499   private def deactivate()
   500   {
   501     val painter = text_area.getPainter
   502     session.commands_changed -= main_actor
   503     session.global_settings -= main_actor
   504     text_area.removeFocusListener(focus_listener)
   505     text_area.getView.removeWindowListener(window_listener)
   506     painter.removeMouseMotionListener(mouse_motion_listener)
   507     text_area.removeCaretListener(caret_listener)
   508     text_area.removeLeftOfScrollBar(overview)
   509     text_area.getGutter.removeExtension(gutter_painter)
   510     text_area_painter.deactivate()
   511     painter.removeExtension(tooltip_painter)
   512     painter.removeExtension(update_perspective)
   513     exit_popup()
   514   }
   515 }