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