src/Tools/jEdit/src/jedit_lib.scala
author wenzelm
Sun Sep 22 18:07:34 2013 +0200 (2013-09-22)
changeset 53784 322a3ff42b33
parent 53712 ea51046be71b
child 53786 064cb0458071
permissions -rw-r--r--
completion popup for history text field;
imitate view font, for default rendering of symbols;
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.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   /* basic tooltips, with multi-line support */
    96 
    97   def wrap_tooltip(text: String): String =
    98     if (text == "") null
    99     else "<html><pre>" + HTML.encode(text) + "</pre></html>"
   100 
   101 
   102   /* buffers */
   103 
   104   def swing_buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   105     Swing_Thread.now { buffer_lock(buffer) { body } }
   106 
   107   def buffer_text(buffer: JEditBuffer): String =
   108     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   109 
   110   def buffer_mode(buffer: JEditBuffer): String =
   111   {
   112     val mode = buffer.getMode
   113     if (mode == null) ""
   114     else {
   115       val name = mode.getName
   116       if (name == null) "" else name
   117     }
   118   }
   119 
   120   def buffer_name(buffer: Buffer): String = buffer.getSymlinkPath
   121 
   122 
   123   /* main jEdit components */
   124 
   125   def jedit_buffers(): Iterator[Buffer] = jEdit.getBuffers().iterator
   126 
   127   def jedit_buffer(name: String): Option[Buffer] =
   128     jedit_buffers().find(buffer => buffer_name(buffer) == name)
   129 
   130   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   131 
   132   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   133     view.getEditPanes().iterator.map(_.getTextArea)
   134 
   135   def jedit_text_areas(): Iterator[JEditTextArea] =
   136     jedit_views().flatMap(jedit_text_areas(_))
   137 
   138   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   139     jedit_text_areas().filter(_.getBuffer == buffer)
   140 
   141   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   142   {
   143     try { buffer.readLock(); body }
   144     finally { buffer.readUnlock() }
   145   }
   146 
   147   def buffer_edit[A](buffer: JEditBuffer)(body: => A): A =
   148   {
   149     try { buffer.beginCompoundEdit(); body }
   150     finally { buffer.endCompoundEdit() }
   151   }
   152 
   153 
   154   /* get text */
   155 
   156   def try_get_text(buffer: JEditBuffer, range: Text.Range): Option[String] =
   157     try { Some(buffer.getText(range.start, range.length)) }
   158     catch { case _: ArrayIndexOutOfBoundsException => None }
   159 
   160   def try_get_text(text: String, range: Text.Range): Option[String] =
   161     try { Some(text.substring(range.start, range.stop)) }
   162     catch { case _: IndexOutOfBoundsException => None }
   163 
   164 
   165   /* buffer range */
   166 
   167   def buffer_range(buffer: JEditBuffer): Text.Range =
   168     Text.Range(0, (buffer.getLength - 1) max 0)
   169 
   170 
   171   /* point range */
   172 
   173   def point_range(buffer: JEditBuffer, offset: Text.Offset): Text.Range =
   174     buffer_lock(buffer) {
   175       def text(i: Text.Offset): Char = buffer.getText(i, 1).charAt(0)
   176       try {
   177         val c = text(offset)
   178         if (Character.isHighSurrogate(c) && Character.isLowSurrogate(text(offset + 1)))
   179           Text.Range(offset, offset + 2)
   180         else if (Character.isLowSurrogate(c) && Character.isHighSurrogate(text(offset - 1)))
   181           Text.Range(offset - 1, offset + 1)
   182         else Text.Range(offset, offset + 1)
   183       }
   184       catch { case _: ArrayIndexOutOfBoundsException => Text.Range(offset, offset + 1) }
   185     }
   186 
   187 
   188   /* visible text range */
   189 
   190   def visible_range(text_area: TextArea): Option[Text.Range] =
   191   {
   192     val buffer = text_area.getBuffer
   193     val n = text_area.getVisibleLines
   194     if (n > 0) {
   195       val start = text_area.getScreenLineStartOffset(0)
   196       val raw_end = text_area.getScreenLineEndOffset(n - 1)
   197       val end = if (raw_end >= 0) raw_end min buffer.getLength else buffer.getLength
   198       Some(Text.Range(start, end))
   199     }
   200     else None
   201   }
   202 
   203   def invalidate_range(text_area: TextArea, range: Text.Range)
   204   {
   205     val buffer = text_area.getBuffer
   206     text_area.invalidateLineRange(
   207       buffer.getLineOfOffset(range.start),
   208       buffer.getLineOfOffset(range.stop))
   209   }
   210 
   211 
   212   /* graphics range */
   213 
   214   case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   215 
   216   // NB: jEdit always normalizes \r\n and \r to \n
   217   // NB: last line lacks \n
   218   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   219   {
   220     val metric = pretty_metric(text_area.getPainter)
   221     val char_width = (metric.unit * metric.average).round.toInt
   222 
   223     val buffer = text_area.getBuffer
   224 
   225     val end = buffer.getLength
   226     val stop = range.stop
   227 
   228     val (p, q, r) =
   229       try {
   230         val p = text_area.offsetToXY(range.start)
   231         val (q, r) =
   232           if (stop >= end) (text_area.offsetToXY(end), char_width * (stop - end))
   233           else if (stop > 0 && buffer.getText(stop - 1, 1) == "\n")
   234             (text_area.offsetToXY(stop - 1), char_width)
   235           else (text_area.offsetToXY(stop), 0)
   236         (p, q, r)
   237       }
   238       catch { case _: ArrayIndexOutOfBoundsException => (null, null, 0) }
   239 
   240     if (p != null && q != null && p.x < q.x + r && p.y == q.y)
   241       Some(Gfx_Range(p.x, p.y, q.x + r - p.x))
   242     else None
   243   }
   244 
   245 
   246   /* pixel range */
   247 
   248   def pixel_range(text_area: TextArea, x: Int, y: Int): Option[Text.Range] =
   249   {
   250     // coordinates wrt. inner painter component
   251     val painter = text_area.getPainter
   252     if (0 <= x && x < painter.getWidth && 0 <= y && y < painter.getHeight) {
   253       val offset = text_area.xyToOffset(x, y, false)
   254       if (offset >= 0) {
   255         val range = point_range(text_area.getBuffer, offset)
   256         gfx_range(text_area, range) match {
   257           case Some(g) if (g.x <= x && x < g.x + g.length) => Some(range)
   258           case _ => None
   259         }
   260       }
   261       else None
   262     }
   263     else None
   264   }
   265 
   266 
   267   /* pretty text metric */
   268 
   269   abstract class Pretty_Metric extends Pretty.Metric
   270   {
   271     def average: Double
   272   }
   273 
   274   def pretty_metric(painter: TextAreaPainter): Pretty_Metric =
   275     new Pretty_Metric {
   276       def string_width(s: String): Double =
   277         painter.getFont.getStringBounds(s, painter.getFontRenderContext).getWidth
   278 
   279       val unit = string_width(Pretty.space)
   280       val average = string_width("mix") / (3 * unit)
   281       def apply(s: String): Double = if (s == "\n") 1.0 else string_width(s) / unit
   282     }
   283 
   284 
   285   /* icons */
   286 
   287   def load_icon(name: String): Icon =
   288   {
   289     val name1 =
   290       if (name.startsWith("idea-icons/")) {
   291         val file =
   292           Isabelle_System.platform_file_url(Path.explode("$JEDIT_HOME/dist/jars/idea-icons.jar"))
   293         "jar:" + file + "!/" + name
   294       }
   295       else name
   296     val icon = GUIUtilities.loadIcon(name1)
   297     if (icon.getIconWidth < 0 || icon.getIconHeight < 0) error("Bad icon: " + name)
   298     else icon
   299   }
   300 
   301   def load_image_icon(name: String): ImageIcon =
   302     load_icon(name) match {
   303       case icon: ImageIcon => icon
   304       case _ => error("Bad image icon: " + name)
   305     }
   306 
   307 
   308   /* key event handling */
   309 
   310   def request_focus_view
   311   {
   312     val view = jEdit.getActiveView()
   313     if (view != null) {
   314       val text_area = view.getTextArea
   315       if (text_area != null) text_area.requestFocus
   316     }
   317   }
   318 
   319   def propagate_key(view: View, evt: KeyEvent)
   320   {
   321     if (view != null && !evt.isConsumed)
   322       view.getInputHandler().processKeyEvent(evt, View.ACTION_BAR, false)
   323   }
   324 
   325   def key_listener(
   326     key_typed: KeyEvent => Unit = _ => (),
   327     key_pressed: KeyEvent => Unit = _ => (),
   328     key_released: KeyEvent => Unit = _ => ()): KeyListener =
   329   {
   330     def process_key_event(evt0: KeyEvent, handle: KeyEvent => Unit)
   331     {
   332       val evt = KeyEventWorkaround.processKeyEvent(evt0)
   333       if (evt != null) handle(evt)
   334     }
   335 
   336     new KeyListener
   337     {
   338       def keyTyped(evt: KeyEvent) { process_key_event(evt, key_typed) }
   339       def keyPressed(evt: KeyEvent) { process_key_event(evt, key_pressed) }
   340       def keyReleased(evt: KeyEvent) { process_key_event(evt, key_released) }
   341     }
   342   }
   343 
   344   def special_key(evt: KeyEvent): Boolean =
   345   {
   346     // cf. 5.1.0/jEdit/org/gjt/sp/jedit/gui/KeyEventWorkaround.java
   347     val mod = evt.getModifiers
   348     (mod & InputEvent.CTRL_MASK) != 0 && (mod & InputEvent.ALT_MASK) == 0 ||
   349     (mod & InputEvent.CTRL_MASK) == 0 && (mod & InputEvent.ALT_MASK) != 0 &&
   350       !Debug.ALT_KEY_PRESSED_DISABLED ||
   351     (mod & InputEvent.META_MASK) != 0
   352   }
   353 }
   354