src/Tools/jEdit/src/document_view.scala
author wenzelm
Mon Jun 13 23:09:01 2011 +0200 (2011-06-13 ago)
changeset 43376 0f6880c1c759
parent 43369 4c86b3405010
child 43381 806878ae2219
permissions -rw-r--r--
some direct text foreground painting, instead of token marking;
common snapshot for all text area painters (NOT gutter etc.)
tuned;
     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   private var highlight_range: Option[(Text.Range, Color)] = None
   166 
   167 
   168   /* CONTROL-mouse management */
   169 
   170   private var control: Boolean = false
   171 
   172   private def exit_control()
   173   {
   174     exit_popup()
   175     highlight_range = None
   176   }
   177 
   178   private val focus_listener = new FocusAdapter {
   179     override def focusLost(e: FocusEvent) {
   180       highlight_range = None // FIXME exit_control !?
   181     }
   182   }
   183 
   184   private val window_listener = new WindowAdapter {
   185     override def windowIconified(e: WindowEvent) { exit_control() }
   186     override def windowDeactivated(e: WindowEvent) { exit_control() }
   187   }
   188 
   189   private val mouse_motion_listener = new MouseMotionAdapter {
   190     override def mouseMoved(e: MouseEvent) {
   191       control = if (OperatingSystem.isMacOS()) e.isMetaDown else e.isControlDown
   192       val x = e.getX()
   193       val y = e.getY()
   194 
   195       if (!model.buffer.isLoaded) exit_control()
   196       else
   197         Isabelle.swing_buffer_lock(model.buffer) {
   198           val snapshot = model.snapshot
   199 
   200           if (control) init_popup(snapshot, x, y)
   201 
   202           highlight_range map { case (range, _) => invalidate_line_range(range) }
   203           highlight_range = if (control) subexp_range(snapshot, x, y) else None
   204           highlight_range map { case (range, _) => invalidate_line_range(range) }
   205         }
   206     }
   207   }
   208 
   209 
   210   /* TextArea painting */
   211 
   212   @volatile private var _text_area_snapshot: Option[Document.Snapshot] = None
   213 
   214   def text_area_snapshot(): Document.Snapshot =
   215     _text_area_snapshot match {
   216       case Some(snapshot) => snapshot
   217       case None => error("Missing text area snapshot")
   218     }
   219 
   220   private val set_snapshot = new TextAreaExtension
   221   {
   222     override def paintScreenLineRange(gfx: Graphics2D,
   223       first_line: Int, last_line: Int, physical_lines: Array[Int],
   224       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   225     {
   226       _text_area_snapshot = Some(model.snapshot())
   227     }
   228   }
   229 
   230   private val reset_snapshot = new TextAreaExtension
   231   {
   232     override def paintScreenLineRange(gfx: Graphics2D,
   233       first_line: Int, last_line: Int, physical_lines: Array[Int],
   234       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   235     {
   236       _text_area_snapshot = None
   237     }
   238   }
   239 
   240   private val background_painter = new TextAreaExtension
   241   {
   242     override def paintScreenLineRange(gfx: Graphics2D,
   243       first_line: Int, last_line: Int, physical_lines: Array[Int],
   244       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   245     {
   246       Isabelle.swing_buffer_lock(model.buffer) {
   247         val snapshot = text_area_snapshot()
   248         val ascent = text_area.getPainter.getFontMetrics.getAscent
   249 
   250         for (i <- 0 until physical_lines.length) {
   251           if (physical_lines(i) != -1) {
   252             val line_range = proper_line_range(start(i), end(i))
   253 
   254             // background color: status
   255             val cmds = snapshot.node.command_range(snapshot.revert(line_range))
   256             for {
   257               (command, command_start) <- cmds if !command.is_ignored
   258               val range = line_range.restrict(snapshot.convert(command.range + command_start))
   259               r <- Isabelle.gfx_range(text_area, range)
   260               color <- Isabelle_Markup.status_color(snapshot, command)
   261             } {
   262               gfx.setColor(color)
   263               gfx.fillRect(r.x, y + i * line_height, r.length, line_height)
   264             }
   265 
   266             // background color (1): markup
   267             for {
   268               Text.Info(range, Some(color)) <-
   269                 snapshot.select_markup(line_range)(Isabelle_Markup.background1).iterator
   270               r <- Isabelle.gfx_range(text_area, range)
   271             } {
   272               gfx.setColor(color)
   273               gfx.fillRect(r.x, y + i * line_height, r.length, line_height)
   274             }
   275 
   276             // background color (2): markup
   277             for {
   278               Text.Info(range, Some(color)) <-
   279                 snapshot.select_markup(line_range)(Isabelle_Markup.background2).iterator
   280               r <- Isabelle.gfx_range(text_area, range)
   281             } {
   282               gfx.setColor(color)
   283               gfx.fillRect(r.x + 2, y + i * line_height + 2, r.length - 4, line_height - 4)
   284             }
   285 
   286             // sub-expression highlighting -- potentially from other snapshot
   287             highlight_range match {
   288               case Some((range, color)) if line_range.overlaps(range) =>
   289                 Isabelle.gfx_range(text_area, line_range.restrict(range)) match {
   290                   case None =>
   291                   case Some(r) =>
   292                     gfx.setColor(color)
   293                     gfx.drawRect(r.x, y + i * line_height, r.length - 1, line_height - 1)
   294                 }
   295               case _ =>
   296             }
   297 
   298             // squiggly underline
   299             for {
   300               Text.Info(range, Some(color)) <-
   301                 snapshot.select_markup(line_range)(Isabelle_Markup.message).iterator
   302               r <- Isabelle.gfx_range(text_area, range)
   303             } {
   304               gfx.setColor(color)
   305               val x0 = (r.x / 2) * 2
   306               val y0 = r.y + ascent + 1
   307               for (x1 <- Range(x0, x0 + r.length, 2)) {
   308                 val y1 = if (x1 % 4 < 2) y0 else y0 + 1
   309                 gfx.drawLine(x1, y1, x1 + 1, y1)
   310               }
   311             }
   312           }
   313         }
   314       }
   315     }
   316 
   317     override def getToolTipText(x: Int, y: Int): String =
   318     {
   319       Isabelle.swing_buffer_lock(model.buffer) {
   320         val snapshot = model.snapshot()
   321         val offset = text_area.xyToOffset(x, y)
   322         if (control) {
   323           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   324           {
   325             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   326             case _ => null
   327           }
   328         }
   329         else {
   330           // FIXME snapshot.cumulate
   331           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   332           {
   333             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   334             case _ => null
   335           }
   336         }
   337       }
   338     }
   339   }
   340 
   341   val text_painter = new Text_Painter(this)
   342 
   343 
   344   /* Gutter painting */
   345 
   346   private val gutter_painter = new TextAreaExtension
   347   {
   348     override def paintScreenLineRange(gfx: Graphics2D,
   349       first_line: Int, last_line: Int, physical_lines: Array[Int],
   350       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   351     {
   352       val gutter = text_area.getGutter
   353       val width = GutterOptionPane.getSelectionAreaWidth
   354       val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   355       val FOLD_MARKER_SIZE = 12
   356 
   357       if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   358         Isabelle.swing_buffer_lock(model.buffer) {
   359           val snapshot = model.snapshot()
   360           for (i <- 0 until physical_lines.length) {
   361             if (physical_lines(i) != -1) {
   362               val line_range = proper_line_range(start(i), end(i))
   363 
   364               // gutter icons
   365               val icons =
   366                 (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   367                   snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   368                 yield icon).toList.sortWith(_ >= _)
   369               icons match {
   370                 case icon :: _ =>
   371                   val icn = icon.icon
   372                   val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   373                   val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   374                   icn.paintIcon(gutter, gfx, x0, y0)
   375                 case Nil =>
   376               }
   377             }
   378           }
   379         }
   380       }
   381     }
   382   }
   383 
   384 
   385   /* caret handling */
   386 
   387   def selected_command(): Option[Command] =
   388   {
   389     Swing_Thread.require()
   390     model.snapshot().node.proper_command_at(text_area.getCaretPosition)
   391   }
   392 
   393   private val caret_listener = new CaretListener {
   394     private val delay = Swing_Thread.delay_last(session.input_delay) {
   395       session.perspective.event(Session.Perspective)
   396     }
   397     override def caretUpdate(e: CaretEvent) { delay() }
   398   }
   399 
   400 
   401   /* overview of command status left of scrollbar */
   402 
   403   private val overview = new JPanel(new BorderLayout)
   404   {
   405     private val WIDTH = 10
   406     private val HEIGHT = 2
   407 
   408     setPreferredSize(new Dimension(WIDTH, 0))
   409 
   410     setRequestFocusEnabled(false)
   411 
   412     addMouseListener(new MouseAdapter {
   413       override def mousePressed(event: MouseEvent) {
   414         val line = y_to_line(event.getY)
   415         if (line >= 0 && line < text_area.getLineCount)
   416           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   417       }
   418     })
   419 
   420     override def addNotify() {
   421       super.addNotify()
   422       ToolTipManager.sharedInstance.registerComponent(this)
   423     }
   424 
   425     override def removeNotify() {
   426       ToolTipManager.sharedInstance.unregisterComponent(this)
   427       super.removeNotify
   428     }
   429 
   430     override def paintComponent(gfx: Graphics)
   431     {
   432       super.paintComponent(gfx)
   433       Swing_Thread.assert()
   434 
   435       val buffer = model.buffer
   436       Isabelle.buffer_lock(buffer) {
   437         val snapshot = model.snapshot()
   438 
   439         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   440         {
   441           try {
   442             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   443             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   444             Some((line1, line2))
   445           }
   446           catch { case e: ArrayIndexOutOfBoundsException => None }
   447         }
   448         for {
   449           (command, start) <- snapshot.node.command_starts
   450           if !command.is_ignored
   451           (line1, line2) <- line_range(command, start)
   452           val y = line_to_y(line1)
   453           val height = HEIGHT * (line2 - line1)
   454           color <- Isabelle_Markup.overview_color(snapshot, command)
   455         } {
   456           gfx.setColor(color)
   457           gfx.fillRect(0, y, getWidth - 1, height)
   458         }
   459       }
   460     }
   461 
   462     private def line_to_y(line: Int): Int =
   463       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   464 
   465     private def y_to_line(y: Int): Int =
   466       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   467   }
   468 
   469 
   470   /* main actor */
   471 
   472   private val main_actor = actor {
   473     loop {
   474       react {
   475         case Session.Commands_Changed(changed) =>
   476           val buffer = model.buffer
   477           Isabelle.swing_buffer_lock(buffer) {
   478             val snapshot = model.snapshot()
   479 
   480             if (changed.exists(snapshot.node.commands.contains))
   481               overview.repaint()
   482 
   483             val visible_range = screen_lines_range()
   484             val visible_cmds = snapshot.node.command_range(snapshot.revert(visible_range)).map(_._1)
   485             if (visible_cmds.exists(changed)) {
   486               for {
   487                 line <- 0 until text_area.getVisibleLines
   488                 val start = text_area.getScreenLineStartOffset(line) if start >= 0
   489                 val end = text_area.getScreenLineEndOffset(line) if end >= 0
   490                 val range = proper_line_range(start, end)
   491                 val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   492                 if line_cmds.exists(changed)
   493               } text_area.invalidateScreenLineRange(line, line)
   494 
   495               // FIXME danger of deadlock!?
   496               // FIXME potentially slow!?
   497               model.buffer.propertiesChanged()
   498             }
   499           }
   500 
   501         case Session.Global_Settings => html_panel_resize()
   502 
   503         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   504       }
   505     }
   506   }
   507 
   508 
   509   /* activation */
   510 
   511   private def activate()
   512   {
   513     val painter = text_area.getPainter
   514 
   515     painter.addExtension(TextAreaPainter.LOWEST_LAYER, set_snapshot)
   516     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, background_painter)
   517     text_painter.activate()
   518     painter.addExtension(TextAreaPainter.HIGHEST_LAYER, reset_snapshot)
   519 
   520     text_area.getGutter.addExtension(gutter_painter)
   521     text_area.addFocusListener(focus_listener)
   522     text_area.getView.addWindowListener(window_listener)
   523     painter.addMouseMotionListener(mouse_motion_listener)
   524     text_area.addCaretListener(caret_listener)
   525     text_area.addLeftOfScrollBar(overview)
   526     session.commands_changed += main_actor
   527     session.global_settings += main_actor
   528   }
   529 
   530   private def deactivate()
   531   {
   532     val painter = text_area.getPainter
   533 
   534     session.commands_changed -= main_actor
   535     session.global_settings -= main_actor
   536     text_area.removeFocusListener(focus_listener)
   537     text_area.getView.removeWindowListener(window_listener)
   538     painter.removeMouseMotionListener(mouse_motion_listener)
   539     text_area.removeCaretListener(caret_listener)
   540     text_area.removeLeftOfScrollBar(overview)
   541     text_area.getGutter.removeExtension(gutter_painter)
   542 
   543     painter.removeExtension(reset_snapshot)
   544     text_painter.deactivate()
   545     painter.removeExtension(background_painter)
   546     painter.removeExtension(set_snapshot)
   547     exit_popup()
   548   }
   549 }