src/Tools/jEdit/src/jedit_lib.scala
author wenzelm
Mon Apr 14 21:51:41 2014 +0200 (2014-04-14)
changeset 56574 2b38472a4695
parent 56457 eea4bbe15745
child 56587 83777a91f5de
permissions -rw-r--r--
some actions to maintain spell-checker dictionary;
     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_buffer(name: Document.Node.Name): Option[Buffer] =
   124     jedit_buffer(name.node)
   125 
   126   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   127 
   128   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   129     view.getEditPanes().iterator.map(_.getTextArea)
   130 
   131   def jedit_text_areas(): Iterator[JEditTextArea] =
   132     jedit_views().flatMap(jedit_text_areas(_))
   133 
   134   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   135     jedit_text_areas().filter(_.getBuffer == buffer)
   136 
   137   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   138   {
   139     try { buffer.readLock(); body }
   140     finally { buffer.readUnlock() }
   141   }
   142 
   143   def buffer_edit[A](buffer: JEditBuffer)(body: => A): A =
   144   {
   145     try { buffer.beginCompoundEdit(); body }
   146     finally { buffer.endCompoundEdit() }
   147   }
   148 
   149 
   150   /* get text */
   151 
   152   def try_get_text(buffer: JEditBuffer, range: Text.Range): Option[String] =
   153     try { Some(buffer.getText(range.start, range.length)) }
   154     catch { case _: ArrayIndexOutOfBoundsException => None }
   155 
   156   def try_get_text(text: String, range: Text.Range): Option[String] =
   157     try { Some(text.substring(range.start, range.stop)) }
   158     catch { case _: IndexOutOfBoundsException => None }
   159 
   160 
   161   /* point range */
   162 
   163   def point_range(buffer: JEditBuffer, offset: Text.Offset): Text.Range =
   164     buffer_lock(buffer) {
   165       def text(i: Text.Offset): Char = buffer.getText(i, 1).charAt(0)
   166       try {
   167         val c = text(offset)
   168         if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(offset + 1)))
   169           Text.Range(offset, offset + 2)
   170         else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(offset - 1)))
   171           Text.Range(offset - 1, offset + 1)
   172         else
   173           Text.Range(offset, offset + 1)
   174       }
   175       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(offset, offset + 1) }
   176     }
   177 
   178 
   179   /* caret */
   180 
   181   def before_caret_range(text_area: TextArea, rendering: Rendering): Text.Range =
   182   {
   183     val snapshot = rendering.snapshot
   184     val former_caret = snapshot.revert(text_area.getCaretPosition)
   185     snapshot.convert(Text.Range(former_caret - 1, former_caret))
   186   }
   187 
   188 
   189   /* text ranges */
   190 
   191   def buffer_range(buffer: JEditBuffer): Text.Range =
   192     Text.Range(0, buffer.getLength)
   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     buffer_range(buffer).try_restrict(range) match {
   211       case Some(range1) if !range1.is_singularity =>
   212         text_area.invalidateLineRange(
   213           buffer.getLineOfOffset(range1.start),
   214           buffer.getLineOfOffset(range1.stop))
   215       case _ =>
   216     }
   217   }
   218 
   219 
   220   /* graphics range */
   221 
   222   case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   223 
   224   // NB: jEdit always normalizes \r\n and \r to \n
   225   // NB: last line lacks \n
   226   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   227   {
   228     val metric = pretty_metric(text_area.getPainter)
   229     val char_width = (metric.unit * metric.average).round.toInt
   230 
   231     val buffer = text_area.getBuffer
   232 
   233     val end = buffer.getLength
   234     val stop = range.stop
   235 
   236     val (p, q, r) =
   237       try {
   238         val p = text_area.offsetToXY(range.start)
   239         val (q, r) =
   240           if (try_get_text(buffer, Text.Range(stop - 1, stop)) == Some("\n"))
   241             (text_area.offsetToXY(stop - 1), char_width)
   242           else if (stop >= end)
   243             (text_area.offsetToXY(end), char_width * (stop - end))
   244           else (text_area.offsetToXY(stop), 0)
   245         (p, q, r)
   246       }
   247       catch { case _: ArrayIndexOutOfBoundsException => (null, null, 0) }
   248 
   249     if (p != null && q != null && p.x < q.x + r && p.y == q.y)
   250       Some(Gfx_Range(p.x, p.y, q.x + r - p.x))
   251     else None
   252   }
   253 
   254 
   255   /* pixel range */
   256 
   257   def pixel_range(text_area: TextArea, x: Int, y: Int): Option[Text.Range] =
   258   {
   259     // coordinates wrt. inner painter component
   260     val painter = text_area.getPainter
   261     if (0 <= x && x < painter.getWidth && 0 <= y && y < painter.getHeight) {
   262       val offset = text_area.xyToOffset(x, y, false)
   263       if (offset >= 0) {
   264         val range = point_range(text_area.getBuffer, offset)
   265         gfx_range(text_area, range) match {
   266           case Some(g) if (g.x <= x && x < g.x + g.length) => Some(range)
   267           case _ => None
   268         }
   269       }
   270       else None
   271     }
   272     else None
   273   }
   274 
   275 
   276   /* pretty text metric */
   277 
   278   abstract class Pretty_Metric extends Pretty.Metric
   279   {
   280     def average: Double
   281   }
   282 
   283   def pretty_metric(painter: TextAreaPainter): Pretty_Metric =
   284     new Pretty_Metric {
   285       def string_width(s: String): Double =
   286         painter.getFont.getStringBounds(s, painter.getFontRenderContext).getWidth
   287 
   288       val unit = string_width(Pretty.space)
   289       val average = string_width("mix") / (3 * unit)
   290       def apply(s: String): Double = if (s == "\n") 1.0 else string_width(s) / unit
   291     }
   292 
   293 
   294   /* icons */
   295 
   296   def load_icon(name: String): Icon =
   297   {
   298     val name1 =
   299       if (name.startsWith("idea-icons/")) {
   300         val file =
   301           Isabelle_System.platform_file_url(Path.explode("$JEDIT_HOME/dist/jars/idea-icons.jar"))
   302         "jar:" + file + "!/" + name
   303       }
   304       else name
   305     val icon = GUIUtilities.loadIcon(name1)
   306     if (icon.getIconWidth < 0 || icon.getIconHeight < 0) error("Bad icon: " + name)
   307     else icon
   308   }
   309 
   310   def load_image_icon(name: String): ImageIcon =
   311     load_icon(name) match {
   312       case icon: ImageIcon => icon
   313       case _ => error("Bad image icon: " + name)
   314     }
   315 
   316 
   317   /* key event handling */
   318 
   319   def request_focus_view
   320   {
   321     val view = jEdit.getActiveView()
   322     if (view != null) {
   323       val text_area = view.getTextArea
   324       if (text_area != null) text_area.requestFocus
   325     }
   326   }
   327 
   328   def propagate_key(view: View, evt: KeyEvent)
   329   {
   330     if (view != null && !evt.isConsumed)
   331       view.getInputHandler().processKeyEvent(evt, View.ACTION_BAR, false)
   332   }
   333 
   334   def key_listener(
   335     key_typed: KeyEvent => Unit = _ => (),
   336     key_pressed: KeyEvent => Unit = _ => (),
   337     key_released: KeyEvent => Unit = _ => ()): KeyListener =
   338   {
   339     def process_key_event(evt0: KeyEvent, handle: KeyEvent => Unit)
   340     {
   341       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   342       if (evt != null) handle(evt)
   343     }
   344 
   345     new KeyListener
   346     {
   347       def keyTyped(evt: KeyEvent) { process_key_event(evt, key_typed) }
   348       def keyPressed(evt: KeyEvent) { process_key_event(evt, key_pressed) }
   349       def keyReleased(evt: KeyEvent) { process_key_event(evt, key_released) }
   350     }
   351   }
   352 
   353   def special_key(evt: KeyEvent): Boolean =
   354   {
   355     // cf. 5.1.0/jEdit/org/gjt/sp/jedit/gui/KeyEventWorkaround.java
   356     val mod = evt.getModifiers
   357     (mod & InputEvent.CTRL_MASK) != 0 && (mod & InputEvent.ALT_MASK) == 0 ||
   358     (mod & InputEvent.CTRL_MASK) == 0 && (mod & InputEvent.ALT_MASK) != 0 &&
   359       !Debug.ALT_KEY_PRESSED_DISABLED ||
   360     (mod & InputEvent.META_MASK) != 0
   361   }
   362 }
   363