src/Tools/jEdit/src/jedit_lib.scala
author wenzelm
Mon Jan 09 20:26:59 2017 +0100 (2017-01-09)
changeset 64854 f5aa712e6250
parent 64824 330ec9bc4b75
child 65469 78ace4a14975
permissions -rw-r--r--
tuned signature;
     1 /*  Title:      Tools/jEdit/src/jedit_lib.scala
     2     Author:     Makarius
     3 
     4 Misc library functions for jEdit.
     5 */
     6 
     7 package isabelle.jedit
     8 
     9 
    10 import isabelle._
    11 
    12 import java.awt.{Component, Container, GraphicsEnvironment, Point, Rectangle, Dimension}
    13 import java.awt.event.{InputEvent, KeyEvent, KeyListener}
    14 import javax.swing.{Icon, ImageIcon, JWindow, SwingUtilities}
    15 
    16 import scala.util.parsing.input.CharSequenceReader
    17 
    18 import org.gjt.sp.jedit.{jEdit, Buffer, View, GUIUtilities, Debug, EditPane}
    19 import org.gjt.sp.jedit.gui.KeyEventWorkaround
    20 import org.gjt.sp.jedit.buffer.{JEditBuffer, LineManager}
    21 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea, TextAreaPainter}
    22 import org.gjt.sp.jedit.syntax.TokenMarker
    23 
    24 
    25 object JEdit_Lib
    26 {
    27   /* location within multi-screen environment */
    28 
    29   final case class Screen_Location(point: Point, bounds: Rectangle)
    30   {
    31     def relative(parent: Component, size: Dimension): Point =
    32     {
    33       val w = size.width
    34       val h = size.height
    35 
    36       val x0 = parent.getLocationOnScreen.x
    37       val y0 = parent.getLocationOnScreen.y
    38       val x1 = x0 + parent.getWidth - w
    39       val y1 = y0 + parent.getHeight - h
    40       val x2 = point.x min (bounds.x + bounds.width - w)
    41       val y2 = point.y min (bounds.y + bounds.height - h)
    42 
    43       val location = new Point((x2 min x1) max x0, (y2 min y1) max y0)
    44       SwingUtilities.convertPointFromScreen(location, parent)
    45       location
    46     }
    47   }
    48 
    49   def screen_location(component: Component, point: Point): Screen_Location =
    50   {
    51     val screen_point = new Point(point.x, point.y)
    52     SwingUtilities.convertPointToScreen(screen_point, component)
    53 
    54     val ge = GraphicsEnvironment.getLocalGraphicsEnvironment
    55     val screen_bounds =
    56       (for {
    57         device <- ge.getScreenDevices.iterator
    58         config <- device.getConfigurations.iterator
    59         bounds = config.getBounds
    60       } yield bounds).find(_.contains(screen_point)) getOrElse ge.getMaximumWindowBounds
    61 
    62     Screen_Location(screen_point, screen_bounds)
    63   }
    64 
    65 
    66   /* window geometry measurement */
    67 
    68   private lazy val dummy_window = new JWindow
    69 
    70   final case class Window_Geometry(width: Int, height: Int, inner_width: Int, inner_height: Int)
    71   {
    72     def deco_width: Int = width - inner_width
    73     def deco_height: Int = height - inner_height
    74   }
    75 
    76   def window_geometry(outer: Container, inner: Component): Window_Geometry =
    77   {
    78     GUI_Thread.require {}
    79 
    80     val old_content = dummy_window.getContentPane
    81 
    82     dummy_window.setContentPane(outer)
    83     dummy_window.pack
    84     dummy_window.revalidate
    85 
    86     val geometry =
    87       Window_Geometry(
    88         dummy_window.getWidth, dummy_window.getHeight, inner.getWidth, inner.getHeight)
    89 
    90     dummy_window.setContentPane(old_content)
    91 
    92     geometry
    93   }
    94 
    95 
    96   /* buffers */
    97 
    98   def buffer_text(buffer: JEditBuffer): String =
    99     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   100 
   101   def buffer_reader(buffer: JEditBuffer): CharSequenceReader =
   102     Scan.char_reader(buffer.getSegment(0, buffer.getLength))
   103 
   104   def buffer_mode(buffer: JEditBuffer): String =
   105   {
   106     val mode = buffer.getMode
   107     if (mode == null) ""
   108     else {
   109       val name = mode.getName
   110       if (name == null) "" else name
   111     }
   112   }
   113 
   114   def buffer_name(buffer: Buffer): String = buffer.getSymlinkPath
   115 
   116   def buffer_line_manager(buffer: JEditBuffer): LineManager =
   117     Untyped.get[LineManager](buffer, "lineMgr")
   118 
   119 
   120   /* main jEdit components */
   121 
   122   def jedit_buffers(): Iterator[Buffer] = jEdit.getBuffers().iterator
   123 
   124   def jedit_buffer(name: String): Option[Buffer] =
   125     jedit_buffers().find(buffer => buffer_name(buffer) == name)
   126 
   127   def jedit_buffer(name: Document.Node.Name): Option[Buffer] =
   128     jedit_buffer(name.node)
   129 
   130   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   131 
   132   def jedit_edit_panes(view: View): Iterator[EditPane] =
   133     if (view == null) Iterator.empty
   134     else view.getEditPanes().iterator.filter(_ != null)
   135 
   136   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   137     if (view == null) Iterator.empty
   138     else view.getEditPanes().iterator.filter(_ != null).map(_.getTextArea).filter(_ != null)
   139 
   140   def jedit_text_areas(): Iterator[JEditTextArea] =
   141     jedit_views().flatMap(jedit_text_areas(_))
   142 
   143   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   144     jedit_text_areas().filter(_.getBuffer == buffer)
   145 
   146   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   147   {
   148     try { buffer.readLock(); body }
   149     finally { buffer.readUnlock() }
   150   }
   151 
   152   def buffer_edit[A](buffer: JEditBuffer)(body: => A): A =
   153   {
   154     try { buffer.beginCompoundEdit(); body }
   155     finally { buffer.endCompoundEdit() }
   156   }
   157 
   158 
   159   /* get text */
   160 
   161   def try_get_text(buffer: JEditBuffer, range: Text.Range): Option[String] =
   162     try { Some(buffer.getText(range.start, range.length)) }
   163     catch { case _: ArrayIndexOutOfBoundsException => None }
   164 
   165   def try_get_text(text: String, range: Text.Range): Option[String] =
   166     try { Some(text.substring(range.start, range.stop)) }
   167     catch { case _: IndexOutOfBoundsException => None }
   168 
   169 
   170   /* point range */
   171 
   172   def point_range(buffer: JEditBuffer, offset: Text.Offset): Text.Range =
   173     if (offset < 0) Text.Range.offside
   174     else
   175       buffer_lock(buffer) {
   176         def text(i: Text.Offset): Char = buffer.getText(i, 1).charAt(0)
   177         try {
   178           val c = text(offset)
   179           if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(offset + 1)))
   180             Text.Range(offset, offset + 2)
   181           else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(offset - 1)))
   182             Text.Range(offset - 1, offset + 1)
   183           else
   184             Text.Range(offset, offset + 1)
   185         }
   186         catch { case _: ArrayIndexOutOfBoundsException => Text.Range(offset, offset + 1) }
   187       }
   188 
   189 
   190   /* text ranges */
   191 
   192   def buffer_range(buffer: JEditBuffer): Text.Range =
   193     Text.Range(0, buffer.getLength)
   194 
   195   def line_range(buffer: JEditBuffer, line: Int): Text.Range =
   196     Text.Range(buffer.getLineStartOffset(line), buffer.getLineEndOffset(line) min buffer.getLength)
   197 
   198   def caret_range(text_area: TextArea): Text.Range =
   199     point_range(text_area.getBuffer, text_area.getCaretPosition)
   200 
   201   def before_caret_range(text_area: TextArea, rendering: JEdit_Rendering): Text.Range =
   202   {
   203     val snapshot = rendering.snapshot
   204     val former_caret = snapshot.revert(text_area.getCaretPosition)
   205     snapshot.convert(Text.Range(former_caret - 1, former_caret))
   206   }
   207 
   208   def visible_range(text_area: TextArea): Option[Text.Range] =
   209   {
   210     val buffer = text_area.getBuffer
   211     val n = text_area.getVisibleLines
   212     if (n > 0) {
   213       val start = text_area.getScreenLineStartOffset(0)
   214       val raw_end = text_area.getScreenLineEndOffset(n - 1)
   215       val end = if (raw_end >= 0) raw_end min buffer.getLength else buffer.getLength
   216       Some(Text.Range(start, end))
   217     }
   218     else None
   219   }
   220 
   221   def invalidate_range(text_area: TextArea, range: Text.Range)
   222   {
   223     val buffer = text_area.getBuffer
   224     buffer_range(buffer).try_restrict(range) match {
   225       case Some(range1) if !range1.is_singularity =>
   226         try {
   227           text_area.invalidateLineRange(
   228             buffer.getLineOfOffset(range1.start),
   229             buffer.getLineOfOffset(range1.stop))
   230         }
   231         catch { case _: ArrayIndexOutOfBoundsException => }
   232       case _ =>
   233     }
   234   }
   235 
   236   def invalidate(text_area: TextArea)
   237   {
   238     val visible_lines = text_area.getVisibleLines
   239     if (visible_lines > 0) text_area.invalidateScreenLineRange(0, visible_lines)
   240   }
   241 
   242 
   243   /* graphics range */
   244 
   245   case class Gfx_Range(x: Int, y: Int, length: Int)
   246 
   247   // NB: jEdit always normalizes \r\n and \r to \n
   248   // NB: last line lacks \n
   249   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   250   {
   251     val metric = pretty_metric(text_area.getPainter)
   252     val char_width = (metric.unit * metric.average).round.toInt
   253 
   254     val buffer = text_area.getBuffer
   255 
   256     val end = buffer.getLength
   257     val stop = range.stop
   258 
   259     val (p, q, r) =
   260       try {
   261         val p = text_area.offsetToXY(range.start)
   262         val (q, r) =
   263           if (try_get_text(buffer, Text.Range(stop - 1, stop)) == Some("\n"))
   264             (text_area.offsetToXY(stop - 1), char_width)
   265           else if (stop >= end)
   266             (text_area.offsetToXY(end), char_width * (stop - end))
   267           else (text_area.offsetToXY(stop), 0)
   268         (p, q, r)
   269       }
   270       catch { case _: ArrayIndexOutOfBoundsException => (null, null, 0) }
   271 
   272     if (p != null && q != null && p.x < q.x + r && p.y == q.y)
   273       Some(Gfx_Range(p.x, p.y, q.x + r - p.x))
   274     else None
   275   }
   276 
   277 
   278   /* pixel range */
   279 
   280   def pixel_range(text_area: TextArea, x: Int, y: Int): Option[Text.Range] =
   281   {
   282     // coordinates wrt. inner painter component
   283     val painter = text_area.getPainter
   284     if (0 <= x && x < painter.getWidth && 0 <= y && y < painter.getHeight) {
   285       val offset = text_area.xyToOffset(x, y, false)
   286       if (offset >= 0) {
   287         val range = point_range(text_area.getBuffer, offset)
   288         gfx_range(text_area, range) match {
   289           case Some(g) if g.x <= x && x < g.x + g.length => Some(range)
   290           case _ => None
   291         }
   292       }
   293       else None
   294     }
   295     else None
   296   }
   297 
   298 
   299   /* pretty text metric */
   300 
   301   abstract class Pretty_Metric extends Pretty.Metric
   302   {
   303     def average: Double
   304   }
   305 
   306   def pretty_metric(painter: TextAreaPainter): Pretty_Metric =
   307     new Pretty_Metric {
   308       def string_width(s: String): Double =
   309         painter.getFont.getStringBounds(s, painter.getFontRenderContext).getWidth
   310 
   311       val unit = string_width(Symbol.space) max 1.0
   312       val average = string_width("mix") / (3 * unit)
   313       def apply(s: String): Double = if (s == "\n") 1.0 else string_width(s) / unit
   314     }
   315 
   316 
   317   /* icons */
   318 
   319   def load_icon(name: String): Icon =
   320   {
   321     val name1 =
   322       if (name.startsWith("idea-icons/")) {
   323         val file = Path.explode("$JEDIT_HOME/dist/jars/idea-icons.jar").file.toURI.toASCIIString
   324         "jar:" + file + "!/" + name
   325       }
   326       else name
   327     val icon = GUIUtilities.loadIcon(name1)
   328     if (icon.getIconWidth < 0 || icon.getIconHeight < 0) error("Bad icon: " + name)
   329     else icon
   330   }
   331 
   332   def load_image_icon(name: String): ImageIcon =
   333     load_icon(name) match {
   334       case icon: ImageIcon => icon
   335       case _ => error("Bad image icon: " + name)
   336     }
   337 
   338 
   339   /* key event handling */
   340 
   341   def request_focus_view(alt_view: View = null)
   342   {
   343     val view = if (alt_view != null) alt_view else jEdit.getActiveView()
   344     if (view != null) {
   345       val text_area = view.getTextArea
   346       if (text_area != null) text_area.requestFocus
   347     }
   348   }
   349 
   350   def propagate_key(view: View, evt: KeyEvent)
   351   {
   352     if (view != null && !evt.isConsumed)
   353       view.getInputHandler().processKeyEvent(evt, View.ACTION_BAR, false)
   354   }
   355 
   356   def key_listener(
   357     key_typed: KeyEvent => Unit = _ => (),
   358     key_pressed: KeyEvent => Unit = _ => (),
   359     key_released: KeyEvent => Unit = _ => ()): KeyListener =
   360   {
   361     def process_key_event(evt0: KeyEvent, handle: KeyEvent => Unit)
   362     {
   363       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   364       if (evt != null) handle(evt)
   365     }
   366 
   367     new KeyListener
   368     {
   369       def keyTyped(evt: KeyEvent) { process_key_event(evt, key_typed) }
   370       def keyPressed(evt: KeyEvent) { process_key_event(evt, key_pressed) }
   371       def keyReleased(evt: KeyEvent) { process_key_event(evt, key_released) }
   372     }
   373   }
   374 
   375   def special_key(evt: KeyEvent): Boolean =
   376   {
   377     // cf. 5.2.0/jEdit/org/gjt/sp/jedit/gui/KeyEventWorkaround.java
   378     val mod = evt.getModifiers
   379     (mod & InputEvent.CTRL_MASK) != 0 && (mod & InputEvent.ALT_MASK) == 0 ||
   380     (mod & InputEvent.CTRL_MASK) == 0 && (mod & InputEvent.ALT_MASK) != 0 &&
   381       !Debug.ALT_KEY_PRESSED_DISABLED ||
   382     (mod & InputEvent.META_MASK) != 0
   383   }
   384 }