src/Tools/jEdit/src/plugin.scala
author wenzelm
Mon Aug 29 16:38:56 2011 +0200 (2011-08-29)
changeset 44573 51f8895b9ad9
parent 44434 3b9b684bfa6f
child 44574 24444588fddd
permissions -rw-r--r--
some dialog for auto loading of required files (still inactive);
     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.io.{File, FileInputStream, IOException}
    14 import java.awt.Font
    15 import javax.swing.JOptionPane
    16 
    17 import scala.collection.mutable
    18 import scala.swing.ComboBox
    19 
    20 import org.gjt.sp.jedit.{jEdit, GUIUtilities, EBMessage, EBPlugin,
    21   Buffer, EditPane, MiscUtilities, ServiceManager, View}
    22 import org.gjt.sp.jedit.buffer.JEditBuffer
    23 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea}
    24 import org.gjt.sp.jedit.syntax.{Token => JEditToken, ModeProvider}
    25 import org.gjt.sp.jedit.msg.{EditorStarted, BufferUpdate, EditPaneUpdate, PropertiesChanged}
    26 import org.gjt.sp.jedit.gui.DockableWindowManager
    27 import org.gjt.sp.jedit.io.{VFS, FileVFS, VFSManager}
    28 
    29 import org.gjt.sp.util.SyntaxUtilities
    30 import org.gjt.sp.util.Log
    31 
    32 import scala.actors.Actor
    33 import Actor._
    34 
    35 
    36 object Isabelle
    37 {
    38   /* plugin instance */
    39 
    40   var plugin: Plugin = null
    41   var session: Session = null
    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   def tooltip_dismiss_delay(): Time =
   129     Time_Property("tooltip-dismiss-delay", Time.seconds(8.0)) max Time.seconds(0.5)
   130 
   131   def setup_tooltips()
   132   {
   133     Swing_Thread.now {
   134       val manager = javax.swing.ToolTipManager.sharedInstance
   135       manager.setDismissDelay(tooltip_dismiss_delay().ms.toInt)
   136     }
   137   }
   138 
   139 
   140   /* icons */
   141 
   142   def load_icon(name: String): javax.swing.Icon =
   143   {
   144     val icon = GUIUtilities.loadIcon(name)
   145     if (icon.getIconWidth < 0 || icon.getIconHeight < 0)
   146       Log.log(Log.ERROR, icon, "Bad icon: " + name)
   147     icon
   148   }
   149 
   150 
   151   /* check JVM */
   152 
   153   def check_jvm()
   154   {
   155     if (!Platform.is_hotspot) {
   156       Library.warning_dialog(jEdit.getActiveView, "Bad Java Virtual Machine",
   157         "This is " + Platform.jvm_name,
   158         "Isabelle/jEdit requires Java Hotspot from Sun/Oracle/Apple!")
   159     }
   160   }
   161 
   162 
   163   /* main jEdit components */
   164 
   165   def jedit_buffers(): Iterator[Buffer] = jEdit.getBuffers().iterator
   166 
   167   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   168 
   169   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   170     view.getEditPanes().iterator.map(_.getTextArea)
   171 
   172   def jedit_text_areas(): Iterator[JEditTextArea] =
   173     jedit_views().flatMap(jedit_text_areas(_))
   174 
   175   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   176     jedit_text_areas().filter(_.getBuffer == buffer)
   177 
   178   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   179   {
   180     try { buffer.readLock(); body }
   181     finally { buffer.readUnlock() }
   182   }
   183 
   184   def swing_buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   185     Swing_Thread.now { buffer_lock(buffer) { body } }
   186 
   187   def buffer_text(buffer: JEditBuffer): String =
   188     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   189 
   190   def buffer_path(buffer: Buffer): (String, String) =
   191   {
   192     val master_dir = buffer.getDirectory
   193     val path = buffer.getSymlinkPath
   194     (master_dir, path)
   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 (master_dir, path) = buffer_path(buffer)
   218             Thy_Header.thy_name(path) match {
   219               case Some(name) =>
   220                 Some(Document_Model.init(session, buffer, master_dir, path, name))
   221               case None => None
   222             }
   223         }
   224       if (opt_model.isDefined) {
   225         for (text_area <- jedit_text_areas(buffer)) {
   226           if (document_view(text_area).map(_.model) != opt_model)
   227             Document_View.init(opt_model.get, text_area)
   228         }
   229       }
   230     }
   231   }
   232 
   233   def exit_model(buffer: Buffer)
   234   {
   235     swing_buffer_lock(buffer) {
   236       jedit_text_areas(buffer).foreach(Document_View.exit)
   237       Document_Model.exit(buffer)
   238     }
   239   }
   240 
   241   def init_view(buffer: Buffer, text_area: JEditTextArea)
   242   {
   243     swing_buffer_lock(buffer) {
   244       document_model(buffer) match {
   245         case Some(model) => Document_View.init(model, text_area)
   246         case None =>
   247       }
   248     }
   249   }
   250 
   251   def exit_view(buffer: Buffer, text_area: JEditTextArea)
   252   {
   253     swing_buffer_lock(buffer) {
   254       Document_View.exit(text_area)
   255     }
   256   }
   257 
   258 
   259   /* dockable windows */
   260 
   261   private def wm(view: View): DockableWindowManager = view.getDockableWindowManager
   262 
   263   def docked_session(view: View): Option[Session_Dockable] =
   264     wm(view).getDockableWindow("isabelle-session") match {
   265       case dockable: Session_Dockable => Some(dockable)
   266       case _ => None
   267     }
   268 
   269   def docked_output(view: View): Option[Output_Dockable] =
   270     wm(view).getDockableWindow("isabelle-output") match {
   271       case dockable: Output_Dockable => Some(dockable)
   272       case _ => None
   273     }
   274 
   275   def docked_raw_output(view: View): Option[Raw_Output_Dockable] =
   276     wm(view).getDockableWindow("isabelle-raw-output") match {
   277       case dockable: Raw_Output_Dockable => Some(dockable)
   278       case _ => None
   279     }
   280 
   281   def docked_protocol(view: View): Option[Protocol_Dockable] =
   282     wm(view).getDockableWindow("isabelle-protocol") match {
   283       case dockable: Protocol_Dockable => Some(dockable)
   284       case _ => None
   285     }
   286 
   287 
   288   /* logic image */
   289 
   290   def default_logic(): String =
   291   {
   292     val logic = Isabelle_System.getenv("JEDIT_LOGIC")
   293     if (logic != "") logic
   294     else Isabelle_System.getenv_strict("ISABELLE_LOGIC")
   295   }
   296 
   297   class Logic_Entry(val name: String, val description: String)
   298   {
   299     override def toString = description
   300   }
   301 
   302   def logic_selector(logic: String): ComboBox[Logic_Entry] =
   303   {
   304     val entries =
   305       new Logic_Entry("", "default (" + default_logic() + ")") ::
   306         Isabelle_System.find_logics().map(name => new Logic_Entry(name, name))
   307     val component = new ComboBox(entries)
   308     entries.find(_.name == logic) match {
   309       case None =>
   310       case Some(entry) => component.selection.item = entry
   311     }
   312     component.tooltip = "Isabelle logic image"
   313     component
   314   }
   315 
   316   def start_session()
   317   {
   318     val timeout = Time_Property("startup-timeout", Time.seconds(10)) max Time.seconds(5)
   319     val modes = space_explode(',', Isabelle_System.getenv("JEDIT_PRINT_MODE")).map("-m" + _)
   320     val logic = {
   321       val logic = Property("logic")
   322       if (logic != null && logic != "") logic
   323       else Isabelle.default_logic()
   324     }
   325     session.start(timeout, modes ::: List(logic))
   326   }
   327 
   328 
   329   /* convenience actions */
   330 
   331   private def user_input(text_area: JEditTextArea, s1: String, s2: String = "")
   332   {
   333     s1.foreach(text_area.userInput(_))
   334     s2.foreach(text_area.userInput(_))
   335     s2.foreach(_ => text_area.goToPrevCharacter(false))
   336   }
   337 
   338   def input_sub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sub_decoded)
   339   def input_sup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sup_decoded)
   340   def input_isub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isub_decoded)
   341   def input_isup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isup_decoded)
   342   def input_bsub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsub_decoded, Symbol.esub_decoded)
   343   def input_bsup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsup_decoded, Symbol.esup_decoded)
   344   def input_bold(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bold_decoded)
   345 }
   346 
   347 
   348 class Plugin extends EBPlugin
   349 {
   350   /* editor file store */
   351 
   352   private val file_store = new Session.File_Store
   353   {
   354     def append(master_dir: String, source_path: Path): String =
   355     {
   356       val path = source_path.expand
   357       if (path.is_absolute) Isabelle_System.platform_path(path)
   358       else {
   359         val vfs = VFSManager.getVFSForPath(master_dir)
   360         if (vfs.isInstanceOf[FileVFS])
   361           MiscUtilities.resolveSymlinks(
   362             vfs.constructPath(master_dir, Isabelle_System.platform_path(path)))
   363         else vfs.constructPath(master_dir, Isabelle_System.standard_path(path))
   364       }
   365     }
   366 
   367     def require(canonical_name: String)
   368     {
   369       Swing_Thread.later {
   370         if (!Isabelle.jedit_buffers().exists(_.getSymlinkPath == canonical_name))
   371           jEdit.openFile(null: View, canonical_name)
   372       }
   373     }
   374   }
   375 
   376 
   377   /* session manager */
   378 
   379   private lazy val delay_load =
   380     Swing_Thread.delay_last(Isabelle.session.load_delay) {
   381       def ask(files: List[String]): Boolean = Swing_Thread.now
   382         {
   383           val file_list = new scala.swing.TextArea(files.mkString("\n"))
   384           file_list.editable = false
   385           val answer =
   386             Library.confirm_dialog(jEdit.getActiveView(),
   387             "Auto loading of required files",
   388             JOptionPane.YES_NO_OPTION,
   389             "The following files are required to resolve theory imports.",
   390             "Reload now?",
   391             file_list)
   392           answer == 0
   393         }
   394 
   395       Isabelle.session.check_loaded_files(ask _)
   396     }
   397 
   398   private val session_manager = actor {
   399     loop {
   400       react {
   401         case phase: Session.Phase =>
   402           phase match {
   403             case Session.Failed =>
   404               Swing_Thread.now {
   405                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   406                 text.editable = false
   407                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   408               }
   409 
   410             case Session.Ready =>
   411               Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   412               delay_load()
   413 
   414             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   415             case _ =>
   416           }
   417         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   418       }
   419     }
   420   }
   421 
   422 
   423   /* main plugin plumbing */
   424 
   425   override def handleMessage(message: EBMessage)
   426   {
   427     Swing_Thread.assert()
   428     message match {
   429       case msg: EditorStarted =>
   430         Isabelle.check_jvm()
   431         if (Isabelle.Boolean_Property("auto-start"))
   432           Isabelle.start_session()
   433 
   434       case msg: BufferUpdate
   435       if msg.getWhat == BufferUpdate.LOADED =>
   436         if (Isabelle.session.is_ready) {
   437           val buffer = msg.getBuffer
   438           if (buffer != null) Isabelle.init_model(buffer)
   439           delay_load()
   440         }
   441 
   442       case msg: EditPaneUpdate
   443       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   444           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   445           msg.getWhat == EditPaneUpdate.CREATED ||
   446           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   447         val edit_pane = msg.getEditPane
   448         val buffer = edit_pane.getBuffer
   449         val text_area = edit_pane.getTextArea
   450 
   451         if (buffer != null && text_area != null) {
   452           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   453               msg.getWhat == EditPaneUpdate.CREATED) {
   454             if (Isabelle.session.is_ready)
   455               Isabelle.init_view(buffer, text_area)
   456           }
   457           else Isabelle.exit_view(buffer, text_area)
   458         }
   459 
   460       case msg: PropertiesChanged =>
   461         Swing_Thread.now { Isabelle.setup_tooltips() }
   462         Isabelle.session.global_settings.event(Session.Global_Settings)
   463 
   464       case _ =>
   465     }
   466   }
   467 
   468   override def start()
   469   {
   470     Isabelle.plugin = this
   471     Isabelle.setup_tooltips()
   472     Isabelle_System.init()
   473     Isabelle_System.install_fonts()
   474     Isabelle.session = new Session(file_store)
   475     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   476     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   477       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   478     Isabelle.session.phase_changed += session_manager
   479   }
   480 
   481   override def stop()
   482   {
   483     Isabelle.session.phase_changed -= session_manager
   484     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   485     Isabelle.session.stop()
   486   }
   487 }