src/Tools/jEdit/src/plugin.scala
author wenzelm
Mon Aug 22 16:12:23 2011 +0200 (2011-08-22)
changeset 44379 1079ab6b342b
parent 44238 36120feb70ed
child 44434 3b9b684bfa6f
permissions -rw-r--r--
added official Text.Range.Ordering;
some support for text perspective;
     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 
    16 import scala.collection.mutable
    17 import scala.swing.ComboBox
    18 
    19 import org.gjt.sp.jedit.{jEdit, GUIUtilities, EBMessage, EBPlugin,
    20   Buffer, EditPane, MiscUtilities, 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 import org.gjt.sp.jedit.io.{VFS, FileVFS, VFSManager}
    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_path(buffer: Buffer): (String, String) =
   190   {
   191     val master_dir = buffer.getDirectory
   192     val path = buffer.getSymlinkPath
   193     (master_dir, path)
   194   }
   195 
   196 
   197   /* document model and view */
   198 
   199   def document_model(buffer: Buffer): Option[Document_Model] = Document_Model(buffer)
   200   def document_view(text_area: JEditTextArea): Option[Document_View] = Document_View(text_area)
   201 
   202   def document_views(buffer: Buffer): List[Document_View] =
   203     for {
   204       text_area <- jedit_text_areas(buffer).toList
   205       val doc_view = document_view(text_area)
   206       if doc_view.isDefined
   207     } yield doc_view.get
   208 
   209   def init_model(buffer: Buffer)
   210   {
   211     swing_buffer_lock(buffer) {
   212       val opt_model =
   213         document_model(buffer) match {
   214           case Some(model) => Some(model)
   215           case None =>
   216             val (master_dir, path) = buffer_path(buffer)
   217             Thy_Header.thy_name(path) match {
   218               case Some(name) =>
   219                 Some(Document_Model.init(session, buffer, master_dir, path, name))
   220               case None => None
   221             }
   222         }
   223       if (opt_model.isDefined) {
   224         for (text_area <- jedit_text_areas(buffer)) {
   225           if (document_view(text_area).map(_.model) != opt_model)
   226             Document_View.init(opt_model.get, text_area)
   227         }
   228       }
   229     }
   230   }
   231 
   232   def exit_model(buffer: Buffer)
   233   {
   234     swing_buffer_lock(buffer) {
   235       jedit_text_areas(buffer).foreach(Document_View.exit)
   236       Document_Model.exit(buffer)
   237     }
   238   }
   239 
   240   def init_view(buffer: Buffer, text_area: JEditTextArea)
   241   {
   242     swing_buffer_lock(buffer) {
   243       document_model(buffer) match {
   244         case Some(model) => Document_View.init(model, text_area)
   245         case None =>
   246       }
   247     }
   248   }
   249 
   250   def exit_view(buffer: Buffer, text_area: JEditTextArea)
   251   {
   252     swing_buffer_lock(buffer) {
   253       Document_View.exit(text_area)
   254     }
   255   }
   256 
   257 
   258   /* dockable windows */
   259 
   260   private def wm(view: View): DockableWindowManager = view.getDockableWindowManager
   261 
   262   def docked_session(view: View): Option[Session_Dockable] =
   263     wm(view).getDockableWindow("isabelle-session") match {
   264       case dockable: Session_Dockable => Some(dockable)
   265       case _ => None
   266     }
   267 
   268   def docked_output(view: View): Option[Output_Dockable] =
   269     wm(view).getDockableWindow("isabelle-output") match {
   270       case dockable: Output_Dockable => Some(dockable)
   271       case _ => None
   272     }
   273 
   274   def docked_raw_output(view: View): Option[Raw_Output_Dockable] =
   275     wm(view).getDockableWindow("isabelle-raw-output") match {
   276       case dockable: Raw_Output_Dockable => Some(dockable)
   277       case _ => None
   278     }
   279 
   280   def docked_protocol(view: View): Option[Protocol_Dockable] =
   281     wm(view).getDockableWindow("isabelle-protocol") match {
   282       case dockable: Protocol_Dockable => Some(dockable)
   283       case _ => None
   284     }
   285 
   286 
   287   /* logic image */
   288 
   289   def default_logic(): String =
   290   {
   291     val logic = Isabelle_System.getenv("JEDIT_LOGIC")
   292     if (logic != "") logic
   293     else Isabelle_System.getenv_strict("ISABELLE_LOGIC")
   294   }
   295 
   296   class Logic_Entry(val name: String, val description: String)
   297   {
   298     override def toString = description
   299   }
   300 
   301   def logic_selector(logic: String): ComboBox[Logic_Entry] =
   302   {
   303     val entries =
   304       new Logic_Entry("", "default (" + default_logic() + ")") ::
   305         Isabelle_System.find_logics().map(name => new Logic_Entry(name, name))
   306     val component = new ComboBox(entries)
   307     entries.find(_.name == logic) match {
   308       case None =>
   309       case Some(entry) => component.selection.item = entry
   310     }
   311     component.tooltip = "Isabelle logic image"
   312     component
   313   }
   314 
   315   def start_session()
   316   {
   317     val timeout = Time_Property("startup-timeout", Time.seconds(10)) max Time.seconds(5)
   318     val modes = space_explode(',', Isabelle_System.getenv("JEDIT_PRINT_MODE")).map("-m" + _)
   319     val logic = {
   320       val logic = Property("logic")
   321       if (logic != null && logic != "") logic
   322       else Isabelle.default_logic()
   323     }
   324     session.start(timeout, modes ::: List(logic))
   325   }
   326 
   327 
   328   /* convenience actions */
   329 
   330   private def user_input(text_area: JEditTextArea, s1: String, s2: String = "")
   331   {
   332     s1.foreach(text_area.userInput(_))
   333     s2.foreach(text_area.userInput(_))
   334     s2.foreach(_ => text_area.goToPrevCharacter(false))
   335   }
   336 
   337   def input_sub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sub_decoded)
   338   def input_sup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.sup_decoded)
   339   def input_isub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isub_decoded)
   340   def input_isup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.isup_decoded)
   341   def input_bsub(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsub_decoded, Symbol.esub_decoded)
   342   def input_bsup(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bsup_decoded, Symbol.esup_decoded)
   343   def input_bold(text_area: JEditTextArea): Unit = user_input(text_area, Symbol.bold_decoded)
   344 }
   345 
   346 
   347 class Plugin extends EBPlugin
   348 {
   349   /* editor file store */
   350 
   351   private val file_store = new Session.File_Store
   352   {
   353     def append(master_dir: String, source_path: Path): String =
   354     {
   355       val path = source_path.expand
   356       if (path.is_absolute) Isabelle_System.platform_path(path)
   357       else {
   358         val vfs = VFSManager.getVFSForPath(master_dir)
   359         if (vfs.isInstanceOf[FileVFS])
   360           MiscUtilities.resolveSymlinks(
   361             vfs.constructPath(master_dir, Isabelle_System.platform_path(path)))
   362         else vfs.constructPath(master_dir, Isabelle_System.standard_path(path))
   363       }
   364     }
   365 
   366     def require(canonical_name: String)
   367     {
   368       Swing_Thread.later {
   369         if (!Isabelle.jedit_buffers().exists(_.getSymlinkPath == canonical_name))
   370           jEdit.openFile(null: View, canonical_name)
   371       }
   372     }
   373   }
   374 
   375 
   376   /* session manager */
   377 
   378   private val session_manager = actor {
   379     loop {
   380       react {
   381         case phase: Session.Phase =>
   382           phase match {
   383             case Session.Failed =>
   384               Swing_Thread.now {
   385                 val text = new scala.swing.TextArea(Isabelle.session.syslog())
   386                 text.editable = false
   387                 Library.error_dialog(jEdit.getActiveView, "Failed to start Isabelle process", text)
   388               }
   389 
   390             case Session.Ready => Isabelle.jedit_buffers.foreach(Isabelle.init_model)
   391             case Session.Shutdown => Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   392             case _ =>
   393           }
   394         case bad => System.err.println("session_manager: ignoring bad message " + bad)
   395       }
   396     }
   397   }
   398 
   399 
   400   /* main plugin plumbing */
   401 
   402   override def handleMessage(message: EBMessage)
   403   {
   404     Swing_Thread.assert()
   405     message match {
   406       case msg: EditorStarted =>
   407         Isabelle.check_jvm()
   408         if (Isabelle.Boolean_Property("auto-start"))
   409           Isabelle.start_session()
   410 
   411       case msg: BufferUpdate
   412       if msg.getWhat == BufferUpdate.PROPERTIES_CHANGED =>
   413 
   414         val buffer = msg.getBuffer
   415         if (buffer != null && Isabelle.session.is_ready)
   416           Isabelle.init_model(buffer)
   417 
   418       case msg: EditPaneUpdate
   419       if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGING ||
   420           msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   421           msg.getWhat == EditPaneUpdate.CREATED ||
   422           msg.getWhat == EditPaneUpdate.DESTROYED) =>
   423 
   424         val edit_pane = msg.getEditPane
   425         val buffer = edit_pane.getBuffer
   426         val text_area = edit_pane.getTextArea
   427 
   428         if (buffer != null && text_area != null) {
   429           if (msg.getWhat == EditPaneUpdate.BUFFER_CHANGED ||
   430               msg.getWhat == EditPaneUpdate.CREATED) {
   431             if (Isabelle.session.is_ready)
   432               Isabelle.init_view(buffer, text_area)
   433           }
   434           else Isabelle.exit_view(buffer, text_area)
   435         }
   436 
   437       case msg: PropertiesChanged =>
   438         Swing_Thread.now { Isabelle.setup_tooltips() }
   439         Isabelle.session.global_settings.event(Session.Global_Settings)
   440 
   441       case _ =>
   442     }
   443   }
   444 
   445   override def start()
   446   {
   447     Isabelle.plugin = this
   448     Isabelle.setup_tooltips()
   449     Isabelle_System.init()
   450     Isabelle_System.install_fonts()
   451     Isabelle.session = new Session(file_store)
   452     SyntaxUtilities.setStyleExtender(new Token_Markup.Style_Extender)
   453     if (ModeProvider.instance.isInstanceOf[ModeProvider])
   454       ModeProvider.instance = new Token_Markup.Mode_Provider(ModeProvider.instance)
   455     Isabelle.session.phase_changed += session_manager
   456   }
   457 
   458   override def stop()
   459   {
   460     Isabelle.session.phase_changed -= session_manager
   461     Isabelle.jedit_buffers.foreach(Isabelle.exit_model)
   462     Isabelle.session.stop()
   463   }
   464 }