Screenshots, hung out to dry. A tiny native macOS app that hangs every screenshot on a line at the top of your screen.
Swift
Change or remove the shortcut from the menu bar
Alejandro Bujána409e69dff4a
diff --git a/README.md b/README.mdindex a2dab9a..babe176 100644--- a/README.md+++ b/README.md@@ -48,7 +48,7 @@ Rest the pointer in the menu bar and it glides down. Move away and it's gone.| Drag to the Trash, or click the cross | Let it go. || Rest the pointer in the menu bar | Bring the line down on that screen. || Click anything in the menu bar | Put it away. |-| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | Show or hide the line. |+| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | Show or hide the line. Change it under Shortcut in the menu bar. |<br>diff --git a/Sources/Tendedero/AppDelegate.swift b/Sources/Tendedero/AppDelegate.swiftindex 6fa09bd..9007d2f 100644--- a/Sources/Tendedero/AppDelegate.swift+++ b/Sources/Tendedero/AppDelegate.swift@@ -72,9 +72,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {clipboardWatcher = ClipboardWatcher { [weak self] url in self?.hangCapture(url) }if ClipboardWatcher.isEnabled { clipboardWatcher.start() }- hotKey = HotKey(keyCode: kVK_ANSI_T, modifiers: controlKey | optionKey) { [weak self] in- self?.toggle()- }+ registerShortcut()setUpStatusItem()watchMenuBarClicks()@@ -488,6 +486,34 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {}}+ // MARK: Shortcut++ private func registerShortcut() {+ hotKey = nil+ guard let shortcut = Shortcut.current else { return }+ hotKey = HotKey(shortcut) { [weak self] in self?.toggle() }+ }++ private func changeShortcut() {+ // Off while recording, so pressing the current one records it+ // instead of showing the line.+ hotKey = nil+ ShortcutRecorder.shared.record { [weak self] result in+ guard let self else { return }+ if let result {+ let previous = Shortcut.current+ Shortcut.current = result+ self.registerShortcut()+ // Taken by another app: keep the one that worked.+ if result != nil && self.hotKey == nil {+ NSSound.beep()+ Shortcut.current = previous+ }+ }+ self.registerShortcut()+ }+ }+private func setSize(_ size: Layout.Size) {guard size != Layout.size else { return }Layout.size = size@@ -528,8 +554,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {let toggleItem = ClosureMenuItem(isRevealed ? L("Hide line") : L("Show line")) { [weak self] inself?.toggle()}- toggleItem.keyEquivalent = "t"- toggleItem.keyEquivalentModifierMask = [.control, .option]+ if let shortcut = Shortcut.current, shortcut.key.count == 1 {+ toggleItem.keyEquivalent = shortcut.key+ toggleItem.keyEquivalentModifierMask = shortcut.modifiers+ }menu.addItem(toggleItem)let clearItem = ClosureMenuItem(L("Take everything down")) { [weak self] in@@ -583,6 +611,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {sizeItem.submenu = sizesmenu.addItem(sizeItem)+ let shortcutItem = NSMenuItem(title: L("Shortcut"), action: nil, keyEquivalent: "")+ let shortcuts = NSMenu()+ let current = NSMenuItem(title: Shortcut.current?.display ?? L("None"), action: nil, keyEquivalent: "")+ current.isEnabled = false+ shortcuts.addItem(current)+ shortcuts.addItem(ClosureMenuItem(L("Change Shortcut…")) { [weak self] in self?.changeShortcut() })+ shortcutItem.submenu = shortcuts+ menu.addItem(shortcutItem)+menu.addItem(ClosureMenuItem(L("Open screenshots folder")) { [weak self] inguard let self else { return }NSWorkspace.shared.open(self.watcher.folder)diff --git a/Sources/Tendedero/HotKey.swift b/Sources/Tendedero/HotKey.swiftindex 236fbda..6ed72ab 100644--- a/Sources/Tendedero/HotKey.swift+++ b/Sources/Tendedero/HotKey.swift@@ -1,3 +1,4 @@+import AppKitimport Carbon/// A single global shortcut through the Carbon hot key API. Unlike a global@@ -5,19 +6,159 @@ import Carbonfinal class HotKey {private var ref: EventHotKeyRef?private static var action: (() -> Void)?+ private static var handlerInstalled = false- init(keyCode: Int, modifiers: Int, action: @escaping () -> Void) {+ /// Nil when the combination cannot be registered, for example because+ /// another app already took it.+ init?(_ shortcut: Shortcut, action: @escaping () -> Void) {HotKey.action = action- var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))- InstallEventHandler(GetApplicationEventTarget(), { _, _, _ in- DispatchQueue.main.async { HotKey.action?() }- return noErr- }, 1, &spec, nil, nil)+ // One handler for the app, however many times the shortcut changes.+ if !HotKey.handlerInstalled {+ var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))+ InstallEventHandler(GetApplicationEventTarget(), { _, _, _ in+ DispatchQueue.main.async { HotKey.action?() }+ return noErr+ }, 1, &spec, nil, nil)+ HotKey.handlerInstalled = true+ }let id = EventHotKeyID(signature: OSType(0x5445_4E44), id: 1) // "TEND"- RegisterEventHotKey(UInt32(keyCode), UInt32(modifiers), id, GetApplicationEventTarget(), 0, &ref)+ let status = RegisterEventHotKey(UInt32(shortcut.keyCode), UInt32(shortcut.carbonModifiers), id,+ GetApplicationEventTarget(), 0, &ref)+ guard status == noErr, ref != nil else { return nil }}deinit {if let ref { UnregisterEventHotKey(ref) }}}++/// The shortcut that shows and hides the line: ⌃⌥T unless changed, or none.+struct Shortcut: Equatable {+ var keyCode: Int+ var modifiers: NSEvent.ModifierFlags+ /// The key as typed, for the menu: "t", " ", "1".+ var key: String++ static let standard = Shortcut(keyCode: kVK_ANSI_T, modifiers: [.control, .option], key: "t")++ private static let defaultsKey = "shortcut"++ /// The user's choice. Nil means no shortcut at all.+ static var current: Shortcut? {+ get {+ guard let saved = UserDefaults.standard.dictionary(forKey: defaultsKey) else { return standard }+ guard let code = saved["keyCode"] as? Int, let flags = saved["modifiers"] as? UInt,+ let key = saved["key"] as? String else { return nil }+ return Shortcut(keyCode: code, modifiers: NSEvent.ModifierFlags(rawValue: flags), key: key)+ }+ set {+ UserDefaults.standard.set(newValue.map {+ ["keyCode": $0.keyCode, "modifiers": $0.modifiers.rawValue, "key": $0.key] as [String: Any]+ } ?? [:], forKey: defaultsKey)+ }+ }++ /// From a key press, if it makes a usable global shortcut: it needs+ /// Command, Control or Option, so typing alone never triggers it.+ init?(event: NSEvent) {+ let flags = event.modifierFlags.intersection([.command, .control, .option, .shift])+ guard !flags.intersection([.command, .control, .option]).isEmpty,+ let key = event.charactersIgnoringModifiers?.lowercased(), !key.isEmpty else { return nil }+ self.init(keyCode: Int(event.keyCode), modifiers: flags, key: key)+ }++ init(keyCode: Int, modifiers: NSEvent.ModifierFlags, key: String) {+ self.keyCode = keyCode+ self.modifiers = modifiers+ self.key = key+ }++ var carbonModifiers: Int {+ var carbon = 0+ if modifiers.contains(.command) { carbon |= cmdKey }+ if modifiers.contains(.control) { carbon |= controlKey }+ if modifiers.contains(.option) { carbon |= optionKey }+ if modifiers.contains(.shift) { carbon |= shiftKey }+ return carbon+ }++ /// As macOS writes it in menus: ⌃⌥⇧⌘ and the key.+ var display: String {+ var text = ""+ if modifiers.contains(.control) { text += "⌃" }+ if modifiers.contains(.option) { text += "⌥" }+ if modifiers.contains(.shift) { text += "⇧" }+ if modifiers.contains(.command) { text += "⌘" }+ return text + (key == " " ? L("Space") : key.uppercased())+ }+}++/// Asks for a new shortcut in a small window: the next key press with+/// Command, Control or Option becomes it. Escape cancels and Delete leaves+/// the line without a shortcut.+@MainActor+final class ShortcutRecorder: NSObject, NSWindowDelegate {+ static let shared = ShortcutRecorder()++ private var window: NSWindow?+ private var monitor: Any?+ private var done: ((Shortcut??) -> Void)?++ /// Calls back with the new shortcut, `.some(nil)` for none, or nil if+ /// cancelled.+ func record(_ done: @escaping (Shortcut??) -> Void) {+ finish(nil)+ self.done = done++ let title = NSTextField(labelWithString: L("Press the new shortcut"))+ title.font = .systemFont(ofSize: 15, weight: .semibold)+ let hint = NSTextField(labelWithString: L("Escape cancels. Delete removes the shortcut."))+ hint.font = .systemFont(ofSize: 12)+ hint.textColor = .secondaryLabelColor+ let stack = NSStackView(views: [title, hint])+ stack.orientation = .vertical+ stack.spacing = 6+ stack.edgeInsets = NSEdgeInsets(top: 22, left: 28, bottom: 22, right: 28)++ let window = NSWindow(contentRect: .zero, styleMask: [.titled, .closable], backing: .buffered, defer: false)+ window.title = L("Change Shortcut")+ window.contentView = stack+ window.isReleasedWhenClosed = false+ window.delegate = self+ window.center()+ self.window = window+ NSApp.activate(ignoringOtherApps: true)+ window.makeKeyAndOrderFront(nil)++ monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in+ guard let self, event.window === self.window else { return event }+ let plain = event.modifierFlags.intersection([.command, .control, .option, .shift]).isEmpty+ if event.keyCode == UInt16(kVK_Escape) && plain {+ self.finish(nil)+ } else if (event.keyCode == UInt16(kVK_Delete) || event.keyCode == UInt16(kVK_ForwardDelete)) && plain {+ self.finish(.some(nil))+ } else if let shortcut = Shortcut(event: event) {+ self.finish(.some(shortcut))+ } else {+ NSSound.beep()+ }+ return nil+ }+ }++ func windowWillClose(_ notification: Notification) {+ guard (notification.object as? NSWindow) === window else { return }+ window = nil+ finish(nil)+ }++ private func finish(_ result: Shortcut??) {+ if let monitor { NSEvent.removeMonitor(monitor) }+ monitor = nil+ let done = self.done+ self.done = nil+ window?.close()+ window = nil+ done?(result)+ }+}diff --git a/Sources/Tendedero/Resources/az.lproj/Localizable.strings b/Sources/Tendedero/Resources/az.lproj/Localizable.stringsindex 346acfb..d40cb20 100644--- a/Sources/Tendedero/Resources/az.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/az.lproj/Localizable.strings@@ -18,6 +18,13 @@"Quit Tendedero" = "Tendedero-dan çıx";"Could not change the login setting" = "Giriş ayarını dəyişmək alınmadı";"Move Tendedero to the Applications folder and try again." = "Tendedero-nu Applications (Proqramlar) qovluğuna köçürün və yenidən cəhd edin.";+"Shortcut" = "Qısayol";+"Change Shortcut…" = "Qısayolu dəyiş…";+"Change Shortcut" = "Qısayolu dəyiş";+"None" = "Yoxdur";+"Space" = "Boşluq";+"Press the new shortcut" = "Yeni qısayolu basın";+"Escape cancels. Delete removes the shortcut." = "Escape ləğv edir. Sil qısayolu silir.";"Size" = "Ölçü";"Small" = "Kiçik";"Medium" = "Orta";diff --git a/Sources/Tendedero/Resources/en.lproj/Localizable.strings b/Sources/Tendedero/Resources/en.lproj/Localizable.stringsindex c0df23f..dfb0639 100644--- a/Sources/Tendedero/Resources/en.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/en.lproj/Localizable.strings@@ -18,6 +18,13 @@"Quit Tendedero" = "Quit Tendedero";"Could not change the login setting" = "Could not change the login setting";"Move Tendedero to the Applications folder and try again." = "Move Tendedero to the Applications folder and try again.";+"Shortcut" = "Shortcut";+"Change Shortcut…" = "Change Shortcut…";+"Change Shortcut" = "Change Shortcut";+"None" = "None";+"Space" = "Space";+"Press the new shortcut" = "Press the new shortcut";+"Escape cancels. Delete removes the shortcut." = "Escape cancels. Delete removes the shortcut.";"Size" = "Size";"Small" = "Small";"Medium" = "Medium";diff --git a/Sources/Tendedero/Resources/es.lproj/Localizable.strings b/Sources/Tendedero/Resources/es.lproj/Localizable.stringsindex 57b4709..5d1006d 100644--- a/Sources/Tendedero/Resources/es.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/es.lproj/Localizable.strings@@ -16,6 +16,13 @@"Quit Tendedero" = "Salir de Tendedero";"Could not change the login setting" = "No se pudo cambiar el inicio de sesión";"Move Tendedero to the Applications folder and try again." = "Mueve Tendedero a la carpeta Aplicaciones y vuelve a intentarlo.";+"Shortcut" = "Atajo";+"Change Shortcut…" = "Cambiar atajo…";+"Change Shortcut" = "Cambiar atajo";+"None" = "Ninguno";+"Space" = "Espacio";+"Press the new shortcut" = "Pulsa el nuevo atajo";+"Escape cancels. Delete removes the shortcut." = "Escape cancela. Borrar quita el atajo.";"Size" = "Tamaño";"Small" = "Pequeño";"Medium" = "Mediano";diff --git a/Sources/Tendedero/Resources/tr.lproj/Localizable.strings b/Sources/Tendedero/Resources/tr.lproj/Localizable.stringsindex 88d9f89..0ebe725 100644--- a/Sources/Tendedero/Resources/tr.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/tr.lproj/Localizable.strings@@ -16,6 +16,13 @@"Quit Tendedero" = "Tendedero'yu kapat";"Could not change the login setting" = "Giriş ayarı değiştirilemedi";"Move Tendedero to the Applications folder and try again." = "Tendedero'yu Uygulamalar klasörüne taşıyın ve tekrar deneyin.";+"Shortcut" = "Kısayol";+"Change Shortcut…" = "Kısayolu değiştir…";+"Change Shortcut" = "Kısayolu değiştir";+"None" = "Yok";+"Space" = "Boşluk";+"Press the new shortcut" = "Yeni kısayolu basın";+"Escape cancels. Delete removes the shortcut." = "Escape iptal eder. Sil kısayolu kaldırır.";"Size" = "Boyut";"Small" = "Küçük";"Medium" = "Orta";diff --git a/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings b/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.stringsindex a01e8bd..3e5f75b 100644--- a/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings+++ b/Sources/Tendedero/Resources/zh-Hans.lproj/Localizable.strings@@ -16,6 +16,13 @@"Quit Tendedero" = "退出 Tendedero";"Could not change the login setting" = "无法更改登录项设置";"Move Tendedero to the Applications folder and try again." = "请先把 Tendedero 移到「应用程序」文件夹,再试一次。";+"Shortcut" = "快捷键";+"Change Shortcut…" = "更改快捷键…";+"Change Shortcut" = "更改快捷键";+"None" = "无";+"Space" = "空格";+"Press the new shortcut" = "请按下新的快捷键";+"Escape cancels. Delete removes the shortcut." = "按 Esc 取消,按删除键移除快捷键。";"Size" = "大小";"Small" = "小";"Medium" = "中";diff --git a/docs/i18n/README.es.md b/docs/i18n/README.es.mdindex e4e7d09..ce26c5c 100644--- a/docs/i18n/README.es.md+++ b/docs/i18n/README.es.md@@ -50,7 +50,7 @@ Lleva el puntero a la barra de menús y la cuerda baja. Apártalo y desaparece.| Arrastrar a la Papelera o hacer clic en la cruz | Te deshaces de ella. || Dejar el puntero en la barra de menús | Baja la cuerda en esa pantalla. || Hacer clic en cualquier sitio de la barra de menús | Recoge la cuerda. |-| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | Muestra u oculta la cuerda. |+| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | Muestra u oculta la cuerda. Se cambia en Atajo, en la barra de menús. |<br>diff --git a/docs/i18n/README.zh-Hans.md b/docs/i18n/README.zh-Hans.mdindex 8a81360..f54c2df 100644--- a/docs/i18n/README.zh-Hans.md+++ b/docs/i18n/README.zh-Hans.md@@ -50,7 +50,7 @@| 拖到废纸篓,或点叉 | 松手丢弃。 || 指针停在菜单栏 | 在那一块屏幕上放下绳子。 || 点击菜单栏任意处 | 把绳子收起来。 |-| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | 显示或隐藏绳子。 |+| <kbd>⌃</kbd> <kbd>⌥</kbd> <kbd>T</kbd> | 显示或隐藏绳子。可在菜单栏的「快捷键」中更改。 |<br>