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