src/Tools/jEdit/src/jedit_lib.scala
author wenzelm
Tue Feb 18 15:38:50 2014 +0100 (2014-02-18)
changeset 55549 5c40782f68b3
parent 53786 064cb0458071
child 55690 d73949233c2e
permissions -rw-r--r--
clarified special eol treatment (amending 3d55ef732cd7): allow last line to be empty, which means stop == end for second-last line;
     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 Text.Range(offset, offset + 1)
   176       }
   177       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(offset, offset + 1) }
   178     }
   179 
   180 
   181   /* visible text range */
   182 
   183   def visible_range(text_area: TextArea): Option[Text.Range] =
   184   {
   185     val buffer = text_area.getBuffer
   186     val n = text_area.getVisibleLines
   187     if (n > 0) {
   188       val start = text_area.getScreenLineStartOffset(0)
   189       val raw_end = text_area.getScreenLineEndOffset(n - 1)
   190       val end = if (raw_end >= 0) raw_end min buffer.getLength else buffer.getLength
   191       Some(Text.Range(start, end))
   192     }
   193     else None
   194   }
   195 
   196   def invalidate_range(text_area: TextArea, range: Text.Range)
   197   {
   198     val buffer = text_area.getBuffer
   199     text_area.invalidateLineRange(
   200       buffer.getLineOfOffset(range.start),
   201       buffer.getLineOfOffset(range.stop))
   202   }
   203 
   204 
   205   /* graphics range */
   206 
   207   case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   208 
   209   // NB: jEdit always normalizes \r\n and \r to \n
   210   // NB: last line lacks \n
   211   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   212   {
   213     val metric = pretty_metric(text_area.getPainter)
   214     val char_width = (metric.unit * metric.average).round.toInt
   215 
   216     val buffer = text_area.getBuffer
   217 
   218     val end = buffer.getLength
   219     val stop = range.stop
   220 
   221     val (p, q, r) =
   222       try {
   223         val p = text_area.offsetToXY(range.start)
   224         val (q, r) =
   225           if (try_get_text(buffer, Text.Range(stop - 1, stop)) == Some("\n"))
   226             (text_area.offsetToXY(stop - 1), char_width)
   227           else if (stop >= end)
   228             (text_area.offsetToXY(end), char_width * (stop - end))
   229           else (text_area.offsetToXY(stop), 0)
   230         (p, q, r)
   231       }
   232       catch { case _: ArrayIndexOutOfBoundsException => (null, null, 0) }
   233 
   234     if (p != null && q != null && p.x < q.x + r && p.y == q.y)
   235       Some(Gfx_Range(p.x, p.y, q.x + r - p.x))
   236     else None
   237   }
   238 
   239 
   240   /* pixel range */
   241 
   242   def pixel_range(text_area: TextArea, x: Int, y: Int): Option[Text.Range] =
   243   {
   244     // coordinates wrt. inner painter component
   245     val painter = text_area.getPainter
   246     if (0 <= x && x < painter.getWidth && 0 <= y && y < painter.getHeight) {
   247       val offset = text_area.xyToOffset(x, y, false)
   248       if (offset >= 0) {
   249         val range = point_range(text_area.getBuffer, offset)
   250         gfx_range(text_area, range) match {
   251           case Some(g) if (g.x <= x && x < g.x + g.length) => Some(range)
   252           case _ => None
   253         }
   254       }
   255       else None
   256     }
   257     else None
   258   }
   259 
   260 
   261   /* pretty text metric */
   262 
   263   abstract class Pretty_Metric extends Pretty.Metric
   264   {
   265     def average: Double
   266   }
   267 
   268   def pretty_metric(painter: TextAreaPainter): Pretty_Metric =
   269     new Pretty_Metric {
   270       def string_width(s: String): Double =
   271         painter.getFont.getStringBounds(s, painter.getFontRenderContext).getWidth
   272 
   273       val unit = string_width(Pretty.space)
   274       val average = string_width("mix") / (3 * unit)
   275       def apply(s: String): Double = if (s == "\n") 1.0 else string_width(s) / unit
   276     }
   277 
   278 
   279   /* icons */
   280 
   281   def load_icon(name: String): Icon =
   282   {
   283     val name1 =
   284       if (name.startsWith("idea-icons/")) {
   285         val file =
   286           Isabelle_System.platform_file_url(Path.explode("$JEDIT_HOME/dist/jars/idea-icons.jar"))
   287         "jar:" + file + "!/" + name
   288       }
   289       else name
   290     val icon = GUIUtilities.loadIcon(name1)
   291     if (icon.getIconWidth < 0 || icon.getIconHeight < 0) error("Bad icon: " + name)
   292     else icon
   293   }
   294 
   295   def load_image_icon(name: String): ImageIcon =
   296     load_icon(name) match {
   297       case icon: ImageIcon => icon
   298       case _ => error("Bad image icon: " + name)
   299     }
   300 
   301 
   302   /* key event handling */
   303 
   304   def request_focus_view
   305   {
   306     val view = jEdit.getActiveView()
   307     if (view != null) {
   308       val text_area = view.getTextArea
   309       if (text_area != null) text_area.requestFocus
   310     }
   311   }
   312 
   313   def propagate_key(view: View, evt: KeyEvent)
   314   {
   315     if (view != null && !evt.isConsumed)
   316       view.getInputHandler().processKeyEvent(evt, View.ACTION_BAR, false)
   317   }
   318 
   319   def key_listener(
   320     key_typed: KeyEvent => Unit = _ => (),
   321     key_pressed: KeyEvent => Unit = _ => (),
   322     key_released: KeyEvent => Unit = _ => ()): KeyListener =
   323   {
   324     def process_key_event(evt0: KeyEvent, handle: KeyEvent => Unit)
   325     {
   326       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   327       if (evt != null) handle(evt)
   328     }
   329 
   330     new KeyListener
   331     {
   332       def keyTyped(evt: KeyEvent) { process_key_event(evt, key_typed) }
   333       def keyPressed(evt: KeyEvent) { process_key_event(evt, key_pressed) }
   334       def keyReleased(evt: KeyEvent) { process_key_event(evt, key_released) }
   335     }
   336   }
   337 
   338   def special_key(evt: KeyEvent): Boolean =
   339   {
   340     // cf. 5.1.0/jEdit/org/gjt/sp/jedit/gui/KeyEventWorkaround.java
   341     val mod = evt.getModifiers
   342     (mod & InputEvent.CTRL_MASK) != 0 && (mod & InputEvent.ALT_MASK) == 0 ||
   343     (mod & InputEvent.CTRL_MASK) == 0 && (mod & InputEvent.ALT_MASK) != 0 &&
   344       !Debug.ALT_KEY_PRESSED_DISABLED ||
   345     (mod & InputEvent.META_MASK) != 0
   346   }
   347 }
   348