How to position NSPopover in status bar application (macOS) - macos

I have created a macOS status bar application using SwiftUI and i finally have everything working the way i want it. The only problem is that when i use it on full screen the status bar hides and the popover menu gets chopped off. Any ideas?
MyApp.swift:
import SwiftUI
#main
struct MyApp: App {
#NSApplicationDelegateAdaptor(AppDelegate.self) var delegate;
var body: some Scene {
Settings {
ContentView()
}
}
}
class AppDelegate: NSObject,NSApplicationDelegate {
var statusItem: NSStatusItem!
var popOver: NSPopover!
func applicationDidFinishLaunching(_ notification: Notification){
let contentView = ContentView()
let popOver = NSPopover();
popOver.behavior = .transient
popOver.animates = true
popOver.contentViewController = NSHostingController(rootView: contentView)
popOver.setValue(true, forKeyPath: "shouldHideAnchor")
self.popOver = popOver
self.statusItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let MenuButton = self.statusItem.button {
MenuButton.image = NSImage(systemSymbolName: "display.2", accessibilityDescription: nil)
MenuButton.action = #selector(MenuButtonToggle)
}
}
#objc func MenuButtonToggle(_ sender: AnyObject){
if let button = self.statusItem.button {
if self.popOver.isShown{
self.popOver.performClose(sender)
}else {
self.popOver.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.popOver.contentViewController?.view.window?.makeKey()
}
}
}
}

In your code just add a "random" larger size than the popover itself.
I think this happens because the size of the popover is not calculated right away so there is a race condition in there, but this seems to work pretty well for me 👌
popOver.contentSize = NSSize(width: 600, height: 1)

Related

How to put searchable in NSPopover?

So I have the following ContentView shows as a popover in the menu bar.
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the popover
let popover = NSPopover()
popover.contentSize = NSSize(width: 500, height: 700)
popover.behavior = .transient
popover.contentViewController = NSHostingController(rootView: contentView)
self.popover = popover
// Create the status item
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let button = self.statusBarItem.button {
button.image = NSImage(named:NSImage.Name("Icon"))
button.action = #selector(togglePopover(_:))
}
(NSApp.delegate as! AppDelegate).statusBarItem.button?.image = NSImage(named:NSImage.Name("Icon"))
NSApp.activate(ignoringOtherApps: true)
}
#objc func togglePopover(_ sender: AnyObject?) {
if let button = self.statusBarItem.button {
if self.popover.isShown {
self.popover.performClose(sender)
} else {
self.popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
self.popover.contentViewController?.view.window?.becomeKey()
}
self.popover.contentViewController?.view.window?.becomeKey()
}
And my content view has a .searchable() tag. I see it when loading it under normal window but not when loading it under a popover. Does anyone know how can I adapt the searchable to the pop over?

TextField in popover. "This would eventually crash when the view is freed"

I have written an app to display timezones in a NSStatusBar popover. All good so far but when I add a second popover from a button inside the original popover view and include a TextField I start getting problems.
The TextField shows as having focus but it refuses input. If I toggle in and out of the second popover then I get a crash.
...as the first responder for window <_NSPopoverWindow: 0x7fb9c1807bb0>, but it is in a different window ((null))! This would eventually crash when the view is freed. The first responder will be set to nil.
I'm assuming these are related.
I have extracted just the NSStatus bar setup and the two popover views and it is fully repeatable in this toy instance. I use an EventMonitor to catch a click outside of the popover to close it. I don't think that is relevant but I have included it in the toy app for completeness
AppDelegate.swift
import Cocoa
import SwiftUI
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var popover: NSPopover!
var statusBarItem: NSStatusItem!
var eventMonitor: EventMonitor?
var contentView = ContentView()
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the popover
let popover = NSPopover()
popover.behavior = .transient
popover.contentViewController = NSHostingController(rootView: contentView)
self.popover = popover
// Create the status item
self.statusBarItem = NSStatusBar.system.statusItem(withLength: CGFloat(NSStatusItem.variableLength))
if let button = self.statusBarItem.button {
button.image = NSImage(named: "Icon")
button.action = #selector(togglePopover(_:))
}
eventMonitor = EventMonitor(mask: [.leftMouseDown, .rightMouseDown]) { [unowned self] event in
if self.popover.isShown {
closePopover(event)
}
}
eventMonitor?.start()
NSApp.activate(ignoringOtherApps: true)
}
#objc func togglePopover(_ sender: AnyObject?) {
if popover.isShown {
closePopover(sender)
} else {
showPopover(sender)
}
}
func showPopover(_ sender: AnyObject?) {
if let button = statusBarItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
self.popover.contentViewController?.view.window?.becomeKey()
}
eventMonitor?.start()
}
func closePopover(_ sender: AnyObject?) {
popover.performClose(sender)
eventMonitor?.stop()
}
}
open class EventMonitor {
fileprivate var monitor: AnyObject?
fileprivate let mask: NSEvent.EventTypeMask
fileprivate let handler: (NSEvent?) -> ()
public init(mask: NSEvent.EventTypeMask, handler: #escaping (NSEvent?) -> ()) {
self.mask = mask
self.handler = handler
}
deinit {
stop()
}
open func start() {
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler) as AnyObject?
}
open func stop() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
}
ContentView.swift
import SwiftUI
struct ContentView: View {
#State private var showingPopover = false
#State var value: String = "Initial Value"
var body: some View {
VStack {
Button {
showingPopover = true
} label: {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
}
.popover(isPresented: $showingPopover) {
EditView(value: $value)
}
Text("Hello, world!")
}
.padding()
}
}
struct EditView: View {
#Binding var value: String
var body: some View {
VStack {
TextField("Location ", text: $value) // the location as a string
.multilineTextAlignment(.center)
.lineLimit(1)
.onSubmit {
print("value submit \(value)")
}
}
.padding()
.frame(width:200, height: 50)
}
}
I've searched for information and found references to similar problems with windowed applications and needing to click in the 'window' before clicking in the TextField but that doesn't seem to do anything in this context
I'm building on MacOS 12.6.2 with Target set for 12.0

SwiftUI 2.0 can't remove .titled from styleMask on NSWindow using NSViewRepresentable

I'm reworking my app for SwiftUI 2.0 but have come across a problem when replicating what I could do with AppDelegate.
I'm using NSViewRepresentable to get access to NSWindow so I can remove the titlebar of the window (I know it's not in the guidelines but this will never be submitted). When removing .titled from styleMask, the app crashes.
struct WindowAccessor: NSViewRepresentable {
#Binding var window: NSWindow?
func makeNSView(context: Context) -> NSView {
let view = NSView()
DispatchQueue.main.async {
self.window = view.window
self.window?.isOpaque = false
self.window?.titlebarAppearsTransparent = true
self.window?.backgroundColor = NSColor.clear
self.window?.styleMask = [.fullSizeContentView]
self.window?.isMovableByWindowBackground = true
self.window?.backingType = .buffered
}
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
}
#main
struct MyApp_App: App {
#State private var window: NSWindow?
var body: some Scene {
WindowGroup {
ContentView().background(WindowAccessor(window: $window))
}
}
}
struct ContentView: View {
var body: some View {
Text("Hello, world!").padding().background(Color(NSColor.windowBackgroundColor))
}
}
When I run the app I get Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
All I'm trying to achieve with my app is a Menu Bar application that looks exactly like Spotlight. No dock icon, no title bar, all preferences to be handled by a popover or another window.
EDIT:
Is this something to do with the canBecomeKey property?

SwiftUI Invoke NSPopover with Keyboard Shortcut

I'm building a menu bar application with SwiftUI for macOS Big Sur and can't figure out how to open the popover (the app's main window, since it's a menu bar app) with a keyboard shortcut. I want users to be able to view the window by pressing Command + [a letter] regardless of what else they're doing on their computer (as long as the application is open of course). Here are the main functions and code that control the popover:
#main
struct MenuBarPopoverApp: App {
#NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
Settings{
EmptyView()
}
.commands {
MenuBarPopoverCommands(appDelegate: appDelegate)
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
var popover = NSPopover.init()
var statusBarItem: NSStatusItem?
var contentView: ContentView!
override class func awakeFromNib() {}
func applicationDidFinishLaunching(_ notification: Notification) {
print("Application launched")
NSApplication.shared.activate(ignoringOtherApps: true)
contentView = ContentView()
popover.animates = false
popover.behavior = .transient
let contentVc = NSViewController()
contentVc.view = NSHostingView(rootView: contentView.environmentObject(self))
popover.contentViewController = contentVc
statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
let itemImage = NSImage(named: "statusBarIcon")
itemImage?.isTemplate = true
statusBarItem?.button?.image = itemImage
statusBarItem?.button?.action = #selector(AppDelegate.togglePopover(_:))
}
#objc func showPopover(_ sender: AnyObject?) {
if let button = statusBarItem?.button {
NSApplication.shared.activate(ignoringOtherApps: true)
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
#objc func closePopover(_ sender: AnyObject?) {
popover.performClose(sender)
}
#objc func togglePopover(_ sender: AnyObject?) {
if popover.isShown {
closePopover(sender)
} else {
showPopover(sender)
}
}
}
And the MenuBarPopoverCommands (the main part of the app is a text editor, so I have a bunch of keyboard shortcuts relating to that):
struct MenuBarPopoverCommands: Commands {
let appDelegate: AppDelegate
init(appDelegate: AppDelegate) {
self.appDelegate = appDelegate
}
var body: some Commands {
CommandMenu("Edit") {
Section {
Button("Cut") {
appDelegate.contentView.editCut()
}.keyboardShortcut(KeyEquivalent("x"), modifiers: .command)
Button("Copy") {
appDelegate.contentView.editCopy()
}.keyboardShortcut(KeyEquivalent("c"), modifiers: .command)
Button("Paste") {
appDelegate.contentView.editPaste()
}.keyboardShortcut(KeyEquivalent("v"), modifiers: .command)
Button("Undo") {
appDelegate.contentView.undo()
}.keyboardShortcut(KeyEquivalent("z"), modifiers: .command)
Button("Redo") {
appDelegate.contentView.redo()
}.keyboardShortcut(KeyEquivalent("z"), modifiers: [.command, .shift])
Button("Bold") {
appDelegate.contentView.bold()
}.keyboardShortcut(KeyEquivalent("b"), modifiers: .command)
Button("Italic") {
appDelegate.contentView.italic()
}.keyboardShortcut(KeyEquivalent("i"), modifiers: .command)
Button("Select All") {
appDelegate.contentView.editSelectAll()
}.keyboardShortcut(KeyEquivalent("a"), modifiers: .command)
}
}
}
}
Swift 5 solution was presented in https://stackoverflow.com/a/58225397/3984522. However, there's a nice package, which does the job https://github.com/soffes/HotKey in a couple of lines of code:
import SwiftUI
import HotKey
#main
struct MenuBarPopoverApp: App {
#NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
Settings{
EmptyView()
}
.commands {
MenuBarPopoverCommands(appDelegate: appDelegate)
}
}
}
class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
var popover = NSPopover.init()
var statusBarItem: NSStatusItem?
var contentView: ContentView!
let hotKey = HotKey(key: .x, modifiers: [.control, .shift]) // Global hotkey
override class func awakeFromNib() {}
func applicationDidFinishLaunching(_ notification: Notification) {
print("Application launched")
NSApplication.shared.activate(ignoringOtherApps: true)
contentView = ContentView()
popover.animates = false
popover.behavior = .transient
let contentVc = NSViewController()
contentVc.view = NSHostingView(rootView: contentView.environmentObject(self))
popover.contentViewController = contentVc
statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
let itemImage = NSImage(systemSymbolName: "eye", accessibilityDescription: "eye")
itemImage?.isTemplate = true
statusBarItem?.button?.image = itemImage
statusBarItem?.button?.action = #selector(AppDelegate.togglePopover(_:))
hotKey.keyUpHandler = { // Global hotkey handler
self.togglePopover()
}
}
#objc func showPopover(_ sender: AnyObject? = nil) {
if let button = statusBarItem?.button {
NSApplication.shared.activate(ignoringOtherApps: true)
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
}
#objc func closePopover(_ sender: AnyObject? = nil) {
popover.performClose(sender)
}
#objc func togglePopover(_ sender: AnyObject? = nil) {
if popover.isShown {
closePopover(sender)
} else {
showPopover(sender)
}
}
}

NSClickGestureRecognizer not working on NSStatusItem

Trying to recognize a right click on a NSStatusItem I got a suggestion ( Thanks to Zoff Dino ) to use a NSClickGestureRecognizer for that. But for some bizarre reason it isn't working as it should be. I am able to recognize a left click (buttonMask = 0x1) but not a right-click (buttonMask = 0x2). This is how I would like it to work but it isn't:
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
if let button = statusItem.button {
// Add right click functionality
let gesture = NSClickGestureRecognizer()
gesture.buttonMask = 0x2 // right mouse
gesture.target = self
gesture.action = "rightClickAction:"
button.addGestureRecognizer(gesture)
}}
func rightClickAction(sender: NSGestureRecognizer) {
if let button = sender.view as? NSButton {
NSLog("rightClick")
}
}
UPDATE:
I still did not manage to gets to work. Somehow it doesn't react on a right click (but changing the code on a left click) does. I guess some really simple issues are occurring that seem to block it from working. Even stranger is the fact that gesture.buttonMask = 0x1 works on the left click.
An alternative solution rather than NSClickGestureRecognizer is to attach a custom view to the status bar and handle the event from there.
The small disadvantage is you have to take care of the drawing and menu delegate methods.
Here a simple example:
Create a file StatusItemView a subclass of NSView
import Cocoa
class StatusItemView: NSView, NSMenuDelegate {
//MARK: - Variables
weak var statusItem : NSStatusItem!
var menuVisible = false
var image : NSImage! {
didSet {
if image != nil {
statusItem.length = image.size.width
needsDisplay = true
}
}
}
//MARK: - Override functions
override func mouseDown(theEvent: NSEvent) {
if let hasMenu = menu {
hasMenu.delegate = self
statusItem.popUpStatusItemMenu(hasMenu)
needsDisplay = true
}
}
override func rightMouseDown(theEvent: NSEvent) {
Swift.print(theEvent)
}
//MARK: - NSMenuDelegate
func menuWillOpen(menu: NSMenu) {
menuVisible = true
needsDisplay = true
}
func menuDidClose(menu: NSMenu) {
menuVisible = false
menu.delegate = nil
needsDisplay = true
}
//MARK: - DrawRect
override func drawRect(dirtyRect: NSRect) {
statusItem.drawStatusBarBackgroundInRect(bounds, withHighlight:menuVisible)
let origin = NSMakePoint(2.0, 3.0) // adjust origin if necessary
image?.drawAtPoint(origin, fromRect: dirtyRect, operation: .CompositeSourceOver, fraction: 1.0)
}
}
In AppDelegate you need a reference to the custom menu and an instance variable for the NSStatusItem instance
#IBOutlet weak var menu : NSMenu!
var statusItem : NSStatusItem!
In applicationDidFinishLaunching create the view and attach it to the status item. Be aware to set the image of the view after attaching it to make sure the width is considered.
func applicationDidFinishLaunching(aNotification: NSNotification) {
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength)
let statusItemView = StatusItemView(frame: NSRect(x: 0.0, y: 0.0, width: statusItem.length, height: 22.0))
statusItemView.statusItem = statusItem;
statusItemView.menu = menu
statusItem.view = statusItemView
statusItemView.image = NSImage(named: NSImageNameStatusAvailable)
}
The special case control-click to trigger the right-click function is not implemented.

Resources