src/Tools/jEdit/src/document_view.scala
author wenzelm
Tue Jun 14 11:36:08 2011 +0200 (2011-06-14 ago)
changeset 43381 806878ae2219
parent 43376 0f6880c1c759
child 43387 a59ae768249e
permissions -rw-r--r--
separate module for text area painting;
     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.jedit.{jEdit, OperatingSystem, Debug}
    22 import org.gjt.sp.jedit.gui.RolloverButton
    23 import org.gjt.sp.jedit.options.GutterOptionPane
    24 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea, TextAreaExtension, TextAreaPainter}
    25 import org.gjt.sp.jedit.syntax.{SyntaxStyle}
    26 
    27 
    28 object Document_View
    29 {
    30   /* document view of text area */
    31 
    32   private val key = new Object
    33 
    34   def init(model: Document_Model, text_area: JEditTextArea): Document_View =
    35   {
    36     Swing_Thread.require()
    37     val doc_view = new Document_View(model, text_area)
    38     text_area.putClientProperty(key, doc_view)
    39     doc_view.activate()
    40     doc_view
    41   }
    42 
    43   def apply(text_area: JEditTextArea): Option[Document_View] =
    44   {
    45     Swing_Thread.require()
    46     text_area.getClientProperty(key) match {
    47       case doc_view: Document_View => Some(doc_view)
    48       case _ => None
    49     }
    50   }
    51 
    52   def exit(text_area: JEditTextArea)
    53   {
    54     Swing_Thread.require()
    55     apply(text_area) match {
    56       case None =>
    57       case Some(doc_view) =>
    58         doc_view.deactivate()
    59         text_area.putClientProperty(key, null)
    60     }
    61   }
    62 }
    63 
    64 
    65 class Document_View(val model: Document_Model, val text_area: JEditTextArea)
    66 {
    67   private val session = model.session
    68 
    69 
    70   /** token handling **/
    71 
    72   /* extended token styles */
    73 
    74   private var styles: Array[SyntaxStyle] = null  // owned by Swing thread
    75 
    76   def extend_styles()
    77   {
    78     Swing_Thread.require()
    79     styles = Document_Model.Token_Markup.extend_styles(text_area.getPainter.getStyles)
    80   }
    81   extend_styles()
    82 
    83   def set_styles()
    84   {
    85     Swing_Thread.require()
    86     text_area.getPainter.setStyles(styles)
    87   }
    88 
    89 
    90   /* visible line ranges */
    91 
    92   // simplify slightly odd result of TextArea.getScreenLineEndOffset etc.
    93   // NB: jEdit already normalizes \r\n and \r to \n
    94   def proper_line_range(start: Text.Offset, end: Text.Offset): Text.Range =
    95   {
    96     val stop = if (start < end) end - 1 else end min model.buffer.getLength
    97     Text.Range(start, stop)
    98   }
    99 
   100   def screen_lines_range(): Text.Range =
   101   {
   102     val start = text_area.getScreenLineStartOffset(0)
   103     val raw_end = text_area.getScreenLineEndOffset(text_area.getVisibleLines - 1 max 0)
   104     proper_line_range(start, if (raw_end >= 0) raw_end else model.buffer.getLength)
   105   }
   106 
   107   def invalidate_line_range(range: Text.Range)
   108   {
   109     text_area.invalidateLineRange(
   110       model.buffer.getLineOfOffset(range.start),
   111       model.buffer.getLineOfOffset(range.stop))
   112   }
   113 
   114 
   115   /* HTML popups */
   116 
   117   private var html_popup: Option[Popup] = None
   118 
   119   private def exit_popup() { html_popup.map(_.hide) }
   120 
   121   private val html_panel =
   122     new HTML_Panel(Isabelle.system, Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   123   html_panel.setBorder(BorderFactory.createLineBorder(Color.black))
   124 
   125   private def html_panel_resize()
   126   {
   127     Swing_Thread.now {
   128       html_panel.resize(Isabelle.font_family(), scala.math.round(Isabelle.font_size()))
   129     }
   130   }
   131 
   132   private def init_popup(snapshot: Document.Snapshot, x: Int, y: Int)
   133   {
   134     exit_popup()
   135 /* FIXME broken
   136     val offset = text_area.xyToOffset(x, y)
   137     val p = new Point(x, y); SwingUtilities.convertPointToScreen(p, text_area.getPainter)
   138 
   139     // FIXME snapshot.cumulate
   140     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match {
   141       case Text.Info(_, Some(msg)) #:: _ =>
   142         val popup = PopupFactory.getSharedInstance().getPopup(text_area, html_panel, p.x, p.y + 60)
   143         html_panel.render_sync(List(msg))
   144         Thread.sleep(10)  // FIXME !?
   145         popup.show
   146         html_popup = Some(popup)
   147       case _ =>
   148     }
   149 */
   150   }
   151 
   152 
   153   /* subexpression highlighting */
   154 
   155   private def subexp_range(snapshot: Document.Snapshot, x: Int, y: Int)
   156     : Option[(Text.Range, Color)] =
   157   {
   158     val offset = text_area.xyToOffset(x, y)
   159     snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.subexp) match {
   160       case Text.Info(_, Some((range, color))) #:: _ => Some((snapshot.convert(range), color))
   161       case _ => None
   162     }
   163   }
   164 
   165   @volatile private var _highlight_range: Option[(Text.Range, Color)] = None
   166   def highlight_range(): Option[(Text.Range, Color)] = _highlight_range
   167 
   168 
   169   /* CONTROL-mouse management */
   170 
   171   private var control: Boolean = false
   172 
   173   private def exit_control()
   174   {
   175     exit_popup()
   176     _highlight_range = None
   177   }
   178 
   179   private val focus_listener = new FocusAdapter {
   180     override def focusLost(e: FocusEvent) {
   181       _highlight_range = None // FIXME exit_control !?
   182     }
   183   }
   184 
   185   private val window_listener = new WindowAdapter {
   186     override def windowIconified(e: WindowEvent) { exit_control() }
   187     override def windowDeactivated(e: WindowEvent) { exit_control() }
   188   }
   189 
   190   private val mouse_motion_listener = new MouseMotionAdapter {
   191     override def mouseMoved(e: MouseEvent) {
   192       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   193       val x = e.getX()
   194       val y = e.getY()
   195 
   196       if (!model.buffer.isLoaded) exit_control()
   197       else
   198         Isabelle.swing_buffer_lock(model.buffer) {
   199           val snapshot = model.snapshot
   200 
   201           if (control) init_popup(snapshot, x, y)
   202 
   203           _highlight_range map { case (range, _) => invalidate_line_range(range) }
   204           _highlight_range = if (control) subexp_range(snapshot, x, y) else None
   205           _highlight_range map { case (range, _) => invalidate_line_range(range) }
   206         }
   207     }
   208   }
   209 
   210 
   211   /* text area painting */
   212 
   213   private val text_area_painter = new Text_Area_Painter(this)
   214 
   215   private val tooltip_painter = new TextAreaExtension
   216   {
   217     override def getToolTipText(x: Int, y: Int): String =
   218     {
   219       Isabelle.swing_buffer_lock(model.buffer) {
   220         val snapshot = model.snapshot()
   221         val offset = text_area.xyToOffset(x, y)
   222         if (control) {
   223           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   224           {
   225             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   226             case _ => null
   227           }
   228         }
   229         else {
   230           // FIXME snapshot.cumulate
   231           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   232           {
   233             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   234             case _ => null
   235           }
   236         }
   237       }
   238     }
   239   }
   240 
   241   private val gutter_painter = new TextAreaExtension
   242   {
   243     override def paintScreenLineRange(gfx: Graphics2D,
   244       first_line: Int, last_line: Int, physical_lines: Array[Int],
   245       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   246     {
   247       val gutter = text_area.getGutter
   248       val width = GutterOptionPane.getSelectionAreaWidth
   249       val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   250       val FOLD_MARKER_SIZE = 12
   251 
   252       if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   253         Isabelle.swing_buffer_lock(model.buffer) {
   254           val snapshot = model.snapshot()
   255           for (i <- 0 until physical_lines.length) {
   256             if (physical_lines(i) != -1) {
   257               val line_range = proper_line_range(start(i), end(i))
   258 
   259               // gutter icons
   260               val icons =
   261                 (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   262                   snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   263                 yield icon).toList.sortWith(_ >= _)
   264               icons match {
   265                 case icon :: _ =>
   266                   val icn = icon.icon
   267                   val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   268                   val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   269                   icn.paintIcon(gutter, gfx, x0, y0)
   270                 case Nil =>
   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               // FIXME danger of deadlock!?
   391               // FIXME potentially slow!?
   392               model.buffer.propertiesChanged()
   393             }
   394           }
   395 
   396         case Session.Global_Settings => html_panel_resize()
   397 
   398         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   399       }
   400     }
   401   }
   402 
   403 
   404   /* activation */
   405 
   406   private def activate()
   407   {
   408     val painter = text_area.getPainter
   409     painter.addExtension(TextAreaPainter.TEXT_LAYER, tooltip_painter)
   410     text_area_painter.activate()
   411     text_area.getGutter.addExtension(gutter_painter)
   412     text_area.addFocusListener(focus_listener)
   413     text_area.getView.addWindowListener(window_listener)
   414     painter.addMouseMotionListener(mouse_motion_listener)
   415     text_area.addCaretListener(caret_listener)
   416     text_area.addLeftOfScrollBar(overview)
   417     session.commands_changed += main_actor
   418     session.global_settings += main_actor
   419   }
   420 
   421   private def deactivate()
   422   {
   423     val painter = text_area.getPainter
   424     session.commands_changed -= main_actor
   425     session.global_settings -= main_actor
   426     text_area.removeFocusListener(focus_listener)
   427     text_area.getView.removeWindowListener(window_listener)
   428     painter.removeMouseMotionListener(mouse_motion_listener)
   429     text_area.removeCaretListener(caret_listener)
   430     text_area.removeLeftOfScrollBar(overview)
   431     text_area.getGutter.removeExtension(gutter_painter)
   432     text_area_painter.deactivate()
   433     painter.removeExtension(tooltip_painter)
   434     exit_popup()
   435   }
   436 }