src/Tools/jEdit/src/document_view.scala
author wenzelm
Tue Aug 23 12:20:12 2011 +0200 (2011-08-23)
changeset 44385 e7fdb008aa7d
parent 44379 1079ab6b342b
child 44436 546adfa8a6fc
permissions -rw-r--r--
propagate editor perspective through document model;
     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 import org.gjt.sp.jedit.syntax.{SyntaxStyle}
    30 
    31 
    32 object Document_View
    33 {
    34   /* document view of text area */
    35 
    36   private val key = new Object
    37 
    38   def apply(text_area: JEditTextArea): Option[Document_View] =
    39   {
    40     Swing_Thread.require()
    41     text_area.getClientProperty(key) match {
    42       case doc_view: Document_View => Some(doc_view)
    43       case _ => None
    44     }
    45   }
    46 
    47   def exit(text_area: JEditTextArea)
    48   {
    49     Swing_Thread.require()
    50     apply(text_area) match {
    51       case None =>
    52       case Some(doc_view) =>
    53         doc_view.deactivate()
    54         text_area.putClientProperty(key, null)
    55     }
    56   }
    57 
    58   def init(model: Document_Model, text_area: JEditTextArea): Document_View =
    59   {
    60     exit(text_area)
    61     val doc_view = new Document_View(model, text_area)
    62     text_area.putClientProperty(key, doc_view)
    63     doc_view.activate()
    64     doc_view
    65   }
    66 }
    67 
    68 
    69 class Document_View(val model: Document_Model, val text_area: JEditTextArea)
    70 {
    71   private val session = model.session
    72 
    73 
    74   /* robust extension body */
    75 
    76   def robust_body[A](default: A)(body: => A): A =
    77   {
    78     try {
    79       Swing_Thread.require()
    80       if (model.buffer == text_area.getBuffer) body
    81       else {
    82         Log.log(Log.ERROR, this, ERROR("Inconsistent document model"))
    83         default
    84       }
    85     }
    86     catch { case t: Throwable => Log.log(Log.ERROR, this, t); default }
    87   }
    88 
    89 
    90   /* visible text range */
    91 
    92   // simplify slightly odd result of TextArea.getScreenLineEndOffset etc.
    93   // NB: jEdit already normalizes \r\n and \r to \n
    94   def proper_line_range(start: Text.Offset, end: Text.Offset): Text.Range =
    95   {
    96     val stop = if (start < end) end - 1 else end min model.buffer.getLength
    97     Text.Range(start, stop)
    98   }
    99 
   100   def visible_range(): Text.Range =
   101   {
   102     val start = text_area.getScreenLineStartOffset(0)
   103     val raw_end = text_area.getScreenLineEndOffset(text_area.getVisibleLines - 1 max 0)
   104     proper_line_range(start, if (raw_end >= 0) raw_end else model.buffer.getLength)
   105   }
   106 
   107   def invalidate_range(range: Text.Range)
   108   {
   109     text_area.invalidateLineRange(
   110       model.buffer.getLineOfOffset(range.start),
   111       model.buffer.getLineOfOffset(range.stop))
   112   }
   113 
   114 
   115   /* perspective */
   116 
   117   def perspective(): Text.Perspective =
   118   {
   119     Swing_Thread.require()
   120     Text.perspective(
   121       for {
   122         i <- 0 until text_area.getVisibleLines
   123         val start = text_area.getScreenLineStartOffset(i)
   124         val stop = text_area.getScreenLineEndOffset(i)
   125         if start >= 0 && stop >= 0
   126       }
   127       yield Text.Range(start, stop))
   128   }
   129 
   130 
   131   /* snapshot */
   132 
   133   // owned by Swing thread
   134   @volatile private var was_outdated = false
   135   @volatile private var was_updated = false
   136 
   137   def update_snapshot(): Document.Snapshot =
   138   {
   139     Swing_Thread.require()
   140     val snapshot = model.snapshot()
   141     was_updated = was_outdated && !snapshot.is_outdated
   142     was_outdated = was_outdated || snapshot.is_outdated
   143     snapshot
   144   }
   145 
   146   def flush_snapshot(): (Boolean, Document.Snapshot) =
   147   {
   148     Swing_Thread.require()
   149     val snapshot = update_snapshot()
   150     val updated = was_updated
   151     if (updated) { was_outdated = false; was_updated = false }
   152     (updated, snapshot)
   153   }
   154 
   155 
   156   /* HTML popups */
   157 
   158   private var html_popup: Option[Popup] = None
   159 
   160   private def exit_popup() { html_popup.map(_.hide) }
   161 
   162   private val html_panel =
   163     new HTML_Panel(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   164   html_panel.setBorder(BorderFactory.createLineBorder(Color.black))
   165 
   166   private def html_panel_resize()
   167   {
   168     Swing_Thread.now {
   169       html_panel.resize(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   170     }
   171   }
   172 
   173   private def init_popup(snapshot: Document.Snapshot, x: Int, y: Int)
   174   {
   175     exit_popup()
   176 /* FIXME broken
   177     val offset = text_area.xyToOffset(x, y)
   178     val p = new Point(x, y); SwingUtilities.convertPointToScreen(p, text_area.getPainter)
   179 
   180     // FIXME snapshot.cumulate
   181     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match {
   182       case Text.Info(_, Some(msg)) #:: _ =>
   183         val popup = PopupFactory.getSharedInstance().getPopup(text_area, html_panel, p.x, p.y + 60)
   184         html_panel.render_sync(List(msg))
   185         Thread.sleep(10)  // FIXME !?
   186         popup.show
   187         html_popup = Some(popup)
   188       case _ =>
   189     }
   190 */
   191   }
   192 
   193 
   194   /* subexpression highlighting */
   195 
   196   private def subexp_range(snapshot: Document.Snapshot, x: Int, y: Int)
   197     : Option[(Text.Range, Color)] =
   198   {
   199     val offset = text_area.xyToOffset(x, y)
   200     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.subexp) match {
   201       case Text.Info(_, Some((range, color))) #:: _ => Some((snapshot.convert(range), color))
   202       case _ => None
   203     }
   204   }
   205 
   206   @volatile private var _highlight_range: Option[(Text.Range, Color)] = None
   207   def highlight_range(): Option[(Text.Range, Color)] = _highlight_range
   208 
   209 
   210   /* CONTROL-mouse management */
   211 
   212   private var control: Boolean = false
   213 
   214   private def exit_control()
   215   {
   216     exit_popup()
   217     _highlight_range = None
   218   }
   219 
   220   private val focus_listener = new FocusAdapter {
   221     override def focusLost(e: FocusEvent) {
   222       _highlight_range = None // FIXME exit_control !?
   223     }
   224   }
   225 
   226   private val window_listener = new WindowAdapter {
   227     override def windowIconified(e: WindowEvent) { exit_control() }
   228     override def windowDeactivated(e: WindowEvent) { exit_control() }
   229   }
   230 
   231   private val mouse_motion_listener = new MouseMotionAdapter {
   232     override def mouseMoved(e: MouseEvent) {
   233       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   234       val x = e.getX()
   235       val y = e.getY()
   236 
   237       if (!model.buffer.isLoaded) exit_control()
   238       else
   239         Isabelle.swing_buffer_lock(model.buffer) {
   240           val snapshot = update_snapshot()
   241 
   242           if (control) init_popup(snapshot, x, y)
   243 
   244           _highlight_range map { case (range, _) => invalidate_range(range) }
   245           _highlight_range = if (control) subexp_range(snapshot, x, y) else None
   246           _highlight_range map { case (range, _) => invalidate_range(range) }
   247         }
   248     }
   249   }
   250 
   251 
   252   /* text area painting */
   253 
   254   private val text_area_painter = new Text_Area_Painter(this)
   255 
   256   private val tooltip_painter = new TextAreaExtension
   257   {
   258     override def getToolTipText(x: Int, y: Int): String =
   259     {
   260       robust_body(null: String) {
   261         val snapshot = update_snapshot()
   262         val offset = text_area.xyToOffset(x, y)
   263         if (control) {
   264           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   265           {
   266             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   267             case _ => null
   268           }
   269         }
   270         else {
   271           // FIXME snapshot.cumulate
   272           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   273           {
   274             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   275             case _ => null
   276           }
   277         }
   278       }
   279     }
   280   }
   281 
   282   private val gutter_painter = new TextAreaExtension
   283   {
   284     override def paintScreenLineRange(gfx: Graphics2D,
   285       first_line: Int, last_line: Int, physical_lines: Array[Int],
   286       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   287     {
   288       robust_body(()) {
   289         val gutter = text_area.getGutter
   290         val width = GutterOptionPane.getSelectionAreaWidth
   291         val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   292         val FOLD_MARKER_SIZE = 12
   293 
   294         if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   295           Isabelle.swing_buffer_lock(model.buffer) {
   296             val snapshot = update_snapshot()
   297             for (i <- 0 until physical_lines.length) {
   298               if (physical_lines(i) != -1) {
   299                 val line_range = proper_line_range(start(i), end(i))
   300 
   301                 // gutter icons
   302                 val icons =
   303                   (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   304                     snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   305                   yield icon).toList.sortWith(_ >= _)
   306                 icons match {
   307                   case icon :: _ =>
   308                     val icn = icon.icon
   309                     val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   310                     val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   311                     icn.paintIcon(gutter, gfx, x0, y0)
   312                   case Nil =>
   313                 }
   314               }
   315             }
   316           }
   317         }
   318       }
   319     }
   320   }
   321 
   322 
   323   /* caret range */
   324 
   325   def caret_range(): Text.Range =
   326     Isabelle.buffer_lock(model.buffer) {
   327       def text(i: Text.Offset): Char = model.buffer.getText(i, 1).charAt(0)
   328       val caret = text_area.getCaretPosition
   329       try {
   330         val c = text(caret)
   331         if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(caret + 1)))
   332           Text.Range(caret, caret + 2)
   333         else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(caret - 1)))
   334           Text.Range(caret - 1, caret + 1)
   335         else Text.Range(caret, caret + 1)
   336       }
   337       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(caret, caret + 1) }
   338     }
   339 
   340 
   341   /* caret handling */
   342 
   343   def selected_command(): Option[Command] =
   344   {
   345     Swing_Thread.require()
   346     update_snapshot().node.proper_command_at(text_area.getCaretPosition)
   347   }
   348 
   349   private val caret_listener = new CaretListener {
   350     private val delay = Swing_Thread.delay_last(session.input_delay) {
   351       session.perspective.event(Session.Perspective)
   352     }
   353     override def caretUpdate(e: CaretEvent) { delay() }
   354   }
   355 
   356 
   357   /* overview of command status left of scrollbar */
   358 
   359   private val overview = new JPanel(new BorderLayout)
   360   {
   361     private val WIDTH = 10
   362     private val HEIGHT = 2
   363 
   364     setPreferredSize(new Dimension(WIDTH, 0))
   365 
   366     setRequestFocusEnabled(false)
   367 
   368     addMouseListener(new MouseAdapter {
   369       override def mousePressed(event: MouseEvent) {
   370         val line = y_to_line(event.getY)
   371         if (line >= 0 && line < text_area.getLineCount)
   372           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   373       }
   374     })
   375 
   376     override def addNotify() {
   377       super.addNotify()
   378       ToolTipManager.sharedInstance.registerComponent(this)
   379     }
   380 
   381     override def removeNotify() {
   382       ToolTipManager.sharedInstance.unregisterComponent(this)
   383       super.removeNotify
   384     }
   385 
   386     override def paintComponent(gfx: Graphics)
   387     {
   388       super.paintComponent(gfx)
   389       Swing_Thread.assert()
   390 
   391       val buffer = model.buffer
   392       Isabelle.buffer_lock(buffer) {
   393         val snapshot = update_snapshot()
   394 
   395         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   396         {
   397           try {
   398             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   399             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   400             Some((line1, line2))
   401           }
   402           catch { case e: ArrayIndexOutOfBoundsException => None }
   403         }
   404         for {
   405           (command, start) <- snapshot.node.command_starts
   406           if !command.is_ignored
   407           (line1, line2) <- line_range(command, start)
   408           val y = line_to_y(line1)
   409           val height = HEIGHT * (line2 - line1)
   410           color <- Isabelle_Markup.overview_color(snapshot, command)
   411         } {
   412           gfx.setColor(color)
   413           gfx.fillRect(0, y, getWidth - 1, height)
   414         }
   415       }
   416     }
   417 
   418     private def line_to_y(line: Int): Int =
   419       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   420 
   421     private def y_to_line(y: Int): Int =
   422       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   423   }
   424 
   425 
   426   /* main actor */
   427 
   428   private val main_actor = actor {
   429     loop {
   430       react {
   431         case Session.Commands_Changed(changed) =>
   432           val buffer = model.buffer
   433           Isabelle.swing_buffer_lock(buffer) {
   434             val (updated, snapshot) = flush_snapshot()
   435             val visible = visible_range()
   436 
   437             if (updated || changed.exists(snapshot.node.commands.contains))
   438               overview.repaint()
   439 
   440             if (updated) invalidate_range(visible)
   441             else {
   442               val visible_cmds =
   443                 snapshot.node.command_range(snapshot.revert(visible)).map(_._1)
   444               if (visible_cmds.exists(changed)) {
   445                 for {
   446                   line <- 0 until text_area.getVisibleLines
   447                   val start = text_area.getScreenLineStartOffset(line) if start >= 0
   448                   val end = text_area.getScreenLineEndOffset(line) if end >= 0
   449                   val range = proper_line_range(start, end)
   450                   val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   451                   if line_cmds.exists(changed)
   452                 } text_area.invalidateScreenLineRange(line, line)
   453               }
   454             }
   455           }
   456 
   457         case Session.Global_Settings => html_panel_resize()
   458 
   459         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   460       }
   461     }
   462   }
   463 
   464 
   465   /* activation */
   466 
   467   private def activate()
   468   {
   469     val painter = text_area.getPainter
   470     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, tooltip_painter)
   471     text_area_painter.activate()
   472     text_area.getGutter.addExtension(gutter_painter)
   473     text_area.addFocusListener(focus_listener)
   474     text_area.getView.addWindowListener(window_listener)
   475     painter.addMouseMotionListener(mouse_motion_listener)
   476     text_area.addCaretListener(caret_listener)
   477     text_area.addLeftOfScrollBar(overview)
   478     session.commands_changed += main_actor
   479     session.global_settings += main_actor
   480   }
   481 
   482   private def deactivate()
   483   {
   484     val painter = text_area.getPainter
   485     session.commands_changed -= main_actor
   486     session.global_settings -= main_actor
   487     text_area.removeFocusListener(focus_listener)
   488     text_area.getView.removeWindowListener(window_listener)
   489     painter.removeMouseMotionListener(mouse_motion_listener)
   490     text_area.removeCaretListener(caret_listener)
   491     text_area.removeLeftOfScrollBar(overview)
   492     text_area.getGutter.removeExtension(gutter_painter)
   493     text_area_painter.deactivate()
   494     painter.removeExtension(tooltip_painter)
   495     exit_popup()
   496   }
   497 }