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