Debian Codegraph @

src/platform/mac/macplatformwindow.mm

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "macplatformwindow.h"
4 #include "cfref.h"
5
6 #include "common/appconfig.h"
7 #include "common/log.h"
8 #include "platform/platformcommon.h"
9
10 #include <AppKit/NSGraphics.h>
11 #include <Cocoa/Cocoa.h>
12 #include <Carbon/Carbon.h>
13 #include <CoreFoundation/CoreFoundation.h>
14 #include <dispatch/dispatch.h>
15
16 #include <QApplication>
17 #include <QSet>
18
19 namespace {
20 // Original from: https://stackoverflow.com/a/33584460/454171
21 NSString* keyCodeToString(CGKeyCode keyCode, const UCKeyboardLayout *keyboardLayout)
22 {
23 UInt32 deadKeyState = 0;
24 UniCharCount maxStringLength = 255;
25 UniCharCount actualStringLength = 0;
26 UniChar unicodeString[maxStringLength];
27
28 OSStatus status = UCKeyTranslate(
29 keyboardLayout,
30 keyCode, kUCKeyActionDown, 0,
31 LMGetKbdType(), 0,
32 &deadKeyState,
33 maxStringLength,
34 &actualStringLength, unicodeString);
35
36 if (actualStringLength == 0 && deadKeyState) {
37 status = UCKeyTranslate(
38 keyboardLayout,
39 kVK_Space, kUCKeyActionDown, 0,
40 LMGetKbdType(), 0,
41 &deadKeyState,
42 maxStringLength,
43 &actualStringLength, unicodeString);
44 }
45
46 if (actualStringLength > 0 && status == noErr) {
47 return [[NSString stringWithCharacters:unicodeString
48 length:(NSUInteger)actualStringLength] lowercaseString];
49 }
50
51 return nil;
52 }
53
54 NSNumber* charToKeyCode(const char c)
55 {
56 CFRef<TISInputSourceRef> currentKeyboard = TISCopyCurrentKeyboardLayoutInputSource();
57 CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(
58 currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
59
60 if (layoutData != nil) {
61 const UCKeyboardLayout *keyboardLayout =
62 (const UCKeyboardLayout*)CFDataGetBytePtr(layoutData);
63
64 COPYQ_LOG( QStringLiteral("Searching key code for '%1'").arg(c) );
65 NSString *keyChar = [NSString stringWithFormat:@"%c" , c];
66 for (size_t i = 0; i < 128; ++i) {
67 NSString* str = keyCodeToString((CGKeyCode)i, keyboardLayout);
68 if (str != nil && [str isEqualToString:keyChar]) {
69 COPYQ_LOG( QStringLiteral("KeyCode for '%1' is %2").arg(c).arg(i) );
70 return [NSNumber numberWithInt:i];
71 }
72 }
73 }
74
75 return nil;
76 }
77
78 CGKeyCode keyCodeFromChar(const char c, CGKeyCode fallback)
79 {
80 const auto keyCode = charToKeyCode(c);
81 return keyCode == nil
82 ? fallback
83 : (CGKeyCode)[keyCode intValue];
84 }
85
86 template<typename T> inline T* objc_cast(id from)
87 {
88 if (from && [from isKindOfClass:[T class]]) {
89 return static_cast<T*>(from);
90 }
91 return nil;
92 }
93
94 void sendShortcut(int modifier, int key) {
95 COPYQ_LOG( QStringLiteral("Sending key codes %1 and %2")
96 .arg(modifier)
97 .arg(key) );
98
99 CFRef<CGEventSourceRef> sourceRef = CGEventSourceCreate(
100 kCGEventSourceStateCombinedSessionState);
101
102 CFRef<CGEventRef> commandDown = CGEventCreateKeyboardEvent(sourceRef, modifier, YES);
103 CFRef<CGEventRef> VDown = CGEventCreateKeyboardEvent(sourceRef, key, YES);
104
105 CFRef<CGEventRef> VUp = CGEventCreateKeyboardEvent(sourceRef, key, NO);
106 CFRef<CGEventRef> commandUp = CGEventCreateKeyboardEvent(sourceRef, modifier, NO);
107
108 // 0x000008 is a hack to fix pasting in Emacs?
109 // https://github.com/TermiT/Flycut/pull/18
110 CGEventSetFlags(VDown,CGEventFlags(kCGEventFlagMaskCommand|0x000008));
111 CGEventSetFlags(VUp,CGEventFlags(kCGEventFlagMaskCommand|0x000008));
112
113 CGEventPost(kCGHIDEventTap, commandDown);
114 CGEventPost(kCGHIDEventTap, VDown);
115 CGEventPost(kCGHIDEventTap, VUp);
116 CGEventPost(kCGHIDEventTap, commandUp);
117 }
118
119 /**
120 * Delays a sending Command+key operation for delayInMS, and retries up to 'tries' times.
121 *
122 * This function is necessary in order to check that the intended window has come
123 * to the foreground. The "isActive" property only changes when the app gets back
124 * to the "run loop", so we can't block and check it.
125 */
126 void delayedSendShortcut(int modifier, int key, int64_t delayInMS, uint tries, NSWindow *window) {
127 COPYQ_LOG( QStringLiteral("Sending key codes %1 and %2 with delay %3ms (%4 retries to go)")
128 .arg(modifier)
129 .arg(key)
130 .arg(delayInMS)
131 .arg(tries) );
132
133 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayInMS * NSEC_PER_MSEC), dispatch_get_main_queue(), ^(void){
134 if (window && ![window isKeyWindow]) {
135 if (tries > 0) {
136 delayedSendShortcut(modifier, key, delayInMS, tries - 1, window);
137 } else {
138 log("Failed to raise application, will not paste.", LogWarning);
139 }
140 } else {
141 sendShortcut(modifier, key);
142 }
143 });
144 }
145
146 pid_t getPidForWid(WId find_wid) {
147 // Build a set of "normal" windows. This is necessary as "NSWindowList" gets things like the
148 // menubar (which can be "owned" by various apps).
149 CFRef<CFArrayRef> windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
150 for (NSDictionary* dict in (__bridge NSArray*)windowList.get()) {
151 long int pid = [(NSNumber*)[dict objectForKey:@"kCGWindowOwnerPID"] longValue];
152 unsigned long int wid = (unsigned long) [(NSNumber*)[dict objectForKey:@"kCGWindowNumber"] longValue];
153
154 if (wid == find_wid) {
155 return pid;
156 }
157 }
158
159 return 0;
160 }
161
162
163 long int getTopWindow(pid_t process_pid) {
164 // Build a set of "normal" windows. This is necessary as "NSWindowList" gets things like the
165 // menubar (which can be "owned" by various apps).
166 QSet<long int> widsForProcess;
167 CFRef<CFArrayRef> windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
168 for (NSDictionary* dict in (__bridge NSArray*)windowList.get()) {
169 long int pid = [(NSNumber*)[dict objectForKey:@"kCGWindowOwnerPID"] longValue];
170 long int wid = [(NSNumber*)[dict objectForKey:@"kCGWindowNumber"] longValue];
171 long int layer = [(NSNumber*)[dict objectForKey:@"kCGWindowLayer"] longValue];
172
173 if (pid == process_pid && layer == 0) {
174 widsForProcess.insert(wid);
175 }
176 }
177
178 // Now look through the windows in NSWindowList (which are ordered from front to back)
179 // the first window in this list which is also in widsForProcess is our frontmost "normal" window
180 long int wid = -1;
181 for (NSNumber *window : [NSWindow windowNumbersWithOptions:0]) {
182 const long int wid2 = [window longValue];
183 if (widsForProcess.contains(wid2)) {
184 wid = wid2;
185 break;
186 }
187 }
188 return wid;
189 }
190
191 QString getTitleFromWid(long int wid) {
192 QString title;
193
194 if (wid < 0) {
195 return title;
196 }
197
198 const void *windowid = reinterpret_cast<const void *>(static_cast<uintptr_t>(wid));
199 CFRef<CFArrayRef> windowArray = CFArrayCreate( NULL, &windowid, 1, NULL );
200 CFRef<CFArrayRef> descArray = CGWindowListCreateDescriptionFromArray(windowArray);
201
202 // Should only be one
203 for (NSDictionary* dict in (__bridge NSArray*)descArray.get()) {
204 title = QString::fromNSString([dict objectForKey:@"kCGWindowName"]);
205 }
206
207 return title;
208 }
209 } // namespace
210
211 MacPlatformWindow::MacPlatformWindow(NSRunningApplication *runningApp)
212 {
213 if (runningApp) {
214 m_runningApplication = runningApp;
215 m_windowNumber = getTopWindow(runningApp.processIdentifier);
216 COPYQ_LOG_VERBOSE("Created platform window for non-copyq");
217 } else {
218 log("Failed to convert runningApplication to application", LogWarning);
219 }
220 }
221
222 MacPlatformWindow::MacPlatformWindow(WId wid)
223 {
224 // Try using wid as an actual window ID
225 pid_t pid = getPidForWid(wid);
226 if (pid != 0) {
227 m_runningApplication = [NSRunningApplication runningApplicationWithProcessIdentifier:pid];
228 m_windowNumber = wid;
229 // This will return 'nil' unless this process owns the window
230 m_window = [NSApp windowWithWindowNumber: wid];
231 } else if (NSView *view = objc_cast<NSView>((id)wid)) {
232 // If given a view, its ours
233 m_runningApplication = [NSRunningApplication currentApplication];
234 m_window = [view window];
235 m_windowNumber = [m_window windowNumber];
236 COPYQ_LOG_VERBOSE("Created platform window for copyq");
237 } else {
238 log("Failed to convert WId to window", LogWarning);
239 }
240 }
241
242 MacPlatformWindow::MacPlatformWindow() = default;
243
244 MacPlatformWindow::~MacPlatformWindow() = default;
245
246 bool MacPlatformWindow::matchesWidget(const QWidget *widget) const
247 {
248 if (!widget || !widget->windowHandle())
249 return false;
250 WId wid = widget->winId();
251 if (NSView *view = objc_cast<NSView>((id)wid))
252 return [[view window] windowNumber] == m_windowNumber;
253 return static_cast<long int>(wid) == m_windowNumber;
254 }
255
256
257 QString MacPlatformWindow::getTitle()
258 {
259 QString appTitle;
260 if (m_runningApplication)
261 appTitle = QString::fromNSString([m_runningApplication localizedName]);
262
263 QString windowTitle;
264 if (m_window)
265 windowTitle = QString::fromNSString([m_window title]);
266 if (windowTitle.isEmpty() && m_windowNumber >= 0)
267 windowTitle = getTitleFromWid(m_windowNumber);
268
269 // We have two separate titles, the application title (shown at the top
270 // left in the menu bar and the window title (shown in the window bar).
271 // Some apps put the app name into the window title as well, some don't. We
272 // want to be able to match on the app name (e.g. Firefox, Safari, or
273 // Terminal) when writing commands, so we'll ensure that the app name is at
274 // the beginning of the returned window title.
275 QString result;
276 if (windowTitle.isEmpty()) {
277 result = appTitle;
278 } else if (appTitle.isEmpty() || windowTitle.startsWith(appTitle)) {
279 result = windowTitle;
280 } else {
281 result = QString("%1 - %2").arg(appTitle, windowTitle);
282 }
283 return result;
284 }
285
286 void MacPlatformWindow::raise()
287 {
288 if (m_window && m_runningApplication &&
289 [m_runningApplication isEqual:[NSRunningApplication currentApplication]]) {
290 COPYQ_LOG( QString("Raise own window \"%1\"").arg(getTitle()) );
291 [NSApp activateIgnoringOtherApps:YES];
292 [m_window makeKeyAndOrderFront:nil];
293 } else if (m_runningApplication) {
294 // Shouldn't need to unhide since we should have just been in this
295 // application..
296 //[m_runningApplication unhide];
297
298 COPYQ_LOG( QString("Raise a window \"%1\"").arg(getTitle()) );
299 [m_runningApplication activateWithOptions:NSApplicationActivateIgnoringOtherApps];
300 if (m_windowNumber != -1) {
301 auto window = [NSApp windowWithWindowNumber: m_windowNumber];
302 [window makeKeyAndOrderFront:nil];
303 }
304 } else {
305 ::log(QString("Tried to raise unknown window"), LogWarning);
306 }
307 }
308
309 bool MacPlatformWindow::pasteFromClipboard()
310 {
311 if (!m_runningApplication) {
312 log("Failed to paste to unknown window", LogWarning);
313 return false;
314 }
315
316 const AppConfig config;
317
318 const auto keyCodeV = keyCodeFromChar('v', kVK_ANSI_V);
319 if (m_window != nullptr) {
320 // Window MUST be raised, otherwise we can't send events to it
321 waitMs(config.option<Config::window_wait_before_raise_ms>());
322 raise();
323 waitMs(config.option<Config::window_wait_after_raised_ms>());
324
325 // Paste after after a delay, try 5 times
326 const int keyPressTimeMs = config.option<Config::window_key_press_time_ms>();
327 delayedSendShortcut(kVK_Command, keyCodeV, keyPressTimeMs, 5, m_window);
328 } else {
329 sendShortcut(kVK_Command, keyCodeV);
330 }
331
332 return true;
333 }
334
335 bool MacPlatformWindow::copyToClipboard()
336 {
337 if (!m_runningApplication) {
338 log("Failed to copy from unknown window", LogWarning);
339 return false;
340 }
341
342 const AppConfig config;
343
344 // Window MUST be raised, otherwise we can't send events to it
345 waitMs(config.option<Config::window_wait_before_raise_ms>());
346 raise();
347 waitMs(config.option<Config::window_wait_after_raised_ms>());
348
349 // Copy after after a delay, try 5 times
350 const int keyPressTimeMs = config.option<Config::window_key_press_time_ms>();
351 const auto keyCodeC = keyCodeFromChar('c', kVK_ANSI_C);
352 delayedSendShortcut(kVK_Command, keyCodeC, keyPressTimeMs, 5, m_window);
353 return true;
354 }