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