src/Tools/jEdit/src/plugin.scala
author wenzelm
Wed Aug 31 14:39:41 2011 +0200 (2011-08-31)
changeset 44606 b625650aa2db
parent 44580 3bc9a215a56d
child 44609 6ec4a5eb2fc0
permissions -rw-r--r--
improved auto loading: selectable file list;
     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 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   /* buffers */
   163 
   164   def swing_buffer_lock[A](buffer: JEditBuffer)(body: => A): A =
   165     Swing_Thread.now { buffer_lock(buffer) { body } }
   166 
   167   def buffer_text(buffer: JEditBuffer): String =
   168     buffer_lock(buffer) { buffer.getText(0, buffer.getLength) }
   169 
   170   def buffer_name(buffer: Buffer): String = buffer.getSymlinkPath
   171 
   172   def buffer_path(buffer: Buffer): (String, String) =
   173     (buffer.getDirectory, buffer_name(buffer))
   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 (master_dir, path) = buffer_path(buffer)
   221             Thy_Header.thy_name(path) match {
   222               case Some(name) =>
   223                 Some(Document_Model.init(session, buffer, master_dir, path, name))
   224               case None => None
   225             }
   226         }
   227       if (opt_model.isDefined) {
   228         for (text_area <- jedit_text_areas(buffer)) {
   229           if (document_view(text_area).map(_.model) != opt_model)
   230             Document_View.init(opt_model.get, text_area)
   231         }
   232       }
   233     }
   234   }
   235 
   236   def exit_model(buffer: Buffer)
   237   {
   238     swing_buffer_lock(buffer) {
   239       jedit_text_areas(buffer).foreach(Document_View.exit)
   240       Document_Model.exit(buffer)
   241     }
   242   }
   243 
   244   def init_view(buffer: Buffer, text_area: JEditTextArea)
   245   {
   246     swing_buffer_lock(buffer) {
   247       document_model(buffer) match {
   248         case Some(model) => Document_View.init(model, text_area)
   249         case None =>
   250       }
   251     }
   252   }
   253 
   254   def exit_view(buffer: Buffer, text_area: JEditTextArea)
   255   {
   256     swing_buffer_lock(buffer) {
   257       Document_View.exit(text_area)
   258     }
   259   }
   260 
   261 
   262   /* dockable windows */
   263 
   264   private def wm(view: View): DockableWindowManager = view.getDockableWindowManager
   265 
   266   def docked_session(view: View): Option[Session_Dockable] =
   267     wm(view).getDockableWindow("isabelle-session") match {
   268       case dockable: Session_Dockable => Some(dockable)
   269       case _ => None
   270     }
   271 
   272   def docked_output(view: View): Option[Output_Dockable] =
   273     wm(view).getDockableWindow("isabelle-output") match {
   274       case dockable: Output_Dockable => Some(dockable)
   275       case _ => None
   276     }
   277 
   278   def docked_raw_output(view: View): Option[Raw_Output_Dockable] =
   279     wm(view).getDockableWindow("isabelle-raw-output") match {
   280       case dockable: Raw_Output_Dockable => Some(dockable)
   281       case _ => None
   282     }
   283 
   284   def docked_protocol(view: View): Option[Protocol_Dockable] =
   285     wm(view).getDockableWindow("isabelle-protocol") match {
   286       case dockable: Protocol_Dockable => Some(dockable)
   287       case _ => None
   288     }
   289 
   290 
   291   /* logic image */
   292 
   293   def default_logic(): String =
   294   {
   295     val logic = Isabelle_System.getenv("JEDIT_LOGIC")
   296     if (logic != "") logic
   297     else Isabelle_System.getenv_strict("ISABELLE_LOGIC")
   298   }
   299 
   300   class Logic_Entry(val name: String, val description: String)
   301   {
   302     override def toString = description
   303   }
   304 
   305   def logic_selector(logic: String): ComboBox[Logic_Entry] =
   306   {
   307     val entries =
   308       new Logic_Entry("", "default (" + default_logic() + ")") ::
   309         Isabelle_System.find_logics().map(name => new Logic_Entry(name, name))
   310     val component = new ComboBox(entries)
   311     entries.find(_.name == logic) match {
   312       case None =>
   313       case Some(entry) => component.selection.item = entry
   314     }
   315     component.tooltip = "Isabelle logic image"
   316     component
   317   }
   318 
   319   def start_session()
   320   {
   321     val timeout = Time_Property("startup-timeout", Time.seconds(10)) max Time.seconds(5)
   322     val modes = space_explode(',', Isabelle_System.getenv("JEDIT_PRINT_MODE")).map("-m" + _)
   323     val logic = {
   324       val logic = Property("logic")
   325       if (logic != null && logic != "") logic
   326       else Isabelle.default_logic()
   327     }
   328     session.start(timeout, modes ::: List(logic))
   329   }
   330 
   331 
   332   /* convenience actions */
   333 
   334   private def user_input(text_area: JEditTextArea, s1: String, s2: String = "")
   335   {
   336     s1.foreach(text_area.userInput(_))
   337     s2.foreach(text_area.userInput(_))
   338     s2.foreach(_ => text_area.goToPrevCharacter(false))
   339   }
   340 
   341   def input_sub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sub_decoded)
   342   def input_sup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sup_decoded)
   343   def input_isub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isub_decoded)
   344   def input_isup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isup_decoded)
   345   def input_bsub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsub_decoded, Symbol.esub_decoded)
   346   def input_bsup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsup_decoded, Symbol.esup_decoded)
   347   def input_bold(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bold_decoded)
   348 }
   349 
   350 
   351 class Plugin extends EBPlugin
   352 {
   353   /* theory files */
   354 
   355   val thy_load = new JEdit_Thy_Load
   356   val thy_info = new Thy_Info(thy_load)
   357 
   358   private lazy val delay_load =
   359     Swing_Thread.delay_last(Isabelle.session.load_delay)
   360     {
   361       val buffers = Isabelle.jedit_buffers().toList
   362       def loaded_buffer(name: String): Boolean =
   363         buffers.exists(buffer => Isabelle.buffer_name(buffer) == name)
   364 
   365       val thys =
   366         for (buffer <- buffers; model <- Isabelle.document_model(buffer))
   367           yield (model.master_dir, model.thy_name)
   368       val files = thy_info.dependencies(thys).map(_._1).filterNot(loaded_buffer _)
   369 
   370       if (!files.isEmpty) {
   371         val files_sorted = { val a = files.toArray; Sorting.quickSort(a); a.toList }
   372         val files_list = new ListView(files_sorted)
   373         for (i <- 0 until files_sorted.length)
   374           files_list.selection.indices += i
   375 
   376         val answer =
   377           Library.confirm_dialog(jEdit.getActiveView(),
   378             "Auto loading of required files",
   379             JOptionPane.YES_NO_OPTION,
   380             "The following files are required to resolve theory imports.",
   381             "Reload selected files now?",
   382             new ScrollPane(files_list))
   383         if (answer == 0)
   384           files_list.selection.items foreach (file =>
   385             if (!loaded_buffer(file)) jEdit.openFile(null: View, file))
   386       }
   387     }
   388 
   389 
   390   /* session manager */
   391 
   392   private val session_manager = actor {
   393     loop {
   394       react {
   395         case phase: Session.Phase =>
   396           phase match {
   397             case Session.Failed =>
   398               Swing_Thread.now {
   399                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   400                 text.editable = false
   401                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   402               }
   403 
   404             case Session.Ready =>
   405               Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   406               delay_load()
   407 
   408             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   409             case _ =>
   410           }
   411         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   412       }
   413     }
   414   }
   415 
   416 
   417   /* main plugin plumbing */
   418 
   419   override def handleMessage(message: EBMessage)
   420   {
   421     Swing_Thread.assert()
   422     message match {
   423       case msg: EditorStarted =>
   424         Isabelle.check_jvm()
   425         if (Isabelle.Boolean_Property("auto-start"))
   426           Isabelle.start_session()
   427 
   428       case msg: BufferUpdate
   429       if msg.getWhat == BufferUpdate.LOADED =>
   430         if (Isabelle.session.is_ready) {
   431           val buffer = msg.getBuffer
   432           if (buffer != null) Isabelle.init_model(buffer)
   433           delay_load()
   434         }
   435 
   436       case msg: EditPaneUpdate
   437       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   438           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   439           msg.getWhat == EditPaneUpdate.CREATED ||
   440           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   441         val edit_pane = msg.getEditPane
   442         val buffer = edit_pane.getBuffer
   443         val text_area = edit_pane.getTextArea
   444 
   445         if (buffer != null && text_area != null) {
   446           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   447               msg.getWhat == EditPaneUpdate.CREATED) {
   448             if (Isabelle.session.is_ready)
   449               Isabelle.init_view(buffer, text_area)
   450           }
   451           else Isabelle.exit_view(buffer, text_area)
   452         }
   453 
   454       case msg: PropertiesChanged =>
   455         Swing_Thread.now { Isabelle.setup_tooltips() }
   456         Isabelle.session.global_settings.event(Session.Global_Settings)
   457 
   458       case _ =>
   459     }
   460   }
   461 
   462   override def start()
   463   {
   464     Isabelle.plugin = this
   465     Isabelle.setup_tooltips()
   466     Isabelle_System.init()
   467     Isabelle_System.install_fonts()
   468     Isabelle.session = new Session(thy_load)
   469     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   470     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   471       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   472     Isabelle.session.phase_changed += session_manager
   473   }
   474 
   475   override def stop()
   476   {
   477     Isabelle.session.phase_changed -= session_manager
   478     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   479     Isabelle.session.stop()
   480   }
   481 }