Mac键位设置

键位设置

Posted by Tan Lin on April 20, 2019

前言

作为程序员,键盘是会经常使用到,但Mac的键盘使用久了感觉手很累,一般的机械键盘没有Mac独有的Command,所以考虑通过键位映射的方式将 Alt 映射为Mac上的 Command

当前配置系统环境:Mac-OS-10.14, Xcode 10.1,Alfred 3.6

准备

Mac Pro 上使用IKBC 描述上看来似乎就是我想要的效果,看起来没几个步骤 操作起来困难重重…

创建profile

通过Karabiner Elements建立3个Profiles,根据说明文档下载源码包后,执行make package报错:

/console_user_server/build_xcode/build/karabiner_console_user_server.build/Release/karabiner_console_user_server.build/Objects-normal/x86_64/main.o
clang: error: unable to execute command: Segmentation fault: 11
clang: error: clang frontend command failed due to signal (use -v to see invocation)
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
clang: note: diagnostic msg: PLEASE submit a bug report to http://developer.apple.com/bugreporter/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/58/fyxfl081135bn_jb15w0fyyr0000gn/T/main-19abac.cpp
clang: note: diagnostic msg: /var/folders/58/fyxfl081135bn_jb15w0fyyr0000gn/T/main-19abac.sh
clang: note: diagnostic msg: Crash backtrace is located in
clang: note: diagnostic msg: /Users/tanlin/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
clang: note: diagnostic msg:

********************

** BUILD FAILED **


The following build commands failed:
	CompileC build_xcode/build/karabiner_console_user_server.build/Release/karabiner_console_user_server.build/Objects-normal/x86_64/main.o src/main.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)
make[3]: *** [build_xcode] Error 65
make[2]: *** [all] Error 2
make[1]: *** [build] Error 2

make: *** [package] Error 99

从issue看,像是xcode 10.2的一个bug,需要使用xcode 10.1才能编译,无奈卸载xcode,重新安装xcode 10.1 然后再次执行make package, dmg 文件已成功编译出来open . 双击安装 dmg 文件

[理论上,项目下的oldrelease安装包直接就能安装了,当时没注意,就直接源码编译安装了,费了不少劲…]

Profile switcher

上一步的三个profile可以用过Karabiner elements profile switcher下载后快速切换 双击profile switcher这个workerflow后,并不能正常使用,提示Upgrade your Alfred Powerpack 也就是说Alfred需要licence…

Alfred Cracker

简书-破解Alfred: 破解文件 9tq2; 破解文件备份 ncch 解压下载后的zip包然后运行dmg文件,清留意系统设置里的安全和隐私允许安装,然后点击下图中的CORE keygen 点击 patch 选择 Alfred 3 出现patch successfull表明破解完成,点击save,重启Alfred。如果重启报错了,请安装CORE keygen同级目录下的一个Alfred 3.6的包。 安装完成后,重新破解一次。如下图所示表明Alfred破解成功,开心使用吧

Alfred Hotkey 切换profile

双击profile switcher,提示Incompatible Python workflow library,官网解决办法:alfred-fixnum github 在终端里执行fixnum前最好将profile switch的workflow备份下 复制以下代码到~/.config/karabiner/karabiner.json文件里

{
  "profiles": [
    {
      "devices": [
        {
          "disable_built_in_keyboard_if_exists": false,
          "identifiers": {
            "is_keyboard": true,
            "is_pointing_device": false,
            "product_id": 610,
            "vendor_id": 1452
          },
          "ignore": false
        },
        {
          "disable_built_in_keyboard_if_exists": false,
          "identifiers": {
            "is_keyboard": true,
            "is_pointing_device": false,
            "product_id": 5890,
            "vendor_id": 1241
          },
          "ignore": false
        }
      ],
      "fn_function_keys": {
        "f1": "vk_consumer_brightness_down",
        "f10": "mute",
        "f11": "volume_down",
        "f12": "volume_up",
        "f2": "vk_consumer_brightness_up",
        "f3": "f3",
        "f4": "vk_launchpad",
        "f5": "vk_consumer_illumination_down",
        "f6": "vk_consumer_illumination_up",
        "f7": "vk_consumer_previous",
        "f8": "vk_consumer_play",
        "f9": "vk_consumer_next"
      },
      "name": "USB Standard Keyboard",
      "selected": true,
      "simple_modifications": {
        "caps_lock": "escape",
        "escape": "caps_lock",
        "fn": "left_control",
        "left_command": "left_option",
        "left_option": "left_command"
      },
      "virtual_hid_keyboard": {
        "caps_lock_delay_milliseconds": 0,
        "keyboard_type": "ansi"
      }
    },
    {
      "devices": [
        {
          "disable_built_in_keyboard_if_exists": false,
          "identifiers": {
            "is_keyboard": true,
            "is_pointing_device": false,
            "product_id": 610,
            "vendor_id": 1452
          },
          "ignore": false
        },
        {
          "disable_built_in_keyboard_if_exists": false,
          "identifiers": {
            "is_keyboard": true,
            "is_pointing_device": false,
            "product_id": 5890,
            "vendor_id": 1241
          },
          "ignore": false
        }
      ],
      "fn_function_keys": {
        "f1": "vk_consumer_brightness_down",
        "f10": "mute",
        "f11": "volume_down",
        "f12": "volume_up",
        "f2": "vk_consumer_brightness_up",
        "f3": "f3",
        "f4": "vk_launchpad",
        "f5": "vk_consumer_illumination_down",
        "f6": "vk_consumer_illumination_up",
        "f7": "vk_consumer_previous",
        "f8": "vk_consumer_play",
        "f9": "vk_consumer_next"
      },
      "name": "Apple Keyboard",
      "selected": true,
      "simple_modifications": {
        "caps_lock": "escape",
        "escape": "caps_lock",
        "fn": "left_control"
      },
      "virtual_hid_keyboard": {
        "caps_lock_delay_milliseconds": 0,
        "keyboard_type": "ansi"
      }
    }
  ]
}

以后,直接调出Alfred后,输入keprofile 就能快速切换自带的键盘还是USB外接键盘。此时,已基本完成了快速切换。 当然,也可以在状态栏/工具栏 点击Karabiner Elements切换,但是总显得慢了好几步,稍显麻烦。

自定义快捷键切换

由于Karabiner Elements 现在还不支持根据键盘自动切换Profile,因此设置快捷键Alfred Trigger Hotkey切换profile有两种设置
Hotkey: 不需要调出Alfred的搜索窗口就可以使用,直接按键盘的键执行特定的操作
keyword: 需要调出Alfred窗口,获取编辑框的内容,然后传给后续的script

开始设置切换ikbc键盘,Alfred -> preferences -> workflow '+' Getting Started -> Hotkeys,仅保留第一个图形”Hotkey”就好。
双击设置快捷键,键盘上右上角倒数第三个按键,对应到Mac为F13,紧接着设置按键的事件,按下F13后需要执行的操作,目前我们需要切换profile为ikbc

由于我们并不知道Karabiner Elements设置profile的命令是什么,但前面提到的profile switcher的功能就是切换键盘,所以参考它的实现。 profile switcher实现方式: 通过Alfred输入keprofile后,switcher工作流被触发,读输入的内容执行python脚本,直接修改~/.config/karabiner/karabiner.json

Karabiner Elements listens for changes in karabiner.json config file, and there is a setting that specifies which profile is currently active – selected: true.

第一步:打开Karabiner Elements,切换到Profiles Tab页,重命名内置键盘为apple,ikbc键盘为ikbc,新建一个none 第二步:将profile switcher里的set.py 复制到新建的 Hotkeys - Getting Started 对应的目录中,set.py就是完成设置功能的脚本 第三步:在Alfred的 workflow界面,右键F13按钮 外的空白区域 Actions -> Run Script 当按下ikbc键盘上的PrtSc键时,profile就已经切换为ikbc了 其中,workflow的路径为~/Library/Application Support/Alfred 3/Alfred.alfredpreferences/,将profile switcher中的set.py 复制到你刚刚创建的workflow中,新建三个run script

// 设置为 ikbc 键盘
/usr/bin/python set.py 'ikbc'
// 设置为内置键盘
/usr/bin/python set.py 'apple'
// 设置为none时
/usr/bin/python set.py 'none'
// list.py
import sys
import json
from workflow import Workflow
from os.path import expanduser


ICON_DEFAULT = 'icon.png'
CONFIG_PATH = '.config/karabiner/karabiner.json'
home = expanduser("~")


def main(wf):
    with open('{}/{}'.format(home, CONFIG_PATH)) as json_data:
        config = json.load(json_data)
        for profile in config['profiles']:
            wf.add_item(
                profile['name'], 'Keyboard Preset Profile',
                arg=profile['name'], valid=True, icon=ICON_DEFAULT)
    wf.send_feedback()

if __name__ == u"__main__":
    wf = Workflow()
    sys.exit(wf.run(main))

//set.py
import sys
import json
from os.path import expanduser
from collections import OrderedDict

CHOSEN_PROFILE = sys.argv[1]
CONFIG_PATH = '.config/karabiner/karabiner.json'


home = expanduser("~")
config = {}

with open('{}/{}'.format(home, CONFIG_PATH)) as conf_file:
    config = json.load(conf_file, object_pairs_hook=OrderedDict)
    for profile in config['profiles']:
        profile['selected'] = profile['name'] == CHOSEN_PROFILE

with open('{}/{}'.format(home, CONFIG_PATH), 'w') as conf_file:
    conf_file.write(json.dumps(config, indent=4, separators=(',', ': ')))

以后,插上ikbc键盘,按下PrtSc就自动将左边的Alt更改为Command键,键位跟Mac一样,很方便

你也许已经开始疯狂的敲代码了,有没有发现,ikbc上的HomeEnd总感觉哪里不对,瞬间跳到文档顶部了,超级难受… 解决办法:将以下代码复制到~/Library/KeyBindings/DefaultKeyBinding.dict这个文件里,然后退出登录以下就好,不需要安装额外的包。

{
    "\UF729"  = moveToBeginningOfParagraph:;  // home
    "\UF72B"  = moveToEndOfParagraph:;  // end
    "$\UF729" = moveToBeginningOfParagraphAndModifySelection:;  // shift-home
    "$\UF72B" = moveToEndOfParagraphAndModifySelection:;  // shift-end
    "^\UF729" = moveToBeginningOfDocument:;  // ctrl-home
    "^\UF72B" = moveToEndOfDocument:;  // ctrl-end
    "^$\UF729" = moveToBeginningOfDocumentAndModifySelection:;  // ctrl-shift-home
    "^$\UF72B" = moveToEndOfDocumentAndModifySelection:;  // ctrl-shift-end
}

感谢

感谢假行僧提供思路 感谢csdn-白马斩辰提供快速下载Xcode的办法,不然要浪费一天时间去下载Xcode…