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

问题描述 投票:2回答:1

上下文

我正在尝试编写交互式的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>。但是,快速运行bash脚本涉及使用Process()NSTask(),在我可以找到的每种使用情况下,它始终是一个单独的进程,因此,无论当前会话窗口的大小如何,它仅返回默认的终端大小。

我尝试使用:

  1. [https://github.com/kareman/SwiftShell run("tput", "cols")(无论窗口大小如何,始终不变)
  2. How do I run an terminal command in a swift script? (e.g. xcodebuild)(与上面相同的问题,只是在没有API的情况下才暴露出来)

问题

我该怎么做才能获取有关当前会话的信息或在当前窗口的上下文中运行我的bash进程,特别是有关窗口大小的信息?

我曾考虑过尝试列出当前终端会话并在其中一个中运行bash脚本的方法,但是我无法弄清楚如何使之工作(类似于bash who,然后选择正确的会话并从那里开始工作。不确定这是否可行。):​​https://askubuntu.com/questions/496914/write-command-in-one-terminal-see-result-on-other-one

swift bash terminal command-line-interface
1个回答
0
投票

您可以使用此功能在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")

它将作为String返回,因此您可能希望将输出转换为Integer。

希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.