肇鑫的技术博客

业精于勤,荒于嬉

macOS应用登录时启动的实现方式

Mac版咕唧2移除了今日扩展,改为了在菜单栏常驻图标的方式。这是因为,今日扩展的方式,不方便使用表情键盘,一旦弹出点击表情键盘,今日栏就会自动关闭。

常驻图标,拥有一个开机启动才是最好的。实现登录时启动,有多种方式,不过随着macOS的发展,一些方式因为沙盒的缘故已经不能使用了。本文介绍的是目前最新的通用方式,适合macOS 10.6及以上,iOS 12.1及以上,wathcOS 5.1及以上的系统。

原理

原理是这样的,对于较新的苹果系统,应用可以通过ServiceManagementSMLoginItemSetEnabled(_:_:)函数注册和取消开机自启。

这个自启是针对当前账户级别的。即每个用户,都需要在开启应用时单独同意,才会在自己进入系统后,自动启动对应的应用。

下面我们来具体看一看这个函数,func SMLoginItemSetEnabled(_ identifier: CFString, _ enabled: Bool) -> Bool

函数的第一个参数是id,这个id就是要执行的应用的包的ID。并且这个应用,必须位于主应用相对路径为Contents/Library/LoginItems的位置。

函数的第二个参数是注册还是取消开机自启。是为开启,否为取消。

函数的返回值则是这个操作是否成功。操作成功返回是,操作失败返回否。

小结

苹果在系统中预定了一项服务叫ServiceManagement,它允许用户在编写主程序时,额外添加一个程序,用于登录时自启。这个程序在主程序中的位置是固定的,必须位于Contents/Library/LoginItems,然后主程序通过SMLoginItemSetEnabled(_:_:)来实现对于开机自启的注册和取消。

实现

知道了原理。实现就简单了。需要第二个应用,所以我们就需要创建它。因为它是服务类型的,不需要界面,所以要将其设定为后台应用。因为它是伴随着主应用安装的,所以它不需要单独安装等等。

这个步骤我就不详细说明了。需要的可以看看这篇文章:Modern Login Items

你创建的辅助应用,Xcode默认会使用最新的系统,而不是你在项目中限定的系统。比如你的项目支持macOS 10.14及以上,但是Xcode创建的辅助应用却是macOS 10.15的。你必须在目标的系统信息里删掉这个10.15,才会应用你的默认限制。

如果你不删除,就会发现你的应用在10.14的系统里无法伴随用户登录自动启动。并且找不到任何提示。你只有在Finder中主动解包,才会看到应用上面的不能执行的标记。

这个是Xcode的锅。

例子

如果你需要的是Objective C的实现,那么看上面的那个说明。
我自己参考Objective C版的,写了一个Swift版的。你可以在这里下载

其它

Register as Login Item with Cocoa?

A Well-formed macOS Menu Bar Application in Sandbox

NSPressGestureRecognizer在模态时失效问题的解决

最近在使用NSPressGestureRecognizer处理长按的时候发现了问题。如果弹出的视图控制器,是采用的show方式,则一切正常。但如果是使用modal的方式,则无法识别长按。

代码如下:

import Cocoa

class VC: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = NSView(frame: NSRect(x: 100, y: 100, width: 100, height: 100))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.systemBrown.cgColor
        let longPress = NSPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        view.addGestureRecognizer(longPress)
        self.view.addSubview(view)
    }

    @objc func longPress(_ sender:Any) {
        print("long")
    }
}

分析

我自己弄了半天,没能找到解决方案,于是跑到SO上问。NSPressGestureRecognizer doesn't work in modal ViewController。一觉睡醒,发现已经有人回答了。

Interesting. What seems to be happening is that the recognizer state never changes from possible to "began" in the modal example.

class Recognizer: NSPressGestureRecognizer {

    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        self.state = .began
    }

}

解答的代码虽然不完整,但是至少提供了一个方向。按照解答的思路,我重新实现了NSPressGestureRecognizer

模拟的目标是实现在show方式下同样的状态改变。即在正常长按的情况下,依次实现possible、began、end。使用一个Timer,在满足长按时间的情况下,发送began,并且在用户抬起鼠标且有began的情况下,发送end。

import Cocoa

class VC: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = NSView(frame: NSRect(x: 100, y: 100, width: 100, height: 100))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.systemBrown.cgColor
        let longPress = MyPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        view.addGestureRecognizer(longPress)

        let click = NSClickGestureRecognizer(target: self, action: #selector(click(_:)))
        view.addGestureRecognizer(click)

        self.view.addSubview(view)
    }

    @objc func click(_ sender:Any) {
        print("click")
    }

    @objc func longPress(_ sender:Any) {
        guard let gesture = sender as? NSGestureRecognizer else { return }

        switch gesture.state {
        case .ended:
            print("long")
        default:
            print(gesture.state)
        }
    }
}

class MyPressGestureRecognizer: NSPressGestureRecognizer {
    private weak var timer:Timer? = nil
    private var hasBegan = false
    private var hasCancelled = false

    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)

        timer = Timer.scheduledTimer(withTimeInterval: minimumPressDuration, repeats: false) { (timer) in
            defer {
                timer.invalidate()
            }

            DispatchQueue.main.async {
                self.state = .began
                self.hasBegan = true
            }
        }
    }

    override func mouseUp(with event: NSEvent) {
        if hasBegan {
            self.state = .ended
            self.hasBegan = false
        }

        super.mouseUp(with: event)
    }

    override func reset() {
        timer?.invalidate()
        super.reset()
    }
}

extension NSGestureRecognizer.State:CustomStringConvertible {
    public var description:String {
        switch self {
        case .possible:
            return "possible"
        case .began:
            return "began"
        case .changed:
            return "changed"
        case .ended:
            return "ended"
        case .cancelled:
            return "cancelled"
        case .failed:
            return "failed"
        @unknown default:
            return "default"
        }
    }
}

运行之后,发现我实现的代码,和苹果原本的NSPressGestureRecognizer,效果完全一样。也就是说,我的代码同样有模态方式下,无法识别长按的问题。

再次思考,我发现问题出现Timer上,在模态运行的视图控制器,Timer不会执行。我猜,苹果大概也是代码中使用了Timer,才会有同样的问题。

解决

最终的方案是不使用Timer,增加一个是否取消的参数进行判断。代码如下:

import Cocoa

class VC: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let view = NSView(frame: NSRect(x: 100, y: 100, width: 100, height: 100))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.systemBrown.cgColor
        let longPress = MyPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
        view.addGestureRecognizer(longPress)

        let click = NSClickGestureRecognizer(target: self, action: #selector(click(_:)))
        view.addGestureRecognizer(click)

        self.view.addSubview(view)
    }

    @objc func click(_ sender:Any) {
        print("click")
    }

    @objc func longPress(_ sender:Any) {
        guard let gesture = sender as? NSGestureRecognizer else { return }

        switch gesture.state {
        case .ended:
            print("long")
        default:
            print(gesture.state)
        }
    }
}

class MyPressGestureRecognizer: NSPressGestureRecognizer {
    private var hasBegan = false
    private var hasCancelled = false

    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)

        hasCancelled = false

        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Int(minimumPressDuration * 1000))) {
            if !self.hasCancelled {
                self.state = .began
                self.hasBegan = true
            }
        }
    }

    override func mouseUp(with event: NSEvent) {
        if hasBegan {
            self.state = .ended
            self.hasBegan = false
        } else {
            self.hasCancelled = true
        }

        super.mouseUp(with: event)
    }
}

extension NSGestureRecognizer.State:CustomStringConvertible {
    public var description:String {
        switch self {
        case .possible:
            return "possible"
        case .began:
            return "began"
        case .changed:
            return "changed"
        case .ended:
            return "ended"
        case .cancelled:
            return "cancelled"
        case .failed:
            return "failed"
        @unknown default:
            return "default"
        }
    }
}

总结

  1. Timer在模态时会失效。我们在使用时需要小心。
  2. 上面的代码只处理了鼠标左键,如果想处理其它按键的长按,也可以用同样的方式进行处理。

参考

NSPressGestureRecognizer doesn't work in modal ViewController

NSCollectionView的选中与恢复

在使用NSCollectionView中发现,如果有选中的项目,那么在重新加载后,选中的项目可能会出现随机的错位。如图:

seleted ite

已经选中了中间的项目,点击底部的Reload按钮后,选中的背景跑到右边的项目上去了。

seleted item reload

代码如下:

import Cocoa

class ViewController: NSViewController {
    @IBOutlet weak var collectionView: NSCollectionView!
    
    private var sources:[String] = [
        "step one",
        "step two",
        "step three",
        "step four",
        "step five",
        "step six",
        "step seven",
        "step eight"
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        registerCollectionViewItem()
    }
    
    private func registerCollectionViewItem() {
        collectionView.register(Item.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("Item"))
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func reloadButtonClicked(_ sender: Any) {
        collectionView.reloadData()
    }
}

extension ViewController:NSCollectionViewDataSource {
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return sources.count
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        
        let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("Item"), for: indexPath)
        item.textField?.stringValue = self.sources[indexPath.item]
         
        return item
    }
}

extension ViewController:NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("select")
    }
    
    func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
        print("deselect")
    }
}

注意:上面提到,跑偏的是“选中的背景”,而“非选中的状态”。因为在collectionView.reloadData()之后,所有的选中状态都清空了。

@IBAction func reloadButtonClicked(_ sender: Any) {
    print(collectionView.selectionIndexPaths.count) // print 1
    
    collectionView.reloadData()
    
    print(collectionView.selectionIndexPaths.count) // print 0
}

根据苹果文档,重新加载的过程是

Call this method when the data in your data source object changes or when you want to force the collection view to update its contents. When you call this method, the collection view discards any currently visible items and views and redisplays them.

也就是说,在数据源改变的时候,重新加载。而如果我们的数据源没有包含选中的信息,大多数情况,我们不会将选中信息保存到数据源,那么重新加载之后,选中的状态就消失了。

分析

既然状态是清空的,为什么还会有错位显示“选中的背景”的问题呢?这是因为,苹果在重新加载的时候,为了效率,会重复使用之前创建的项目,同时还采用了并行的处理方式进行生成,因此,会导致显示背景的错乱。

解决思路有两个,一个是手动恢复选择。一个是将选中状态写到数据源。

方法一:手动恢复选择

思路:先保存选中的数据,然后重新加载,最后恢复。代码如下:

@IBAction func reloadButtonClicked(_ sender: Any) {
    let indexPaths = collectionView.selectionIndexPaths
    
    collectionView.reloadData()
    
    collectionView.selectItems(at: indexPaths, scrollPosition: .init())
}

func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
    
    let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("Item"), for: indexPath)
    item.textField?.stringValue = self.sources[indexPath.item]
    
    item.highlightState = .none
     
    return item
}

注意看一下第14行,即item.highlightState = .none,因为在应用中恢复选中,并不会激发选中的状态改变,所以我们必须手动更新选中状态。这里相应的代码如下。

import Cocoa

class Item: NSCollectionViewItem {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.wantsLayer = true
        self.highlightState = .none
    }
    
    override var highlightState: NSCollectionViewItem.HighlightState {
        didSet {
            switch highlightState {
            case .none:
                self.view.layer?.backgroundColor = isSelected ? NSColor.systemBlue.withAlphaComponent(0.8).cgColor : NSColor.systemGreen.withAlphaComponent(0.8).cgColor
            case .forSelection:
                self.view.layer?.backgroundColor = NSColor.systemBlue.withAlphaComponent(0.5).cgColor
            case .forDeselection:
                self.view.layer?.backgroundColor = NSColor.systemGreen.withAlphaComponent(0.5).cgColor
            case .asDropTarget:
                fatalError()
            @unknown default:
                fatalError()
            }
        }
    }
}

那么问题来了,我们的思路是先重新加载,之后恢复选中。既然是这样的顺序,为什么在重新加载的时候,项目会是已经选中的状态呢?不应该是重新加载完成,才选中的吗?这是因为,所有的重新加载,都不是立即重新加载的。而是先恢复状态,然后在下一个事件循环才加载。所以实际的运行类似如下的伪代码:

public func reloadData() {
    // 恢复状态
    DispatchQueue.main.async {
        // 重新加载
    }
}

因此,实际运行的顺序是:

  1. 恢复状态
  2. 恢复选中
  3. 重新加载

这样在实际的重新加载中,项目本身已经是选中的状态了。

另外一个小问题

我们知道,在macOS中,我们可以使用快捷键来进行一些常用的操作。比如利用cmd+a,我们可以进行全部选中。但是如果现在我们使用全部选中,虽然在控制台,我们看到的确是选中了。但是实际上,选中的背景并没有应用。这是因为NSCollectionViewItem.highlightState是针对鼠标操作的,直接用键盘操作,没有鼠标操作的过程,因此背景颜色就没有改变。

分析

highlightState没有改变的,但是选中状态改变了。所以我们在选中状态改变之后,进行背景颜色的改变。代码如下:

import Cocoa

class Item: NSCollectionViewItem {
    
    override var isSelected: Bool {
        didSet {
            self.view.layer?.backgroundColor = isSelected ? NSColor.systemBlue.withAlphaComponent(0.8).cgColor : NSColor.systemGreen.withAlphaComponent(0.8).cgColor
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.wantsLayer = true
        self.isSelected = false
    }
    
    override var highlightState: NSCollectionViewItem.HighlightState {
        didSet {
            switch highlightState {
            case .none:
                break
            case .forSelection:
                self.view.layer?.backgroundColor = NSColor.systemBlue.withAlphaComponent(0.5).cgColor
            case .forDeselection:
                self.view.layer?.backgroundColor = NSColor.systemGreen.withAlphaComponent(0.5).cgColor
            case .asDropTarget:
                fatalError()
            @unknown default:
                fatalError()
            }
        }
    }
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
    
    let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("Item"), for: indexPath)
    item.textField?.stringValue = self.sources[indexPath.item]
     
    return item
}

这里,我们移除了.none状态对于背景颜色的改变,而是采用isSelecteddidSet。并且在viewDidLoad()中恢复状态。这样,我们就不必在collectionView(_:itemForRepresentedObjectAt:)恢复状态了。

方法二:将选中状态写到数据源

单纯的将选中状态写入到数据源很简单,就不详细叙述了。这里介绍的是在不将选中状态写入到数据源的情况下,利用中间对象来进行处理的办法。

我们创建了一个中间对象StateObject<Element>来保存真正的数据和是否选中的状态。这样,就可以不必在真正的数据源中记录选中信息了。

class ViewController: NSViewController {
    @IBOutlet weak var collectionView: NSCollectionView!
    
    private var sources:[String] = [
        "step one",
        "step two",
        "step three",
        "step four",
        "step five",
        "step six",
        "step seven",
        "step eight"
    ]
    
    lazy private var elements:[StateObject<String>] = self.sources.map { StateObject($0) }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        registerCollectionViewItem()
    }
    
    private func registerCollectionViewItem() {
        collectionView.register(Item.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier("Item"))
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func reloadButtonClicked(_ sender: Any) {
        collectionView.reloadData()
    }
}

extension ViewController:NSCollectionViewDataSource {
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return elements.count
    }
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        
        let dataObject = elements[indexPath.item]
        let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier("Item"), for: indexPath)
        item.textField?.stringValue = dataObject.object
        
        if dataObject.isSelected {
            item.isSelected = true
            collectionView.selectionIndexPaths.insert(indexPath)
        } else {
            item.isSelected = false
        }
         
        return item
    }
}

extension ViewController:NSCollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        print("select")
        
        indexPaths.forEach {
            elements[$0.item].isSelected = true
        }
    }
    
    func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
        print("deselect")
        
        indexPaths.forEach {
            elements[$0.item].isSelected = false
        }
    }
}

class StateObject<Element> {
    var isSelected:Bool
    var object:Element
    
    init(_ object:Element) {
        self.object = object
        isSelected = false
    }
}
import Cocoa

class Item: NSCollectionViewItem {
    
    override var isSelected: Bool {
        didSet {
            self.view.layer?.backgroundColor = isSelected ? NSColor.systemBlue.withAlphaComponent(0.8).cgColor : NSColor.systemGreen.withAlphaComponent(0.8).cgColor
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.wantsLayer = true
    }
    
    override var highlightState: NSCollectionViewItem.HighlightState {
        didSet {
            switch highlightState {
            case .none:
                break
            case .forSelection:
                self.view.layer?.backgroundColor = NSColor.systemBlue.withAlphaComponent(0.5).cgColor
            case .forDeselection:
                self.view.layer?.backgroundColor = NSColor.systemGreen.withAlphaComponent(0.5).cgColor
            case .asDropTarget:
                fatalError()
            @unknown default:
                fatalError()
            }
        }
    }
}

总结

  1. 项目的选中,从鼠标点击角度看,一个分成三步:
    1. 项目原始状态,此时的NSCollectionViewItem.HighlightStatenone
    2. 鼠标按压,此时的NSCollectionViewItem.HighlightStateforSelection
    3. 鼠标放开,此时的NSCollectionViewItem.HighlightStatenone
  2. 而如果之前有选中的项目,并且只允许单选的话,那么已选中项目,对应上面2的是forDeselection
  3. 我们可以通过状态none结合isSelected来判断应该设置何种的背景颜色。但是这种方式不如直接在isSelecteddidSet中设置更为方便。这是因为,只有鼠标交互才会改变NSCollectionViewItem.HighlightState,而无论何种交互方式,都会改变isSelected,后者才是确认项目是否已经选中的方式。
  4. 每次重新加载,NSCollectionView的状态都会立即重置,并且在下一个主线程周期进行实际加载。
  5. 我们可以通过暂存并手动恢复的方式来恢复选择,也可以直接将选中状态直接写入到数据源。如果后者不方便,我们可以创建中间对象,来进行处理。
  6. 相对于手动恢复的方式,使用中间对象来进行处理,更加自然,代码也更加集中,更方便今后的修改。