1 /* Title: Pure/System/isabelle_system.scala
4 Fundamental Isabelle system environment: quasi-static module with
5 optional init operation.
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
18 import scala.io.Source
19 import scala.util.matching.Regex
20 import scala.collection.mutable
23 object Isabelle_System
25 /** implicit state **/
27 private case class State(standard_system: Standard_System, settings: Map[String, String])
29 @volatile private var _state: Option[State] = None
31 private def check_state(): State =
33 if (_state.isEmpty) init() // unsynchronized check
37 def standard_system: Standard_System = check_state().standard_system
38 def settings: Map[String, String] = check_state().settings
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)
46 def init(this_isabelle_home: String = null) = synchronized {
48 import scala.collection.JavaConversions._
50 val standard_system = new Standard_System
53 val env0 = sys.env + ("ISABELLE_JDK_HOME" -> standard_system.this_jdk_home())
55 val user_home = System.getProperty("user.home")
57 if (user_home == null || env0.isDefinedAt("HOME")) env0
58 else env0 + ("HOME" -> user_home)
61 if (this_isabelle_home != null) this_isabelle_home
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")
68 case Some(path) => path
71 Standard_System.with_tmp_file("settings") { dump =>
73 if (Platform.is_windows) List(standard_system.platform_root + "\\bin\\bash", "-l")
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)
81 (for (entry <- Standard_System.read_file(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))
86 entries + ("PATH" -> entries("PATH_JVM")) - "PATH_JVM"
89 _state = Some(State(standard_system, settings))
96 def getenv(name: String): String = settings.getOrElse(name, "")
98 def getenv_strict(name: String): String =
100 val value = getenv(name)
101 if (value != "") value else error("Undefined environment variable: " + name)
105 /** file-system operations **/
107 /* path specifications */
109 def standard_path(path: Path): String = path.expand.implode
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))
114 def platform_file_url(raw_path: Path): String =
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('\\', '/')
124 def posix_path(jvm_path: String): String = standard_system.posix_path(jvm_path)
129 def try_read(paths: Seq[Path]): String =
131 val buf = new StringBuilder
134 file = platform_file(path) if file.isFile
135 } { buf.append(Standard_System.read_file(file)); buf.append('\n') }
142 private def try_file(file: JFile) = if (file.isFile) Some(file) else None
144 def source_file(path: Path): Option[JFile] =
146 if (path.is_absolute || path.is_current)
147 try_file(platform_file(path))
149 val pure_file = (Path.explode("~~/src/Pure") + path).file
150 if (pure_file.isFile) Some(pure_file)
151 else if (getenv("ML_SOURCES") != "") try_file((Path.explode("$ML_SOURCES") + path).file)
158 /** external processes **/
162 def execute_env(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*): Process =
165 if (Platform.is_windows) List(standard_system.platform_root + "\\bin\\env.exe") ++ args
167 val env1 = if (env == null) settings else settings ++ env
168 Standard_System.raw_execute(cwd, env1, redirect, cmdline: _*)
171 def execute(redirect: Boolean, args: String*): Process =
172 execute_env(null, null, redirect, args: _*)
175 /* managed process */
177 class Managed_Process(cwd: JFile, env: Map[String, String], redirect: Boolean, args: String*)
180 List(standard_path(Path.explode("~~/lib/scripts/process")), "group", "-", "no_script")
181 private val proc = execute_env(cwd, env, redirect, (params ++ args):_*)
186 val stdin: BufferedWriter =
187 new BufferedWriter(new OutputStreamWriter(proc.getOutputStream, Standard_System.charset))
189 val stdout: BufferedReader =
190 new BufferedReader(new InputStreamReader(proc.getInputStream, Standard_System.charset))
192 val stderr: BufferedReader =
193 new BufferedReader(new InputStreamReader(proc.getErrorStream, Standard_System.charset))
198 private val pid = stdout.readLine
200 private def kill(signal: String): Boolean =
202 execute(true, "kill", "-" + signal, "-" + pid).waitFor
203 execute(true, "kill", "-0", "-" + pid).waitFor == 0
206 private def multi_kill(signal: String): Boolean =
210 while (running && count > 0) {
220 def interrupt() { multi_kill("INT") }
221 def terminate() { multi_kill("INT") && multi_kill("TERM") && kill("KILL"); proc.destroy }
226 private val shutdown_hook = new Thread { override def run = terminate() }
228 try { Runtime.getRuntime.addShutdownHook(shutdown_hook) }
229 catch { case _: IllegalStateException => }
231 private def cleanup() =
232 try { Runtime.getRuntime.removeShutdownHook(shutdown_hook) }
233 catch { case _: IllegalStateException => }
238 def join: Int = { val rc = proc.waitFor; cleanup(); rc }
244 def bash_env(cwd: JFile, env: Map[String, String], script: String): (String, String, Int) =
246 Standard_System.with_tmp_file("isabelle_script") { script_file =>
247 Standard_System.write_file(script_file, script)
248 val proc = new Managed_Process(cwd, env, false, "bash", posix_path(script_file.getPath))
251 val (_, stdout) = Simple_Thread.future("bash_stdout") { Standard_System.slurp(proc.stdout) }
252 val (_, stderr) = Simple_Thread.future("bash_stderr") { Standard_System.slurp(proc.stderr) }
256 catch { case e: InterruptedException => Thread.interrupted; proc.terminate; 130 }
257 (stdout.join, stderr.join, rc)
261 def bash(script: String): (String, String, Int) = bash_env(null, null, script)
263 class Bash_Job(cwd: JFile, env: Map[String, String], script: String)
265 private val (thread, result) = Simple_Thread.future("bash_job") { bash_env(cwd, env, script) }
267 def terminate: Unit = thread.interrupt
268 def is_finished: Boolean = result.is_finished
269 def join: (String, String, Int) = result.join
271 override def toString: String = if (is_finished) join._3.toString else "<running>"
277 def isabelle_tool(name: String, args: String*): (String, Int) =
279 Path.split(getenv_strict("ISABELLE_TOOLS")).find { dir =>
280 val file = (dir + Path.basic(name)).file
282 file.isFile && file.canRead && file.canExecute &&
283 !name.endsWith("~") && !name.endsWith(".orig")
285 catch { case _: SecurityException => false }
288 val file = standard_path(dir + Path.basic(name))
289 Standard_System.process_output(execute(true, (List(file) ++ args): _*))
290 case None => ("Unknown Isabelle tool: " + name, 2)
296 /** Isabelle resources **/
300 def components(): List[Path] =
301 Path.split(getenv_strict("ISABELLE_COMPONENTS"))
306 def find_logics(): List[String] =
308 val ml_ident = getenv_strict("ML_IDENTIFIER")
309 val logics = new mutable.ListBuffer[String]
310 for (dir <- Path.split(getenv_strict("ISABELLE_PATH"))) {
311 val files = (dir + Path.explode(ml_ident)).file.listFiles()
313 for (file <- files if file.isFile) logics += file.getName
322 def get_font(family: String = "IsabelleText", size: Int = 1, bold: Boolean = false): Font =
323 new Font(family, if (bold) Font.BOLD else Font.PLAIN, size)
327 val ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
328 for (font <- Path.split(getenv_strict("ISABELLE_FONTS")))
329 ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, font.file))