src/Tools/jEdit/src/plugin.scala
author wenzelm
Mon Aug 29 21:55:49 2011 +0200 (2011-08-29)
changeset 44574 24444588fddd
parent 44573 51f8895b9ad9
child 44577 96b6388d06c4
permissions -rw-r--r--
actual auto loading of required files;
eliminated File_Store in favour of Thy_Load;
tuned;
     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 import javax.swing.text.Segment
    17 
    18 import scala.collection.mutable
    19 import scala.swing.ComboBox
    20 import scala.util.Sorting
    21 
    22 import org.gjt.sp.jedit.{jEdit, GUIUtilities, EBMessage, EBPlugin,
    23   Buffer, EditPane, MiscUtilities, ServiceManager, View}
    24 import org.gjt.sp.jedit.buffer.JEditBuffer
    25 import org.gjt.sp.jedit.textarea.{JEditTextArea, TextArea}
    26 import org.gjt.sp.jedit.syntax.{Token => JEditToken, ModeProvider}
    27 import org.gjt.sp.jedit.msg.{EditorStarted, BufferUpdate, EditPaneUpdate, PropertiesChanged}
    28 import org.gjt.sp.jedit.gui.DockableWindowManager
    29 import org.gjt.sp.jedit.io.{VFS, FileVFS, VFSManager}
    30 
    31 import org.gjt.sp.util.SyntaxUtilities
    32 import org.gjt.sp.util.Log
    33 
    34 import scala.actors.Actor
    35 import Actor._
    36 
    37 
    38 object Isabelle
    39 {
    40   /* plugin instance */
    41 
    42   var plugin: Plugin = null
    43   var session: Session = null
    44 
    45 
    46   /* properties */
    47 
    48   val OPTION_PREFIX = "options.isabelle."
    49 
    50   object Property
    51   {
    52     def apply(name: String): String =
    53       jEdit.getProperty(OPTION_PREFIX + name)
    54     def apply(name: String, default: String): String =
    55       jEdit.getProperty(OPTION_PREFIX + name, default)
    56     def update(name: String, value: String) =
    57       jEdit.setProperty(OPTION_PREFIX + name, value)
    58   }
    59 
    60   object Boolean_Property
    61   {
    62     def apply(name: String): Boolean =
    63       jEdit.getBooleanProperty(OPTION_PREFIX + name)
    64     def apply(name: String, default: Boolean): Boolean =
    65       jEdit.getBooleanProperty(OPTION_PREFIX + name, default)
    66     def update(name: String, value: Boolean) =
    67       jEdit.setBooleanProperty(OPTION_PREFIX + name, value)
    68   }
    69 
    70   object Int_Property
    71   {
    72     def apply(name: String): Int =
    73       jEdit.getIntegerProperty(OPTION_PREFIX + name)
    74     def apply(name: String, default: Int): Int =
    75       jEdit.getIntegerProperty(OPTION_PREFIX + name, default)
    76     def update(name: String, value: Int) =
    77       jEdit.setIntegerProperty(OPTION_PREFIX + name, value)
    78   }
    79 
    80   object Double_Property
    81   {
    82     def apply(name: String): Double =
    83       jEdit.getDoubleProperty(OPTION_PREFIX + name, 0.0)
    84     def apply(name: String, default: Double): Double =
    85       jEdit.getDoubleProperty(OPTION_PREFIX + name, default)
    86     def update(name: String, value: Double) =
    87       jEdit.setDoubleProperty(OPTION_PREFIX + name, value)
    88   }
    89 
    90   object Time_Property
    91   {
    92     def apply(name: String): Time =
    93       Time.seconds(Double_Property(name))
    94     def apply(name: String, default: Time): Time =
    95       Time.seconds(Double_Property(name, default.seconds))
    96     def update(name: String, value: Time) =
    97       Double_Property.update(name, value.seconds)
    98   }
    99 
   100 
   101   /* font */
   102 
   103   def font_family(): String = jEdit.getProperty("view.font")
   104 
   105   def font_size(): Float =
   106     (jEdit.getIntegerProperty("view.fontsize", 16) *
   107       Int_Property("relative-font-size", 100)).toFloat / 100
   108 
   109 
   110   /* text area ranges */
   111 
   112   sealed case class Gfx_Range(val x: Int, val y: Int, val length: Int)
   113 
   114   def gfx_range(text_area: TextArea, range: Text.Range): Option[Gfx_Range] =
   115   {
   116     val p = text_area.offsetToXY(range.start)
   117     val q = text_area.offsetToXY(range.stop)
   118     if (p != null && q != null && p.y == q.y) Some(new Gfx_Range(p.x, p.y, q.x - p.x))
   119     else None
   120   }
   121 
   122 
   123   /* tooltip markup */
   124 
   125   def tooltip(text: String): String =
   126     "<html><pre style=\"font-family: " + font_family() + "; font-size: " +
   127         Int_Property("tooltip-font-size", 10).toString + "px; \">" +  // FIXME proper scaling (!?)
   128       HTML.encode(text) + "</pre></html>"
   129 
   130   def tooltip_dismiss_delay(): Time =
   131     Time_Property("tooltip-dismiss-delay", Time.seconds(8.0)) max Time.seconds(0.5)
   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   /* main jEdit components */
   166 
   167   def jedit_buffers(): Iterator[Buffer] = jEdit.getBuffers().iterator
   168 
   169   def jedit_views(): Iterator[View] = jEdit.getViews().iterator
   170 
   171   def jedit_text_areas(view: View): Iterator[JEditTextArea] =
   172     view.getEditPanes().iterator.map(_.getTextArea)
   173 
   174   def jedit_text_areas(): Iterator[JEditTextArea] =
   175     jedit_views().flatMap(jedit_text_areas(_))
   176 
   177   def jedit_text_areas(buffer: JEditBuffer): Iterator[JEditTextArea] =
   178     jedit_text_areas().filter(_.getBuffer == buffer)
   179 
   180   def buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   181   {
   182     try { buffer.readLock(); body }
   183     finally { buffer.readUnlock() }
   184   }
   185 
   186   def swing_buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   187     Swing_Thread.now { buffer_lock(buffer) { body } }
   188 
   189   def buffer_text(buffer: JEditBuffer): String =
   190     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   191 
   192   def buffer_name(buffer: Buffer): String = buffer.getSymlinkPath
   193 
   194   def buffer_path(buffer: Buffer): (String, String) =
   195     (buffer.getDirectory, buffer_name(buffer))
   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   /* theory files via editor document model */
   351 
   352   val thy_load = new Thy_Load
   353   {
   354     private var loaded_theories: Set[String] = Set()
   355 
   356     def register_thy(thy_name: String)
   357     {
   358       synchronized { loaded_theories += thy_name }
   359     }
   360     def is_loaded(thy_name: String): Boolean =
   361       synchronized { loaded_theories.contains(thy_name) }
   362 
   363     def append(master_dir: String, source_path: Path): String =
   364     {
   365       val path = source_path.expand
   366       if (path.is_absolute) Isabelle_System.platform_path(path)
   367       else {
   368         val vfs = VFSManager.getVFSForPath(master_dir)
   369         if (vfs.isInstanceOf[FileVFS])
   370           MiscUtilities.resolveSymlinks(
   371             vfs.constructPath(master_dir, Isabelle_System.platform_path(path)))
   372         else vfs.constructPath(master_dir, Isabelle_System.standard_path(path))
   373       }
   374     }
   375 
   376     def check_thy(node_name: String): Thy_Header =
   377     {
   378       Swing_Thread.now {
   379         Isabelle.jedit_buffers().find(buffer => Isabelle.buffer_name(buffer) == node_name) match {
   380           case Some(buffer) =>
   381             Isabelle.buffer_lock(buffer) {
   382               val text = new Segment
   383               buffer.getText(0, buffer.getLength, text)
   384               Some(Thy_Header.read(text))
   385             }
   386           case None => None
   387         }
   388       } getOrElse {
   389         val file = new File(node_name)  // FIXME load URL via jEdit VFS (!?)
   390         if (!file.exists || !file.isFile) error("No such file: " + quote(file.toString))
   391         Thy_Header.read(file)
   392       }
   393     }
   394   }
   395 
   396   val thy_info = new Thy_Info(thy_load)
   397 
   398   private lazy val delay_load =
   399     Swing_Thread.delay_last(Isabelle.session.load_delay)
   400     {
   401       val buffers = Isabelle.jedit_buffers().toList
   402       def loaded_buffer(name: String): Boolean =
   403         buffers.exists(buffer => Isabelle.buffer_name(buffer) == name)
   404 
   405       val thys =
   406         for (buffer <- buffers; model <- Isabelle.document_model(buffer))
   407           yield (model.master_dir, model.thy_name)
   408       val files = thy_info.dependencies(thys).map(_._1).filterNot(loaded_buffer _)
   409 
   410       val do_load = !files.isEmpty &&
   411         {
   412           val files_sorted = { val a = files.toArray; Sorting.quickSort(a); a.toList }
   413           val files_text = new scala.swing.TextArea(files_sorted.mkString("\n"))
   414           files_text.editable = false
   415           Library.confirm_dialog(jEdit.getActiveView(),
   416             "Auto loading of required files",
   417             JOptionPane.YES_NO_OPTION,
   418             "The following files are required to resolve theory imports.  Reload now?",
   419             files_text) == 0
   420         }
   421       if (do_load)
   422         for (file <- files if !loaded_buffer(file))
   423           jEdit.openFile(null: View, file)
   424     }
   425 
   426 
   427   /* session manager */
   428 
   429   private val session_manager = actor {
   430     loop {
   431       react {
   432         case phase: Session.Phase =>
   433           phase match {
   434             case Session.Failed =>
   435               Swing_Thread.now {
   436                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   437                 text.editable = false
   438                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   439               }
   440 
   441             case Session.Ready =>
   442               Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   443               delay_load()
   444 
   445             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   446             case _ =>
   447           }
   448         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   449       }
   450     }
   451   }
   452 
   453 
   454   /* main plugin plumbing */
   455 
   456   override def handleMessage(message: EBMessage)
   457   {
   458     Swing_Thread.assert()
   459     message match {
   460       case msg: EditorStarted =>
   461         Isabelle.check_jvm()
   462         if (Isabelle.Boolean_Property("auto-start"))
   463           Isabelle.start_session()
   464 
   465       case msg: BufferUpdate
   466       if msg.getWhat == BufferUpdate.LOADED =>
   467         if (Isabelle.session.is_ready) {
   468           val buffer = msg.getBuffer
   469           if (buffer != null) Isabelle.init_model(buffer)
   470           delay_load()
   471         }
   472 
   473       case msg: EditPaneUpdate
   474       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   475           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   476           msg.getWhat == EditPaneUpdate.CREATED ||
   477           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   478         val edit_pane = msg.getEditPane
   479         val buffer = edit_pane.getBuffer
   480         val text_area = edit_pane.getTextArea
   481 
   482         if (buffer != null && text_area != null) {
   483           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   484               msg.getWhat == EditPaneUpdate.CREATED) {
   485             if (Isabelle.session.is_ready)
   486               Isabelle.init_view(buffer, text_area)
   487           }
   488           else Isabelle.exit_view(buffer, text_area)
   489         }
   490 
   491       case msg: PropertiesChanged =>
   492         Swing_Thread.now { Isabelle.setup_tooltips() }
   493         Isabelle.session.global_settings.event(Session.Global_Settings)
   494 
   495       case _ =>
   496     }
   497   }
   498 
   499   override def start()
   500   {
   501     Isabelle.plugin = this
   502     Isabelle.setup_tooltips()
   503     Isabelle_System.init()
   504     Isabelle_System.install_fonts()
   505     Isabelle.session = new Session(thy_load)
   506     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   507     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   508       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   509     Isabelle.session.phase_changed += session_manager
   510   }
   511 
   512   override def stop()
   513   {
   514     Isabelle.session.phase_changed -= session_manager
   515     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   516     Isabelle.session.stop()
   517   }
   518 }