Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0613· OpenAIHugging Face Arena Human Preference 55K

in swiftui on macos, make an app that capture the current selected text to clipboard by…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4-0314’s answer.
  1. User

    in swiftui on macos, make an app that capture the current selected text to clipboard by using the Shift-F13 key combo, and then uppercase this text and then set clipboard to this text

  2. Assistant

    Sure, you can accomplish this by using SwiftUI, AppKit, and the Pasteboard APIs.

    Unfortunately, SwiftUI doesn't have API access to capture global keyboard input or manipulate the system clipboard. However, you can use AppKit (a macOS framework) for hotkey registration and clipboard access.

    Here’s an example of how you can achieve this:

    import SwiftUI
    import AppKit
    
    @main
    struct ClipboardApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    
    struct ContentView: View {
        var body: some View {
            Text("Hello, World!")
                .onAppear {
                    registerHotkeys()
                }
        }
    
        func registerHotkeys() {
            let keyCombo = KeyCombo(key: .f13, cocoaModifiers: [.shift])
            let hotKey = HotKey(identifier: "ShiftF13", keyCombo: keyCombo, target: self, action: #selector(handleHotkey))
    
            // Register HotKey
            hotKey.register()
        }
    
        @objc func handleHotkey(_ hotKey: HotKey) {
            let pasteboard = NSPasteboard.general
            if let items = pasteboard.pasteboardItems,
               let item = items.first,
               let str = item.string(forType: .string) {
                let uppercasedStr = str.uppercased()
    
                // Set the uppercased string to the clipboard
                pasteboard.clearContents()
                pasteboard.setString(uppercasedStr, forType: .string)
            }
        }
    }
    

    In this code, when the ContentView appears, it registers a global hotkey for Shift-F13. When that hotkey is pressed, it will read the current contents of the system clipboard, uppercase the text, and then set the clipboard to the new text.

    Note: Please make sure to add a .plist entry to allow keyboard input capture in your app. Also, you might need to use NSEvent.addGlobalMonitorForEvents to monitor text selection events across system, as SwiftUI doesn't have an API for that. The Swift library "HotKey" is a useful tool for handling hotkeys in Swift. It can be found here: https://github.com/soffes/HotKey

    Please replace "Hello, World!" with your own content.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.