src/Tools/jEdit/src/plugin.scala
author wenzelm
Sat Sep 10 14:48:06 2011 +0200 (2011-09-10)
changeset 44864 e50557cb0eb6
parent 44721 ba478c3f7255
child 44954 b536b1144eb3
permissions -rw-r--r--
explicit jEdit actions -- to enable key mappings, for example;
     1 /*  Title:      Tools/jEdit/src/plugin.scala
     2     Author:     Makarius
     3 
     4 Main Isabelle/jEdit plugin setup.
     5 */
     6 
     7 package isabelle.jedit
     8 
     9 
    10 import isabelle._
    11 
    12 import java.lang.System
    13 import java.awt.Font
    14 import javax.swing.JOptionPane
    15 
    16 import scala.collection.mutable
    17 import scala.swing.{ComboBox, ListView, ScrollPane}
    18 
    19 import org.gjt.sp.jedit.{jEdit, GUIUtilities, EBMessage, EBPlugin,
    20   Buffer, EditPane, ServiceManager, View}
    21 import org.gjt.sp.jedit.buffer.JEditBuffer
    22 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea}
    23 import org.gjt.sp.jedit.syntax.{Token => JEditToken, ModeProvider}
    24 import org.gjt.sp.jedit.msg.{EditorStarted, BufferUpdate, EditPaneUpdate, PropertiesChanged}
    25 import org.gjt.sp.jedit.gui.DockableWindowManager
    26 
    27 import org.gjt.sp.util.SyntaxUtilities
    28 import org.gjt.sp.util.Log
    29 
    30 import scala.actors.Actor._
    31 
    32 
    33 object Isabelle
    34 {
    35   /* plugin instance */
    36 
    37   var plugin: Plugin = null
    38   var session: Session = null
    39 
    40 
    41   /* properties */
    42 
    43   val OPTION_PREFIX = "options.isabelle."
    44 
    45   object Property
    46   {
    47     def apply(name: String): String =
    48       jEdit.getProperty(OPTION_PREFIX + name)
    49     def apply(name: String, default: String): String =
    50       jEdit.getProperty(OPTION_PREFIX + name, default)
    51     def update(name: String, value: String) =
    52       jEdit.setProperty(OPTION_PREFIX + name, value)
    53   }
    54 
    55   object Boolean_Property
    56   {
    57     def apply(name: String): Boolean =
    58       jEdit.getBooleanProperty(OPTION_PREFIX + name)
    59     def apply(name: String, default: Boolean): Boolean =
    60       jEdit.getBooleanProperty(OPTION_PREFIX + name, default)
    61     def update(name: String, value: Boolean) =
    62       jEdit.setBooleanProperty(OPTION_PREFIX + name, value)
    63   }
    64 
    65   object Int_Property
    66   {
    67     def apply(name: String): Int =
    68       jEdit.getIntegerProperty(OPTION_PREFIX + name)
    69     def apply(name: String, default: Int): Int =
    70       jEdit.getIntegerProperty(OPTION_PREFIX + name, default)
    71     def update(name: String, value: Int) =
    72       jEdit.setIntegerProperty(OPTION_PREFIX + name, value)
    73   }
    74 
    75   object Double_Property
    76   {
    77     def apply(name: String): Double =
    78       jEdit.getDoubleProperty(OPTION_PREFIX + name, 0.0)
    79     def apply(name: String, default: Double): Double =
    80       jEdit.getDoubleProperty(OPTION_PREFIX + name, default)
    81     def update(name: String, value: Double) =
    82       jEdit.setDoubleProperty(OPTION_PREFIX + name, value)
    83   }
    84 
    85   object Time_Property
    86   {
    87     def apply(name: String): Time =
    88       Time.seconds(Double_Property(name))
    89     def apply(name: String, default: Time): Time =
    90       Time.seconds(Double_Property(name, default.seconds))
    91     def update(name: String, value: Time) =
    92       Double_Property.update(name, value.seconds)
    93   }
    94 
    95 
    96   /* font */
    97 
    98   def font_family(): String = jEdit.getProperty("view.font")
    99 
   100   def font_size(): Float =
   101     (jEdit.getIntegerProperty("view.fontsize", 16) *
   102       Int_Property("relative-font-size", 100)).toFloat / 100
   103 
   104 
   105   /* text area ranges */
   106 
   107   sealed case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   108 
   109   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   110   {
   111     val p = text_area.offsetToXY(range.start)
   112     val q = text_area.offsetToXY(range.stop)
   113     if (p != null && q != null && p.y == q.y) Some(new Gfx_Range(p.x, p.y, q.x - p.x))
   114     else None
   115   }
   116 
   117 
   118   /* tooltip markup */
   119 
   120   def tooltip(text: String): String =
   121     "<html><pre style=\"font-family: " + font_family() + "; font-size: " +
   122         Int_Property("tooltip-font-size", 10).toString + "px; \">" +  // FIXME proper scaling (!?)
   123       HTML.encode(text) + "</pre></html>"
   124 
   125   private val tooltip_lb = Time.seconds(0.5)
   126   private val tooltip_ub = Time.seconds(60.0)
   127   def tooltip_dismiss_delay(): Time =
   128     Time_Property("tooltip-dismiss-delay", Time.seconds(8.0)) max tooltip_lb min tooltip_ub
   129 
   130   def setup_tooltips()
   131   {
   132     Swing_Thread.now {
   133       val manager = javax.swing.ToolTipManager.sharedInstance
   134       manager.setDismissDelay(tooltip_dismiss_delay().ms.toInt)
   135     }
   136   }
   137 
   138 
   139   /* icons */
   140 
   141   def load_icon(name: String): javax.swing.Icon =
   142   {
   143     val icon = GUIUtilities.loadIcon(name)
   144     if (icon.getIconWidth < 0 || icon.getIconHeight < 0)
   145       Log.log(Log.ERROR, icon, "Bad icon: " + name)
   146     icon
   147   }
   148 
   149 
   150   /* check JVM */
   151 
   152   def check_jvm()
   153   {
   154     if (!Platform.is_hotspot) {
   155       Library.warning_dialog(jEdit.getActiveView, "Bad Java Virtual Machine",
   156         "This is " + Platform.jvm_name,
   157         "Isabelle/jEdit requires Java Hotspot from Sun/Oracle/Apple!")
   158     }
   159   }
   160 
   161 
   162   /* buffers */
   163 
   164   def swing_buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   165     Swing_Thread.now { buffer_lock(buffer) { body } }
   166 
   167   def buffer_text(buffer: JEditBuffer): String =
   168     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   169 
   170   def buffer_name(buffer: Buffer): String = buffer.getSymlinkPath
   171 
   172 
   173   /* main jEdit components */
   174 
   175   def jedit_buffers(): Iterator[Buffer] = jEdit.getBuffers().iterator
   176 
   177   def jedit_buffer(name: String): Option[Buffer] =
   178     jedit_buffers().find(buffer => buffer_name(buffer) == name)
   179 
   180   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   181 
   182   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   183     view.getEditPanes().iterator.map(_.getTextArea)
   184 
   185   def jedit_text_areas(): Iterator[JEditTextArea] =
   186     jedit_views().flatMap(jedit_text_areas(_))
   187 
   188   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   189     jedit_text_areas().filter(_.getBuffer == buffer)
   190 
   191   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   192   {
   193     try { buffer.readLock(); body }
   194     finally { buffer.readUnlock() }
   195   }
   196 
   197 
   198   /* document model and view */
   199 
   200   def document_model(buffer: Buffer): Option[Document_Model] = Document_Model(buffer)
   201   def document_view(text_area: JEditTextArea): Option[Document_View] = Document_View(text_area)
   202 
   203   def document_views(buffer: Buffer): List[Document_View] =
   204     for {
   205       text_area <- jedit_text_areas(buffer).toList
   206       val doc_view = document_view(text_area)
   207       if doc_view.isDefined
   208     } yield doc_view.get
   209 
   210   def init_model(buffer: Buffer)
   211   {
   212     swing_buffer_lock(buffer) {
   213       val opt_model =
   214         document_model(buffer) match {
   215           case Some(model) => Some(model)
   216           case None =>
   217             val name = buffer_name(buffer)
   218             Thy_Header.thy_name(name) match {
   219               case Some(theory) =>
   220                 val node_name = Document.Node.Name(name, buffer.getDirectory, theory)
   221                 Some(Document_Model.init(session, buffer, node_name))
   222               case None => None
   223             }
   224         }
   225       if (opt_model.isDefined) {
   226         for (text_area <- jedit_text_areas(buffer)) {
   227           if (document_view(text_area).map(_.model) != opt_model)
   228             Document_View.init(opt_model.get, text_area)
   229         }
   230       }
   231     }
   232   }
   233 
   234   def exit_model(buffer: Buffer)
   235   {
   236     swing_buffer_lock(buffer) {
   237       jedit_text_areas(buffer).foreach(Document_View.exit)
   238       Document_Model.exit(buffer)
   239     }
   240   }
   241 
   242   def init_view(buffer: Buffer, text_area: JEditTextArea)
   243   {
   244     swing_buffer_lock(buffer) {
   245       document_model(buffer) match {
   246         case Some(model) => Document_View.init(model, text_area)
   247         case None =>
   248       }
   249     }
   250   }
   251 
   252   def exit_view(buffer: Buffer, text_area: JEditTextArea)
   253   {
   254     swing_buffer_lock(buffer) {
   255       Document_View.exit(text_area)
   256     }
   257   }
   258 
   259 
   260   /* dockable windows */
   261 
   262   private def wm(view: View): DockableWindowManager = view.getDockableWindowManager
   263 
   264   def docked_session(view: View): Option[Session_Dockable] =
   265     wm(view).getDockableWindow("isabelle-session") match {
   266       case dockable: Session_Dockable => Some(dockable)
   267       case _ => None
   268     }
   269 
   270   def docked_output(view: View): Option[Output_Dockable] =
   271     wm(view).getDockableWindow("isabelle-output") match {
   272       case dockable: Output_Dockable => Some(dockable)
   273       case _ => None
   274     }
   275 
   276   def docked_raw_output(view: View): Option[Raw_Output_Dockable] =
   277     wm(view).getDockableWindow("isabelle-raw-output") match {
   278       case dockable: Raw_Output_Dockable => Some(dockable)
   279       case _ => None
   280     }
   281 
   282   def docked_protocol(view: View): Option[Protocol_Dockable] =
   283     wm(view).getDockableWindow("isabelle-protocol") match {
   284       case dockable: Protocol_Dockable => Some(dockable)
   285       case _ => None
   286     }
   287 
   288 
   289   /* logic image */
   290 
   291   def default_logic(): String =
   292   {
   293     val logic = Isabelle_System.getenv("JEDIT_LOGIC")
   294     if (logic != "") logic
   295     else Isabelle_System.getenv_strict("ISABELLE_LOGIC")
   296   }
   297 
   298   class Logic_Entry(val name: String, val description: String)
   299   {
   300     override def toString = description
   301   }
   302 
   303   def logic_selector(logic: String): ComboBox[Logic_Entry] =
   304   {
   305     val entries =
   306       new Logic_Entry("", "default (" + default_logic() + ")") ::
   307         Isabelle_System.find_logics().map(name => new Logic_Entry(name, name))
   308     val component = new ComboBox(entries)
   309     entries.find(_.name == logic) match {
   310       case None =>
   311       case Some(entry) => component.selection.item = entry
   312     }
   313     component.tooltip = "Isabelle logic image"
   314     component
   315   }
   316 
   317   def start_session()
   318   {
   319     val timeout = Time_Property("startup-timeout", Time.seconds(10)) max Time.seconds(5)
   320     val modes = space_explode(',', Isabelle_System.getenv("JEDIT_PRINT_MODE")).map("-m" + _)
   321     val logic = {
   322       val logic = Property("logic")
   323       if (logic != null && logic != "") logic
   324       else Isabelle.default_logic()
   325     }
   326     session.start(timeout, modes ::: List(logic))
   327   }
   328 
   329 
   330   /* convenience actions */
   331 
   332   private def user_input(text_area: JEditTextArea, s1: String, s2: String = "")
   333   {
   334     s1.foreach(text_area.userInput(_))
   335     s2.foreach(text_area.userInput(_))
   336     s2.foreach(_ => text_area.goToPrevCharacter(false))
   337   }
   338 
   339   def input_sub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sub_decoded)
   340   def input_sup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sup_decoded)
   341   def input_isub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isub_decoded)
   342   def input_isup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isup_decoded)
   343   def input_bsub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsub_decoded, Symbol.esub_decoded)
   344   def input_bsup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsup_decoded, Symbol.esup_decoded)
   345   def input_bold(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bold_decoded)
   346 
   347   def check_buffer(buffer: Buffer)
   348   {
   349     document_model(buffer) match {
   350       case None =>
   351       case Some(model) => model.full_perspective()
   352     }
   353   }
   354 
   355   def cancel_execution() { session.cancel_execution() }
   356 }
   357 
   358 
   359 class Plugin extends EBPlugin
   360 {
   361   /* theory files */
   362 
   363   val thy_load = new JEdit_Thy_Load
   364   val thy_info = new Thy_Info(thy_load)
   365 
   366   private lazy val delay_load =
   367     Swing_Thread.delay_last(Isabelle.session.load_delay)
   368     {
   369       val buffers = Isabelle.jedit_buffers().toList
   370       def loaded_buffer(name: String): Boolean =
   371         buffers.exists(buffer => Isabelle.buffer_name(buffer) == name)
   372 
   373       val thys =
   374         for (buffer <- buffers; model <- Isabelle.document_model(buffer))
   375           yield model.name
   376       val files = thy_info.dependencies(thys).toList.map(_._1.node).filterNot(loaded_buffer _)
   377 
   378       if (!files.isEmpty) {
   379         val files_list = new ListView(Library.sort_strings(files))
   380         for (i <- 0 until files.length)
   381           files_list.selection.indices += i
   382 
   383         val answer =
   384           Library.confirm_dialog(jEdit.getActiveView(),
   385             "Auto loading of required files",
   386             JOptionPane.YES_NO_OPTION,
   387             "The following files are required to resolve theory imports.",
   388             "Reload selected files now?",
   389             new ScrollPane(files_list))
   390         if (answer == 0)
   391           files_list.selection.items foreach (file =>
   392             if (!loaded_buffer(file)) jEdit.openFile(null: View, file))
   393       }
   394     }
   395 
   396 
   397   /* session manager */
   398 
   399   private val session_manager = actor {
   400     loop {
   401       react {
   402         case phase: Session.Phase =>
   403           phase match {
   404             case Session.Failed =>
   405               Swing_Thread.now {
   406                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   407                 text.editable = false
   408                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   409               }
   410 
   411             case Session.Ready =>
   412               Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   413               delay_load()
   414 
   415             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   416             case _ =>
   417           }
   418         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   419       }
   420     }
   421   }
   422 
   423 
   424   /* main plugin plumbing */
   425 
   426   override def handleMessage(message: EBMessage)
   427   {
   428     Swing_Thread.assert()
   429     message match {
   430       case msg: EditorStarted =>
   431         Isabelle.check_jvm()
   432         if (Isabelle.Boolean_Property("auto-start"))
   433           Isabelle.start_session()
   434 
   435       case msg: BufferUpdate
   436       if msg.getWhat == BufferUpdate.LOADED =>
   437         if (Isabelle.session.is_ready) {
   438           val buffer = msg.getBuffer
   439           if (buffer != null) Isabelle.init_model(buffer)
   440           delay_load()
   441         }
   442 
   443       case msg: EditPaneUpdate
   444       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   445           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   446           msg.getWhat == EditPaneUpdate.CREATED ||
   447           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   448         val edit_pane = msg.getEditPane
   449         val buffer = edit_pane.getBuffer
   450         val text_area = edit_pane.getTextArea
   451 
   452         if (buffer != null && text_area != null) {
   453           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   454               msg.getWhat == EditPaneUpdate.CREATED) {
   455             if (Isabelle.session.is_ready)
   456               Isabelle.init_view(buffer, text_area)
   457           }
   458           else Isabelle.exit_view(buffer, text_area)
   459         }
   460 
   461       case msg: PropertiesChanged =>
   462         Swing_Thread.now { Isabelle.setup_tooltips() }
   463         Isabelle.session.global_settings.event(Session.Global_Settings)
   464 
   465       case _ =>
   466     }
   467   }
   468 
   469   override def start()
   470   {
   471     Isabelle.plugin = this
   472     Isabelle.setup_tooltips()
   473     Isabelle_System.init()
   474     Isabelle_System.install_fonts()
   475     Isabelle.session = new Session(thy_load)
   476     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   477     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   478       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   479     Isabelle.session.phase_changed += session_manager
   480   }
   481 
   482   override def stop()
   483   {
   484     Isabelle.session.phase_changed -= session_manager
   485     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   486     Isabelle.session.stop()
   487   }
   488 }