src/Tools/jEdit/src/plugin.scala
author wenzelm
Fri Sep 23 13:44:31 2011 +0200 (2011-09-23)
changeset 45055 55274f7e306b
parent 44963 4662dddc2fd8
child 45075 6c66e268f8eb
permissions -rw-r--r--
explicit option for socket vs. fifo communication;
     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(10)) max Time.seconds(5)
   323     val use_socket = Isabelle_System.getenv("JEDIT_USE_SOCKET") == "true"
   324     val modes = space_explode(',', Isabelle_System.getenv("JEDIT_PRINT_MODE")).map("-m" + _)
   325     val logic = {
   326       val logic = Property("logic")
   327       if (logic != null && logic != "") logic
   328       else Isabelle.default_logic()
   329     }
   330     session.start(timeout, use_socket, modes ::: List(logic))
   331   }
   332 
   333 
   334   /* convenience actions */
   335 
   336   private def user_input(text_area: JEditTextArea, s1: String, s2: String = "")
   337   {
   338     s1.foreach(text_area.userInput(_))
   339     s2.foreach(text_area.userInput(_))
   340     s2.foreach(_ => text_area.goToPrevCharacter(false))
   341   }
   342 
   343   def input_sub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sub_decoded)
   344   def input_sup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sup_decoded)
   345   def input_isub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isub_decoded)
   346   def input_isup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isup_decoded)
   347   def input_bsub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsub_decoded, Symbol.esub_decoded)
   348   def input_bsup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsup_decoded, Symbol.esup_decoded)
   349   def input_bold(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bold_decoded)
   350 
   351   def check_buffer(buffer: Buffer)
   352   {
   353     document_model(buffer) match {
   354       case None =>
   355       case Some(model) => model.full_perspective()
   356     }
   357   }
   358 
   359   def cancel_execution() { session.cancel_execution() }
   360 }
   361 
   362 
   363 class Plugin extends EBPlugin
   364 {
   365   /* theory files */
   366 
   367   private lazy val delay_load =
   368     Swing_Thread.delay_last(Isabelle.session.load_delay)
   369     {
   370       val view = jEdit.getActiveView()
   371 
   372       val buffers = Isabelle.jedit_buffers().toList
   373       def loaded_buffer(name: String): Boolean =
   374         buffers.exists(buffer => Isabelle.buffer_name(buffer) == name)
   375 
   376       val thys =
   377         for (buffer <- buffers; model <- Isabelle.document_model(buffer))
   378           yield model.name
   379       val files = Isabelle.thy_info.dependencies(thys).map(_._1.node).
   380         filter(file => !loaded_buffer(file) && Isabelle.thy_load.check_file(view, file))
   381 
   382       if (!files.isEmpty) {
   383         val files_list = new ListView(Library.sort_strings(files))
   384         for (i <- 0 until files.length)
   385           files_list.selection.indices += i
   386 
   387         val answer =
   388           Library.confirm_dialog(view,
   389             "Auto loading of required files",
   390             JOptionPane.YES_NO_OPTION,
   391             "The following files are required to resolve theory imports.",
   392             "Reload selected files now?",
   393             new ScrollPane(files_list))
   394         if (answer == 0)
   395           for {
   396             file <- files
   397             if files_list.selection.items.contains(file)
   398           } jEdit.openFile(null: View, file)
   399       }
   400     }
   401 
   402 
   403   /* session manager */
   404 
   405   private val session_manager = actor {
   406     loop {
   407       react {
   408         case phase: Session.Phase =>
   409           phase match {
   410             case Session.Failed =>
   411               Swing_Thread.now {
   412                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   413                 text.editable = false
   414                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   415               }
   416 
   417             case Session.Ready =>
   418               Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   419               delay_load()
   420 
   421             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   422             case _ =>
   423           }
   424         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   425       }
   426     }
   427   }
   428 
   429 
   430   /* main plugin plumbing */
   431 
   432   override def handleMessage(message: EBMessage)
   433   {
   434     Swing_Thread.assert()
   435     message match {
   436       case msg: EditorStarted =>
   437         Isabelle.check_jvm()
   438         if (Isabelle.Boolean_Property("auto-start"))
   439           Isabelle.start_session()
   440 
   441       case msg: BufferUpdate
   442       if msg.getWhat == BufferUpdate.LOADED =>
   443         if (Isabelle.session.is_ready) {
   444           val buffer = msg.getBuffer
   445           if (buffer != null) Isabelle.init_model(buffer)
   446           delay_load()
   447         }
   448 
   449       case msg: EditPaneUpdate
   450       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   451           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   452           msg.getWhat == EditPaneUpdate.CREATED ||
   453           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   454         val edit_pane = msg.getEditPane
   455         val buffer = edit_pane.getBuffer
   456         val text_area = edit_pane.getTextArea
   457 
   458         if (buffer != null && text_area != null) {
   459           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   460               msg.getWhat == EditPaneUpdate.CREATED) {
   461             if (Isabelle.session.is_ready)
   462               Isabelle.init_view(buffer, text_area)
   463           }
   464           else Isabelle.exit_view(buffer, text_area)
   465         }
   466 
   467       case msg: PropertiesChanged =>
   468         Swing_Thread.now { Isabelle.setup_tooltips() }
   469         Isabelle.session.global_settings.event(Session.Global_Settings)
   470 
   471       case _ =>
   472     }
   473   }
   474 
   475   override def start()
   476   {
   477     Isabelle.plugin = this
   478     Isabelle.setup_tooltips()
   479     Isabelle_System.init()
   480     Isabelle_System.install_fonts()
   481     Isabelle.session = new Session(Isabelle.thy_load)
   482     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   483     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   484       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   485     Isabelle.session.phase_changed += session_manager
   486   }
   487 
   488   override def stop()
   489   {
   490     Isabelle.session.phase_changed -= session_manager
   491     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   492     Isabelle.session.stop()
   493   }
   494 }