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