src/Tools/jEdit/src/document_view.scala
author wenzelm
Sat Jun 18 21:03:52 2011 +0200 (2011-06-18 ago)
changeset 43448 90aec5043461
parent 43419 6ed49c52d463
child 43510 17d431c92575
permissions -rw-r--r--
more robust caret painting wrt. surrogate characters;
discontinued glyphvector drawing -- less special cases;
     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 range */
   306 
   307   def caret_range(): Text.Range =
   308     Isabelle.buffer_lock(model.buffer) {
   309       def text(i: Text.Offset): Char = model.buffer.getText(i, 1).charAt(0)
   310       val caret = text_area.getCaretPosition
   311       try {
   312         val c = text(caret)
   313         if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(caret + 1)))
   314           Text.Range(caret, caret + 2)
   315         else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(caret - 1)))
   316           Text.Range(caret - 1, caret + 1)
   317         else Text.Range(caret, caret + 1)
   318       }
   319       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(caret, caret + 1) }
   320     }
   321 
   322 
   323   /* caret handling */
   324 
   325   def selected_command(): Option[Command] =
   326   {
   327     Swing_Thread.require()
   328     update_snapshot().node.proper_command_at(text_area.getCaretPosition)
   329   }
   330 
   331   private val caret_listener = new CaretListener {
   332     private val delay = Swing_Thread.delay_last(session.input_delay) {
   333       session.perspective.event(Session.Perspective)
   334     }
   335     override def caretUpdate(e: CaretEvent) { delay() }
   336   }
   337 
   338 
   339   /* overview of command status left of scrollbar */
   340 
   341   private val overview = new JPanel(new BorderLayout)
   342   {
   343     private val WIDTH = 10
   344     private val HEIGHT = 2
   345 
   346     setPreferredSize(new Dimension(WIDTH, 0))
   347 
   348     setRequestFocusEnabled(false)
   349 
   350     addMouseListener(new MouseAdapter {
   351       override def mousePressed(event: MouseEvent) {
   352         val line = y_to_line(event.getY)
   353         if (line >= 0 && line < text_area.getLineCount)
   354           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   355       }
   356     })
   357 
   358     override def addNotify() {
   359       super.addNotify()
   360       ToolTipManager.sharedInstance.registerComponent(this)
   361     }
   362 
   363     override def removeNotify() {
   364       ToolTipManager.sharedInstance.unregisterComponent(this)
   365       super.removeNotify
   366     }
   367 
   368     override def paintComponent(gfx: Graphics)
   369     {
   370       super.paintComponent(gfx)
   371       Swing_Thread.assert()
   372 
   373       val buffer = model.buffer
   374       Isabelle.buffer_lock(buffer) {
   375         val snapshot = update_snapshot()
   376 
   377         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   378         {
   379           try {
   380             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   381             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   382             Some((line1, line2))
   383           }
   384           catch { case e: ArrayIndexOutOfBoundsException => None }
   385         }
   386         for {
   387           (command, start) <- snapshot.node.command_starts
   388           if !command.is_ignored
   389           (line1, line2) <- line_range(command, start)
   390           val y = line_to_y(line1)
   391           val height = HEIGHT * (line2 - line1)
   392           color <- Isabelle_Markup.overview_color(snapshot, command)
   393         } {
   394           gfx.setColor(color)
   395           gfx.fillRect(0, y, getWidth - 1, height)
   396         }
   397       }
   398     }
   399 
   400     private def line_to_y(line: Int): Int =
   401       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   402 
   403     private def y_to_line(y: Int): Int =
   404       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   405   }
   406 
   407 
   408   /* main actor */
   409 
   410   private val main_actor = actor {
   411     loop {
   412       react {
   413         case Session.Commands_Changed(changed) =>
   414           val buffer = model.buffer
   415           Isabelle.swing_buffer_lock(buffer) {
   416             val (updated, snapshot) = flush_snapshot()
   417             val visible_range = screen_lines_range()
   418 
   419             if (updated || changed.exists(snapshot.node.commands.contains))
   420               overview.repaint()
   421 
   422             if (updated) invalidate_line_range(visible_range)
   423             else {
   424               val visible_cmds =
   425                 snapshot.node.command_range(snapshot.revert(visible_range)).map(_._1)
   426               if (visible_cmds.exists(changed)) {
   427                 for {
   428                   line <- 0 until text_area.getVisibleLines
   429                   val start = text_area.getScreenLineStartOffset(line) if start >= 0
   430                   val end = text_area.getScreenLineEndOffset(line) if end >= 0
   431                   val range = proper_line_range(start, end)
   432                   val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   433                   if line_cmds.exists(changed)
   434                 } text_area.invalidateScreenLineRange(line, line)
   435               }
   436             }
   437           }
   438 
   439         case Session.Global_Settings => html_panel_resize()
   440 
   441         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   442       }
   443     }
   444   }
   445 
   446 
   447   /* activation */
   448 
   449   private def activate()
   450   {
   451     val painter = text_area.getPainter
   452     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, tooltip_painter)
   453     text_area_painter.activate()
   454     text_area.getGutter.addExtension(gutter_painter)
   455     text_area.addFocusListener(focus_listener)
   456     text_area.getView.addWindowListener(window_listener)
   457     painter.addMouseMotionListener(mouse_motion_listener)
   458     text_area.addCaretListener(caret_listener)
   459     text_area.addLeftOfScrollBar(overview)
   460     session.commands_changed += main_actor
   461     session.global_settings += main_actor
   462   }
   463 
   464   private def deactivate()
   465   {
   466     val painter = text_area.getPainter
   467     session.commands_changed -= main_actor
   468     session.global_settings -= main_actor
   469     text_area.removeFocusListener(focus_listener)
   470     text_area.getView.removeWindowListener(window_listener)
   471     painter.removeMouseMotionListener(mouse_motion_listener)
   472     text_area.removeCaretListener(caret_listener)
   473     text_area.removeLeftOfScrollBar(overview)
   474     text_area.getGutter.removeExtension(gutter_painter)
   475     text_area_painter.deactivate()
   476     painter.removeExtension(tooltip_painter)
   477     exit_popup()
   478   }
   479 }