src/Pure/System/isabelle_system.scala
author wenzelm
Thu Aug 02 12:36:54 2012 +0200 (2012-08-02)
changeset 48646 91281e9472d8
parent 48550 97592027a2a8
child 48923 a2df77fcf1eb
permissions -rw-r--r--
more official command specifications, including source position;
     1 /*  Title:      Pure/System/isabelle_system.scala
     2     Author:     Makarius
     3 
     4 Fundamental Isabelle system environment: quasi-static module with
     5 optional init operation.
     6 */
     7 
     8 package isabelle
     9 
    10 import java.lang.System
    11 import java.util.regex.Pattern
    12 import java.util.Locale
    13 import java.io.{InputStream, OutputStream, File => JFile, BufferedReader, InputStreamReader,
    14   BufferedWriter, OutputStreamWriter, IOException}
    15 import java.awt.{GraphicsEnvironment, Font}
    16 import java.awt.font.TextAttribute
    17 
    18 import scala.io.Source
    19 import scala.util.matching.Regex
    20 import scala.collection.mutable
    21 
    22 
    23 object Isabelle_System
    24 {
    25   /** implicit state **/
    26 
    27   private case class State(standard_system: Standard_System, settings: Map[String, String])
    28 
    29   @volatile private var _state: Option[State] = None
    30 
    31   private def check_state(): State =
    32   {
    33     if (_state.isEmpty) init()  // unsynchronized check
    34     _state.get
    35   }
    36 
    37   def standard_system: Standard_System = check_state().standard_system
    38   def settings: Map[String, String] = check_state().settings
    39 
    40   /*
    41     isabelle_home precedence:
    42       (1) this_isabelle_home as explicit argument
    43       (2) ISABELLE_HOME process environment variable (e.g. inherited from running isabelle tool)
    44       (3) isabelle.home system property (e.g. via JVM application boot process)
    45   */
    46   def init(this_isabelle_home: String = null) = synchronized {
    47     if (_state.isEmpty) {
    48       import scala.collection.JavaConversions._
    49 
    50       val standard_system = new Standard_System
    51       val settings =
    52       {
    53         val env0 = sys.env + ("ISABELLE_JDK_HOME" -> standard_system.this_jdk_home())
    54 
    55         val user_home = System.getProperty("user.home")
    56         val env =
    57           if (user_home == null || env0.isDefinedAt("HOME")) env0
    58           else env0 + ("HOME" -> user_home)
    59 
    60         val isabelle_home =
    61           if (this_isabelle_home != null) this_isabelle_home
    62           else
    63             env.get("ISABELLE_HOME") match {
    64               case None | Some("") =>
    65                 val path = System.getProperty("isabelle.home")
    66                 if (path == null || path == "") error("Unknown Isabelle home directory")
    67                 else path
    68               case Some(path) => path
    69             }
    70 
    71           File.with_tmp_file("settings") { dump =>
    72               val shell_prefix =
    73                 if (Platform.is_windows) List(standard_system.platform_root + "\\bin\\bash", "-l")
    74                 else Nil
    75               val cmdline =
    76                 shell_prefix ::: List(isabelle_home + "/bin/isabelle", "getenv", "-d", dump.toString)
    77               val (output, rc) = Standard_System.raw_exec(null, env, true, cmdline: _*)
    78               if (rc != 0) error(output)
    79 
    80               val entries =
    81                 (for (entry <- File.read(dump) split "\0" if entry != "") yield {
    82                   val i = entry.indexOf('=')
    83                   if (i <= 0) (entry -> "")
    84                   else (entry.substring(0, i) -> entry.substring(i + 1))
    85                 }).toMap
    86               entries + ("PATH" -> entries("PATH_JVM")) - "PATH_JVM"
    87             }
    88           }
    89       _state = Some(State(standard_system, settings))
    90     }
    91   }
    92 
    93 
    94   /* getenv */
    95 
    96   def getenv(name: String): String = settings.getOrElse(name, "")
    97 
    98   def getenv_strict(name: String): String =
    99   {
   100     val value = getenv(name)
   101     if (value != "") value else error("Undefined environment variable: " + name)
   102   }
   103 
   104 
   105   /** file-system operations **/
   106 
   107   /* path specifications */
   108 
   109   def standard_path(path: Path): String = path.expand.implode
   110 
   111   def platform_path(path: Path): String = standard_system.jvm_path(standard_path(path))
   112   def platform_file(path: Path): JFile = new JFile(platform_path(path))
   113 
   114   def platform_file_url(raw_path: Path): String =
   115   {
   116     val path = raw_path.expand
   117     require(path.is_absolute)
   118     val s = platform_path(path).replaceAll(" ", "%20")
   119     if (!Platform.is_windows) "file://" + s
   120     else if (s.startsWith("\\\\")) "file:" + s.replace('\\', '/')
   121     else "file:///" + s.replace('\\', '/')
   122   }
   123 
   124   def posix_path(jvm_path: String): String = standard_system.posix_path(jvm_path)
   125 
   126 
   127   /* source files */
   128 
   129   private def try_file(file: JFile) = if (file.isFile) Some(file) else None
   130 
   131   def source_file(path: Path): Option[JFile] =
   132   {
   133     if (path.is_absolute || path.is_current)
   134       try_file(platform_file(path))
   135     else {
   136       val pure_file = (Path.explode("~~/src/Pure") + path).file
   137       if (pure_file.isFile) Some(pure_file)
   138       else if (getenv("ML_SOURCES") != "") try_file((Path.explode("$ML_SOURCES") + path).file)
   139       else None
   140     }
   141   }
   142 
   143 
   144 
   145   /** external processes **/
   146 
   147   /* plain execute */
   148 
   149   def execute_env(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*): Process =
   150   {
   151     val cmdline =
   152       if (Platform.is_windows) List(standard_system.platform_root + "\\bin\\env.exe") ++ args
   153       else args
   154     val env1 = if (env == null) settings else settings ++ env
   155     Standard_System.raw_execute(cwd, env1, redirect, cmdline: _*)
   156   }
   157 
   158   def execute(redirect: Boolean, args: String*): Process =
   159     execute_env(null, null, redirect, args: _*)
   160 
   161 
   162   /* managed process */
   163 
   164   class Managed_Process(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*)
   165   {
   166     private val params =
   167       List(standard_path(Path.explode("~~/lib/scripts/process")), "group", "-", "no_script")
   168     private val proc = execute_env(cwd, env, redirect, (params ++ args):_*)
   169 
   170 
   171     // channels
   172 
   173     val stdin: BufferedWriter =
   174       new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, Standard_System.charset))
   175 
   176     val stdout: BufferedReader =
   177       new BufferedReader(new InputStreamReader(proc.getInputStream, Standard_System.charset))
   178 
   179     val stderr: BufferedReader =
   180       new BufferedReader(new InputStreamReader(proc.getErrorStream, Standard_System.charset))
   181 
   182 
   183     // signals
   184 
   185     private val pid = stdout.readLine
   186 
   187     private def kill(signal: String): Boolean =
   188     {
   189       execute(true, "kill", "-" + signal, "-" + pid).waitFor
   190       execute(true, "kill", "-0", "-" + pid).waitFor == 0
   191     }
   192 
   193     private def multi_kill(signal: String): Boolean =
   194     {
   195       var running = true
   196       var count = 10
   197       while (running && count > 0) {
   198         if (kill(signal)) {
   199           Thread.sleep(100)
   200           count -= 1
   201         }
   202         else running = false
   203       }
   204       running
   205     }
   206 
   207     def interrupt() { multi_kill("INT") }
   208     def terminate() { multi_kill("INT") && multi_kill("TERM") && kill("KILL"); proc.destroy }
   209 
   210 
   211     // JVM shutdown hook
   212 
   213     private val shutdown_hook = new Thread { override def run = terminate() }
   214 
   215     try { Runtime.getRuntime.addShutdownHook(shutdown_hook) }
   216     catch { case _: IllegalStateException => }
   217 
   218     private def cleanup() =
   219       try { Runtime.getRuntime.removeShutdownHook(shutdown_hook) }
   220       catch { case _: IllegalStateException => }
   221 
   222 
   223     /* result */
   224 
   225     def join: Int = { val rc = proc.waitFor; cleanup(); rc }
   226   }
   227 
   228 
   229   /* bash */
   230 
   231   def bash_env(cwd: JFile, env: Map[String, String], script: String): (String, String, Int) =
   232   {
   233     File.with_tmp_file("isabelle_script") { script_file =>
   234       File.write(script_file, script)
   235       val proc = new Managed_Process(cwd, env, false, "bash", posix_path(script_file.getPath))
   236 
   237       proc.stdin.close
   238       val (_, stdout) = Simple_Thread.future("bash_stdout") { File.read(proc.stdout) }
   239       val (_, stderr) = Simple_Thread.future("bash_stderr") { File.read(proc.stderr) }
   240 
   241       val rc =
   242         try { proc.join }
   243         catch { case e: InterruptedException => Thread.interrupted; proc.terminate; 130 }
   244       (stdout.join, stderr.join, rc)
   245     }
   246   }
   247 
   248   def bash(script: String): (String, String, Int) = bash_env(null, null, script)
   249 
   250 
   251   /* system tools */
   252 
   253   def isabelle_tool(name: String, args: String*): (String, Int) =
   254   {
   255     Path.split(getenv_strict("ISABELLE_TOOLS")).find { dir =>
   256       val file = (dir + Path.basic(name)).file
   257       try {
   258         file.isFile && file.canRead && file.canExecute &&
   259           !name.endsWith("~") && !name.endsWith(".orig")
   260       }
   261       catch { case _: SecurityException => false }
   262     } match {
   263       case Some(dir) =>
   264         val file = standard_path(dir + Path.basic(name))
   265         Standard_System.process_output(execute(true, (List(file) ++ args): _*))
   266       case None => ("Unknown Isabelle tool: " + name, 2)
   267     }
   268   }
   269 
   270 
   271 
   272   /** Isabelle resources **/
   273 
   274   /* components */
   275 
   276   def components(): List[Path] =
   277     Path.split(getenv_strict("ISABELLE_COMPONENTS"))
   278 
   279 
   280   /* find logics */
   281 
   282   def find_logics_dirs(): List[Path] =
   283   {
   284     val ml_ident = Path.explode("$ML_IDENTIFIER").expand
   285     Path.split(getenv_strict("ISABELLE_PATH")).map(_ + ml_ident)
   286   }
   287 
   288   def find_logics(): List[String] =
   289     (for {
   290       dir <- find_logics_dirs()
   291       files = dir.file.listFiles() if files != null
   292       file <- files.toList if file.isFile } yield file.getName).sorted
   293 
   294 
   295   /* fonts */
   296 
   297   def get_font(family: String = "IsabelleText", size: Int = 1, bold: Boolean = false): Font =
   298     new Font(family, if (bold) Font.BOLD else Font.PLAIN, size)
   299 
   300   def install_fonts()
   301   {
   302     val ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
   303     for (font <- Path.split(getenv_strict("ISABELLE_FONTS")))
   304       ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, font.file))
   305   }
   306 }