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