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