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