src/Tools/jEdit/src/document_view.scala
author wenzelm
Sun Jun 12 20:08:49 2011 +0200 (2011-06-12 ago)
changeset 43369 4c86b3405010
parent 43282 5d294220ca43
child 43376 0f6880c1c759
permissions -rw-r--r--
separate isabelle.jedit.Text_Painter, which actually replaces the original TextAreaPainter$PaintText instance;
     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, 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 painters */
   211 
   212   private val background_painter = new TextAreaExtension
   213   {
   214     override def paintScreenLineRange(gfx: Graphics2D,
   215       first_line: Int, last_line: Int, physical_lines: Array[Int],
   216       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   217     {
   218       Isabelle.swing_buffer_lock(model.buffer) {
   219         val snapshot = model.snapshot()
   220         val ascent = text_area.getPainter.getFontMetrics.getAscent
   221 
   222         for (i <- 0 until physical_lines.length) {
   223           if (physical_lines(i) != -1) {
   224             val line_range = proper_line_range(start(i), end(i))
   225 
   226             // background color: status
   227             val cmds = snapshot.node.command_range(snapshot.revert(line_range))
   228             for {
   229               (command, command_start) <- cmds if !command.is_ignored
   230               val range = line_range.restrict(snapshot.convert(command.range + command_start))
   231               r <- Isabelle.gfx_range(text_area, range)
   232               color <- Isabelle_Markup.status_color(snapshot, command)
   233             } {
   234               gfx.setColor(color)
   235               gfx.fillRect(r.x, y + i * line_height, r.length, line_height)
   236             }
   237 
   238             // background color (1): markup
   239             for {
   240               Text.Info(range, Some(color)) <-
   241                 snapshot.select_markup(line_range)(Isabelle_Markup.background1).iterator
   242               r <- Isabelle.gfx_range(text_area, range)
   243             } {
   244               gfx.setColor(color)
   245               gfx.fillRect(r.x, y + i * line_height, r.length, line_height)
   246             }
   247 
   248             // background color (2): markup
   249             for {
   250               Text.Info(range, Some(color)) <-
   251                 snapshot.select_markup(line_range)(Isabelle_Markup.background2).iterator
   252               r <- Isabelle.gfx_range(text_area, range)
   253             } {
   254               gfx.setColor(color)
   255               gfx.fillRect(r.x + 2, y + i * line_height + 2, r.length - 4, line_height - 4)
   256             }
   257 
   258             // sub-expression highlighting -- potentially from other snapshot
   259             highlight_range match {
   260               case Some((range, color)) if line_range.overlaps(range) =>
   261                 Isabelle.gfx_range(text_area, line_range.restrict(range)) match {
   262                   case None =>
   263                   case Some(r) =>
   264                     gfx.setColor(color)
   265                     gfx.drawRect(r.x, y + i * line_height, r.length - 1, line_height - 1)
   266                 }
   267               case _ =>
   268             }
   269 
   270             // squiggly underline
   271             for {
   272               Text.Info(range, Some(color)) <-
   273                 snapshot.select_markup(line_range)(Isabelle_Markup.message).iterator
   274               r <- Isabelle.gfx_range(text_area, range)
   275             } {
   276               gfx.setColor(color)
   277               val x0 = (r.x / 2) * 2
   278               val y0 = r.y + ascent + 1
   279               for (x1 <- Range(x0, x0 + r.length, 2)) {
   280                 val y1 = if (x1 % 4 < 2) y0 else y0 + 1
   281                 gfx.drawLine(x1, y1, x1 + 1, y1)
   282               }
   283             }
   284           }
   285         }
   286       }
   287     }
   288 
   289     override def getToolTipText(x: Int, y: Int): String =
   290     {
   291       Isabelle.swing_buffer_lock(model.buffer) {
   292         val snapshot = model.snapshot()
   293         val offset = text_area.xyToOffset(x, y)
   294         if (control) {
   295           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.tooltip) match
   296           {
   297             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   298             case _ => null
   299           }
   300         }
   301         else {
   302           // FIXME snapshot.cumulate
   303           snapshot.select_markup(Text.Range(offset, offset + 1))(Isabelle_Markup.popup) match
   304           {
   305             case Text.Info(_, Some(text)) #:: _ => Isabelle.tooltip(text)
   306             case _ => null
   307           }
   308         }
   309       }
   310     }
   311   }
   312 
   313   val text_painter = new Text_Painter(model, text_area)
   314 
   315   private val gutter_painter = new TextAreaExtension
   316   {
   317     override def paintScreenLineRange(gfx: Graphics2D,
   318       first_line: Int, last_line: Int, physical_lines: Array[Int],
   319       start: Array[Int], end: Array[Int], y: Int, line_height: Int)
   320     {
   321       val gutter = text_area.getGutter
   322       val width = GutterOptionPane.getSelectionAreaWidth
   323       val border_width = jEdit.getIntegerProperty("view.gutter.borderWidth", 3)
   324       val FOLD_MARKER_SIZE = 12
   325 
   326       if (gutter.isSelectionAreaEnabled && !gutter.isExpanded && width >= 12 && line_height >= 12) {
   327         Isabelle.swing_buffer_lock(model.buffer) {
   328           val snapshot = model.snapshot()
   329           for (i <- 0 until physical_lines.length) {
   330             if (physical_lines(i) != -1) {
   331               val line_range = proper_line_range(start(i), end(i))
   332 
   333               // gutter icons
   334               val icons =
   335                 (for (Text.Info(_, Some(icon)) <- // FIXME snapshot.cumulate
   336                   snapshot.select_markup(line_range)(Isabelle_Markup.gutter_message).iterator)
   337                 yield icon).toList.sortWith(_ >= _)
   338               icons match {
   339                 case icon :: _ =>
   340                   val icn = icon.icon
   341                   val x0 = (FOLD_MARKER_SIZE + width - border_width - icn.getIconWidth) max 10
   342                   val y0 = y + i * line_height + (((line_height - icn.getIconHeight) / 2) max 0)
   343                   icn.paintIcon(gutter, gfx, x0, y0)
   344                 case Nil =>
   345               }
   346             }
   347           }
   348         }
   349       }
   350     }
   351   }
   352 
   353 
   354   /* caret handling */
   355 
   356   def selected_command(): Option[Command] =
   357   {
   358     Swing_Thread.require()
   359     model.snapshot().node.proper_command_at(text_area.getCaretPosition)
   360   }
   361 
   362   private val caret_listener = new CaretListener {
   363     private val delay = Swing_Thread.delay_last(session.input_delay) {
   364       session.perspective.event(Session.Perspective)
   365     }
   366     override def caretUpdate(e: CaretEvent) { delay() }
   367   }
   368 
   369 
   370   /* overview of command status left of scrollbar */
   371 
   372   private val overview = new JPanel(new BorderLayout)
   373   {
   374     private val WIDTH = 10
   375     private val HEIGHT = 2
   376 
   377     setPreferredSize(new Dimension(WIDTH, 0))
   378 
   379     setRequestFocusEnabled(false)
   380 
   381     addMouseListener(new MouseAdapter {
   382       override def mousePressed(event: MouseEvent) {
   383         val line = y_to_line(event.getY)
   384         if (line >= 0 && line < text_area.getLineCount)
   385           text_area.setCaretPosition(text_area.getLineStartOffset(line))
   386       }
   387     })
   388 
   389     override def addNotify() {
   390       super.addNotify()
   391       ToolTipManager.sharedInstance.registerComponent(this)
   392     }
   393 
   394     override def removeNotify() {
   395       ToolTipManager.sharedInstance.unregisterComponent(this)
   396       super.removeNotify
   397     }
   398 
   399     override def paintComponent(gfx: Graphics)
   400     {
   401       super.paintComponent(gfx)
   402       Swing_Thread.assert()
   403 
   404       val buffer = model.buffer
   405       Isabelle.buffer_lock(buffer) {
   406         val snapshot = model.snapshot()
   407 
   408         def line_range(command: Command, start: Text.Offset): Option[(Int, Int)] =
   409         {
   410           try {
   411             val line1 = buffer.getLineOfOffset(snapshot.convert(start))
   412             val line2 = buffer.getLineOfOffset(snapshot.convert(start + command.length)) + 1
   413             Some((line1, line2))
   414           }
   415           catch { case e: ArrayIndexOutOfBoundsException => None }
   416         }
   417         for {
   418           (command, start) <- snapshot.node.command_starts
   419           if !command.is_ignored
   420           (line1, line2) <- line_range(command, start)
   421           val y = line_to_y(line1)
   422           val height = HEIGHT * (line2 - line1)
   423           color <- Isabelle_Markup.overview_color(snapshot, command)
   424         } {
   425           gfx.setColor(color)
   426           gfx.fillRect(0, y, getWidth - 1, height)
   427         }
   428       }
   429     }
   430 
   431     private def line_to_y(line: Int): Int =
   432       (line * getHeight) / (text_area.getBuffer.getLineCount max text_area.getVisibleLines)
   433 
   434     private def y_to_line(y: Int): Int =
   435       (y * (text_area.getBuffer.getLineCount max text_area.getVisibleLines)) / getHeight
   436   }
   437 
   438 
   439   /* main actor */
   440 
   441   private val main_actor = actor {
   442     loop {
   443       react {
   444         case Session.Commands_Changed(changed) =>
   445           val buffer = model.buffer
   446           Isabelle.swing_buffer_lock(buffer) {
   447             val snapshot = model.snapshot()
   448 
   449             if (changed.exists(snapshot.node.commands.contains))
   450               overview.repaint()
   451 
   452             val visible_range = screen_lines_range()
   453             val visible_cmds = snapshot.node.command_range(snapshot.revert(visible_range)).map(_._1)
   454             if (visible_cmds.exists(changed)) {
   455               for {
   456                 line <- 0 until text_area.getVisibleLines
   457                 val start = text_area.getScreenLineStartOffset(line) if start >= 0
   458                 val end = text_area.getScreenLineEndOffset(line) if end >= 0
   459                 val range = proper_line_range(start, end)
   460                 val line_cmds = snapshot.node.command_range(snapshot.revert(range)).map(_._1)
   461                 if line_cmds.exists(changed)
   462               } text_area.invalidateScreenLineRange(line, line)
   463 
   464               // FIXME danger of deadlock!?
   465               // FIXME potentially slow!?
   466               model.buffer.propertiesChanged()
   467             }
   468           }
   469 
   470         case Session.Global_Settings => html_panel_resize()
   471 
   472         case bad => System.err.println("command_change_actor: ignoring bad message " + bad)
   473       }
   474     }
   475   }
   476 
   477 
   478   /* activation */
   479 
   480   private def activate()
   481   {
   482     val painter = text_area.getPainter
   483     painter.addExtension(TextAreaPainter.LINE_BACKGROUND_LAYER + 1, background_painter)
   484     text_painter.activate()
   485     text_area.getGutter.addExtension(gutter_painter)
   486     text_area.addFocusListener(focus_listener)
   487     text_area.getView.addWindowListener(window_listener)
   488     painter.addMouseMotionListener(mouse_motion_listener)
   489     text_area.addCaretListener(caret_listener)
   490     text_area.addLeftOfScrollBar(overview)
   491     session.commands_changed += main_actor
   492     session.global_settings += main_actor
   493   }
   494 
   495   private def deactivate()
   496   {
   497     val painter = text_area.getPainter
   498     session.commands_changed -= main_actor
   499     session.global_settings -= main_actor
   500     text_area.removeFocusListener(focus_listener)
   501     text_area.getView.removeWindowListener(window_listener)
   502     painter.removeMouseMotionListener(mouse_motion_listener)
   503     text_area.removeCaretListener(caret_listener)
   504     text_area.removeLeftOfScrollBar(overview)
   505     text_area.getGutter.removeExtension(gutter_painter)
   506     text_painter.deactivate()
   507     painter.removeExtension(background_painter)
   508     exit_popup()
   509   }
   510 }