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