您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

上手 Touch Bar:用 Objective-C 寫一個菜單列小工具

編輯:iOS 開發基礎

看到新款 MacBook 的 Touch Bar,第一反應是這東西能拿來幹什麼。於區域限制與可編程性之間反覆權衡之後,我寫了個小工具 CPUBar——它能在 Touch Bar 上逐個開關 CPU 核心(當然,主核心是不給關的)。

下面以 Objective-C 為例,說明一個最小可用的 Touch Bar 應用該怎麼搭。

第一步:讓 AppDelegate 成為 Touch Bar 提供者

新建 Cocoa Application,讓 AppDelegate 繼承 NSResponder,並在實現文件中聲明遵循 NSTouchBarDelegate。

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSTouchBarDelegate>
@end

之所以要繼承 NSResponder,是因為系統查找 Touch Bar 的方式決定的。Apple 文檔的原話是:

Touch bars are discovered by searching certain well known components of the application for objects that conform to the NSTouchBarProvider protocol.

也就是說,系統會按固定順序在進程內查找遵循 NSTouchBarProvider 協議的對象,順序依次是:

  • application delegate

  • application 對象本身

  • 主窗口的 window controller

  • 主窗口的 delegate

  • 主窗口本身

  • 主窗口的 first responder

  • 鑰匙窗口(key window)的 window controller / delegate / 窗口本身 / first responder

對應的獲取代碼大致如下:

// Objective-C                                   // Swift
[[NSApplication sharedApplication] delegate];   // NSApplication.shared().delegate
[NSApplication sharedApplication];              // NSApplication.shared()
[[[NSApplication sharedApplication] mainWindow] windowController];  // NSApplication.shared().mainWindow?.windowController
[[[NSApplication sharedApplication] mainWindow] delegate];          // NSApplication.shared().mainWindow?.delegate
[[NSApplication sharedApplication] mainWindow];                     // NSApplication.shared().mainWindow
[[[NSApplication sharedApplication] mainWindow] firstResponder];    // NSApplication.shared().mainWindow?.firstResponder
[[[NSApplication sharedApplication] keyWindow] windowController];   // NSApplication.shared().keyWindow?.windowController
[[[NSApplication sharedApplication] keyWindow] delegate];           // NSApplication.shared().keyWindow?.delegate
[[NSApplication sharedApplication] keyWindow];                      // NSApplication.shared().keyWindow
[[[NSApplication sharedApplication] keyWindow] firstResponder];     // NSApplication.shared().keyWindow?.firstResponder

文檔還補充:如果這些對象是 NSResponder 或其子類實例,那麼以它為起點的響應者鏈也會被繼續搜索。猜想的實現大致如下:

NSResponder *next = [self nextResponder];
while (next) {
    // 是否是 NSTouchBar provider?
    //   YES → break
    //   NO  → next = [next nextResponder];
}

第二步:重寫 makeTouchBar

讓 AppDelegate 繼承 NSResponder 還有一個原因:NSTouchBar.h 中為 NSResponder 定義了一個 category。

@interface NSResponder (NSTouchBarProvider)

/* 與該響應者關聯的 touch bar。若未顯式設置,NSResponder 會向自己發送 -makeTouchBar
   以創建默認的 touch bar。此屬性會被歸檔。 */
@property (strong, readwrite, nullable) NSTouchBar *touchBar NS_AVAILABLE_MAC(10_12_1);

/* 子類應重寫此方法,以創建並配置該響應者的默認 touch bar。 */
- (nullable NSTouchBar *)makeTouchBar NS_AVAILABLE_MAC(10_12_1);

@end

註釋說得很清楚:沒有顯式設置 touchBar 時,系統會調用 -makeTouchBar 生成一個;子類應該重寫這個方法來構建自己的 Touch Bar。所以我們只需要在 AppDelegate 中重寫它。

創建 NSTouchBar 本身很簡單:alloc、init,然後設置 customizationIdentifier 與 delegate。

self.touchBar = [[NSTouchBar alloc] init];
[self.touchBar setCustomizationIdentifier:@"com.0xBBC.CPUBar"];
[self.touchBar setDelegate:self];

customizationIdentifier 乍看是 NSTouchBarCustomizationIdentifier,實際上只是個 typedef 的字符串,直接寫字面量即可:

typedef NSString * NSTouchBarCustomizationIdentifier NS_EXTENSIBLE_STRING_ENUM;

接著設置 defaultItemIdentifiers——這個屬性會在初始化 item 時作為參數傳給 -[NSTouchBarDelegate touchBar:makeItemForIdentifier:]。

省略 CPU 信息獲取過程,完整的 -makeTouchBar 如下:

- (NSTouchBar *)makeTouchBar {
    self.touchBar = [[NSTouchBar alloc] init];

    [self.touchBar setCustomizationIdentifier:@"com.0xBBC.CPUBar"];
    [self.touchBar setDelegate:self];

    if ([self retriveProcessorInfo]) {
        NSMutableArray *defaultItemIdentifiers = [[NSMutableArray alloc] init];
        for (int i = 0; i < processor_count; i++) {
            [defaultItemIdentifiers addObject:[[NSString alloc] initWithFormat:@"com.0xBBC.CPUBar.CPU%d", i]];
        }
        [self.touchBar setDefaultItemIdentifiers:defaultItemIdentifiers];
    } else {
        [self alertMessage:@"Oops, CPUBar needs root privilege to run."
                informative:@"Try to run CPUBar with root privilege"];
        [NSApp terminate:nil];
    }

    return self.touchBar;
}

第三步:實現 delegate 方法創建 item

這裡選擇 NSCustomTouchBarItem,內部放一個 NSButton,設置好標題後把 button 賦給 item 的 view。

- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar
              makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {
    NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

    NSButton *button = [NSButton buttonWithTitle:@"" target:self action:@selector(setProcessor:)];
    button.tag = [[identifier substringFromIndex:@"com.0xBBC.CPUBar.CPU".length] integerValue];

    processor_basic_info_data_t basic_info;
    mach_msg_type_number_t info_count = PROCESSOR_BASIC_INFO_COUNT;
    processor_info(processor_list[button.tag], PROCESSOR_BASIC_INFO, &port,
                   (processor_info_t)&basic_info, &info_count);

    if (basic_info.is_master) {
        // 通常它是 0 號,但以防萬一
        masterCPU = button.tag;
    }

    button.attributedTitle = [self stringForCPU:button.tag status:basic_info.running];
    item.view = button;

    return item;
}

到這裡,一個能用的 Touch Bar 就成型了。

完整 AppDelegate.m

#import "AppDelegate.h"

#define CPU_STATUS_MASK 0x1000

@implementation AppDelegate {
    mach_port_t port;
    host_priv_t priv_port;
    processor_port_array_t processor_list;
    mach_msg_type_number_t processor_count;
    NSInteger masterCPU;
}

#pragma mark - NSApplicationDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    masterCPU = -1;
    processor_count = 0;
    processor_list = (processor_port_array_t)0;
    [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
}

#pragma mark - NSTouchBarDelegate

- (NSTouchBar *)makeTouchBar {
    self.touchBar = [[NSTouchBar alloc] init];
    [self.touchBar setCustomizationIdentifier:@"com.0xBBC.CPUBar"];
    [self.touchBar setDelegate:self];

    if ([self retriveProcessorInfo]) {
        NSMutableArray *defaultItemIdentifiers = [[NSMutableArray alloc] init];
        for (int i = 0; i < processor_count; i++) {
            [defaultItemIdentifiers addObject:[[NSString alloc] initWithFormat:@"com.0xBBC.CPUBar.CPU%d", i]];
        }
        [self.touchBar setDefaultItemIdentifiers:defaultItemIdentifiers];
    } else {
        [self alertMessage:@"Oops, CPUBar needs root privilege to run."
                informative:@"Try to run CPUBar with root privilege"];
        [NSApp terminate:nil];
    }

    return self.touchBar;
}

- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar
              makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {
    NSCustomTouchBarItem *item = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

    NSButton *button = [NSButton buttonWithTitle:@"" target:self action:@selector(setProcessor:)];
    button.tag = [[identifier substringFromIndex:@"com.0xBBC.CPUBar.CPU".length] integerValue];

    processor_basic_info_data_t basic_info;
    mach_msg_type_number_t info_count = PROCESSOR_BASIC_INFO_COUNT;
    processor_info(processor_list[button.tag], PROCESSOR_BASIC_INFO, &port,
                   (processor_info_t)&basic_info, &info_count);

    if (basic_info.is_master) {
        masterCPU = button.tag;
    }

    button.attributedTitle = [self stringForCPU:button.tag status:basic_info.running];
    item.view = button;

    return item;
}

#pragma mark - Private Methods

- (BOOL)retriveProcessorInfo {
    port = mach_host_self();

    kern_return_t rc;
    rc = host_get_host_priv_port(port, &priv_port);
    if (rc != KERN_SUCCESS) return NO;

    rc = host_processors(priv_port, &processor_list, &processor_count);
    if (rc != KERN_SUCCESS) return NO;

    return YES;
}

- (void)alertMessage:(NSString *)msg informative:(NSString *)info {
    NSAlert *alert = [[NSAlert alloc] init];
    alert.alertStyle = NSAlertStyleWarning;
    alert.messageText = msg;
    alert.informativeText = info;
    [alert runModal];
}

- (NSAttributedString *)stringForCPU:(NSInteger)index status:(BOOL)on {
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"●"
        attributes:@{NSForegroundColorAttributeName: on ? [NSColor greenColor] : [NSColor redColor]}];

    [string appendAttributedString:[[NSAttributedString alloc] initWithString:
        [NSString stringWithFormat:@" CPU %ld ", index]
        attributes:@{NSForegroundColorAttributeName: [NSColor whiteColor]}]];

    [string setAlignment:NSTextAlignmentCenter range:NSMakeRange(0, string.length)];
    return string;
}

- (void)setProcessor:(NSButton *)button {
    kern_return_t kr;

    if (button.tag & CPU_STATUS_MASK) {
        button.tag = ~CPU_STATUS_MASK;

        kr = processor_start(processor_list[button.tag]);
        if (kr != KERN_SUCCESS) {
            [self alertMessage:[NSString stringWithFormat:@"Cannot restart CPU %ld", button.tag]
                    informative:@"Perhaps wait for a moment and retry it"];
            button.tag |= CPU_STATUS_MASK;
        } else {
            button.attributedTitle = [self stringForCPU:button.tag status:YES];
        }
    } else {
        if (button.tag == masterCPU) {
            // 相信我,沒人真想關掉主核心
            return;
        }

        kr = processor_exit(processor_list[button.tag]);
        if (kr != KERN_SUCCESS) {
            [self alertMessage:[NSString stringWithFormat:@"Cannot stop CPU %ld", button.tag]
                    informative:@"Perhaps wait for a moment and retry it"];
        } else {
            button.attributedTitle = [self stringForCPU:button.tag status:NO];
            button.tag |= CPU_STATUS_MASK;
        }
    }
}
@end

幾點補充

權限問題。操作 CPU 核心需要 host 私有端口,普通進程拿不到,因此這類工具必須以 root 身份運行,否則 host_get_host_priv_port 會失敗。

狀態標記。示例用 button.tag 的高位做「已關閉」標記位,這是為了在 tag 中同時保存核心序號與開關狀態。這種做法能省事,但可讀性一般,正式項目裡更推薦用獨立屬性或字典維護狀態。

customizationIdentifier 的作用。它不只是個標識符:設置之後,用戶可以通過 Touch Bar 的自定義界面增刪你的 item。如果希望某個 item 不可被移除,可以把它加入 principalItemIdentifier。

CPUBar 的完整工程已放在 GitHub(BlueCocoa/CPUBar),有興趣可以直接拉下來跑。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved