Skip to content

Instantly share code, notes, and snippets.

@nk9
Last active May 7, 2021 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nk9/bad67bde1c05d3bc4831967d5e204da1 to your computer and use it in GitHub Desktop.
Save nk9/bad67bde1c05d3bc4831967d5e204da1 to your computer and use it in GitHub Desktop.
A window that uses overlays to show its first responder and ALL of the views which have that responder as their nextValidKeyView. Useful for debugging key view loop issues in macOS applications.
//
// KVLWindow.swift
// KVLTest
//
// Created by Nick Kocharhook on 04/05/2021.
// Based in part on LMWindow by Micha Mazaheri
//
// Released under the MIT License: http://opensource.org/licenses/MIT
//
// Copyright 2021 Nick Kocharhook
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
import Cocoa
class KVLWindow: NSWindow {
static var _keyViewChainDebugMenuItemsInstalled: Bool = false
static var _showFirstResponderOverlays: Bool = true
static var _overlayWindows: [NSWindow] = []
static var _makeFirstResponderStack: [NSResponder] = []
override func becomeMain() {
if (KVLWindow._keyViewChainDebugMenuItemsInstalled == false) {
let appMenu = NSApp.mainMenu?.item(at: 0)?.submenu
// Reverse order
appMenu?.insertItem(NSMenuItem.separator(), at: 0)
appMenu?.insertItem(withTitle:"Show/Hide Overlays", action:#selector(_showHideFirstResponderOverlay), keyEquivalent:"O", at: 0)
KVLWindow._keyViewChainDebugMenuItemsInstalled = true
}
}
@objc func _showHideFirstResponderOverlay() {
KVLWindow._showFirstResponderOverlays = !KVLWindow._showFirstResponderOverlays
_showOverlayWindowsIfNeeded(self.firstResponder)
}
func _showOverlayWindowsIfNeeded(_ responder: NSResponder?) {
for win in KVLWindow._overlayWindows {
self.removeChildWindow(win)
win.orderOut(nil)
}
// Clear the windows
KVLWindow._overlayWindows = []
if let resp = responder {
if (KVLWindow._showFirstResponderOverlays && resp is NSView) {
let firstRespColor = NSColor.init(calibratedRed:0, green:50, blue:100, alpha:0.3)
_addOverlayWindow(resp as! NSView, color: firstRespColor)
// Add windows for the preceding views
for view in _allPreviousValidKeyViews() {
let color = NSColor.init(calibratedRed:100, green:0, blue:100, alpha:0.3)
_addOverlayWindow(view, color: color)
}
}
}
}
func _addOverlayWindow(_ view: NSView, color: NSColor) {
let frame = self.convertToScreen(view.convert(view.bounds, to:nil))
let overlay = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false)
overlay.backgroundColor = color
overlay.isOpaque = false
overlay.ignoresMouseEvents = true
self.addChildWindow(overlay, ordered: .above)
KVLWindow._overlayWindows.append(overlay)
}
func _allPreviousValidKeyViews() -> [NSView] {
var views: [NSView] = []
for view in self.contentView?.subviewsRecursive() ?? [] {
if view.acceptsFirstResponder {
if view.nextValidKeyView == self.firstResponder {
views.append(view)
}
}
}
return views
}
override func makeFirstResponder(_ responder: NSResponder?) -> Bool {
if KVLWindow._makeFirstResponderStack.count == 0 {
print("Make First Responder:")
}
if let resp: NSResponder = responder {
let depth = KVLWindow._makeFirstResponderStack.count
let indent = "".padding(toLength: depth*2, withPad: " ", startingAt: 0)
KVLWindow._makeFirstResponderStack.append(resp)
let classStr = String(describing: resp.self)
let id: String = resp.kvlIdentifier()
print("\(indent)\(classStr) \(id)")
}
let r = super.makeFirstResponder(responder)
_showOverlayWindowsIfNeeded(responder)
KVLWindow._makeFirstResponderStack.removeLast()
let depth = KVLWindow._makeFirstResponderStack.count
let indent = "".padding(toLength: depth*2, withPad: " ", startingAt: 0)
print("\(indent)mFR=\(r)")
if KVLWindow._makeFirstResponderStack.count == 0 {
print("--\n\n")
}
return r
}
}
extension NSView {
func subviewsRecursive() -> [NSView] {
return subviews + subviews.flatMap {$0.subviewsRecursive()}
}
}
extension NSResponder {
// Try to make a human-readable string from the object
func kvlIdentifier() -> String {
var id = ""
if let view = self as? NSView, let unwrappedId = view.identifier {
if let control = view as? NSControl {
if let button = control as? NSButton {
id = button.title
} else {
id = "\"\(control.stringValue)\""
}
} else {
id = unwrappedId.rawValue
}
}
return id
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment