|
3 | 3 | // found in the package's LICENSE file. |
4 | 4 |
|
5 | 5 | import host.os |
| 6 | +import host.pipe |
6 | 7 | import system |
7 | 8 |
|
8 | 9 | /** |
@@ -96,3 +97,66 @@ The base directory relative to which user-specific non-essential (cached) data |
96 | 97 | */ |
97 | 98 | cache-home -> string?: |
98 | 99 | return from-env_ "XDG_CACHE_HOME" --fallback=".cache" |
| 100 | + |
| 101 | +/** |
| 102 | +Opens the given URL in the default browser. |
| 103 | +
|
| 104 | +Typically, opening the browser doesn't take long, so the function will wait for |
| 105 | + at most $timeout-ms milliseconds. If the command hasn't returned in that time |
| 106 | + it will be killed. |
| 107 | +*/ |
| 108 | +open-browser url/string --timeout-ms/int=20_000: |
| 109 | + catch: |
| 110 | + command/string? := null |
| 111 | + args/List? := null |
| 112 | + platform := system.platform |
| 113 | + if platform == system.PLATFORM-LINUX: |
| 114 | + command = "xdg-open" |
| 115 | + args = [ url ] |
| 116 | + else if platform == system.PLATFORM-MACOS: |
| 117 | + command = "open" |
| 118 | + args = [ url ] |
| 119 | + else if platform == system.PLATFORM-WINDOWS: |
| 120 | + command = "cmd" |
| 121 | + escaped-url := url.replace "&" "^&" |
| 122 | + args = [ "/c", "start", escaped-url ] |
| 123 | + else: |
| 124 | + throw "Unsupported platform" |
| 125 | + |
| 126 | + if command != null: |
| 127 | + fork-data := pipe.fork |
| 128 | + true // Use path. |
| 129 | + pipe.PIPE-CREATED // Stdin. |
| 130 | + pipe.PIPE-CREATED // Stdout. |
| 131 | + pipe.PIPE-CREATED // Stderr. |
| 132 | + command |
| 133 | + [ command ] + args |
| 134 | + stdin := fork-data[0] |
| 135 | + stdout/pipe.OpenPipe := fork-data[1] |
| 136 | + stderr/pipe.OpenPipe := fork-data[2] |
| 137 | + pid := fork-data[3] |
| 138 | + stdin.out.close |
| 139 | + task --background:: catch: stdout.in.drain |
| 140 | + task --background:: catch: stderr.in.drain |
| 141 | + task --background:: |
| 142 | + // The 'open' command should finish in almost no time. |
| 143 | + // Even if it doesn't, then the CLI almost always terminates |
| 144 | + // shortly after calling 'open'. |
| 145 | + // However, if we modify the CLI, so it becomes long-running (for |
| 146 | + // example inside a server), we need to make sure we don't keep |
| 147 | + // spawned processes around. |
| 148 | + exception := catch: with-timeout --ms=timeout-ms: |
| 149 | + pipe.wait-for pid |
| 150 | + if exception == DEADLINE-EXCEEDED-ERROR: |
| 151 | + killed := false |
| 152 | + if platform != system.PLATFORM-WINDOWS: |
| 153 | + // Try a gentle kill first. |
| 154 | + SIGTERM ::= 15 |
| 155 | + catch: |
| 156 | + pipe.kill_ pid SIGTERM |
| 157 | + with-timeout --ms=1_000: |
| 158 | + pipe.wait-for pid |
| 159 | + killed = true |
| 160 | + if not killed: |
| 161 | + SIGKILL ::= 9 |
| 162 | + catch: pipe.kill_ pid SIGKILL |
0 commit comments