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