Swift命令行工具当前窗口大小



上下文

我正在尝试编写一个交互式swift命令行工具。其中的一个关键部分是有一个"writeToScreen"函数,该函数将一系列页眉、页脚和正文作为参数,并将它们很好地格式化为终端窗口的当前大小,将溢出压缩为"列表"选项。因此,该函数将类似于:

func writeToScreen(_ headers: [String], _ footers: [String], _ body: String) {
let (terminalWindowRows, terminalWindowCols) = getCurrentScreenSize()
// perform formatting within this window size...
}
func getCurrentScreenSize() -> (Int, Int) {
// perform some bash script like tput lines and tput cols and return result
}

例如,像writeToScreen(["h1","h2"], ["longf1","longf2"], "body...")这样的输入会为相应的屏幕大小产生以下内容,比如:

22x7
_ _ _ _ _ _ _ _ _ _ _ _
|(1) h1, (2) list...  |
|                     |
| body...             |
|                     |
|                     |
|                     |
|(3) list...          |
_ _ _ _ _ _ _ _ _ _ _ _
28x7
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _
|(1) h1, (2) h2, (3) list...|
|                           |
| body...                   |
|                           |
|                           |
|                           |
|(4) longf1, (5) list...    |
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _

问题

我遇到的问题是,要获得终端窗口大小,我需要运行至少一个bash脚本,比如echo "$(tput cols)-$(tput lines)",它会将屏幕大小输出为<cols>-<rows>。然而,在swift中运行bash脚本需要使用Process()NSTask(),在我能找到的每一种使用情况下,它总是一个单独的进程,因此无论当前会话窗口大小如何,都只返回默认的终端大小。

我尝试过使用:

  1. https://github.com/kareman/SwiftShellrun("tput", "cols")(无论窗口大小,始终恒定)
  2. 如何在swift脚本中运行终端命令?(例如xcodebuild)(与上面的问题相同,只是在没有API的情况下暴露出来)

问题

我需要做些什么才能获得有关当前会话的信息,或者在当前窗口的上下文中运行bash进程,特别是有关窗口大小的信息

我曾想过尝试一些方法,列出当前的终端会话,并在其中一个会话中运行bash脚本,但我不知道如何使其工作(比如bashwho,然后选择正确的会话并从中工作。不确定这是否是一个可行的途径。):https://askubuntu.com/questions/496914/write-command-in-one-terminal-see-result-on-other-one

您可以使用此函数在bash:中执行命令

func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}

然后简单地使用:

let cols = shell("tput cols")
let lines = shell("tput lines")

它将以字符串的形式返回,因此您可能希望将输出转换为Integer。

希望能有所帮助。

最新更新