src/Pure/GUI/gui.scala
author wenzelm
Sun, 10 Aug 2014 13:59:08 +0200
changeset 59095 91e188508bc9
parent 58981 ba170c8ea578
child 59180 85ec71012df8
permissions -rw-r--r--
proper layered_pane for JDialog, e.g. relevant for floating dockables in jEdit, for completion popup in text field;
     1 /*  Title:      Pure/GUI/gui.scala
     2     Module:     PIDE-GUI
     3     Author:     Makarius
     4 
     5 Basic GUI tools (for AWT/Swing).
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import java.lang.{ClassLoader, ClassNotFoundException, NoSuchMethodException}
    12 import java.awt.{Image, Component, Container, Toolkit, Window, Font, KeyboardFocusManager}
    13 import java.awt.font.{TextAttribute, TransformAttribute, FontRenderContext, LineMetrics}
    14 import java.awt.geom.AffineTransform
    15 import javax.swing.{ImageIcon, JOptionPane, UIManager, JLayeredPane, JFrame, JWindow, JDialog,
    16   JButton, JTextField}
    17 
    18 import scala.collection.convert.WrapAsJava
    19 import scala.swing.{ComboBox, TextArea, ScrollPane}
    20 import scala.swing.event.SelectionChanged
    21 
    22 
    23 object GUI
    24 {
    25   /* Swing look-and-feel */
    26 
    27   def get_laf(): String =
    28   {
    29     if (Platform.is_windows || Platform.is_macos)
    30       UIManager.getSystemLookAndFeelClassName()
    31     else
    32       UIManager.getInstalledLookAndFeels().find(_.getName == "Nimbus").map(_.getClassName)
    33         .getOrElse(UIManager.getCrossPlatformLookAndFeelClassName())
    34   }
    35 
    36   def init_laf(): Unit = UIManager.setLookAndFeel(get_laf())
    37 
    38   def is_macos_laf(): Boolean =
    39     Platform.is_macos &&
    40     UIManager.getSystemLookAndFeelClassName() == UIManager.getLookAndFeel.getClass.getName
    41 
    42 
    43   /* plain focus traversal, notably for text fields */
    44 
    45   def plain_focus_traversal(component: Component)
    46   {
    47     val dummy_button = new JButton
    48     def apply(id: Int): Unit =
    49       component.setFocusTraversalKeys(id, dummy_button.getFocusTraversalKeys(id))
    50     apply(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)
    51     apply(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)
    52   }
    53 
    54 
    55   /* X11 window manager */
    56 
    57   def window_manager(): Option[String] =
    58   {
    59     if (Platform.is_windows || Platform.is_macos) None
    60     else
    61       try {
    62         val XWM = Class.forName("sun.awt.X11.XWM", true, ClassLoader.getSystemClassLoader)
    63         val getWM = XWM.getDeclaredMethod("getWM")
    64         getWM.setAccessible(true)
    65         getWM.invoke(null) match {
    66           case null => None
    67           case wm => Some(wm.toString)
    68         }
    69       }
    70       catch {
    71         case _: ClassNotFoundException => None
    72         case _: NoSuchMethodException => None
    73       }
    74   }
    75 
    76 
    77   /* simple dialogs */
    78 
    79   def scrollable_text(txt: String, width: Int = 60, height: Int = 20, editable: Boolean = false)
    80     : ScrollPane =
    81   {
    82     val text = new TextArea(txt)
    83     if (width > 0) text.columns = width
    84     if (height > 0 && split_lines(txt).length > height) text.rows = height
    85     text.editable = editable
    86     new ScrollPane(text)
    87   }
    88 
    89   private def simple_dialog(kind: Int, default_title: String,
    90     parent: Component, title: String, message: Seq[Any])
    91   {
    92     GUI_Thread.now {
    93       val java_message = message map { case x: scala.swing.Component => x.peer case x => x }
    94       JOptionPane.showMessageDialog(parent,
    95         java_message.toArray.asInstanceOf[Array[AnyRef]],
    96         if (title == null) default_title else title, kind)
    97     }
    98   }
    99 
   100   def dialog(parent: Component, title: String, message: Any*): Unit =
   101     simple_dialog(JOptionPane.PLAIN_MESSAGE, null, parent, title, message)
   102 
   103   def warning_dialog(parent: Component, title: String, message: Any*): Unit =
   104     simple_dialog(JOptionPane.WARNING_MESSAGE, "Warning", parent, title, message)
   105 
   106   def error_dialog(parent: Component, title: String, message: Any*): Unit =
   107     simple_dialog(JOptionPane.ERROR_MESSAGE, "Error", parent, title, message)
   108 
   109   def confirm_dialog(parent: Component, title: String, option_type: Int, message: Any*): Int =
   110     GUI_Thread.now {
   111       val java_message = message map { case x: scala.swing.Component => x.peer case x => x }
   112       JOptionPane.showConfirmDialog(parent,
   113         java_message.toArray.asInstanceOf[Array[AnyRef]], title,
   114           option_type, JOptionPane.QUESTION_MESSAGE)
   115     }
   116 
   117 
   118   /* zoom box */
   119 
   120   private val Zoom_Factor = "([0-9]+)%?".r
   121 
   122   abstract class Zoom_Box extends ComboBox[String](
   123     List("50%", "70%", "85%", "100%", "125%", "150%", "175%", "200%", "300%", "400%"))
   124   {
   125     def changed: Unit
   126     def factor: Int = parse(selection.item)
   127 
   128     private def parse(text: String): Int =
   129       text match {
   130         case Zoom_Factor(s) =>
   131           val i = Integer.parseInt(s)
   132           if (10 <= i && i < 1000) i else 100
   133         case _ => 100
   134       }
   135 
   136     private def print(i: Int): String = i.toString + "%"
   137 
   138     def set_item(i: Int) {
   139       peer.getEditor match {
   140         case null =>
   141         case editor => editor.setItem(print(i))
   142       }
   143     }
   144 
   145     makeEditable()(c => new ComboBox.BuiltInEditor(c)(text => print(parse(text)), x => x))
   146     peer.getEditor.getEditorComponent match {
   147       case text: JTextField => text.setColumns(4)
   148       case _ =>
   149     }
   150 
   151     selection.index = 3
   152 
   153     listenTo(selection)
   154     reactions += { case SelectionChanged(_) => changed }
   155   }
   156 
   157 
   158   /* tooltip with multi-line support */
   159 
   160   def tooltip_lines(text: String): String =
   161     if (text == null || text == "") null
   162     else "<html>" + HTML.encode(text) + "</html>"
   163 
   164 
   165   /* screen resolution */
   166 
   167   def resolution_scale(): Double = Toolkit.getDefaultToolkit.getScreenResolution.toDouble / 72
   168   def resolution_scale(i: Int): Int = (i.toDouble * resolution_scale()).round.toInt
   169 
   170 
   171   /* icon */
   172 
   173   def isabelle_icon(): ImageIcon =
   174     new ImageIcon(getClass.getClassLoader.getResource("isabelle/isabelle_transparent-32.gif"))
   175 
   176   def isabelle_icons(): List[ImageIcon] =
   177     for (icon <- List("isabelle/isabelle_transparent-32.gif", "isabelle/isabelle_transparent.gif"))
   178       yield new ImageIcon(getClass.getClassLoader.getResource(icon))
   179 
   180   def isabelle_image(): Image = isabelle_icon().getImage
   181 
   182   def isabelle_images(): java.util.List[Image] =
   183     WrapAsJava.seqAsJavaList(isabelle_icons.map(_.getImage))
   184 
   185 
   186   /* component hierachy */
   187 
   188   def get_parent(component: Component): Option[Container] =
   189     component.getParent match {
   190       case null => None
   191       case parent => Some(parent)
   192     }
   193 
   194   def ancestors(component: Component): Iterator[Container] = new Iterator[Container] {
   195     private var next_elem = get_parent(component)
   196     def hasNext(): Boolean = next_elem.isDefined
   197     def next(): Container =
   198       next_elem match {
   199         case Some(parent) =>
   200           next_elem = get_parent(parent)
   201           parent
   202         case None => Iterator.empty.next()
   203       }
   204   }
   205 
   206   def parent_window(component: Component): Option[Window] =
   207     ancestors(component).collectFirst({ case x: Window => x })
   208 
   209   def layered_pane(component: Component): Option[JLayeredPane] =
   210     parent_window(component) match {
   211       case Some(w: JWindow) => Some(w.getLayeredPane)
   212       case Some(w: JFrame) => Some(w.getLayeredPane)
   213       case Some(w: JDialog) => Some(w.getLayeredPane)
   214       case _ => None
   215     }
   216 
   217 
   218   /* font operations */
   219 
   220   def font_metrics(font: Font): LineMetrics =
   221     font.getLineMetrics("", new FontRenderContext(null, false, false))
   222 
   223   def imitate_font(family: String, font: Font, scale: Double = 1.0): Font =
   224   {
   225     val font1 = new Font(family, font.getStyle, font.getSize)
   226     val size = scale * (font_metrics(font).getAscent / font_metrics(font1).getAscent * font.getSize)
   227     font1.deriveFont(size.round.toInt)
   228   }
   229 
   230   def transform_font(font: Font, transform: AffineTransform): Font =
   231   {
   232     import scala.collection.JavaConversions._
   233     font.deriveFont(Map(TextAttribute.TRANSFORM -> new TransformAttribute(transform)))
   234   }
   235 }
   236