src/Tools/jEdit/src/document_view.scala
author wenzelm
Thu Jun 16 22:05:40 2011 +0200 (2011-06-16 ago)
changeset 43414 f0770743b7ec
parent 43404 c8369f3d88a1
child 43417 83be997a11d6
permissions -rw-r--r--
static token markup, based on outer syntax only;
eliminated obsolete buffer.propertiesChanged (expensive due to remarking of full buffer etc.);
     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     Swing_Thread.now {
    76       try {
    77         Isabelle.buffer_lock(model.buffer) {
    78           if (model.buffer == text_area.getBuffer) body
    79           else default
    80         }
    81       }
    82       catch { case t: Throwable => Log.log(Log.ERROR, this, t); default }
    83     }
    84 
    85 
    86   /** token handling **/
    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   /* HTML popups */
   114 
   115   private var html_popup: Option[Popup] = None
   116 
   117   private def exit_popup() { html_popup.map(_.hide) }
   118 
   119   private val html_panel =
   120     new HTML_Panel(Isabelle.system, Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   121   html_panel.setBorder(BorderFactory.createLineBorder(Color.black))
   122 
   123   private def html_panel_resize()
   124   {
   125     Swing_Thread.now {
   126       html_panel.resize(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   127     }
   128   }
   129 
   130   private def init_popup(snapshot: Document.Snapshot, x: Int, y: Int)
   131   {
   132     exit_popup()
   133 /* FIXME broken
   134     val offset = text_area.xyToOffset(x, y)
   135     val p = new Point(x, y); SwingUtilities.convertPointToScreen(p, text_area.getPainter)
   136 
   137     // FIXME snapshot.cumulate
   138     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match {
   139       case Text.Info(_, Some(msg)) #:: _ =>
   140         val popup = PopupFactory.getSharedInstance().getPopup(text_area, html_panel, p.x, p.y + 60)
   141         html_panel.render_sync(List(msg))
   142         Thread.sleep(10)  // FIXME !?
   143         popup.show
   144         html_popup = Some(popup)
   145       case _ =>
   146     }
   147 */
   148   }
   149 
   150 
   151   /* subexpression highlighting */
   152 
   153   private def subexp_range(snapshot: Document.Snapshot, x: Int, y: Int)
   154     : Option[(Text.Range, Color)] =
   155   {
   156     val offset = text_area.xyToOffset(x, y)
   157     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.subexp) match {
   158       case Text.Info(_, Some((range, color))) #:: _ => Some((snapshot.convert(range), color))
   159       case _ => None
   160     }
   161   }
   162 
   163   @volatile private var _highlight_range: Option[(Text.Range, Color)] = None
   164   def highlight_range(): Option[(Text.Range, Color)] = _highlight_range
   165 
   166 
   167   /* CONTROL-mouse management */
   168 
   169   private var control: Boolean = false
   170 
   171   private def exit_control()
   172   {
   173     exit_popup()
   174     _highlight_range = None
   175   }
   176 
   177   private val focus_listener = new FocusAdapter {
   178     override def focusLost(e: FocusEvent) {
   179       _highlight_range = None // FIXME exit_control !?
   180     }
   181   }
   182 
   183   private val window_listener = new WindowAdapter {
   184     override def windowIconified(e: WindowEvent) { exit_control() }
   185     override def windowDeactivated(e: WindowEvent) { exit_control() }
   186   }
   187 
   188   private val mouse_motion_listener = new MouseMotionAdapter {
   189     override def mouseMoved(e: MouseEvent) {
   190       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   191       val x = e.getX()
   192       val y = e.getY()
   193 
   194       if (!model.buffer.isLoaded) exit_control()
   195       else
   196         Isabelle.swing_buffer_lock(model.buffer) {
   197           val snapshot = model.snapshot
   198 
   199           if (control) init_popup(snapshot, x, y)
   200 
   201           _highlight_range map { case (range, _) => invalidate_line_range(range) }
   202           _highlight_range = if (control) subexp_range(snapshot, x, y) else None
   203           _highlight_range map { case (range, _) => invalidate_line_range(range) }
   204         }
   205     }
   206   }
   207 
   208 
   209   /* text area painting */
   210 
   211   private val text_area_painter = new Text_Area_Painter(this)
   212 
   213   private val tooltip_painter = new TextAreaExtension
   214   {
   215     override def getToolTipText(x: Int, y: Int): String =
   216     {
   217       robust_body(null: String) {
   218         val snapshot = model.snapshot()
   219         val offset = text_area.xyToOffset(x, y)
   220         if (control) {
   221           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   222           {
   223             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   224             case _ => null
   225           }
   226         }
   227         else {
   228           // FIXME snapshot.cumulate
   229           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   230           {
   231             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   232             case _ => null
   233           }
   234         }
   235       }
   236     }
   237   }
   238 
   239   private val gutter_painter = new TextAreaExtension
   240   {
   241     override def paintScreenLineRange(gfx: Graphics2D,
   242       first_line: Int, last_line: Int, physical_lines: Array[Int],
   243       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   244     {
   245       robust_body(()) {
   246         val gutter = text_area.getGutter
   247         val width = GutterOptionPane.getSelectionAreaWidth
   248         val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   249         val FOLD_MARKER_SIZE = 12
   250   
   251         if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   252           Isabelle.swing_buffer_lock(model.buffer) {
   253             val snapshot = model.snapshot()
   254             for (i <- 0 until physical_lines.length) {
   255               if (physical_lines(i) != -1) {
   256                 val line_range = proper_line_range(start(i), end(i))
   257   
   258                 // gutter icons
   259                 val icons =
   260                   (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   261                     snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   262                   yield icon).toList.sortWith(_ >= _)
   263                 icons match {
   264                   case icon :: _ =>
   265                     val icn = icon.icon
   266                     val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   267                     val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   268                     icn.paintIcon(gutter, gfx, x0, y0)
   269                   case Nil =>
   270                 }
   271               }
   272             }
   273           }
   274         }
   275       }
   276     }
   277   }
   278 
   279 
   280   /* caret handling */
   281 
   282   def selected_command(): Option[Command] =
   283   {
   284     Swing_Thread.require()
   285     model.snapshot().node.proper_command_at(text_area.getCaretPosition)
   286   }
   287 
   288   private val caret_listener = new CaretListener {
   289     private val delay = Swing_Thread.delay_last(session.input_delay) {
   290       session.perspective.event(Session.Perspective)
   291     }
   292     override def caretUpdate(e: CaretEvent) { delay() }
   293   }
   294 
   295 
   296   /* overview of command status left of scrollbar */
   297 
   298   private val overview = new JPanel(new BorderLayout)
   299   {
   300     private val WIDTH = 10
   301     private val HEIGHT = 2
   302 
   303     setPreferredSize(new Dimension(WIDTH, 0))
   304 
   305     setRequestFocusEnabled(false)
   306 
   307     addMouseListener(new MouseAdapter {
   308       override def mousePressed(event: MouseEvent) {
   309         val line = y_to_line(event.getY)
   310         if (line >= 0 && line < text_area.getLineCount)
   311           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   312       }
   313     })
   314 
   315     override def addNotify() {
   316       super.addNotify()
   317       ToolTipManager.sharedInstance.registerComponent(this)
   318     }
   319 
   320     override def removeNotify() {
   321       ToolTipManager.sharedInstance.unregisterComponent(this)
   322       super.removeNotify
   323     }
   324 
   325     override def paintComponent(gfx: Graphics)
   326     {
   327       super.paintComponent(gfx)
   328       Swing_Thread.assert()
   329 
   330       val buffer = model.buffer
   331       Isabelle.buffer_lock(buffer) {
   332         val snapshot = model.snapshot()
   333 
   334         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   335         {
   336           try {
   337             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   338             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   339             Some((line1, line2))
   340           }
   341           catch { case e: ArrayIndexOutOfBoundsException => None }
   342         }
   343         for {
   344           (command, start) <- snapshot.node.command_starts
   345           if !command.is_ignored
   346           (line1, line2) <- line_range(command, start)
   347           val y = line_to_y(line1)
   348           val height = HEIGHT * (line2 - line1)
   349           color <- Isabelle_Markup.overview_color(snapshot, command)
   350         } {
   351           gfx.setColor(color)
   352           gfx.fillRect(0, y, getWidth - 1, height)
   353         }
   354       }
   355     }
   356 
   357     private def line_to_y(line: Int): Int =
   358       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   359 
   360     private def y_to_line(y: Int): Int =
   361       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   362   }
   363 
   364 
   365   /* main actor */
   366 
   367   private val main_actor = actor {
   368     loop {
   369       react {
   370         case Session.Commands_Changed(changed) =>
   371           val buffer = model.buffer
   372           Isabelle.swing_buffer_lock(buffer) {
   373             val snapshot = model.snapshot()
   374 
   375             if (changed.exists(snapshot.node.commands.contains))
   376               overview.repaint()
   377 
   378             val visible_range = screen_lines_range()
   379             val visible_cmds = snapshot.node.command_range(snapshot.revert(visible_range)).map(_._1)
   380             if (visible_cmds.exists(changed)) {
   381               for {
   382                 line <- 0 until text_area.getVisibleLines
   383                 val start = text_area.getScreenLineStartOffset(line) if start >= 0
   384                 val end = text_area.getScreenLineEndOffset(line) if end >= 0
   385                 val range = proper_line_range(start, end)
   386                 val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   387                 if line_cmds.exists(changed)
   388               } text_area.invalidateScreenLineRange(line, line)
   389             }
   390           }
   391 
   392         case Session.Global_Settings => html_panel_resize()
   393 
   394         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   395       }
   396     }
   397   }
   398 
   399 
   400   /* activation */
   401 
   402   private def activate()
   403   {
   404     val painter = text_area.getPainter
   405     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, tooltip_painter)
   406     text_area_painter.activate()
   407     text_area.getGutter.addExtension(gutter_painter)
   408     text_area.addFocusListener(focus_listener)
   409     text_area.getView.addWindowListener(window_listener)
   410     painter.addMouseMotionListener(mouse_motion_listener)
   411     text_area.addCaretListener(caret_listener)
   412     text_area.addLeftOfScrollBar(overview)
   413     session.commands_changed += main_actor
   414     session.global_settings += main_actor
   415   }
   416 
   417   private def deactivate()
   418   {
   419     val painter = text_area.getPainter
   420     session.commands_changed -= main_actor
   421     session.global_settings -= main_actor
   422     text_area.removeFocusListener(focus_listener)
   423     text_area.getView.removeWindowListener(window_listener)
   424     painter.removeMouseMotionListener(mouse_motion_listener)
   425     text_area.removeCaretListener(caret_listener)
   426     text_area.removeLeftOfScrollBar(overview)
   427     text_area.getGutter.removeExtension(gutter_painter)
   428     text_area_painter.deactivate()
   429     painter.removeExtension(tooltip_painter)
   430     exit_popup()
   431   }
   432 }