Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227import Foundationimport ParcelIPC
struct CLIOutput { static func write(_ text: String) throws { try FileHandle.standardOutput.write(contentsOf: Data(text.utf8)) }
static func response( _ response: IPCResponse, query: IPCQuery? = nil, json: Bool = false, why: Bool = false, diagnostics: Bool = false ) throws -> String { guard response.ok else { guard let error = response.error else { throw CLIOutputError.missingError } throw CLIOutputError.rejected(code: error.code, message: error.message) } guard let result = response.result else { throw CLIOutputError.missingResult } if diagnostics { return try DiagnosticsOutput.format(result, json: json) } if why && !json { guard case .object(let fields) = result, case .string(let reason) = fields["reason"] else { throw CLIOutputError.missingReason } return escapeCell(reason) + "\n" } return try format(result, query: query, json: json) }
static func event(_ event: IPCEvent, json: Bool = false) throws -> String { if json { return try jsonLine(event) } return event.topic.rawValue + ": " + escapeCell(String(try jsonLine(event.data).dropLast())) + "\n" }
static func format(_ value: JSONValue, query: IPCQuery? = nil, json: Bool = false) throws -> String { if json { return try jsonLine(value) }
switch value { case .array(let rows): return try rowTable(rows, emptyMessage: emptyMessage(query)) case .object(let fields): if let query, fields.count == 1, let rows = fields[query.rawValue] { return try format(rows, query: query) } guard !fields.isEmpty else { return emptyMessage(query) + "\n" } let rows = try fields.sorted { $0.key < $1.key }.map { field in [escapeCell(field.key), try cell(field.value)] } let keyHeading = query == .config ? String(localized: "Setting", bundle: .module) : String(localized: "Field", bundle: .module) return table(headers: [keyHeading, String(localized: "Value", bundle: .module)], rows: rows) case .null: return String(localized: "Done.", bundle: .module) + "\n" default: return try cell(value) + "\n" } }
static func jsonLine<Value: Encodable>(_ value: Value) throws -> String { guard let text = String(data: try IPCCodec.encode(value), encoding: .utf8) else { throw CLIOutputError.invalidUTF8 } return text }
static func rowTable(_ values: [JSONValue], emptyMessage: String) throws -> String { guard !values.isEmpty else { return emptyMessage + "\n" } let objects = values.compactMap { value -> [String: JSONValue]? in guard case .object(let fields) = value else { return nil } return fields } if objects.isEmpty { return table( headers: [String(localized: "Value", bundle: .module)], rows: try values.map { [try cell($0)] } ) } guard objects.count == values.count else { throw CLIOutputError.inconsistentRows } let columns = Set(objects.flatMap(\.keys)).sorted(by: columnOrder) guard !columns.isEmpty else { return table(headers: [String(localized: "Value", bundle: .module)], rows: objects.map { _ in ["{}"] }) } let rows = try objects.map { fields in try columns.map { key in if let value = fields[key] { return try cell(value) } return String(localized: "—", bundle: .module) } } return table(headers: columns.map(heading), rows: rows) }
static func table(headers: [String], rows: [[String]]) -> String { precondition(!headers.isEmpty, "Tables need at least one column.") precondition(rows.allSatisfy { $0.count == headers.count }, "Table rows must match the column count.") let safeHeaders = headers.map(escapeCell) let safeRows = rows.map { $0.map(escapeCell) } let widths = safeRows.reduce(safeHeaders.map(terminalWidth)) { widths, row in zip(widths, row).map { max($0.0, terminalWidth($0.1)) } } func line(_ row: [String]) -> String { row.enumerated().map { index, cell in if index == row.count - 1 { return cell } return cell + String(repeating: " ", count: widths[index] - terminalWidth(cell)) }.joined(separator: " ") } let separator = widths.map { String(repeating: "─", count: $0) }.joined(separator: " ") return ([line(safeHeaders), separator] + safeRows.map(line)).joined(separator: "\n") + "\n" }
static func cell(_ value: JSONValue) throws -> String { switch value { case .null: return String(localized: "—", bundle: .module) case .bool(let flag): return flag ? String(localized: "Yes", bundle: .module) : String(localized: "No", bundle: .module) case .string(let text): return escapeCell(text) default: return escapeCell(String(try jsonLine(value).dropLast())) } }
static func escapeCell(_ text: String) -> String { text.unicodeScalars.map { scalar in switch scalar { case "\n": return "\\n" case "\r": return "\\r" case "\t": return "\\t" default: switch scalar.properties.generalCategory { case .control, .lineSeparator, .paragraphSeparator: return "\\u{" + String(scalar.value, radix: 16) + "}" case .format where scalar.value != 0x200C && scalar.value != 0x200D: return "\\u{" + String(scalar.value, radix: 16) + "}" default: return String(scalar) } } }.joined() }
// Grapheme counts alone misalign wide glyphs, combining marks, and joined emoji in terminal tables. static func terminalWidth(_ text: String) -> Int { text.reduce(0) { width, character in let scalars = character.unicodeScalars let emoji = scalars.contains { $0.properties.isEmojiPresentation } || (scalars.contains { $0.value == 0xFE0F } && scalars.contains { $0.properties.isEmoji }) if emoji { return width + 2 } let characterWidth = scalars.map { scalar -> Int in switch scalar.properties.generalCategory { case .nonspacingMark, .enclosingMark, .format: return 0 default: break } switch scalar.value { case 0x1100...0x115F, 0x2329...0x232A, 0x2E80...0x303E, 0x3040...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 0xFE10...0xFE19, 0xFE30...0xFE6F, 0xFF01...0xFF60, 0xFFE0...0xFFE6, 0x1B000...0x1B2FF, 0x1F200...0x1F251, 0x20000...0x3FFFD: return 2 default: return 1 } }.max() ?? 0 return width + characterWidth } }
private static func columnOrder(_ lhs: String, _ rhs: String) -> Bool { let preferred = ["id", "pid", "app", "title", "name", "workspace", "display", "layout", "focused"] let left = preferred.firstIndex(of: lhs) ?? preferred.count let right = preferred.firstIndex(of: rhs) ?? preferred.count return left == right ? lhs < rhs : left < right }
private static func heading(_ key: String) -> String { switch key { case "id": return String(localized: "ID", bundle: .module) case "pid": return String(localized: "PID", bundle: .module) case "app": return String(localized: "Application", bundle: .module) case "title": return String(localized: "Title", bundle: .module) case "name": return String(localized: "Name", bundle: .module) case "workspace": return String(localized: "Workspace", bundle: .module) case "display": return String(localized: "Display", bundle: .module) case "layout": return String(localized: "Layout", bundle: .module) case "focused": return String(localized: "Focused", bundle: .module) default: return escapeCell(key) } }
private static func emptyMessage(_ query: IPCQuery?) -> String { switch query { case .windows: String(localized: "No windows.", bundle: .module) case .workspaces: String(localized: "No workspaces.", bundle: .module) case .spaces: String(localized: "No spaces.", bundle: .module) case .displays: String(localized: "No displays.", bundle: .module) case .config: String(localized: "No configuration values.", bundle: .module) case .setups: String(localized: "No setups.", bundle: .module) case nil: String(localized: "No results.", bundle: .module) } }}
enum CLIOutputError: LocalizedError { case rejected(code: String, message: String) case missingResult case missingError case missingReason case inconsistentRows case invalidUTF8
var errorDescription: String? { switch self { case .rejected(let code, let message): String( localized: "Parcel rejected the command (\(CLIOutput.escapeCell(code))): \(CLIOutput.escapeCell(message))", bundle: .module) case .missingResult: String(localized: "Parcel returned a response without a result.", bundle: .module) case .missingError: String(localized: "Parcel returned a failed response without an error.", bundle: .module) case .missingReason: String(localized: "Parcel returned a window explanation without a reason string.", bundle: .module) case .inconsistentRows: String(localized: "Parcel returned a table mixing records and other values.", bundle: .module) case .invalidUTF8: String(localized: "Parcel returned JSON that is not valid UTF-8.", bundle: .module) } }}