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